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
ericholscher/cookiecutter
tests/__init__.py
Python
bsd-3-clause
3,893
0.003596
#!/usr/bin/env python # -*- coding: utf-8 -*- """ __init__ --------- Contains testing helpers. """ import os import shutil import stat import sys if sys.version_info[:2] < (2, 7): import unittest2 as unittest else: import unittest def force_delete(func, path, exc_info): """ Error handler for `shuti...
self.cookiecutters_dir_found = True # Remove existing backups before backing up. If they exist, they're stale. if os.path.isdir(self.cookiecutters_dir_backup): shutil.rmtree(self.cookiecutters_dir_backup) shutil.copytree(self.cookiecutters_dir, self.cookiecut...
cookiecutterrc, so this logic is simpler. if self.user_config_found and os.path.exists(self.user_config_path_backup): shutil.copy(self.user_config_path_backup, self.user_config_path) os.remove(self.user_config_path_backup) # Carefully delete the created ~/.cookiecutters dir only...
sjh/python
default_dict.py
Python
apache-2.0
477
0.002096
#!/usr/bin/env python3 # _*_ coding: utf-8 _*_ u""" One way of implementing default dictionary. """ class DefaultDic
t(dict): def __missing__(self, key): u""" Return default value as key if no value specified dictionary key. """ return key if __name__ == "__main__": d = DefaultDict() print(d, type(d), d.keys()) d['flop'] = 127 print(d, type(d), d.keys()) d['flip'] = 130
print(d, type(d), d.keys()) print(d['no_value'])
thomaslima/PySpice
PySpice/Spice/Simulation.py
Python
gpl-3.0
14,801
0.004256
################################################################################################### # # PySpice - A Spice Package for Python # Copyright (C) 2014 Fabrice Salvaire # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published ...
f the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # #################################################################################################### #################################################################################################### import lo...
import NgSpiceShared from .Server import SpiceServer #################################################################################################### _module_logger = logging.getLogger(__name__) #################################################################################################### class CircuitSim...
derekjchow/models
research/slim/nets/mobilenet/conv_blocks.py
Python
apache-2.0
13,351
0.005243
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
th divisible by this value. split_divisible_by: make sure every split group is divisible by this number. expansion_transform: Optional function that takes expansion as a single input and returns output. depthwise_location: where to put depthwise covnvolutions supported values None, 'input'...
es. So if input had c channels, output will have c x depthwise_channel_multpilier. endpoints: An optional dictionary into which intermediate endpoints are placed. The keys "expansion_output", "depthwise_output", "projection_output" and "expansion_transf
hawkphantomnet/leetcode
FirstMissingPositive/Solution.py
Python
mit
495
0.00202
class Solution(object): def firstMissingPositive(self, nums): """ :type nums: List[int] :rtype: int """ l = len(nums) for i in range(0, l): cur = nums[i] while cur >= 1 and cur <= l and nums[cur -
1] != cur:
tmp = nums[cur - 1] nums[cur - 1] = cur cur = tmp for i in range(0, l): if nums[i] != i + 1: return i + 1 return l + 1
klnprj/testapp
django/db/models/fields/__init__.py
Python
bsd-3-clause
47,219
0.000911
import copy import datetime import decimal import math import warnings from itertools import tee from django.db import connection from django.db.models.query_utils import QueryWrapper from django.conf import settings from django import forms from django.core import exceptions, validators from django.utils.datastructur...
tart # of most "choices" lists. BLANK_CHOICE_DASH = [("", "---------")] BLANK_CHOICE_NONE = [("", "None")] class FieldDoesNotExist(Exception): pass # A guide to Field parameters: # # * name: The name of the field specifed in the model. # * attname: The attribute to use on the model object. This i
s the same as # "name", except in the case of ForeignKeys, where "_id" is # appended. # * db_column: The db_column specified in the model (or None). # * column: The database column for this field. This is the same as # "attname", except if db_column is specified. # # ...
pinax/pinax-lms-activities
pinax/lms/activities/models.py
Python
mit
4,304
0.000465
from django.contrib.auth.models import User from django.db import models from django.utils import timezone import jsonfield from .hooks import hookset from .utils import load_path_attr class UserState(models.Model): """ this stores the overall state of a particular user. """ user = models.OneToOneFi...
s = { "available": [], "inprogress": [], "completed": [], "repeatable": [] } for key, activity_class_pat
h in hookset.all_activities(): activity = load_path_attr(activity_class_path) state = ActivityState.state_for_user(user, key) user_num_completions = ActivitySessionState.objects.filter( user=user, activity_key=key, completed__isnull=False ).count() ...
Vodak/SINS
src/main.py
Python
gpl-3.0
91
0
""" Fichier main qui lance le programme """
from Game import * game = Game() game.play()
cwolferh/heat-scratch
heat/db/sqlalchemy/migrate_repo/versions/071_stack_owner_id_index.py
Python
apache-2.0
897
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 # ...
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import sqlalchemy def upgrade(migrate_engine
): meta = sqlalchemy.MetaData(bind=migrate_engine) stack = sqlalchemy.Table('stack', meta, autoload=True) name_index = sqlalchemy.Index('ix_stack_owner_id', stack.c.owner_id, mysql_length=36) name_index.create(migrate_engine)
kennethlove/django
django/db/models/query.py
Python
bsd-3-clause
70,273
0.001352
""" The main QuerySet implementation. This provides the public API for the ORM. """ import copy import itertools import sys from django.core import exceptions from django.db import connections, router, transaction, IntegrityError from django.db.models.fields import AutoField from django.db.models.query_utils import (...
inimize code duplication, we use the __len__ # code path which also forces this, and also does the prefetch len(self) if self._result_cache is not None: return bool(self._result_cache) try: next(iter(self)) except StopIteration: return...
def __contains__(self, val): # The 'in' operator works without this method, due to __iter__. This # implementation exists only to shortcut the creation of Model # instances, by bailing out early if we find a matching element. pos = 0 if self._result_cache is not None: ...
JinnLynn/genpac
tests/util.py
Python
mit
1,389
0.002185
# -*- coding: utf-8 -*- from __future__ import (unicode_literals, absolute_import, division, print_function) import sys import os import pytest from contextlib import contextmanager import genpac from genpac._compat import string_types, iterkeys, iteritems parametrize = pytest.mark.parametrize...
[] if isinstance(argv, string_types): argv = argv.split(' ') if not argv or argv[0] != 'genpac': argv.insert(0, 'genpac') envs.setdefault('GENPAC_TEST_TMP', _TMP_DIR) envs.setdefault('GENPAC_TEST_ETC', _ETC_DIR) for k, v in iteritems(envs):
os.environ[k] = v old_argv = sys.argv sys.argv = argv yield genpac.Generator._gfwlists.clear() for k in iterkeys(envs): if k in os.environ: del os.environ[k] sys.argv = old_argv
wangjun/pyload
module/plugins/hoster/FreakshareCom.py
Python
gpl-3.0
6,038
0.004306
#!/usr/bin/env python # -*- coding: utf-8 -*- import re from module.plugins.Hoster import Hoster from module.plugins.internal.CaptchaService import ReCaptcha class FreakshareCom(Hoster): __name__ = "FreakshareCom" __type__ = "hoster" __pattern__ = r"http://(?:www\.)?freakshare\.(net|com)/files/\S*?/" ...
eturn int(timestring.group(1)
) + 1 # add 1 sec as tenths of seconds are cut off else: return 60 def file_exists(self): """ returns True or False """ if self.html is None: self.download_html() if re.search(r"This file does not exist!", self.html) is not None: return F...
roshantha9/AbstractManycoreSim
src/libMappingAndScheduling/FullyDynamic/TaskMappingSchemesFullyDyn.py
Python
gpl-3.0
320
0.028125
class TaskMappingSchemesFullyD
yn: TASKMAPPINGSCHEMESFULLYDYN_NONE = 0 # this will give error TASKMAPPINGSCHEMESFULLYDYN_RANDOM = 1 TASKMAPPI
NGSCHEMESFULLYDYN_LOWESTUTIL_NEARESTPARENT = 2
tadek-project/tadek-common
tadek/core/location.py
Python
gpl-3.0
9,460
0.008985
################################################################################ ## ## ## This file is a part of TADEK. ## ## ...
): errors.extend(_addModuleDir(module, os.path.join(path, dirname))) # Add a corresponding locale locale.add(os.path.join(path, _LOCALE_DIR)) if errors: disable(path) return errors def disable(path):
''' Disables a location of models and test cases specified by the path. :param path: A path to a location directory :type path: string ''' path = os.path.abspath(path) for dirname, module in _DIRS_MAP.iteritems(): _removeModuleDir(module, os.path.join(path, dirname)) # Remove a ...
menpo/lsfm
lsfm/model.py
Python
bsd-3-clause
968
0
import numpy as np from menpo.model import PCAModel from menpo.visualize import print_progress def prune(weights, n_retained=50): w_norm = (weights[:
, :n_retained] ** 2).sum(axis=1) # High weights here suggest problematic samples bad_to_good_index = np.argsort(w_norm)[::-1]
return w_norm, bad_to_good_index def pca_and_weights(meshes, retain_eig_cum_val=0.997, verbose=False): model = PCAModel(meshes, verbose=verbose) n_comps_retained = (model.eigenvalues_cumulative_ratio() < retain_eig_cum_val).sum() if verbose: print('\nRetaining {:.2%} o...
fatrix/django-golive
project_examples/django_example/django_example/urls.py
Python
bsd-2-clause
801
0.007491
from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() from django.views.generic import TemplateView urlpatterns = patterns('', # Examples:
url(r'^$', TemplateView.as_view(template_name='index.html'), name='index'), # url(r'^django_example/', include('django_example.foo.urls')), # Uncomment the admin/doc li
ne below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), )
DigitalCampus/django-nurhi-oppia
oppia/templatetags/query_string.py
Python
gpl-3.0
2,788
0.002511
import urllib from django import template from django.utils.safestring import mark_safe register = template.Library() @register.tag def query_string(parser, token): """ Allows to manipulate the query string of a page by adding and removing keywords. If a given value is a context variable it will resolve...
del p[k] elif v is not None:
p[k] = v for k, v in p.items(): try: p[k] = template.Variable(v).resolve(context) except: p[k] = v return mark_safe('?' + '&amp;'.join([u'%s=%s' % (urllib.quote_plus(str(k)), urllib.quote_plus(str(v))) for k, v in p.items()])) # Taken from lib/utils.py def string_to_...
mikesligo/distributed-search
Exceptions/Invalid_IP_exception.py
Python
mit
48
0
class
Invalid_IP_exceptio
n(Exception): pass
eemiliosl/pyanno_voting
setup.py
Python
bsd-2-clause
916
0.021834
import os from setuptools import setup # Utility function to read the README file. # Used for the long_description. It's nice, because now 1) we have a top lev
el # README file and 2) it's easier to type in the README file than to put a raw # string in below ... def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name = "PyAnno", version = "0.1a", author = "Whatever", author_email = "[email protected]", des...
= "my own webpage", packages=['pyanno'], # This what is really needed, the rest is optional long_description=read('README.md'), classifiers=[ "Development Status :: 3 - Alpha", "Topic :: Utilities", "License :: OSI Approved :: BSD License", ], )
andela-bojengwa/talk
venv/lib/python2.7/site-packages/markdown/extensions/wikilinks.py
Python
mit
2,901
0.005515
''' WikiLinks Extension for Python-Markdown ====================================== Converts [[WikiLinks]] to relative links. See <https://pythonhosted.org/Markdown/extensions/wikilinks.html> for documentation. Original code Copyright [Waylan Limberg](http://achinghead.com/). All changes Copyright The Python Markdo...
s) def extendMarkdown(self, md, md_globals): self.md = md # append to end of inline patterns WIKILINK_RE =
r'\[\[([\w0-9_ -]+)\]\]' wikilinkPattern = WikiLinks(WIKILINK_RE, self.getConfigs()) wikilinkPattern.md = md md.inlinePatterns.add('wikilink', wikilinkPattern, "<not_strong") class WikiLinks(Pattern): def __init__(self, pattern, config): super(WikiLinks, self).__init__(pattern) ...
ericmoritz/flask-auth
flaskext/auth/views.py
Python
bsd-2-clause
2,020
0.00198
from flask import (Module, request, abort, current_app, session, flash, redirect, render_template) import re mod = Module(__name__, name="auth") def check_next(next): """return the value of next if next is a valid next param, it returns None if the next param is invalid""" # security ch...
re.match(r'[^\?]*//', next): return None else: return next @mod.route("/login/", methods=["GET", "POST"]) def login(): backend = current_app.config['AUTH_BACKEND'] next = request.args.get("next", "") next = check_next(next) # Try to authenticate error = None if request.m...
returned, use that as the auth_key in the session if result is not None: session["auth_key"] = result flash("Login successful.") if next: return redirect(next) else: flash("Login Invalid", "error") return render_template("auth/login....
google-research/language
language/xsp/data_preprocessing/wikisql_preprocessing.py
Python
apache-2.0
5,129
0.008384
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by ...
uture__ import print_function import json from language.xsp.data_preprocessing import abstract_sql from language.xsp.data_preprocessing import abstract_sql_converters from language.xsp.data_preprocessing.nl_to_sql_example import NLToSQLExample from language.xsp.data_preprocessing.nl_to_sql_example import populate_utt...
port ParseError from language.xsp.data_preprocessing.sql_parsing import populate_sql from language.xsp.data_preprocessing.sql_utils import preprocess_sql import sqlparse import tensorflow.compat.v1.gfile as gfile def normalize_sql(sql, replace_period=True): """Normalizes WikiSQL SQL queries.""" sql = sql.replace(...
psicobyte/ejemplos-python
ApendiceI/p202.py
Python
gpl-3.0
167
0.005988
#!/usr/bin/python # -*- coding: utf-8 -*- class MiClase: @staticmethod d
ef metodo(entrada): retur
n entrada objeto = MiClase print objeto.metodo(5)
tensorflow/tensorboard
tensorboard/backend/event_processing/plugin_asset_util.py
Python
apache-2.0
3,555
0.000281
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
set_name: The name of the requested asset. Returns: string contents of the plugin asset. Raises: KeyError: if the asset does not exist. """ asset_path = o
s.path.join(PluginDirectory(logdir, plugin_name), asset_name) try: with tf.io.gfile.GFile(asset_path, "r") as f: return f.read() except tf.errors.NotFoundError: raise KeyError("Asset path %s not found" % asset_path) except tf.errors.OpError as e: raise KeyError( ...
renesas-rz/u-boot-2013.04
tools/patman/patman.py
Python
gpl-2.0
6,763
0.001774
#!/usr/bin/python # # Copyright (c) 2011 The Chromium OS Authors. # # See file CREDITS for list of people who contributed to this # project. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; eit...
for module in ['gitutil', 'settings']: suite = doctest.DocTestSuite(module) suite.run(result) # TODO: Surely we can just 'print' result? print result for test, err in result.errors: print err for test, err in result.failures: print err # Called from git with a patch...
is patch elif options.cc_cmd: fd = open(options.cc_cmd, 'r') re_line = re.compile('(\S*) (.*)') for line in fd.readlines(): match = re_line.match(line) if match and match.group(1) == args[0]: for cc in match.group(2).split(', '): cc = cc.strip() if...
pkimber/old_moderate
example/base.py
Python
apache-2.0
5,826
0.000515
""" Django settings """ from django.core.urlresolvers import reverse_lazy DEBUG = True TEMPLATE_DEBUG = DEBUG SESSION_COOKIE_SECURE = False CSRF_COOKIE_SECURE = False TEMPLATE_STRING_IF_INVALID = '**** INVALID EXPRESSION: %s ****' ADMINS = ( ('admin', '[email protected]'), ) MANAGERS = ADMINS # Local time zone...
ATION = 'example.wsgi.application' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) INSTAL
LED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: 'django.contrib.admin', # Uncomment the next line to enable ad...
benob/chainer
chainer/links/connection/mlp_convolution_2d.py
Python
mit
3,009
0.000332
from chainer.functions.activation import relu from chainer import link from chainer.links.connection import convolution_2d class MLPConvolution2D(link
.ChainList): """Two-dimensional MLP convolution layer of Network
in Network. This is an "mlpconv" layer from the Network in Network paper. This layer is a two-dimensional convolution layer followed by 1x1 convolution layers and interleaved activation functions. Note that it does not apply the activation function to the output of the last 1x1 convolution layer. ...
joshl8n/school-projects
illustrate/water.py
Python
gpl-3.0
1,287
0.034188
import pygame from fish import Fish from seaweed import Seaweed class Water: def __init__(self): # color, pos_x, pos_y, width, height self.mOrangeFish = Fish((255, 152, 0), 50, 175, 175, 100) self.mGreyFish = Fish((96, 125, 139), 350, 130, 125, 200) self.mRedFish = Fish((183, 28, 28), 200, 300, 175, 50...
[(0, 80), (100, 100), (200, 80), (300, 100), (400, 80), (500, 100), (600, 80), (600, 500), (0, 500)] pygame.
draw.polygon(surface, color, pointlist, 0) self.mOrangeFish.draw(surface) self.mGreyFish.draw(surface) self.mRedFish.draw(surface) self.mSeaweed.draw(surface) self.mSeaweed2.draw(surface) self.mSeaweed3.draw(surface) self.mSeaweed4.draw(surface) self.mSeaweed5.draw(surface) return
hypermindr/barbante
barbante/recommendation/tests/__init__.py
Python
mit
41
0
""" Tests fo
r mo
dule recommendation. """
magnusmorton/pycket
pycket/hash/simple.py
Python
mit
6,811
0.002496
from pycket import values from pycket.error import SchemeException from pycket.hash.base import ( W_MutableHashTable, W_ImmutableHashTable, w_missing, get_dict_item) from pycket.hash.persistent_hash_map import make_persistent_hash_type from rpy...
e_non_null=True) while isinstance(assocs, values.W_Cons): entry, assocs = assocs.car(), assocs.cdr() if not isinstance(entry, values.W_Cons): raise SchemeException("%s: expected list of pairs" % who) key, val = entry.car(), entry.cdr() data[key] = val return cls(data)...
) for i, k in enumerate(keys): table = table.assoc(k, vals[i]) return table @specialize.arg(0) def make_simple_immutable_table_assocs(cls, assocs, who): if not assocs.is_proper_list(): raise SchemeException("%s: not given proper list" % who) table = cls.EMPTY while isinstanc...
ZipFile/papi.py
papi/helpers.py
Python
bsd-2-clause
356
0
import sys if sys.version_info[0] == 2:
from urlparse import urljoin string_types = basestring, else: from urllib.parse impor
t urljoin string_types = str, def atoi(string, default=0): if (isinstance(string, int)): return string try: return int(string) except (TypeError, ValueError): return default
xstrengthofonex/code-live-tutorials
python_web_development/database/handlers/base_handler.py
Python
mit
1,866
0.000536
import hmac import config from jinja2 import Environment, FileSystemLoader jinja2_env = Environment(loader=FileSystemLoader( config.TEMPLATE_DIRS), autoescape=True) class BaseHandler(object): def __init__(self): self.request = None self.response = None def make_secure_value(self, value):...
n(self, user): self.set_secu
re_cookie('username', str(user['username'])) def logout(self, user): self.response.delete_cookie('username') def write(self, text): self.response.write(text) def redirect(self, url, status=301): self.response.status = status self.response.location = url def render(sel...
lduarte1991/edx-platform
common/djangoapps/third_party_auth/tests/test_admin.py
Python
agpl-3.0
3,696
0.001353
""" Tests third_party_auth admin views """ import unittest from django.contrib.admin.sites import AdminSite from django.core.files.uploadedfile import SimpleUploadedFile from django.core.urlresolvers import reverse from django.forms import models from student.tests.factories import UserFactory from third_party_auth.a...
value.
del post_data['max_session_length'] # Change the name, to verify POST post_data['name'] = 'Another name' # Post the edit form: expecting redirect response = self.client.post(update_url, post_data) self.assertEquals(response.status_code, 302) # Editing the existi...
repology/repology
repology/parsers/parsers/t2.py
Python
gpl-3.0
4,354
0.002067
# Copyright (C) 2019-2021 Dmitry Marakasov <[email protected]> # # This file is part of repology # # repology 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 optio...
e', 't': 'text',
'u': 'url', 'a': 'author', 'm': 'maintainer', 'c': 'category', 'f': 'flag', 'r': 'architecture', 'arch': 'architecture', 'k': 'kernel', 'kern': 'kernel', 'e': 'dependency', 'dep': 'dependency', 'l': 'license', 's': 'stat...
ESS-LLP/frappe
frappe/integrations/doctype/paypal_settings/paypal_settings.py
Python
mit
12,324
0.022558
# -*- coding: utf-8 -*- # Copyright (c) 2015, Frappe Technologies and contributors # For license information, please see license.txt """ # Integrating PayPal ### 1. Validate Currency Support Example: from frappe.integrations.utils import get_payment_gateway_controller controller = get_payment_gateway_controller(...
s(self, params, kwargs): # removing the params as we have t
o setup rucurring payments for param in ('PAYMENTREQUEST_0_PAYMENTACTION', 'PAYMENTREQUEST_0_AMT', 'PAYMENTREQUEST_0_CURRENCYCODE'): del params[param] params.update({ "L_BILLINGTYPE0": "RecurringPayments", #The type of billing agreement "L_BILLINGAGREEMENTDESCRIPTION0": kwargs['description'] }) def...
dataxu/ansible
lib/ansible/modules/cloud/vmware/vmware_guest_find.py
Python
gpl-3.0
4,032
0.002232
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright: Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', ...
ES = r''' - name: Find Guest's Folder using name vmware_guest_find: hostname: 192.168.1.209 username: [email protected] password: vmware validate_certs: no name: testvm register: vm_folder - name: Find Guest's Folder using UUID vmware_guest_find: hostname: 192.168.1.209 user...
[email protected] password: vmware validate_certs: no uuid: 38c4c89c-b3d7-4ae6-ae4e-43c5118eae49 register: vm_folder ''' RETURN = r""" folders: description: List of folders for user specified virtual machine returned: on success type: list sample: [ '/DC0/vm', ] """ fro...
xyalan/build-interpreter
docker_tools/docker_opt.py
Python
apache-2.0
2,738
0.002191
#coding=utf-8 from docker import Client import time import logging from envir import config import ast import re log = logging.getLogger(__name__) class DockerOpt: def __init__(self): app_config = config.read_app_config() self.app = app_config self.url = app_config['docker']['url'] ...
fix/"): tag_name = api_version + "-" + app_version + "-h" + now_str else: raise Exception('unsupported branch') return tag_name def gen_repository(self, registry, project_key, app_name): return str(registry) + "/" + str(project_key) + "/" + str(app_name) def bu...
to the `docker interpreter`, interpreter a docker image :param path: context path include Dockerfile :param tag: image's tag :return: None """ self.read_port() version = self.app['docker']['api']['version'] cli = Client(base_url=self.url, version=str(version)) ...
jsfyfield/pyboids
gfx_boids.py
Python
gpl-2.0
1,867
0.024103
#!python2 from random import randint from boids import * import sys,pygame,time,copy screenx = 800 screeny = 600 ticktime = 0.01 fps = 80 clock = pygame.time.Clock() size = screenx,screeny pygame.init() screen = pygame.display.set_mode(size) time = 0 def gen_boids(x,y,low,upper): nboids = randint(low,upper) b...
[i].step(boids,ticktime) # returns the accel boids[i].pos = complex(boi
ds[i].pos.real % screenx, boids[i].pos.imag % screeny) # wrap around # draw the acceleration vector #thisarect = pygame.draw.aaline(background, (0,0,255), (boids[i].pos.real, boids[i].pos.imag), # (boids[i].pos.real + boidaccel.real, boids[i]....
gmimano/commcaretest
corehq/apps/commtrack/tests/test_sms_reporting.py
Python
bsd-3-clause
9,297
0.003442
from datetime import datetime from casexml.apps.stock.models import StockReport, StockTransaction from corehq.apps.commtrack.const import RequisitionStatus from corehq.apps.commtrack.models import RequisitionCase from casexml.apps.case.models import CommCareCase from corehq.apps.commtrack.tests.util import CommTrackTes...
[req_r
ef] = spp.reverse_indices req_case = RequisitionCase.get(req_ref.referenced_id) self.assertEqual(str(amt), req_case.amount_requested) self.assertEqual(self.user._id, req_case.requested_by) self.assertEqual(req_case.location_, self.sp.location_) self.assertTrue...
dserv01/SyncLosslessToLossyMusicLibrary
SyncLosslessToLossyMusicLibrary.py
Python
gpl-2.0
6,785
0.005601
__author__ = 'Dominik Krupke, dserv01.de' # # While you want to listen to lossless music on your computer you may not be able to also listen to it mobile because # it takes too much space. A 32GB-SDCard does not suffice for your full music library so you only have the options to # either only hearing to a subset mobil...
OMMANDS = [['flac', 'ogg', 'oggenc -q 8 [INPUT].flac -o [OUTPUT].ogg'], ['mp3', 'mp3', 'cp [INPUT].mp3 [OUTPUT].mp3'] # ,['jpg', 'jpg', 'cp [INPUT].jpg [OUTPUT].jpg'] ] # Remove files that are not in the original library SYNC_DE
LETIONS = True ASK_BEFORE_DELETE = False ############################################################################################################### # Check if vorbis-tools are installed output = subprocess.check_output("whereis oggenc", shell=True) if (len(output) < 10): print "You need to install vorbis-too...
tiagocoutinho/bliss
bliss/tango/servers/nanobpm_ds.py
Python
lgpl-3.0
19,010
0.00526
# -*- coding: utf-8 -*- # # This file is part of the bliss project # # Copyright (c) 2016 Beamline Control Unit, ESRF # Distributed under the GNU LGPLv3. See LICENSE for more info. import sys import time import numpy import struct import logging import threading # tango imports import tango from tango import GreenMod...
String[self._acqMode]) attr = self.get_devic
e_attr().get_attr_by_name("imageDepth") attr.set_write_value(self.imageDepth2String[self._imageDepth]) if self._nanoBpm is not None: attr = self.get_device_attr().get_attr_by_name("gain") attr.set_write_value(self._nanoBpm.GAIN) attr = self.get_device_attr().get_attr_...
openpli-arm/enigma2-arm
lib/python/Plugins/Extensions/FactoryTest/NetworkTest.py
Python
gpl-2.0
16,179
0.033191
import os import re from os import system, popen, path as os_path, listdir from Screens.Screen import Screen from Components.Harddisk import * from Components.Sources.StaticText import StaticText from Components.ActionMap import ActionMap, NumberActionMap from FactoryTestPublic import * import time from enigma import ...
ion="-10" size="1100,605" pixmap="DMConcinnity-HD-Transp/menu/setupbg.png" /> <widget source="global.CurrentTime" render="Label
" position="20,20" size="80,25" font="Regular;23" foregroundColor="black" backgroundColor="grey" transparent="1"> <convert type="ClockToText">Default</convert> </widget> <widget source="global.CurrentTime" render="Label" position="110,20" size="140,25" font="Regular;23" foregroundColor="blue" backgroundColor=...
biomodels/BIOMD0000000370
BIOMD0000000370/model.py
Python
cc0-1.0
427
0.009368
import os path = os.path.dirname(os.path.realpath(__file__)) sbmlFilePath = os.path.join(path, 'BIOMD0000000370.xml') with open(sbmlFilePath,'r') as
f: sbmlString = f.read() def module_exists(module_name)
: try: __import__(module_name) except ImportError: return False else: return True if module_exists('libsbml'): import libsbml sbml = libsbml.readSBMLFromString(sbmlString)
weixsong/algorithm
leetcode/10.py
Python
mit
1,638
0.002463
#!/usr/bin/env python """ Regular Expression Matching Implement regular expression matching with support for '.' and '*'. '.' Matches any single character. '*' Matches zero or more of the preceding element. The matching should cover the entire input string (not partial). The function prototype should be: bool isMatc...
".*") → tr
ue isMatch("aab", "c*a*b") → true """ class Solution(object): """ O(n^2) """ def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ m, n = len(p), len(s) table = [[False for j in xrange(n + 1)] for i in xrange(m + 1)] ta...
cupy/cupy
examples/stream/thrust.py
Python
mit
412
0
# nvprof --print-gpu-trace python examples/stream/thrust.py import cupy x =
cupy.array([1, 3, 2]) expected = x.sort() cupy.cuda.Device().synchronize() stream = cupy.cuda.stream.Stream() with stream: y = x.sort() stream.synchronize() cupy.testing.assert_array_equal(y, expected
) stream = cupy.cuda.stream.Stream() stream.use() y = x.sort() stream.synchronize() cupy.testing.assert_array_equal(y, expected)
sernst/cauldron
cauldron/cli/server/run.py
Python
mit
4,787
0
import logging import os import site import time import typing from argparse import ArgumentParser import waitress from flask import Flask import cauldron as cd from cauldron import environ from cauldron import templating from cauldron.render.encoding import ComplexFlaskJsonEncoder from cauldron.session import writin...
port: int = 5010, debug: bool = False, public: bool = False, host=None, authentication_code: str = '',
quiet: bool = False, **kwargs ) -> dict: """...""" if kwargs.get('version'): environ.log('VERSION: {}'.format(environ.version)) return environ.systems.end(0) if host is None and public: host = '0.0.0.0' server_data['host'] = host server_data['port'] = port ser...
milkey-mouse/swood
swood/complain.py
Python
mit
4,905
0.003262
"""User-friendly exception handler for swood.""" import http.client import traceback import sys import os __file__ = os.path.abspath(__file__) class ComplainToUser(Exception): """When used with ComplaintFormatter, tells the user what error (of theirs) caused the failure and exits.""" pass def can_submit():...
return False elif not can_submit(): print( "Something went wrong. A bug report will not be sent because of
your config setting.", file=sys.stderr) return False else: print( "Something went wrong. A bug report will be sent to help figure it out. (see --optout)", file=sys.stderr) try: conn = http.client.HTTPSConnection("meme.in...
mganeva/mantid
Testing/SystemTests/tests/analysis/EQSANSFlatTestAPIv2.py
Python
gpl-3.0
3,330
0.001201
# Mantid Repository : https://github.com/mantidproject/mantid # # Copyright &copy; 2018 ISIS Rutherford Appleton Laboratory UKRI, # NScD Oak Ridge National Laboratory, European Spallation Source # & Institut Laue - Langevin # SPDX - License - Identifier: GPL - 3.0 + #pylint: disable=no-init,attribute-defined-ou...
s meant to be run at SNS and takes a long time. It is used to verify that the complete reduction chain works and reproduces reference results. """ configI = ConfigService.Instance() configI["facilityName"]='SNS' EQSANS() S
olidAngle() DarkCurrent(FILE_LOCATION+"EQSANS_5704_event.nxs") TotalChargeNormalization(beam_file="bl6_flux_at_sample") AzimuthalAverage(n_bins=100, n_subpix=1, log_binning=False) IQxQy(nbins=100) UseConfigTOFTailsCutoff(True) PerformFlightPathCorrection(True) Use...
dajohnso/cfme_tests
utils/workloads.py
Python
gpl-2.0
3,720
0.008602
"""Functions for workloads.""" from utils.conf import cfme_performance def get_capacity_and_utilization_replication_scenarios(): if 'test_cap_and_util_rep' in cfme_performance.get('tests', {}).get('workloads', []): if (cfme_performance['tests']['workloads']['test_cap_and_util_rep']['scenarios'] and ...
']['test_provisioning']['scenarios'] and len(cfme_performance['tests']['workloads']['test_provisioning']['scenarios']) > 0): return cfme_performance['tests']['workloads']['test_provisioning']['scenarios'] return [] def get_refresh_providers_scenarios(): if 'test_refresh_providers' ...
', {}).get('workloads', []): if (cfme_performance['tests']['workloads']['test_refresh_providers']['scenarios'] and len( cfme_performance['tests']['workloads']['test_refresh_providers']['scenarios']) > 0): return cfme_performance['tests']['workloads']['test_refresh_provide...
Ingenico-ePayments/connect-sdk-python2
ingenico/connect/sdk/domain/payment/definitions/customer_account.py
Python
mit
10,943
0.005209
# -*- coding: utf-8 -*- # # This class was auto-generated from the API references found at # https://epayments-api.developer-ingenico.com/s2sapi/v1/ # from ingenico.connect.sdk.data_object import DataObject from ingenico.connect.sdk.domain.payment.definitions.customer_account_authentication import CustomerAccountAuthen...
self.has_forgotten_password is not None: dictionary['hasForgottenPassword'] = self.has_forgotten_password if self.has_password is not None: dictionary['hasPassword'] = self.has_password if self.password_change_date is not None: dictionary['passwordChangeDate'] = self...
d_changed_during_checkout is not None: dictionary['passwordChangedDuringCheckout'] = self.password_chang
hazelnusse/sympy-old
sympy/printing/gtk.py
Python
bsd-3-clause
498
0.008032
from sympy import Basic from sympy.printing.mathml import mathml import tempfile import os def print_gtk(x, start_viewer=True):
"""Print to Gtkmathview, a gtk widget capable of rendering MathML. Needs libgtkmathview-bin""" from sympy.utilities.mathml import c2p tmp = tempfile.mktemp() # create a temp file to store the result file = open(tmp, 'wb') file.write( c2p(mathml(x), simple=True) ) file.clo
se() if start_viewer: os.system("mathmlviewer " + tmp)
HERA-Team/hera_mc
alembic/versions/5feda4ca9935_add_rtp_task_multiple_process_event_table.py
Python
bsd-2-clause
1,093
0.000915
"""Add rtp_task_multiple_process_event table Revision ID: 5feda4ca9935 Revises: 9d9af47e64c8 Create Date: 2021-09-30 16:22:30.118641+00:00 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = "5feda4ca9935" down_revision = "...
me", sa.Text(), nullable=False), sa.Column( "event", sa.Enum( "started", "finished", "error", name="rtp_task_multiple_process_enum" ), nullable=False, ), sa.ForeignKeyConstraint( ["obsid_start"], ["hera_obs.o...
rtp_task_multiple_process_event")
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_08_01/operations/_azure_firewalls_operations.py
Python
mit
26,909
0.004645
# 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 ...
rewall_name=azure_firewall_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}...
ze.url("resource_group_name", resource_group_name, 'str'), 'azureFirewallName': self._serialize.url("azure_firewall_name", azure_firewall_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is Tru...
regilero/HTTPWookiee
httpwookiee/http/client.py
Python
gpl-3.0
6,832
0.000146
#!/usr/bin/env python # -*- coding: utf-8 -*- # from httpwookiee.config import ConfigFactory from httpwookiee.core.tools import Tools, outmsg, inmsg from httpwookiee.http.parser.responses import Responses import socket import ipaddress import ssl import six class ClosedSocketError(Exception): """Raise this when...
NG Delayed ({0}) =====>'.format(msglen)) # hopefully we do not use strange bytes in delayed chunks for now Tools.print_message(six.text_type(msg), cleanup=True) try: self._socket_send(msg) except socket.error as errms
g: outmsg('#<====ABORTED COMMUNICATION WHILE' ' SENDING (delayed) ' '{0}\r\n#{1}'.format(six.text_type(msg), errmsg)) return def read_all(self, timeout=None, buffsize=None): """Read all...
acshi/osf.io
api_tests/base/test_versioning.py
Python
apache-2.0
6,291
0.003656
from nose.tools import * # flake8: noqa from api.base import settings from tests.base import ApiTestCase # The versions below are specifically for testing purposes and do not reflect the actual versioning of the API. # If changes are made to this list, or to DEFAULT_VERSION, please reflect those changes in: # api/...
etUp(self): super(TestBaseVersioning, self).setUp() def test_url_path_version(self): res = self.app.get(self.valid_url_path_version_url) assert_equal(res.status_code, 200) assert_equal(res.json['meta']['version'], self.valid_url_path_version)
def test_header_version(self): headers = {'accept': 'application/vnd.api+json;version={}'.format(self.valid_header_version)} res = self.app.get(self.valid_url_path_version_url, headers=headers) assert_equal(res.status_code, 200) assert_equal(res.json['meta']['version'], self.valid_hea...
alvinkatojr/django-db-log
djangodblog/models.py
Python
bsd-3-clause
5,442
0.006248
from django.conf import settings as dj_settings from django.db import models, transaction from django.core.signals import got_request_exception from django.http import Http404 from django.utils.encoding import smart_unicode from django.utils.translation import ugettext_lazy as _ from djangodblog import settings from d...
f): return self.data.get('url'
) or self.url full_url.short_description = _('url') full_url.admin_order_field = 'url' def error(self): message = smart_unicode(self.message) if len(message) > 100: message = message[:97] + '...' if self.class_name: return "%s: %s" % (self.class_name, mes...
iulian787/spack
var/spack/repos/builtin/packages/py-nest-asyncio/package.py
Python
lgpl-2.1
633
0.004739
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for detai
ls. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) class PyNestAsyncio(PythonPackage): """Patch asyncio to allow nested event loops.""" homepage = "https://github.com/erdewit/nest_asyncio" url = "https://pypi.io/packages/source/n/nest-asyncio/nest_asyncio-1.4.0.tar.gz" version('1.4.0', sha256...
setuptools', type='build')
zackurtz/box-maker
boxmaker.py
Python
gpl-3.0
10,763
0.047849
#! /usr/bin/env python ''' Generates Inkscape SVG file containing box components needed to create several different types of laser cut tabbed boxes. Derived from original version authored by elliot white - [email protected] This program is free software: you can redistribute it and/or modify it under the terms of the GN...
((x,y), (d,a), (-b,a), -thickness if a else thickness, dx, (1,0), a)) # side a drawS(self.tabbed_side((x+dx,y), (-b,a), (-b,-c), thickness if b else -thickness, dy, (0,1), b)) # side b drawS(self.tabbed_side((x+dx,y+dy), (-
b,-c), (d,-c), thickness if c else -thickness, dx, (-1,0), c)) # side c drawS(self.tabbed_side((x,y+dy), (d,-c), (d,a), -thickness if d else thickness, dy, (0,-1), d)) # side d def effect(self): global parent, nomTab, equalTabs, correction # Get access to main SVG document element and get it...
robocomp/learnbot
learnbot_dsl/functions/perceptual/camera/is_center_blue_line.py
Python
gpl-3.0
418
0.028708
from __f
uture__ import print_function, absolute_import import cv2 import numpy as np import sys, os path = os.path.dirname(os.path.realpath(__file__)) sys.path.append(path) import visual_auxiliary as va def is_center_blue_line(lbot): frame = lbot.getImage() if frame is not None: rois = va.detect_blue_line(frame) maxInd...
ue return False
hanfang/glmnet_python
glmnet_python/elnet.py
Python
gpl-2.0
8,525
0.029795
# -*- coding: utf-8 -*- """ Internal function called by glmnet. See also glmnet, cvglmnet """ # import packages/methods import scipy import ctypes from loadGlmLib import loadGlmLib def elnet(x, is_sparse, irs, pcs, y, weights, offset, gtype, parm, lempty, nvars, jd, vp, cl, ne, nx, nlam, flmin, ulam, ...
ia[0:ninmax] - 1 # ia is 1-indexed in fortran oja = scipy.argsort(ja) ja1 = ja[oja] beta = scipy.zeros([nvars, lmu], dtype = scipy.float64) beta[ja1, :] = ca[oja, :]
else: beta = scipy.zeros([nvars, lmu], dtype = scipy.float64) df = scipy.zeros([1, lmu], dtype = scipy.float64) fit = dict() fit['a0'] = a0 fit['beta'] = beta fit['dev'] = rsq fit['nulldev'] = nulldev fit['df']= df fit['lambdau'] = alm fit['npasses'] = nlp_r.value ...
ad-m/pru
pru/blog/views.py
Python
bsd-3-clause
1,186
0
from django.shortcuts import get_object_or_404 from django.views.generic import DetailView, ListView from braces.views import OrderableListMixin from .models import Post, Tag ORDER_FIELD = {'title': 'title'} class PermissionMixin(object): def get_queryset(self, *args, **kwargs): qs = super(PermissionMix...
gs: self.tag = get_object_or_404(Tag, slug=self.kwargs['tag_slug']) qs = qs.filter(tags__in=self.tag) return qs def g
et_context_data(self, **kwargs): context = super(PostListView, self).get_context_data(**kwargs) if hasattr(self, 'tag'): self.context['object'] = self.tag return context
Ryan-Amaral/PyTPG
tpg_tests/test_utils.py
Python
mit
2,999
0.015005
import random import numpy as np from tpg.learner import Learner from tpg.action_object import ActionObject from tpg.program import Program from tpg.team import Team dummy_init_params = { 'generation': 0, 'actionCodes':[ 0,1,2,3,4,5,6,7,8,9,10,11 ] } dummy_mutate_params = { 'pProgMut': 0.5,...
being created by the function. For example, to test a Team you would create dummy programs and learners. But you wouldn't use the create_dummy_team function to test the creation
of a team. This is because these methods verify nothing about the init procedure of the class they're returning an object of. ''' ''' Create a dummy program with some preset values ''' def create_dummy_program(): program = Program( maxProgramLength=128, nOperations=7, nDestination...
avanzosc/avanzosc6.1
steel_quality_test/__init__.py
Python
agpl-3.0
50
0
# # Generated by the Op
en ERP m
odule recorder ! #
tchellomello/home-assistant
homeassistant/components/mobile_app/webhook.py
Python
apache-2.0
18,676
0.00075
"""Webhook handlers for mobile_app.""" import asyncio from functools import wraps import logging import secrets from aiohttp.web import HTTPBadRequest, Request, Response, json_response from nacl.secret import SecretBox import voluptuous as vol from homeassistant.components import notify as hass_notify, tag from homea...
rt attach from homeassistant.helpers.typing import HomeAssistantType from homeassistant.util.decorator import Registry from .const import ( ATTR_ALTITUDE, ATTR_APP_DATA, ATTR_APP_VERSION, ATTR_CAMERA_ENTITY_ID, ATTR_COURSE, ATTR_DEVICE_ID, ATTR_DEVICE_NAME, ATTR_EVENT_DATA,
ATTR_EVENT_TYPE, ATTR_MANUFACTURER, ATTR_MODEL, ATTR_OS_VERSION, ATTR_SENSOR_ATTRIBUTES, ATTR_SENSOR_DEVICE_CLASS, ATTR_SENSOR_ICON, ATTR_SENSOR_NAME, ATTR_SENSOR_STATE, ATTR_SENSOR_TYPE, ATTR_SENSOR_TYPE_BINARY_SENSOR, ATTR_SENSOR_TYPE_SENSOR, ATTR_SENSOR_UNIQUE_ID, ...
teampopong/crawlers
election_commission/main.py
Python
agpl-3.0
4,602
0.007388
#!/usr/bin/python2.7 # -*- encoding=utf-8 -*- from argparse import ArgumentParser, RawTextHelpFormatter import codecs import gevent from gevent import monkey import json from types import UnicodeType from crawlers import Crawler from crawlers.local.static import get_election_type_name from utils import check_dir def...
mentParser(formatter_class=RawTextHelpFormatter) parser.add_argument('target'
, choices=['assembly', 'local', 'president'],\ help="name of target election") parser.add_argument('type', choices=['candidates', 'elected', 'precandidates'], help="type of person") parser.add_argument('start', help="starting election id", type=float) parser.add_argument('end', help=...
Dhivyap/ansible
lib/ansible/modules/files/template.py
Python
gpl-3.0
2,564
0.00234
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2017, Ansible Pr
oject # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # This is a virtual module that is entirely implemented as an action plugin and runs on the controller from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata...
'supported_by': 'core'} DOCUMENTATION = r''' --- module: template version_added: historical options: follow: description: - Determine whether symbolic links should be followed. - When set to C(yes) symbolic links will be followed, if they exist. - When set to C(no) symbolic links will n...
karljakoblarsson/Rattan-Geometry
Utils.py
Python
mit
130
0.007692
import
os def run(name='test1.py'): filename = os.getcwd() + name exec(compile(open(filename).read(), filename,
'exec'))
GinoGalotti/python-selenium-utils
SeleniumPythonFramework/src/main/Pages/HomePage.py
Python
apache-2.0
710
0
from selenium.webdriver.common.by import By from SeleniumPythonFramework.src.main.Pages.CommonPage import CommonPage # Production locations TRY_TEXT = {"by": By.ID, "locator": "url-input"} TRY_BUTTON = {"by": By.ID, "locator": "get-data"} PATH = "" class HomePage(CommonPage): def __init__(se
lf, **kwargs): super(HomePage, self).__init__(page_url=PATH, **kwargs) def try_url_text(self): return self.get_element(TRY_TEXT) def try_url_button(self): return self.get_element(TRY_BUTTON) def try_url(self, url): self.try_url_text().send_keys(url) try_button = se
lf.try_url_button() with self.wait_for_page_load: try_button.click()
hugoatease/encas
errors.py
Python
gpl-3.0
2,359
0.010598
# Encas Sales Management Server # Copyright 2013 - Hugo Caille # # This file is part of Encas. # # Encas 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...
xcept MissingFieldsError as e: return jsonify(e.serialize()) except ApiError as e: return jsonify(e.serialize()) except OperationalError as e: return jsonify({'error' : True, 'reason' : "Cannot access database"}) except ValueError: return jsonify({...
r
MetaPlot/MetaPlot
metaplot/helpers.py
Python
mit
4,900
0.008776
from __future__ import print_function import os import sys import subprocess import pkg_resources try: import pkg_resources _has_pkg_resources = True except: _has_pkg_resources = False try: import svn.local _has_svn_local = True except: _has_svn_local = False def test_helper(): return...
fault) as 'SVN INFO' where the value is a string containing essentially what is returned by 'svn info'. The optional argument 'label' allows you to set the string used
as the dictionary key in the returned dictionary. """ if not _has_svn_local: print('SVN information unavailable.') print('You do not have the "svn" package installed.') print('Install "svn" from pip using "pip install svn"') return {} if svndir: repo = svn.local.Local...
hasibi/TAGME-Reproducibility
nordlys/tagme/tagme.py
Python
mit
11,198
0.001875
""" TAGME implementation @author: Faegheh Hasibi ([email protected]) """ import argparse import math from nordlys.config import OUTPUT_DIR from nordlys.tagme import config from nordlys.tagme import test_coll from nordlys.tagme.query import Query from nordlys.tagme.mention import Mention from nordlys.tagme.lu...
n, "mw_rel:", mw_rel vote += cmn * mw_rel vote /= float(len(men_cand_ens)) return vote def __get_mw_rel(self, e1, e2): """ Calculates Milne & Witten relatedness for two entities. This implementation is based on Dexter implementation (which is similar to TAGME imp...
blob/master/dexter-core/src/main/java/it/cnr/isti/hpc/dexter/relatedness/MilneRelatedness.java - TAGME: it.acubelab.tagme.preprocessing.graphs.OnTheFlyArrayMeasure """ if e1 == e2: # to speed-up return 1.0 en_uris = tuple(sorted({e1, e2})) ens_in_links = [self.__ge...
alxgu/ansible
lib/ansible/modules/windows/win_xml.py
Python
gpl-3.0
2,841
0.00176
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2018, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # this is a windows documentation stub. actual code lives in the .ps1 # file of the same name ANSIBLE_METADATA = {'metadata_version': '1.1', ...
upported_by': 'community'} DOCUMENTATION = r''' --- module: win_xml version_added: "2.
7" short_description: Add XML fragment to an XML parent description: - Adds XML fragments formatted as strings to existing XML on remote servers. - For non-Windows targets, use the M(xml) module instead. options: path: description: - The path of remote servers XML. type: path ...
jcmgray/autoray
tests/test_lazy.py
Python
apache-2.0
11,880
0
import functools import re import pytest from autoray import do, lazy, to_numpy, infer_backend, get_dtype_name, astype from numpy.testing import assert_allclose from .test_autoray import BACKENDS, gen_rand def test_manual_construct(): def foo(a, b, c): a1, a2 = a b1 = b['1'] c1, c2 = c...
andom.uniform', size=(5, 7), like='numpy') x0 = lazy.array(x[0, :]) x1 = lazy.array(x[1, :]) x2 = lazy.array(x[2, :]) x3 = lazy.array(x[3, :]) x4 = lazy.array(x[4, :]
) y = lazy.LazyArray( backend=infer_backend(x), fn=foo, args=((x0, x1), {'1': x2}), kwargs=dict(c={'sub': (x3, x4)}), shape=(7,), dtype='float64', ) assert y.deps == (x0, x1, x2, x3, x4) assert re.match( r'x\d+ = foo\d+\(\(x\d+, x\d+,\), ' ...
gisodal/cumodoro
cumodoro/main.py
Python
mit
765
0.007843
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys import os import curses import cumodoro.config as config import cumodoro.interface as interface impo
rt cumodoro.globals as globals from cumodoro.cursest import Refresher import logging log = logging.getLogger('cumodoro') def set_title(msg): print("\x1B]0;%s\x07" % msg) def get_title(): print("\x1B[23t") return sys.stdin.read() def save_title(): prin
t("\x1B[22t") def restore_title(): print("\x1B[23t") def main(): globals.refresher = Refresher() globals.refresher.start() globals.database.create() globals.database.load_tasks() os.environ["ESCDELAY"] = "25" save_title() set_title("Cumodoro") curses.wrapper(interface.main) re...
nion-software/nionswift
nion/swift/model/ApplicationData.py
Python
gpl-3.0
3,883
0.004378
""" Stores application data. """ # standard libraries import copy import json import pathlib import threading import typing # third party libraries from nion.swift.model import Utility from nion.utils import Event from nion.utils import StructuredModel class ApplicationData: """Application data is a singleton t...
]: return __application_data.get_data_dict() def set_data(d: typing.Mapping[str, typing.Any]) -> None: __application_data.set_data_dict(d) # class SessionMetadata: """Session data is a singleton that stores application data via the Appli
cationData singleton.""" def __init__(self) -> None: site_field = StructuredModel.define_field("site", StructuredModel.STRING) instrument_field = StructuredModel.define_field("instrument", StructuredModel.STRING) task_field = StructuredModel.define_field("task", StructuredModel.STRING) ...
OzFlux/PyFluxPro
scripts/constants.py
Python
gpl-3.0
4,163
0.017535
beta = 5 # "beta" value in adiabatic correction to wind profile Cd = 840.0 # heat capacity of mineral component of soil, J/kg/K Co = 1920.0 # heat capacity of organic component of soil, J/kg/K Cp = 1004.67 # specific heat of dry air at constant pressure, J/kg-K Cpd = 1004.67 # specific heat of dry air a...
ength of LI7500 IRGA, m Tb = 1800 # 30-min period, seconds C2
K = 273.15 # convert degrees celsius to kelvin # dictionary of site names and time zones tz_dict = {"adelaideriver":"Australia/Darwin", "alicespringsmulga":"Australia/Darwin", "arcturus":"Australia/Brisbane", "calperum":"Australia/Adelaide", "capetribulation":"Australia/Bri...
muffl0n/ansible-modules-extras
cloud/vmware/vca_fw.py
Python
gpl-3.0
14,207
0.011755
#!/usr/bin/python # Copyright (c) 2015 VMware, Inc. All Rights Reserved. # # 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 ...
Please check",\ valid_instances=s_json) if not vca.login_to_instance(instance=instance, password=None, token=vca.vcloud_session.token, org_url=vca.vcloud_session.org_url): module.fail_json(msg = "Error logging into org for the...
gin Failed: Please check username or password", error=vca.response.content) if not vca.login(token=vca.token): module.fail_json(msg = "Failed to get the token", error=vca.response.content) if not vca.login_to_org(service, org): module.fail_json(msg = "Failed to login to org, Plea...
Verizon/hlx
tests/blackbox/examples/bb_test_basic.py
Python
apache-2.0
1,993
0.002509
# ------------------------------------------------------------------------------ # # ------------------------------------------------------------------------------ from nose.tools import with_setup import subprocess import requests import os from .. import util import time import json # -------------------------------...
----------------------------------------------------
--- # # ------------------------------------------------------------------------------ def teardown_func(): global g_server_pid l_code, l_out, l_err = util.run_command('kill -9 %d'%(g_server_pid)) time.sleep(0.2) # ------------------------------------------------------------------------------ # # ---------...
plotly/plotly.py
packages/python/plotly/plotly/validators/histogram2d/stream/_token.py
Python
mit
499
0.002004
import _plotly_utils.basevalid
ators class TokenValidator(_plotly_utils.basevalidators.StringValidator): def __init__(self, plotly_name="to
ken", parent_name="histogram2d.stream", **kwargs): super(TokenValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), no_blank=kwargs.pop("no_blank", True), strict=kwargs.pop("strict", Tru...
brownjm/praisetex
song.py
Python
gpl-3.0
2,932
0.006139
"""New song class to work with a plain text song file format""" import os import re chord_regex = re.compile("[A-G][1-9#bminajsugd]*[/]*[A-G]*[1-9#bminajsugd]*") valid_chords = "ABCDEFGb#minajsugd123456789" not_chords = "HJKLOPQRTVWXYZ\n" class Chord(object): """Represents a single chord within a song file""" ...
())) # insert chords in verse order since insertion shifts positions of subsequent chords combined = [] chords.reverse() for chor
d in chords: loc, ch = chord combined.append(Text(lyrics[loc:])) combined.append(Chord(ch)) lyrics = lyrics[:loc] if len(lyrics) > 0: # handle any leftover text before first chord combined.append(Text(lyrics)) combined.reverse() return combined def is_chord_line(li...
fretscha/pfa
config/settings/common.py
Python
bsd-3-clause
8,513
0.000822
# -*- coding: utf-8 -*- """ Django settings for pfa project. For more information on this file, see https://docs.djangoproject.com/en/dev/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/dev/ref/settings/ """ from __future__ import absolute_import, unicode_literal...
------------------------------------------------------------ # See: https://docs.djangoproject.com/en/dev/ref/settings/#databases DATABASES = { # Raises ImproperlyConfigured exception if DATABASE_URL not in os.environ 'default': env.db("DATABASE_URL", default="postgres://localhost/pfa"), } DATABASES['default'][...
----------------------------------------------------------------------- # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # In a Windows environment this must be set to your sy...
mgaitan/waliki_flask
waliki/extensions/uploads.py
Python
bsd-3-clause
4,692
0.008316
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2013-2014, Martín Gaitán # Copyright (c) 2012-2013, Alexander Jung-Loddenkemper # This file is part of Waliki (http://waliki.nqnwebs.com/) # License: BSD (https://github.com/mgaitan/waliki/blob/master/LICENSE) #============================================...
MAIN #=================================================================
============== if __name__ == "__main__": print(__doc__)
prabodhprakash/problemsolving
spoj/EBOXES.py
Python
mit
148
0.033784
n
o_inputs = int(raw_input()) for i in range (0, no_inputs): n, k, t, f = map(int, raw_input().split()) answer = n + k*((f-n)/(k-1)) print an
swer
Kinggerm/GetOrganelle
Utilities/evaluate_assembly_using_mapping.py
Python
gpl-3.0
29,914
0.005517
#! /usr/bin/env python # coding:utf8 from argparse import ArgumentParser import os import sys PATH_OF_THIS_SCRIPT = os.path.split(os.path.realpath(__file__))[0] sys.path.insert(0,
os.path.join(PATH_OF_THIS_SCRIPT, "..")) import GetOrganelleLib from GetOrganelleLib.pipe_control_func import * from GetOrganelleLib.seq_parser import * from GetOrganelleLib.sam_parser import * from GetOrganelleLib.statistical_func import * from GetOrganelleLib.versions import get_versions PATH_OF_THIS_SCRIPT = os.pat...
import platform SYSTEM_NAME = "" if platform.system() == "Linux": SYSTEM_NAME = "linux" elif platform.system() == "Darwin": SYSTEM_NAME = "macOS" else: sys.stdout.write("Error: currently GetOrganelle is not supported for " + platform.system() + "! ") exit() GO_LIB_PATH = os.path.split(GetOrganelleLib.__...
okfde/froide-campaign
froide_campaign/migrations/0008_campaignpage.py
Python
mit
1,181
0.000847
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2016-10-18 15:02 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("froide_campaign", "0007_campaign_subject_template"), ] operations = [ migra...
("description", models.TextField(blank=True)), ("public", models.BooleanField(default=False)), ("campaigns", models.ManyToManyField(to="fro
ide_campaign.Campaign")), ], options={ "verbose_name": "Campaign page", "verbose_name_plural": "Campaign pages", }, ), ]
zamanashiq3/code-DNN
time_dis_cnn.py
Python
mit
2,449
0.02205
""" Multiple stacked lstm implemeation on the lip movement data. Akm Ashiquzzaman [email protected] Fall 2016 """ from __future__ import print_function import numpy as np np.random.seed(1337)
#random seed fixing for reproducibility #data load & preprocessing X_train = np.load('../data/videopart43.npy').astype('float32') Y_train = np.load('../data/audiopart43.npy').astype('float32') #normalizing data X_train = X_train/255 Y_train = Y_train/32767 X_train = X_train.reshape((826,13,1,53,53)).astype('float32...
ted,LSTM,Bidirectional from keras.layers import Convolution2D,Flatten,MaxPooling2D import time print("Building Model.....") model_time = time.time() model = Sequential() model.add(TimeDistributed(Convolution2D(64, 3, 3,border_mode='valid'),batch_input_shape=(14,13,1,53,53),input_shape=(13,1,53,53))) model.add(Activa...
smartforceplus/SmartForceplus
openerp/addons/project_stage/__openerp__.py
Python
agpl-3.0
1,603
0
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2015 ADHOC SA (http://www.adhoc.com.ar) # All Rights Reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Pu...
.access.csv', ], 'demo': [ ], 'test': [ ], 'installable': True, 'auto_install': False, 'application': False, } # vim:expandtab:smartindent:tabstop=4:softtab
stop=4:shiftwidth=4:
lbybee/NVLDA
code/build_dataset.py
Python
gpl-2.0
865
0.002312
from datetime import datetime import csv import pandas import os import sys os.chdir(sys.argv[1]) ticker_f = open(sys.argv[2], "rb") ticker_reader = csv.reader(ticker_f) tickers = [r[0] for r in ticker_reader][1:] tic
ker_f.close() tln = len(tickers) t_1 = datetime.now() # build full data frame res = None for i, t in enumerate(tickers): t_n = t.split("/")[1] df = pandas.io.parsers.read_csv("%s.csv" % t_n) df[t_n] = (df["Close"].shift(1) - df["Close"]) / df["Close"] df = df[["Date", t_n]] df.set_index("Date") ...
f, on="Date", how="outer") print i, i * 100. / tln, datetime.now() - t_1 res = res.dropna(axis=0, int(sys.argv[3])) # drop many missing obs res = res.dropna(axis=1, int(sys.argv[4])) # drop many missing vars res = res.dropna() res.to_csv(sys.argv[5])
nikhilponnuru/codeCrumbs
code/code_display.py
Python
mit
3,605
0.035229
#!/usr/bin/env python #want to display file contents #testing display code import pyperclip import re import subprocess import os,sys,time counter=1 already_checked='' def get_extension(file_name): if file_name.find('.')!=-1: ext = file_name.split('.') return (ext[1]) else: retu...
e.search("\'[a-z,A-Z,0-9
, ]+\'",str_lower[0]) if search_string!=None: entered_string = search_string.group() final_search_string=entered_string[1:len(entered_string)-1] try: hosts = subprocess.check_output("grep '%s' /home/nikhil/code_snippets -r" % (final_search_string...
skill-huddle/skill-huddle
dummy_data/populatedb.py
Python
mit
10,113
0.014734
import os,sys,django sys.path.append(os.path.dirname(os.path.abspath('.'))) os.environ["DJANGO_SETTINGS_MODULE"] = 'skill_huddle.settings' django.setup() from sh_app.models import SH_User,League,Suggestion,Huddle from django.contrib.auth.models import User from django_countries import countries from localflavor.us.us...
_adjs[random.randint(1,len(list_adjs))-1].strip('\n'
) + " " + list_nouns[random.randint(1,len(list_nouns))-1].strip('\n') + " huddle" address = str(random.randint(1,1000
CN-UPB/OpenBarista
utils/decaf-utils-protocol-stack/decaf_utils_protocol_stack/rpc/json_rpc_application.py
Python
mpl-2.0
7,693
0.0039
## # Copyright 2016 DECaF Project Group, University of Paderborn # This file is part of the decaf orchestration framework # All Rights Reserved. # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at htt...
outing_key, function_pointer=function_pointer, **params) def receive(self, *args, **kwargs): self._pool.apply_async(func=self._receive
, args=args, kwds=kwargs) def apply_in_pool(self, function): def apply_f(*args, **kwargs): self._pool.apply_async(func=function, args=args, kwds=kwargs) apply_f.func_name = function.func_name return apply_f def _make_handler(self, function): """ This meth...
jvanbrug/scout
functional_tests.py
Python
mit
1,460
0
import pytest from selenium import webdriver from selenium.webdriver.common.keys import Keys @pytest.fixture(scope='function') def browser(request): browser_ = webdriver.Firefox() def fin(): browser_.quit() request.addfinalizer(fin) return browser_ def test_can_show_a_relevant_code_snippet...
er') assert actual
_search_prompt == expected_search_prompt # He searches "python yield" search_box.send_keys('python yield') search_box.send_keys(Keys.ENTER) # The page updates, and now the page shows a code snippet # that uses the dummy variables "mylist" and "mygenerator" # (the highest-voted python page on S...
tkaitchuck/nupic
examples/prediction/experiments/confidenceTest/2/description.py
Python
gpl-3.0
2,040
0.005392
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have purchased from # Numenta, Inc. a separate commercial license for this software code, the # following terms and conditions apply: # # This pro...
------------------------------------- """ Tests the following set of sequences: z-a-b-c: (1X) a-b-c: (6X) a-d-e: (2X) a-f-g-a-h: (1X) We want to insure that when we see 'a', that we predict 'b' with highest confidence, then 'd', then 'f' and 'h' with equally low confidence. We expect the following pre...
: 1.0 inputPredScore_at3 : 1.0 inputPredScore_at4 : 1.0 """ from nupic.frameworks.prediction.helpers import importBaseDescription config = dict( sensorVerbosity=0, spVerbosity=0, tpVerbosity=0, ppVerbosity=2, fi...
gaeun/open-event-orga-server
app/api/tracks.py
Python
gpl-3.0
3,167
0.000316
from flask.ext.restplus import Namespace from app.models.track import Track as TrackModel from .helpers import custom_fields as fields from .helpers.helpers import ( can_create, can_update, can_delete, requires_auth ) from .helpers.utils import PAGINATED_MODEL, PaginatedResourceBase, ServiceDAO, \ ...
@can_create(DAO) @api.doc('create_track', responses=POST_RESPONSES) @api.marshal_with(TRACK) @api.expect(TRACK_POST) def post(self, event_id): """Create a track""" retu
rn DAO.create( event_id, self.api.payload, self.api.url_for(self, event_id=event_id) ) @api.route('/events/<int:event_id>/tracks/page') class TrackListPaginated(Resource, PaginatedResourceBase): @api.doc('list_tracks_paginated', params=PAGE_PARAMS) @api.header(*ETAG...
robwarm/gpaw-symm
doc/documentation/tddft/Be_8bands_lrtddft_dE.py
Python
gpl-3.0
218
0.004587
from gpaw import GPAW from gpaw.lrtddft import LrTDDF
T c = GPAW('Be_gs_8bands.gpw') dE = 10 # maximal Kohn-Sham transition energy to consider in eV lr = LrTDDFT(c, xc='LDA', energy_range=dE) lr.writ
e('lr_dE.dat.gz')
EmreAtes/spack
lib/spack/spack/test/sbang.py
Python
lgpl-2.1
6,406
0.001405
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, [email protected], All rights reserved. # LLNL-CODE-64...
ANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with thi
s program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## """\ Test that Spack's shebang filtering works correctly. """ import os import stat import pytest import tempfile import ...
pylover/khayyam
khayyam/tests/test_algorithms.py
Python
gpl-3.0
4,401
0.002954
# -*- coding: utf-8 -*- import unittest from khayyam import algorithms_c as alg_c from khayyam import algorithms_pure as alg_p __author__ = 'vahid' # TODO: test with negative values class TestCAlgorithms(unittest.TestCase): def test_get_julian_day_from_gregorian(self): self.assertRaises(ValueError, alg_p...
alg_c.get_julian_day_from_gregorian_date, 2016, 2, 30) self.assertRaises(ValueError, alg_c.get_julian_day_from_gregorian_date, 2015, 2, 29) self.assertRaises(ValueError, alg_c.get_julian_day_from_gregorian_date, -4713, 2, 30)
self.assertRaises(ValueError, alg_c.get_julian_day_from_gregorian_date, -4713, 2, 29) self.assertEqual( alg_c.get_julian_day_from_gregorian_date(-4713, 11, 25), alg_p.get_julian_day_from_gregorian_date(-4713, 11, 25) ) for i in range(3000): self.assertEqual(...
idealabasu/code_pynamics
python/pynamics/integration.py
Python
mit
1,030
0.017476
import pynamics import numpy import logging logger = logging.getLogger('pynamics.integration') def integrate(*args,**kwargs):
if pynamics.integrator==0: return integrate_odeint(*args,**kwargs) elif pynamics.integrator==1: newargs = args[0],args[2][0],args[1],args[2][-1] return integrate_rk(*newargs ,**kwargs) def integrate_odeint(*arguments,**keyword_arguments): import scipy.integrate ...
integration') return result def integrate_rk(*arguments,**keyword_arguments): import scipy.integrate logger.info('beginning integration') try: result = scipy.integrate.RK45(*arguments,**keyword_arguments) y = [result.y] while True: result.step() ...
Hexadorsimal/pynes
nes/__init__.py
Python
mit
73
0
from .nes import N
es from .bus
.devices.cartridge import CartridgeFactory
gptech/ansible
lib/ansible/modules/packaging/os/apt.py
Python
gpl-3.0
35,672
0.003644
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2012, Flowroute LLC # Written by Matthew Williams <[email protected]> # Based on yum module written by Seth Vidal <skvidal at fedoraproject.org> # # This module is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public Lic...
ce-confdef" -o "Dpkg::Options::=--force-confold"' - Options should be supplied as comma separated list required: false default: 'force-confdef,force-confold' deb: description: - Path to a .deb package on the remote machine. - If :// in the path, ansible will attempt to download deb be...
se version_added: "1.6" autoremove: description: - If C(yes), remove unused dependency packages for all module states except I(build-dep). It can also be used as the only option. required: false default: no choices: [ "yes", "no" ] aliases: [ 'autoclean'] version_added: "2.1" only...