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
mazaclub/mazabot-core
plugins/ChannelStats/test.py
Python
bsd-3-clause
4,460
0.000897
### # Copyright (c) 2002-2004, Jeremiah Fincher # Copyright (c) 2010, James Vega # 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 copyri...
al(m1.args[1], m2.args[1]) finally:
conf.supybot.plugins.ChannelStats.selfStats.setValue(True) def testNoKeyErrorStats(self): self.assertNotRegexp('stats sweede', 'KeyError') def testRank(self): self.assertError('channelstats stats %s' % self.irc.nick) self.assertNotError('channelstats stats %s' % self.irc.nick) ...
pytorch/fairseq
fairseq/data/encoders/nltk_tokenizer.py
Python
mit
755
0
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in
the root directory of this source tree. from fairseq.data.e
ncoders import register_tokenizer from fairseq.dataclass import FairseqDataclass @register_tokenizer("nltk", dataclass=FairseqDataclass) class NLTKTokenizer(object): def __init__(self, *unused): try: from nltk.tokenize import word_tokenize self.word_tokenize = word_tokenize ...
Vanuan/gpx_to_road_map
biagoni2012/gpsmatcher.py
Python
apache-2.0
2,740
0.016788
from viterbi import Viterbi from rtree import Rtree from spatialfunclib import * class GPSMatcher: def __init__(self, hmm, emission_probability, constraint_length=10, MAX_DIST=500, priors=None, smallV=0.00000000001): # initialize spatial index self.previous_obs = None if pr...
lat-MAX_DIST/METERS_PER_DEGREE_LATITUDE, lon+MAX_DIST/METERS_PER_DEGREE_LONGITUDE, lat+MAX_DIST/METERS_PER_DEGREE_LATITUDE)) candidates = [id_to_state[id] ...
constraint_length=constraint_length, priors=priors, candidate_states=candidate_states, smallV=smallV) def step(self,obs,V,p): if self.previous_obs != None: for int_obs in self.in...
weaver-viii/h2o-3
h2o-py/tests/testdir_algos/naivebayes/pyunit_prostateNB.py
Python
apache-2.0
836
0.008373
import sys sys.path.insert(1, "../../../") import h2o def nb_prostate(ip, port): print "Importing prostate.csv data..." prostate = h2o.upload_file(h2o.locate("smalldata/logreg/prostate.csv")) print "Converting CAPSULE, RACE, DCAPS, and DPROS to categorical" prostate['CAPSULE'] = prostate['CAPSUL...
prostate['DCAPS'] = prostate['DCAPS'].asfactor() prostate['DPROS'] = prostate['DPROS'].asfactor() print "Compare with Naive Bayes when x = 3:9, y = 2" prostate_nb = h2o.naive_bayes(x=prostate[2:9], y=prostate[1], l
aplace = 0) prostate_nb.show() print "Predict on training data" prostate_pred = prostate_nb.predict(prostate) prostate_pred.head() if __name__ == "__main__": h2o.run_test(sys.argv, nb_prostate)
UTAlan/ginniBeam.net
gin/contact/models.py
Python
gpl-2.0
189
0.015873
from django import forms class ContactForm(forms.Form):
name = forms.CharField(max_length=100) email = forms.EmailField() message = forms.CharField(widget=forms.Textarea
)
arth-co/shoop
shoop_tests/utils/test_analog.py
Python
agpl-3.0
837
0
# -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserve
d. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from django.db import models from shoop.utils.analog import define_log_model, BaseLogEntry class FakeModel(models.Model): pass def test_analog(): FakeModelLogEntry = define_log...
ogEntry.__module__ == FakeModel.__module__ assert FakeModelLogEntry._meta.get_field("target").rel.to is FakeModel assert FakeModel.log_entries.related.model is FakeModel assert FakeModel.log_entries.related.related_model is FakeModelLogEntry assert issubclass(FakeModelLogEntry, BaseLogEntry) assert ...
benjamindeleener/scad
scripts/sct_orientation.py
Python
mit
11,010
0.003724
#!/usr/bin/env python ######################################################################################### # # Get or set orientation of nifti 3d or 4d data. # # --------------------------------------------------------------------------------------- # Copyright (c) 2014 Polytechn
ique Montreal <www.neuro.polymtl.ca> # Authors: Julien Cohen-Adad # Modified: 2014-10-18 # # About the license: see the file LICENSE.TXT ######################################################################################### import sys import os import getopt import commands import sct_utils as sct import time # ...
_init__(self): self.debug = 0 self.fname_data = '' self.fname_out = '' self.orientation = '' self.list_of_correct_orientation = 'RIP LIP RSP LSP RIA LIA RSA LSA IRP ILP SRP SLP IRA ILA SRA SLA RPI LPI RAI LAI RPS LPS RAS LAS PRI PLI ARI ALI PRS PLS ARS ALS IPR SPR IAR SAR IPL SPL...
AndreyBalabanov/python_training_mantisBT
fixture/project.py
Python
apache-2.0
1,944
0.002572
from model.project import Project class ProjectHelper: def __init__(self, app): self.app = app self.project_list_cache = None def open_page_manage_projects(self): wd = self.app.wd wd.find_element_by_link_text("Manage").click() wd.find_element_by_link_text("Manage Proj...
wd.find_element_by_css_selector("form > input.button").click() wd.find_element_by_css_selector("input.button").click() def get_project_list(self): wd = self.app.wd self.open_page_manage_projects() projects_list = wd.find_elements_by_xpath("//table[3]/tbody/tr")[2:] ...
self.open_page_manage_projects() return len(wd.find_elements_by_css_selector(".fa.fa-check.fa-lg")) project_cache = None
opensvn/test
src/study/python/backward.py
Python
gpl-2.0
151
0
#!/usr/bin/env python def backword(s):
length = len(s) i = -1 t = s while i >= -length: t += s
[i] i -= 1 return t
qilicun/python
python2/PyMOTW-1.132/PyMOTW/shlex/shlex_source.py
Python
gpl-3.0
1,405
0.000712
#!/usr/bin/env python # # Copyright 2007 Doug Hellmann. # # # All Rights Reserved #
# Permission to use, copy, modify, and distribute this software and # its documentation for any purpose and without
fee is hereby # granted, provided that the above copyright notice appear in all # copies and that both that copyright notice and this permission # notice appear in supporting documentation, and that the name of Doug # Hellmann not be used in advertising or publicity pertaining to # distribution of the software without ...
openplans/community-almanac
communityalmanac/tests/functional/test_users.py
Python
agpl-3.0
208
0.004808
from communityalmanac.
tests import * class TestUsersController(TestController): def test_index(self): response = self.app.get(url(controller='users', action='index')) # Test response...
Yukarumya/Yukarum-Redfoxes
testing/web-platform/tests/tools/pytest/testing/cx_freeze/tox_run.py
Python
mpl-2.0
464
0.002155
"""
Called by tox.ini: uses the generated executable to run the tests in
./tests/ directory. .. note:: somehow calling "build/runtests_script" directly from tox doesn't seem to work (at least on Windows). """ if __name__ == '__main__': import os import sys executable = os.path.join(os.getcwd(), 'build', 'runtests_script') if sys.platform.startswith('win'): ...
thammegowda/algos
usc-csci-ml/hw5/src/CSCI567_hw5_fall16.py
Python
apache-2.0
9,745
0.003797
# coding: utf-8 ''' Name : ThammeGowda Narayanaswamy USCID: 2074669439 ''' import math from scipy.stats import multivariate_normal import numpy as np from matplotlib import pyplot as plt import matplotlib.patches as mpatches import scipy as sp from scipy import spatial from scipy import stats from pprint import pprin...
his kernel outputs lesser distance for the points that are from circumference :params: x1 - first point x2 -
second point center - center of circle(default = origin (0,0,...)) ''' if center is None: center = np.zeros(len(x1)) dist1 = distance(x1, center) dist2 = distance(x2, center) return 1.0 - min(dist1, dist2) / max(dist1, dist2) clusters = KernelKMeans().cluster(circles, 2, circular_ke...
ProfessorX/Config
.PyCharm30/system/python_stubs/-1247971765/PyQt4/QtGui/QApplication.py
Python
gpl-2.0
14,490
0.009455
# encoding: utf-8 # module PyQt4.QtGui # from /usr/lib/python3/dist-packages/PyQt4/QtGui.cpython-34m-x86_64-linux-gnu.so # by generator 1.135 # no doc # imports import PyQt4.QtCore as __PyQt4_QtCore class QApplication(__PyQt4_QtCore.QCoreApplication): """ QApplication(list-of-str) QApplication(list-of-st...
unknown """ QApplication.lastWindowClosed [sign
al] """ pass def layoutDirection(self): # real signature unknown; restored from __doc__ """ QApplication.layoutDirection() -> Qt.LayoutDirection """ pass def mouseButtons(self): # real signature unknown; restored from __doc__ """ QApplication.mouseButtons() -> Qt.MouseButtons "...
sirk390/coinpy
coinpy-lib/src/coinpy/lib/blockchain/bsddb/serialization/s11n_disktxpos.py
Python
lgpl-3.0
804
0.002488
from coinpy.lib.serializati
on.common.field import Field from coinpy.lib.serialization.common.structure import Structure from coinpy.lib.blockchain.bsddb.objects.disktxpos import DiskTxPos class DiskTxPosSerializer(): DISKTXPOS = Structure([Field("<I", "file"), Field("<I", "blockpos"), Fi...
return (self.DISKTXPOS.serialize([disktxpos_obj.file, disktxpos_obj.blockpos, disktxpos_obj.txpos])) def deserialize(self, data, cursor=0): (file, nblockpos, ntxpos), cursor = self.DISKTXPOS.deserialize(data, cursor) ...
steko/totalopenstation
docs/conf.py
Python
gpl-3.0
9,411
0.006057
# -*- coding: utf-8 -*- # # Total Open Station documentation build configuration file, created by # sphinx-quickstart on Sat Feb 28 23:03:04 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 ...
6x16 or 32x32 # pixels large. html_favicon = "tops.ico" # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] #...
the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. html_use_smartypants =...
Ruide/angr-dev
simuvex/simuvex/plugins/cgc.py
Python
bsd-2-clause
86
0.011628
print '... Importing s
imuvex/plugins/cgc.py ...' from angr.s
tate_plugins.cgc import *
lnls-sirius/dev-packages
siriuspy/siriuspy/clientconfigdb/types/si_tunecorr_params.py
Python
gpl-3.0
1,290
0
"""SI tune correction configuration. Values in _template_dict are arbitrary. They are used just to compare with corresponding values when a new configuration is tried to be inserted i
n the servconf database. """ from copy import deepcopy as _dcopy def get_dict(): """Return configuration t
ype dictionary.""" module_name = __name__.split('.')[-1] _dict = { 'config_type_name': module_name, 'value': _dcopy(_template_dict) } return _dict # Tune Correction Parameters for Storage Ring # # | DeltaTuneX | | m00 m01...m07 | | KL SI QFA | # | | = | ...
TheQtCompany/git-repo
subcmds/diff.py
Python
apache-2.0
1,328
0.004518
# -*- coding:utf-8 -*- # # Copyright (C) 2008 The Android Open Source Project # # 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 co
py 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 "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. from command import PagedCommand class Diff(PagedCommand): common = True helpSummary = "Show changes between commit and workin...
OCA/stock-logistics-warehouse
stock_request_picking_type/__init__.py
Python
agpl-3.0
133
0
# Copyright 2019 Open Source Integrators # License LGPL-3.0 or later (https://www.gnu.org/licenses/l
gpl.html). fr
om . import models
enolfc/keystone-voms
tests/test_middleware_voms_authn.py
Python
apache-2.0
23,887
0
# Copyright 2012 Spanish National Research Council # # 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...
"0"] = chain return req class MiddlewareVomsAuthn(tests.TestCase): def setUp(self): super(MiddlewareVomsAuthn, self).setUp() self.config([tests.dirs.etc('keystone.conf.sample'), tests.dirs.tests_conf('keystone_voms.conf')]) self.useFixture(data...
ANTS[0]['name'] CONF.voms.voms_policy = tests.dirs.tests_conf("voms.json") def test_middleware_proxy_unscoped(self): """Verify unscoped request.""" req = prepare_request(get_auth_body(), valid_cert, valid_cert_chain) aux = ...
chewse/djangorestframework-signed-permissions
signedpermissions/__init__.py
Python
mit
174
0
# -*- coding: utf-8 -*- from .permissions import SignedPermission #
noqa from .signing import sign_filter_permissions # noqa from .views import SignedViewSetMixin #
noqa
andymeneely/attack-surface-metrics
attacksurfacemeter/loaders/cflow_line_parser.py
Python
mit
1,154
0
__author__ = 'kevin' import re from attacksurfacemeter.loaders.base_line_parser import BaseLineParser class CflowLineParser(BaseLineParser): """""" _instance = None @staticmethod def get_instance(cflow_line=None): if CflowLineParser._instance is None: CflowLineParser._instance =...
elf._level = 0 def load(self, cflow_line): self.__init__() split_line = cflow_line.split(CflowLineParser.indent
) function_info = split_line[-1].strip() self._level = len(split_line) - 1 function_name = re.search(r"(\w+\(\))", function_info).group(0) self._function_name = function_name[:function_name.index('(')] match = re.search(r"(?:at\s)(\..*)(?::\d+>)", function_info) if matc...
tks0123456789/kaggle-Otto
exp_XGB_CF_tc_mb_mf_ntree.py
Python
mit
6,574
0.009735
""" Experiment for XGBoost + CF Aim: To find the best tc(max_depth), mb(min_child_weight), mf(colsample_bytree * 93), ntree tc: [13, 15, 17] mb: [5, 7, 9] mf: [40, 45, 50, 55, 60] ntree: [160, 180, 200, 220, 240, 260, 280, 300, 320, 340, 360] Averaging 20 models Summary Best loss ...
mb = params['mb'] mf = params['mf'] cs = float(mf) / X.shape[1] print tc, mb, mf
predAll = [np.zeros(y_valid.shape) for k in range(nt_len)] for i in range(nIter): seed = 112233 + i param = {'bst:max_depth':tc, 'bst:eta':sh,'objective':'multi:softprob','num_class':9, 'min_child_weight':mb, 'subsample':bf, 'colsample_bytree':cs, 'silent':1, 'nthre...
mjenrungrot/competitive_programming
Facebook Hackercup/2020/Round 1/A1.py
Python
mit
3,016
0.001658
import math from collections import deque def run(): N, K, W = list(map(int, input().split())) Ls = list(map(int, input().split())) A_L, B_L, C_L, D_L = list(map(int, input().split())) Hs = list(map(int, input().split())) A_H, B_H, C_H, D_H = list(map(int, input().split())) for i in range(K+1, ...
ueue[0][0]) height_queue.popleft() height_queue_len -= 1 height_queue.append((Hs[i], new_ending_x)) height_queue_len += 1 if max_height > -1: curr_perim -= max_height curr_perim += abs(Hs[i] - max_height) + Hs[i] ...
{} {}".format(abs(Hs[i] - max_height), Hs[i])) """ ________________ | | 2 5| | ___________| | | ___|_________ | 6 | | | | | ...
lawrencejones/neuro
iz/ModularFocalNetwork.py
Python
gpl-3.0
1,792
0.00279
""" Examples ======== ModularFocalNetwork(8, [1600, 800], 4).plot() => 8 modules, 4 connections to each neuron """ import numpy as np from Plotters import plot_connectivity_matrix def range_from_base(base, size): return xrange(base, base + size) class ModularFocalNetwork(object): def __init__(self, C, di...
s the connection from node j in input layer to node i in this layer. """ self.C = C self.dim = dim self.module_dim = [layer_size / C for layer_size in dim] self.focal_width = focal_width self.CIJ = np.zeros(dim) for i in range(C): self.init_module(i)...
Initialises the target module with connections from the input layer. """ target_dim, input_dim = self.module_dim input_nodes = range_from_base(module_index * input_dim, input_dim) target_nodes = range_from_base(module_index * target_dim, target_dim) for i in target_nodes: ...
wbrefvem/festina
festina/urls.py
Python
mit
345
0.011594
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'festina.views.home', name='home'), # url(r'^blog/', include('blog.urls')),
url(r'^resume/$', i
nclude('resume.urls')), url(r'^admin/', include(admin.site.urls)), )
kadrlica/ugali
ugali/analysis/farm.py
Python
mit
8,918
0.013007
#!/usr/bin/env python """ Dispatch the likelihood scan to a cluster. """ import os,sys from os.path import join, exists import shutil import subprocess import time import glob import numpy as np import healpy as hp import ugali.utils.config import ugali.utils.skymap import ugali.utils.batch from ugali.utils.project...
subfile submit = np.any(commands[:,-1]) if submit: self.write_script(subfile,commands) else: # Not end of chunk continue commands=[] # Actual job submission if not submit: logger.info(self.s...
gger.info(" "+job) time.sleep(0.5) def write_script(self, filename, commands): """ Write a batch submission script. Parameters ---------- filename : filename of batch script commands : list of commands to execute Returns ------- Non...
js0701/chromium-crosswalk
third_party/WebKit/Source/bindings/scripts/v8_methods.py
Python
bsd-3-clause
24,023
0.002622
# Copyright (C) 2013 Google Inc. 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 of conditions and the ...
if is_custom_element_callbacks: includes.add('core/dom/custom/CustomElementProcessingStack.h') is_raises_exception = 'RaisesException' in extended_attributes is_custom_cal
l_prologue = has_extended_attribute_value(method, 'Custom', 'CallPrologue') is_custom_call_epilogue = has_extended_attribute_value(method, 'Custom', 'CallEpilogue') is_post_message = 'PostMessage' in extended_attributes if is_post_message: includes.add('bindings/core/v8/SerializedScriptValueFactory....
rogerhoward/funcaas
server.py
Python
mit
673
0.002972
#!/usr/bin/env python """Server run file. Run by './server.py' Access properties as 'config.property' """ import pkgutil, sys from flask import Flask, Blueprint, render_template, reques
t import config app = Flask(__name__) modules = pkgutil.iter_modules(path=[config.modules_directory_name]) for loader, mod_name, ispkg in modules: if mod_name not in sys.modules: loaded_mod = __import__(config.modules_directory_name + '.' + mod_name, fromlist=[mod_name]) for obj in vars(loaded_mod...
app.register_blueprint(obj) app.run(debug=config.debug, host=config.host, port=config.port)
shahbazn/neutron
neutron/db/l3_dvr_db.py
Python
apache-2.0
31,701
0.000315
# Copyright (c) 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 # # Unless ...
tributed", 'default': cfg.CONF.router_distributed }]) def _create_router_db(self, context, router, tenant_id): """Create a router db object with dvr
additions.""" router['distributed'] = is_distributed_router(router) with context.session.begin(subtransactions=True): router_db = super( L3_NAT_with_dvr_db_mixin, self)._create_router_db( context, router, tenant_id) self._process_extra_attr_ro...
instana/python-sensor
instana/instrumentation/aws/triggers.py
Python
mit
10,212
0.001469
# (c) Copyright IBM Corp. 2021 # (c) Copyright Instana Inc. 2020 """ Module to handle the work related to the many AWS Lambda Triggers. """ import gzip import json import base64 from io import BytesIO import opentracing as ot from ...log import logger STR_LAMBDA_TRIGGER = 'lambda.trigger' def get_context(tracer, e...
span.set_tag('lambda.cw.events.more', False) report = [] for item in resources: if len(item) > 200: item = it
em[:200] report.append(item) span.set_tag('lambda.cw.events.resources', report) elif is_cloudwatch_logs_trigger(event): logger.debug("Detected as Cloudwatch Logs Trigger") span.set_tag(STR_LAMBDA_TRIGGER, 'aws:cloudwatch.logs') try: ...
nil0x42/phpsploit
plugins/credentials/cloudcredgrab/plugin_args.py
Python
gpl-3.0
596
0.003356
import argparse import ui.output def help_format_cloudcredgrab(prog): kwargs = dict() kwargs['width'] = ui.output.columns() kwargs['max_help_position'] = 34 format = argparse.HelpFormatter(prog, **kwargs) return (format) def parse(args): parser = argparse.ArgumentParser(prog="cloudcredgrab", ...
) parser.add_argument('platf
orm') options = vars(parser.parse_args(args))
fdroidtravis/repomaker
repomaker/wsgi.py
Python
agpl-3.0
396
0
""" WSGI config for repomaker project. It exposes the WSGI callable as a module-level variable named ``application``. For m
ore information on this file, see https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/ """ import os from django.core.wsgi
import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "repomaker.settings") application = get_wsgi_application()
debasishbai/django_blog
blog/database_config.py
Python
mit
454
0.002203
import psycopg2 import urlparse import os def server_db(): urlparse.uses_netloc.append("postgres") url = urlparse.urlparse(os.environ["DATABASE_URL"]) conn = psycopg2.c
onnect(database=url.path[1:], user=url.username, password=url.password, host=url.hostname, port=url.port) cur = conn.cursor() return cur def lo
cal_db(): conn = psycopg2.connect(host="", user="", password="", dbname="") cur = conn.cursor() return cur
sprax/python
bin_pack.py
Python
lgpl-3.0
10,413
0.001825
#!/usr/bin/env python3 ''' @file: bin_pack.py @auth: Sprax Lines @date: 2018-02-07 00:19:39 Wed 07 Feb Can the space requirements specified by bits be packed into the specified bins? ''' from __future__ import print_function from itertools import islice # import pdb # from pdb import set_trace from datetime import dat...
bits)), no sorting. Implementation: Naive exhaustive recursion with supplementary array. Complexity: Time O(N!), additional space O(N). * Tries to fit bits into bins in the original order given. * @param bins * @param bits * @param packed * @return ''' if all(packed): return ...
[i]: # Exhaustive: check all remaining solutions that start with item[i] # packed in some bin[j] packed[i] = True for j in range(len(bins)): if bins[j] >= bits[i]: # deduct item amount from bin and try to pack the rest ...
googleapis/gapic-generator-python
tests/integration/goldens/logging/samples/generated_samples/logging_v2_generated_config_service_v2_delete_sink_sync.py
Python
apache-2.0
1,381
0.000724
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # 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...
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 governing permissions and # limitations under the License. # # Generated code. DO NOT EDIT! # # Snippet for DeleteSink # NOTE: This snippet has been automatically generated for illustrative...
GeneralizedLearningUtilities/SuperGLU
python_module/SuperGLU/Services/TextProcessing/Tests/Inflect/test_classical_herd.py
Python
mit
835
0.008383
from nose.tools import eq_ import inflect def test_ancient_1(): p = inflect.engine()
# DEFAULT... eq_(p.plural_noun('wildebeest'), 'wildebeests', msg="classical 'herd' not active") # "person" PLURALS ACTIVATED... p.classical(herd=True) eq_(p.plural_noun('wildebeest'), 'wildebeest', msg="classical 'herd' active") # OTHER CLASSICALS NOT ACTIVATED... eq_(p.plural_noun(...
t' active") eq_(p.plural_noun('error', 0), 'errors', msg="classical 'zero' not active") eq_(p.plural_noun('Sally'), 'Sallys', msg="classical 'names' active") eq_(p.plural_noun('brother'), 'brothers', msg="classical 'all' not active") eq_(p.plural_noun('person'), 'peopl...
PanDAWMS/autopyfactory
autopyfactory/authmanager.py
Python
apache-2.0
8,906
0.011004
#!/usr/bin/env python """ A credential management component for AutoPyFactory """ import logging import math import os import pwd, grp import sys import threading import time import socket # Added to support running module as script from arbitrary location. from os.path import dirname, realpath, sep, pardir fu...
authpluginname = self.aconfig.get(sect, 'plugin') sshh = pluginmanager.getplugin(['autopyfactory', 'plugins', 'authmanager', 'auth'], authpluginname, self, self.aconfig, sect) self.handlers.append(sshh) else: self.log.warn("Unrecognized auth plugin %s...
rs, if needed """ for ah in self.handlers: if isinstance(ah, threading.Thread) : self.log.debug("Handler [%s] is a thread. Starting..." % ah.name) ah.start() else: self.log.debug("Handler [%s] is not a thread. No action." % ah.nam...
keenondrums/sovrin-node
sovrin_common/test/types/test_pool_upg_schema.py
Python
apache-2.0
1,055
0.000948
import pytest from sovrin_common.types import ClientPoolUpgradeOperation from collections import OrderedDict from plenum.common.messages.fields import ConstantField, ChooseField, VersionField, MapField, Sha256HexField, \ NonNegativeNumberField, LimitedLengthStringField, BooleanField EXPECTED_ORDERED_FIELDS = Orde...
ooseField), ("version", VersionField), ('schedule', MapField), ('sha256', Sha256HexField), ('timeout', NonNegativeNumberField), ('justification', LimitedLengthStringField), ("name", LimitedLengthStringField), ("force", BooleanField), ("
reinstall", BooleanField), ]) def test_has_expected_fields(): actual_field_names = OrderedDict(ClientPoolUpgradeOperation.schema).keys() assert actual_field_names == EXPECTED_ORDERED_FIELDS.keys() def test_has_expected_validators(): schema = dict(ClientPoolUpgradeOperation.schema) for field, validat...
SOMA-PainKiller/ECAReview
ECARUSS/wsgi.py
Python
mit
391
0.002558
""" WSGI config for ECAPlanet project. It exposes the WSGI callable as a module-level variable na
med ``application``. For more information on this file, see https://docs.djangoprojec
t.com/en/1.7/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ECARUSS.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application()
beav/pulp
server/pulp/plugins/util/nectar_config.py
Python
gpl-2.0
2,490
0.001205
# -*- coding: utf-8 -*- # Copyright (c) 2013 Red Hat, Inc. # # This software is licensed to you under the GNU General Public # License as published by the Free Software Foundation; either version # 2 of the License (GPLv2) or (at your option) any later version. # There is NO WARRANTY for this software, express or impli...
nses/gpl-2.0.txt. """ Contains functions related to working with the Nectar downloading
library. """ from functools import partial from nectar.config import DownloaderConfig from pulp.common.plugins import importer_constants as constants def importer_config_to_nectar_config(importer_config): """ Translates the Pulp standard importer configuration into a DownloaderConfig instance. :param ...
flavio-casacurta/File-FixedS
calc_length.py
Python
mit
3,848
0.002339
# -*- coding: utf-8 -*- """ Created on 27/04/2015 @author: C&C - HardSoft """ from util.HOFs import * from util.CobolPatterns import * from util.homogenize import Homogenize def calc_length(copy): if isinstance(copy, list): book = copy else: if isinstance(copy, str): book = ...
t usage: usage = 'DISPLAY' if 'COMP-3' in usage or 'COMPUTATIONAL-3' in usage: len_field = len_field / 2 + 1 elif 'COMP' in usage or 'COMPUTATIONAL' in usage or 'BINARY' in usage: len_field = len_field / 2 elif 'SIGN' in usage: len_field += 1 return len
_field
stephane-martin/salt-debian-packaging
salt-2016.3.2/salt/modules/x509.py
Python
apache-2.0
46,018
0.003607
# -*- coding: utf-8 -*- ''' Manage X509 certificates .. versionadded:: 2015.8.0 ''' # Import python libs from __future__ import absolute_import import os import logging import hashlib import glob import random import ctypes import tempfile import yaml import re import datetime import ast # Import salt libs import s...
M2Crypto's inability to get them from CSR objects. ''' cmd = ('openssl crl -text -noout -in {0}'.format(crl_filename)) output = __salt__['cmd.run_stdout'](cmd) crl = {}
for line in output.split('\n'): line = line.strip() if line.startswith('Version '): crl['Version'] = line.replace('Version ', '') if line.startswith('Signature Algorithm: '): crl['Signature Algorithm'] = line.replace('Signature Algorithm: ', '') if line.startsw...
ticklemepierce/osf.io
website/addons/osfstorage/utils.py
Python
apache-2.0
3,726
0.001074
# -*- coding: utf-8 -*- import os import httplib import logging import functools from modularodm.exceptions import ValidationValueError from fram
ework.exceptions import HTTPError from framework.analytics import update_counter from website.addons.osfstorage import settings logger = logging.getLogger(__name__) LOCATION_KEYS = ['service', settings.WATERBUTLER_RESOURCE, 'object'] def update_analytics(node, file_id, version_idx): """ :param Node node: R...
file_id)) update_counter(u'download:{0}:{1}:{2}'.format(node._id, file_id, version_idx)) def serialize_revision(node, record, version, index, anon=False): """Serialize revision for use in revisions table. :param Node node: Root node :param FileRecord record: Root file record :param FileVersion v...
cancan101/StarCluster
starcluster/plugins/users.py
Python
lgpl-3.0
8,400
0.000476
# Copyright 2009-2014 Justin Riley # # This file is part of StarCluster. # # StarCluster is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) any # later ...
batch_file): bfile = master.ssh.remote_file(batch_file, 'r') bfilecontents = bfile.read() bfile.close() return bfilecontents bfilecontents = '' tmpl = "%(username)s:%(password)s:%(uid)d:%(gid)d:" tmpl += "Cluster user account %(username)s:" ...
base_uid, base_gid = self._get_max_unused_user_id() for user in usernames: home_folder = '/home/%s' % user if master.ssh.path_exists(home_folder): s = master.ssh.stat(home_folder) uid = s.st_uid gid = s.st_gid else: ...
mvaled/sentry
src/sentry/tasks/commits.py
Python
bsd-3-clause
7,974
0.001756
from __future__ import absolute_import import logging import six from django.core.urlresolvers import reverse from sentry.exceptions import InvalidIdentity, PluginError from sentry.integrations.exceptions import IntegrationError from sentry.models import Deploy, LatestRelease, Release, ReleaseHeadCommit, Repository,...
_delay=60 * 5, max_retries=5, ) @retry(exclude=(Release.DoesNotExist, User.DoesNotExist)) def fetch_commits(release_id, user_id, refs, prev_release_id=None, **kwargs): # TODO(dcramer): this function could use some cleanup/refactoring as its a bit unwieldly commit_list = [] release = Release.objects.get...
try: prev_release = Release.objects.get(id=prev_release_id) except Release.DoesNotExist: pass for ref in refs: try: repo = Repository.objects.get( organization_id=release.organization_id, name=ref["repository"] ) except Re...
medallia/aurora
src/main/python/apache/aurora/executor/common/sandbox.py
Python
apache-2.0
12,730
0.012412
# # 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, software # distributed under ...
Creates mesos_host_sandbox_root (recursively) # - Symlinks self._mesos_dir -> $MESOS_SANDBOX (typically /mnt/mesos/sandbox) # $MESOS_SANDBOX is provided in the environment by the Mesos containerizer. mesos_host_sandbox_root = os.path.dirname(self._mesos_dir) try: safe_mkdir(mesos_host_sandbox_r...
def create(self): self._create_symlinks() super(DockerDirectorySandbox, self).create() class FileSystemImageSandbox(DirectorySandbox): """ A sandbox implementation that configures the sandbox correctly for tasks provisioned from a filesystem image. """ # returncode from a `useradd` or `groupadd` ca...
doctormo/django-autotest
testapp/models.py
Python
agpl-3.0
217
0.018433
""" Test models. ""
" from django.db.models import Model, CharField, BooleanField, DateTimeField #raise IOError("A") class Thing(Model): name = CharField(max_length=32) #
value = BooleanField(default=False)
germfue/vps-tools
vps/console.py
Python
bsd-3-clause
3,431
0.000292
# -*- coding: utf-8 -*- # Copyright (c) 2016, Germán Fuentes Capella <development@fuentescapella.com> # BSD 3-Clause License # # Copyright (c) 2017, Germán Fuentes Capella # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the follo...
l) that contain same keys """ headers = get_headers(dl) csize = column_size(headers, dl) cons_width = console_width({}) values = csize.values() content_width = sum(values) if content_width > cons_width: # if content is bigger than console, sw
itch to yaml format output = {} for d in dl: key = d.get('label') or d.get('SUBID') or d.get('SCRIPTID') output[key] = d puts(ruamel.yaml.dump(output, Dumper=ruamel.yaml.RoundTripDumper)) else: # otherwise, print a table row = [[header, csize.get(heade...
alexgerstein/dartmouth-roommates
migrations/versions/36e92a9c018b_.py
Python
gpl-2.0
748
0.009358
"""empty message Revision ID: 36e92a9c018b Revises: 4758ea467345 Create Date: 2015-05-06 02:42:39.064090 """ # revision identifiers, used by Alembic. revision = '36e92a9c018b' down_revision = '4758ea467345' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - ...
# with op.batch_alter_table('user', schema=None) as batch_op: batch_op.add_column(sa.Column('last_emailed', sa.DateTime(), nullable=True)) ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### with op.batch_alter_table('user', schema=None) a...
h_op.drop_column('last_emailed') ### end Alembic commands ###
TarnumG95/PictureMatchCheater
merge/UI.py
Python
mit
1,196
0.016863
# -*- coding: utf-8 -*- # -- cmd -- pip install PyUserInput import time import win32gui import win32con import PIL.ImageGrab from pymouse import PyMouse PIECE_X = 44 PIECE_Y = 40 NUM_X = 14 NUM_Y = 10 d
ef getOrigin(): cwllk = '宠物连连看'.decode('utf8') hwnd = win32gui.FindWindow("#32770", cwllk) print hwnd #win32gui.ShowWindow(hwnd, win32con.SW_SHOWMINIMIZED) win32gui.ShowWindow(hwnd, win32con.SW_SHOWNORMAL) win32gui.SetForegroundWindow(hwnd) rect = win32gui.GetWindowRect(hwnd) time.s...
return rect def getPic(RECT): """ RECT = (x1,y1,x2,y2) """ pic = PIL.ImageGrab.grab(getOrigin()) return pic def pause(): m = PyMouse() m.click(RECT[0] -58 + 307, RECT[1] - 104 + 62) time.sleep(0.5) def click(pos): ''' pos: (x, y) # (0, 0) for top left piece ''' ...
DavidAndreev/indico
indico/modules/events/surveys/controllers/display.py
Python
gpl-3.0
5,780
0.003114
# This file is part of Indico. # Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN). # # Indico 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 (a...
es/>. from __future__ import unicode_literals from flask import redirect, flash, session, request from sqlalchemy.orm import joinedload from werkzeug.exceptions import Forbidden from indico.core.db import db from indico.modules.auth.util import redirect_to_login from indico.modules.events.models.events import EventT...
urveyAnswer, SurveySubmission from indico.modules.events.surveys.models.surveys import Survey, SurveyState from indico.modules.events.surveys.util import make_survey_form, was_survey_submitted, save_submitted_survey_to_session from indico.modules.events.surveys.views import (WPDisplaySurveyConference, WPDisplaySurveyMe...
nsdf/nsdf
benchmark/benchmark_writer.py
Python
gpl-3.0
13,434
0.00402
# benchmark_writer.py --- # # Filename: benchmark_writer.py # Description: # Author: Subhasis Ray # Maintainer: # Created: Wed Sep 3 10:22:50 2014 (+0530) # Version: # Last-Updated: # By: # Update #: 0 # URL: # Keywords: # Compatibility: # # # Commentary: # # # # # Change log: # # # ...
nvar_list = [] evar_list = [] if args.sampling: if args.sampling.startswith('u'): uvar_list = create_uniform_vars(args.variables,
args.sources, (args.maxcol + args.mincol) / 2, prefix='uniform') elif args.sampling.startswith('n'): nvar_list = create_nonuniform_vars(args.variables, ...
zingale/pyro2
compressible/BC.py
Python
bsd-3-clause
8,919
0.001009
""" compressible-specific boundary conditions. Here, in particular, we implement an HSE BC in the vertical direction. Note: the pyro BC routines operate on a single variable at a time, so some work will necessarily be repeated. Also note: we may come in here with the aux_data (source terms), so we'll do a special ca...
er x boundary # inflow condition with post shock setup v = ccdata.get_var(variable) i = myg.ilo - 1 if variable in ["density", "x-momentum", "y-momentum", "energy"]: val = inflow_post_bc(variable, gamma) while i >= 0: v...
:] = val i = i - 1 else: v[:, :] = 0.0 # no source term elif bc_edge == "ylb": # lower y boundary # for x > 1./6., reflective boundary # for x < 1./6., inflow with post shock setup if variable in ["density", "x-...
rodrigoasmacedo/l10n-brazil
__unported__/l10n_br_account_product/wizard/l10n_br_account_nfe_export_invoice.py
Python
agpl-3.0
8,955
0.00302
# -*- encoding: utf-8 -*- ############################################################################### # # # Copyright (C) 2009 Renato Lima - Akretion # # Copyright (C) 2011 Vinicius Dittgen - PROGE, Leonar...
el.data') model_data_ids = mod_obj.search( cr, uid, [(
'model', '=', 'ir.ui.view'), ('name', '=', 'l10n_br_account_product_nfe_export_invoice_form')], context=context) resource_id = mod_obj.read( cr, uid, model_data_ids, fields=['res_id'], context=context)[0]['res_id'] return { 'type': 'ir.acti
timotk/tweakstream
tweakstream/cli.py
Python
mit
3,757
0.000532
from datetime import datetime import click import crayons import tweakers from tabulate import tabulate from . import __version__, config, utils def format_date(dt): if dt.date() == datetime.today().date(): return dt.strftime("%H:%M") elif dt.year == datetime.today().year: return dt.strftime...
), crayons.green(comment.user.name),
crayons.blue(comment.url), ) print(comment.text, "\n") def choose_topic(topics): """Return chosen topic from a printed list of topics Args: topics (list): List of Topic objects Returns: topic (Topic): Chosen topic """ table = [] for i, t in enumerate(topics): ...
Mirantis/mos-horizon
openstack_dashboard/test/integration_tests/pages/project/network/routerspage.py
Python
apache-2.0
5,775
0
# 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, software # d...
e return True def is_gateway_set(self, name, network_name=DEFAULT_EXTERNAL_NETWORK): row = self._get_row_with_router_name(name) def cell_getter(): return row.cells[self.ROUTERS_TABLE_NETWORK_COLUMN] try: self._wait_till_text_p
resent_in_element(cell_getter, network_name) except exceptions.TimeoutException: return False return True def go_to_interfaces_page(self, name): self._get_element(by.By.LINK_TEXT, name).click() self._get_element(*self._interfaces_tab_locator).click() return Route...
pybuilder/pybuilder
src/main/python/pybuilder/_vendor/pkg_resources/_vendor/importlib_resources/_itertools.py
Python
apache-2.0
884
0
from itertools import filterfalse from typing import ( Callable, Iterable, Iterator, Optional, Set, TypeVar, Union, ) # Type and type variable definitions _T = TypeVar('_T') _U = TypeVar('_U') def unique_everseen( iterable: Iterable[_T], key: Optional[Callable[[_T], _U]] = None ) -> ...
ts ever seen." # unique_everseen('AAAABBBCCDAABBB') --> A B C
D # unique_everseen('ABBCcAD', str.lower) --> A B C D seen: Set[Union[_T, _U]] = set() seen_add = seen.add if key is None: for element in filterfalse(seen.__contains__, iterable): seen_add(element) yield element else: for element in iterable: k = k...
open-mmlab/mmdetection
configs/retinanet/retinanet_r101_fpn_2x_coco.py
Python
apache-2.0
197
0
_base_ = './retinanet_r50_fpn_2x_coco.py' model = dict( backbone=dict( depth=101, init_cfg=dict(type='Pretrained', checkpoint
='torchvision://resnet10
1')))
zetasyanthis/myarchive
src/myarchive/libs/livejournal/backup.py
Python
mit
7,193
0.001529
#!/usr/bin/env python3 __revision__ = "$Rev$" try: import configparser except ImportError: import ConfigParser as configparser import pickle import datetime import time import os.path import sys from optparse import OptionParser import lj """ journal backup dictionary structure: { 'last_entry': timestamp...
= {'comments': {}, 'usermaps': {}} maxid = str(int(highest) + 1) while highest < maxid:
meta = server.fetch_comment_meta(highest, session) maxid = meta['maxid'] for id, data in list(meta['comments'].items()): if int(id) > int(highest): highest = id all['comments'][id] = data all['usermaps'].update(meta['usermaps']) all['maxid'] = maxid ...
charityscience/csh-sms
cshsms/urls.py
Python
gpl-3.0
925
0.005405
"""cshsms URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-bas...
Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls impor
t include, url from django.contrib import admin from django.views.generic import RedirectView urlpatterns = [ url(r'^management/', include('management.urls')), url(r'^admin/', admin.site.urls), url(r'^$', RedirectView.as_view(url='/management')) ]
ActiveState/code
recipes/Python/181780_Using_wxPythTwisted/recipe-181780.py
Python
mit
465
0.021505
from wxPython.wx import * from twisted.internet import reactor class MyApp(wxApp): def OnInit(self): # Twisted Reactor Code reactor.startRunning() EVT_TIMER(self,999999,se
lf.OnTimer) self.timer=wxTimer(self,999999) self.timer.Start(250,False) # End Twisted Code # Do whatever you need to do here return True def OnTimer(self,event): reactor.runUntilCurrent() reactor.doIt
eration(0)
rnortman/boomscooter
boomscooter/follower.py
Python
apache-2.0
2,694
0.00631
# Copyright 2016 Randall Nortman # # 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 writi...
.size) msg_len, flags, seqno = MsgHeader.unpack(header) if flags & MSG_FLAGS_COMMITTED: assert msg_len == MsgHeader.size else:
payload = yield from reader.readexactly(msg_len - MsgHeader.size) #loop.call_later(0.5, self.send_ack, writer, seqno) self.send_ack(writer, seqno) except: LOG.exception('Exception occured in Follower task') writer.close() raise...
weiwang/popcorn
analysis/BagOfWords.py
Python
mit
4,190
0.011456
#!/usr/bin/env python # Author: Angela Chapman # Date: 8/6/2014 # # This file contains code to accompany the Kaggle tutorial # "Deep learning goes to the movies". The code in this file # is for Part 1 of the tutorial on Natural Language Processing. # # *************************************** # import os from sk...
s Enter to continue...") #print 'Download text data sets. If you already have NLTK datasets downlo
aded, just close the Python download window...' #nltk.download() # Download text data sets, including stop words # Initialize an empty list to hold the clean reviews clean_train_reviews = [] # Loop over each review; create an index i that goes from 0 to the length # of the movie review list ...
rosarior/mayan
apps/sources/views.py
Python
gpl-3.0
31,364
0.004591
from __future__ import absolute_import from django.conf import settings from django.contrib import messages from django.core.exceptions import PermissionDenied from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.shortcuts import render_to_response, get_object_or_404 fr...
led=True) for staging_folder in staging_folders: tab_links.append(get_tab_link_for_source(staging_folder, document)) return { 'tab_links': tab_links, SOURCE_CHOICE_WEB_FORM: web_forms, SOURCE_CHOICE_STAGING: staging_folders } def upload_interactive(request, source_type=Non...
k=None): subtemplates_list = [] if document_pk: document = get_object_or_404(Document, pk=document_pk) try: Permission.objects.check_permissions(request.user, [PERMISSION_DOCUMENT_NEW_VERSION]) except PermissionDenied: AccessEntry.objects.check_access(PERMISSION_...
lmmsoft/LeetCode
LeetCode-Algorithm/1147. Longest Chunked Palindrome Decomposition/1147.py
Python
gpl-2.0
896
0.002232
from collections import defaultdict class Solution: def longestDecomposition(self, text: str) -> int: num = 0 L = len(text) l, r = 0, L - 1 mp1 = defaultdict(int) mp2 = defaultdict(int) while l < r: mp1[text[l]] += 1 mp2[text[r]] += 1 ...
= 1 if not mp1 and not mp2 and l > r: pass else: num += 1 return num if __name__ == '__main__': assert Solution().longestDecomposition("ghiabcdefhelloadamhelloabcdefghi") == 7 assert Solution().longestDecomposition("merchant") == 1 assert Solution().longestD...
assert Solution().longestDecomposition("aaa") == 3
ntt-sic/python-cinderclient
cinderclient/openstack/common/apiclient/base.py
Python
apache-2.0
15,937
0.000063
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 Jacob Kaplan-Moss # Copyright 2011 OpenStack Foundation # Copyright 2012 Grid Dynamics # Copyright 2013 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except i...
lass(self, body[response_key]) def _put(self, url, json=None, response_key=No
ne): """Update an object with PUT method. :param url: a partial URL, e.g., '/servers' :param json: data that will be encoded as JSON and passed in POST request (GET will be sent by default) :param response_key: the key to be looked up in response dictionary, e.g....
pliz/gunfolds
tools/comparison.py
Python
gpl-3.0
2,830
0.021555
import ecj import scipy import numpy import operator import networkx as nx #from progressbar import ProgressBar, Percentage numpy.random.RandomState() import bfutils as bfu import numpy as np import gmpy as gmp def num2CG(num,n): """num2CG - converts a number whose binary representaion encodes edge presence/a...
ng graph. The code searches over all undersampled version of G to find all matches with Gstar """ compat = [] GG = G Gprev = G if G == Gstar: return [0] j = 1 G = ecj.undersample(GG,j) while not (G
== Gprev): if Gstar == G: compat.append(j) j += 1 Gprev = G G = ecj.undersample(GG,j) return compat def searchMatch(Gstar,G, iter=5): if gcd4scc(G) >1: return SM_fixed(Gstar, G, iter=iter) return SM_converging(Gstar, G) def hasSink(G): return not reduce(operator.and_, [bo...
aleksandr-bakanov/astropy
astropy/io/fits/hdu/compressed.py
Python
bsd-3-clause
87,677
0.00008
# Licensed under a 3-clause BSD style license - see PYFITS.rst import ctypes import gc import itertools import math import re import time import warnings from contextlib import suppress import numpy as np from .base import DELAYED, ExtensionHDU, BITPIX2DTYPE, DTYPE2BITPIX from .image import ImageHDU from .table impo...
def __init__(self, table_header, image_header): self._cards = image_header._cards
self._keyword_indices = image_header._keyword_indices self._rvkc_indices = image_header._rvkc_indices self._modified = image_header._modified self._table_header = table_header # We need to override and Header methods that can modify the header, and # ensure that they sync with the und...
statsmodels/statsmodels
statsmodels/datasets/nile/data.py
Python
bsd-3-clause
1,398
0.005722
"""Nile River Flows.""" import pandas as pd from statsmodels.datasets import utils as du __docformat__ = 'restructuredtext' COPYRIGHT = """This is public domain.""" TITLE = """Nile River flows at Ashw
an 1871-1970""" SOURCE = """ This data is first analyzed in: Cobb, G. W. 1978. "The Problem of the Nile: Conditional Solution to a Changepoint Problem." *Biometrika*. 65.2, 243-51. """ DESCRSHORT = """This dataset contains measurements on the annual flow of the Nile as me
asured at Ashwan for 100 years from 1871-1970.""" DESCRLONG = DESCRSHORT + " There is an apparent changepoint near 1898." #suggested notes NOTE = """:: Number of observations: 100 Number of variables: 2 Variable name definitions: year - the year of the observations volumne - the...
openstack/neutron-lib
neutron_lib/exceptions/vlantransparent.py
Python
apache-2.0
902
0
# Copyright (c) 2015 Cisco Systems, 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 re...
d 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 governing permissions and limitations # under the License. from ne...
rted by all mechanism drivers.""" message = _("Backend does not support VLAN Transparency.")
pearsonlab/thunder
test/test_seriesloader.py
Python
apache-2.0
10,333
0.002419
import glob import json import os import struct import unittest from nose.tools import assert_almost_equal, assert_equals, assert_true, assert_raises from numpy import allclose, arange, array, array_equal from numpy import dtype as dtypeFunc from thunder.rdds.fileio.seriesloader import SeriesLoader from thunder.utils...
tearDown of the spark context # data will be a sequence of test data # all keys and all values in a test data item must be of the same length # keys get converted to ints regardless of raw input format DATA = [ SeriesBinaryTestData.fromArrays([[1, 2, 3]], [[11, 12, 13
]], 'int16', 'int16'), SeriesBinaryTestData.fromArrays([[1, 2, 3], [5, 6, 7]], [[11], [12]], 'int16', 'int16'), SeriesBinaryTestData.fromArrays([[1, 2, 3]], [[11, 12, 13]], 'int16', 'int32'), SeriesBinaryTestData.fromArrays([[1, 2, 3]], [[11, 12, 13]], 'int32', 'int16'), ...
SUSE/azure-sdk-for-python
azure-mgmt-web/azure/mgmt/web/models/experiments.py
Python
mit
931
0
# 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 cause incorrect behavior and w...
--------------------------------------------------------- from msrest.serialization import Model class Experiments(Model): """Routing rules in production experiments. :param ramp_up_rules: List of ramp-up rules. :type ramp_up_rules: list of :class:`RampUpRule <azure.mgmt.web.models.RampUpRule>` ...
Shugabuga/LapisMirror
plugins/gifscom.py
Python
mit
3,379
0.000296
# The MIT License (MIT) # Copyright (c) 2015 kupiakos # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, me...
e': url, 'importer_display': {'header': 'Mirrored gifscom image:\n\n'}} r = requests.head(url, headers=self.headers) mime_text = r.headers.get('Content-Type') mime = mimeparse.parse_mime_type(mime_text) if mime[0] == 'image': ...
t an image: %s', submission.url) return None data['import_urls'] = [image_url] return data except Exception: self.log.error('Could not import gifs.com URL %s (%s)', submission.url, traceback.format_exc()) return None __...
idea4bsd/idea4bsd
python/testData/copyPaste/LineToBegin.dst.py
Python
apache-2.0
23
0.086957
p<caret>rint
1 print
3
coinapi/coinapi-sdk
oeml-sdk/python/openapi_client/api/__init__.py
Python
mit
219
0.004566
# do not import all apis into this module b
ecause that uses a lot of memory and stack frames # if you need the ability to import all apis from one package, import them with # from openapi_client.apis i
mport BalancesApi
pupapaik/contrail-kubernetes
scripts/opencontrail-kubelet/opencontrail_kubelet/vrouter_api.py
Python
apache-2.0
1,675
0
# # Copyright (c) 2015 Juniper Networks, Inc. # import json import logging import requests VROUTER_AGENT_PORT = 9091 class ContrailVRouterApi(object): def __init__(self): pass def add_p
ort(self, instanceId, nicId, sysIfName, macAddress, **kwargs): data = { "id": nicId, "instance-id": instanceId, "system-name": sysIfName, "mac-address": macAddress, "vn-id": "00000000-0000-0000-0000-000000000001", "vm-project-id": "00000000...
ip6-address": "0::0", "rx-vlan-id": 0, "tx-vlan-id": 0, "type": 0 } if 'display_name' in kwargs: data['display-name'] = kwargs['display_name'] if 'port_type' in kwargs: if kwargs['port_type'] == "NovaVMPort": data['type...
zodiac/incubator-airflow
tests/api/common/mark_tasks.py
Python
apache-2.0
9,129
0.000548
# -*- coding: utf-8 -*- # # 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, software ...
altered = set_state(task=task, execution_date=self.execution_dates[0], upstream=False, downstream=False, future=False, past=False, state=State.SUCCESS, commit=True) self.assertEqual(len(altered), 0) self.verify_state(self.dag1, [task.task_id], [...
lf.execution_dates[0], upstream=False, downstream=False, future=False, past=False, state=State.FAILED, commit=True) self.assertEqual(len(altered), 1) self.verify_state(self.dag1, [task.task_id], [self.execution_dates[0]], ...
RossBrunton/BMAT
bookmarks/migrations/0002_bookmark_valid_url.py
Python
mit
399
0
# -*- coding: utf-8 -*- from __future__ import unicode_l
iterals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('bookmarks', '0001_initial'), ] operations = [ migrations.AddField( model_name='bookmark', name='valid_url', field=models.
BooleanField(default=False), ), ]
UUDigitalHumanitieslab/timealign
stats/migrations/0009_auto_20180620_1232.py
Python
mit
583
0.001715
# -*- coding: utf-8 -*- # Generated by Django 1.9.13 on 2018-06-20 12:32 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('stats', '0008_scenario_mds_allow_partial'), ] operations...
model_name='scenario', na
me='owner', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='scenarios', to=settings.AUTH_USER_MODEL), ), ]
platformio/platformio
platformio/util.py
Python
apache-2.0
14,440
0.001108
# Copyright (c) 2014-present PlatformIO <contact@platformio.org> # # 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 appli...
self.cache.clear() class throttle(object): def __init__(self, threshhold): self.threshhold = threshhold # milliseconds self.last = 0 def __call__(self, func): @wraps(func) def wrapper(*args, **kwargs): diff = int(round((time.time() - self.last) * 1000)) ...
sleep((self.threshhold - diff) * 0.001) self.last = time.time() return func(*args, **kwargs) return wrapper def singleton(cls): """ From PEP-318 http://www.python.org/dev/peps/pep-0318/#examples """ _instances = {} def get_instance(*args, **kwargs): if cls not in ...
rborn/TiSocial.Framework
build.py
Python
mit
6,767
0.041377
#!/usr/bin/env python # # Appcelerator Titanium Module Packager # # import os, subprocess, sys, glob, string import zipfile from datetime import date cwd = os.path.abspath(os.path.dirname(sys._getframe(0).f_code.co_filename)) os.chdir(cwd) required_module_keys = ['name','version','moduleid','description','copyright','...
=') if idx > 0: key = line[0:idx].strip() value = line[idx+1:].strip() config[key] = replace_vars(config,value) return config def generate_doc(config): docdir = os.path.join(cwd,'documentation') if not os.path.exists(docdir): print "Couldn
't find documentation file at: %s" % docdir return None try: import markdown2 as markdown except ImportError: import markdown documentation = [] for file in os.listdir(docdir): if file in ignoreFiles or os.path.isdir(os.path.join(docdir, file)): continue md = open(os.path.join(docdir,file)).read() h...
igrowing/Orchids
manage.py
Python
mit
805
0
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "orchids.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the ...
try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed a
nd " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
daveinnyc/various
python-practice/class_demos.py
Python
mit
3,833
0.00574
# Notes on classes class Sample(): def __init__(self, name, number): self.name = name self.number = number def print_values(self): print(f"name: {self.name}") print(f"number: {self.number}") class SampleWithProperties(): def __init__(self, name, number)...
ion}, l
et's go! ") if __name__ == "__main__": ''' # Demo Sample() instance = Sample("fred", 3) instance.print_values() print(f"Access name field directly: {instance.name}") instance.number += 100 print(f"Access number field directly: {instance.number}") ''' ''' ...
ron1818/Singaboat_RobotX2016
robotx_nav/nodes/move_base_force_cancel.py
Python
gpl-3.0
1,191
0.008396
#! /usr/bin/env python import rospy import actionlib from move_base_msgs.msg import MoveBaseActionGoal from actionlib_msgs.msg import GoalID class ForceCancel(object): def __init__(self, nodename="force_cancel", is_newnode=True, repetition=10): self.repetition = rospy.get_param("~repetition", repetition) ...
"move_base/goal", MoveBaseActionGoal, 60) r = rospy.Rate(1) counter = 0 while not rospy.is_shutdown() and (counter < self.repetition): msg = GoalID() msg.id = self.id pub.publish(msg)
r.sleep() counter += 1 def callback(self, msg): self.id = msg.goal_id.id def shutdown(self): rospy.loginfo("cancel job finished") rospy.sleep(1) pass if __name__ == "__main__": fc = ForceCancel('force_cancel', False, 5)
enoordeh/Pangloss
Calibrate.py
Python
gpl-2.0
10,551
0.013079
#!/usr/bin/env python # ====================================================================== import pangloss import sys,getopt,cPickle,numpy import scipy.stats as stats # ====================================================================== def Calibrate(argv): """ NAME Calibrate.py PURPOSE...
ode it up!" print "Calibrate: (This should be easy, but you can ask tcollett@ast.cam.uk for help)." exit() # Now calculate comparators: callist=numpy.empty((Nc,2)) jd=pangloss.PDF(["kappa_
ext",comparator+'_'+comparatorType]) for i in range(Nc): C = calresultpickles[i] pdf = pangloss.readPickle(C) if comparator=="Kappah": if comparatorType=="median": # Recall that we created a special file for this #...
asajeffrey/servo
tests/wpt/web-platform-tests/content-security-policy/embedded-enforcement/support/echo-required-csp.py
Python
mpl-2.0
1,679
0.006552
import json from wptserve.utils import isomorphic_decode def main(request, response): message = {} header = request.headers.get(b"Test-Header-Injection"); message[u'test_header_injection'] = isomorphic_decode(header) if header else None header = request.headers.get(b"Sec-Required-CSP"); message[...
rmat(isomorphic_decode(request.GET[b"second_level_iframe_csp"])) else: second_level_iframe_code = u'''<script> var i2 = document.createElement('iframe'); i2.src = 'echo-required-csp.py'; document.body.appendChild(i2); </script>''' return [(b"Content-T...
ml> <head> <!--{2}--> <script> window.addEventListener('message', function(e) {{ window.parent.postMessage(e.data, '*'); }}); window.parent.postMessage({0}, '*'); </script> </head> <body> {1} </body> </html> '''.format(json.dumps(message), second_level_iframe_code, str(request.hea...
jacobajit/ion
intranet/apps/auth/backends.py
Python
gpl-2.0
6,021
0.002159
# -*- coding: utf-8 -*- import logging import os import re import uuid from django.conf import settings from django.contrib.auth.hashers import check_password import pexpect from ..users.models import User logger = logging.getLogger(__name__) class KerberosAuthenticationBackend(object): """Authenticate using...
eout=5) kinit.sendline(password) kinit.expect(pexpect.EOF) kinit.close() exitstatus = kinit.exitstatus except pexpect.TIMEOUT: KerberosAuthenticationBackend.kinit_timeout_handle(username, realm) exitstatus = 1 ...
bug("Kerberos authorized {}@{}".format(username, realm)) return True else: logger.debug("Kerberos failed to authorize {}".format(username)) if "KRB5CCNAME" in os.environ: del os.environ["KRB5CCNAME"] return False def authenticate(self, usernam...
A-Manning/FStar
src/tools/updateDiscriminators.py
Python
apache-2.0
419
0.019093
import sys import subprocess result=subprocess.check_output("grep -
or 'is_[A-Z]\w*' .", shell=True) lines=[ l for l in str(result).splitlines() if l.find('.fst') != -1] for l in lines: content = l.split(':') constr=content[1].strip()[0:-1] print("sed -i -e 's/%s[.]/%s?./g' %s" % (constr, constr, content[0])) subprocess.call("sed -i -e 's/%s[.]/%s?./g' %s" %
(constr, constr, content[0]), shell=True)
Marocco2/EpicRace
BOX/box.py
Python
lgpl-3.0
10,406
0.002787
# # # BBBBBBBBBBBBBBBBB OOOOOOOOO XXXXXXX XXXXXXX # B::::::::::::::::B OO:::::::::OO X:::::X X:::::X # B::::::BBBBBB:::::B OO:::::::::::::OO X:::::X X:::::X # BB:::::B B:::::BO:::::::OOO:::::::OX::::::X X::::::X # B::::B B:::::BO::::::O O::::::OXXX:::::...
::O O:::::O X:::::X X:::::X # B::::BBBBBB:::::B O:::::O O:::::O X:::::
X:::::X # B:::::::::::::BB O:::::O O:::::O X:::::::::X # B::::BBBBBB:::::B O:::::O O:::::O X:::::::::X # B::::B B:::::BO:::::O O:::::O X:::::X:::::X # B::::B B:::::BO:::::O O:::::O X:::::X X:::::X # B::::B B:::::BO::::::O O::::::OXXX:::::X X:::::XXX...
MasAval/django_pipedrive
pipedrive/migrations/0005_auto_20170510_1253.py
Python
bsd-3-clause
4,508
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('pipedrive', '0004_auto_20170502_1701'), ] operations = [ migrations.AlterField( model_name='activity', ...
rganization', name='address', field=models.CharField(max_length=500, null=True, blank=True), ), migrations.AlterField( model_name='organization', name='name', field=models.CharField(max_length=500, null=True, blank=True), ), mig...
arField(max_length=500), ), migrations.AlterField( model_name='organizationfield', name='key', field=models.CharField(max_length=500), ), migrations.AlterField( model_name='organizationfield', name='name', field=mode...
smmribeiro/intellij-community
python/helpers/pydev/setup_cython.py
Python
apache-2.0
5,308
0.004145
''' A simpler setup version just to compile the speedup module. It should be used as: python setup_cython build_ext --inplace Note: the .c file and other generated files are regenerated from the .pyx file by running "python build_tools/build.py" ''' import os import sys from setuptools import setup os.chdir(os.pat...
evd_name,)) shutil.copy(pxd_file, new_pxd_file) assert os.path.exists(pyx_file) try: if force_cython: from Cython.Build import cythonize # @UnusedImport ext_modules = cythonize([
"%s/%s.pyx" % (dir_name, target_pydevd_name,), ], force=True) else: # Always compile the .c (and not the .pyx) file (which we should keep up-to-date by running build_tools/build.py). from distutils.extension import Extension ext_modules = [Extension...
tomsilver/nupic
nupic/regions/CLAClassifierRegion.py
Python
gpl-3.0
9,996
0.006803
#!/usr/bin/env python # ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions ...
at bit and then votes across these to get the resulting classification(s). The caller can choose to tell the region that the classifications for iteration N+K should be aligned with the activationPattern for iteration N. This results in the classifier producing p
redictions for K steps in advance. Any number of different K's can be specified, allowing the classifier to learn and infer multi-step predictions for a number of steps in advance. """ ############################################################################### @classmethod def getSpec(cls): ns = di...
shubhamdhama/zulip
analytics/lib/counts.py
Python
apache-2.0
29,311
0.003685
import logging import time from collections import OrderedDict, defaultdict from datetime import datetime, timedelta from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union from django.conf import settings from django.db import connection from django.db.models import F from psycopg2.sql import SQL, C...
er_realm.id = {}").format(Literal(realm.id)) else: realm_clause = SQL("") if output_table in (UserCount, StreamCount): realmcount_query = SQL("""
INSERT INTO analytics_realmcount (realm_id, value, property, subgroup, end_time) SELECT
cygnushan/measurement
SC_spectrum/Ui_SC_main.py
Python
mit
31,084
0.001263
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'G:\WorkDir\gas-sensing_resistors\SC_spectrum\SC_main.ui' # # Created: Wed Jan 20 20:49:15 2016 # by: PyQt4 UI code generator 4.11.3 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui from Rt_mplCa...
talLayout_15")) self.verticalLayout_10 = QtGui.QVBoxLayout() self.verticalLayout_10.setObjectName(_fromUtf8("verticalLayout_10")) self.SC_MPLS = QtGui.QStackedWidget(SC_APP) self.SC_MPLS.setMinimumSize(QtCore.QSize(480, 320))
self.SC_MPLS.setMaximumSize(QtCore.QSize(480, 320)) font = QtGui.QFont() font.setPointSize(12) self.SC_MPLS.setFont(font) self.SC_MPLS.setObjectName(_fromUtf8("SC_MPLS")) self.Rt_MPL = Rt_CanvasWidget() self.Rt_MPL.setObjectName(_fromUtf8("Rt_MPL")) self.SC_MPLS.a...
jstewmon/proselint
proselint/checks/wallace/redundancy.py
Python
bsd-3-clause
659
0
# -*- coding: utf-8 -*- """Redundancy. --- layout: post source: Da
vid Foster Wallace source_url: http://bit.ly/1c85lgR title: Red
undancy date: 2014-06-10 12:31:19 categories: writing --- Points out use redundant phrases. """ from proselint.tools import memoize, preferred_forms_check @memoize def check(text): """Suggest the preferred forms.""" err = "wallace.redundancy" msg = "Redundancy. Use '{}' instead of '{}'." redu...
ToontownUprising/src
toontown/hood/Place.py
Python
mit
37,237
0.002793
from pandac.PandaModules import * from toontown.toonbase.ToonBaseGlobal import * from direct.directnotify import DirectNotifyGlobal from direct.fsm import StateData from direct.showbase.PythonUtil import PriorityCallbacks from toontown.safezone import PublicWalk from toontown.launcher import DownloadForceAcknowledge im...
lf.preserveFriendsList() self.fsm.request(state) def getState(self): if hasattr(self, 'fsm'): curState = self.fsm.getCurrentState().getName() return curState def getZoneId(self): return self.zoneId def getTaskZoneId(self): return self.getZoneId(...
fromAvatar, toAvatar): if base.config.GetBool('want-tptrack', False): if toAvatar == localAvatar: toAvatar.doTeleportResponse(fromAvatar, toAvatar, toAvatar.doId, 1, toAvatar.defaultShard, base.cr.playGame.getPlaceId(), self.getZoneId(), fromAvatar.doId) else: ...
GuardianRG/angr
angr/simos.py
Python
bsd-2-clause
19,350
0.004393
""" Manage OS-level configuration """ import logging l = logging.getLogger("angr.simos") from archinfo import ArchARM, ArchMIPS32, ArchX86, ArchAMD64 from simuvex import SimState, SimIRSB, SimStateSystem, SimActionData from simuvex import s_options as o from simuvex.s_procedure import SimProcedure, SimProcedureContin...
ader, kwargs={'project': self.proj}) self.proj.hook(self._loader_lock_addr, _dl_rtld_lock_recursive) self.proj.hook(self._loader_unlock_addr, _dl_rtld_unlock_recursive) self.proj.hook(self._vsyscall_addr, _vsyscall) ld_obj = self.proj.loader.linux_loader_object if ld_obj is not ...
oj.loader}) _rtld_global = ld_obj.get_symbol('_rtld_global') if _rtld_global is not None: if isinstance(self.proj.arch, ArchAMD64): self.proj.loader.memory.write_addr_at(_rtld_global.rebased_addr + 0xF08, self._loader_lock_addr) self.proj....
clld/tsezacp
tests/test_selenium.py
Python
apache-2.0
183
0
fro
m __future
__ import unicode_literals import time import pytest @pytest.mark.selenium def test_ui(selenium): selenium.browser.get(selenium.url('/download')) time.sleep(3)