repo_name stringlengths 5 100 | path stringlengths 4 231 | language stringclasses 1
value | license stringclasses 15
values | size int64 6 947k | score float64 0 0.34 | prefix stringlengths 0 8.16k | middle stringlengths 3 512 | suffix stringlengths 0 8.17k |
|---|---|---|---|---|---|---|---|---|
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/rest_framework/serializers.py | Python | agpl-3.0 | 41,575 | 0.001034 | """
Serializers and ModelSerializers are similar to Forms and ModelForms.
Unlike forms, they are not constrained to dealing with HTML output, and
form encoded input.
Serialization in REST framework is a two-phase process:
1. Serializers marshal between complex types like model instances, and
python primitives.
2. The... | ms():
if key not in ret:
| ret[key] = val
# If 'fields' is specified, use those fields, in that order.
if self.opts.fields:
assert isinstance(self.opts.fields, (list, tuple)), '`fields` must be a list or tuple'
new = SortedDict()
for key in self.opts.fields:
new[key] = ... |
Mark-E-Hamilton/tappy | tap/tests/testcase.py | Python | bsd-2-clause | 258 | 0 | # Copyri | ght (c) 2016, Matt Layman
import unittest
from tap.tests.factory import Factory
class TestCase(unittest.TestCase):
def __init__(self, methodName='runTest'):
super(TestCase, self).__init__(methodName)
self.factory = Factor | y()
|
tsu-iscd/lyapas-lcc | lyapas_to_json.py | Python | bsd-3-clause | 753 | 0.010624 | #!/usr/bin/env python2.7
import json
import argparse
import codecs
import sys
def main(args):
data = args.in_lyapas.read()
data = json.dumps(data, ensure_ascii=False, encoding='utf-8')
json_data = '{"file": "' + args.in_lyapas.name + '",' + ' "source": ' + data +'}'
args.out_filename.write(json_data)
... | lt=sys.stdin)
parser.add_argument('-out_filename', help='Name of output file | ', nargs='?', type=argparse.FileType('w'), default=sys.stdout)
args = parser.parse_args()
main(args)
|
waterponey/scikit-learn | sklearn/linear_model/ridge.py | Python | bsd-3-clause | 51,357 | 0.000156 | """
Ridge regression
"""
# Author: Mathieu Blondel <mathieu@mblondel.org>
# Reuben Fletcher-Costin <reuben.fletchercostin@gmail.com>
# Fabian Pedregosa <fabian@fseoane.net>
# Michael Eickenberg <michael.eickenberg@nsup.org>
# License: BSD 3 clause
from abc import ABCMeta, abstractmethod
impor... | mv = create_mv(alpha[i])
if n_features > n_samples:
# kernel ridge
# w = X.T * inv(X X^t + alpha*Id) y
C = sp_linalg.LinearOperator(
(n_samples, n_samples), matvec=mv, dtype=X.dtype)
| coef, info = sp_linalg.cg(C, y_column, tol=tol)
coefs[i] = X1.rmatvec(coef)
else:
# linear ridge
# w = inv(X^t X + alpha*Id) * X.T y
y_column = X1.rmatvec(y_column)
C = sp_linalg.LinearOperator(
(n_features, n_features), matvec=mv... |
phac-nml/irida-miseq-uploader | Tests/unitTests/test_directoryscanner.py | Python | apache-2.0 | 1,282 | 0.00234 | import unittest
from os import path
from API.directoryscanner import find_runs_in_directory
path_to_module = path.abspath(path.dirname(__file__))
class TestDirectoryScanner(unittest.TestCase):
def test_sample_names_spaces(self):
runs = find_r | uns_in_directory(path.join(path_to_module, "sample-names-with-spaces"))
self.assertEqual(1, len(runs))
samples = runs[0].sample_list
self.assertEqual(3, len(samples))
for sample in samples:
self.assertEqual(sample.get_id(), sample.get_id().strip())
def test_single_end(se... | y(path.join(path_to_module, "single_end"))
self.assertEqual(1, len(runs))
self.assertEqual("SINGLE_END", runs[0].metadata["layoutType"])
samples = runs[0].sample_list
self.assertEqual(3, len(samples))
for sample in samples:
self.assertFalse(sample.is_paired_end())
... |
1065865483/0python_script | four/Webdriver/screenshot.py | Python | mit | 405 | 0.008264 | from selenium import webdriver
f | rom time import sleep
driver=webdriver.Firefox()
#打开我要自学网页面并截图
driver.get("http://www.51zxw.net/")
driver.get_screenshot_as_file(r'E:\0python_script\four\Webdriver\zxw.jpg')
sleep(2)
#打开百度页面并截图
driver.get("http://www.baidu.com")
driver.get_scre | enshot_as_file(r'E:\0python_script\four\Webdriver\baidu.png')
sleep(2)
driver.quit()
|
ys-nuem/project-euler | 003/003.py | Python | mit | 603 | 0.006861 | import random
N = 600851475143
def gcd(a, b):
while b > 0:
a, b = b, a % b
return a
def factorize(N):
" N の素因数分解を求める ( | Pollard's rho algorithm) "
factors = []
while N >= 2:
d = 1
while d == 1:
x = random.randint(1, N)
y = random.randint(1, N)
d = gcd(abs(x-y), N)
d = int(d)
if d < N:
factors.append(d)
N /= d
elif d == N:
... | d(factorize(N)))
print(factors[-1])
|
tensorflow/tensorflow | tensorflow/python/kernel_tests/image_ops/decode_jpeg_op_test.py | Python | apache-2.0 | 7,835 | 0.006254 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | ters, tile)
duration_decode_crop = self._evalDecodeJpeg(
'medium.jpg', parallelism, num_iters, False, crop_window, tile)
duration_decode_after_crop = self._evalDecodeJpeg(
'medium.jpg', parallelism, num_iters, True, crop_window, tile)
self.report_benchmark(
name='decode_j... | ' % (parallelism),
iters=num_iters,
wall_time=duration_decode)
self.report_benchmark(
name='decode_crop_jpeg_large_p%d' % (parallelism),
iters=num_iters,
wall_time=duration_decode_crop)
self.report_benchmark(
name='decode_after_crop_jpeg_large_p%d'... |
mscuthbert/abjad | abjad/tools/timespantools/offset_happens_before_timespan_stops.py | Python | gpl-3.0 | 1,081 | 0.000925 | # -*- encoding: utf-8 -*-
def offset_happens_before_timespan_stops(
timespan=None,
offset=None,
hold=False,
):
r'''Makes time relation indicating that `offset` happens
| before `timespan` stops.
::
>>> relation = timespantools.offset_happens_before_timespan_stops()
>>> print(format(relation))
timespantools.OffsetTimespanTimeRelation(
inequality=timespantools.CompoundInequality(
[
timespantools.SimpleInequali... | logical_operator='and',
),
)
Returns time relation or boolean.
'''
from abjad.tools import timespantools
inequality = timespantools.CompoundInequality([
'offset < timespan.stop',
])
time_relation = timespantools.OffsetTimespanTimeRelation(
... |
zk33/negi | negi/main.py | Python | mit | 798 | 0.035088 | # -*- coding: utf-8 -*-
import aaargh
from app import Negi
app = aaargh.App(description="Jinja2+JSON powered static HTML build tool")
@app.cmd(help='Parse JSON and build HTML')
@app.cmd_arg('-d','--data_dir',default='./data',help='JSON data dirctory(default:./data')
@app.cmd_arg('-t','--tmpl_dir',default='./template... | ,tmpl_dir,out_dir,verbose):
builder = Negi(
| data_dir= data_dir,
tmpl_dir = tmpl_dir,
out_dir = out_dir,
verbose = verbose
)
builder.build()
def main():
app.run()
if __name__ == '__main__':
main()
|
svirt/tp-libvirt | libvirt/tests/src/virsh_cmd/host/virsh_nodecpustats.py | Python | gpl-2.0 | 8,299 | 0.000361 | import re
from autotest.client.shared import error
from autotest.client import utils
from virttest import virsh
from virttest import utils_libvirtd
def run(test, params, env):
"""
Test the command virsh nodecpustats
(1) Call the virsh nodecpustats command for all cpu host cpus
separately
(2... | "not succeeded" % option)
# Run the test case for each cpu to get the cpu stats in percentage
for cpu in host_cpus_list:
option = "--cpu %s --percen | t" % cpu
output = virsh.nodecpustats(ignore_status=True, option=option)
status = output.exit_status
if status == 0:
actual_value = parse_percentage_output(output)
virsh_check_nodecpustats_percentage(actual_value)
el... |
ryfeus/lambda-packs | pytorch/source/numpy/f2py/__main__.py | Python | mit | 134 | 0 | # See http://cens.ioc.ee/projects/f2py2e/
fr | om __future__ imp | ort division, print_function
from numpy.f2py.f2py2e import main
main()
|
YPCrumble/django-annoying | annoying/tests/models.py | Python | bsd-3-clause | 363 | 0 | from django.db import mode | ls
from annoying.fields import AutoOneToOneField
class SuperVillain(models.Model):
name = models.CharField(max_length="20", default="Dr Horrible")
class SuperHero(models.Model):
name = models.CharField(max_length="20", default="Captain Hammer")
mortal_enemy = AutoOneToOneField(SuperVillain, related_name... | al_enemy')
|
grlee77/nipype | nipype/interfaces/semtools/brains/classify.py | Python | bsd-3-clause | 2,306 | 0.006071 | # -*- coding: utf8 -*-
"""Autogenerated file - DO NOT EDIT
If you spot a bug, please report it on the mailing list and/or change the generator."""
from nipype.interfaces.base import CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath
i... | argstr="--inputSurfaceGmVolume %s")
inputCsfVolume = File(desc="CSF Posterior Volume", exists=True, argstr="--inputCsfVolume %s")
inputVbVolume = File(desc="Venous Blood Posterior Volume", exists=True, argstr="--inputVbVolume %s")
inputCrblGmVolume = File(desc="Cerebellum Grey Matter Posterior Volume", exi... | olume = File(desc="Cerebellum White Matter Posterior Volume", exists=True, argstr="--inputCrblWmVolume %s")
outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Output Continuous Tissue Classified Image", argstr="--outputVolume %s")
class BRAINSPosteriorToContinuousClassOutputSpec(TraitedSpec... |
AndyHannon/ctrprogress | wowapi.py | Python | mit | 5,784 | 0.007089 | # -*- coding: utf-8 -*-
#!/usr/bin/env python
import json
import logging
import time
from google.appengine.ext import ndb
from google.appengine.api import urlfetch
from google.appengine.api import urlfetch_errors
class APIKey(ndb.Model):
key = ndb.StringProperty(indexed=True,required=True)
class Importer:
... | i','ignore'))
toondata['toon'] = name
toondata['status'] = 'nok'
toondata['reason'] = 'Network error retrieving data from Battle.net for | toon %s. Refresh page to try again.' % name
return
except:
logging.error('urlfetch threw unknown exception on toon %s' % name.encode('ascii','ignore'))
toondata['toon'] = name
toondata['status'] = 'nok'
toondata['reason'] = 'Unknown error retrieving d... |
nirvaris/nirvaris-djangofence | djangofence/urls.py | Python | mit | 566 | 0.003534 | from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.auth.decorators import login_required
from .views import UploadBlackListView, DemoView, UdateBlackListView
urlpatterns = [
| url(r'^admin/', include(admin.site.urls)),
url(r'^upload-blacklist$', login_required(UploadBlackListView.as_view()), name='upload-blacklist'),
url(r'^update-blacklist$', UdateBlackListView.as_view(), name='update-blacklist'),
url(r'^profile/', include('n_profile.urls')),
url(r'^demo$', DemoView.as_view(... | ]
|
subodhchhabra/airflow | airflow/contrib/hooks/segment_hook.py | Python | apache-2.0 | 3,748 | 0.0008 | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundatio | n (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache Lic | ense, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
#... |
jonparrott/gcloud-python | firestore/google/cloud/firestore_v1beta1/proto/event_flow_document_change_pb2.py | Python | apache-2.0 | 2,565 | 0.011696 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/cloud/firestore_v1beta1/proto/event_flow_document_change.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _... | b2.DESCRIPTOR,])
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
DESCRIPTOR.has_options = True
DESCRIP | TOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n\034com.google.firestore.v1beta1B\034EventFlowDocumentChangeProtoP\001ZAgoogle.golang.org/genproto/googleapis/firestore/v1beta1;firestore\252\002\036Google.Cloud.Firestore.V1Beta1'))
try:
# THESE ELEMENTS WILL BE DEPRECATED.
# Please use t... |
klausman/scion | python/sciond/sciond.py | Python | apache-2.0 | 30,793 | 0.000974 | # Copyright 2014 ETH Zurich
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, sof... | "
pmgt = cpld.union
path_reply = pmgt.union
assert isinstance(path_reply, PathSegmentReply), type(path_reply)
recs = path_reply.recs()
for srev_info in recs.iter_srev_infos():
self.check_revocation(srev_info, lamb | da x: self.continue_revocation_processing(
srev_info) if not x else False, meta)
req = path_reply.req()
key = req.dst_ia(), req.flags()
with self.req_path_lock:
r = self.requested_paths.get(key)
if r:
r.notify_reply(path_... |
geotagx/geotagx-pybossa-archive | pybossa/hateoas.py | Python | agpl-3.0 | 2,393 | 0 | # -*- coding: utf8 -*-
# This file is part of PyBossa.
#
# Copyright (C) 2013 SF Isle of Man Limited
#
# PyBossa is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at... | item.task_id is not None:
links.append(self.create_link(item.task, r | el='parent'))
return links, link
elif cls == 'task':
link = self.create_link(item)
links = []
if item.app_id is not None:
links = [self.create_link(item.app, rel='parent')]
return links, link
elif cls == 'category':
... |
nubakery/smith3 | python/spcaspt2/gen_split.py | Python | gpl-2.0 | 2,179 | 0.001377 | #!/opt/local/bin/python
import string
import os
def header(n) :
return "//\n\
// BAGEL - Brilliantly Advanced General Electronic Structure Library\n\
// Filename: SPCASPT2_gen" + str(n) + ".cc\n\
// Copyright (C) 2014 Toru Shiozaki\n\
//\n\
// Author: Toru Shiozaki <shiozaki@northwestern.edu>\n\
// Maintainer: Sh... | \
//\n\
\n\
#include <bagel_config.h>\n\
#ifdef COMPILE_SMITH\n\
\n\
#include <src/smith/caspt2/SPCASPT2_tasks" + str(n) + ".h>\n\
\n\
using namespace std;\n\
using namespace bagel;\n\
using namespace bagel::SMITH;\n\
using namespace bagel::SMITH::SPCASPT2;\n\
\n\
"
footer = "#endif\n"
f = open('SPCASPT2_gen.cc', 'r'... | \n")[32:]
tasks = []
tmp = ""
for line in lines:
if (line[0:4] == "Task"):
if (tmp != ""):
tasks.append(tmp)
tmp = ""
if (line != ""):
tmp += line + "\n"
if (line == "}"):
tmp += "\n"
tasks.append(tmp)
tmp = ""
num = 0
chunk = 50
for i in range(len(... |
duanx/bdcspider | bdmysqlDB.py | Python | gpl-2.0 | 3,758 | 0.00612 | #!/usr/bin/env python
# coding:utf-8
__author__ = 'lixin'
'''
°²×°MySQL
¿ÉÒÔÖ±½Ó´ÓMySQL¹Ù·½ÍøÕ¾ÏÂÔØ×îеÄCommunity Server 5.6.x°æ±¾¡£MySQLÊÇ¿çÆ½Ì¨µÄ£¬Ñ¡Ôñ¶ÔÓ¦µÄƽ̨ÏÂÔØ°²×°Îļþ£¬°²×°¼´¿É¡£
°²×°Ê±£¬MySQL»áÌáʾÊäÈërootÓû§µÄ¿ÚÁÇëÎñ±Ø¼ÇÇå³þ¡£Èç¹ûżDz»×¡£¬¾Í°Ñ¿ÚÁîÉèÖÃΪpassword¡£
ÔÚWindowsÉÏ£¬°²×°Ê±ÇëÑ¡ÔñUTF-8±àÂ룬ÒÔ±... | t (0.00 sec)
¿´µ½utf8×ÖÑù¾Í±íʾ±àÂëÉèÖÃÕýÈ·¡£
'''
# ÐèÒª°²×°MYSQLÇý¶¯,Ö¸ÁîÈçÏ£º
# $ pip install my | sql-connector-python --allow-external mysql-connector-python
# µ¼Èë:
# 导å
¥:
import uuid
from datetime import datetime
from sqlalchemy import Column, String, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
# å建对象çåºç±»:
Base = declarative_bas... |
yuxng/Deep_ISM | ISM/lib/datasets/rgbd_scenes.py | Python | mit | 4,957 | 0.004035 | __author__ = 'yuxiang'
import os
import datasets
import datasets.rgbd_scenes
import datasets.imdb
import numpy as np
import subprocess
import cPickle
class rgbd_scenes(datasets.imdb):
def __init__(self, image_set, rgbd_scenes_path=None):
datasets.imdb.__init__(self, 'rgbd_scenes_' + image_set)
sel... | _file):
with open(cache_file, 'rb') as fid:
| roidb = cPickle.load(fid)
print '{} gt roidb loaded from {}'.format(self.name, cache_file)
return roidb
gt_roidb = [self._load_rgbd_scenes_annotation(index)
for index in self.image_index]
with open(cache_file, 'wb') as fid:
cPickle.dump... |
Stanford-Online/edx-ora2 | openassessment/xblock/resolve_dates.py | Python | agpl-3.0 | 10,291 | 0.003984 | """
Resolve unspecified dates and date strings to datetimes.
"""
import datetime as dt
from dateutil.parser import parse as parse_date
import pytz
class InvalidDateFormat(Exception):
"""
The date string could not be parsed.
"""
pass
class DateValidationError(Exception):
"""
Dates are not se... | end - dt.timedelta(milliseconds=1)
# Override start/end dates if they fail to satisfy our validation rules
# These are the only parameters a course author can change in Studio
# without triggering our validation rule | s, so we need to use sensible
# defaults. See the docstring above for a more detailed justification.
for step_start, step_end in date_ranges:
if step_start is not None:
parsed_start = _parse_date(step_start, _)
start = min(start, parsed_start)
end = max(end, parsed_s... |
road2ge/cyber-defense-scripts | main-for-windows.py | Python | gpl-3.0 | 9,651 | 0.017615 | # This script is actually for Cyber Security on Windows 7. Should mostly work
# for Windows 8 and 10 too. I just absolutely hate using Windows 8 and refuse
# to test it on any Windows 8 machine.
from __future__ import print_function
from subprocess import call
from subprocess import check_output
import os
###########... | for command in registry_commands.readlines():
os.system(command)
############################# Search for media files #############################
if raw_input("Shall we search for media files? y/n. ") == 'y':
file_list = []
# Ask for directory to be scanned.
directory_to_scan = input('What d | irectory would you like to scan for media files? Remember to enclose your directory in \'s or "s, and use two \s if your directory ends in a \. ')
# Inefficient but I spent too much time looking how to do this to delete it.
'''for root, dirs, files in os.walk(directory_to_scan):
for f_name in files:
... |
EderSantana/fuel | fuel/datasets/svhn.py | Python | mit | 2,213 | 0 | # -*- coding: utf-8 -*-
import os
from fuel import config
from fuel.datasets import H5PYDataset
from fuel.transformers.defaults import uint8_pixels_to_floatX
class SVHN(H5PYDataset):
"""The Street View House Numbers (SVHN) dataset.
SVHN [SVHN] is | a real-world image dataset for developing machine
learning and object recognition algorithms with minimal requirement
on data preprocessing and formatti | ng. It can be seen as similar in
flavor to MNIST [LBBH] (e.g., the images are of small cropped
digits), but incorporates an order of magnitude more labeled data
(over 600,000 digit images) and comes from a significantly harder,
unsolved, real world problem (recognizing digits and numbers in
natural ... |
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2018_01_01/operations/_local_network_gateways_operations.py | Python | mit | 27,633 | 0.005139 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(u | rl, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_paramet... |
pvagner/orca | test/keystrokes/firefox/aria_combobox_dojo.py | Python | lgpl-2.1 | 4,695 | 0.000852 | #!/usr/bin/python
"""Test of Dojo combo box presentation."""
from macaroon.playback import *
import utils
sequence = MacroSequence()
sequence.append(PauseAction(5000))
sequence.append(KeyComboAction("Tab"))
sequence.append(KeyComboAction("Tab"))
sequence.append(utils.StartRecordingAction())
sequence.append(KeyComb... | er font): C $l'",
" VISIBLE: '(200% Courie | r font): C $l', cursor=23",
"BRAILLE LINE: 'US State test 1 (200% Courier font): US State test 1 (200% Courier font): combo box'",
" VISIBLE: 'te test 1 (200% Courier font): U', cursor=32",
"SPEECH OUTPUT: 'expanded'"]))
sequence.append(utils.StartRecordingAction())
sequence.append(KeyComboAction(... |
teltek/edx-platform | common/djangoapps/student/views/management.py | Python | agpl-3.0 | 44,012 | 0.002545 | """
Student Views
"""
import datetime
import logging
import uuid
from collections import namedtuple
from bulk_email.models import Optout
from courseware.courses import get_courses, sort_by_announcement, sort_by_start_date
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.de... | NOTPROVIDED':
return ''
return | (u'<div style="display:none"><input type="hidden"'
' name="csrfmiddlewaretoken" value="{}" /></div>'.format(token))
# NOTE: This view is not linked to directly--it is called from
# branding/views.py:index(), which is cached for anonymous users.
# This means that it should always return the same thing for... |
ASMlover/study | python/src/config_parser.py | Python | bsd-2-clause | 1,635 | 0 | #!/usr/bin/env python
# -*- encoding | : utf-8 -*-
#
# Copyright (c) 2014 ASMlover. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted | provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list ofconditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following discla... |
whtsky/Dash.py | dash_py/__init__.py | Python | mit | 109 | 0 | """
Create python docs for das | h easily.
"""
__version__ = '0.2.1'
__author__ = 'whtsky'
__license__ = 'MIT'
| |
digimarc/django | tests/forms_tests/tests/test_fields.py | Python | bsd-3-clause | 83,991 | 0.005026 | # -*- coding: utf-8 -*-
"""
##########
# Fields #
##########
Each Field class does some sort of validation. Each Field has a clean() method,
which either raises django.forms.ValidationError or returns the "clean"
data -- usually a Unicode object, but, in some rare cases, a list.
Each Field's __init__() takes at least... | self.assertEqual(f.widget_attrs(TextInput()), {'maxlength': '10'})
self.assertEqual(f.widget_attrs(PasswordInput()), {'maxlength': '10'})
self.assertEqual(f.widget_attrs(Textarea()), {'maxlength': '10'})
# IntegerField ################################################################
de... | test_integerfield_1(self):
f = IntegerField()
self.assertWidgetRendersTo(f, '<input type="number" name="f" id="id_f" />')
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '')
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, No... |
pmuller/django-softdeletion | django_softdeletion/models.py | Python | mit | 5,119 | 0 | import logging
from django.db.models import DateTimeField, Model, Manager
from django.db.models.query import QuerySet
from django.db.models.fields.related import \
OneToOneField, ManyToManyField, ManyToManyRel
from django.utils.translation import ugettext_lazy as _
from django.utils.timezone import now
from django... | """
def delete(self):
"""Soft delete all objects included in this queryset.
"""
for ob | j in self:
_unset_related_objects_relations(obj)
self.update(deleted=now())
def undelete(self):
"""Soft undelete all objects included in this queryset.
"""
objects = self.filter(deleted__isnull=False)
if objects.count():
LOGGER.debug(
... |
foobarbazblarg/stayclean | stayclean-2020-january/display-final-after-month-is-over.py | Python | mit | 3,056 | 0.004254 | #!/usr/bin/python
# TODO: issu | es with new oauth2 stuff. Keep using older version of Python for now.
# #!/usr/bin/env python
from participantCollection import ParticipantCollection
import re
import datetime
import pyperclip
# Edit Me!
# This script ge | ts run on the first day of the following month, and that month's URL is
# what goes here. E.g. If this directory is the directory for February, this script gets
# run on March 1, and this URL is the URL for the March challenge page.
nextMonthURL = "https://www.reddit.com/r/pornfree/comments/ex6nis/stay_clean_february_... |
dntt1/youtube-dl | youtube_dl/extractor/jwplatform.py | Python | unlicense | 5,161 | 0.002906 | # coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
determine_ext,
float_or_none,
int_or_none,
)
class JWPlatformBaseIE(InfoExtractor):
@staticmethod
def _find_jwplayer_data(webpage):
# TODO | : Merge this with JWPlayer-related codes in generic.py
| mobj = re.search(
'jwplayer\((?P<quote>[\'"])[^\'" ]+(?P=quote)\)\.setup\((?P<options>[^)]+)\)',
webpage)
if mobj:
return mobj.group('options')
def _extract_jwplayer_data(self, webpage, video_id, *args, **kwargs):
jwplayer_data = self._parse_json(
... |
gully/PyKE | pyke/kepoutlier.py | Python | mit | 14,393 | 0.00139 | from .utils import PyKEArgumentHelpFormatter
import numpy as np
from astropy.io import fits as pyfits
from matplotlib import pyplot as plt
from tqdm import tqdm
from . import kepio, kepmsg, kepkey, kepfit, kepstat, kepfunc
__all__ = ['kepoutlier']
def kepoutlier(infile, outfile=None, datacol='SAP_FLUX', nsig=3.0, s... | Julian
Dates (BJDs). Multiple ranges are separated by a semi-colon. An example
containing two time ranges is::
'2455012.48517,2455014.50072;2455022.63487,2455025.08231'
If the user wants to correct the entire time series then providing
``ranges = '0,0'`` will tell the task... | on the whole time series.
plot : bool
Plot the data and outliers?
plotfit : bool
Overlay the polynomial fits upon the plot?
overwrite : bool
Overwrite the output file?
verbose : bool
Print informative messages and warnings to the shell and logfile?
logfile : str
... |
trthanhquang/bus-assistant | webApp/getBusTiming.py | Python | mit | 2,827 | 0.038557 | #!/usr/bin/env python
import urllib2
from bs4 import BeautifulSoup as BS
import re
import time
def getAgenciesList():
agenciesList_re | q = urllib2.Request('''http://services.my511.org/Transit2.0/GetAgencies.aspx?token=aeeb38de-5385-482a-abde-692dfb2769e3''')
xml_resp = urllib2.urlopen(agenciesList_req)
soup = BS(xml_resp.read(),'lxml')
print soup.prettify()
agencies = soup.find_all('agency')
for a | in agencies:
print a['name']
def getBusList(busCodes):
api_url = '''http://services.my511.org/Transit2.0/GetRoutesForAgencies.aspx
?token=aeeb38de-5385-482a-abde-692dfb2769e3
&agencyNames=SF-MUNI'''
req = urllib2.urlopen(''.join(api_url.split()))
soup = BS(req.read(),'lxml')
routes = soup.find_all('route')
... |
912/M-new | virtualenvironment/experimental/lib/python2.7/site-packages/django/contrib/gis/db/models/proxy.py | Python | gpl-2.0 | 2,643 | 0.001892 | """
The GeometryProxy object, allows for lazy-geometries. The proxy uses
Python descriptors for instantiating and setting Geometry objects
corresponding to geographic model fields.
Thanks to Robert Coup for providing this functionality (see #4322).
"""
from django.contrib.gis import memoryview
from django.utils impor... | Getting the value of the field.
geom_value = obj.__dict__[self._field.attname]
if isinstance(geom_value, self._klass):
| geom = geom_value
elif (geom_value is None) or (geom_value == ''):
geom = None
else:
# Otherwise, a Geometry object is built using the field's contents,
# and the model's corresponding attribute is set.
geom = self._klass(geom_value)
seta... |
google-research/google-research | kws_streaming/models/att_rnn.py | Python | apache-2.0 | 5,484 | 0.008388 | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | tional)',
)
parser_nn.add_argument(
'--rnn_type',
type=str, |
default='gru',
help='RNN type: it can be gru or lstm',
)
parser_nn.add_argument(
'--rnn_units',
type=int,
default=128,
help='Units number in RNN cell',
)
parser_nn.add_argument(
'--dropout1',
type=float,
default=0.1,
help='Percentage of data dropped',... |
nathanielvarona/airflow | airflow/cli/commands/provider_command.py | Python | apache-2.0 | 3,862 | 0.000259 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | uted on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Providers sub-commands"""
import re
from airflow.cli.simple_table im | port AirflowConsole
from airflow.providers_manager import ProvidersManager
from airflow.utils.cli import suppress_logs_and_warning
def _remove_rst_syntax(value: str) -> str:
return re.sub("[`_<>]", "", value.strip(" \n."))
@suppress_logs_and_warning
def provider_get(args):
"""Get a provider info."""
pro... |
cmunk/protwis | build_gpcr/management/commands/build_statistics_trees.py | Python | apache-2.0 | 142 | 0.021429 | from build.managemen | t.commands.build_statistics_trees import Command as BuildStatisticsTrees
class Command(BuildStatisticsT | rees):
pass |
bajibabu/merlin | misc/scripts/vocoder/world/extract_features_for_merlin.py | Python | apache-2.0 | 5,044 | 0.011102 | import os
import sys
import shutil
import glob
import time
import multiprocessing as mp
if len(sys.argv)!=5:
print("Usage: ")
print("python extract_features_for_merlin.py <path_to_merlin_dir> <path_to_wav_dir> <path_to_feat_dir> <sampling rate>")
sys.exit(1)
# top merlin directory
merlin_dir | = sys.argv[1]
# input audio directory
wav_dir = sys.argv[2]
# Output features directory
out_dir = sys.argv[3]
# initializations
fs = int(sys.argv[4])
# tools directory
world = os.path.join(merlin_dir, "tools/bin/WORLD")
sptk = os.path.join(merlin_dir, "tools/bin/SP | TK-3.9")
sp_dir = os.path.join(out_dir, 'sp' )
mgc_dir = os.path.join(out_dir, 'mgc')
ap_dir = os.path.join(out_dir, 'ap' )
bap_dir = os.path.join(out_dir, 'bap')
f0_dir = os.path.join(out_dir, 'f0' )
lf0_dir = os.path.join(out_dir, 'lf0')
if not os.path.exists(out_dir):
os.mkdir(out_dir)
if not os.path.exist... |
markreidvfx/pyaaf | example/aaf2xml.py | Python | mit | 281 | 0 | import aaf
import os
from optparse imp | ort OptionParser
parser = OptionParser()
(options, args) = parser.parse_args()
if not args:
parser.error("not enough argements")
path = args[0]
name | , ext = os.path.splitext(path)
f = aaf.open(path, 'r')
f.save(name + ".xml")
f.close()
|
tensorflow/tensorflow | tensorflow/python/profiler/pprof_profiler_test.py | Python | apache-2.0 | 5,145 | 0.005442 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | _only('b/120545219')
def testProfileWithWhileLoop(self):
options = | config_pb2.RunOptions()
options.trace_level = config_pb2.RunOptions.FULL_TRACE
run_metadata = config_pb2.RunMetadata()
num_iters = 5
with self.cached_session() as sess:
i = constant_op.constant(0)
c = lambda i: math_ops.less(i, num_iters)
b = lambda i: math_ops.add(i, 1)
r = con... |
Fizzadar/ElasticQuery | setup.py | Python | mit | 554 | 0 | # ElasticQuery
# File: setup.p | y
# Desc: needed
from setuptools import setup
if __name__ == '__main__':
setup(
version='3.2',
name='ElasticQuery',
description='A simple query builder for Elasticsearch 2',
author='Nick Barrett',
author_email='pointlessrambler@gmail.com',
url='http://github.com/Fi... |
'elasticquery',
],
install_requires=['six>=1.4.0'],
)
|
jmchilton/galaxy-central | modules/docutils/languages/sv.py | Python | mit | 2,135 | 0.001405 | # Author: Adam Chodorowski
# Contact: chodorowski@users.sourceforge.net
# Revision: $Revision: 2224 $
# Date: $Date: 2004-06-05 21:40:46 +0200 (Sat, 05 Jun 2004) $
# Copyright: This module has been placed in the public domain.
# New language mappings are welcome. Before doing a new translation, please
# re... | : u'Kontakt',
'version': u'Version',
'revision': u'Revision',
'status': u'Status',
'date': u'Datum',
'copyright': u'Copyright',
| 'dedication': u'Dedikation',
'abstract': u'Sammanfattning',
'attention': u'Observera!',
'caution': u'Varning!',
'danger': u'FARA!',
'error': u'Fel',
'hint': u'V\u00e4gledning',
'important': u'Viktigt',
'note': u'Notera',
'tip': u... |
trondhindenes/ansible | lib/ansible/modules/storage/netapp/na_ontap_svm.py | Python | gpl-3.0 | 18,691 | 0.001498 | #!/usr/bin/python
# (c) 2018, NetApp, Inc
# GNU General Public License v3.0+
# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
... | e='str'),
root_volume_aggregate=dict(type='str'),
root_volume_security_style=dict(type='str', choices=['unix',
'ntfs',
'mixed',
| 'unified'
]),
allowed_protocols=dict(type='list'),
aggr_list=dict(type='list'),
ipspace=dict(type='str', required=False),
snapshot_policy=dict(type='str... |
olduvaihand/ProjectEuler | src/python/problem303.py | Python | mit | 475 | 0.004228 | # -*- coding: utf-8 -*-
# ProjectEuler/src/python/problem303.py
#
# Multiples with small digits
# ===========================
# Published on Saturday, 25th September 2010, 10:00 pm
#
# F | or a positive integer n, define f(n) as the least positive multiple of n
# that, written in base 10, | uses only digits 2. Thus f(2)=2, f(3)=12, f(7)=21,
# f(42)=210, f(89)=1121222. Also, . Find .
import projecteuler as pe
def main():
pass
if __name__ == "__main__":
main()
|
pdxwebdev/yadapy | yadapy/friendnode.py | Python | gpl-3.0 | 3,507 | 0.013117 | import logging, os, marshal, json, cPickle, time, copy, time, datetime, re, urllib, httplib
from base64 import b64encode, b64decode
from lib.crypt import encrypt, decrypt
from uuid import uuid4
from node import Node, InvalidIdentity
class FriendNode(Node):
def __init__(self, *args, **kwargs):
... | ta['data'] \
and 'name' in data['data']['identity'] \
and 'avatar' in data['data']['identity']:
return True
else:
raise InvalidIdentity("invalid identity dictionary for identity")
except InvalidIdentity: |
raise
class RoutedFriendNode(FriendNode):
def __init__(self, *args, **kwargs):
if 'identityData' in kwargs:
identityData = kwargs['identityData']
else:
identityData = args[0]
kwargs['identityData'] = identityData
... |
MuhammadVT/davitpy | davitpy/pydarn/proc/music/music.py | Python | gpl-3.0 | 84,879 | 0.014338 | # -*- coding: utf-8 -*-
# Copyright (C) 2012 VT SuperDARN Lab
# Full license can be found in LICENSE.txt
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
#... | -
dataObj : musicArray
dataSet : Optional[str]
which dataSet in the musicArray object to process
Returns
-------
currentData : musicDataObj object
Written by Nathaniel A. Frissell, Fall | 2013
"""
lst = dir(dataObj)
if dataSet not in lst:
tmp = []
for item in lst:
if dataSet in item:
tmp.append(item)
if len(tmp) == 0:
dataSet = 'active'
else:
tmp.sort()
dataSet = tmp[-1]
currentData = getat... |
mileistone/test | utils/test/setup.py | Python | mit | 5,817 | 0.003094 | # --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
import os
from os.path import join as pjoin
from setuptools im... | ompiler_so', CUDA['nvcc'])
# use only a subset of the extra_postargs, which are 1-1 translated
# from the extra_compile_args in the Extension class
postargs = extra_postargs['nvcc']
else:
postargs = extra_postargs['gcc']
super(obj, src, ext, cc_arg... | self.compiler_so = default_compiler_so
# inject our redefined _compile method into the class
self._compile = _compile
# run the customize_compiler
class custom_build_ext(build_ext):
def build_extensions(self):
customize_compiler_for_nvcc(self.compiler)
build_ext.build_exte... |
jamespcole/home-assistant | homeassistant/components/telegram_bot/polling.py | Python | apache-2.0 | 3,026 | 0 | """Support for Telegram bot using polling."""
import logging
from homeassistant.const import (
EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP)
from homeassistant.core import callback
from . import (
CONF_ALLOWED_CHAT_IDS, PLATFORM_SCHEMA as TELEGRAM_PLATFORM_SCHEMA,
BaseTelegramBotEntity, initialize_... | ONF_ALLOWED_CHAT_IDS])
@callback
def _start_bot(_event):
| """Start the bot."""
pol.start_polling()
@callback
def _stop_bot(_event):
"""Stop the bot."""
pol.stop_polling()
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, _start_bot)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _stop_bot)
return True
def process_erro... |
scheib/chromium | third_party/blink/renderer/bindings/scripts/bind_gen/style_format.py | Python | bsd-3-clause | 3,817 | 0 | # Copyright 2019 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os.path
import subprocess
import sys
_enable_style_format = None
_clang_format_command_path = None
_gn_command_path = None
def init(root_src_dir, e... | path is None
_enable_style_format = enable_style_format
root_src_dir = os.path.abspath(root_src_dir)
# Determine //buildtools/<platform>/ directory
if sys.platform.startswith("linux"):
platform = "linux64"
exe_suffix = ""
elif sys.platform.startswith("darwin"):
platform = ... | n platform: {}".format(sys.platform)
buildtools_platform_dir = os.path.join(root_src_dir, "buildtools",
platform)
# //buildtools/<platform>/clang-format
_clang_format_command_path = os.path.join(
buildtools_platform_dir, "clang-format{}".format(exe_suffix)... |
blutack/mavlog | docs/conf.py | Python | bsd-3-clause | 8,361 | 0.005502 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# complexity documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# ... | , target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'mavlog',
u'MAVLog Documentation',
u'Gareth R',
'mavlog',
'One line description | of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to dis |
iseppi/zookeepr | alembic/versions/20_58ee75910929_add_theme_to_config_.py | Python | gpl-2.0 | 603 | 0.006633 | """Add theme to config
Revision ID: 58ee75910929
Revises: 1c22ceb384a7
Create Date: 2015-08-28 15:15:47.971807
"""
# revision identifiers, used by Alembic.
revision = '58ee75910929'
down_revision = '1c22ceb384a7'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.execute("INSERT INTO config (cat... | , key, value, description) VALUES ('general', 'theme', '\"zkpylons\"', 'The enabled theme to use. Should match the theme folder name (requires a server restart to take effect)')")
def downgrade():
op.execute("DELETE FROM config WHERE category='general' AND key='them | e'")
|
CatoTH/OpenSlides | server/openslides/motions/migrations/0005_auto_20180202_1318.py | Python | mit | 2,199 | 0.00091 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2018-02-02 12:18
from __future__ import unicode_literals
from django.contrib.auth.models import Permission
from django.db import migrations
def delete_old_comment_permission(apps, schema_editor):
"""
Deletes the old 'can_see_and_manage_comments' permiss... | st() is necessary to evalu | ate the database query right now.
groups = list(perm.group_set.all())
# Delete permission
perm.delete()
# Create new permission
perm_see = Permission.objects.create(
codename="can_see_comments",
name="Can see comments",
content_type=content_t... |
Vvucinic/Wander | venv_2_7/lib/python2.7/site-packages/Django-1.9-py2.7.egg/django/template/backends/jinja2.py | Python | artistic-2.0 | 3,342 | 0.000598 | # Since this package contains a "django" module, this is required on Python 2.
from __future__ import absolute_import
import sys
import jinja2
from django.conf import settings
from django.template import TemplateDoesNotExist, TemplateSyntaxError
from django.utils import six
from django.utils.module_loading import im... | r as exc:
new = TemplateSyntaxError(exc.args)
new.template_debug = get_exception_inf | o(exc)
six.reraise(TemplateSyntaxError, new, sys.exc_info()[2])
class Template(object):
def __init__(self, template):
self.template = template
self.origin = Origin(
name=template.filename, template_name=template.name,
)
def render(self, context=None, request=N... |
eltonkevani/tempest_el_env | tempest/api/object_storage/test_container_quotas.py | Python | apache-2.0 | 4,616 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 Cloudwatt
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licen... | @testtools.skipIf(not container_quotas_available, SKIP_MSG)
@attr(type="smoke")
def test_upload_large_object(self):
"""Attempts to upload an object lagger than the bytes quota."""
object_name = data_utils.rand_name(name="TestObject")
data = data_utils.arbitrary_string(QUOTA_BYTES + 1)... | ytes_used()
self.assertRaises(exceptions.OverLimit,
self.object_client.create_object,
self.container_name, object_name, data)
nafter = self._get_bytes_used()
self.assertEqual(nbefore, nafter)
@testtools.skipIf(not container_quotas_availa... |
FrostyX/pysysinfo | doc/conf.py | Python | gpl-2.0 | 8,133 | 0.006271 | # -*- coding: utf-8 -*-
#
# pysysinfo documentation build configuration file, created by
# sphinx-quickstart on Fri Nov 6 16:05:30 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
#... | name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_par | ts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = Tru... |
TAMU-CPT/galaxy-tools | tools/webapollo/list_organism_data.py | Python | gpl-3.0 | 951 | 0.001052 | #!/usr/bin/env python
import json
import argparse
from webapollo import WAAuth, WebApolloInstance, AssertUser, accessible_organisms
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="List all organisms available in an Apollo instance"
)
WAAuth(parser)
parser.add_argument(... | rganisms.findAllOrganisms()
orgs = accessibl | e_organisms(gx_user, all_orgs)
cleanedOrgs = []
for organism in all_orgs:
org = {
"name": organism["commonName"],
"id": organism["id"],
"annotations": organism["annotationCount"],
"sequences": organism["sequences"],
}
cleanedOrgs.append(or... |
christianurich/VIBe2UrbanSim | 3rdparty/opus/src/urbansim_parcel/models/building_location_choice_model.py | Python | gpl-2.0 | 5,528 | 0.009949 | # Opus/UrbanSim ur | ban simulation software.
# Copyright (C) 2005-2009 University of Washington
# See opus_core/LICENSE
from urbansim.models.building_location_choice_model import BuildingLocationChoiceModel as UrbansimBuildingLocationChoice | Model
from numpy import where, arange, zeros
from numpy import logical_or, logical_not
from opus_core.variables.variable_name import VariableName
from opus_core.resources import Resources
from opus_core.datasets.dataset import Dataset
class BuildingLocationChoiceModel(UrbansimBuildingLocationChoiceModel):
# ... |
dugan/coverage-reporter | coverage_reporter/extras/unittest2_plugin.py | Python | mit | 1,511 | 0.003971 | from unittest2.events import Plugin, addOption
from unittest2.util import getS | ource
import os
import sys
try:
import coverag | e
except ImportError, e:
coverage = None
coverageImportError = e
help_text1 = 'Enable coverage reporting'
class CoveragePlugin(Plugin):
configSection = 'coverage'
commandLineSwitch = ('C', 'coverage', help_text1)
def __init__(self):
self.configFile = self.config.get('config', ''... |
nuagenetworks/nuage-openstack-horizon | nuage_horizon/dashboards/project/gateways/urls.py | Python | apache-2.0 | 1,078 | 0 | # Copyright 2020 Nokia.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use | this file except in compliance with the License. You may obtain
# a copy of the License at
#
# ht | tp://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governin... |
samvarankashyap/linch-pin | linchpin/tests/mockdata/contextdata.py | Python | gpl-3.0 | 4,450 | 0.002472 | from __future__ import absolute_import
import os
import tempfile
from six.moves import configparser as ConfigParser
from six import iteritems
from linchpin.exceptions import LinchpinError
"""
Provide valid context data to test against.
"""
class ContextData(object):
def __init__(self, parser=ConfigParser.Con... | self.evars = self.cfg_data.get('evars', {})
def _parse_config(self, path):
"""
| Parse configs into the self.cfg_data dict from provided path.
:param path: A path to a config to parse
"""
try:
config = ConfigParser.ConfigParser()
f = open(path)
config.readfp(f)
f.close()
for section in config.sections():
... |
jablonskim/jupyweave | jupyweave/settings/output_types.py | Python | mit | 1,920 | 0.000521 | from enum import Enum
import re
class OutputTypes:
"""Class representing visible output types"""
class Types(Enum):
"""Types"""
Stdout = 1
Stderr = 2
Result = 3
Image = 4
Pdf = 5
def __init__(self, types_str):
"""Initialization from string"""
... | types_str = 'All'
| types = set()
types_tokens = [token.lower() for token in re.findall(r'\w+', types_str)]
if 'stdout' in types_tokens:
types.add(OutputTypes.Types.Stdout)
if 'stderr' in types_tokens:
types.add(OutputTypes.Types.Stderr)
if 'result' in types_tokens:
... |
tnwhitwell/lexicon | tests/providers/test_nsone.py | Python | mit | 972 | 0.003086 | # Test for one implementat | ion of the interface
from lexicon.providers.nsone import Provider
from integration_tests import IntegrationTests
from unittest import TestCase
import pytest
# Hook into testing framework by inheriting unittest.TestCase and reuse
# the tests which *each and every* implementation of the in | terface must
# pass, by inheritance from define_tests.TheTests
class Ns1ProviderTests(TestCase, IntegrationTests):
Provider = Provider
provider_name = 'nsone'
domain = 'lexicon-example.com'
def _filter_headers(self):
return ['X-NSONE-Key', 'Authorization']
@pytest.mark.skip(reason="can not... |
Teamxrtc/webrtc-streaming-node | third_party/webrtc/src/chromium/src/build/android/pylib/local/device/local_device_instrumentation_test_run.py | Python | mit | 6,414 | 0.011381 | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import re
import time
from devil.android import device_errors
from pylib import flag_changer
from pylib.base import base_test_result
from pyl... | e.DismissCrashDialogIfNeeded()
if not package:
return False
# Assume test package convention of ".test" suffix
if package in package_name:
return True
except device_errors.CommandFailedError:
logging.exception('Error while attempting to dismiss crash dialog.')
return False
_C... | ice_test_run.LocalDeviceTestRun):
def __init__(self, env, test_instance):
super(LocalDeviceInstrumentationTestRun, self).__init__(env, test_instance)
self._flag_changers = {}
def TestPackage(self):
return None
def SetUp(self):
def substitute_external_storage(d, external_storage):
if not d:... |
fayf/pyload | module/plugins/hooks/SmoozedComHook.py | Python | gpl-3.0 | 876 | 0.025114 | # -*- coding: utf-8 -*-
from module.plugins.internal.MultiHook import MultiHook
class SmoozedComHook(MultiHook):
__name__ = "SmoozedComHook"
__type__ = "hook"
__version__ = "0.04"
__status__ = "testing"
__config__ = [("pluginmode" , "all;listed;unlisted", "Use for plugins" ... | oad interval in hours" , 12 | )]
__description__ = """Smoozed.com hook plugin"""
__license__ = "GPLv3"
__authors__ = [("", "")]
def get_hosters(self):
user, info = self.account.select()
return self.account.get_data(user)['hosters']
|
yeleman/snisi | snisi_vacc/indicators.py | Python | mit | 4,346 | 0.00069 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4 nu
from __future__ import (unicode_literals, absolute_import,
division, print_function)
import logging
import numpy
from snisi_core.models.Projects import Cluster
# from snisi_core.models.Reporting import ExpectedRepor... | .format(indicator_name))
| geo_section = getattr(indicator, 'geo_section', None)
if geo_section not in indicators.keys():
indicators.update({geo_section: []})
spec = indicator.spec()
spec.update({'slug': indicator.__name__})
indicators[geo_section].append(spec)
return indicators
|
TNT-Samuel/Coding-Projects | Image Test/_ImageEdit3MultiProcess.py | Python | gpl-3.0 | 17,506 | 0.00914 | if __name__ == '__main__':
print("Loading Modules...")
from setuptools.command import easy_install
def install_with_easyinstall(package):
easy_install.main(["-U", package])
imported = False
tries = 0
while not imported:
try:
import socket, importlib
globals()['PIL'] = importlib.import_m... | str(ex))
elif not q2.empty() and im.currq == 2:
try:
qlock.acquire()
datax = q2.get()
qlock.release()
gotqdata = True
except Exception as ex: |
print("Q2Error: " + str(ex))
else:
time.sleep(0.1)
if gotqdata:
#queueLock.release()
#print ("%s processing %s" % (threadName, data))
x = datax
#print("[" + str(threadName) + "] Processing " + str(x))
y = canvas_he... |
kalev/anaconda | pyanaconda/storage/deviceaction.py | Python | gpl-2.0 | 20,775 | 0.000722 | # deviceaction.py
# Device modification action classes for anaconda's storage configuration |
# module.
#
# Copyright (C) 2009 Red Hat, Inc.
#
# This copyrighted | material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, ... |
melizeche/PyBlog | blog/models.py | Python | gpl-2.0 | 607 | 0.039539 | from django.db import models
# Create your models here.
class Autor(models.Model):
nombre = models.CharField(max_length=50)
ed | ad = models.IntegerField(null=True, blank=True)
email = models.EmailField()
def __unicode__(self):
return self.nombre
class Meta:
verbose_name_plural = "Autores"
class Articulo(models.Model):
autor = models.ForeignKey('Autor', n | ull=True)
titulo = models.CharField(max_length=100)
texto = models.TextField(blank=True, null=True)
created = models.DateTimeField('Agregado',auto_now_add=True, null=True, blank=True)
def __unicode__(self):
return self.titulo
|
0sm0s1z/subterfuge | modules/models.py | Python | gpl-3.0 | 1,614 | 0.02912 | from django.db import models
from django import forms
class installed(models.Model):
name = models.CharField(max_length=300)
active = models.CharField(max_length=300)
class vectors(models.Model):
name = models.CharField(max_length=300)
active = models.CharField(max_len... | Field(max_length=300)
channel = models.CharField(max_length=300)
atknic = models.CharField(max_length=300)
netnic = models.CharField(max_length=300)
class arppoison(models.Model):
target = models.CharField(m | ax_length=300, default = 'none')
method = models.CharField(max_length=300, default = 'none')
class sessions(models.Model):
source = models.CharField(max_length=300)
session = models.CharField(max_length=300)
date = models.CharField(max_length=300)
|
ahmadiga/min_edx | common/test/acceptance/pages/studio/course_rerun.py | Python | agpl-3.0 | 971 | 0 | """
Course rerun page in Studio
"""
from .course_page import CoursePage
from .utils import set_input_value
class CourseRerunPage(CoursePage):
"""
Course rerun page in Studio
"""
url_path = "course_rerun"
COURSE_RUN_INPUT = '.rerun-course-run'
def is_browser_on_page(self):
"""
... | rse-create-rerun').present
@property
def course_run(self):
"""
Retur | ns the value of the course run field.
"""
return self.q(css=self.COURSE_RUN_INPUT).text[0]
@course_run.setter
def course_run(self, value):
"""
Sets the value of the course run field.
"""
set_input_value(self, self.COURSE_RUN_INPUT, value)
def create_rerun(se... |
codeaudit/myriad-toolkit | tools/python/myriad/compiler/debug.py | Python | apache-2.0 | 2,056 | 0.006323 | '''
Copyright 2010-2013 DIMA Research Group, TU Berlin
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to... | der.alexandrov@tu-berlin.de>
'''
from myriad.compiler.visitor import AbstractVisitor
class PrintVisitor(AbstractVisitor):
'''
classdocs
'''
__indent = 0
__indentPrefix = " "
def __init__(self, *args, **kwargs):
super(PrintVisitor, self).__init__( | *args, **kwargs)
def traverse(self, node):
print "~" * 160
node.accept(self)
print "~" * 160
def _preVisitAbstractNode(self, node):
if (len(node.allAttributes()) == 0):
# print node with attributes
print "%s+ %s" % (self.__indentPrefix * self.__i... |
kenorb-contrib/BitTorrent | python_bt_codebase_library/BTL/ebrpc.py | Python | gpl-3.0 | 3,425 | 0.012555 | # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# bu... |
def __repr__(self):
return (
"<Fault %s: %s>" %
(self.faultCode, repr(self.faultString))
)
### datagram interface
### has transaction ID as third return valuebt
### slightly different API, returns a tid as third arg | ument in query/response
def dumpd(params, methodname=None, methodresponse=None, encoding=None, allow_none=False, tid=None):
assert tid is not None, "need a transaction identifier"
if methodname:
out = ebencode({'y':'q', 't':tid, 'q':methodname, 'a':params})
elif isinstance(params, DFault):
o... |
Trust-Code/addons-yelizariev | reminder_base/reminder_base_models.py | Python | lgpl-3.0 | 6,555 | 0.001831 | from openerp import api, models, fields, SUPERUSER_ID
class reminder(models.AbstractModel):
_name = 'reminder'
_reminder_date_field = 'date'
_reminder_description_field = 'description'
# res.users or res.partner fields
_reminder_attendees_fields = ['user_id']
reminder_event_id = fields.Many... | '] = self.id
if update_date:
fdate = self._fields[self._reminder_date_field]
fdate_value = getattr(self, self._reminder_date_field)
if not fdate_value:
event.unlink()
return
if fdate.type == 'date':
vals.update({
| 'allday': True,
'start_date': fdate_value,
'stop_date': fdate_value,
})
elif fdate.type == 'datetime':
vals.update({
'allday': False,
'start_datetime': fdate_value,
... |
stargaser/astropy | astropy/units/decorators.py | Python | bsd-3-clause | 9,242 | 0.001839 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ['quantity_input']
import inspect
from astropy.utils.decorators import wraps
from astropy.utils.misc import isiterable
from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies
from .physical import _unit_... | without an 'is_equivalent' method"
else:
error_msg = "no 'unit' attribute"
raise TypeError("Argument '{}' to function '{}' has {}. "
"You may want to pass in | an astropy Quantity instead."
.format(param_name, func_name, error_msg))
else:
if len(targets) > 1:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to one of: {}."
.format(param_name,... |
ciaranlangton/reddit-cxlive-bot | config.py | Python | mit | 62 | 0 | username = | "x"
pas | sword = "x"
subreddit = "x"
client_id = "x"
|
Comunitea/CMNT_00040_2016_ELN_addons | sales_mrp_stock_forecast_link/wizard/__init__.py | Python | agpl-3.0 | 1,048 | 0 | # -*- | coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2004-2012 Pexego Sistemas Informáticos All Rights Reserved
# $Pedro Gómez$ <pegomez@elnogal.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms o... | ublic License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A P... |
shudwi/CrimeMap | Type_Of_Crime/admin.py | Python | gpl-3.0 | 131 | 0 | from django.contrib import admin
from .m | odels import Typ | e_Of_Crime
admin.site.register(Type_Of_Crime)
# Register your models here.
|
tpsatish95/Topic-Modeling-Social-Network-Text-Data | Kseeds/modifiedCluster.py | Python | apache-2.0 | 4,434 | 0.016013 | import numpy as np
from sklearn import cluster, datasets, preprocessing
import pickle
import gensim
import time
import re
import tokenize
from scipy import spatial
def save_obj(obj, name ):
with open( name + '.pkl', 'wb') as f:
pickle.dump(obj, f, protocol=2)
def load_obj(name ):
with open( name + '.... | the cosine similarities
Cosine_Similarity = dict()
for k in Cluster_lookUP.keys():
# if len(Cluster_lookUP[k]) == 1:
Cosine_Similarity[k] = 1 - spatial.distance.cosine(model[k], catVec[Cluster_KlookU | P[k]])
# else:
# Cosine_Similarity[k] = [1 - spatial.distance.cosine(model[k], catVec[wk]) for wk in Cluster_KlookUP[k]]
#check
print(num2cat[Cluster_lookUP["flight"][0]] + " "+str(Cosine_Similarity["flight"]))
print(num2cat[Cluster_lookUP["gamecube"][0]] +" "+str(Cosine_Similarity["gamecube"]))
#Savi... |
ianloic/fuchsia-sdk | scripts/common.py | Python | apache-2.0 | 848 | 0.004717 | #!/usr/bin/env python
import json
import os
import subprocess
def normalize_target(target):
if ':' in target: return target
return target + ':' + os.path.basename(target)
def gn_desc(root_out_dir, target, *what_to_show):
# gn desc may fail transiently for an unknown reason; retry loop
for i in xrange... | t
] + list(what_to_show))
try:
output = json.loads(desc)
break
except ValueError:
if i >= 1:
print 'Failed to describe target ', target, '; output: ', desc
raise
if target not in | output:
target = normalize_target(target)
return output[target]
|
bd-j/magellanic | magellanic/sfhs/prediction_scripts/predicted_total.py | Python | gpl-2.0 | 5,894 | 0.009841 | import sys, pickle, copy
import numpy as np
import matplotlib.pyplot as pl
import astropy.io.fits as pyfits
import magellanic.regionsed as rsed
import magellanic.mcutils as utils
from magellanic.lfutils import *
try:
import fsps
from sedpy import observate
except ImportError:
#you wont be able to predict... | s(), 20, 23, [7, 13, | 16], [3,5,6]]
cloud_info['lmc'] = [utils.lmc_regions(), 48, 38, [7, 11, 13, 16], [3,4,5,6]]
def total_cloud_data(cloud, filternames = None, basti=False,
lfstring=None, agb_dust=1.0,
one_metal=None):
#########
# SPS
#########
#
if filternames is not No... |
MDAnalysis/mdanalysis | package/MDAnalysis/analysis/hole2/hole.py | Python | gpl-2.0 | 67,157 | 0.000626 | # -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
#
# MDAnalysis --- https://www.mdanalysis.org
# Copyright (c) 2006-2020 The MDAnalysis Development Team and contributors
# (see the file AUTHORS for the full list of names)
#
# Released under t... | MDAnalysis.analysis import hole2
u = mda.Universe(MULTIPDB_HOLE)
ha = hol | e2.HoleAnalysis(u, executable='~/hole2/exe/hole') as h2:
ha.run()
ha.create_vmd_surface(filename='hole.vmd')
The VMD surface created by the class updates the pore for each frame of the trajectory.
Use it as normal by loading your trajectory in VMD and sourcing the file in the Tk Console.
You can access the ac... |
mjlong/openmc | tests/test_filter_material/test_filter_material.py | Python | mit | 858 | 0.003497 | #!/usr/bin/env python
import os
import sys
sys.path.insert(0, os.pardir)
from testing_harness import TestHarness, PyAPITestHarness
import openmc
class FilterMaterialTestHarness(PyAPITestHarness):
def _build_inputs(self):
filt = openmc.Filter(type='material', bins=(1, 2, 3, 4))
tally = openmc.Tall... | def _cleanup(self):
super(FilterMaterialTestHarness, self)._cleanup()
f = os.path.join(os.getcwd(), 'tallies.xml')
if os.path.exists(f): os.remove(f)
if __name__ == '__main__':
harness = FilterMaterialTestHarne | ss('statepoint.10.*', True)
harness.main()
|
unlessbamboo/django | accounts/models.py | Python | gpl-3.0 | 1,076 | 0.005576 | from __future__ import unicode_literals
from django import forms
from django.db import models
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class Accounts(User):
class Meta:
proxy = True
class LoginForm(forms.Form):
# This creates two variables c... | RegistrationForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ('username', 'first_name', 'last_name',
'email', 'password1', 'password2')
def save(self, commit=True):
user = super(RegistrationForm, self).... | ]
if commit:
user.save()
return user
|
david-ragazzi/nupic | examples/opf/simple_server/model_params.py | Python | gpl-3.0 | 9,288 | 0.001507 | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2015, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... | PClass in
# CLARegion.py).
'temporalImp': 'cpp',
# New Synapse formation count
# NOTE: If None, use spNumActivePerIn | hArea
#
# TODO: need better explanation
'newSynapseCount': 20,
# Maximum number of synapses per segment
# > 0 for fixed-size CLA
# -1 for non-fixed-size CLA
#
# TODO: for Ron: once the appropriate value is placed in TP
... |
wangg12/IRLS_tf_pytorch | src/IRLS_tf_v2.py | Python | apache-2.0 | 6,061 | 0.003135 | # python 3
# tensorflow 2.0
from __future__ import print_function, division, absolute_import
import os
import argparse
import random
import numpy as np
import datetime
# from numpy import linalg
import os.path as osp
import sys
cur_dir = osp.dirname(osp.abspath(__file__))
sys.path.insert(1, osp.join(cur_dir, '.'))
fr... | optimize(w, w_update)
i += 1
print("training done.")
if __name__ = | = "__main__":
# test_acc should be about 0.85
lambda_ = 20 # 0
train_IRLS(X_train, y_train, X_test, y_test, L2_param=lambda_, max_iter=100)
from sklearn.linear_model import LogisticRegression
classifier = LogisticRegression()
classifier.fit(X_train, y_train.reshape(N_train,))
y_pred_train ... |
ragb/sudoaudio | sudoaudio/speech/__init__.py | Python | gpl-3.0 | 1,242 | 0.003221 | # Copyright (c) 2011 - Rui Batista <ruiandrebatista@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public L | icense as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICUL... | the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import locale
import logging
from accessible_output import speech
logger = logging.getLogger(__name__)
_speaker = None
def init():
global _speaker
if _speaker:
return
_speaker = speech.Spe... |
dariosena/LearningPython | general/dry/test_calc.py | Python | gpl-3.0 | 794 | 0 | import unittest
import calc
class CalcTestCase(unittest.TestCase):
"""Test calc.py"""
def setUp(self):
self.num1 = 10
self.num2 = 5
def tearDown(self):
pass
def test_add(self):
self.assertTrue(calc.add(self.num1, self.num2), self.num1 + self.num2)
... |
unittest.mai | n()
|
grnet/synnefo | snf-cyclades-app/synnefo/app_settings/default/api.py | Python | gpl-3.0 | 8,466 | 0.000472 | # -*- coding: utf-8 -*-
#
# API configuration
#####################
DEBUG = False
# Top-level URL for deployment. Numerous other URLs depend on this.
CYCLADES_BASE_URL = "https://compute.example.synnefo.org/compute/"
# The API will return HTTP Bad Request if the ?changes-since
# parameter refers to a point in time ... | ("ext_archipelago", "ext_vlmc")
# The maximum number of tags allowed for a Cyclades Virtual Machine
CYCLADES_VM_MAX_TAGS = 50 |
# The maximmum allowed metadata items for a Cyclades Virtual Machine
CYCLADES_VM_MAX_METADATA = 10
# Define cache for public stats
PUBLIC_STATS_CACHE = {
"BACKEND": "django.core.cache.backends.locmem.LocMemCache",
"LOCATION": "",
"KEY_PREFIX": "publicstats",
"TIMEOUT": 300,
}
# Permit users of speci... |
wmak/mvmv | mvmv/cli.py | Python | mit | 6,353 | 0.001259 | #!/usr/bin/env python
from os import path
import sys
import sqlite3
import random
import argparse
import re
import gzip
import mvmv.mvmv as mvmv
import mvmv.mvmvd as mvmvd
import mvmv.parse as parse
class DownloadDB(argparse.Action):
def __init__(self, option_strings, dest, nargs=None, **kwargs):
super(D... | rgs.excludes)]
args.srcdirs = [path.abspath(sdir) for sdir in args.srcdirs
if path.isdir(sdir)]
args.destdir = path.abspath(args.destdir[0])
for arg in args.args:
if path.isdir(arg):
args.srcdirs.append(path.abspath(arg))
elif mvmv.is_valid_file(arg):
... | if not path.isdir(args.destdir[0]):
error("'%s' is not a directory." % args.destdir[0])
sys.exit(1)
if not args.srcdirs and not args.files:
error("You must specify a directory or filename in the commandline.")
sys.exit(1)
conn = sqlite3.connect(args.dbpath)
cursor = conn.cur... |
Sorsly/subtle | google-cloud-sdk/lib/surface/logging/sinks/list.py | Python | mit | 4,667 | 0.004928 | # Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | name.
for typed_sink in self.ListLogServiceSinks(project, service.name):
yield typed_sink
# Lastly, get all v2 sinks.
for typed_sink in self.ListSinks(util.GetCurrentProjectParent()):
yield typed_sink
def Run(self, args): |
"""This is what gets called when the user runs this command.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
The list of sinks.
"""
util.CheckLegacySinksCommandArguments(args)
project = properties.VALUES.core.pr... |
HumanCompatibleAI/imitation | src/imitation/scripts/config/train_adversarial.py | Python | mit | 4,850 | 0.000825 | """Configuration for imitation.scripts.train_adversarial."""
import sacred
from imitation.rewards import reward_nets
from imitation.scripts.common import common, demonstrations, reward, rl, train
train_adversarial_ex = sacred.Experiment(
"train_adversarial",
ingredients=[
common.common_ingredient,
... | e="HalfCheetah-v2")
rl | = dict(batch_size=16384, rl_kwargs=dict(batch_size=1024))
algorithm_specific = dict(
airl=dict(total_timesteps=int(5e6)),
gail=dict(total_timesteps=int(8e6)),
)
reward = dict(
algorithm_specific=dict(
airl=dict(
net_cls=reward_nets.BasicShapedRewardNet,
... |
shakamunyi/neutron-vrrp | neutron/tests/unit/ml2/test_mechanism_odl.py | Python | apache-2.0 | 9,006 | 0 | # Copyright (c) 2013-2014 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Un... | plugin.Ml2Plugin()
def test_missing_url_raises_exception(self):
self._test_missing_config(url=None)
def test_m | issing_username_raises_exception(self):
self._test_missing_config(username=None)
def test_missing_password_raises_exception(self):
self._test_missing_config(password=None)
class OpenDaylightMechanismTestBasicGet(test_plugin.TestBasicGet,
OpenDaylightTestCas... |
edoburu/django-fluent-utils | fluent_utils/softdeps/any_imagefield.py | Python | apache-2.0 | 1,856 | 0.002694 | """
Optional integration with django-any-Imagefield
"""
from __future__ import absolute_import
from django.db import models
from fluent_utils.django_compat import is_installed
if is_installed('any_imagefield'):
from any_imagefield.models import AnyFileField as BaseFileField, AnyImageField as BaseImageField
else:... | def deconstruct(self):
# For Django migrations, masquerade as normal FileField too
name, path, args, kwargs = super(AnyFileField, self).deconstruct()
# FileField behavior
if kwargs.get("max_length") == 100:
del kwargs["max_length"]
kwargs['upload_to'] = getattr(se... | , None) or getattr(self, 'directory', None) or ''
return name, "django.db.models.FileField", args, kwargs
# subclassing here so South or Django migrations detect a single class.
class AnyImageField(BaseImageField):
"""
An ImageField that can refer to an uploaded image file.
If *django-any-imagef... |
indirectlylit/kolibri | kolibri/core/content/test/test_deletechannel.py | Python | mit | 1,918 | 0.000521 | from django.core.management import call_command
from django.test import TestCase
from mock import call
from mock import patch
from kolibri.core.con | tent import models as content
class DeleteChannelTestCase(TestCase):
"""
Testcase for delete channel management command
"""
fixtures = ["content_test.json"]
the_channel_id = "6199dde695db4ee4ab392222d5af1e5c"
def delete_channel(self):
call_command("deletechannel", self.the_channel_id... | .ChannelMetadata.objects.count())
def test_channelmetadata_delete_remove_contentnodes(self):
self.delete_channel()
self.assertEquals(0, content.ContentNode.objects.count())
def test_channelmetadata_delete_leave_unrelated_contentnodes(self):
c2c1 = content.ContentNode.objects.get(title=... |
errollw/EyeTab | EyeTab_Python/gaze_geometry.py | Python | mit | 5,818 | 0.010141 | import visual as vpy
import numpy as np
import anatomical_constants
from math import sin, cos, acos, atan, radians, sqrt
from conic_section import Ellipse
cam_mat_n7 = np.array([[1062.348, 0.0 , 344.629],
[0.0 , 1065.308, 626.738],
[0.0 , 0.0 , 1.0]])
# [... | _offset_px = device | .screen_y_offset_px # height of notification bar
x_offset, y_offset = device.offset_mm # screen offset from camera position
x_screen_px = (x_screen_mm + x_offset) / screen_w_mm * screen_w_px
y_screen_px = (y_screen_mm - y_offset) / screen_h_mm * screen_h_px - screen_y_offset_px
... |
ConstantinT/jAEk | crawler/models/urlstructure.py | Python | gpl-3.0 | 1,991 | 0.00452 | '''
Copyright (C) 2015 Constantin Tschuertz
This program is free software: you can | redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is di | stributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.