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
2ndy/RaspIM
usr/lib/python2.6/lib2to3/fixer_util.py
Python
gpl-2.0
14,225
0.002812
"""Utility functions, node construction macros, etc.""" # Author: Collin Winter # Local imports from .pgen2 import token from .pytree import Leaf, Node from .pygram import python_symbols as syms from . import patcomp ########################################################### ### Common node-construction "macros" ##...
umber(n, prefix=None): return Leaf(token.NUMBER, n, prefix=prefix) def Subscript(index_node): """A numeric or string subscript""" return Node(syms.trailer, [Leaf(token.LBRACE, u'['), index_node, Leaf(token.RBRACE, u']')]) def String(string, pre...
ing, prefix=prefix) def ListComp(xp, fp, it, test=None): """A list comprehension of the form [xp for fp in it if test]. If test is None, the "if test" part is omitted. """ xp.prefix = u"" fp.prefix = u" " it.prefix = u" " for_leaf = Leaf(token.NAME, u"for") for_leaf.prefix = u" " i...
toastdriven/alligator
alligator/gator.py
Python
bsd-3-clause
10,077
0
from .constants import ALL from .tasks import Task from .utils import import_attr class Gator(object): def __init__( self, conn_string, queue_name=ALL, task_class=Task, backend_class=None ): """ A coordination for scheduling & processing tasks. Handles creating tasks (with opt...
to process Returns: Task: The canceled ``Task`` instance """ data = self.backend.get(self.queue_name, task_id) if data: task = self.task_class.deserialize(data) task.to_canceled() return task def execute(self, task): """ ...
task.to_call(add, 101, 35) finished_task = gator.execute(task) Args: task_id (str): The identifier of the task to process Returns: Task: The completed ``Task`` instance """ try: return task.run() except Exception: ...
jordanemedlock/psychtruths
temboo/core/Library/Utilities/XML/__init__.py
Python
apache-2.0
319
0.00627
from temboo.Library.Utilities.XML.GetValuesFromXML import GetValues
FromXML, GetValuesFromXMLInputSet, GetValuesFromXMLResultSet, GetValuesFromXMLChoreographyExecution from te
mboo.Library.Utilities.XML.RunXPathQuery import RunXPathQuery, RunXPathQueryInputSet, RunXPathQueryResultSet, RunXPathQueryChoreographyExecution
andreafrittoli/eowyn
eowyn/api.py
Python
apache-2.0
4,364
0.000229
# Copyright 2015 Andrea Frittoli <andrea.frittoli@gmail.com> # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
ase of duplicated configs, the last one wins manager_configs = {k: v for (k, v) in manager_configs} # Other configs debug = config.get('default', 'debug') except IndexError: # Or else use defaults debug = False manager_type = 'redis' manager_configs = {'host':...
ug) if __name__ == '__main__': main()
stevecassidy/pyunitgrading
tests/bad/single/43684882/comp249-psst-starter-master/users.py
Python
bsd-3-clause
815
0.008589
""" @author: """ import bottle # this variable MUST be used as the name for the cookie used by this application COOKIE_
NAME = 'sessionid' def check_login(db, usernick, password): """returns True if password matches stored""" def generate_session(db, usernick): """create a new session and add a cookie to the request object (bottle.request) user must be a valid user in the databas
e, if not, return None There should only be one session per user at any time, if there is already a session active, use the existing sessionid in the cookie """ def delete_session(db, usernick): """remove all session table entries for this user""" def session_user(db): """try to retrieve t...
mzdanieltest/pex
tests/test_bdist_pex.py
Python
apache-2.0
1,373
0.00874
# Copyright 2016 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import os import subprocess import sys from textwrap import dedent from twitter.common.contextutil import pushd from pex.testing import temporary_content def assert_entry_points(entry_...
: with pushd(project_dir): subprocess.check_call([sys.executable, 'setup.py', 'bdist_pex']) process = subproces
s.Popen([os.path.join(project_dir, 'dist', 'my_app-0.0.0.pex')], stdout=subprocess.PIPE) stdout, _ = process.communicate() assert 0 == process.returncode assert stdout == b'hello world!\n' def test_entry_points_dict(): assert_entry_points({'console_scripts': ['my_a...
scikit-build/scikit-ci
ci/utils.py
Python
apache-2.0
1,327
0
# -*- coding: utf-8 -*- """This module defines functions generally useful in scikit-ci.""" import os from .constants import SERVICES, SERVICES_ENV_VAR def current_service(): for service, env_var in SERVICES_ENV_VAR.items(): if os.environ.get(env_var, 'false').lower() == 'true': return servi...
{} are set " "to 'true' or 'True'".format(", ".join(SERVICES_ENV_VAR.values())) ) def current_operating_system(service): return os.environ[SERVICES[service]] if SERVICES[service] else None def indent(text, prefix, predicate=None): """Adds 'prefix' to the beginning of selected lines
in 'text'. If 'predicate' is provided, 'prefix' will only be added to the lines where 'predicate(line)' is True. If 'predicate' is not provided, it will default to adding 'prefix' to all non-empty lines that do not consist solely of whitespace characters. Copied from textwrap.py available in pytho...
KirillMysnik/obs-ws-rc
examples/2. Make requests/make_requests.py
Python
mit
1,156
0
"""Example shows how to send requests and get responses.""" import asyncio from obswsrc import OBSWS from obswsrc.requests import ResponseStatus, StartStreamingRequest from obswsrc.types import Stream, StreamSettings async def main(): async with OBSWS('localhost', 4444, "password") as obsws: #
We can send an empty StartStreaming request (in that case the plugin # will use OBS configuration), but let's provide some settings as well stream_settings = StreamSettings( server="rtmp://example.org/my_application", key="secret_stream_key", use_auth=False ) ...
, type="rtmp_custom", ) # Now let's actually perform a request response = await obsws.require(StartStreamingRequest(stream=stream)) # Check if everything is OK if response.status == ResponseStatus.OK: print("Streaming has started") else: ...
Rustem/toptal-blog-celery-toy-ex
celery_uncovered/tricks/utils.py
Python
mit
347
0
from json import loads import codecs import environ FIXTURE_PATH = (environ.Path(__file__) - 1).path('fixtures') def read_json(fpath): with codec
s.open(fpath, 'rb', encoding='utf-8') as fp: return loads(fp.read()) def read_fixture(*subpath): fixture_file = str(FIXTURE_PATH.path(*subpath)) return read_js
on(fixture_file)
bastings/neuralmonkey
neuralmonkey/runners/beamsearch_runner.py
Python
bsd-3-clause
5,107
0.000587
from typing import Callable, List, Dict, Optional import numpy as np from typeguard import check_argument_types from neuralmonkey.model.model_part import ModelPart from neuralmonkey.decoders.beam_search_decoder import (BeamSearchDecoder, SearchStepOutput) from ne...
postprocess: Callable[
[List[str]], List[str]]=None ) -> List[BeamSearchRunner]: """A list of beam search runners for a range of ranks from 1 to max_rank. This means there is max_rank output series where the n-th series contains the n-th best hypothesis from the beam search. Args: outp...
mrniranjan/python-scripts
reboot/practice6.py
Python
gpl-2.0
149
0.033557
class MyStuff(object): def __init__(self): self.tang
erine = "And now a thousand years between" def apple(s
elf): print "I am classy apples!"
bigswitch/neutron
neutron/tests/functional/agent/test_ovs_flows.py
Python
apache-2.0
19,181
0.000209
# Copyright (c) 2015 Mirantis, 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 requir...
_spoof_for_port(self.src_p.name, [self.src_addr]) self._setup_arp_spoof_for_port(self.dst_p.name, [self.dst_addr]) self.src_p.addr.add('%s/24' % self.src_addr) self.dst_p.addr.add('%s/24' % self.dst_addr) net_helpers.assert_ping(self.src_namespace, self.dst_addr, count=2) def test_m...
rc_p.name, [self.src_addr]) self._setup_arp_spoof_for_port(self.dst_p.name, [self.dst_addr]) self.src_p.addr.add('%s/24' % self.src_addr) self.dst_p.addr.add('%s/24' % self.dst_addr) net_helpers.assert_ping(self.src_namespace, self.dst_addr, count=2) # changing the allowed mac sh...
nickofbh/kort2
app/dashboard/views.py
Python
mit
1,414
0.019095
from app.app_and_db import app from flask import Blueprint, jsonify, render_template import datetime import random import requests dashboard = Blueprint('dashboard', __name__) cumtd_endpoint = 'https://developer.cumtd.com/api/{0}/{1}/{2}' cumtd_endpoint = cumtd_endpoint.format('v2.2', 'json', 'GetDeparturesByStop') ...
l', image_number=random.randrange(1, 9), time=time) #Quer
y no more than once a minute @dashboard.route('/bus') def bus_schedule(): params = {'key' : app.config['CUMTD_API_KEY'], 'stop_id' : 'GRN4TH', 'count' : '5'} response = requests.get(cumtd_endpoint, params=params) json = response.json() departures = [] for departure in json['departures'...
edespino/gpdb
gpAux/gpdemo/gpsegwalrep.py
Python
apache-2.0
24,714
0.005422
#! /usr/bin/env python """ Initialize, start, stop, or destroy WAL replication mirror segments. ============================= DISCLAIMER ============================= This is a developer tool to assist with development of WAL replication for mirror segments. This tool is not meant to be used in production. It is sug...
user = subprocess.check_output(["whoami"]).rstrip('\n') initThreads = [] for segconfig in self.segconfigs: assert(segconfig.content != GpSegmentConfiguration.MASTER_CONTENT_ID) if self.init: assert(segconfig.role == GpSegmentConfiguration.ROLE_PRIMARY) ...
self.initThread, args=(segconfig, user)) thread.start() initThreads.append(thread) for thread in initThreads: thread.join() class StartInstances(): ''' Start a greenplum segment ''' def __init__(self, cluster_config, host, wait=False): self.clusterconfig = ...
dionaea-honeypot/dionaea
modules/python/dionaea/echo.py
Python
gpl-2.0
1,366
0.012445
# This file is part of the dionaea honeypot # # SPDX-FileCopyrightText: 2009 Paul Baecher
& Markus Koetter & Mark Schloesser # # SPDX-License-Identifier: GPL-2.0-or-later from dionaea.core import connection class echo(connection): def __init__ (self, proto=None): print("echo init") connection.__init__(self,proto) self.timeouts.idle = 5. self.timeouts.sustain = 10. de...
print("self {:s} {:s}:{:d} -> {:s}:{:d}".format(self.protocol, self.local.host,self.local.port, self.remote.host,self.remote.port)) def handle_established(self): print("new connection to serve!") self.send('welcome to reverse world!\n') d...
konstantinoskostis/sqlalchemy-utils
sqlalchemy_utils/types/ltree.py
Python
bsd-3-clause
3,375
0
from __future__ import absolute_import from sqlalchemy import types from sqlalchemy.dialects.postgr
esql import ARRAY from sqlalchemy.dialects.postgresql.base import ischema_names, PGTypeCompiler from sqlalchemy.sql import expression from ..primitives import Ltree from .scalar_coercible import ScalarCoercible class LtreeType(types.Concatenable, types.UserDefinedType, ScalarCoercible): """Postgresql LtreeType t...
hierarchial tree-like structure. For more detailed information please refer to http://www.postgresql.org/docs/current/static/ltree.html :: from sqlalchemy_utils import LtreeType class DocumentSection(Base): __tablename__ = 'document_section' id = sa.Column(sa.Integer...
agendaTCC/AgendaTCC
tccweb/apps/website/urls.py
Python
gpl-2.0
603
0.008292
from django.conf.urls import patterns, url from django.views.generic import Tem
plateView from django.contrib.auth.decorators import login_required, user_passes_test urlpatterns = patterns('', url(r'^$', 'website.views.index', name='website_index'), url(r'^termos/$',TemplateView.as_view(template_name='website/termos_de_uso.html'), name='website_termos'),
url(r'^sobre/$', TemplateView.as_view(template_name='website/sobre.html'), name='website_sobre'), url(r'^relatorios/$', login_required(TemplateView.as_view(template_name='website/relatorios.html')), name='website_relatorios'), )
jw/imagery
imagery/impart/migrations/0005_auto_20170117_0922.py
Python
mit
621
0
# -*- codi
ng: utf-8 -*- # Generated by Django 1.10.4 on 2017-01-17 09:22 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [("impart", "0004_auto_20170117_0916")] operations = [ migrations.Al...
", name="artist", field=models.ForeignKey( blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to="impart.Artist", ), ) ]
zsiciarz/django-pgallery
tests/factories.py
Python
mit
805
0
from django.conf import settings import factory from pgallery.models import Gallery, Photo class UserFactory(factory.django.DjangoModelFactory): username = factory
.Sequence(lambda n: "user_%d" % n) email = factory.Sequence(lambda n: "user_%d@example.com" % n) class Meta: model = settings.AUTH_USER_MODEL class GalleryFactory(factory.django.DjangoModelFactory): author = factory.SubFactory(UserFactory) slug = factory.Sequence(lambda n: "gallery_%d" % n) ...
lery class PhotoFactory(factory.django.DjangoModelFactory): gallery = factory.SubFactory(GalleryFactory) author = factory.LazyAttribute(lambda obj: obj.gallery.author) image = factory.django.ImageField(width=1024, height=768) class Meta: model = Photo
dssg/energywise
Code/clean_brecs.py
Python
mit
947
0.01056
from utils import * import sys def clean_rec(d): kwhs, kwhs_oriflag = d["kwhs"] temps, temps_oriflag = d["temps"] for i in range(len(temps_oriflag)): t = temps[i] if t < -60: temps_oriflag[i] = False #Ain't no way that reading's real temps[i] = 0 for i in range...
emps, temps_oriflag) d["kwhs"] = (kwhs, kwhs_oriflag) if __name__ == "__main__": args = sys.argv if len(args) > 1: the_year = int(args[1]) brecs, desc = qload("state_b_records_" + str(the_y
ear) + "_updated_with_temps.pkl") for d in brecs: clean_rec(d) qdump((brecs, desc + "(Plus we cleaned out curiously low values (noise))"), "state_b_records_" + str(the_year) + "_with_temps_cleaned.pkl")
gunan/tensorflow
tensorflow/python/types/core.py
Python
apache-2.0
1,707
0.005858
# Copyright 2020 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...
Consider adding ABC once the dependence on isinstance is reduced. # TODO(mdan): Add type annotations. class Tensor(object): """The base class of all dense Tensor objects. A dense tensor has a static data type (dtype), and may have a static rank and shape. Tensor objects are immutable. Mutable objects may be ba...
pass @property def shape(self): pass class Symbol(Tensor): """Symbolic "graph" Tensor. These objects represent the output of an op definition and do not carry a value. """ pass class Value(Tensor): """Tensor that can be associated with a value (aka "eager tensor"). These objects represent...
mattcaldwell/zipline
zipline/protocol.py
Python
apache-2.0
14,487
0
# # Copyright 2013 Quantopian, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wr...
ev
ent. This alias is intended to be temporary, to provide backwards compatibility with existing algorithms, but should be considered deprecated, and may be removed in the future. """ return self.dt def get(self, name, default=None): return self.__dict__.get(name, defa...
zmarvel/playground
sound/testplay.py
Python
mit
3,152
0.005076
import alsaaudio from math import pi, sin, pow import getch SAMPLE_RATE = 44100 FORMAT = alsaaudio.PCM_FORMAT_U8 PERIOD_SIZE = 512 N_SAMPLES = 1024 notes = "abcdefg" frequencies = {} for i, note in enumerate(notes): frequencies[note] = 440 * pow(pow(2, 1/2), i) # Generate the sine wave, centered at y=128 with 10...
ave(f*6)] #w_o5 = [x//14 for x in make_wave(f*7)] #w_o6 = [x//16 for x in make_wave(f*8)] #for i, samp in enumerate(w_o1): # w[i] += samp + w_o2[i] + w_o3[i] + w_o4[i] + w_o5[i] + w_o6[i] + 128 # print(w[i]) #buf = bytearray(w) #for i, samp in enumerate(w): # if samp > 0: ...
8 for x in make_wave(square_wave, 440)] buf = bytearray(w) char = getch.getch() last = 'q' while char != 'q': if char != last: if char == '1': w = [x//2 + 128 for x in make_wave(sine_wave, 440)] buf = bytearray(w) elif char == '2': ...
SamK/check_iftraffic_nrpe.py
setup.py
Python
gpl-3.0
524
0.015267
#!/usr/bin/env python from distutils.core import setup setup(name='check_iftraffic_nrpe', version='0.12.1', description='Nagios NRPE plugin to check Linux network traffic', scripts = ['check_iftraffic_nrpe.py'], author='Samuel Krieg', author_email='samuel.kri
eg+github@gmail.com', url='https://github.com/SamK/check_iftraffic_nrpe.py', download_url = 'https://github.com/Sa
mK/check_iftraffic_nrpe.py/tarball/0.12.1', keywords = ['nagios', 'traffic', 'nrpe', 'monitoring'] )
aabmass/CIS4301-Project-GUL
backend/loaddb/createtables.py
Python
mit
534
0.007491
#!/usr/bin/env python2 from dbutil import * def createTables(): """ Populate the array with names of sql DDL files """ for sqlFileName in ["Address.sql", "Electricity.sql", "CodeViolationsReport.sql", "FireRescueEMSResponse.sql", "NaturalGasReport.sql", "WaterRe...
format(sqlFileName.split(".sql")[0]
) except Exception as e: pass createTables()
jlcarmic/producthunt_simulator
venv/lib/python2.7/site-packages/scipy/optimize/_lsq/common.py
Python
mit
20,742
0.001736
"""Functions used by least-squares algorithms.""" from math import copysign import numpy as np from numpy.linalg import norm from scipy.linalg import cho_factor, cho_solve, LinAlgError from scipy.sparse import issparse from scipy.sparse.linalg import LinearOperator, aslinearoperator EPS = np.finfo(float).eps # Fu...
_. """ denom = s**2 + alpha p_norm = norm(suf / d
enom) phi = p_norm - Delta phi_prime = -np.sum(suf ** 2 / denom**3) / p_norm return phi, phi_prime suf = s * uf # Check if J has full rank and try Gauss-Newton step. if m >= n: threshold = EPS * m * s[0] full_rank = s[-1] > threshold else: full_rank = Fa...
pyrocko/pyrocko
src/apps/fomosto.py
Python
gpl-3.0
36,133
0
#!/usr/bin/env python # http://pyrocko.org - GPLv3 # # The Pyrocko Developers, 21st Century # ---|P------/S----------~Lg---------- from __future__ import print_function import sys import re import os.path as op import logging import copy import shutil from optparse import OptionParser from pyrocko import util, trace,...
': 'build decimated variant of a GF store', 'redeploy': 'copy traces from one GF store into another', 'view': 'view selected traces', 'extract': 'extract selected traces', 'import': 'convert Kiwi GFDB to GF store format', 'export': 'convert GF store to Kiwi GFD...
'plot travel time table', 'tttextract': 'extract selected travel times', 'tttlsd': 'fix holes in travel time tables', 'server': 'run seismosizer server', 'download': 'download GF store from a server', 'modelview': 'plot earthmodels', 'upgrade': 'upgrade stor...
10177591/BnB-bot
utils/FileDownloader.py
Python
gpl-3.0
2,539
0.002757
import logging from logging import config import paramiko import os from read_config import * class FileDownloader(object): ip = None port = None user = None password = None local_file_path = None remote_file_path = None abs_file_list = [] ssh = None logger = None...
adline().strip() if res == "1": self.list_remote_file(remote_folder + '/' + file) else: self.abs_file_list.append(remote_folder + '/' + file) def connect(self): self.ssh = paramiko.SSHClient() self.ssh.s
et_missing_host_key_policy(paramiko.AutoAddPolicy()) self.ssh.connect(self.ip, int(self.port), self.user, self.password) self.logger.info('Connect to ' + self.ip + ' successfully.') def close(self): self.ssh.close() self.logger.info('Disconnect to ' + self.ip + ' successfully....
jean/sentry
src/sentry/south_migrations/0159_auto__add_field_authidentity_last_verified__add_field_organizationmemb.py
Python
bsd-3-clause
52,679
0.000835
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'AuthIdentity.last_verified' db.add_column( 'se...
elds.foreignkey.FlexibleForeignKey', [], { 'to': "orm[
'sentry.Group']", 'null': 'True' } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'message': ('django.db.models.fields.TextField', [], {}), 'proje...
hangpark/kaistusc
apps/manager/admin.py
Python
bsd-2-clause
1,268
0.003061
""" 사이트 관리 도구 어드민 페이지 설정. """ from django.contrib import admin from modeltranslation.admin import TranslationAdmin from .models import Category, GroupServicePermission, Service, TopBanner class CategoryAdmin(TranslationAdmin): """ :class:`Category` 모델에 대한 커스텀 어드민. `django-modeltranlation` 에서 제공하는 :clas...
드민. `django-modeltranlation` 에서 제공하는 :class:`TranslationAdmin`
을 상속받아 다국어 처리를 사용자 친화적으로 변경하였습니다. """ pass admin.site.register(Category, CategoryAdmin) admin.site.register(Service, ServiceAdmin) admin.site.register(TopBanner, TopBannerAdmin) admin.site.register(GroupServicePermission)
shunliz/test
python/scikit/linear.py
Python
apache-2.0
505
0.011881
from sklearn import datasets from sklearn.linear_model
import LinearRegression import matplotlib.pyplot as plt loaded_data = datasets.load_boston() data_X = loaded_data.data data_y = loaded_data.target model = LinearRegression() model.fit(data_X, data_y) print(model.predict(data_X[:4,:])) print(data_y[:4]) print(model.coef_) print(model.intercept_) print(model.score(da...
ples=100, n_features=1, n_targets=1, noise=20) #plt.scatter(X,y) #plt.show()
kantale/MutationInfo
web/web/settings.py
Python
mit
2,056
0
""" Django settings for web project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/re
f/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) impor
t os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'a(g^11#$6jyys)0mjl3zv4=r029or=v*ldq=)44866...
bitprophet/pytest-relaxed
tasks.py
Python
bsd-2-clause
1,883
0
from invoke import task, Collection from invocations.checks import blacken from invocations.packaging import release from invocations import docs, pytest as pytests, travis @task def coverage(c, html=True): """ Run coverage with coverage.py. """ # NOTE: this MUST use coverage itself, and not pytest-co...
est") if html:
c.run("coverage html") c.run("open htmlcov/index.html") # TODO: good candidate for builtin-to-invoke "just wrap <other task> with a # tiny bit of behavior", and/or args/kwargs style invocations @task def test( c, verbose=True, color=True, capture="sys", opts="", x=False, k...
CloudBrewery/duplicity-swiftkeys
duplicity/tempdir.py
Python
gpl-2.0
9,197
0.001414
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright 2002 Ben Escoto <ben@emerose.org> # Copyright 2007 Kenneth Loafman <kenneth@loafman.com> # # This file is part of duplicity. # # Duplicity is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License...
forget unknown tempfile %s - this is probably a bug.") % util.ufn(fname)) pass finally: self.__lock.release() def cleanup(self): """ Cleanup any files created in the tempora
ry directory (that have not bee
Rogentos/legacy-anaconda
storage/zfcp.py
Python
gpl-2.0
16,651
0.003784
# # zfcp.py - mainframe zfcp configuration install data # # Copyright (C) 2001, 2002, 2003, 2004 Red Hat, Inc. All rights reserved. # # 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 Fre
e Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public Licen...
Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Author(s): Karsten Hopp <karsten@redhat.com> # import string import os from constants import * from udev import udev_settle import gettext _ = lambda x: gettext.ldgettext("anaconda", x) import logging log = logging.getLogger("...
ChristosChristofidis/h2o-3
h2o-py/tests/testdir_misc/pyunit_vec_show.py
Python
apache-2.0
516
0.00969
import sys sys.path.insert(1, "../../") import h2o def vec_show(ip,port): # Connect to h2o h2o.in
it(ip,port) iris = h2o.import_frame(path=h2o.locate("smalldata/iris/iris_wheader.csv")) print "iris:" iris.show() ################################################################### res = 2 - iris res2 = res[0] print "res2:" res2.show() res3 = res[1] print "res3:"
res3.show() iris[2].show() if __name__ == "__main__": h2o.run_test(sys.argv, vec_show)
bdcht/masr
masr/plugins/graph/main.py
Python
gpl-2.0
5,512
0.02812
# -*- coding: utf-8 -*- # Copyright (C) 2010 Axel Tillequin (bdcht3@gmail.com) # This code is part of Masr # published under GPLv2 license import gtk from grandalf.graphs import Vertex,Edge,Graph from grandalf.layouts import SugiyamaLayout from grandalf.routing import * from grandalf.utils import median_wh,Dot f...
def info(self): for s in self.L: print s def ast2Graph(ast): V={} E=[] # create Vertex and Vertex.view for each no
de in ast : for k,x in ast.nodes.iteritems(): try: label = x.attr['label'] except (KeyError,AttributeError): label = x.name v = dotnode(label.strip('"\n')) V[x.name] = v edgelist = [] # create Edge and Edge_basic for each edge in ast: for e in ast.edges: edgelist.append(e) for edot...
x3ro/RIOT
tests/gnrc_sock_dns/tests/01-run.py
Python
lgpl-2.1
12,071
0.000331
#!/usr/bin/env python3 # Copyright (C) 2018 Freie Universität Berlin # # This file is subject to the terms and conditions of the GNU Lesser # General Public License v2.1. See the file LICENSE in the top level # directory for more details. import base64 import os import re import socket import sys import subprocess im...
run SERVER_TIMEOUT = 5 SERVER_PORT
= 5335 # 53 requires root and 5353 is used by e.g. Chrome for MDNS DNS_RR_TYPE_A = 1 DNS_RR_TYPE_AAAA = 28 DNS_RR_TYPE_A_DLEN = 4 DNS_RR_TYPE_AAAA_DLEN = 16 DNS_MSG_COMP_MASK = b"\xc0" TEST_NAME = "example.org" TEST_A_DATA = "10.0.0.1" TEST_AAAA_DATA = "2001:db8::1" TEST_QDCOUNT = 2 TEST_ANCOUNT = 2 class Serve...
mattcongy/piprobe
imports/pyTemperature.py
Python
mit
507
0.013807
import time from datetime import datetime class pyTemperature(object): def __init__(self, date = datetime.now(), temp=None,pressure=None,humidity=None): self.date = date self.temperature = temp self
.pressure = pressure self.humidity = humidity def printTemperature(self): pr
int(self.date) print("Temp: ") print(self.temperature) print("Press: ") print(self.pressure) print("Humidity: ") print(self.humidity)
levilucio/SyVOLT
GM2AUTOSAR_MM/merge_inter_layer_rules/Himesis/HReconnectMatchElementsRHS.py
Python
mit
6,605
0.008176
from core.himesis import Himesis, HimesisPostConditionPattern import cPickle as pickle from uuid import UUID class HReconnectMatchElementsRHS(HimesisPostConditionPattern): def __init__(self): """ Creates the himesis graph representing the AToM3 model HReconnectMatchElementsRHS. """ ...
============================================================ #=============================================================================== # Create new nodes #=============================================================================== # match_contains3 new_node = ...
graph.vs[new_node][Himesis.Constants.META_MODEL] = 'match_contains' #=============================================================================== # Create new edges #=============================================================================== # MatchModel1 -> matc...
mne-tools/mne-tools.github.io
0.15/_downloads/plot_sensor_regression.py
Python
bsd-3-clause
2,578
0
""" ===================================== Sensor space least squares regression ===================================== Predict single trial activity from a continuous variable. A single-trial regression is performed in each sensor and timepoint individually, resulting in an Evoked object which contains the regression c...
np.float) design_matrix = np.column_stack([intercept, # intercept np.linspace(0, 1, len(intercept))]) # also accepts source estimates lm = linear_regression(epochs, design_matrix, names) def plot_topomap(x, units): x.plot_topomap(ch_type='mag', scalings=1., size=1.5, vmax=np.max...
al_count.t_val, units='t') plot_topomap(trial_count.mlog10_p_val, units='-log10 p') plot_topomap(trial_count.stderr, units='z (error)')
kkamkou/gitmostwanted.com
gitmostwanted/tasks/github.py
Python
mit
1,028
0.002918
from gitmostwanted.app import celery, db from gitmostwanted.lib.github.api import user_starred, user_starred_star from gitmostwanted.models.repo import Repo from gitmostwanted.models.user import UserAttitude @celery.task() def repo_starred_star(user_id: int, access_token: str): starred, code = user_starred(access...
if s['full_name'] == a.repo.full_name]] lst_out = [user_starred_star(r.repo.full_name, access_token) for r in attitudes if not [x for x in s
tarred if x['full_name'] == r.repo.full_name]] return len(lst_out), len(list(filter(None, lst_in))) def repo_like(repo_name: str, uid: int): repo = Repo.get_one_by_full_name(repo_name) if not repo: return None db.session.merge(UserAttitude.like(uid, repo.id)) db.session.commit() retu...
ioGrow/iogrowCRM
crm/iomodels/notes.py
Python
agpl-3.0
13,724
0.001749
from crm import model from endpoints_proto_datastore.ndb import EndpointsModel from google.appengine.api import search from google.appengine.ext import ndb from crm.model import Userinfo from protorpc import messages from crm.iograph import Edge # The message class that defines the author schema class AuthorSchema(m...
): about_item = str(self.key.id()) perm = model.Permission(about_kind='Note', about_item=about_item, type='user', role='owner', value=self.owner) perm.put() def p...
index the element at each""" empty_string = lambda x: x if x else "" collaborators = " ".join(self.collaborators_ids) organization = str(self.organization.id()) if data: search_key = ['topics', 'tags'] for key in search_key: if key not in data.keys...
IAPark/PITherm
src/shared/models/Mongo/state_change_repeating.py
Python
mit
2,592
0.003086
from bson import ObjectId from . import repeating_schedule from state_change import StateChange class StateChangeRepeating(StateChange): def __init__(self, seconds_into_week, AC_target, heater_target, fan, id=None): self.id = id self.seconds_into_week = seconds_into_week self.AC_target =...
assert type(seconds_into_week) is int or long assert type(AC_target) is int or float assert type(heater_target) is int or float assert type(fan) is int or float @classmethod def from_dictionary(cls, json): seconds_into_week = json["week_time"] AC_target = json["...
heater_target = json["state"]["heater_target"] fan = json["state"]["fan"] try: id = ObjectId(json["_id"]["$oid"]) except KeyError: id = None except TypeError: try: id = ObjectId(json["_id"]) except: i...
NeCTAR-RC/horizon
openstack_dashboard/test/integration_tests/tests/test_users.py
Python
apache-2.0
1,687
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 # 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 openstack_dashboard.test.integration_tests import decorators from opensta...
joehalloran/shoppinglist_project
shoppinglist/core/models.py
Python
apache-2.0
368
0.027174
from
__future__ import unicode_literals from django.db import models # Create your models here. class TimeStampedModel(models.Model): """ An ab
stract base class model that provides self-updating "created" and "modified" fields. """ created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) class Meta: abstract = True
kevbradwick/rockyroad
rockyroad/driver.py
Python
bsd-3-clause
7,103
0.001971
import errno import glob import platform import re import sys import tempfile import zipfile from contextlib import contextmanager from distutils.version import StrictVersion import os import requests from xml.etree import ElementTree IS_64_BIT = sys.maxsize > 2**32 IS_LINUX = platform.system().lower() == 'linux' I...
): return destination_dir # download an unzip to repo directory with download_file(download_url) as name: _mkdirp(destination_dir) z = zipfile.ZipFile(name, 'r') z.extractall(destination_dir) z.close() for filename in glob.iglob(destination_di
r + '/*'): os.chmod(filename, 777) return destination_dir def get_binary(name, arch=None, version=None): """ Get the driver binary. This will check the cache location to see if it has already been downloaded and return its path. If it is not in the cache then it will be downloaded. ...
Ouranosinc/Magpie
tests/test_magpie_ui.py
Python
apache-2.0
50,956
0.006084
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_magpie_ui ---------------------------------- Tests for :mod:`magpie.ui` module. """ import re import unittest from typing import TYPE_CHECKING from six.moves.urllib.parse import urlparse # NOTE: must be imported without 'from', otherwise the interface's test c...
_name, self.test_
service_child_resource_name): if TestVersion(self.version) <= TestVersion("3.20.1"): if TestVersion(self.version) >= TestVersion("3.0"): find = "<div class=\"tree-key\">{}</div>".format(res_name) text = resp.text.replace("\n", "").repla...
dbentley/pants
src/python/pants/backend/docgen/tasks/markdown_to_html.py
Python
apache-2.0
8,705
0.00919
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, div
ision, generators, nested_scopes, print_function, unicode_literals, with_statement) import codecs import os import re from pkg_resources import resource_string from pygments.forma
tters.html import HtmlFormatter from pygments.styles import get_all_styles from pants.backend.docgen.targets.doc import Page from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.generator import Generator from pants.base.workunit import WorkUnitLabel from p...
jakubroztocil/httpie
tests/test_output.py
Python
bsd-3-clause
18,705
0.00016
import argparse from pathlib import Path from unittest import mock import json import os import io from urllib.request import urlopen import pytest import requests import responses from httpie.cli.argtypes import ( PARSED_DEFAULT_FORMAT_OPTIONS, parse_format_options, ) from httpie.cli.definition import parse...
tp: warning: HTTP 500' in r.stderr def test_quiet_quiet_with_check_status_non_zero(self, httpbin): r = http( '--quiet', '--quiet', '--check-status', httpbin + '/status/500', tolerate_error_exit_status=True, ) assert not r.stderr def test_quiet_quiet_with_check_s...
pe(self, httpbin): r = http( '--quiet', '--quiet', '--check-status', httpbin + '/status/500', tolerate_error_exit_status=True, env=MockEnvironment(stdout_isatty=False) ) assert 'http: warning: HTTP 500' in r.stderr @pytest.mark.parametrize('quiet_flags', ...
olexiim/edx-platform
common/djangoapps/student/tests/test_roles.py
Python
agpl-3.0
7,708
0.001816
""" Tests of student.roles """ import ddt from django.test import TestCase from courseware.tests.factories import UserFactory, StaffFactory, InstructorFactory from student.tests.factories import AnonymousUserFactory from student.roles import ( GlobalStaff, CourseRole, CourseStaffRole, CourseInstructorRole, Or...
structor = InstructorFactory(course_key=self.course_key) def test_global_staff(self): self.assertFalse(GlobalStaff().has_user(self.student)) self.assertFalse(GlobalStaff().ha
s_user(self.course_staff)) self.assertFalse(GlobalStaff().has_user(self.course_instructor)) self.assertTrue(GlobalStaff().has_user(self.global_staff)) def test_group_name_case_sensitive(self): uppercase_course_id = "ORG/COURSE/NAME" lowercase_course_id = uppercase_course_id.lower() ...
MrYsLab/razmq
hardware_baseline/encoders/left_encoder.py
Python
gpl-3.0
491
0.004073
impo
rt pigpio import time class LeftEncoder: def __init__(self, pin=24): self.pi = pigpio.pi() self.pin = pin self.pi.set_mode(pi
n, pigpio.INPUT) self.pi.set_pull_up_down(pin, pigpio.PUD_UP) cb1 = self.pi.callback(pin, pigpio.EITHER_EDGE, self.cbf) self.tick = 0 def cbf(self, gpio, level, tick): # print(gpio, level, tick) print(self.tick) self.tick += 1 e = LeftEncoder() while True: tim...
mapycz/mapnik
scons/scons-local-3.0.1/SCons/Tool/latex.py
Python
lgpl-2.1
2,759
0.004349
"""SCons.Tool.latex Tool-specific initialization for LaTeX. Generates .dvi files from .latex or .ltx files There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001 - 2017 The SCons Foundation #...
faults import SCons.Scanner.LaTeX import SCons.Util import SCons.Tool import SCons.Tool.tex def LaTeXAuxFunction(target = None, source= None, env=None): result = SCons.Tool.tex.InternalLaTeXAuxAction( SCons.Tool.tex.LaTeXAction, target, source, env ) if result != 0: SCons.Tool.tex.check_file_error_mess...
ex.TeXLaTeXStrFunction) def generate(env): """Add Builders and construction variables for LaTeX to an Environment.""" env.AppendUnique(LATEXSUFFIXES=SCons.Tool.LaTeXSuffixes) from . import dvi dvi.generate(env) from . import pdf pdf.generate(env) bld = env['BUILDERS']['DVI'] bld.add...
valentin-krasontovitsch/ansible
lib/ansible/modules/cloud/google/gcp_compute_target_tcp_proxy.py
Python
gpl-3.0
12,924
0.003327
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2017 Google # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # ---------------------------------------------------------------------------- # # *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** # ...
on: - An optional descr
iption of this resource. returned: success type: str id: description: - The unique identifier for the resource. returned: success type: int name: description: - Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. ...
rdkdd/tp-spice
spice/lib/vm_actions_rv.py
Python
gpl-2.0
14,208
0.000352
#!/usr/bin/env python # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that ...
yer to VM. env : dict Dictionary of env variables to be passed before remote-viewer starts. Returns ------- None """ env = env or {} method = vmi.cfg.rv_parameters_from if method == 'cmd': act.info(vmi, "Connect to VM using command line.") rv_connect_cmd(vmi, s...
: act.info(vmi, "Connect to VM using .vv file.") rv_connect_file(vmi, ssn, env) else: raise RVSessionConnect(vmi.test, "Wrong connect method.") #TODO: pass env variables @reg.add_action(req=[ios.ILinux]) def rv_connect_cmd(vmi, ssn, env): cmd = act.rv_basic_opts(vmi) url = act.rv_u...
pedrobaeza/odoo
addons/mrp_byproduct/mrp_byproduct.py
Python
agpl-3.0
8,828
0.006004
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
ct_uom.id, production.product_qty, pro
duction.bom_id.product_uom.id) qty1 = sub_product.product_qty qty2 = production.product_uos and production.product_uos_qty or False product_uos_factor = 0.0 if qty2 and production.bom_id.product_uos.id: product_uos_factor = product_uom_...
wavesoft/yaco
yaco/wsgi.py
Python
gpl-3.0
1,413
0.000708
""" WSGI config for yaco project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` set...
ustom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites in the same mod_ws...
own daemon process, or use # os.environ["DJANGO_SETTINGS_MODULE"] = "yaco.settings" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "yaco.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points he...
DevHugo/zds-site
zds/forum/migrations/0005_auto_20151119_2224.py
Python
gpl-3.0
594
0.001684
# -*- coding: utf-8 -*- from __future_
_ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('forum', '0004_topic_update_index_date'), ] database_operations = [ migrations.AlterModelTable('TopicFollowed', 'notification_topicfollowed') ] state_oper...
State( database_operations=database_operations, state_operations=state_operations) ]
iceout/python_koans_practice
python2/koans/about_sets.py
Python
mit
1,706
0.001758
#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutSets(Koan): def test_sets_make_keep_lists_unique(self): highlanders = ['MacLeod', 'Ramirez', 'MacLeod', 'Matunas', 'MacLeod', 'Malcolm', 'MacLeod'] there_can_only_be_only_one = set(highlanders) ...
nidas']) self.assertEqual(set(['Willie']), scotsmen - warriors) self.assertEqual(set(['MacLeod', 'Wallace', 'Willie', 'Leonidas']), scotsmen | warriors) self.assertEqual(set(['MacLeod', 'Wallace']), scotsmen & warriors) self.assertEqual(set(['Willie', 'Leonidas']), scotsmen ^ warriors) ...
_membership(self): self.assertEqual(True, 127 in set([127, 0, 0, 1])) self.assertEqual(True, 'cow' not in set('apocalypse now')) def test_we_can_compare_subsets(self): self.assertEqual(True, set('cake') <= set('cherry cake')) self.assertEqual(True, set('cake').issubset(set('cherry c...
h4/fuit-webdev
projects/logger/manage.py
Python
mit
249
0
#!/usr/bin
/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "logger.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.arg
v)
jhcodeh/my-doku
my_doku_application/my_doku_application/wsgi.py
Python
mit
413
0.002421
""" WSGI config for my_doku_application project. It exposes the WSGI c
allable as a module-level variable named ``application``. For m
ore information on this file, see https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_doku_application.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application()
naziris/HomeSecPi
picamera/bcm_host.py
Python
apache-2.0
2,448
0.001634
# vim: set et sw=4 sts=4 fileencoding=utf-8: # # Python header conversion # Copyright (c) 2013,2014 Dave Hughes <dave@waveform.org.uk> # # Original headers # Copyright (c) 2012, Broadcom Europe Ltd # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitte...
e of the copyright h
older nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,...
emsrc/daeso-dutch
lib/daeso_nl/ga/kb/baseline.py
Python
gpl-3.0
8,138
0.010445
""" simple alignment baselines """ # TODO: # - better implementions from daeso.pair import Pair def greedy_align_equal_words(corpus): for graph_pair in corpus: graph_pair.clear() graphs = graph_pair.get_graphs() target_nodes = graphs.target.terminals(with_punct=False, ...
relation = "generalizes" break elif tr in sr and len(tw) > 3: relation = "specifies" break # check if roots share a morphological segment elif sparts.intersection(tr.split("_")): ...
ts" break if relation: tn = target_nodes[i] graph_pair.add_align(Pair(sn, tn), relation) del target_nodes[i] del target_words[i] del target_roots[i] ...
natano/python-git-orm
git_orm/__init__.py
Python
isc
758
0.006596
__version__ = '0.4' __author__ = 'Martin Natano <natano@natano.net>' _repository = None _branch = 'git-orm' _remote = 'origin' class GitError(Exception): pass def set_repository(value): from pygit2 import discover_repository, Repository global _repository if value is None: _repository = None ...
urn try: path = discover_repository(value) except KeyError: raise GitError('no repository found in "{}"'.format(value)) _repository = Re
pository(path) def get_repository(): return _repository def set_branch(value): global _branch _branch = value def get_branch(): return _branch def set_remote(value): global _remote _remote = value def get_remote(): return _remote
google-research/language
language/labs/memory/synthetic_dataset.py
Python
apache-2.0
7,696
0.007277
# 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 ...
ice(range(num_pairs)) target_key, target_val_text = pairs[target_idx] target_val_encoded = vocab.index(target_val_text) seq_text = "".join([k + v for k, v in pairs]) + "?" + target_key seq_encoded = [vocab.index(char) for char in seq_text] return seq_text, seq_encoded, target_val_text, target_val_encoded, t...
ve=False, num_patterns_store=None): """Generates a dataset of sequences of patterns and retrieval targets. Args: n: Number of examples num_patterns: Number of unique patterns in the sequence pattern_size: Dimensionality of each pattern selective (bool): True if only a subset...
chetan/cherokee
admin/plugins/proxy.py
Python
gpl-2.0
10,677
0.018638
# -*- coding: utf-8 -*- # # Cherokee-admin # # Authors: # Alvaro Lopez Ortega <alvaro@alobbs.com> # # Copyright (C) 2010 Alvaro Lopez Ortega # # This program is free software; you can redistribute it and/or # modify it under the terms of version 2 of the GNU General Public # License as published by the Free Softwa...
subst = CTK.TextCfg ('%s!%s!substring'%(key,k), False)
remove = CTK.ImageStock('del') remove.bind('click', CTK.JS.Ajax (URL_APPLY, data={'%s!%s'%(key,k): ''}, complete = refresh.JS_to_refresh())) table += [regex, subst, remove] submit = CTK.Submi...
RNAcentral/rnacentral-import-pipeline
tests/databases/intact/parser_test.py
Python
apache-2.0
8,022
0.002618
# -*- coding: utf-8 -*- """ Copyright [2009-2020] EMBL-European Bioinformatics Institute 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...
data.InteractionIdentifier("go", "GO:0031428", "box C/D snoRNP comple
x"), data.InteractionIdentifier("go", "GO:0032040", "small-subunit processome"), data.InteractionIdentifier("go", "GO:0003723", "RNA binding"), data.InteractionIdentifier( "go", "GO:0000494", "box C/D snoRNA 3'-end processing" ), data.Interacti...
leitelm/RISE_scada
wsgi.py
Python
apache-2.0
189
0.021164
# coding=utf-8 # Run a test server. from app import app import sys reload(sys) sys.setdefaultencoding('utf-8') if __nam
e__ == '__main__': app.run(host='0.0.0.0', port=7000, deb
ug=True)
dongjoon-hyun/tensorflow
tensorflow/python/training/basic_loops.py
Python
apache-2.0
2,343
0.004695
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
: `tf.train.Supervisor` to run the training services. train_step_fn: Callable to execute one training step. Called repeatedly as `train_step_fn(session, *args
**kwargs)`. args: Optional positional arguments passed to `train_step_fn`. kwargs: Optional keyword arguments passed to `train_step_fn`. master: Master to use to create the training session. Defaults to `""` which causes the session to be created in the local process. """ if args is None: arg...
sdavlenov/is210-week-05-warmup
task_03.py
Python
mpl-2.0
142
0
#!/usr/bin/
env python # -*- coding: utf-8 -*- """module that copies from another module""" from task_01.peanut import BUTTER JELLY
= BUTTER
allieus/pylockfile
lockfile/sqlitelockfile.py
Python
mit
5,541
0.000722
from __future__ import absolute_import, division import time import os try: unicode except NameError: unicode = str from . import LockBase, NotLocked, NotMyLock, LockTimeout, AlreadyLocked class SQLiteLockFile(LockBase): "Demonstrate SQL-based locking." testdb = None def __init__(self, path, t...
er. if timeout is not None and time.time() > end_time: if timeout > 0: # No more waiting. raise LockTimeout("Timeout waiting to acquire" " lock for %s" % self.path) ...
. raise AlreadyLocked("%s is already locked" % self.path) # Well, okay. We'll give it a bit longer. time.sleep(wait) def release(self): if not self.is_locked(): raise NotLocked("%s is not locked" % self.path) if not self.i_am_locking(): ...
npp/npp-api
data/management/commands/import_fcna_spending.py
Python
mit
1,982
0.007064
from django import db from django.conf import settings from django.core.management.base import NoArgsCommand from data.models import FCNASpending import csv # National Priorities Project Data Repository # import_fcna_spending.py # Updated 7/23/2010, Joshua Ruihley, Sunlight Foundation # Imports Federal Child Nutritio...
he source file you just created # 4) change 'amount' column in data_FCNASpending table to type 'bigint' # 5) Run as Django management command from your project path "python manage.py import_fcna_spending" SOURCE_FILE = '%s/education/fcna_spending.csv' % (settings.LOCAL_DATA_ROOT) class Command(NoArgsCommand): ...
def clean_int(value): if value=='': value=None return value data_reader = csv.reader(open(SOURCE_FILE)) for i, row in enumerate(data_reader): if i == 0: year_row = row; else: ...
slint/zenodo
zenodo/modules/support/config.py
Python
gpl-2.0
8,030
0
# -*- coding: utf-8 -*- # # This file is part of Zenodo. # Copyright (C) 2017 CERN. # # Zenodo 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 2 of the # License, or (at your option) any later v...
in <u>all</u> of the points below:' '<ol>' '<li>Provide a justification for the file change in t
he ' 'description.</li>' '<li>Mention any use of the record(s) DOI in publications or ' 'online, e.g.: list papers that cite your record and ' 'provide links to posts on blogs and social media. ' 'Otherwise, state that to the best of your knowledge the DOI has...
171121130/SWI
venv/Lib/site-packages/tablib/formats/_json.py
Python
mit
1,312
0
# -*- coding: utf-8 -*- """ Tablib - JSON Support """ import decimal import tablib try: import ujson as json except ImportError: import json title = 'json' extensions = ('json', 'jsn') def date_handler(obj): if isinstance(obj, decimal.Decimal): return str(obj) elif hasattr(obj, 'isoformat'...
] data.dict = sheet['data'] dbook.add_sheet(data)
def detect(stream): """Returns True if given stream is valid JSON.""" try: json.loads(stream) return True except ValueError: return False
berjc/aus-senate-audit
aus_senate_audit/senate_election/simulated_senate_election.py
Python
apache-2.0
3,665
0.004366
# -*- coding: utf-8 -*- """ Implements a Class for Representing a Simulated Senate Election. """ from collections import Counter from random import random from random import seed as set_seed from time import asctime from time import localtime from aus_senate_audit.senate_election.base_senate_election import BaseSena...
m_ballots_drawn) for _ in range(batch_size): candidate_values = [(i + v * random(), cid) for i, cid in enumerate(self._candidate_ids)] ballot = tuple(cid for val, cid in sorted(candidate_values)) self.add_ballot(ballot, 1) def get_outcome(self, ballot_weights): "...
:param :class:`Counter` ballot_weights: A mapping from a ballot type to the number of ballots drawn of that type. :returns: The IDs of the candidates elected to the available seats, sorted in lexicographical order. :rtype: tuple """ counter = Counter() for ballot, we...
atilag/qiskit-sdk-py
qiskit/extensions/qasm_simulator_cpp/snapshot.py
Python
apache-2.0
2,505
0
# -*- coding: utf-8 -*- # pylint: disable=invalid-name # Copyright 2017 IBM RESEARCH. All Rights Reserved. # # Licensed under the Apache License, Vers
ion 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
cable 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. # ============================...
martini97/django-ecommerce
checkout/urls.py
Python
gpl-3.0
276
0
from django.conf.urls import url f
rom . import views urlpatterns = [ url(r'^carrinho/adicionar/(?P<slug>[\w_-]+)/$',
views.CreateCartItemView.as_view(), name='create_cartitem'), url(r'^carrinho/$', views.CartItemView.as_view(), name='cart_item') ]
jorisvandenbossche/geopandas
geopandas/tests/test_explore.py
Python
bsd-3-clause
29,278
0.001366
import geopandas as gpd import numpy as np import pandas as pd import pytest from distutils.version import LooseVersion folium = pytest.importorskip("folium") branca = pytest.importorskip("branca") matplotlib = pytest.importorskip("matplotlib") mapclassify = pytest.importorskip("mapclassify") import matplotlib.cm as ...
assert m.width == (200.0, "px") # custom XYZ tiles m = self.nybb.explore( zoom_control
=False, width=200, height=200, tiles="https://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}", attr="Google", ) out_str = self._fetch_map_string(m) s = '"https://mt1.google.com/vt/lyrs=m\\u0026x={x}\\u0026y={y}\\u0026z={z}"' assert s in out_st...
nerosketch/djing
tariff_app/views.py
Python
unlicense
5,574
0.001435
from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import PermissionRequiredMixin from django.db.models import Count from django.urls import reverse_lazy from django.utils.translation import ugettext as _ from django.shortcuts import render, get_object_or_404, redirect from django...
scr)s", %(amount).2f' % { 'title': self.object.title or '-', 'descr': self.obj
ect.descr or '-', 'amount': self.object.amount or 0.0 }) messages.success(request, _('Service has been deleted')) return res def get_context_data(self, **kwargs): kwargs['tid'] = self.kwargs.get('tid') return super().get_context_data(**kwargs) class PeriodicPay...
scribblemaniac/MCEdit2Blender
blocks/__init__.py
Python
gpl-3.0
132
0.015152
__all__ = ["Block", "Unknown", "Multitextured", "DataValues", "Stairs", "MultitexturedStairs", "Slab", "MultitexturedSlab",
"Log"]
vanhonit/xmario_center
test/gtk3/test_custom_lists.py
Python
gpl-3.0
1,958
0.005618
#!/usr/bin/python from gi.repository import Gtk, GObject import time import unittest from testutils import setup_test_env setup_test_env() from softwarecenter.enums import XapianValues, ActionButtons TIMEOUT=300 class TestCustomLists(unittest.TestCase): def _debug(self, index, model, needle): print ("...
ndex(0, model, "ark") self.assertPkgInListAtIndex(1, model, "software-center") self.assertPkgInListAtIndex(2, model, "artha") # check that the status bar offers to install the packages install_button = pane.action_bar.get_button(ActionButtons.INSTALL) self.assertNotEqual...
for i in range(10): time.sleep(0.1) while Gtk.events_pending(): Gtk.main_iteration() if __name__ == "__main__": import logging logging.basicConfig(level=logging.INFO) unittest.main()
veltzer/riddling
scripts/wrapper_lacheck.py
Python
gpl-3.0
939
0
#!/usr/bin/python """ This is a wrapper to run the 'lacheck(1)' tool from the 'lacheck' package. Why do we need this wrapper? - lacheck does NOT report in its
exit status whether it had warnings o
r not. - it is too verbose when there are no warnings. """ import sys # for argv, exit, stderr import subprocess # for Popen def main(): out = subprocess.check_output([ 'lacheck', sys.argv[1], ]) errors = False remember = None printed_remember = False for line in out.split('...
DirkHoffmann/indico
indico/modules/categories/compat.py
Python
gpl-3.0
1,374
0.002183
# This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. import re from flask import abort, redirect, request from werkzeug.exceptions import NotFound from indic...
) view_args = request.view_args.copy() view_args['legacy_category_id'] = mapping.category_id # To create the same URL with the proper ID we take advantage of the # fact that the legacy endpoint works perfectly fine with proper IDs # too (you can pass an int for a string argument), but due to the ...
endpoints, the URL will # then be handled by the proper endpoint instead of this one. return redirect(url_for(request.endpoint, **dict(request.args.to_dict(), **view_args)), 301)
flav-io/flavio
flavio/physics/zdecays/test_zdecays.py
Python
mit
6,570
0.002435
import unittest import flavio from math import sqrt, pi from flavio.physics.zdecays.gammazsm import Zobs, pb from flavio.physics.zdecays.gammaz import GammaZ_NP from flavio.physics.zdecays import smeftew par = flavio.default_parameters.get_central_all() class TestGammaZ(unittest.TestCase): def test_obs_sm(self)...
u)'), 0) def test_Gamma_NP(self): # compare NP contributions to A.49-A.52 from 1706.08945 GF, mZ, s2w_eff = par['GF'], par['m_Z'], par['s2w']*1.0010 d_gV = 0.055 d_gA = 0.066 # A.49-A.52 from 1706.08945 dGamma_Zll = sqrt(2)*GF*mZ
**3/(6*pi) * (-d_gA + (-1+4*s2w_eff)*d_gV) dGamma_Znn = sqrt(2)*GF*mZ**3/(6*pi) * (d_gA + d_gV) dGamma_Zuu = sqrt(2)*GF*mZ**3/(pi) * (d_gA -1/3*(-3+8*s2w_eff)*d_gV) /2 dGamma_Zdd = sqrt(2)*GF*mZ**3/(pi) * (-3/2*d_gA +1/2*(-3+4*s2w_eff)*d_gV) /3 # term squared in d_gV and d_gA not include...
jespino/urwintranet
urwintranet/ui/views/__init__.py
Python
apache-2.0
108
0
# -*-
coding: utf-8 -*- """ urwintranet.ui.views ~~~~~~~~~~~~~~~~~~ """ from . import (a
uth, home, parts)
thisisshi/cloud-custodian
tests/test_airflow.py
Python
apache-2.0
3,504
0.001427
# Copyright The Cloud Custodian Authors. # SPDX-License-Identifier: Apache-2.0 from .common import BaseTest import jmespath class TestApacheAirflow(BaseTest): def test_airflow_environment_value_filter(self): session_factory = self.replay_flight_data('test_airflow_environment_value_filter') p = sel...
new_tag, call['Environment'].get('Tags')) def test_airflow_environment_untag(self): session_factory = self.replay_flight_data('test_airflo
w_environment_untag') p = self.load_policy( { 'name': 'airflow-untag', 'resource': 'airflow', 'filters': [{ 'tag:env': 'dev' }], 'actions': [{ 'type': 'remove-tag', ...
MikeLaptev/sandbox_python
mera/selenium_training_automation/pages/page.py
Python
apache-2.0
913
0.001095
""" Created on Sep 14, 2015 @author: Mikhail """ from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support.expected_conditions import visibility_of_element_located, visibility_of from selenium.co
mmon.exceptions
import TimeoutException __author__ = 'Mikhail' class Page(object): def __init__(self, driver, url): self.driver = driver self.url = url self.wait = WebDriverWait(self.driver, 5) def open_page(self, url): self.driver.get(url) def is_element_visible_by_locator(self, locat...
Erotemic/local
misc/code/TAing/fixcmake.py
Python
gpl-3.0
478
0
import os import fnmatch def find_files(directory, pattern): for root, dirs, files in os.walk(di
rectory): for basename in files: if fnmatch.fnmatch(basename, pattern): filename = os.path.join(root, basename) yield filename for fname in find_files('.', 'CMakeLists.txt'): f = open(fname, 'a') f.write( '\ninclude_directories(${OPENGL_INC...
NCLUDE_PATH})') f.close()
dever860/cabot
cabot/cabotapp/models.py
Python
mit
30,857
0.00188
from django.db import models from django.conf import settings from django.core.exceptions import ValidationError from polymorphic import PolymorphicModel from django.db.models import F from django.core.urlresolvers import reverse from djan
go.contrib.a
uth.models import User from celery.exceptions import SoftTimeLimitExceeded from .jenkins import get_job_status from .alert import (send_alert, AlertPlugin, AlertPluginUserData, update_alert_plugins) from .calendar import get_events from .graphite import parse_metric from .graphite import get_data from .tasks import up...
wolfram74/flask_exploration
run.py
Python
mit
66
0
from pro
ject import app if __name__ == '__main__':
app.run()
longnow/panlex-tools
libpython/gary/sh_parser.py
Python
mit
1,521
0.007242
from collections import defaultdict, namedtuple import regex as re from gary import ignore_parens_list Record = namedtuple('Record', ['dob', 'eng', 'pos', 'phn']) @ignore_parens_list def split_words(text:str) -> list: return re.split('\s*;\s*', text) class ShParser: def __init__(self, text): self....
curr['ps'] = match[2] if match[1] == 'ge': word_list = split_words(match[2]) for word in word_list: curr['ge'].append(word) def getEntries(self): for entry in self.entrie
s: if 'lx' in entry: dob = entry['lx'] else: dob = '' eng = '‣'.join( entry['ge']) pos = entry['ps'] phn = entry['ph'] yield Record(dob,eng,pos,phn)
cupy/cupy
cupyx/jit/_cuda_types.py
Python
mit
3,661
0
import numpy from cupy._core._scalar import get_typename # Base class for cuda types. class TypeBase: def __str__(self): raise NotImplementedError def declvar(self, x): return f'{self} {x}' class Void(TypeBase): def __init__(self): pass def __str__(self): return '...
get_typename(self.dtype) c_contiguous = get_cuda_code_from_constant(self._c_contiguous, bool_) index_32_bits = get_cuda_code_from_constant(self._index_32_bits, bool_) r
eturn f'CArray<{ctype}, {self.ndim}, {c_contiguous}, {index_32_bits}>' def __eq__(self, other): return ( isinstance(other, CArray) and self.dtype == other.dtype and self.ndim == other.ndim and self._c_contiguous == other._c_contiguous and self._in...
emogenet/ghdl
libraries/openieee/build_numeric.py
Python
gpl-2.0
32,279
0.004058
#!/usr/bin/env python # Generate the body of ieee.numeric_std and numeric_bit from a template. # The implementation is based only on the specification and on testing (as # the specifications are often ambiguous). # The algorithms are very simple: carry ripple adder, restoring division. # This file is part of GHDL....
t) res = """ function {func} (l : {ltype}; r : {rtype}) return compare_type is subtype res_type is {vtype} ({vparam}'length - 1 downto 0); alias la : res_type is l;""" + \ declare_int_var (dic['iparam'], dic['itype']) + """ variable lb, rb : {logic}; variable res : compare_type; begin ...
c['vparam']) + \ extract_int_lsb("r", right) if logic == 'std': res += """ if {vparam}b = 'X' then return compare_unknown; end if;""" res += """ if lb = '1' and rb = '0' then res := compare_gt; elsif lb = '0' and rb = '1' then
pastpages/wordpress-memento-plugin
fabfile/migrate.py
Python
mit
268
0
from venv import _venv from fabric.api import task @tas
k def migrate(): """ Run Django's migrate command
""" _venv("python manage.py migrate") @task def syncdb(): """ Run Django's syncdb command """ _venv("python manage.py syncdb")
jut-io/jut-python-tools
tests/jut_run_tests.py
Python
mit
3,794
0.002636
""" basic set of `jut run` tests """ import json import unittest from tests.util import jut BAD_PROGRAM = 'foo' BAD_PROGRAM_ERROR = 'Error line 1, column 1 of main: Error: no such sub: foo' class JutRunTests(unittest.TestCase): def test_jut_run_syntatically_incorrect_program_reports_error_with_format_json(s...
'--format'
, 'csv', 'emit -from :2014-01-01T00:00:00.000Z: -limit 5') process.expect_status(0) stdout = process.read_output() process.expect_eof() self.assertEqual(stdout, '#time\n' '2014-01-01T00:00:00.000Z\n' ...
OmkarPathak/Python-Programs
CompetitiveProgramming/HackerEarth/DataStructures/Arrays/P02_Mark-The-Answer.py
Python
gpl-3.0
1,372
0.008824
# Our friend Monk has an exam that has quite we
ird rules. Each question has a difficulty level in the form of an # Integer. Now, Monk can only solve the problems that have difficulty level less than X . Now the rules are- # # Score of the student is equal to the maximum number of answers he/she has attempted without skipping a question. # Student is allowed to skip...
he problem he/she attempts and always starts the paper from first # question. # # Given the number of Questions, N ,the maximum difficulty level of the problem Monk can solve , X ,and the difficulty # level of each question, Ai can you help him determine his maximum score? # # Input Format # First Line contains Integer...
stack-of-tasks/rbdlpy
tutorial/lib/python2.7/site-packages/OpenGL/GL/ARB/robustness_isolation.py
Python
lgpl-3.0
1,604
0.015586
'''OpenGL extension ARB.robustness_isolation This module customises the behaviour of the OpenGL.raw.GL.ARB.robustness_isolation to provide a more Python-friendly API Overview (from the spec) GL_ARB_robustness and supporting window system extensions allow creating an OpenGL context supporting graphics reset noti...
stant, arrays from OpenGL import extensions, wrapper import ctypes from OpenGL.raw.GL import _types, _glgets from OpenGL.raw.GL.ARB.robustness_isolation import * from OpenGL.raw.GL.ARB.robustness_isolation import _EXTENSION_NAME def glInitRobustnessIsolationARB(): '''Return boolean indicating whether this extensio...
its-dirg/svs
setup.py
Python
apache-2.0
1,148
0.000871
from setuptools import find_packages from setuptools import setup setup( name='svs', version='1.0.0', description='The InAcademia Simple validation Service allows for the easy validation of affiliation (Student,' 'Faculty, Staff) of a user in Academia', license='Apache 2.0', classif...
che Software License', 'Programming Language :: Python :: 3', ], author='Rebecka Gulliksson', author_email='tech@inacademia.org',
zip_safe=False, url='http://www.inacademia.org', packages=find_packages('src'), package_dir={'': 'src'}, package_data={ 'svs': [ 'data/i18n/locale/*/LC_MESSAGES/*.mo', 'templates/*.mako', 'site/static/*', ], }, message_extractors={ '...
dayatz/taiga-back
taiga/export_import/services/store.py
Python
agpl-3.0
29,644
0.002699
# -*- coding: utf-8 -*- # Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz> # Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com> # Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com> # Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net> # This program is free software: you can r...
_in_custom_attributes_values(custom_attributes, values): ret = {} for attr in custom_attributes: value = values.get(attr["name"], None) if value is not None: ret[str(attr["id"])] = value return ret def _store_custom_attributes_values(obj, data_values, obj_field, serializer_cla...
data = { obj_field: obj.id, "attributes_values": data_values, } try: custom_attributes_values = obj.custom_attributes_values serializer = serializer_class(custom_attributes_values, data=data) except ObjectDoesNotExist: serializer = serializer_class(data=data) ...
christianholz/QuickShuttle
bookings.py
Python
gpl-3.0
3,213
0.012138
#!/usr/bin/env python """list all previously made bookings""" import os import sys import cgi import datetime import json import shuttle import shconstants import smtplib import shcookie print "Content-type: text/html\r\n" shuttle.do_login(shcookie.u, shcookie.p) form = cgi.FieldStorage() if 'action' in form: a...
['dt'], b['dl'], b['gt'], b['gl']) if 'cn' in b: print ' <span class="cn">Connector %s</span>' % (b['cn']) if not past: loc = shuttle.get_shuttle_location(b['r'], b['cn']) if loc != None: stop = shuttle.get_stop_gps(b['r'], b['dl'
]) if stop != None: dst = shuttle.get_maps_eta((loc['lat'], loc['lon']), (stop[0], stop[1])) print ' <span class="et">ETA: %s (<a href="https://www.google.com/maps?q=%f,%f">%s</a>)</span>' % ( dst[1], loc['lat'], loc['lon'], dst[0]) if 'cl' in b: print ''' <form ...