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 |
|---|---|---|---|---|---|---|---|---|
cloudera/ibis | ibis/backends/impala/hdfs.py | Python | apache-2.0 | 17,817 | 0 | """File system module."""
# Copyright 2014 Cloudera 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 o... | ctory
Raises
------
NotImplementedError
"""
| raise NotImplementedError
def put_tarfile(
self,
hdfs_path: str,
local_path: str,
compression: str = 'gzip',
verbose: bool = None,
overwrite: bool = False,
):
"""
Write contents of tar archive to HDFS.
Write contents of tar archive to HD... |
pombredanne/ompc | examples/izhikevich/izhikevich.py | Python | bsd-3-clause | 1,088 | 0.009191 |
from num | py import *
from pylab import plot, show, find, rand, randn
# Created by Eugene M. Izhikevich, February 25, 2003
# Excitatory neurons Inhibitory neurons
Ne = 800
Ni = 200
re = rand(Ne)
ri = rand(Ni)
a = r_[0.02 * ones(Ne), 0.02 + 0.08 * | ri]
b = r_[0.2 * ones(Ne), 0.25 - 0.05 * ri]
c = r_[-65 + 15 * re**2, -65 * ones(Ni)]
d = r_[8 - 6 * re**2, 2 * ones(Ni)]
S = c_[0.5 * rand(Ne + Ni, Ne), -rand(Ne + Ni, Ni)]
v = -65 * ones(Ne + Ni)# Initial values of v
u = b*v # Initial values of u
firings = zeros((0,2))
for t in xrange(1... |
switowski/invenio | invenio/modules/submit/models.py | Python | gpl-2.0 | 19,892 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2011, 2012, 2015 CERN.
#
# Invenio 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 optio... | id = db.Column(db.Integer(11), nullable=False, autoincrement=True,
primary_key=True)
_id_father = db.Column(db.Integer(11), db.ForeignKey(SbmCOLLECTION.id),
nullable=True, name="id_father")
id_son = db.Column(db.Char(10) | , db.ForeignKey(SbmDOCTYPE.sdocname),
nullable=False)
catalogue_order = db.Column(db.Integer(11), nullable=False,
server_default='0')
father = db.relationship(
SbmCOLLECTION,
backref=db.backref('sonDoctype', uselist=False),
)
@db.h... |
dustalov/watset | impl/cpm/cpm.py | Python | mit | 575 | 0.001739 | #!/usr/bin/env python3
import argparse
import sys
from signal import signal, SIGINT
import networkx as nx
signal(SIGINT, lambda signum, frame: sys.exit(1))
parser = argparse.ArgumentParser()
parser.add_argument('-k', nargs='?', type=int, default= | 2)
args = | parser.parse_args()
lines = sys.stdin.read().splitlines()
G = nx.parse_edgelist(lines, delimiter='\t', nodetype=str, data=(('weight', float),))
communities = nx.k_clique_communities(G, args.k)
for i, community in enumerate(communities):
print('\t'.join((str(i), str(len(community)), ', '.join(community))))
|
persandstrom/home-assistant | homeassistant/components/mysensors/__init__.py | Python | apache-2.0 | 5,714 | 0 | """
Connect to a MySensors gateway via pymysensors API.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/mysensors/
"""
import logging
import voluptuous as vol
from homeassistant.components.mqtt import (
valid_publish_topic, valid_subscribe_topic)
f... | device_class_copy = device_class
if isinstance(device_class, dict):
child = gateway.sensors[node_id].children[child_id]
s_type = gateway.const.Presentation(child.type).na | me
device_class_copy = device_class[s_type]
name = _get_mysensors_name(gateway, node_id, child_id)
args_copy = (*device_args, gateway, node_id, child_id, name,
value_type)
devices[dev_id] = device_class_copy(*args_copy)
new_devices.append(devices[dev_id]... |
yahman72/robotframework | atest/testresources/testlibs/PythonVarArgsConstructor.py | Python | apache-2.0 | 228 | 0.008772 | class PythonVarA | rgsConstructor:
def __init__(self, mandatory, *varargs):
self.mandatory = mandatory
self.varargs = varargs
def get_args(self):
return self.mandatory, ' '.joi | n(self.varargs)
|
ignatenkobrain/rpg | tests/support.py | Python | gpl-2.0 | 434 | 0 | from pathlib import Path
from unittest import mock, TestCase
from rpg.spec import Spec
class RpgTestCase | (TestCase):
test_project_dir = Path("tests/project")
def assertExistInDir(self, expected, pathlibobject):
path = Path(pathlibobject)
for files in expected:
self.assertTrue((path / files).exists(), msg=files)
class PluginTestCase(RpgTestCase):
sack = mock.MagicMock()
spec =... | |
anhstudios/swganh | data/scripts/templates/object/tangible/powerup/weapon/fs_quest_sad/shared_melee_speed_quest.py | Python | mit | 483 | 0.045549 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DON | E IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/powerup/weapon/fs_quest_sad/shared_melee_speed_quest.iff"
result.attribute_template_id = -1
result.stfName("powerup_n","weapon_melee_speed_ques... | END MODIFICATIONS ####
return result |
unioslo/cerebrum | Cerebrum/modules/no/uio/voip/bofhd_voip_help.py | Python | gpl-2.0 | 4,975 | 0 | # -*- encoding: utf-8 -*-
#
# Copyright 2010-2018 University of Oslo, Norway
#
# This file is part of Cerebrum.
#
# Cerebrum 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
... | -1307, USA.
"""This module contains help strings for voip bofhd extension. """
group_help = {
"voip": "voip-module related commands.",
}
command_help = {
"voip": {
"voip_s | ervice_new":
"Create a new voip service.",
"voip_service_info":
"Display information about a voip service.",
"voip_service_type_list":
"Show available voip_service types.",
"voip_service_delete":
"Remove a voip service from Cerebrum.",
"voi... |
cebrusfs/217gdb | pwndbg/heap/ptmalloc.py | Python | mit | 18,839 | 0.006847 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from collections import OrderedDict
from collections import namedtuple
import gdb
import pwndbg.color.memory as M
import p... | 'debugging symbols and try agai | n.'))
return self._main_arena
@property
@pwndbg.memoize.reset_on_stop
def arenas(self):
arena = self.main_arena
arenas = []
arena_cnt = 0
main_arena_addr = int(arena.address)
sbrk_page = self.get_heap_boundaries().vaddr
... |
tiborsimko/invenio-access | invenio_access/ext.py | Python | mit | 6,195 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Invenio module for common role based access control."""
from __future__ import ab... | f.load_entry_point_actions(entry_point_actions)
if entry_point_system_roles:
self.load_entry_point_system_roles(entry_point_system_roles)
@cached_property
def cache(self):
"""Return a cache instance."""
cache = self._cache or self.app.config.get('ACCESS_CACHE')
| return import_string(cache) if isinstance(cache, six.string_types) \
else cache
def set_action_cache(self, action_key, data):
"""Store action needs and excludes.
.. note:: The action is saved only if a cache system is defined.
:param action_key: The unique action name.
... |
jordiclariana/ansible | lib/ansible/utils/module_docs_fragments/iosxr.py | Python | gpl-3.0 | 2,875 | 0.001391 | #
# (c) 2015, Peter Sprygada <psprygada@ansible.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any late... | g with the network device
for either connecting or sending commands. If the timeout is
exceeded before the operation is completed, the module will error.
require: false
default: 10
ssh_keyfile:
description:
- Specifies the SSH key to use to authenticate the connection to
the... | the value of environment variable C(ANSIBLE_NET_SSH_KEYFILE)
will be used instead.
required: false
provider:
description:
- Convenience method that allows all I(iosxr) arguments to be passed as
a dict object. All constraints (required, choices, etc) must be
met either by indivi... |
ovnicraft/server-tools | auth_session_timeout/__manifest__.py | Python | agpl-3.0 | 691 | 0 | # -*- coding: utf-8 -*-
# (c) 2015 ACSONE SA/NV, Dhinesh D
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
'name': "Inactive Sessions Timeout",
'summary': """
This module disable all inactive sessions since a given delay""",
'author': "ACSONE SA/NV, "
"Dhinesh D... | ommunity Association (OCA)',
'w | ebsite': "http://acsone.eu",
'category': 'Tools',
'version': '10.0.1.0.2',
'license': 'AGPL-3',
'data': [
'data/ir_config_parameter_data.xml'
],
'installable': True,
}
|
QiJune/Paddle | python/paddle/fluid/tests/unittests/test_modified_huber_loss_op.py | Python | apache-2.0 | 2,103 | 0 | # Copyright (c) 2018 PaddlePaddle 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 app... | np[pos] = np.random.uniform(-2., 2.)
y_np[pos] = np.random.choice([0, 1])
product_res[pos] = x_np[pos] * (2 * y_np[pos] - 1)
val = product_res[pos]
self.inputs = {'X': x_np, 'Y': y_np}
loss = np.vectorize(modified_huber_loss_forward)(product_res)
... | f):
self.check_output()
def test_check_grad(self):
self.check_grad(['X'], 'Out', max_relative_error=0.01)
if __name__ == '__main__':
unittest.main()
|
pietroalbini/trackdeps | trackdeps/tracker.py | Python | mit | 4,649 | 0 | """
trackdeps.tracker
Track dependencies versions and which one needs updates
Copyright (c) 2015 Pietro Albini <pietro@pietroalbini.io>
Released under the MIT license
"""
import datetime
import requests
from packaging import specifiers, version
from . import parser
PYPI_URL = "https://pypi.python.... | only the same dependency
if dep.package != package:
raise ValueError("Can't merge Dependency of different packages!")
for requirement in dep._needed_by_raw:
dependency.add_requirement(requirement)
return dependency | |
pombredanne/prerepo | tests/shared/models/test_file.py | Python | bsd-2-clause | 3,978 | 0.003017 | class BaseTestFile(object):
def test_create_file(self):
path = '/hello world'
data = 'my hello world'
self.assertIs(self.redis.get(':'.join((self.uid, path))), None)
self.f.createfile(path, data)
self.assertEqual(self.redis.get(':'.join((self.uid, path, 'content'))),
... | self.assertIs(self.redis.get(':'.join((self.uid, | path))), None)
self.f.createdir(path)
self.assertEqual(self.redis.get(':'.join((self.uid, path, 'type'))),
'd')
self.assertIn('hello world', self.redis.smembers(':'.join((self.uid,
'/', 'content'))))
self.assertEqual(len(self.redis.smembers(':... |
vipullakhani/mi-instrument | mi/instrument/wetlabs/fluorometer/flord_d/test/test_driver.py | Python | bsd-2-clause | 19,945 | 0.002808 | """
@package mi.instrument.wetlabs.fluorometer.flord_d.test.test_driver
@file marine-integrations/mi/instrument/wetlabs/fluorometer/flort_d/driver.py
@author Tapana Gupta
@brief Test cases for flord_d driver
USAGE:
Make tests verbose and provide stdout
* From the IDK
$ bin/test_driver
$ bin/test_driv... | @param verify_values: bool, should we verify parameter values
"""
| self.assert_data_particle_keys(FlordMenuParticleKey, self._flordD_mnu_parameters)
|
repotvsupertuga/tvsupertuga.repository | plugin.video.youtube/resources/lib/youtube_plugin/__init__.py | Python | gpl-2.0 | 54 | 0 | __autho | r__ = 'bromix'
__all__ = | ['kodion', 'youtube']
|
piiswrong/dec | dec/make_stl_data.py | Python | mit | 229 | 0 | impo | rt os
import dec
print 'Building HOG feature extractor...'
os.system('python setup_features.py build')
os.system('python setup_features.py install')
print 'Preparing stl data. This could take a while...'
dec.make_stl_d | ata()
|
edgarcosta/lmfdb-gce | transition_scripts/reimport_knowls_and_userdb.sage.py | Python | mit | 4,038 | 0.006686 |
# This file was *autogenerated* from the file reimport_knowls_and_userdb.sage
from sage.all_cmdline import * # import sage library
_sage_const_0 = Integer(0)
os.chdir("/home/edgarcosta/lmfdb/")
import lmfdb
db = lmfdb.db_backend.db
DelayCommit = lmfdb.db_backend.DelayCommit
load("/home/edgarcosta/lmfdb-gce/transiti... | cur = conn.cursor()
# delete rows of usersdb.users
"DELETE FROM userdb.users;"
with open('/scratch/importing/users.txt') as F:
cur.copy_from(F, 'userdb.users', columns=["username", "password", "bcpassword", "admin", "color_scheme", "full_name", "email", "u... | conn.rollback()
print "Failure in importing users"
print err
print "Successfully imported users"
export_knowls()
export_users()
backup()
import_knowls()
import_users()
|
mardix/Mocha | mocha/contrib/auth/decorators.py | Python | mit | 5,732 | 0.000349 | import functools
import flask_login
import signals
import inspect
from mocha import (utils,
abort,
request,
)
from mocha.core import apply_function_to_members
from . import (is_authenticated,
not_authenticated,
ROLES_ADMIN,
... | func):
apply_function_to_members(func, accepts_moderator_roles)
return func
else:
@functools.wraps(func)
def decorator(*args, **kwargs):
return accepts_roles(*ROLES_MODERATOR)(func)(*args, **kwargs)
return decorator
def jwt_required(func):
"""
Checks if... | throw 401
:param func:
:return:
"""
if inspect.isclass(func):
apply_function_to_members(func, jwt_required)
return func
else:
@functools.wraps(func)
def deco(*a, **kw):
if not "Authorization" in request.headers:
abort(401, "Not Authorized")... |
nacc/autotest | frontend/afe/views.py | Python | gpl-2.0 | 2,216 | 0.001354 | import httplib2, sys, traceback, cgi
from django.http import HttpResponse, HttpResponsePermanentRedirect
from django.http import HttpResponseServerError
from django.template import Context, loader
from autotest.client.shared import utils
from autotest.frontend import views_common
from autotest.frontend.afe import mode... | er.get_template('500.html')
trace = traceback.format_exc()
context = Context({
| 'type': sys.exc_type,
'value': sys.exc_value,
'traceback': cgi.escape(trace)
})
return HttpResponseServerError(t.render(context))
|
klahnakoski/ActiveData | vendor/jx_elasticsearch/es52/painless/not_op.py | Python | mpl-2.0 | 1,218 | 0.000821 | # encoding: utf-8
#
#
# 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 distri | buted with this file,
# You can obtain one at http:# mozilla.org/MPL/2.0/.
#
# Contact: Kyle Lahnakoski (kyle@lahnakoski.com)
#
from __future__ import absolute_import, division, unicode_literals
from jx_base.expressions import NotOp as NotOp_
from jx_elasticsearch.es52.painless._utils import Painless
from jx_elasticse... | search.es52.painless.false_op import false_script
from jx_elasticsearch.es52.painless.null_op import null_script
from jx_elasticsearch.es52.painless.true_op import true_script
from mo_json import BOOLEAN
class NotOp(NotOp_):
def to_es_script(self, schema, not_null=False, boolean=False, many=True):
value =... |
blandry/crazyflie-tools | lcm/crazyflie_t/vortex_sensor_t.py | Python | mit | 1,903 | 0.006831 | """LCM type definitions
This file automatically generated by lcm.
DO NOT MODIFY BY HAND!!!!
"""
try:
import cStringIO.StringIO as BytesIO
except ImportError:
from io import BytesIO
import struct
class vortex_sensor_t(object):
__slots__ = ["sensor1", "sensor2", "velocity"]
def __init__(self):
... | _get_hash_recursive(parents):
if vortex_sensor_t in parents: return 0
tmphash = (0x3525d46ae32101c3) & 0xffffffffffffffff
tmphash = (((tmphash<<1)&0xffffffffffffffff) + (tmphash>>63)) & 0xffffffffffffffff
return tmphash
_get_hash_recursive = staticmethod(_get_hash_recursive)
_... | struct.pack(">Q", vortex_sensor_t._get_hash_recursive([]))
return vortex_sensor_t._packed_fingerprint
_get_packed_fingerprint = staticmethod(_get_packed_fingerprint)
|
5monkeys/content-io | cio/pipeline/pipes/meta.py | Python | bsd-3-clause | 548 | 0 | # coding=utf-8
from __future__ import unicode_literals
| from time import mktime
from datetime import datetime
from ...pipeline.pipes.base import BasePipe
class MetaPipe(BasePipe):
def set_request(self, request):
for node in request.values():
node.meta['modified_at'] = self._utc_timestamp()
def publish_request(self, request):
for node ... | t.values():
node.meta['published_at'] = self._utc_timestamp()
def _utc_timestamp(self):
return int(mktime(datetime.utcnow().timetuple()))
|
vintasoftware/tapioca-instagram | tapioca_instagram/tapioca_instagram.py | Python | mit | 1,118 | 0 | # coding: utf-8
from tapioca import (JSONAdapterMixin, TapiocaAdapter,
generate_wrapper_from_adapter)
from .resource_mapping import RESOURCE_MAPPING
class InstagramClientAdapter(JSONAdapterMixin, TapiocaAdapter):
api_root = 'https://api.instagram.com/v1/'
resource_mapping = RESOURCE_MAP... | ('access_token', '')}
)
return params
def get_iterator_list(self, response_data):
return response_data['data']
def get_iterator_next_request_kwargs(self, iterator_request_kwargs,
response_data, response):
paging = response_data.get('pagi... | if url:
return {'url': url}
Instagram = generate_wrapper_from_adapter(InstagramClientAdapter)
|
tapasweni-pathak/Horoscope-API | server.py | Python | mit | 1,933 | 0.039834 | from flask import Flask, jsonify
from pyhoroscope import Horoscope
from flask_cors import CORS
app = Flask (__name__)
CORS(app)
############################################
# Index
############################################
@app.route ('/', methods=['GET'])
def index_route () :
return jsonify({
'author' : '... | e'],
sunsign=result['sunsign'],
horoscope=result['horoscope'])
#Current Week Horoscope
@app.route ('/horoscope/week/<sunsign>', methods=['GET'])
def weekly_horoscope_route (sunsign) :
result = dict (Horoscope.get_weekly_horoscope (sunsign))
return jsonify (week=result['week'],
sunsign=result['sunsign'... | )
def monthly_horoscope_route (sunsign) :
result = dict (Horoscope.get_monthly_horoscope (sunsign))
return jsonify (month=result['month'],
sunsign=result['sunsign'],
horoscope=result['horoscope'])
#Current Year Horoscope
@app.route ('/horoscope/year/<sunsign>', methods=['GET'])
def yearly_horoscope_route (suns... |
skosukhin/spack | var/spack/repos/builtin.mock/packages/indirect-mpich/package.py | Python | lgpl-2.1 | 1,664 | 0.000601 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | eral Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Softwa | re
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class IndirectMpich(Package):
"""Test case for a package that depends on MPI and one of its
dependencies requires a *particular ver... |
nfschmidt/cryptopals | python/byte.py | Python | mit | 206 | 0.004854 |
def hamming_distan | ce(bytes1, bytes2):
distance = 0
for b1, b2 in zip(bytes1, bytes2):
xored = b1^b2
distance += sum(1 for n in range(8) if (xored >> n) & 0x01)
return distance | |
nemesisdesign/openwisp2 | openwisp_controller/config/migrations/0027_add_indexes_on_ip_fields.py | Python | gpl-3.0 | 982 | 0.001018 | # Generated by Django 3.0.4 on 2020-04-15 23:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [('config', '0026_hardware_id_not_unique')]
operations = [
migrations.AlterField(
model_name='device',
name='last_ip',
f... | 'last request coming from the device'
),
null=True,
| ),
),
migrations.AlterField(
model_name='device',
name='management_ip',
field=models.GenericIPAddressField(
blank=True,
db_index=True,
help_text='ip address of the management interface, if available',
nul... |
MacHu-GWU/single_file_module-project | sfm/_version.py | Python | mit | 94 | 0 | __version__ = "0.0.17"
if __name__ == "_ | _main__": # pragma: no cover
print(__ | version__)
|
Cerfoglg/cattle | tests/integration/cattletest/core/test_link.py | Python | apache-2.0 | 4,582 | 0 | from common_fixtures import * # NOQA
def test_link_instance_stop_start(super_client, client, context):
target1 = context.create_container(ports=['180', '122/udp'])
target2 = context.create_container(ports=['280', '222/udp'])
c = context.create_container(instanceLinks={
'target1_link': target1.id... | tanceLinks={
'target1_link': target1.id})
c = client.wait_success(c)
links = c.instanceLinks()
assert len(links) == 1
link = links[0]
assert link.state == 'inactive'
c = client.wait_success(c.start())
link = client.reload(link)
assert c.state == 'ru... | eload(link)
link = super_client.wait_success(link.remove())
assert link.state == 'removed'
c = client.wait_success(c.start())
assert c.state == 'running'
|
ddddwee1/SULsT | SUL1/sample/AgingNet/temp/network.py | Python | lgpl-3.0 | 6,686 | 0.061621 | import tensorflow as tf
from dyn import model_attention as Model
import model as M
bn_training = True
reuse_att = False
reuse_enc = False
reuse_gen = False
reuse_dis = False
reuse_feat = False
reuse_dis2 = False
reuse_dis_f = False
reuse_genatt = False
reuse_agecls = False
reuse_agecls_r = False
reuse_age_enc = {}
... | reuse_dis_f,bn_training
with tf.variable_scope('dis_f',reuse=reuse_dis_f):
mod = Model(inp)
mod.set_bn_training(True)
mod.flatten()
feat = mod.get_current_layer()
mod.fcLayer(512,activation=M.PARAM_LRELU,batch_norm=True)
mod.fcLayer(256,activation=M.PARAM_LRELU,batch_norm=True)
adv = mod.fcLayer(1)
mo... | al reuse_genatt,bn_training,blknum
blknum=0
with tf.variable_scope('gen_att',reuse=reuse_genatt):
mod = Model(inp)
mod.set_bn_training(bn_training)
mod.convLayer(5,32,stride=2,activation=M.PARAM_LRELU,batch_norm=True) #64
block(mod,64,1)
mod.convLayer(3,128,stride=2,activation=M.PARAM_LRELU,batch_norm=True)... |
timrae/anki | aqt/webview.py | Python | agpl-3.0 | 5,072 | 0.002563 | # Copyright: Damien Elmes <anki@ichi2.net>
# -*- coding: utf-8 -*-
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import sys
from anki.hooks import runHook
from aqt.qt import *
from aqt.utils import openLink
from anki.utils import isMac, isWin
import anki.js
# Bridge for Qt<->JS
######... | f, handler=None):
# handler should return true if event should be swallowed
self._keyHandler = handler
def setHtml(self, html, loadCB=None):
self.key = None
self._loadFinishedCB = loadCB
QWebView.setHtml(self, html)
def stdHtml(self, body, css="", bodyClass="", loadCB=N... | l; height: 24px;"
else:
button = "font-weight: normal;"
self.setHtml("""
<!doctype html>
<html><head><style>
button {
%s
}
%s</style>
<script>%s</script>
%s
</head>
<body class="%s">%s</body></html>""" % (
button, css, js or anki.js.jquery+anki.js.browserSel,
head, bodyClass, body),... |
nextoa/comb | comb/mq/mongo.py | Python | mit | 480 | 0.008333 | # -*- coding: utf-8 -*-
def token(collection, token='token'):
return collection.find_and_modify({token: {'$exists': False}}, {'$set': {'token': True}})
def release(collection, token='token'):
return collection.update({token: True}, {'$set': {token: False} | }, multi=True)
def garbage(collection, token='token'):
"""
garbage for mongo message queue
:param collection:
:param token:
:return:
| """
collection.remove({token: False}, multi=True) |
qrsforever/workspace | ML/learn/tensorflow.google.cn/low_level/graph_session.py | Python | mit | 2,151 | 0.010693 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @file graph_session.py
# @brief
# @author QRS
# @blog qrsforever.github.io
# @version 1.0
# @date 2019-05-30 18:22:35
################################ jupyter-vim #######################################
# https://github.com/qrsforever/vim/blob/master/bundle/.configs/jupyt... | #####################################################
c_0 = tf.constant(0, name='c') # Tensor("c:0", shape=(), dtype=int32)
c_1 = tf.constant(1, name='c') # Tensor("c_1:0", shape=(), dtype=int32)
with | tf.name_scope('scope1'):
c_2 = tf.constant(2, name='c') # Tensor("scope1/c:0", shape=(), dtype=int32)
c_3 = tf.constant(3, name='c') # Tensor("scope1/c_1:0", shape=(), dtype=int32)
with tf.name_scope('scopse2'):
c_4 = tf.constant(4, name='c') # "scope1/scopse2/c:0"
c_5 = tf.constant(5, nam... |
davismathew/netbot-django | bootcamp/traceroute/views.py | Python | mit | 10,645 | 0.014937 | from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponseBadRequest, HttpResponse
from bootcamp.tasks.models import Task
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from bootcamp.tasks.forms import TaskForm
from django.contrib.auth.decorators impo... | = get_vars('ansibenginemtn')
if vrf == 'True':
vrf="True"
else:
vrf="False"
return render(request, 'traceroute/runtraceroute.html', {'sourceip': sourceip, 'destip':destip,'vrfname': vrfname, 'vrf':vrf,'baseurl':baseurl})
@login_required()
def runtraceapi(request):
sourceip = request... | vrf')
vrfname = request.POST.get('vrfname')
baseurl = request.POST.get('baseurl')
url = baseurl+'/ansibengine/api/v1.0/runtrace'
headers = {'content-type': 'application/json'}
temp= {}
data= {}
data['sourceip']=sourceip
data['destip']=destip
data['vrfname']=vrfname
if vrf == '... |
ICTSTUDIO/accounting-addons | account_move_line_report/report/account_move_line_report.py | Python | agpl-3.0 | 7,901 | 0.002785 | # -*- coding: utf-8 -*-
# Copyright© 2016 ICTSTUDIO <http://www.ictstudio.eu>
# License: AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
from openerp import tools, models, fields, api
import openerp.addons.decimal_precision as dp
class AccountMoveLineReport(models.Model):
_name = "account.move.line.report"
... | j = self.env['account.period']
if self._context.get('period', False) == 'current_period':
current_period = period_obj.find()[0]
domain.append( | ['period_id', 'in', [current_period.id]])
elif self._context.get('year', False) == 'current_year':
current_year = fiscalyear_obj.find()
ids = fiscalyear_obj.read([current_year.id], ['period_ids'])[0]['period_ids']
domain.append(['period_id', 'in', ids])
else:
... |
canhhs91/greenpointtrees | src/oscar/apps/dashboard/orders/config.py | Python | mit | 245 | 0 | from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
|
class OrdersDashboardConfig(AppConfig):
label = 'orders_dashboard'
name = 'oscar.apps.dashboard.orders'
verbose_name = _('Orders dashboa | rd')
|
mgaldzic/antimony | src/bindings/python/doc-converter/test/cases/test_test.py | Python | bsd-3-clause | 203 | 0.014778 | #!/usr/bin/env python
import unittest
class TestTest(unittest.TestCase):
def test_true(self):
self.failUnless(True)
def main():
unittest.main()
if __name__ | == '__main__':
| main()
|
igor-rangel7l/igorrangelteste.repository | script.module.urlresolver/lib/urlresolver/plugins/up2stream.py | Python | gpl-2.0 | 2,789 | 0.003586 | """
up2stream urlresolver plugin
Copyright (C) 2015 tknorris
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is d... | (urllib2.urlopen(r, timeout=15).headers['Content-Length'])
if r > 1048576:
stream_url += '|' + urllib.urlencode(headers)
return stream_url
except:
UrlResolver.ResolverError("File Not Playable")
def get_url(self, host, media_id):
return 'http | ://up2stream.com/view.php?ref=%s' % media_id
def get_host_and_id(self, url):
r = re.search(self.pattern, url)
if r:
return r.groups()
else:
return False
def valid_url(self, url, host):
return re.search(self.pattern, url) or self.name in host
|
AnalogJ/lexicon | lexicon/providers/rage4.py | Python | mit | 5,281 | 0.001136 | """Module provider for rage4"""
import json
import logging
import requests
from lexicon.exceptions import AuthenticationError
from lexicon.providers.base import Provider as BaseProvider
LOGGER = logging.getLogger(__name__)
NAMESERVER_DOMAINS = ["rage4.com"]
def provider_parser(subparser):
"""Configure provide... | in delete_record_id:
self._post("/deleterecord/", {"id": record_id})
# is always True at this point, if a non 200 response is returned an error is raised.
LOGGER.debug("delete_record: %s", True)
return True
# Helpers
def _request(self, action="GET", url="/", data=None, que... | data = {}
if query_params is None:
query_params = {}
default_headers = {
"Accept": "application/json",
"Content-Type": "application/json",
}
default_auth = requests.auth.HTTPBasicAuth(
self._get_provider_option("auth_username"),
... |
teoliphant/scipy | scipy/optimize/optimize.py | Python | bsd-3-clause | 101,264 | 0.0016 | #__docformat__ = "restructuredtext en"
# ******NOTICE***************
# optimize.py module by Travis E. Oliphant
#
# You may copy and use this module as you see fit with no
# guarantee implied provided you keep this notice in all copies.
# *****END NOTICE************
# A collection of optimization algorithms. Version ... | nterpolation (Mar. 2004)
# Minimization routines
__all__ = ['fmin', 'fmin_powell', 'fmin_bfgs', 'fmin_ncg', 'fmin_cg',
'fminbound', 'brent', 'golden', 'bracket', 'rosen', 'rosen_der',
'rosen_hess', 'rosen_hess_prod', 'brute', 'approx_fprime',
'line_search', 'check_grad', 'Resul | t', 'show_options',
'OptimizeWarning']
__docformat__ = "restructuredtext en"
import warnings
import numpy
from numpy import atleast_1d, eye, mgrid, argmin, zeros, shape, \
squeeze, vectorize, asarray, absolute, sqrt, Inf, asfarray, isinf
from linesearch import \
line_search_BFGS, line_search_wolf... |
mbirru/midonet-charms | neutron-api/hooks/charmhelpers/core/services/base.py | Python | apache-2.0 | 12,852 | 0.001634 | # Copyright 2014-2015 Canonical Limited.
#
# This file is part of charm-helpers.
#
# charm-helpers is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License version 3 as
# published by the Free Software Foundation.
#
# charm-helpers is distributed in the hope ... | set on a given relation.
The 'data_ready' value should be either a single callback, or a list of
callbacks, to be called when all items in 'required_data' pass `is_ready()`.
Each callback will be called with the service name as the only parameter.
After all of the 'data_ready' callbacks... | he 'start' callbacks
are fired.
The 'data_lost' value should be either a single callback, or a list of
callbacks, to be called when a 'required_data' item no longer passes
`is_ready()`. Each callback will be called with the service name as the
only parameter. After all of the ... |
tobikausk/nest-simulator | pynest/examples/plot_quantal_stp_synapse.py | Python | gpl-2.0 | 3,593 | 0 | # -*- coding: utf-8 -*-
#
# plot_quantal_stp_synapse.py
#
# This file is part of NEST.
#
# Copyright (C) 2004 The NEST Initiative
#
# NEST 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 th... | distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implie | d warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see <http://www.gnu.org/licenses/>.
'''
Compare Tsodyks-Markram Synapse models.
----------------... |
sidnarayanan/PandaCore | Tools/python/processes/SM.py | Python | mit | 23,991 | 0.037181 | #!/usr/bin/env python
'''@package docstring
Just a giant list of processes and properties
'''
processes = {
# inclusive NLO V+jets
'DYJetsToLL_M-50_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8':('ZJets_nlo','MC',6025.2),
'DYJetsToNuNu_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8':('ZtoNuNu_nlo','MC',1... | madgraphMLM-pythia8':('ZJets_ht800to1200','MC',0.6304),
'DYJetsToLL_M-50_HT-100to200_TuneCP5_13TeV-madgraphMLM-pythia8':('ZJets_ht100to200_CP5','MC',147.40),
'DYJetsToLL_M-50_HT-200to400_TuneCP5_13TeV-madgraphMLM-pyt | hia8':('ZJets_ht200to400_CP5','MC',40.99),
'DYJetsToLL_M-50_HT-400to600_TuneCP5_13TeV-madgraphMLM-pythia8':('ZJets_ht400to600_CP5','MC',5.678),
'DYJetsToLL_M-50_HT-600to800_TuneCP5_13TeV-madgraphMLM-pythia8':('ZJets_ht600to800_CP5','MC',1.367),
'DYJetsToLL_M-50_HT-800to1200_TuneCP5_13TeV-madgrap... |
lepistone/oerpscenario | features/steps/purchase_order.py | Python | gpl-2.0 | 5,237 | 0.000573 | from support import *
import datetime
@step('I press the purchase button')
def impl(ctx):
ctx.purchase_order = mode | l('purchase.order').get([('sale_id', '=', ctx.saleorder.id)])
ctx.purchase_order._send('purchase_confirm')
@step('the purchase expected date is {date}')
def impl(ctx, date):
assert_equal(ctx.purchase_order.picking_ids[0].max_date, date)
@step('containing the following purchase order lines')
def impl(ctx):
... | roduct_uom'] = row['uom']
del row['uom']
values = parse_table_values(ctx, 'purchase.order.line', row.items())
product = model('product.product').get(values['product_id'])
values['name'] = '%s %s' % (purchase_order.name, product.partner_ref)
values['order_id'] = purchase_order.id
... |
tomjelinek/pcs | pcs_test/tier0/lib/commands/cluster/test_setup.py | Python | gpl-2.0 | 116,523 | 0.000094 | # pylint: disable=too-many-lines
import json
from copy import deepcopy
from unittest import (
TestCase,
mock,
)
from pcs import settings
from pcs.common import (
file_type_codes,
reports,
)
from pcs.common.file import RawFileError
from pcs.common.host import Destination
from pcs.common.ssl import (
... | "pacemaker",
"pacemaker_remote",
"corosync",
"pcs | d",
"sbd",
"qdevice",
"booth",
]
RING_TEMPLATE = "ring{i}_addr: {addr}"
NODE_TEMPLATE = """\
node {{
{ring_list}
name: {name}
nodeid: {id}
}}
"""
COROSYNC_CONF_TEMPLATE = """\
totem {{
version: 2
cluster_name: {cluster_name}
transport: {transport_type}\
{totem_opt... |
mugwort-rc/idata | idata/config/assertion.py | Python | gpl-3.0 | 2,193 | 0 | import re
from . import expression
class AssertionBase:
pass
class RowAssertion(AssertionBase):
def __init__(self, config, assert_config):
assert assert_config["type"] == "row"
self.config = config
self.assert_config = assert_config
def check(self, data):
if self.type =... | elif self.type == "match":
source = self.get(self.args_source, data)
| return "{} does not match {}".format(source, repr(self.args_value))
raise NotImplementedError
def assertEqual(self, data):
source = self.get(self.args_source, data)
value = self.args_value
return source == value
def assertIn(self, data):
value = self.args_value
... |
daviddeng/azrael | azrael/test/test.py | Python | agpl-3.0 | 6,059 | 0.003631 | # Copyright 2015, Oliver Nagy <olitheolix@gmail.com>
#
# This file is part of Azrael (https://github.com/olitheolix/azrael)
#
# Azrael is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of... | ameInA=(0, 0, 0, 0, 0, 0, 1),
frameInB=(0, 0, 0, 0, 0, 0, 1),
stiffness=(1, 2, 3, 4, 5.5, 6),
damping=(2, 3.5, 4, 5, 6.5, 7),
equilibrium=(-1, -1, -1, 0, 0, 0),
linLimitLo=(-10.5, -10.5, -10.5),
linLimitHi=(10.5, 10.5, 10.5),
rotLimitLo=(-0.1, -0.2, -0.3),
... | se, False, False, False))
return ConstraintMeta(aid, '6DOFSPRING2', rb_a, rb_b, dof)
def getRigidBody(scale: (int, float)=1,
imass: (int, float)=1,
restitution: (int, float)=0.9,
rotation: (tuple, list)=(0, 0, 0, 1),
position: (tuple, list, np.nd... |
kennethreitz/pipenv | pipenv/vendor/cerberus/tests/test_registries.py | Python | mit | 2,841 | 0.001056 | # -*- coding: utf-8 -*-
from cerberus import schema_registry, rules_set_registry, Validator
from cerberus.tests import (
assert_fail,
assert_normalized,
assert_schema_error,
assert_success,
)
def test_schema_registry_simple():
schema_registry.add('foo', {'bar': {'type': 'string'}})
schema = {... | ef test_normalization_ | with_rules_set():
# https://github.com/pyeve/cerberus/issues/283
rules_set_registry.add('foo', {'default': 42})
assert_normalized({}, {'bar': 42}, {'bar': 'foo'})
rules_set_registry.add('foo', {'default_setter': lambda _: 42})
assert_normalized({}, {'bar': 42}, {'bar': 'foo'})
rules_set_registry... |
ar4s/django | tests/invalid_models_tests/test_ordinary_fields.py | Python | bsd-3-clause | 31,641 | 0.000664 | import unittest
import uuid
from django.core.checks import Error, Warning as DjangoWarning
from django.db import connection, models
from django.test import (
SimpleTestCase, TestCase, skipIfDBFeature, skipUnlessDBFeature,
)
from django.test.utils import isolate_apps, override_settings
from django.utils.functional ... | models.CharField(max_length=True)
field = Model._meta.get_field('field')
self.assertEqual(field.check(), [
Error(
"'max_length' must be a positive integer.",
obj=field,
id='fields.E121'
),
])
def test_non_iterable_cho... | models.CharField(max_length=10, choices='bad')
field = Model._meta.get_field('field')
self.assertEqual(field.check(), [
Error(
"'choices' must be an iterable (e.g., a list or tuple).",
obj=field,
id='fields.E004',
),
])
... |
developersociety/django-glitter | glitter/tests/factories.py | Python | bsd-3-clause | 1,042 | 0 | from django.contrib.contenttypes.models import ContentType
import factory
from glitter.models import Version
from glitter.pages.models import Page
class PageFactory(factory.DjangoModelFactory):
url = factory.Sequence(lambda n: '/page-{}/'.format(n))
title = factory.Sequence(lambda n: 'Page {}'.format(n))
... | eta:
exclude = ('content_o | bject',)
abstract = True
class PageVersionFactory(VersionFactory):
content_object = factory.SubFactory(PageFactory)
class Meta:
model = Version
@factory.post_generation
def set_version(self, create, extracted, **kwargs):
if extracted:
page = self.content_object
... |
ptisserand/ansible | lib/ansible/modules/cloud/docker/docker_service.py | Python | gpl-3.0 | 37,555 | 0.00237 | #!/usr/bin/python
#
# Copyright 2016 Red Hat | Ansible
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['prev... | - Supports check mode.
options:
project_src:
description:
- Path to a directory containing a docker-compose.yml or docker-compose.yaml file.
- Mutually exclusive with C(definition).
- Required when no C(definition) is | provided.
project_name:
description:
- Provide a project name. If not provided, the project name is taken from the basename of C(project_src).
- Required when C(definition) is provided.
files:
description:
- List of file names relative to C(project_src). Overrides docker-compose... |
tomchor/pymicra | pymicra/algs/auxiliar.py | Python | gpl-3.0 | 3,396 | 0.010601 | from __future__ import absolute_import, print_function, division
"""
"""
def stripDown(str, final='', args=['_', '-']):
"""
Auxiliar function to strip down keywords from symbols
"""
for arg in args:
str=str.replace(arg,final)
return str
def lenYear(year):
"""
Calculates th... | ef applyResult(result, failed, df, control=None, testname=None, filename=None, failshow=F | alse, index_n=None):
"""
Auxiliar function to be used with util.qcontrol
Parameters
-----------
result: bool
whether the test failed and succeeded
failed: list
list of failed variables. None object if the test was successful
control: dictionary
dictionary whose keys ... |
hitlonewind/PR-experiment | Classifrer/Adaboost.py | Python | mit | 713 | 0.001403 | import numpy as np
import time
from sklearn.ensemble import AdaBoostClassifier
from sklearn.metrics import classification_report
data = np.loadtxt('./data/TrainSamples.csv', delimiter=",")
label = np.loadtxt('./data/TrainLabels.csv', delimiter=",")
test = np.loadtxt('./data/TestSamples1.csv', delimiter=',')
testLabel ... | format(str(end - start) | ))
report.close() |
jr-garcia/Engendro3D | e3d/scene_management/ScenesManagerClass.py | Python | mit | 2,253 | 0.000888 | from __future__ import print_function
from .SceneClass import Scene
from ..backends.base_backend import DrawingData
class ScenesManager(object):
def __init__(self):
self._scenes = {}
self._models = None
self.sounds = None
self._engine = None
self.currentSceneID = ""
... | ne:
scene = self._defaultScene
self.currentSceneID = scene.ID
def getCurrentScene(self):
"""
@rtype : Scene
"""
r | eturn self.getScene(self.currentSceneID)
currentScene = property(getCurrentScene, setCurrentScene)
def update(self, netElapsedTime, windowSize):
currentScene = self.currentScene
if currentScene:
return currentScene.update(netElapsedTime, windowSize)
else:
self.c... |
bd4/monster-hunter-scripts | mhapi/skills.py | Python | mit | 3,065 | 0.005873 |
from mhapi.util import EnumBase
class CapSkill(EnumBase):
NONE = 0
EXPERT = 1
MASTER = 2
GOD = 3
_names = { NONE: "No skills",
EXPERT: "Capture Expert",
MASTER: "Capture Master",
GOD: "Capture God" }
class LuckSkill(EnumBase):
NONE = 0
GOOD ... |
class ElementAttackUp(EnumBase):
NONE = 0
ONE = 1
TWO = 2
THREE = 3
ELEMENT = 4
_names = { NONE: "",
ONE: "(element) Atk +1",
TWO: "(element) Atk +2",
THREE: "(element) Atk +3",
ELEMENT: "Element Atk Up" }
@classmethod
def m... | l)
if skill == cls.ONE:
element += 40
elif skill == cls.TWO:
element += 60
elif skill == cls.THREE:
element += 90
elif skill == cls.ELEMENT:
element *= 1.1
else:
raise ValueError("Unknown element ... |
ndp-systemes/odoo-addons | bus_integration/models/mapping_configuration_helper.py | Python | agpl-3.0 | 6,420 | 0.002025 | # -*- coding: utf8 -*-
#
# Copyright (C) 2019 NDP Systèmes (<http://www.ndp-systemes.fr>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# Licen... | id
rec.deactivated_sync = mapping.deactivated_sync
rec.deactivate_on_delete = mapping.deactivate_on_delete
rec.update_prohibited = mapping.update_prohibited
rec.is_exportable = mapping.is_exportable
rec.is_importable = mapping.is_importable... | n.helper.line']
mapping = self.env['bus.object.mapping'].get_mapping(self.model_name)
mapping_fields = self.env['bus.object.mapping.field'].search([('mapping_id', '=', mapping.id)])
for mapping_field in mapping_fields:
self.field_ids |= self.env['mapping.configuration.helper.line'].c... |
bzzzz/cython | Cython/Compiler/Tests/TestTreeFragment.py | Python | apache-2.0 | 2,243 | 0.002675 | from Cython.TestUtils import CythonTest
from Cython.Compiler.TreeFragment import *
from Cython.Compiler.Nodes import *
from Cython.Compiler.UtilNodes import *
import Cython.Compiler.Naming as Naming
class TestTreeFragments(CythonTest):
def test_basic(self):
F = self.fragment(u"x = 4")
T = F.copy()... | atNod | e), T)
def test_pos_is_transferred(self):
F = self.fragment(u"""
x = y
x = u * v ** w
""")
T = F.substitute({"v" : NameNode(pos=None, name="a")})
v = F.root.stats[1].rhs.operand2.operand1
a = T.stats[1].rhs.operand2.operand1
self.assertEquals(v.pos, a... |
amonmoce/corba_examples | omniORBpy-4.2.1/build/python/COS/CosCollection__POA/__init__.py | Python | mit | 249 | 0.004016 | # DO NOT EDIT THIS FILE!
#
# Python module CosCollection__POA generated by o | mniidl
imp | ort omniORB
omniORB.updateModule("CosCollection__POA")
# ** 1. Stub files contributing to this module
import CosCollection_idl
# ** 2. Sub-modules
# ** 3. End
|
XeCycle/indico | indico/core/index/event.py | Python | gpl-3.0 | 3,751 | 0.000267 | # This file is part of Indico.
# Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (a... |
i = 0
for cid, index in self._container.iteritems():
# simple data structure check
for problem in index._check():
yield problem
# consistency with CategoryManager
if cid not in categIdx:
yield "Category '%s' not in Catego... | for ts, conf in index.iteritems():
if conf.getId() not in confIdx:
yield "[%s] Conference '%s'(%s) not in ConferenceHolder" \
% (cid, conf.getId(), ts)
if dbi and i % 100 == 99:
dbi.abort()
i += 1
|
UQ-UQx/edx-platform_lti | lms/djangoapps/courseware/access.py | Python | agpl-3.0 | 20,899 | 0.002871 | """This file contains (or should), all access control logic for the courseware.
Ideally, it will be the only place that needs to know about any special settings
like DISABLE_START_DATES"""
import logging
from datetime import datetime, timedelta
import pytz
from django.conf import settings
from django.contrib.auth.mode... | nalAuthMap
from courseware.masquerade imp | ort is_masquerading_as_student
from django.utils.timezone import UTC
from student import auth
from student.roles import (
GlobalStaff, CourseStaffRole, CourseInstructorRole,
OrgStaffRole, OrgInstructorRole, CourseBetaTesterRole
)
from student.models import CourseEnrollment, CourseEnrollmentAllowed
from opaque_k... |
lincolnloop/django-ttag | ttag/__init__.py | Python | bsd-3-clause | 840 | 0 | try:
from ttag.args import Arg, BasicArg, BooleanArg, ConstantArg, DateArg, \
DateTimeArg, IntegerArg, IsInstanceArg, KeywordsArg, \
ModelInstanceArg, StringArg, TimeArg, MultiArg
from ttag.core import Tag
from ttag.exceptions import TagArgumentMissing, TagValidationError
from ttag impor... | ur if ttag is
# being installed at | the same time as Django.
pass
VERSION = (3, 0)
def get_version(number_only=False):
version = [str(VERSION[0])]
number = True
for bit in VERSION[1:]:
if not isinstance(bit, int):
if number_only:
break
number = False
version.append(number and '.'... |
dnsbob/pynet_testz | SNMP/get_snmp_name_desc.py | Python | apache-2.0 | 418 | 0.0311 |
''' get_snmp_name_desc.py '''
from snmp_helper import snmp_get_oid,snmp_extract
PORT=161
COMMUNITY='galileo'
rtrs={'pynet-rtr1':'184.105.247.70', 'pynet-rtr2':'184.105.247.71'}
oids={'sysName':'1.3.6.1.2.1.1.5.0', 'sysDescr':'1.3.6.1.2.1 | .1.1.0'}
for rtr in rtrs.keys():
print rtr
for oid in oids.keys():
print " | " + oid + " = " + snmp_extract(snmp_get_oid((rtrs[rtr],COMMUNITY,PORT),oids[oid]))
|
Donkyhotay/MoonPy | twisted/conch/ssh/userauth.py | Python | gpl-3.0 | 29,730 | 0.002926 | # -*- test-case-name: twisted.conch.test.test_userauth -*-
# Copyright (c) 2001-2009 Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Implementation of the ssh-userauth service.
Currently implemented authentication types are public-key and password.
Maintainer: Paul Swartz
"""
import struct, warnings
from... | chError('unsupported authentication, failing'))
kind = kind.replace('-', '_')
f = getattr(self,'auth_%s'%kind, None)
if f:
ret = f(data)
if not ret:
return defer.fail(
error.ConchError('% | s return None instead of a Deferred'
% kind))
else:
return ret
return defer.fail(error.ConchError('bad auth type: %s' % kind))
def ssh_USERAUTH_REQUEST(self, packet):
"""
The client has requested authentication. Payload::
... |
jcostamagna/restauranteConcurrente | test/lib/googletest/test/gtest_env_var_test.py | Python | gpl-3.0 | 4,036 | 0.005451 | #!/usr/bin/env python
#
# Copyright 2008, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list... | _author__ = 'wan@google.com (Zhanyong Wan | )'
import os
import gtest_test_utils
IS_WINDOWS = os.name == 'nt'
IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux'
COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_env_var_test_')
environ = os.environ.copy()
def AssertEq(expected, actual):
if expected != actual:
print('Expected: %s' % (exp... |
tomshen/checkmeout | venmo.py | Python | mit | 1,337 | 0.00374 | from requests import get, post
class Venmo(object):
"""A wrapper for the Venmo HTTP API"""
endpoint = 'https://api.venmo.com'
def __init__(self, access_token):
super(Venmo, self).__init__()
self.scope = 'access_profile,access_friends,make_payments'
self.access_token = access_token
... | ta']
def pay(self, user_id, note, amount, audience='friends'):
path = self.endpoint + '/payments'
params = {
| 'access_token': self.access_token,
'user_id': user_id,
'note': note,
'amount': amount,
'audience': audience
}
return post(path, params=params).json()
def charge(self, user_id, note, amount, audience='friends'):
return pay(user_id, note,... |
flake123p/ProjectH | Python/_Basics2_/UI_Tk/tkui.py | Python | gpl-3.0 | 126 | 0 | fr | om tkinter import *
root = Tk()
some = Label(root, text="Tk's job!!", width="30", height="5")
some.pack()
root.mainloop() | |
tensorflow/tensorflow | tensorflow/lite/testing/op_tests/cumsum.py | Python | apache-2.0 | 1,920 | 0.002604 | # 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... | r the License.
# ==============================================================================
"""Test configs for cumsum."""
import tensorflow.compat.v1 as tf
from tensorflow.lite.testing.zip_test_utils import create_tensor_data
from tensorflow.lite.testing.zip_test_utils import make_zip_of_tests
from tensorflow.lite... | test_utils import register_make_test_function
@register_make_test_function()
def make_cumsum_tests(options):
"""Make a set of tests to do cumsum."""
test_parameters = [{
"shape": [(3, 6), (8, 9, 7)],
"dtype": [tf.int32, tf.int64, tf.float32],
"axis": [0, 1],
"exclusive": [True, False],
... |
glynjackson/django-time-out | manage.py | Python | mit | 289 | 0 | #!/usr/bin/env python
import os
import sys
| if __name__ == "__main__":
os.environ.setdefault('DJANGO_SETTINGS_MODULE',
'time_out.tests.south_settings')
from django.core.management import execute_from_command_line
execute_f | rom_command_line(sys.argv)
|
Azure/azure-sdk-for-python | sdk/hybridcompute/azure-mgmt-hybridcompute/azure/mgmt/hybridcompute/aio/operations/_machine_extensions_operations.py | Python | mit | 30,060 | 0.005489 | # 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 ... | ------------------------------------------------------------------------
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpRespo | nseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.mgmt.core.exceptions import ARMErrorForma... |
val314159/hackweek-dec2016 | classy.py | Python | unlicense | 9,664 | 0.011279 | # Copyright 2015 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... | not exist %s', image)
image_data = tf.gfile.FastGFile(image, 'rb').read()
with tf.Session() as sess:
# Some useful tensors:
# | 'softmax:0': A tensor containing the normalized prediction across
# 1000 labels.
# 'pool_3:0': A tensor containing the next-to-last layer containing 2048
# float description of the image.
# 'DecodeJpeg/contents:0': A tensor containing a string providing JPEG
# encoding of the image.
# Runs... |
Danceiny/HackGirlfriend | Spider/commentbox/data/push_cache.py | Python | apache-2.0 | 856 | 0.004717 | #coding=utf-8
import sys
sys.path.insert(0, '.')
from app import create_app
create_app()
from models import Song, Artist, SEARCH_KEY, SUGGEST_KEY, search, suggest
SEARCH_KEY = 'commentbox:search:{type}:{id}'
SUGGEST_KEY = 'commentbox:suggest:{text}'
songs = [song.name for song in Song.objects.all()]
artists = [art... | t预热
for text in text_set:
print 'cache suggest', text
suggest(text)
# search预热
for song in Song.objects.all():
print 'cache search song', song.id
search(song.id, 'song')
for artist in Artist.o | bjects.all():
print 'cache search artist', artist.id
search(artist.id, 'artist')
|
adbetin/organico-cooperativas | organico_cooperativas/asgi.py | Python | gpl-3.0 | 163 | 0.01227 | import os
import channels.asgi
os. | environ.setdefault("DJANGO_SETTINGS_MODULE", "organico_cooperativas.settings")
channel_layer = channels.asgi. | get_channel_layer() |
rizac/gfzreport | tests/test_templates_network.py | Python | gpl-3.0 | 24,752 | 0.004404 | '''
Created on Jun 19, 2016
@author: riccardo
'''
import os
import sys
import glob
from click.testing import CliRunner
from gfzreport.cli import main as gfzreport_main
from gfzreport.sphinxbuild import get_logfilename as get_build_logfilename
from gfzreport.templates.utils import get_logfilename as get_template_logfil... | ile).st_mtime
shutil.rmtree(conf_files_dir)
shutil.rmtree( | data_dir)
assert not os.path.isdir(conf_files_dir)
assert not os.path.isdir(data_dir)
confile_path = os.path.join(outpath_, 'conf.py')
# modify conf.py and assert later that we overwrote it:
with open(confile_path) as opn_:
text = "dummyvar='ert'" + opn_.read()
... |
modelblocks/modelblocks-release | resource-jlstm/scripts/lm_1b/data_utils.py | Python | gpl-3.0 | 8,982 | 0.008907 | # Copy | right 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 applicable la... | lied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""A library for loading 1B word benchmark dataset."""
import random
import numpy as np
import tensorflow as tf
class Vocabul... |
andrewleech/script.module.human_curl | lib/human_curl/core.py | Python | bsd-3-clause | 30,880 | 0.001749 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
human_curl.core
~~~~~~~~~~~~~~~
Heart of human_curl library
:copyright: Copyright 2011 - 2012 by Alexandr Lispython (alex@obout.ru).
:license: BSD, see LICENSE for more details.
"""
import time
from os.path import exists as file_exists
from logging import getLogger... |
from itertools import chain
from urlparse import urlparse, urljoin, urlunparse, parse_qsl
from types import (StringTypes, TupleType, DictType, NoneType,
ListType, FunctionType)
try:
import pycurl2 as pycurl
except Impor | tError:
import pycurl
from . import get_version
from .compat import json
from .auth import AuthManager, BasicAuth
from .exceptions import (InvalidMethod, CurlError, InterfaceError)
from .utils import (decode_gzip, CaseInsensitiveDict, to_cookiejar,
morsel_to_cookie, data_wrapper, make_curl_post_... |
uclouvain/osis | ddd/logic/learning_unit/tests/use_case/read/test_get_effective_class_warnings_service.py | Python | agpl-3.0 | 12,176 | 0.002628 | ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core ... | me is greater than the volume of the LU')
),
warnings
)
def test_should_get_volumes_sum_greater_than_learning_unit_volume_annual_warning(self):
effective_class = attr.evolve(
self.effective_class,
volumes=ClassVolumes(
volume_first_qua... | unit.lecturing_part.volumes.volume_first_quadrimester + 1,
volume_second_quadrimester=self.learning_unit.lecturing_part.volumes.volume_second_quadrimester + 1
)
)
self.effective_class_repository.save(effective_class)
warnings = get_effective_class_warnings(
... |
babelsberg/babelsberg-r | tests/modules/test_marshal.py | Python | bsd-3-clause | 16,593 | 0.002833 | from ..base import BaseTopazTest
class TestMarshal(BaseTopazTest):
def test_version_constants(self, space):
w_res = space.execute("return Marshal::MAJOR_VERSION")
assert space.int_w(w_res) = | = 4
w_res = space.execute("return Marshal::MINOR_VERSION")
assert space.int_w(w_res) == 8
w_res = space.execute("return Marshal.dump('test')[0].ord")
assert space.int_w(w_res) == 4
w_res = space.execute("return Marshal.dump('test')[1].ord")
assert space.int_w(w_res) ==... | "return Marshal.dump(nil)")
assert space.str_w(w_res) == "\x04\b0"
w_res = space.execute("return Marshal.dump(true)")
assert space.str_w(w_res) == "\x04\bT"
w_res = space.execute("return Marshal.dump(false)")
assert space.str_w(w_res) == "\x04\bF"
def test_load_constants(s... |
looker/sentry | src/sentry/runner/__init__.py | Python | bsd-3-clause | 5,028 | 0.001989 | """
sentry.runner
~~~~~~~~~~~~~
:copyright: (c) 2015 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import, print_function
import os
import click
import sys
import sentry
import datetime
from sentry.utils.imports import import_string
... | )' % (sentry.VERSION, sentry.__build_ | _[:12])
@click.group()
@click.option(
'--config',
default='',
envvar='SENTRY_CONF',
help='Path to configuration files.',
metavar='PATH'
)
@click.version_option(version=version_string)
@click.pass_context
def cli(ctx, config):
"""Sentry is cross-platform crash reporting built with love.
Th... |
paulmadore/Eric-IDE | 6-6.0.9/eric/Helpviewer/HelpTabWidget.py | Python | gpl-3.0 | 37,071 | 0.003911 | # -*- coding: utf-8 -*-
# Copyright (c) 2010 - 2015 Detlev Offenbach <detlev@die-offenbachs.de>
#
"""
Module implementing the central widget showing the web pages.
"""
from __future__ import unicode_literals
import os
from PyQt5.QtCore import pyqtSignal, pyqtSlot, Qt, QUrl
from PyQt5.QtGui import QIcon
from PyQt5.... | tarrow.png"),
self.tr('Move Right'), self.__tabCo | ntextMenuMoveRight)
self.__tabContextMenu.addSeparator()
self.tabContextCloneAct = self.__tabContextMenu.addAction(
self.tr("Duplicate Page"), self.__tabContextMenuClone)
self.__tabContextMenu.addSeparator()
self.tabContextCloseAct = self.__tabContextMenu.addAction(
... |
tareqalayan/pytest | testing/test_capture.py | Python | mit | 40,501 | 0.000148 | from __future__ import absolute_import, division, print_function
# note: py.io capture tests where copied from
# pylib 1.4.20.dev2 (rev 13d9af95547e)
from __future__ import with_statement
import pickle
import os
import sys
from io import UnsupportedOperation
import _pytest._code
import py
import pytest
import contextl... | nc2():
print ("in func2")
assert 0
""")
| result = testdir.runpytest(p)
s = result.stdout.str()
assert "in func1" not in s
assert "in func2" in s
def test_teardown_capturing(self, testdir):
p = testdir.makepyfile("""
def setup_function(function):
print ("setup func1")
def teardown_f... |
noelevans/sandpit | euler/big_summation_q13.py | Python | mit | 6,516 | 0 | DATA = """ 37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
91942213363574161572522430563301811072406154908250
23067588207539346171171980310421047513778063246676
... | 65378607361501 | 080857009149939512557028198746004375
35829035317434717326932123578154982629742552737307
94953759765105305946966067683156574377167401875275
88902802571733229619176668713819931811048770190271
25267680276078003013678680992525463401061632866526
3627021854049770558... |
SimplyMinimal/Liberarsi | calendar-cmd-line-sample/sample.py | Python | apache-2.0 | 4,864 | 0.00884 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2013 Google 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 applicabl... | ITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command-line skeleton application for Calendar API.
Usage:
$ python sample.py
You can also get help on all the command-line flags the program understands
by runnin... | help
"""
import argparse
import httplib2
import os
import sys
from apiclient import discovery
from oauth2client import file
from oauth2client import client
from oauth2client import tools
# Parser for command-line arguments.
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawD... |
qvazzler/Flexget | tests/test_user.py | Python | mit | 955 | 0 | from __future__ import unicode_literals, division, absolute_import
from builtins import * # pylint: disable=unused-import, redefined-builtin
from flexget.utils import json
class TestUserAPI(object):
config = 'tasks: {}'
def test_change_password(self, execute_task, api_client):
weak_password = {'pa... | api_client.json_put('/user/', data=json.dumps(medium_password))
assert rsp.status_code == 200
rsp = api_client.json_put('/user/', data=json.dumps(strong_password))
assert rsp.status_code == 200
def test_ch | ange_token(self, execute_task, api_client):
rsp = api_client.get('user/token/')
assert rsp.status_code == 200
|
1tush/reviewboard | reviewboard/webapi/tests/test_repository.py | Python | mit | 31,592 | 0 | from __future__ import unicode_literals
import os
import paramiko
from django.utils import six
from djblets.testing.decorators import add_fixtures
from reviewboard import scmtools
from reviewboard.hostingsvcs.models import HostingServiceAccount
from reviewboard.reviews.models import ReviewRequest
from reviewboard.sc... | te_repository(name='test1', path='dummy1', tool_name='Test')
self.create_repository(name='test2', path='dummy2', tool_name='Test')
self.create_repository(name='test3', path='dummy3', tool_name='Test')
rsp = self.api_get(get_repository_list_url() + '?path=dummy1,dum | my2',
expected_mimetype=repository_list_mimetype)
self.assertEqual(rsp['stat'], 'ok')
self.assertEqual(len(rsp['repositories']), 2)
self.assertEqual(rsp['repositories'][0]['name'], 'test1')
self.assertEqual(rsp['repositories'][1]['name'], 'test2')
def test... |
prasadtalasila/INET-Vagrant-Demos | Nonce_Demo/impacket-0.9.12/impacket/dcerpc/v5/nrpc.py | Python | gpl-2.0 | 91,296 | 0.010493 | # Copyright (c) 2003-2014 CORE Security Technologies
#
# This software is provided under under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# $Id: nrpc.py 1244 2014-06-26 13:54:47Z bethus@gmail.com $
#
# Author: Alberto Solino
#
# Description:... | N_CREDENTIAL
class UCHAR_FIXED_ARRAY(NDRUniFixedArray):
align = 1
def getDataLen(self, data):
return len(CYPHER_BLOCK())
class NETLOGON_CREDENTIAL(NDRSTRUCT):
structure = (
('Data',UCHAR_FIXED_ARRAY),
)
def getAlignment(self):
ret | urn 1
# 2.2.1.1.5 NETLOGON_AUTHENTICATOR
class NETLOGON_AUTHENTICATOR(NDRSTRUCT):
structure = (
('Credential', NETLOGON_CREDENTIAL),
('Timestamp', DWORD),
)
class PNETLOGON_AUTHENTICATOR(NDRPOINTER):
referent = (
('Data', NETLOGON_AUTHENTICATOR),
)
# 2.2.1.2.1 DOMAIN_CONTROLLE... |
dmpetrov/dataversioncontrol | dvc/ui/pager.py | Python | apache-2.0 | 2,414 | 0 | """Draws DAG in ASCII."""
import logging
import os
import pydoc
import sys
from rich.pager import Pager
from dvc.env import DVC_PAGER
from dvc.utils import format_link
logger = logging.getLogger(__name__)
DEFAULT_PAGER = "less"
LESS = "LESS"
PAGER_ENV = "PAGER"
def prepare_default_pager(
clear_screen: bool ... | ss_env,
no_init=not less_env,
)
return pager
def pager(text: str) -> None:
_pager = find_pager()
logger.trace(f"Using pager: '{_pager}'") # type: ignore[attr-defined]
make_pager(_pager)(text)
class DvcPager(Pager):
de | f show(self, content: str) -> None:
pager(content)
|
Btjones711/RiotApplications | DailyIP.py | Python | mit | 1,899 | 0.005793 | """DailyIP.py
Program written to do the backend calculations for a daily IP calculator
Brendan Jones
3/8/2017 -started ground work and function layout
"""
import RiotAPI as RA
import time
current_time = time.time()
def getTimePlayed(json_index):
"""Function that returns the time played of a given game
input:... | for i in range(len(recentGames)):
current = recentGames[i]
time_played = getTimePlayed(current)
end_date = getEndDate(current)
if check_date(getDateOfGame(time_played, end_date),date):
sum1 += getIP(current)
return sum1
######Unit tesitin | g area######
if __name__ == "__main__":
my_id = RA.getSummonerID(["BruttonGuster"])
x = RA.getRecentGames(my_id[0])['games']
print(x)
print(getDateOfGame(getTimePlayed(x[9]), getEndDate(x[9])))
print(sum_daily_ip(x,"08 Mar 2017"))
|
Erotemic/utool | utool/util_cplat.py | Python | apache-2.0 | 49,052 | 0.002752 | # -*- coding: utf-8 -*-
"""
cross platform utilities
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import pipes
import six
import sys
import platform
import subprocess
import shlex
from os.path import exists, normpath, basename, dirname, join, expanduser
from utool imp... | ion time:",statbuf.st_mtime
def get_file_nBytes(fpath):
return os.path.getsize(fpath)
def get_file_nBytes_str(fpath):
from utool import util_str
return util_str.byte_str2(os.path.getsize(fpath))
def get_disk_space(start_path='.'):
"""
References:
http:/ | /stackoverflow.com/questions/1392413/calculating-a-directory-size-using-python
"""
total_size = 0
for root, dname_list, fname_list in os.walk(start_path):
for fname in fname_list:
fpath = os.path.join(root, fname)
try:
total_size += os.path.getsize(fpath)
... |
amanharitsh123/zulip | zerver/webhooks/semaphore/view.py | Python | apache-2.0 | 2,201 | 0.001363 | # Webhooks for external integrations.
from django.http import HttpRequest, HttpResponse
from django.utils.translation import ugettext as _
from zerver.models import get_client
from zerver.lib.actions import check_send_stream_message
from zerver.lib.response import json_success, json_error
from zerver.decorator import... | rgument_type='body'),
stream=REQ(default='builds')):
# type: (HttpRequest, UserProfile, Dict[str, Any], str) -> HttpResponse
# semaphore only gives the last commit, even if there were multiple commits
# since the last build
branch_name = payload["branch_name"]
| project_name = payload["project_name"]
result = payload["result"]
event = payload["event"]
commit_id = payload["commit"]["id"]
commit_url = payload["commit"]["url"]
author_email = payload["commit"]["author_email"]
message = payload["commit"]["message"]
if event == "build":
build_... |
biomodels/BIOMD0000000033 | setup.py | Python | cc0-1.0 | 377 | 0.005305 | from setuptools import setup, find_packages
setup(name='BIOMD0000000033',
version=20140916,
description='BIOMD000 | 0000033 from BioModels',
url='http://www.ebi.ac.uk/biomodels-main/BIOMD | 0000000033',
maintainer='Stanley Gu',
maintainer_url='stanleygu@gmail.com',
packages=find_packages(),
package_data={'': ['*.xml', 'README.md']},
) |
sadad111/leetcodebox | Minesweeper.py | Python | gpl-3.0 | 2,887 | 0.004157 | # public class Solution {
# public char[][] updateBoard(char[][] board, int[] click) {
# int m = board.length, n = board[0].length;
# int row = click[0], col = click[1];
#
# if (board[row][col] == 'M') { // Mine
# board[row][col] = 'X';
# }
# else { // Empty
# ... | )
queue = collections.deque()
queue.append((click[0], click[1]))
valid_neighbours = lambda (i, j): 0<=i<m and 0<=j<n
while queue:
x, y = queue.pop()
if board[x][y] == 'M':
board[x][y] = 'X'
else:
| # Filter out the valid neighbours
neighbours = filter(valid_neighbours, [(x-1, y), (x+1, y),
(x, y-1), (x, y+1), (x-1, y-1), (x+1, y-1), (x-1, y+1), (x+1, y+1)])
# Count the number of mines amongst the neighbours
mine_count = sum([board[i... |
Pulgama/supriya | supriya/ugens/PV_MagSmear.py | Python | mit | 585 | 0.003419 | import collections
from supriya.ugens | .PV_ChainUGen import PV_ChainUGen
class PV_MagSmear(PV_ChainUGen):
"""
Averages magnitudes across bins.
::
>>> pv_chain = supriya.ugens.FFT(
... source=supriya.ugens.WhiteNoise.ar(),
... )
>>> pv_mag_smear = supriya.ugens.PV_MagSmear.new(
... bins=0,
... | ections.OrderedDict([("pv_chain", None), ("bins", 0)])
|
defjam903/Google-Interview-prep | Searching/Bunny_Lap.py | Python | mit | 110 | 0.063636 | def getoverlap(a,b):
| return max(0,min(a[1],b[1]) - max(a[0],b[0]))
print(getoverlap( [[1, 3], [3, 6]])) | |
dcastro9/video_library_project | Django/video_manager/models.py | Python | mit | 906 | 0.00883 | from django.db import models
from django.contrib.auth.models import User
class Task(models.Model):
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class Surgeon(models.Model):
name = models.CharField(max_length=100)
def __unicode__(self):
return self.... | def __unicode__(self):
return self.filename + " | " + self.task.name + " | By: " + self.surgeon.name
class Rating(models.Model):
user = models.Fo | reignKey(User)
video = models.ForeignKey(Video)
rating = models.IntegerField(max_length=5, choices=[(i, i) for i in range(1,6)])
def __unicode__(self):
return self.user.username + "'s Rating for " + self.video.filename + " - " + str(self.rating) |
chintak/google-python-ex | babynames/solution/babynames.py | Python | apache-2.0 | 3,874 | 0.015746 | #!/usr/bin/python
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
import sys
import re
"""Baby Names exercise
Define the extract_names() function below and c... | .
names = []
# Open and read the file.
f = open(filename, 'rU')
text = f.read()
# Could process the file line-by-line, but regex on the whole text
# at once is even easier.
# Get the year.
year_match = re.search(r'Popularity\sin\s(\d\d\d\d)', text)
if not ye | ar_match:
# We didn't find a year, so we'll exit with an error message.
sys.stderr.write('Couldn\'t find the year!\n')
sys.exit(1)
year = year_match.group(1)
names.append(year)
# Extract all the data tuples with a findall()
# each tuple is: (rank, boy-name, girl-name)
tuples = re.findall(r'<td>(\... |
boehlke/OpenSlides | openslides/agenda/views.py | Python | mit | 16,711 | 0.001257 | import jsonschema
from django.contrib.auth import get_user_model
from django.db import transaction
from openslides.core.config import config
from openslides.utils.autoupdate import inform_changed_data
from openslides.utils.exceptions import OpenSlidesError
from openslides.utils.rest_api import (
GenericViewSet,
... | .request.user, "agenda.can_manage_list_of_speakers"
)
elif self.action in ("numbering",):
result = has_perm(self.request.user, "agenda.can_see") and has_perm(
self.request.user, "agenda.can_manage"
)
else:
result = False
re | turn result
def update(self, *args, **kwargs):
"""
Customized view endpoint to update all children if the item type has changed.
"""
old_type = self.get_object().type
response = super().update(*args, **kwargs)
# Update all children if the item type has changed.
... |
Andrwe/py3status | py3status/argparsers.py | Python | bsd-3-clause | 6,668 | 0.0003 | import argparse
import os
import subprocess
from platform import python_version
from py3status.version import version
def parse_cli_args():
"""
Parse the command line arguments
"""
# get config paths
home_path = os.path.expanduser("~")
xdg_home_path = os.environ.get("XDG_CONFIG_HOME", "{}/.co... | self.print_help()
self.exit(1)
# hide choices on errors
def _check_value(self, action, value):
if action.choices is not None and value not in action.choices:
raise argpa | rse.ArgumentError(
action, "invalid choice: '{}'".format(value)
)
class HelpFormatter(argparse.ArgumentDefaultsHelpFormatter):
def _format_action_invocation(self, action):
metavar = self._format_args(action, action.dest.upper())
return "{} {}".for... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.