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
KSG-IT/ksg-nett
common/context_processors.py
Python
gpl-3.0
317
0.009464
from organization.models import InternalGroup def internal_groups(request): groups = InternalGroup.objects.filter(type=InternalGroup.Type.INTERNAL_GROUP).order_by("name") return {"header_internal_groups": groups} # we prefix it header_ so it does not conflict in the
organization/internalgroups/<id>
view
petrjasek/superdesk-server
apps/auth/db/reset_password.py
Python
agpl-3.0
4,394
0.001821
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license import loggi...
ST'] item_methods = [] class ResetPasswordService(BaseService): def create(self, docs, **kwargs): for doc in docs: email = doc.get('email') key = doc.get('token') password = doc.get('password') if key and password: return self.reset_pas...
Either key:password or email must be provided') def store_reset_password_token(self, doc, email, days_alive, user_id): token_ttl = app.config['RESET_PASSWORD_TOKEN_TIME_TO_LIVE'] now = utcnow() doc[app.config['DATE_CREATED']] = now doc[app.config['LAST_UPDATED']] = now doc['...
Kazanz/redis-py
redis/_compat.py
Python
mit
5,651
0.000177
"""Internal module for Python 2 backwards compatibility.""" import errno import sys try: InterruptedError = InterruptedError except: InterruptedError = OSError # For Python older than 3.5, retry EINTR. if sys.version_info[0] < 3 or (sys.version_info[0] == 3 and sys.version_info[...
) if sys.version_info[0] < 3: from urllib import unquote from urlparse import parse_qs, urlparse from itertools import imap, izip from string import letters as ascii_letters from Queue import Queue try: from cStringIO import StringIO as BytesIO except ImportError: from Strin...
as BytesIO # special unicode handling for python2 to avoid UnicodeDecodeError def safe_unicode(obj, *args): """ return the unicode representation of obj """ try: return unicode(obj, *args) except UnicodeDecodeError: # obj is byte string ascii_text = s...
philippjfr/bokeh
bokeh/document/document.py
Python
bsd-3-clause
35,065
0.00154
''' Provide the ``Document`` class, which is a container for Bokeh Models to be reflected to the client side BokehJS library. As a concrete example, consider a column layout with ``Slider`` and ``Select`` widgets, and a plot with some tools, an axis and grid, and a glyph renderer for circles. A simplified representati...
istered on this document. Args:
model (Model) : The model to add as a root of this document. setter (ClientSession or ServerSession or None, optional) : This is used to prevent "boomerang" updates to Bokeh apps. (default: None) In the context of a Bokeh server application,...
christianurich/VIBe2UrbanSim
3rdparty/opus/src/urbansim/household_x_zone/is_high_income_x_percent_high_income.py
Python
gpl-2.0
1,967
0.019827
# Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE from opus_core.variables.variable import Variable from urbansim.functions import attribute_label class is_high_income_x_percent_high_income(Variable): """Percent of households with high-i...
iable_name = "urbansim.household_x_zone.is_high_income_x_percent_high_income" def test_my_inputs(self): percent_high_income_households = array([50, 10, 20]) is_high_income = array([1, 0, 1, 0]) values = VariableTestToolbox().compute_variable(self.variable_name, ...
{"zone":{ "percent_high_income_households":percent_high_income_households}, "household":{ "is_high_income":is_high_income}}, dataset = "household_x_zone") should_be = array([[50, 10, 20], [0, 0, 0 ], [50, 10, 20], [0,0,0]]) ...
calston/tensor
tensor/protocol/sflow/protocol/counters.py
Python
mit
9,132
0.004161
from construct import * class InterfaceCounters(object): def __init__(self, u): self.if_index = u.unpack_uint() self.if_type = u.unpack_uint() self.if_speed = u.unpack_uhyper() self.if_mode = u.unpack_uint() self.if_status = u.unpack_uint() self.if_inOctets = u.unp...
u.unpack_uint() self.dot5StatsTransmitBeacons = u.unpack_uint() self.dot5StatsRecoverys = u.unpack_uint() self.dot5StatsLobeWires = u.unpack_uint() se
lf.dot5StatsRemoves = u.unpack_uint() self.dot5StatsSingles = u.unpack_uint() self.dot5StatsFreqErrors = u.unpack_uint() class VGCounters(object): def __init__(self, u): self.dot5StatsLineErrors = u.unpack_uint() self.dot5StatsBurstErrors = u.unpack_uint() self.dot5StatsACEr...
ets-labs/python-dependency-injector
examples/wiring/flask_resource_closing.py
Python
bsd-3-clause
807
0
"""`Resource` - Flask request scope example.""" from dependency_injector import containers, providers from dependency_injector.wiring import Closing, Provide, inject from
flask import Flask, current_app class Service: ... def init_service() -> Service: print("Init service") yield Service() print("Shutdown service") class Container(containers.DeclarativeContainer): service = providers.R
esource(init_service) @inject def index_view(service: Service = Closing[Provide[Container.service]]): assert service is current_app.container.service() return "Hello World!" container = Container() container.wire(modules=[__name__]) app = Flask(__name__) app.container = container app.add_url_rule("/", "in...
huaxz1986/git_book
chapters/Bayesian/bernoulliNB.py
Python
gpl-3.0
2,962
0.024143
# -*- coding: utf-8 -*- """ 贝叶斯分类器和贝叶斯网络 ~~~~~~~~~~~~~~~~~~~~~~~~~~ BernoulliNB :copyright: (c) 2016 by the huaxz1986. :license: lgpl-3.0, see LICENSE for more details. """ from sklearn import naive_bayes import numpy as np import matplotlib.pyplot as plt def test_BernoulliNB(*data): ''' ...
yes.BernoulliNB(alpha=alpha) cls.fit(X_train,y_train) tr
ain_scores.append(cls.score(X_train,y_train)) test_scores.append(cls.score(X_test, y_test)) ## 绘图 fig=plt.figure() ax=fig.add_subplot(1,1,1) ax.plot(alphas,train_scores,label="Training Score") ax.plot(alphas,test_scores,label="Testing Score") ax.set_xlabel(r"$\alpha$") ax.set_ylabel...
zentralopensource/zentral
zentral/contrib/osquery/__init__.py
Python
apache-2.0
76
0
default_app_config = "zentral.con
trib.osquery.a
pps.ZentralOsqueryAppConfig"
MarsBighead/mustang
Python/twoSum.py
Python
mit
428
0.03271
#!/usr/bin/python class Solution(object): def twoSum(sef, nums, target): for i in range(len(nums)):
anotherLoc = nums.index(target - nums[i]) if anot
herLoc>=0: return [i,anotherLoc] else: return [] nums=[2,11,15,7] target=9 instance =Solution() twoSum = instance.twoSum(nums, target) print "Two nums' location:",twoSum
kcaylor/eve-mongoengine
tests/test_patch.py
Python
bsd-3-clause
4,336
0.001153
import json import unittest from eve.utils import config from tests import BaseTest, SimpleDoc, ComplexDoc def post_simple_item(f): def wrapper(self): response = self.client.post('/simpledoc/', data='{"a": "jimmy", "b": 23}', content...
'/simpledoc/%s/complexdoc/%s' % (s.id, d.id)) json_data = response.get_json() self.assertListEqual(json_data['l'], ['x', 'y', 'z']) self.assertEqual(
json_data['n'], 999) # cleanup s.delete() d.delete()
zxyle/PyNote
15.regex.py
Python
gpl-3.0
1,774
0.007618
#!/usr/bin/env python3 # coding:utf-8 import re re.match(pattern, string, flags=0) re.search(pattern, string, flags=0) re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回AttributeError;而re.search匹配整个字符串,直到找到一个匹配. re.sub(pattern, repl, string, max=0) 替换 # task01 匹配国内固话 区号有3或4位 后面有7或8位的情况 # phone_number = input("please ent...
",s) # re.findall(r"wORld$",s,re.I) # re.findall(r"\b\w+\b",s) # task06 # s = "hello world" # re.sub(r"hello",'hi',s) # re.sub(r"hello","hi",s[-4:]) # re.sub(r"world","China",s[-5:]) # task07 # s = "你好 WORLD2" # print "匹配的
字母数字" + re.sub(r"\w","hi",s) # print "替换次数:" + str(re.subn(r"\w","hi",s)[1]) # print "匹配非字母数字的字符:"+ re.sub(r"\W","hi",s) # print "替换词数:"+str(re.subn(r"\W",'hi',s)[1])
multidadosti-erp/multidadosti-addons
calendar_systray_menu/models/__init__.py
Python
agpl-3.0
23
0
from .
import calenda
r
klim-iv/phantomjs-qt5
src/webkit/Source/WebCore/inspector/CodeGeneratorInspector.py
Python
bsd-3-clause
98,207
0.003299
#!/usr/bin/env python # Copyright (c) 2011 Google Inc. All rights reserved. # Copyright (c) 2012 Intel Corporation. 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 sou...
e arguments: %s\n\n" % exc) sys.stderr.write("Usage: <script> Inspector.json --outpu
t_h_dir <output_header_dir> --output_cpp_dir <output_cpp_dir> --output_js_dir <output_js_dir> [--write_always] [--no_verification]\n") exit(1) def dash_to_camelcase(word): return ''.join(x.capitalize() or '-' for x in word.split('-')) def fix_camel_case(name): refined = re.sub(r'-(\w)', lambda pat: pat....
sevein/archivematica
src/dashboard/src/wsgi.py
Python
agpl-3.0
218
0
import os from django.core.wsgi import get_wsgi_application import elasticSearchFunctions application = get_
wsgi_application() # Set up Elasticsearch client elasti
cSearchFunctions.setup_reading_from_client_conf()
antoinecarme/pyaf
tests/periodicities/Day/Cycle_Day_100_D_60.py
Python
bsd-3-clause
82
0.04878
import tests.periodicities.per
iod_test as per per.buildModel((60 ,
'D' , 100));
Fshem/micro_bank_system
loan/apps.py
Python
agpl-3.0
124
0
from _
_future__ import unicode_literals from django.apps import AppConfig class LoanConfig(AppConfig): name =
'loan'
davecranwell/wagtail
wagtail/wagtailforms/wagtail_hooks.py
Python
bsd-3-clause
953
0.002099
from django.core import urlresolvers from django.conf.urls import include, url from django.utils.translation import ugettext_lazy as _ from wagtail.wagtailcore import hooks from wagtail.wagtailadmin.menu import MenuItem from wagtail.wagtailforms import urls from wagtail.wagtailforms.models import get_forms_for_user ...
r'^forms/', include(urls, app_name='wagtailforms', namespace='wagtailforms')), ] class FormsMenuItem(MenuItem): def is_shown(self, request): # show this only if the user has permission to retrieve submissions for at least one form return get_forms_for_user(request.user).exists() @hooks.regis...
rs.reverse('wagtailforms:index'), name='forms', classnames='icon icon-form', order=700 )
computersalat/ansible
lib/ansible/template/__init__.py
Python
gpl-3.0
43,207
0.002384
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible 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) an...
eAssertionError from ansible.module_utils.six import iteritems, string_types, text_type from ansible.module_utils.six.moves import range from ansible.module_utils._text import to_native, to_text, to_bytes from ansible.module_utils.common._collections_compat import Iterator, Sequence, Mapping, MappingView, MutableMappin...
ter_loader, lookup_loader, test_loader from ansible.template.safe_eval import safe_eval from ansible.template.template import AnsibleJ2Template from ansible.template.vars import AnsibleJ2Vars from ansible.utils.collection_loader import AnsibleCollectionRef from ansible.utils.display import Display from ansible.utils.co...
NikolausDemmel/catkin_tools
tests/unit/test_config.py
Python
apache-2.0
4,666
0.001072
import os import shutil import mock from catkin_tools import config from ..utils import assert_raises_regex from ..utils import in_temporary_directory from ..utils import redirected_stdio @mock.patch('catkin_tools.config.initialize_verb_aliases') @in_temporary_directory def test_config_initialization(patched_func):...
test_folder) with assert_raises_regex(RuntimeError, "Cannot get verb aliases because the verb aliases config path"): config.get_verb_aliases(test_folder) shutil.rmtree(test_folder) # Test the normal case config
.initialize_config(test_folder) aliases = config.get_verb_aliases(test_folder) assert 'b' in aliases assert aliases['b'] == 'build' # Test a custom file base_path = os.path.join(test_folder, 'verb_aliases') with open(os.path.join(base_path, '01-my-custom-aliases.yml'), 'w') as f: f.write...
jwodder/javaproperties
src/javaproperties/__init__.py
Python
mit
1,654
0
""" Read & write Java .properties files ``javaproperties`` provides support for reading & writing Java ``.properties`` files (both the simple line-oriented format and XML) with a simple API based on the ``json`` module — though, for recovering Java addicts, it also includes a ``Properties`` class intended to match the...
as much as is Pythonically possible. Visit <https://github.com/jwodder/javaproperties> or <http://javaproperties.rtfd.io> for more information. """ import codecs from .propclass import Properties from .propfile import PropertiesFile from .reading import ( Comment, InvalidUEscapeError, KeyValue, Prope...
mps, escape, java_timestamp, javapropertiesreplace_errors, join_key_value, to_comment, ) from .xmlprops import dump_xml, dumps_xml, load_xml, loads_xml __version__ = "0.8.1" __author__ = "John Thorvald Wodder II" __author_email__ = "javaproperties@varonathe.org" __license__ = "MIT" __url__ = "https...
PeachyPrinter/peachytoolchain
src/audio/tuning_parameters.py
Python
gpl-3.0
4,182
0.001913
from .modulation import ModulationTypes class TuningParameterCollection(object): """ Holds multiple tuning parameters at various heights. Each acts as a calibration point. """ tuning_parameters = [] build_x_min = -50.0 build_y_min = -50.0 build_x_max = 50.0 build_y_max = 50.0 dwell_...
velocity_x_max = 6000.0 velocity_y_max = 6000.0 drips_per_height
= 100.0 sublayer_height = 0.01 modulation = ModulationTypes.AM def __init__(self): self.tuning_parameters = [ ] self._cached_tuning_parameters = None self._cached_height = None def reset_cache(self): self._cached_tuning_parameters = None self._cached_height = N...
glogiotatidis/mozillians-new
mozillians/announcements/tests/__init__.py
Python
bsd-3-clause
396
0.002525
import factory from test_utils import TestCase as BaseTestCase from mozillians.announcements import models class TestCase(BaseTestCase): pass class AnnouncementFactory(factory.Dja
ngoModelFactory): FACTORY_FOR = models.Announcement title = factory.Sequence(lambda n: 'Test Announcement {0}'.
format(n)) text = factory.Sequence(lambda n: 'Text for Announcement {0}'.format(n))
SkierPGP/Skier
skier/pgpactions.py
Python
agpl-3.0
5,513
0.001814
import datetime import threading import requests import db import cfg from skier import pgp from cfg import API_VERSION, SKIER_VERSION def import_key(keyserver: str, keyid: str): """ Attempts to import a key from the keyserver. :param keyserver: The keyserver to import from. :param keyid: The Key ID...
- -2: Could not connect to keyserver - -3: Invalid key - -4: Already exists on server unchanged """ # Check to see if the server is a skier server. is_skier = False try:
if 'http://' not in keyserver and "https://" not in keyserver: keyserver = "http://" + keyserver r = requests.post(keyserver + "/skier", data=[API_VERSION,SKIER_VERSION]) if r.status_code == 200: js = r.json() # Check the API version to make sure we're compatible. ...
senior-zero/metanet
metanet/networks/artificial_networks/hopfield_network.py
Python
gpl-3.0
5,218
0.002137
## @file hopfield_network.py # HopfieldNetwork implementation # Логика обучения была взята из https://github.com/pmatigakis/hopfieldnet ## @package artificial_networks # @author Evtushenko Georgy # @date 05/03/2015 17:19:00 # @version 1.1 ## @mainpage Metanet documentation # @section intro_sec Introduction # ...
n = len(input_patterns) num_neurons = self.weights.shape[0] weights = np.zeros((num_neurons, num_neurons)) for i in range(num_neurons): for j in range(num_neurons): if i == j: continue for m in range(n): weights[i, j] +=...
ut_patterns[m][i] * input_patterns[m][j] weights *= 1/float(n) self.weights = weights def draw_net(self): import matplotlib.pyplot as plt position = dict() for i, layer in enumerate(self.layers): for j, neuron in enumerate(layer.get_nodes()): ...
xclxxl414/rqalpha
tests/mod/sys_accounts/test_account_model.py
Python
apache-2.0
2,003
0.000501
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2017 Ricequant, Inc # # 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 r...
if context.now.date() > datetime.date(2015, 12, 29): assert context.portfolio.total_value == context.total_value_before_delisted return init, handle_bar
JazzeYoung/VeryDeepAutoEncoder
pylearn2/pylearn2/datasets/tfd.py
Python
bsd-3-clause
4,912
0
""" .. todo:: WRITEME """ import numpy as np from pylearn2.datasets import dense_design_matrix from pylearn2.utils.serial import load from pylearn2.utils.rng import make_np_rng from pylearn2.utils import contains_nan class TFD(dense_design_matrix.DenseDesignMatrix): """ Pylearn2 wrapper for the Toronto ...
e[1]) else:
ex_range = slice(None) # get images and cast to float32 data_x = data['images'][set_indices] data_x = np.cast['float32'](data_x) data_x = data_x[ex_range] # create dense design matrix from topological view data_x = data_x.reshape(data_x.shape[0], image_size ** 2) ...
r4is3/heimdall
server/heimdall/objects.py
Python
gpl-3.0
1,370
0.005109
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of Heimdall. Heimdall 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. Heimdall 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 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 Heimdall. If not, see <http://www.gnu.org/licenses/...
hydroshare/hydroshare
hs_file_types/models/base_model_program_instance.py
Python
bsd-3-clause
24,351
0.003942
import json import logging import os import random import shutil from uuid import uuid4 from django.contrib.postgres.fields import JSONField from django.core.exceptions import ValidationError from django.db import models from foresite import utils, Aggregation, URIRef, AggregatedResource, RdfLibSerializer from rdflib ...
le_res_file: return single_res_file.short_path return "" @property def schema_short_file_path(self):
"""File path of the aggregation metadata schema file relative to {resource_id}/data/contents/ """ json_file_name = self.aggregation_name if not json_file_name: return json_file_name if "/" in json_file_name: json_file_name = os.path.basename(json_file_name)...
ME-ICA/me-ica
meica.libs/select_model.py
Python
lgpl-2.1
12,834
0.059218
__version__="v2.5 beta10" welcome_block=""" # Multi-Echo ICA, Version %s # # Kundu, P., Brenowitz, N.D., Voon, V., Worbe, Y., Vertes, P.E., Inati, S.J., Saad, Z.S., # Bandettini, P.A. & Bullmore, E.T. Integrated strategy for improving functional # connectivity mapping using multiecho fMRI. PNAS (2013). # # Kundu, P.,...
ICT_FACTOR=2 if knobargs!='': for knobarg in ''.join(knobargs).split(','
): exec(knobarg) """ Do some tallies for no. of significant voxels """ countsigZ = Z_clmaps.sum(0) countsigFS0 = F_S0_clmaps.sum(0) countsigFR2 = F_R2_clmaps.sum(0) countnoise = np.zeros(len(nc)) """ Make table of dice values """ dice_table = np.zeros([nc.shape[0],2]) csize = np.max([int(mask.sum()*0.0005...
arantebillywilson/python-snippets
py2/cool-things/isprime.py
Python
mit
565
0.00531
#!/usr/bin/pyt
hon # -*- coding: utf-8 -*- # isprime.py # # Author: Billy Wilson Arante # Created: 2016/06/16 PHT # Modified: 2016/10/01 EDT (America/New York) from sys import argv def isprime(x): """Checks if x is prime number Returns true if x is a prime number, otherwise false. """ if x <= 1: return Fa...
0: return False return True def main(): """Main""" filename, number = argv print isprime(int(number)) if __name__ == "__main__": main()
sdgdsffdsfff/redis-ctl
models/__init__.py
Python
mit
211
0
import os module = None for m
odule in os.listdir(os.path.dirname(__file__)): if module == '__init__.py' or module[-3:] != '.py': continue __import__(module[:-3], loc
als(), globals()) del module
BD2KGenomics/slugflow
docs/conf.py
Python
apache-2.0
6,375
0.002981
# Toil documentation build configuration file, created by # sphinx-quickstart on Tue Aug 25 12:37:16 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. # # All configuration values have ...
'sphinx.ext.doctest', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.viewcode', 'sphinx.ext.intersphinx', 'fulltoc', ] intersphinx_mapping = {'python': ('https://docs.python.org/3', None),} # Link definitions available everywhere so we don't need to keep repeating ourselves. rst_epilog = "...
what, name, obj, skip, options): return name != '__init__' and (skip or inspect.isclass(obj) or name.startswith('_') and not inspect.ismodule(obj)) def setup(app): app.connect('autodoc-skip-member', skip) # Add any paths that contain templ...
charles-cooper/raiden
raiden/tests/fixtures/__init__.py
Python
mit
2,921
0
# -*- coding: utf-8 -*- from raiden.tests.fixtures.abi import ( token_abi, registry_abi, channel_manager_abi, netting_channel_abi, ) from raiden.tests.fixtures.api import ( api_raiden_service, api_test_context, api_backend ) from raiden.tests.fixtures.blockchain import ( token_address...
en.tests.fixtures.tester import ( tester_blockgas_limit, tester_events, tester_state, tester_token_address, tester_nettingchannel_library_address, tester_channelmanager_library_address, tester_registry_address, tester_token_raw, tester_token, tester_registry, tester_channelma...
ort ( send_ping_time, max_unresponsive_time, settle_timeout, reveal_timeout, events_poll_timeout, deposit, both_participants_deposit, number_of_tokens, number_of_nodes, channels_per_node, poll_timeout, transport_class, privatekey_seed, deploy_key, token_amount...
manly-man/moodle-destroyer-tools
frontend/interactive.py
Python
mit
1,271
0.004721
import curses from curses.textpad import Textbox, rectangle import asyncio import readline import rlcompleter # import readline # optional, will allow
Up/Down/History in the console # import code # vars = gl
obals().copy() # vars.update(locals()) # shell = code.InteractiveConsole(vars) # shell.interact() class CursesUi: def __init__(self): self.screen = curses.initscr() self.screen.clear() def __enter__(self): print('__enter__') return self def __exit__(self, exc_type, exc_va...
simonmeister/UnFlow
src/e2eflow/synthia/data.py
Python
mit
2,040
0.00049
import os import sys import numpy as np import matplotlib.image as mpimg from ..core.data import Data from ..util import tryremove URL = 'http://synthia-dataset.cvc.uab.cat/SYNTHIA_SEQS/' SEQS = [ # SUMMER and WINTER from sequences `1 - 6` 'SYNTHIA-SEQS-01-SUMMER', 'SYNTHIA-SEQS-01-WINTER', 'SYNTHIA-SEQS...
r) def _fetch_if_missing(self): self._maybe_get_synthia() def get_raw_dirs(self): root_dir = os.path.join(self.current_dir, 'synthia') dirs = [] seqs = os.listdir(root_dir) for seq in seqs: seq_dir = os.path.join(root_dir, seq, seq, 'RGB', 'Stereo_Left') ...
ws: view_dir = os.path.join(seq_dir, view) dirs.extend([view_dir]) return dirs def _maybe_get_synthia(self): seqs = DEV_SEQS if self.development else SEQS for seq in seqs: root_dir = os.path.join(self.data_dir, 'synthia') url = URL + s...
cw-andrews/texools
tests/test_files.py
Python
mit
2,260
0
from typing import Text import pytest from texools.files import new_file_check, partspath class TestPartspath(object): partspath_raises_params = [ (), (dict()), (list(), list()), ('', ''), (13,), (None,), (None,), (None, None), ('C:/', None), (12, 'directory') ] partspath_return_types = ...
es'), ('\\\\server1', 'directory_1'), ('//server1', 'directory_1') ] partspath_return_expected = [ (('/home/johnny',), ('/home/johnny', '\\ho
me\\johnny')), (('~',), ('/home/johnny', '\\home\\johnny')), (('/home/johnny', 'Desktop'), ('/home/johnny/Desktop', '\\home\\johnny\\Desktop')), (('~/stuff', 'textfile.txt'), ('/home/johnny/stuff/textfile.txt', '\\home...
bvisness/the-blue-alliance
datafeeds/usfirst_event_offseason_list_parser.py
Python
mit
2,125
0.002353
from datetime import datetime import urlparse import logging from BeautifulSoup import BeautifulSoup from consts.event_type import EventType from datafeeds.parser_base import ParserBase from helpers.event_helper import EventHelper class UsfirstEventOffseasonListParser(ParserBase): @classmethod def parse(se...
d["class"].count('views-field-title') > 0: event["first_eid"] = td.a["href"].split("/")[-1] event["name"] = " ".join(td.a.text.split(" ")[:-1]) event["location"] = str(td.a.text.split(" ")[-1]).translate(None, "()") ...
pan in td.findAll('span'): if span["class"].count("date-display-start") > 0: event["start_date"] = datetime.strptime(span["content"][:10], "%Y-%m-%d") if span["class"].count("date-display-end") > 0: e...
himleyb85/django
tests/invalid_models_tests/test_relative_fields.py
Python
bsd-3-clause
58,804
0.002568
# -*- encoding: utf-8 -*- from __future__ import unicode_literals import warnings from django.core.checks import Error, Warning as DjangoWarning from django.db import models from django.db.models.fields.related import ForeignObject from django.test import ignore_warnings from django.test.testcases import SimpleTestCa...
) def test_one_to_o
ne_field_without_on_delete_warning(self): with warnings.catch_warnings(record=True) as warns: warnings.simplefilter('always') # prevent warnings from appearing as errors class Target(models.Model): model = models.IntegerField() class Model(models.Model): ...
Juniper/contrail-dev-controller
src/vnsw/agent/uve/mock_generator.py
Python
apache-2.0
16,590
0.011151
# # Copyright (c) 2014 Juniper Networks, Inc. All rights reserved. # import gevent from gevent import monkey; monkey.patch_all() import argparse import os import socket import random import math import uuid from netaddr import IPAddress from pysandesh.sandesh_base import * from pysandesh.util import UTCTimestampUsec f...
tip = int(self._ip_vns[other_vn] + \ self._ip_start_index + nvm) flows.append(FlowDataIpv4( flowuuid = str(uuid.uuid1()), direction_ing = random.randint(0, 1), sour...
), destvn = self._VN_PREFIX + str(other_vn), sourceip = sourceip, destip = destip, sport = random.randint(0, 65535), dport = random.randint(0, 65535), ...
timabbott/zulip
corporate/views.py
Python
apache-2.0
12,645
0.003954
import logging from decimal import Decimal from typing import Any, Dict, Optional, Union import stripe from django.conf import settings from django.core import signing from django.http import HttpRequest, HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from django...
management=%s, licenses=%s, has stripe_token: %s",
e.description, user.id, user.realm.id, user.realm.string_id, billing_modality, schedule, license_management, licenses, stripe_token is not None, ) return json_error(e.message, data={'error_description': e.description}) except Exception: billing_logger.exce...
metalpriest/django-constance
setup.py
Python
bsd-3-clause
1,931
0.000518
import os import re import codecs from setuptools import setup, find_packages def read(*parts): filename = os.path.join(os.path.dirname(__file__), *parts) with codecs.open(filename, encoding='utf-8') as fp: return fp.read() def find_version(*file_paths): version_file = read(*file_paths) vers...
hor='Jannis Leidel', author_email='jannis@leidel.info', license='BSD', keywords='django libraries settings redis'.split(), platforms='any', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended ...
'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3...
alxgu/ansible
lib/ansible/plugins/action/cli_config.py
Python
gpl-3.0
1,287
0.000777
# # Copyright 2018 Red Hat Inc. # # This file is part of Ansible # # Ansible 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. # # Ansibl...
tmp no longer has any effect self._config_module = True if self._play_context.connection != 'network_cli': return {'failed': True, 'msg': 'Connection type %s is not valid for cli_config module' % self._play_context.connection} return super(ActionModule,
self).run(task_vars=task_vars)
razvanc-r/godot-python
tests/bindings/lib/_pytest/_code/code.py
Python
mit
30,105
0.001761
import sys from inspect import CO_VARARGS, CO_VARKEYWORDS import re from weakref import ref import py builtin_repr = repr reprlib = py.builtin._tryimport('repr', 'reprlib') if sys.version_info[0] >= 3: from traceback import format_exception_only else: from ._py2traceback import format_exception_only class ...
th.local(self.raw.co_filename) # maybe don't try this checking if not p.check(): raise OSError("py.path check failed.") except OSError: # XXX maybe try harder like the weird logic # in the standard lib [linecache.updatecache] does? p = ...
""" from _pytest._code import source full, _ = source.findsource(self.raw) return full def source(self): """ return a _pytest._code.Source object for the code object's source only """ # return source only for that part of code import _pytest._code ...
modelrockettier/wget
testenv/Test-metalink-xml-homepath-trust.py
Python
gpl-3.0
3,186
0.002197
#!/usr/bin/env python3 from sys import exit from misc.metalinkv3_xml import Metalinkv3_XML """ This is to test if Metalink/XML forbids the home path and names beginning with the ~ (tilde) character. With --trust-server-names, trust the metalink:file names. Without --trust-server-names, don't trust t...
################### Meta = Metalinkv3_XML() # file_name: metalink:file "name" field # save_name: metalink:file save name, if None the file is rejected # content : metalink:file content # # size: # True auto-compute size # None no <size></size> # any use this size # # hash_sha25
6: # False no <verification></verification> # True auto-compute sha256 # None no <hash></hash> # any use this hash # # srv_file : metalink:url server file # srv_content: metalink:url server file content, if None the file doesn't exist # utype : metalink:url type # location : metalink:ur...
foursquare/pants
contrib/scrooge/src/python/pants/contrib/scrooge/tasks/java_thrift_library_fingerprint_strategy.py
Python
apache-2.0
1,733
0.008656
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import absolute_import, division, print_function, unicode_literals import hashlib from builtins import str from pants.backend.codege
n.thrift.java.java_thrift_library import JavaThriftLibrary from pants.base.fingerprint_strategy import FingerprintStrategy class JavaThriftLibraryFingerprintStrategy(FingerprintStrategy): """Scrooge cares about a Thrift target
's `language` and `compiler_args` and more in addition to its payload. As such this strategy ensures new code is generated by Scrooge whenever any option that effects codegen changes. """ def __init__(self, thrift_defaults): self._thrift_defaults = thrift_defaults def compute_fingerprint(self, target...
ferdavid1/Tequila-Mockingbird
check_mic.py
Python
gpl-3.0
204
0.004902
import sp
eech_recognition as sr for index, name in enumerate(sr.Microphone.list_microphone_names()): print("Microphone with name \"{1}\" found for `Microphone(devic
e_index={0})`".format(index, name))
caioserra/apiAdwords
tests/adspygoogle/dfp/dfp_utils_test.py
Python
apache-2.0
10,061
0.002485
#!/usr/bin/python # # Copyright 2013 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 b...
'email': 'fake_email', 'password': 'fake_password', 'applicationName': 'fake_application_name', 'authToken': ' ' } client = DfpClient(headers=headers) self.failUnlessRaises( ValidationError, DfpUtils.GetAllEntitiesByStatement, client, 'User', 'ORDER BY name LI...
line_item_service = mock.Mock() rval = 'Line items for everyone!' def VerifyExpectedCall(arg): self.assertEqual({'values': None, 'query': 'ORDER BY name LIMIT 500 OFFSET 0'}, arg) return [{'results': [rval]}] line_item_service._service_name = 'LineItemService' ...
rebearteta/social-ideation
connectors/migrations/0012_auto_20150624_1119.py
Python
mit
427
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('connectors', '0011_auto_20150624_1055'), ] operations = [ migrations.RenameField( model_name='socialnetworkconne...
_package', new_name='connecto
r_module', ), ]
702nADOS/sumo
tools/purgatory/routes2OD.py
Python
gpl-3.0
3,825
0.00183
#!/usr/bin/env python """ @file routes2OD.py @author Julia Ringel @author Daniel Krajzewicz @author Michael Behrisch @date 2009-04-15 @version $Id: routes2OD.py 22608 2017-01-17 06:28:54Z behrisch $ Creates an OD-matrix in visum format $O from a route.xml file when starting the programm the name for the input...
.Start) + ' ' + myTimes.seconds2TimeOfDay(myTimes.End), file=outputData) print('* Factor', file=outputData) print('1.00', file=outputData) print('*some additional comments', file=outputData) startbez = myData.keys()
startbez.sort() for x in startbez: endbez = myData[x].keys() endbez.sort() x1 = str(x).rjust(23) for y in endbez: y1 = str(y).rjust(20) value1 = (str(myData[x][y]) + ".00").rjust(12) print(x1, y1, value1, file=outputData) outputData.close() ...
Safihre/cherrypy
docs/conf.py
Python
bsd-3-clause
7,289
0
"""CherryPy sphinx doc configuration module.""" # -*- coding: utf-8 -*- # # CherryPy documentation build configuration file, created by # sphinx-quickstart on Sat Feb 20 09:18:03 2010. # # This file is execfile()d with the current directory set to its containing # dir. # # Note that not all possible configuration value...
quired to buil
d docs' def try_import(mod_name): """Attempt importing module and suppress failure of doing this.""" try: return importlib.import_module(mod_name) except ImportError: pass def get_supported_pythons(classifiers): """Return min and max supported Python version from meta as tuples.""" ...
w1lq/MacPerformance
Simulation.py
Python
mit
2,721
0.020581
#! /usr/bin/python from TOSSIM import * from sets import Set import sys from optparse import OptionParser parser = OptionParser(usage="usage: %prog [options] filename", version="%prog 1.0") parser.add_option("-g", "--gainfile", action="store", dest="gainfile", default="topology.txt", help="file containing gains ...
vars(options) print options_dict['gainfile'] print "Simulation start" from tinyos.tossim.TossimApp import * n = NescApp() vars = n.variables.variables() t = Tossim(vars) r = t.radio() mac = t.mac() # Topology configuration gainfile = open(options_dict['gainfile'], "r") nodes = Set([]) print "Simulation Topology:...
nes = gainfile.readlines() for line in lines: splitlines = line.split() if (len(splitlines) > 0): if (splitlines[0] == "gain"): r.add(int(splitlines[1]), int(splitlines[2]), float(splitlines[3].replace(",","."))) print "Source:", splitlines[1], "Destination:", splitlines[2], "Gain:", splitlines[3], "dBm"; ...
amsqr/k-Met
phonetic_algorithms.py
Python
gpl-3.0
21,699
0.018574
#coding= utf-8 class PhoneticAlgorithms(): ''' This script implements the Double Metaphone algorithm (c) 1998, 1999 by Lawrence Philips it was translated to Python from the C source written by Kevin Atkinson (http://aspell.net/metaphone/) By Andrew Collins - January 12, 2007 who claims no rights to...
d 'michael' if pos > first and st[pos:pos+4] == 'CHAE' : nxt = ('K', 'X', 2) elif pos == first and (st[pos+1:pos
+6] in ['HARAC', 'HARIS'] or \ st[pos+1:pos+4] in ["HOR", "HYM", "HIA", "HEM"]) and st[first:first+5] != 'CHORE' : nxt = ('K', 2) #germanic, greek, or otherwise 'ch' for 'kh' sound elif st[first:first+4] in ['VAN ', 'VON '] or st[fir...
great-expectations/great_expectations
tests/core/usage_statistics/util.py
Python
apache-2.0
849
0.002356
from typing import List from great_expectations.core.usage_statistics.usage_statistics import ( UsageStatsExce
ptionPrefix, ) def usage_stats_exceptions_exist(messages: List[str]) -> bool: """ Since the usage stats functionality does not raise exceptions but merely logs them, w
e need to check the logs for errors. """ return any( [ UsageStatsExceptionPrefix.EMIT_EXCEPTION.value in message for message in messages ] ) def usage_stats_invalid_messages_exist(messages: List[str]) -> bool: """ Since the usage stats functionality does no...
matthiask/django-cte-forest
cte_forest_test/tests.py
Python
bsd-3-clause
54,769
0.001278
# -*- coding: utf-8 -*- # # This document is free and open-source software, subject to the OSI-approved # BSD license below. # # Copyright (c) 2011 - 2013 Alexis Petrounias <www.petrounias.org>, # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted p...
bottom_node_2 = SimpleNode.objects.create(parent=middle_node) bottom_node_3 = SimpleNode.objects.create(parent=middle_node) self.assertEqual(root_node.children.all()[0].id, middle_node.id) self.assertEqual( [node.pk for node in middle_node.children.all()], [bottom_node...
hildren.all()), 0) def test_tree_structure_siblings(self): root_node = SimpleNode.objects.create() middle_node_1 = SimpleNode.o
ArcEye/machinekit-testing
tests/interp/subroutine-return/test-ui.py
Python
lgpl-2.1
5,619
0.00872
#!/usr/bin/env python import linuxcnc import hal import time import sys import os # this is how long we wait for linuxcnc to do our bidding timeout = 1.0 class LinuxcncError(Exception): pass # def __init__(self, value): # self
.value = value # def __str__(self): # return repr(self.value) class LinuxcncControl: ''' issue G-Code commands make
sure important modes are saved and restored mode is saved only once, and can be restored only once usage example: e = emc_control() e.prepare_for_mdi() any internal sub using e.g("G0.....") e.finish_mdi() ''' def __init__(self): self.c = linuxcnc....
tinloaf/home-assistant
homeassistant/components/notify/hangouts.py
Python
apache-2.0
2,112
0
""" Hangouts notification service. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/notify.hangouts/ """ import logging import voluptuous as vol from homeassistant.components.notify import (ATTR_TARGET, PLATFORM_SCHEMA, ...
E, ATTR_DATA) from homeassistant.components.hangouts.const \ import (DOMAIN, SERVICE_SEND_MESSAGE, TARGETS_SCHEMA, CONF_DEFAULT_CONVERSATIONS) _LOGGER = logging.getLogger(__name__) DEPENDENCIES = [DOMAIN] PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_DEFAULT_CONVERSATIONS): [TARGE...
F_DEFAULT_CONVERSATIONS)) class HangoutsNotificationService(BaseNotificationService): """Send Notifications to Hangouts conversations.""" def __init__(self, default_conversations): """Set up the notification service.""" self._default_conversations = default_conversations def send_message...
robertmattmueller/sdac-compiler
pddl/predicates.py
Python
gpl-3.0
503
0.003976
class Predicate(object): def __init__(self, name, arguments): self.name = name self.arguments = argum
ents self.value_mapping = dict() self.cost_str = "" def __str__(self): return "%s(%s)" % (self.name, ", ".join(map
(str, self.arguments))) def get_arity(self): return len(self.arguments) def get_arguments(self): return self.arguments def add_value(self, args, values): self.value_mapping[args] = values
Joel-U/sparkle
test/tests/unit/stim/types/test_stimuli_classes.py
Python
gpl-3.0
1,693
0.000591
from nose.tools import assert_equal import test.sample as sample from sparkle.stim.types import get_stimuli_models class TestStimuliTypes(): def setUp(self): stimuli_classes = get_stimuli_models() self.stimuli = [] for stimclass in stimuli_classes: if stimclass.protocol: ...
) assert msg == 0 def test_state_change(self): # test that the minimum states update mandatory_attrs = ['duration', 'intensity', 'risefall'] for stimulus in self.stimuli: state
= stimulus.stateDict() for attr in mandatory_attrs: assert attr in state state[attr] = 666 stimulus.loadState(state) assert_equal(state, stimulus.stateDict()) def test_serializable(self): for stimulus in self.stimuli: stream = ...
smaragden/chancery
chancery/catalog.py
Python
mit
628
0.001592
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'fredrik.brannbacka' from
user import User class Catalog(object): __domain = "" def __init__(self, domain=""): self.__domain = domain @property def domain(self): return self.__domain @domain.setter def domain(self, domain): self.__domain = domain def re
gister(self, name=u"John Doe"): user = User(name.decode('utf-8'), self.domain) return user def register_users(self, names=[]): for name in names: user = User(name.decode('utf-8'), self.domain) yield user
seankelly/buildbot
master/buildbot/db/dbconfig.py
Python
gpl-2.0
3,096
0
# This file is part of Buildbot. Buildbot 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, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without eve...
del(db) db.state = state.StateConnectorComponent(db) try: self.objectid = db.state.thdGetObjectId( db_engine, self.name, "DbConfig")['id'] except (ProgrammingError, OperationalError): # ProgrammingError: mysql&pg, OperationalError: sqlite # ass...
def get(self, name, default=state.StateConnectorComponent.Thunk): db = self.getDb() if db is not None: ret = db.state.thdGetState( db.pool.engine, self.objectid, name, default=default) db.pool.engine.close() else: if default is not state.State...
BlogomaticProject/Blogomatic
opt/blog-o-matic/usr/lib/python/Bio/NaiveBayes.py
Python
gpl-2.0
8,639
0.001968
# Copyright 2000 by Jeffrey Chang. All rights reserved. # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. """This provides code for a general Naive Bayes learner. Naive Bayes is a supervised classifi...
of data. p_conditional CLASS x DIM array of dicts of value -> P(value|class,dim) p_prior List of the prior probabilities for every class. dimensionality Dimensionality of the data. """ def __init__(self): self.classes = [] self.p_conditional = None self.p_prior = ...
lass|observation) for each class. nb is a NaiveBayes classifier that has been trained. observation is a list representing the observed data. scale is whether the probability should be scaled by P(observation). By default, no scaling is done. The return value is a dictionary where the keys is the cl...
futurulus/falcon
listview.py
Python
bsd-2-clause
7,474
0.00107
import os import wx import datetime import menu import schedule import edit import flight class FlightsPanel(wx.Panel): def __init__(self, *args, **kwargs): wx.Panel.__init__(self, *args, **kwargs) self.MainSizer = wx.BoxSizer(wx.VERTICAL) self.AddPanel = AddPanel(parent=self) s...
def open_action(): self.schedule = schedule.Schedule(filename) edit.try_flight(open_action, self.GetParent()) def OnSave(self): if self.schedule.filename is None: self.OnSaveAs() else: self.schedule.save() def OnSaveAs(self): ...
le(wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) if filename is not None: self.schedule.save(filename) def OnImport(self): filename = self.PromptForFile(wx.FD_OPEN) if filename is not None: def import_action(): self.schedule.load_file(filename, False) ...
vranki/pajabot
bot/gpio_pins.py
Python
gpl-3.0
477
0.006289
import RPi.GPIO as GPIO # RPi GPIO pin stuff (NOT USED ATM) class GpioPins(): def __init__(self): self.doorpin = 11 GPIO.s
etmode(GPIO.BOARD) GPIO.setup(self.doorpin, GPIO.IN) self.doorStatus = GPIO.input(self.doorpin) def pollPins(self) newDs = GPIO.input(self.doorpin)
if newDs is not self.doorStatus: self.doorStatus = newDs self.sayDoorStatus() def close(self): GPIO.cleanup()
Tomme/PAL
Listener.py
Python
gpl-3.0
3,589
0.015325
# PAL # Listener # Thomas Elvey # 0.2 import math, audioop, time, wave, os from collections import deque from pocketsphinx import * import pyaudio from VoiceDecoder import VoiceDecoder class Listener(): def __init__(self): print "Listener Created" # INIT FUNCTIONS # self.setupMic...
es/PALActivate.dic', '/home/pi/PAL/resources/PALActivate.lm', '/home/pi/PAL/resources/PALActivateKeyphrase.list') def setupMic(self, samples = 50): # Setup microphone, background noise adjustments etc. print "Getting mic values..." ...
= pyaudio.PyAudio() stream = p.open(format = pyaudio.paInt16, channels = 1, rate = 16000, input = True, frames_per_buffer = 1024) values = [math.sqrt(abs(audioop.avg(s...
alphagov/notifications-api
app/v2/inbound_sms/get_inbound_sms.py
Python
mit
1,247
0.000802
from flask import current_app, jsonify, request, url_for from app import authenticated_service from app.dao import inbound_sms_dao from app.schema_validation import validate from app.v2.inbound_sms import v2_inbound_sms_blueprint from app.v2.inbound_sms.inbound_sms_schemas import get_inbound_sms_request @v2_inbound_...
0 def _build_links(inbound_sms_list): _links = { 'current': url_for( "v2_inbound_sms.get_inbound_sms", _external=True, ), } if inbound_sms_list: _links['next'] = url_for( "v2_inbound_sms.get_inbound_sms",
older_than=inbound_sms_list[-1].id, _external=True, ) return _links
sigmunau/nav
python/nav/web/portadmin/views.py
Python
gpl-2.0
25,624
0.000078
# # Copyright (C) 2010 Norwegian University of Science and Technology # Copyright (C) 2011-2015 UNINETT AS # # This file is part of Network Administration Visualized (NAV). # # NAV is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License version 2 as published by # ...
r_on_netbox, find_allowed_vlans_for_user, filter_vlans, fetch_voice_vlans, should_check_access_rights, mark_detained_interfaces, read_c...
add_dot1x_info, is_restart_interface_enabled, is_write_mem_enabled) from nav.Snmp.errors import SnmpError, TimeOutException from nav.portadmin.snmputils import SNMPFactory, SNMPHandler from .forms import SearchForm _logger = logging.ge...
TakeshiTseng/SDN-Work
MultiControl/ms/MasterApp.py
Python
mit
3,607
0.001941
''' Master App, testing for master con
troller ''' # -*- encoding: utf-8 -*- # file: MasterApp.py from ryu.base import app_manager from ryu.controller import ofp_event from ryu.controller.handler import MAIN_DISPATCHER from ryu.controller.handler import HANDSHAKE_DISPATCHER from ryu.controller.handler import CONFIG_DISPATCHER from ryu.controller.handler im...
rt time class MasterApp(app_manager.RyuApp): OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION] def __init__(self, *args, **kwargs): super(MasterApp, self).__init__(*args, **kwargs) print 'prepare server' master_server = MasterServer(7999) print 'starting server' master_server.st...
cgstudiomap/cgstudiomap
main/parts/geospatial/geoengine_partner/__openerp__.py
Python
agpl-3.0
1,309
0
# -*- coding: utf-8 -*- ############################################################################## # # Author: Nicolas Bessi # Copyright 2011-2012 Camptocamp SA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # ...
# You should have received a copy of the GNU Affero General Public License #
along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## {'name': 'Geospatial support of partners', 'version': '0.1', 'category': 'GeoBI', 'author': "Camptocamp,Odoo Community Association (OCA)", 'license': 'AGPL-3', 'w...
senttech/Cura
cura/Settings/__init__.py
Python
agpl-3.0
671
0.002981
# Copyright (c) 2016 Ultimaker B.V. # Cura is released under the terms of the AGPLv3 or higher. from .MaterialSettingsVisibilityHandler import MaterialSettingsVisibilityHandler from .ContainerManager import ContainerManager from .ContainerSettingsModel import ContainerSettingsModel from .CuraContainerRegistry import C...
l import ExtrudersModel from .MachineManager import MachineManager from .M
aterialSettingsVisibilityHandler import MaterialSettingsVisibilityHandler from .SettingOverrideDecorator import SettingOverrideDecorator from .QualitySettingsModel import QualitySettingsModel
shownotes/snotes20-restapi
snotes20/views/EditorViewSet.py
Python
agpl-3.0
444
0.002252
from django.conf import settings from rest_framework import viewsets from rest_framework.response import Response import snotes20.models as models class EditorViewSet(viewsets.ViewS
et): def list(self, request): return Response([ { 'short': short, 'long': long, 'url': settings.EDITORS[short]['userurl'] } for short, long in models.EDITOR_CHOICES ])
dpgaspar/Flask-AppBuilder
examples/enums/app/views.py
Python
bsd-3-clause
3,436
0.000873
import calendar from flask_appbuilder import ModelView from flask_appbuilder.charts.views import GroupByChartView from flask_appbuilder.models.group import aggregate_count from flask_appbuilder.models.sqla.interface import SQLAInterface from . import appbuilder, db from .models import Contact, ContactGroup class C...
], "expanded
": False, }, ), ] class GroupModelView(ModelView): datamodel = SQLAInterface(ContactGroup) related_views = [ContactModelView] class ContactChartView(GroupByChartView): datamodel = SQLAInterface(Contact) chart_title = "Grouped contacts" label_columns = ContactModelView.lab...
maremaremare/elisa_v
elisa_v/content/migrations/0001_initial.py
Python
mit
2,764
0.008321
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Page' db.create_table(u'content_page', ( (u'id', self.gf('django.db.models.field...
ue=True, max_length=50)), ('text', self.gf('django.db.models.fields.TextField')()), (u'lft', self.gf('django.db.models.fields.PositiveIntegerField')(db_index=True)), (u'rght', self.gf('django.db.models.fields.PositiveIntegerField')(db_index=True)), (u'tree_id', self.gf('d...
_index=True)), (u'level', self.gf('django.db.models.fields.PositiveIntegerField')(db_index=True)), )) db.send_create_signal(u'content', ['Page']) def backwards(self, orm): # Deleting model 'Page' db.delete_table(u'content_page') models = { u'content.page':...
vmanoria/bluemix-hue-filebrowser
hue-3.8.1-bluemix/apps/security/src/security/api/hive.py
Python
gpl-2.0
12,751
0.008391
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
f uri: if uri.startswith('hdfs:///'): uri = uri.replace('hdfs://', get_defaultfs()) e
lif uri.startswith('/'): uri = get_defaultfs() + uri return uri def _drop_sentry_privilege(user, role, authorizable): return get_api(user).alter_sentry_role_revoke_privilege(role['name'], _to_sentry_privilege(authorizable)) def create_role(request): result = {'status': -1, 'message': 'Error'} try: ...
narthollis/eve-shoppinglist
shoppinglist/dns/tsig.py
Python
mit
7,702
0.002337
# Copyright (C) 2001-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "...
Returns the wire format string and the hash module to use for the specified TSIG algorithm @rtype: (string, hash constructor) @raises NotImplementedError: I{algorithm} is not supported """ global _hashes if _hashes is None: _setup_hashes() if isinstance(algorithm, (str, unicode)):...
2): raise NotImplementedError("TSIG algorithm " + str(algorithm) + " requires Python 2.5.2 or later") try: return (algorithm.to_digestable(), _hashes[algorithm]) except KeyError: raise NotImplementedError("TSIG algorithm " + str(algorithm) + ...
zenn1989/scoria-interlude
L2Jscoria-Game/data/scripts/quests/75_SagaOfTheTitan/__init__.py
Python
gpl-3.0
2,327
0.033949
# Made by Emperorc import sys from com.l2scoria.gameserver.model.quest import State from com.l2scoria.gameserver.model.quest import QuestState from quests.SagasSuperclass import Quest as JQuest qn = "75_SagaOfTheTitan" qnu = 75 qna = "Saga of the Titan" class Quest (JQuest) : def __init__(self,id,name,descr): ...
","Now, my soul freed from the shackles of the millennium, Halixia, to the back side I come ...", "Why do you interfere others' battles?","This is a waste of time.. Say goodbye...!","...That is the enemy", "...Goodness! PLAYERNAME you are still looking?","PLAYERNAME ... Not just to w...
nel involved in the fighting are eligible to share in the victory.", "Your sword is not an ornament. Don't you think, PLAYERNAME?","Goodness! I no longer sense a battle there now.","let...","Only engaged in the battle to bar their choice. Perhaps you should regret.", "The human natio...
linea-it/masterlist
masterlist/candidates/admin.py
Python
mit
95
0
fro
m django.contrib import admin from .models import Candidate admin.site.register(Candidate)
flaviogrossi/billiard
billiard/queues.py
Python
bsd-3-clause
12,304
0.000081
# # Module implementing queues # # multiprocessing/queues.py # # Copyright (c) 2006-2008, R Oudkerk # Licensed to PSF under a Contributor Agreement. # from __future__ import absolute_import import sys import os import threading import collections import weakref import errno from . import connection from . import cont...
if wacquire is None:
send_bytes(obj) else: wacquire() try: send_bytes(obj) finally: wrelease() except IndexError: pass e...
intagger/paraproxio
paraproxio.py
Python
gpl-3.0
54,244
0.00236
#!/usr/bin/env python """ Paraproxio is an HTTP proxy with a parallel downloading of big files. """ # Copyright (C) 2016 Alexander Logger <intagger@gmail.com> # # 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 Softwa...
bytes_ranges.append(bytes_range) last_range_offset = last_range_idx * range_size bytes_ranges.append((last_range_offset, last_range_o
ffset + last_range_size - 1)) return bytes_ranges def get_bytes_ranges_by_part_size(length: int, part_size: int) -> List[Tuple[int, int]]: bytes_ranges = [] for offset in range(0, length, part_size): left = length - offset if left < part_size: part_size = left bytes_ran...
havardgulldahl/jottalib
src/jottalib/__init__.py
Python
gpl-3.0
20
0.05
__ve
rsio
n__='0.5.1'
koll00/Gui_SM
SMlib/utils/encoding.py
Python
mit
7,022
0.004416
# -*- coding: utf-8 -*- # # Copyright © 2009-2010 Pierre Raybaut # Licensed under the terms of the MIT License # (see spyderlib/__init__.py for details) """ Text encoding utilities, text file I/O Functions 'get_coding', 'decode', 'encode' and 'to_unicode' come from Eric4 source code (Utilities/__init___.py)...
name, encoding, mode) def read(filename, encoding='utf-8'): """ Read text from file ('filename') Return text and encoding """ text, encoding = decode( file(filename, 'rb').read() ) return text, encoding def readlines(filename, encoding='utf-8'): """ Read lines from file ('f...
ep), encoding
luzheqi1987/nova-annotation
nova/tests/unit/integrated/v3/test_user_data.py
Python
apache-2.0
1,352
0
# Copyright 2012 Nebula, Inc. # Copyright 2013 IBM Corp. # # 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...
e specific language governing permissions and limitations # under the License. import base64 from nova.tests.unit.image import fake from nova.tests.unit.integrated.v3 import api_sample_base class UserDataJsonTest(api_sample_base.ApiSampleTestBaseV3): extension_name = "os-user-data" def test_user_data_po...
= { 'image_id': fake.get_valid_image_id(), 'host': self._get_host(), 'user_data': user_data } response = self._do_post('servers', 'userdata-post-req', subs) subs.update(self._get_regexes()) self._verify_response('userdata-post-resp', subs, respons...
mammique/django
tests/regressiontests/admin_inlines/tests.py
Python
bsd-3-clause
32,499
0.004185
from __future__ import absolute_import, unicode_literals from django.contrib.admin.tests import AdminSeleniumWebDriverTestCase from django.contrib.admin.helpers import InlineAdminForm from django.contrib.auth.models import User, Permission from django.contrib.contenttypes.models import ContentType from django.test imp...
, data) # Here colspan is "4": two fields (title1 and title2), one hidden field and the delete checkbock. self.assertContains(response, '<tr><td colspan="4"><ul class="errorlist"><li>The two titles must be the same</li></ul></td></tr>') def test_no_parent_callable_lookup(self): """Admin inl...
e parent ModelAdmin callable""" # Identically named callable isn't present in the parent ModelAdmin, # rendering of the add view shouldn't explode response = self.client.get('/admin/admin_inlines/novel/add/') self.assertEqual(response.status_code, 200) # View should have the chil...
polyaxon/polyaxon
core/polyaxon/plugins/sentry.py
Python
apache-2.0
1,564
0.000639
#!/usr/bin/python # # Copyright 2018-2021 Polyaxon, Inc. # # 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 ...
env_vars.keys import POLYAXON_KEYS_SERVICE cli_config = settings.CLI_CONFIG options = options or {} environment = options.get("environment") dsn = options.get("dsn") sample_rate = options.get("sample_rate", 0) if cli_config and cli_config.log_handler and cli_config.log_han
dler.decoded_dsn: dsn = dsn or cli_config.log_handler.decoded_dsn environment = environment or cli_config.log_handler.environment if dsn: import sentry_sdk sentry_sdk.init( dsn=dsn, release=pkg.VERSION, environment=environment, server...
ikasumi/chainer
cupy/cindexer.py
Python
mit
754
0
import ctypes import six from cupy import carray from cupy import internal def _make_cindexer(n): class CIndexer(ctypes.Structure): _fields_ = [('size', ctypes.c_int), ('shape', ctypes.c_int * n
), ('index', ctypes.c_int * n)] return CIndexer _cindexers = [_make_cindexer(i) for i in six.moves.range(carray.MAX_NDIM)] def to_cindexer(size, shape): return _cindexers[len(shape)](size, shape, (0,) * len(shape)) c
lass Indexer(object): def __init__(self, shape): self.shape = shape self.size = internal.prod(shape) @property def ndim(self): return len(self.shape) @property def ctypes(self): return to_cindexer(self.size, self.shape)
thodoris/djangoPharma
djangoPharma/drugs/restService.py
Python
apache-2.0
767
0.001304
import json from urllib.request import urlopen from django.conf import settings # get rest endpoint from settings rest_api = settings.DJANGOPHARMA_REST_URL # get all data from rest service def get_drugs(): json_data = json.load(urlopen(rest_api)) return json_data # returns a drug dict (drug id , drug , name...
api + '/' + drug_id re
st_result = urlopen(urlpath) resp = json.load(rest_result) return resp
parenthetical-e/pyentropy
setup.py
Python
gpl-2.0
2,730
0.011355
import sys, os import pyentropy # BEFORE importing disutils, remove MANIFEST. distutils doesn't properly # update it when the contents of directories change. if os.path.exists('MANIFEST'): os.remove('MANIFEST') from distutils.core import setup from distutils.extension import Extension from distutils.command.build_ext...
gsl_min_version=(1,), python_min_version=(2,5) ) exts.append(statk_wrap) except: pass class build_ext_allow_fail( build_ext ): # This class allows C extension building to fail. # Taken from visionegg (LGPL) # http://g...
xt.build_extension(self, ext) except CCompilerError, x: ext_failed_warning(ext.name) setup(name='pyentropy', version=pyentropy.__version__, description='Entropy and Information Theoretic Estimates', author=pyentropy.__author__, author_email='pyentropy@robince.net', ur...
mtth/hdfs
test/dat/client_template.py
Python
mit
302
0.006623
#!/usr/bin/env python # encoding: utf-8 """A template for generating new clients. This is used to test autoloading from `CliConfig` (see `test/test_main.py`). """ from hdfs import Client class $class_name(C
lient): one = 1 def __init__(self, url): super($class_na
me, self).__init__(url)
multmeio/django-hstore-flattenfields
tests/app/models.py
Python
bsd-3-clause
2,676
0.002616
from django.db import models from hstore_flattenfields.db.base import * from hstore_flattenfields.models import * class SomethingType(DynamicFieldGroup): pass class AuthorType(DynamicFieldGroup): pass class Something(HStoreGroupedModel): name = models.CharField(max_length=32) # relations some...
ield = 'something_group' class Author(HStoreM2MGroupedModel): # author_name = models.CharField(max_length=50) # relations author_groups = models.ManyToManyField(AuthorType, null=True, blank=True, related_name='authors', verbose_name=u'Group') class Meta: # hstore hstore_related_field ...
super(Author, self).__str__() class Illustrator(Author): class Meta: # hstore hstore_related_field = 'author_groups' def __str__(self): if hasattr(self, 'illustrator_name'): return "%s" % self.illustrator_name else: return super(Author, self).__...
coodoing/udacity-searchengine
course7_Star3.py
Python
apache-2.0
6,721
0.01473
#Multi-word Queries #Triple Gold Star #For this question, your goal is to modify the search engine to be able to #handle multi-word queries. To do this, we need to make two main changes: # 1. Modify the index to keep track of not only the URL, but the position # within that page where a word appears. # 2....
links to] index = {} while tocraw
l: page = tocrawl.pop() if page not in crawled: content = get_page(page) add_page_to_index(index, page, content) outlinks = get_all_links(content) graph[page] = outlinks union(tocrawl, outlinks) crawled.append(page) return inde...
pierotofy/WebODM
plugins/openaerialmap/plugin.py
Python
mpl-2.0
2,293
0.001744
from django.contrib import messages from django.shortcuts import render from app.plugins import PluginBase, Menu, MountPoint from django.contrib.auth.decorators import login_required from django import forms from plugins.openaerialmap.api import Info, Share class TokenForm(forms.Form): token = forms.CharField(l...
ds.set_string('token', form.cleaned_data['token']) messages.success(request, 'Token updated.') form = TokenForm(initial={'token': ds.get_string('token', default="")}) return render(request, self.template_path("app.html"), { 'title': 'OpenAe...
}) return home
zozo123/buildbot
master/buildbot/test/unit/test_util_netstrings.py
Python
gpl-3.0
1,718
0
# This file is part of Buildbot. Buildbot 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, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WA
RRANT
Y; 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, write to the Free Software Foundation, Inc., 51 # Franklin Stree...
csdms/standard_names
docs/source/conf.py
Python
mit
9,546
0.005866
# -*- coding: utf-8 -*- # # standard_names documentation build configuration file, created by # sphinx-quickstart on Fri Jul 22 11:31:51 2016. # # 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...
a' uses this config value #html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. #html_search_scorer = 'scorer.js' # Output file base name for HTML help b
uilder. htmlhelp_basename = 'standard_namesdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTe...
mandeeps708/django-app
rollno/migrations/0001_initial.py
Python
gpl-2.0
689
0.001451
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='roll', fields=[ ('id', models.AutoField(verbose...
teTimeField(auto_now_add=True)), ('updated', models.DateTimeField(auto_now=True)), ], options={
}, bases=(models.Model,), ), ]
the-blue-alliance/the-blue-alliance
old_py2/datafeeds/parsers/tba/tba_videos_parser.py
Python
mit
860
0
import logging import re from datafeeds.parser_base import ParserBase class TbaVideosParser(ParserBase): """ Facilitates building TBAVideos store from TBA. """ @classmethod def parse(self, html): """ Parse the directory listing on TBA to extract relevant TBAVideo inf
ormation. Returns a list of TBAVideos """ from bs4 import BeautifulSoup soup = BeautifulSoup(html) videos = dict() for a in soup.findAll("a", href=True): parts = a["href"].split(".") if len(parts) == 2: (key, filetype) = parts ...
videos[key].append(filetype) else: logging.info("Malformed video filename: " + a["href"]) continue return videos, False
kavardak/suds
tests/axis2.py
Python
lgpl-3.0
4,781
0.003347
# This program is free software; you can redistribute it and/or modify # it under the terms of the (LGPL) GNU Lesser 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 ...
# print 'person=\n%s' % person # # add the person (using the webservice) # print 'addPersion()' result = client.service.addPerson(person) print '\nreply(\n%s\n)\n' % result.encode('utf-8') # # create a new name object used to update the person # newname = client.factory.create('ns2:Name') newname.first = 'Todd' newna...
esult = client.service.updatePerson(person, newname) print '\nreply(\n%s\n)\n' % str(result) result = client.service.updatePerson(person, None) print '\nreply(\n%s\n)\n' % str(result) # # invoke the echo service # print 'echo()' client.service.echo(None) result = client.service.echo('this is cool') print '\nreply( %s...
patrickhoefler/secta
app/index_tags.py
Python
mit
1,940
0
#!/usr/bin/env python3 import codecs from collections import defaultdict import errno import json import os def tree(): """ http://recursive-labs.com/blog/2012/05/31/one-line-python-tree-explained/ """ return defaultdict(tree) def index_tags(): """ Iterate through all locally saved JSON fil...
dump(index, output_file, ensure_ascii=False) # Some status information for the console print('Successful
ly created the tag index.') # If the script is called directly, execute the index_tags() function if __name__ == '__main__': index_tags()
kobiluria/openbudgets
openbudgets/apps/contexts/views/api.py
Python
bsd-3-clause
3,078
0.001624
import datetime from rest_framework.generics import ListAPIView, RetrieveAPIView from openbudgets.apps.contexts import serializers from openbudgets.apps.contexts import models class ContextList(ListAPIView): """Called via an API endpoint that represents a list of context objects.""" model = models.Context ...
. if periods: periods = [datetime.date(int(p), 1, 1) for p in periods.split(',')] queryset = queryset.filter(period_start__in=periods) return queryset class ContextDetail(Retrie
veAPIView): """Called via an API endpoint that represents a single context object.""" model = models.Context queryset = model.objects.related_map() serializer_class = serializers.ContextBaseSerializer class CoefficientList(ListAPIView): """Called via an API endpoint that represents a list of coef...
Jchase2/py-pubsubhubbub-subscriber
server.py
Python
gpl-2.0
347
0.008646
import http.server import socketserver PORT = 8000 handler = http.server.CGIHTTPRequestHandler handler.cgi_directories = ['/webhook'] # or wherever you store
the script... cgi_bin is default without this server_address = ("", PORT) httpd = http.server.HTTPSer
ver(server_address, handler) print("serving at port", PORT) httpd.serve_forever()
rouault/mapnik
tests/python_tests/compositing_test.py
Python
lgpl-2.1
11,101
0.014143
#encoding: utf8 from nose.tools import eq_ import os from utilities import execution_path, run_all from utilities import get_unique_colors, pixel2channels, side_by_side_image import mapnik def setup(): # All of the paths used are relative, if we run the tests # from another directory we need to chdir() os...
rt/b.png') #b.save('/tmp/mapnik-comp-op-test-original-mask.png') #eq_(b.tostring('png32'),expected_b.tostring('png32'), '/tmp/mapnik-comp-op-test-original-mask.png is no longer equivalent to original mask: ./images/support/b.png') def test_pre_multiply_status(): b = m
apnik.Image.open('./images/support/b.png') # not premultiplied yet, should appear that way result = validate_pixels_are_not_premultiplied(b) eq_(result,True) # not yet premultiplied therefore should return false result = validate_pixels_are_premultiplied(b) eq_(result[0],False) # now actuall...