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 |
|---|---|---|---|---|---|---|---|---|
jimsrc/seatos | sheaths/src/forbush/test.py | Python | mit | 2,196 | 0.037341 | from numpy import *
from pylab import *
from Scientific.IO.NetCDF import NetCDFFile
from datetime import datetime, time
from read_table import t_shck
from funcs import *
fname_inp_murdo = "../../../../actividad_solar/neutron_monitors/mcmurdo/mcmurdo_utc_correg.dat"
fname_inp_evs = "../data_317events_iii.nc"
data_murdo... | set / taufd
nonans = ~isnan(ratio)
cond = []
cond += [ ((MC==0) & nonans) & cond_wTau ] # irregular icme
cond += [ ((MC==1) & nonans) & cond_wTau ] # B-field rotation
cond += [ ((MC==2) & nonans) & cond_wTau ] # MCs only
#--- filtramos por ratio:
cond[0] = cond[0] & (ratio<THRES)
cond[1] = cond[1] & (ratio<THRES)... | # B-field rotation
ind += [find(cond[2])] # MCs only
n0 = len(ind[0])
n1 = len(ind[1])
n2 = len(ind[2])
print "n0, n1, n2: %d, %d, %d" % (n0, n1, n2)
import time
for j in range(3):
taumin = min(taufd[cond[j]])
taumax = max(taufd[cond[j]])
print " partial selection #", j
print " tau [days] (min/max): %2.1f / %... |
blechschmidt/massdns | scripts/ct.py | Python | gpl-3.0 | 1,748 | 0.00286 | #!/usr/bin/env python3
import argparse
import json
import sys
import urllib.parse
import urllib.request
parser = argparse.ArgumentParser(description='Certificate transparency name extractor.')
parser.add_argument('-d', '--domains', metavar='domain_file', type=str, help='Domains for certificate search.',
... | -8'))
for crt in data:
for domain in crt['name_value'].split('\n'):
if '@' in domain:
continue
if domain not in subdomains:
subdomains.add(domain)
try:
print(domain)
... | 3/library/signal.html#note-on-sigpipe
# Python flushes standard streams on exit; redirect remaining output
# to devnull to avoid another BrokenPipeError at shutdown
devnull = os.open(os.devnull, os.O_WRONLY)
os.dup2(devnull,... |
moddevices/mod-pacmanager | pacman/settings.py | Python | gpl-3.0 | 597 | 0.005025 | import os
DOWNLOAD_TMP_DIR = '/tmp'
REPOSITORY_PUBLIC_KEY = '/root/keys/cloud_key.pub'
LOCAL_REPOSITORY_DIR = '/pkgs'
HTML_DIR = '/usr/share/mod-pacmanager/html/'
IHM_RESET_SCRIPT = '/root/reset.py'
if os.path.exists("/root/repository"):
fh = open("/root/repository")
REPOSITORY_ADDRESS = fh.read().strip()
... | man'
def check_environment():
for dirname in (DOWNLOAD_TMP_DIR, LOCAL_REPOSITORY_DIR):
if not os.path | .exists(dirname):
os.mkdir(dirname)
|
manti-by/Telonius | app/bearing/management/commands/remove_bearing_items_duplicates.py | Python | bsd-3-clause | 1,877 | 0.001598 | import logging
from django.core.management.base import BaseCommand
from bearing.models import BearingISO, BearingManufacturer, BearingItem
from bearing.deploy.duplicates import ISO_MAP, MANUFACTURER_MAP
from core.mixins import PrettyPrintCommandMixin
logger = l | ogging.getLogger('file')
class Command(PrettyPrintCommandMixin, BaseCommand):
help = 'Remove Bearing Items duplicates'
@staticmethod
def get_iso_replacement(value):
for target_value, duplicates_set in ISO_MAP.items():
if value in duplicates_set:
return target_value
... | for target_value, duplicates_set in MANUFACTURER_MAP.items():
if value in duplicates_set:
return target_value
def handle(self, *args, **options):
super().handle(*args, **options)
count = errors = 0
for item in BearingItem.objects.all():
try:
... |
ekansa/open-context-py | opencontext_py/apps/exports/exptables/identifiers.py | Python | gpl-3.0 | 1,536 | 0.001953 | from django.conf import settings
from opencontext_py.apps.entities.uri.models import URImanagement
from opencontext_py.apps.ocitems.identifiers.models import StableIdentifer
class ExpTableIdentifiers():
"""
Methods for managing identifiers of tables. This is needed because
of legacy export tables that hav... | ier.split('/')
self.table_id = id_ex[1] + '_' + id_ex[0]
self.public_table_id = identifier
self.uri = URImanagement.make_oc_uri(self.public_table_id, 'tables')
elif '_' in identifier:
id_ex = identifier.split('_')
self.table_id = identifier
... | self.uri = URImanagement.make_oc_uri(self.public_table_id, 'tables')
else:
self.table_id = identifier
self.public_table_id = identifier
self.uri = URImanagement.make_oc_uri(self.public_table_id, 'tables')
|
kakaroto/amsn2 | amsn2/plugins/core.py | Python | gpl-2.0 | 1,882 | 0.008502 | # plugins module for amsn2
"""
Plugins with amsn2 will be a subclass of the aMSNPlugin() class.
When this module is initially imported it should load the plugins from the last session. Done in the init() proc.
Then the GUI should call plugins.loadPlugin(name) or plugins.unLoadPlugin(name) in order to deal with plugins.... | module for the plugin. The module is then responsible for calling plugins.registerPlugin(instance).
def loadPlugin(plugin_name): pass
# | unLoadPlugin(plugin_name)
# Called to unload a plugin. Name is name as set in plugin's XML.
def unLoadPlugin(plugin_name): pass
# registerPlugin(plugin_instance)
# Saves the instance of the plugin, and registers it in the loaded list.
def registerPlugin(plugin_instance): pass
# getPlugins()
# Returns a list of all a... |
uml-robotics/player-2.1.3 | libplayercore/bindings/java/parse.py | Python | gpl-2.0 | 9,344 | 0.014769 | #!/usr/bin/env python
import re
import string
import sys
import os
USAGE = 'USAGE: parse.y <player.h> <playercore_casts.i> <playercore_arraysofclasses.i> <Jplayercore> <playercore> <player.java>'
if __name__ == '__main__':
if len(sys.argv) != 7:
print USAGE
sys.exit(-1)
infilename = sys.argv[1]
outfi... | f type == 'char':
jtype = 'char'
elif type == 'bool_t':
jtype = 'boolean'
elif type == 'double':
jtype = 'd | ouble'
elif type == 'float':
jtype = 'float'
else:
# rely on a previous declaration of a J class for this type
jtype = 'J' + type
builtin_type = 0
# iterate through each variable
for var in vars:
varstring = var.string[var.start(1):var.end(1)]
# i... |
mpetyx/pychatbot | SemanticWebApproach/RoboWriter/allegrordf-1.0.1/rdfliba/test.py | Python | apache-2.0 | 2,835 | 0.01552 | import unittest2
from rdflib import Namespace, Literal, URIRef
from rdflib.namespace import _XSD_NS
from store import Store
class TestStore(unittest2.TestCase):
def setUp(self):
self.store = Store(name="scratch")
self.ns = Namespace('http://example.com/#')
def tearDown(self):
... | triple = (self.ns['alice'],self.ns['name'],Literal('Alice'))
self.store.add(triple)
self.store.add((self.ns['bob'],self.ns['name'],Literal('Bob')))
for tri in self.store.query("SELECT ?p ?o WHERE { ?s ?p ?o .}", initBindings={'s':self.ns['alice']}):
for i in range(1,3):
... | pe=_XSD_NS.date)
comp = Literal('2006-01-01', datatype=_XSD_NS.date)
triple = (self.ns['alice'],self.ns['birthdate'],birth)
self.store.add(triple)
for s, p, o in self.store.query("SELECT ?s ?p ?o WHERE {?s ?p ?o .}"):
self.assertLess(comp,birth)
if __name__ == '__main__... |
midnightmagic/bitcoin | test/functional/feature_abortnode.py | Python | mit | 1,738 | 0 | #!/usr/bin/env python3
# Copyright (c) 2019-2020 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test bitcoind aborts if can't disconnect a block.
- Start a single node and generate 3 blocks.
- Delet... | hat bitcoind AbortNode's.
"""
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import wait_until, get_datadir_path, connect_nodes
import os
class AbortNodeTest(BitcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 2... | l connect the nodes later
def run_test(self):
self.nodes[0].generate(3)
datadir = get_datadir_path(self.options.tmpdir, 0)
# Deleting the undo file will result in reorg failure
os.unlink(os.path.join(datadir, self.chain, 'blocks', 'rev00000.dat'))
# Connecting to a node wi... |
piskvorky/smart_open | smart_open/tests/test_utils.py | Python | mit | 528 | 0 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2019 Radim Rehurek <me@radimrehurek.com>
#
# This code is distributed under the terms and conditions
# from the MIT License (MIT).
#
import unittest
import smart_open.utils
class Cl | ampTest(unittest.TestCase):
def test_low(self):
self.assertEqual(smart_open.utils.clamp(5, 0, 10), 5)
def test_high(self):
self.assertEqual(smart_open.ut | ils.clamp(11, 0, 10), 10)
def test_out_of_range(self):
self.assertEqual(smart_open.utils.clamp(-1, 0, 10), 0)
|
brainstorm/bcbio-nextgen | bcbio/cwl/cwlutils.py | Python | mit | 3,196 | 0.003129 | """Useful utilities for handling CWL inputs and outputs.
This is shared functionality abstracted across multiple approaches, currently
mostly handling CWL records. This needs some generalization to apply across
non-variant calling workflows.
"""
import collections
import pprint
import toolz as tz
def _get_all_cwlkey... | g decision making about which are primary and extras.
"""
default_keys = set(["metadata__batch", "config__algorith | m__validate",
"config__algorithm__validate_regions", "validate__summary",
"validate__tp", "validate__fp", "validate__fn"])
all_keys = set([])
for data in items:
all_keys.update(set(data["cwl_keys"]))
all_keys.update(default_keys)
return all_keys
d... |
SymbiFlow/edalize | edalize/vcs.py | Python | bsd-2-clause | 3,290 | 0.001216 | # Copyright edalize contributors
# Licensed under the 2-Clause BSD License, see LICENSE for details.
# SPDX-License-Identifier: BSD-2-Clause
import os
import logging
from edalize.edatool import Edatool
logger = logging.getLogger(__name__)
class Vcs(Edatool):
_description = """ Synopsys VCS Backend
VCS is one... | )
plusargs = []
if self.plusarg:
for key, value in self.plusarg.items():
plusargs += ["+{}={}".format(key, self._param_value_str(value))]
vcs_options = self.tool_options.get("vcs_options", [])
(src_files, incdirs) = self._get_fileset_files(force_slash=True... | ix"):
vcs_options.append("-sverilog")
if self._filelist_has_filetype(src_files, "verilog2001", match_type="exact"):
vcs_options.append("+v2k")
template_vars = {
"name": self.name,
"vcs_options": vcs_options,
"run_options": self.tool_options.g... |
tom-heimbrodt/oeplatform | literature/urls.py | Python | agpl-3.0 | 396 | 0 | from django.conf.urls import url
from literature import views
pgsql_q | ualifier = r"[\w\d_]+"
urlpatterns = [
url(r'^$', views.list_references,),
url(r'^en | try/upload/$', views.upload,),
url(r'^entry/(?P<entries_id>\d+)/$', views.show_entry,),
url(r'^entry/add$', views.LiteratureView.as_view(),),
url(r'^entry/(?P<entries_id>\d+)/edit/$', views.LiteratureView.as_view(),),
]
|
whitepyro/debian_server_setup | sickbeard/providers/womble.py | Python | gpl-3.0 | 2,490 | 0.002811 | # Author: Nic Wolfe <nic@wolfeden.ca>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of SickRage.
#
# SickRage 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,... | for url in [self.provider.url + 'rss/?sec=tv-sd&fr=false', self.provider.url + 'rss/?sec= | tv-hd&fr=false']:
logger.log(u"Womble's Index cache update URL: " + url, logger.DEBUG)
data = self.getRSSFeed(url)
# As long as we got something from the provider we count it as an update
if not data:
return []
# By now we know we've got data... |
827992983/mylib | python/error.py | Python | apache-2.0 | 545 | 0.007339 | class Error(object):
def __init__(self, code, msg=None, data=None):
self.code = code
self.msg = msg
self. | data = data
def __str__(self):
err = self.to_dict()
return str(err)
def to_dict(self):
err = {}
err['err_code'] = self.code
if self.msg:
err['err_msg'] = self.msg
if | self.data:
err['data'] = self.data
return err
def err_code(self):
return self.code
def err_msg(self):
return self.msg |
pennersr/django-allauth | allauth/socialaccount/providers/untappd/client.py | Python | mit | 1,640 | 0.00061 | import requests
from allauth.socialaccount import app_settings
from allauth.socialaccount.providers.oauth2.client import (
OAuth2Client,
OAuth2Error,
)
from .provider import UntappdProvider
class UntappdOAuth2Client(OAuth2Client):
"""
Custom client because Untappd:
* uses redirect_url instea... | extra 'response' object
"""
def get_access_token(self, code):
data = {
"client_id": self.consumer_key,
| "redirect_url": self.callback_url,
"grant_type": "authorization_code",
"response_type": "code",
"client_secret": self.consumer_secret,
"code": code,
}
params = None
self._strip_empty_keys(data)
url = self.access_token_url
... |
jreese/markdown-pp | MarkdownPP/Module.py | Python | mit | 805 | 0.001242 | # Copyright 2015 John Reese
# Licensed under the MIT license
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import sys
class Mo | dule:
"""
This class provides a generic interface for the preprocessor to pass
data to the module and retrieve a list of Transforms to the data.
"""
priority = 5
"""
Priority is defined as a range of integers with 0 being highest priority,
and 5 being "normal".
"""
def __init__... | sform(self, data):
"""
This method should generate a list of Transform objects for each
modification to the original data, and return this list when ready.
"""
return []
|
KevinHCChen/wireless-aoa | simulations/plotting.py | Python | mit | 5,832 | 0.013546 | import plotly as py
import plotly.graph_objs as go
from plotly import tools
import numpy as np
color_vector = ['r', 'g', 'b', 'c', 'm', 'y', 'k']
color = ['red', 'green', 'blue', 'c', 'm', 'y', 'k']
def plotStations(baseStations):
traces = []
for i, bs in enumerate(baseStations):
#plt.plot(bs[0][0], b... | aveflag, dir_name, iter_number):
# 2D case
if true_pos.shape[1] == 2:
fig = tools.make_subplots(rows=2, cols=2)
trace = plot_scatter(true_pos, error, title)
fig.append_trace(trace, 1,1)
trace = plot_scatter(true_pos, error, title, True)
fig.ap | pend_trace(trace, 2,1)
trace = plot_scatter(predicted_pos, error, title)
fig.append_trace(trace, 1,2)
trace = plot_scatter(predicted_pos, error, title, True)
fig.append_trace(trace, 2,2)
ax_range = [-4.5,4.5]
fig['layout']['xaxis1'].update( range=ax_range)
fig['l... |
quantopian/zipline | zipline/pipeline/visualize.py | Python | apache-2.0 | 5,975 | 0 | """
Tools for visualizing dependencies between Terms.
"""
from __future__ import unicode_literals
from contextlib import contextmanager
import errno
from functools import partial
from io import BytesIO
from subprocess import Popen, PIPE
from networkx import topological_sort
from six import iteritems
from zipline.pip... | t`.
Parameters
----------
g : zipline.pipeline.graph.TermGraph
Graph to render.
out : file-like object
format_ : str {'png', 'svg'}
Output format.
include_asset_exists : bool
Whether to filter out `AssetExists()` nodes.
"""
graph_attrs = {'rankdir': 'TB', 'spline... | attrs = {'style': 'filled', 'color': 'lightgoldenrod1'}
in_nodes = g.loadable_terms
out_nodes = list(g.outputs.values())
f = BytesIO()
with graph(f, "G", **graph_attrs):
# Write outputs cluster.
with cluster(f, 'Output', labelloc='b', **cluster_attrs):
for term in filter_n... |
ChonchoFronto/sarah | lambda/apiai/requests/user_entities/user_entities_request.py | Python | mit | 2,842 | 0 | # -*- coding: utf-8 -*-
from ..request import Request
from ..query import Entity
from ..query import Entry
import json
class UserEntity(Entity):
"""UserEntity object used for upload user entities.
Detail information about user entities you can see at our site
https://docs.api.ai/docs/userentities"""
... | ._session_id
parent_data['extend'] = self._ex | tend
return parent_data
class UserEntityEntry(Entry):
"""UserEntityEntry object used for upload user entities.
Detail information about user entities you can see at our site
https://docs.api.ai/docs/userentities"""
pass
class UserEntitiesRequest(Request):
"""UserEntitiesRequest is requ... |
mirzadelic/django-social-example | django_social_example/person/models.py | Python | unlicense | 1,534 | 0 | from __future__ import unicode_literals
from django.db import models
class Person(models.Model):
""" Person model """
gender_choices = (
('male', 'Male'),
('female', 'Female')
)
firstName = models.CharField(max_length=50, blank=True, null=True)
surname = models.CharField(max_lengt... |
""" Property for generating full_name """
return '%s %s' % (self.firstName, self.surname)
def __str__(self):
return self.full_name
def __unicode__(self):
return self.full_name
@property
def friends_of_friends(self):
""" Property for list of friends of friends ... | @property
def suggested_friends(self):
""" Property for list of suggested friends """
exclude_pks = list(self.friends.all().values_list('pk', flat=True))
exclude_pks.append(self.pk)
suggested_friends = []
for person in Person.objects.exclude(pk__in=exclude_pks):
... |
kr41/ggrc-core | test/integration/ggrc/converters/test_import_comprehensive.py | Python | apache-2.0 | 9,749 | 0.001436 | # Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Comprehensive import tests.
These tests should eventually contain all good imports and imports with all
possible errors and warnings.
"""
from ggrc import db
from ggrc.models import AccessGroup
from ggrc... | s with no warnings or errors."""
filename = "full_good_import_no_warnings.csv"
response = self.import_file(filename)
admin = db.session.query(Role.id).filter(Role.name == "Administrator")
reader = db.session.query(Role.id).filter(Role.name == "Reader")
creator = db.session.query(Role.id).filter(Rol... | le_id == admin).all()
readers = UserRole.query.filter(UserRole.role_id == reader).all()
creators = UserRole.query.filter(UserRole.role_id == creator).all()
access_groups = db.session.query(AccessGroup).all()
self.assertEqual(len(admins), 12)
self.assertEqual(len(readers), 5)
self.assertEqual(len... |
colour-science/colour | colour/examples/graph/examples_graph.py | Python | bsd-3-clause | 2,239 | 0 | """Showcases *Automatic Colour Conversion Graph* computations."""
import numpy as np
import colour
from colour.utilities import message_box
message_box("Automatic Colour Conversion Graph")
message_box(
'Converting a "ColorC | hecker" "dark skin" sample spectral distribution to '
'"Output-Referred" "sRGB" col | ourspace.'
)
sd_dark_skin = colour.SDS_COLOURCHECKERS["ColorChecker N Ohta"]["dark skin"]
print(colour.convert(sd_dark_skin, "Spectral Distribution", "sRGB"))
print(
colour.XYZ_to_sRGB(
colour.sd_to_XYZ(
sd_dark_skin, illuminant=colour.SDS_ILLUMINANTS["D65"]
)
/ 100
)
)
pri... |
anhstudios/swganh | data/scripts/templates/object/mobile/shared_dressed_marooned_pirate_hum_f.py | Python | mit | 456 | 0.046053 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Creature()
result.template = "object/mobile/shared_dressed_marooned_pirate_hum_f.iff"
result.attribute_template_i... | lt.stfName("npc_name","human_ba | se_female")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
tum-i22/macke | leagacy/batch_klee.py | Python | apache-2.0 | 8,300 | 0.005422 | import time
import sys
import os
import glob
from optparse import OptionParser, OptionGroup
import re
from source_coverage import source_coverage
from compose_units import get_top_level_funcs, get_outlier_funcs
from read_ktest import generate_assert_code, get_location_to_insert, modify_unit_files, get_lines_to_insert
f... | lete.units', 'w')
if not no_klee:
for ud in glob.glob(d | ir_name+'*_units/'):
main_pattern = dir_name+'(.*)_units/'
main_match = re.search(main_pattern, ud)
main_name = main_match.group(1)
for f in glob.glob(ud+'*_*.c.units'):
re_pattern = ud+'(.*)_(.*)\.c\.units'
re_match = re.search(re_pattern,... |
ccphillippi/AFP | afp/sentiment/Decision_Tree_Classifier.py | Python | mit | 4,125 | 0.02497 | import re
import nltk
import pickle
#Importing lemmatizer
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
#Importing tagger
from nltk.tag import UnigramTagger
from nltk.corpus import treebank
train_sents = treebank.tagged_sents()
tagger=UnigramTagger(train_s... | t = []
#Create a list of 'negatives' with the exact length of our negative tweet list.
for i in range(0,len(negtxt)):
negli | st.append('negative')
#Likewise for positive.
for i in range(0,len(postxt)):
poslist.append('positive')
#Creates a list of tuples, with sentiment tagged.
postagged = zip(postxt, poslist)
negtagged = zip(negtxt, neglist)
#Combines all of the tagged tweets to one large list.
taggedtweets = postagged + negtagged
sh... |
Solinea/belka | belka/exception.py | Python | apache-2.0 | 700 | 0 | # Copyright (c) 2013 Solinea, Inc. (code@solinea.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 o | btain 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.
class MissingTokenError(Exception):
message = "Token is required for interacting with cloud."
|
HSDL/HeuristicBursts | tests/TroubleshootingTests/troubleshooting_test_wec_D.py | Python | mit | 914 | 0.004376 | # This test is for quickly testing functionality of individual rules
import wec.wec
import wec.wec_visual
import time
def test_simulation_of_wec():
device = wec.wec.WEC()
display = wec.wec_visual.wec_visual()
display.display(device)
device.add_body('sphere', 650.0, (400, 400), radius=25) |
# device.add_rotational_body('sphere', 650, (450, 400), 0, 0, 1000, 10000000, radius=25)
# device.add_rotational_body('sphere', 650, (500, 400), 1, 0, 1000, 10 | 000000, radius=25)
# device.add_rotational_body('sphere', 650, (550, 400), 2, 0, 1000, 10000000, radius=25)
# device.add_rotational_body('sphere', 650, (600, 400), 3, 0, 1000, 10000000, radius=25)
device.create_initial_design(20)
# device.rule_perform(3)
# device.rule_perform(2)
# device.rule_p... |
miurahr/seahub | tests/api/endpoints/test_be_shared_repo.py | Python | apache-2.0 | 2,485 | 0.002817 | import json
import seaserv
from seaserv import seafile_api
from sea | hub.test_utils import BaseTestCase
class BeSharedRepoTest(BaseTestCase):
def setUp(self):
self.login_as(self.admin)
def tearDown(self):
self.remove_repo()
def _add_shared_items(self):
# create repo for user
sub_repo_id = seafile_api.create_virtual_repo(self.repo.id,
... | der,
self.repo.name, '',
self.user.username)
self.sub_repo_id = sub_repo_id
# create group for admin
admin_group_id = seaserv.ccnet_threaded_rpc.create_group('admin-group',
... |
mortcanty/earthengine | src/ee/tests/number_test.py | Python | mit | 905 | 0.00442 | #!/usr/bin/env python
"""Test for the ee.number module."""
import unittest
import ee
from ee import apitestcase
class NumberTest(apitestcase.ApiTestCase):
def testNumber(self):
"""Verifies basic behavior of ee.Number."""
num = ee.Number(1)
self.assertEquals(1 | , num.encode())
computed = ee.Number(1).add(2)
self.assertTrue(isinstance(computed, ee.Number))
self.assertEquals(ee.ApiFunction.lookup('Number.add'), computed.func)
self.assertEquals({'left': ee.Number(1), 'right': ee.Number(2)},
com | puted.args)
def testInternals(self):
"""Test eq(), ne() and hash()."""
a = ee.Number(1)
b = ee.Number(2.1)
c = ee.Number(1)
self.assertEquals(a, a)
self.assertNotEquals(a, b)
self.assertEquals(a, c)
self.assertNotEquals(b, c)
self.assertNotEquals(hash(a), hash(b))
if __name__ =... |
apoorvarpi/Computer_Vision | vedio.py | Python | mit | 1,027 | 0.037001 | import cv2
import numpy
from tkinter import *
from PIL import Image, ImageTk
import argparse
#count=1
def on_mouse(event,x,y,flags,params):
#print("getting")
if event == cv2.EVENT_LBUTTONDOWN:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
print("ok\n")
name = "calib1.jpg" # save frame as JPEG file
#count=... | ;
cap = cv2.VideoCapture("http://rit2014023:got%40S4L2@172.16.15.245:8081/?action=stream?dummy=param.mjpg")
#cap = cv2.VideoCapture(0)
#cap.open("http://rit2014023:got%40S4L2@172.16.15.215:8081.mjpeg/")
if ~cap.isOpened():
print ('error')
#cv2.setMouseCallback('frame', on_mous | e)
while cap.isOpened():
_,frame = cap.read()
#cv2.namedWindow('frame')
cv2.imshow("stream",frame)
cv2.setMouseCallback('stream', on_mouse)
c = cv2.waitKey(1)
if c == 27:
break
|
lbryio/lbry | lbry/lbry/extras/daemon/comment_client.py | Python | mit | 1,961 | 0.00153 | import logging
import time
import hashlib
import binascii
import aiohttp
import ecdsa
from torba.client.hash import sha256
from lbry.wallet.transaction import Output
log = logging.getLogger(__name__)
def get_encoded_signature(signature):
signature = signature.encode() if type(signature) is str else signature
... | yError:
pass
return False
def sign_comment(comment: dict, channel: Output):
timestamp = str(int(time.time())).encode()
pieces = [timestamp, channel.claim_hash, comment['comment'].encode()]
digest = sha256(b''.join(pieces))
signature = channel.private_key.sign_digest_deterministic(digest, h... | tr, **params) -> any:
json_body = {'jsonrpc': '2.0', 'id': None, 'method': method, 'params': params}
headers = {'Content-Type': 'application/json'}
async with aiohttp.request('POST', url, json=json_body, headers=headers) as response:
try:
result = await response.json()
return... |
juliakreutzer/bandit-neuralmonkey | neuralmonkey/runners/base_runner.py | Python | bsd-3-clause | 2,727 | 0.000367 | from typing import (Any, Dict, Tuple, List, NamedTuple, Union, Set, TypeVar,
Generic, Optional)
import numpy as np
import tensorflow as tf
from neuralmonkey.logging import notice
from neuralmonkey.model.model_part import ModelPart
# pylint: disable=invalid-name
FeedDict = Dict[tf.Tensor, Union[int,... | compute_losses: bool,
summaries: bool,
num_sessions: int) -> Executable:
raise NotImplementedError()
@property
def | decoder_data_id(self) -> Optional[str]:
return getattr(self._decoder, "data_id", None)
@property
def loss_names(self) -> List[str]:
raise NotImplementedError()
def reduce_execution_results(
execution_results: List[ExecutionResult]) -> ExecutionResult:
"""Aggregate execution resul... |
hirofumi0810/tensorflow_end2end_speech_recognition | models/encoders/core/pyramidal_blstm.py | Python | mit | 7,080 | 0.000282 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""Pyramidal bidirectional LSTM encoder."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
class PyramidBLSTMEncoder(object):
"""Pyramidal bidirectional LSTM Encoder.
Args:
... | floor(
tf.cast(inputs_seq_len, tf.float32) / 2),
tf.int32)
# Transpose to `[batch_size, time, input_size]`
outputs = tf.transpose(outputs, ( | 1, 0, 2))
(outputs_fw, outputs_bw), final_state = tf.nn.bidirectional_dynamic_rnn(
cell_fw=lstm_fw,
cell_bw=lstm_bw,
inputs=outputs,
sequence_length=inputs_seq_len,
dtype=tf.float32,
... |
syncboard/syncboard | src/session.py | Python | gpl-2.0 | 8,410 | 0.001189 | """
Cross-platform clipboard syncing tool
Copyright (C) 2013 Syncboard
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 opt... | list of all the connections
"""
return self._con_mgr.connections
def get_connection(self, address):
"""
Returns the Connection object that has the given address
"""
return self._con_mgr.get_connection(address)
def new_connection(self, alias, addre... | see a new connection appear (with the address on this end) with
status REQUEST.
After this has executed:
New Connection on both ends.
Connection on this end status: PENDING
Conneciton on other end status: REQUEST
"""
self._network.conn... |
jlopezmalla/spark | python/pyspark/ml/classification.py | Python | apache-2.0 | 70,656 | 0.003637 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | ier', 'MultilayerPerceptronClassificationModel',
'OneVsRest', 'OneVsRestModel']
@inherit_doc
class JavaClassificationModel(JavaPrediction | Model):
"""
(Private) Java Model produced by a ``Classifier``.
Classes are indexed {0, 1, ..., numClasses - 1}.
To be mixed in with class:`pyspark.ml.JavaModel`
"""
@property
@since("2.1.0")
def numClasses(self):
"""
Number of classes (values which the label can take).
... |
meeb/txcloudflare | examples/ip_ban.py | Python | apache-2.0 | 2,255 | 0.003548 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright 2013 Joe Harris
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
... | .com/docs/client-api.html#s4.7
'''
import os, sys
# make sure our local copy of txcloudflare is in sys.path
PATH_TO_TXCF = '../txcloudflare/'
try:
import txcloudflare
except ImportError:
txcfpath = os.path.dirname(os.path.realpath(PATH_ | TO_TXCF))
if txcfpath not in sys.path:
sys.path.insert(0, txcfpath)
from twisted.internet import reactor
import txcloudflare
def got_response(response):
'''
'response' is a txcloudflare.response.Response() instance.
'''
print '< got a response (done)'
print '< ip: {0}'.format(respo... |
ianmiell/OLD-shutitdist | rsync/rsync.py | Python | gpl-2.0 | 1,111 | 0.047705 | """ShutIt module. See http://shutit.tk/
"""
from shutit_module import ShutItModule
class rsync(ShutItModule):
def is_installed(self, shutit):
return False
def build(self, shutit):
shutit.send('mkdir -p /tmp/build/rsync')
shutit.send('cd /tmp/build/rsync')
shutit.send('curl -L http://rsync.samba.org/ftp... | self, shutit):
# return True
def finalize(self, shutit):
#shutit.send('rm -rf
return True
#def remove(self, shutit):
# return True
#def test(self, shutit):
# return True
def module():
return rsync(
'shutit.tk.sd.rsync.rsync', 158844782.003,
description='',
maintainer='ian.miell@gmail.com',
depend... | g_config.pkg_config']
)
|
GrognardsFromHell/TemplePlus | tpdatasrc/co8infra/scr/Spell531 - Web.py | Python | mit | 2,420 | 0.044628 | from toee import *
import _include
from co8Util import size
from co8Util.PersistentData import *
from co8Util.ObjHandling import *
WEB_KEY = "Sp531_Web_Activelist"
def OnBeginSpellCast( spell ):
print "Web OnBeginSpellCast"
print "spell.target_list=", spell.target_list
print "spell.caster=", spell.caster, " caster... | on_add_arg_x( 3, Web_partsys_id )
#objectevent_id = web_obj.condition_get_arg_x( 2 )
#########################
# Added by Sitra Achara #
#########################
web_obj.obj_set_int( obj_f_secretdoor_dc, 531 + (1<<15) )
# Mark it as an "obscuring mist" object.
# 1<<15 - marks it as "active"
# bits 16 a... | l.id, derefHandle(web_obj)])
Co8PersistentData.setData(WEB_KEY, activeList)
#########################
# End of Section #
#########################
def OnBeginRound( spell ):
print "Web OnBeginRound"
def OnEndSpellCast( spell ):
print "Web OnEndSpellCast"
activeList = Co8PersistentData.getData(WEB_KEY)
... |
davidenitti/ML | RL/agent/buffers.py | Python | gpl-3.0 | 7,628 | 0.002622 | import gym
import numpy as np
import random
import pickle
import os
class ReplayMemory(object):
def __init__(self, max_size, observation_dims, observation_dtype,
action_space: gym.Space, history: int, discount, use_priority=False):
assert len(list(observation_dims)) == 3 or len(list(obser... | prob_mem /= prob_mem.sum()
ind = np.random.choice(self.sizemem() - 1, batch_size, p=prob_mem)
else:
ind = np.random.choice(self.sizemem() - 1, batch_size)
return ind
def set_priority(self, idx, vals): # item ha | s to be from 0 to len(mem)-1
raise NotImplementedError
assert (idx < len(self.mem)).all()
idx_new = (self.start_ind + idx) % self.max_size
self.priority[idx_new] = vals
def get_priorities(self):
raise NotImplementedError
assert self.start_ind >= 0 and self.last_ind >... |
recto/udacity_full_stack_web_developer | P2_Tournament_Results/tournament_test.py | Python | mit | 12,215 | 0.000737 | #!/usr/bin/env python
"""
Test cases for tournament.py
"""
from tournament import *
def testDeleteMatches():
""" test deleteMatches. """
deleteMatches()
print "1. Old matches can be deleted."
def testDelete():
deleteMatches()
deletePlayers()
print "2. Player records can be deleted."
def t... | deletePlayers()
registerPlayer("Twilight Sparkle")
registerPlayer("Fluttershy")
registerPlayer("Applejack")
registerPlayer("Pinkie Pie")
standings = playerStandings()
[id1, id2, id3, id4] = [row[0] for row in standings]
reportMatch(id1, id2)
reportMatch(id3, id4)
pairings = swissPair... | gs) != 2:
raise ValueError(
"For four players, swissPairings should return two pairs.")
[(pid1, pname1, pid2, pname2), (pid3, pname3, pid4, pname4)] = pairings
correct_pairs = set([frozenset([id1, id3]), frozenset([id2, id4])])
actual_pairs = set([frozenset([pid1, pid2]), frozenset([pid3... |
nginx/unit | test/python/errors_write/wsgi.py | Python | apache-2.0 | 203 | 0 | def | application(environ, start_response):
environ['wsgi.errors'].write('Error in application.')
environ['wsgi.err | ors'].flush()
start_response('200', [('Content-Length', '0')])
return []
|
chengduoZH/Paddle | python/paddle/fluid/layers/device.py | Python | apache-2.0 | 1,438 | 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... | s not None:
attrs['device_type'] = | str(device_type)
helper.append_op(
type='get_places', outputs={"Out": [out_places]}, attrs=attrs)
return out_places
|
maldun/MyGeom | Types.py | Python | lgpl-2.1 | 16,096 | 0.011494 | # MyGeom Module - API for easier Salome geompy usage
# Types.py: Extended Data Types for MyGeom
#
# Copyright (C) 2013 Stefan Reiterer - maldun.finsterschreck@gmail.com
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published ... | __init__(self,x, y = 0.0, z = 0.0):
if isinstance(x,GEOM._objref_GEOM_Object):
if x.GetShapeType() == GEOM.VERTEX:
self.setCoord(geompy.GetPosition(x)[:3])
self.setGeomObject(x)
else:
raise ValueError("Er | ror: This is not a vertex!")
elif isinstance(x,MyVertex):
self.setCoord(x.getCoord())
self.setGeomObject(x.getGeomObject())
elif isinstance(x,ndarray) or isinstance(x,tuple) or isinstance(x,list):
if len(x) is 3:
self.setCoord(data_type(x))
... |
frankrousseau/weboob | modules/jvmalin/module.py | Python | agpl-3.0 | 1,678 | 0.000596 | # -*- coding: utf-8 -*-
# Copyright(C) 2013 Alexandre Lissy
#
# This file is part of weboob.
#
# weboob 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 License, or
# (at your op... | <http://www.gnu.org/licenses/>.
from weboob.capabilities.travel import CapTravel, RoadStep
from weboob.tools.backend import Module
from .browser import JVMalin
__all__ = ['JVMalinModule']
class JVMalinModule(Module, CapTravel):
N | AME = 'jvmalin'
MAINTAINER = u'Alexandre Lissy'
EMAIL = 'github@lissy.me'
VERSION = '1.1'
LICENSE = 'AGPLv3+'
DESCRIPTION = u"Multimodal public transportation for whole Région Centre, France"
BROWSER = JVMalin
def iter_roadmap(self, departure, arrival, filters):
with self.browser:
... |
kostaspl/SpiderMonkey38 | testing/mozbase/mozdevice/setup.py | Python | mpl-2.0 | 1,156 | 0.002595 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
from setuptools import setup
PACKA | GE_NAME = 'mozdevice'
PACKAGE_VERSION = '0.44'
deps = ['mozfile >= 1.0',
'mozlog >= 2.1',
'moznetwork >= 0.24',
'mozprocess >= 0.19',
]
setup(name=PACKAGE_NAME,
version=PACKAGE_VERSION,
description="Mozilla-authored device management",
long_description="see http://mozb... | sting Team',
author_email='tools@lists.mozilla.org',
url='https://wiki.mozilla.org/Auto-tools/Projects/Mozbase',
license='MPL',
packages=['mozdevice'],
include_package_data=True,
zip_safe=False,
install_requires=deps,
entry_points="""
# -*- Entry points: -*-
[... |
cernops/jens | src/jens/repos.py | Python | gpl-3.0 | 15,212 | 0.001118 | # Copyright (C) 2014, CERN
# This software is distributed under the terms of the GNU General Public
# Licence version 3 (GPL Version 3), copied verbatim in the file "COPYING".
# In applying this license, CERN does not waive the privileges and immunities
# granted to it by virtue of its status as Intergovernmental Organ... | definition, inventory[partition],
desired[partition])
# If hints are passed but there's nothing explicitly declared
# for a given partition, we make it explicit here.
if hints and partition not in hints:
| hints[partition] = set()
logging.info("Expanding EXISTING bare repositories...")
_refresh_repositories(delta['existing'], partition, inventory[partition],
desired[partition], hints[partition] if hints else None)
logging.info("Purging REMOVED bare repositories...")... |
coderholic/pyradio | pyradio/window_stack.py | Python | mit | 16,747 | 0.000955 | # -*- coding: utf-8 -*-
from collections import deque
import logging
import locale
locale.setlocale(locale.LC_ALL, "")
logger = logging.getLogger(__name__)
class Window_Stack_Constants(object):
''' Modes of Operation '''
DEPENDENCY_ERROR = -2
NO_PLAYER_ERROR_MODE = -1
NORMAL_MODE = 0
PLAYLIST_MODE... | IST_ | RECOVERY_ERROR_MODE = 200
PLAYLIST_NOT_FOUND_ERROR_MODE = 201
PLAYLIST_LOAD_ERROR_MODE = 202
PLAYLIST_RELOAD_ERROR_MODE = 203
PLAYLIST_RELOAD_CONFIRM_MODE = 204
PLAYLIST_DIRTY_RELOAD_CONFIRM_MODE = 205
PLAYLIST_SCAN_ERROR_MODE = 206
SAVE_PLAYLIST_ERROR_1_MODE = 207
SAVE_PLAYLIST_ERROR_2_... |
kuiche/chromium | webkit/build/action_useragentstylesheets.py | Python | bsd-3-clause | 1,985 | 0.015113 | #!/usr/bin/python
# Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# usage: action_useragentstylesheets.py OUTPUTS -- INPUTS
#
# Multiple OUTPUTS and INPUTS may be listed. The sections are separated b... | s to
# be fed t | o that script.
import os
import subprocess
import sys
def SplitArgsIntoSections(args):
sections = []
while len(args) > 0:
if not '--' in args:
# If there is no '--' left, everything remaining is an entire section.
dashes = len(args)
else:
dashes = args.index('--')
sections.append(... |
dagwieers/ansible | lib/ansible/modules/database/postgresql/postgresql_schema.py | Python | gpl-3.0 | 11,616 | 0.00241 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2016, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | = []
class NotSupportedError(Exception):
pass
# ===========================================
# Postgr | eSQL module specific support methods.
#
def set_owner(cursor, schema, owner):
query = "ALTER SCHEMA %s OWNER TO %s" % (
pg_quote_identifier(schema, 'schema'),
pg_quote_identifier(owner, 'role'))
cursor.execute(query)
executed_queries.append(query)
return True
def get_schema_in... |
hjheath/ProjectEuler | projecteuler/tests/problem_test.py | Python | mit | 1,231 | 0 | """Test the problems get the correct answers."""
import unittest
from projecteuler.tests.answers import PROBLEM_ANSWERS
class MetaTests(type):
"""Meta class to dynamically create test cases for each problem"""
def __new__(mcs, name, bases, attrs):
for problem_name, answer in PROBLEM_ANSWERS.items():... | ):
"""The actual test."""
self.assertEqual(problem(), answer)
return test_function
class TestProblems(unittest.TestCase, metaclass=MetaTests):
"""Test that each problem function returns the co | rrect answer."""
|
miniworld-project/miniworld_core | miniworld/management/serialization/ShellCommandSerializer.py | Python | mit | 12,647 | 0.002214 | import collections
import math
from collections import OrderedDict
from concurrent import futures
from ordered_set import OrderedSet
from miniworld.Scenario import scenario_config
from miniworld.model.singletons.Resetable import Resetable
from miniworld.model.singletons.Singletons import singletons
from miniworld.uti... | ##############################
def run_commands(self, max_workers=None, events_order=None):
"""
Parameters
----------
| max_workers
events_order : list<str>
List of events to filter for. E.g. "bridge".
Returns
-------
"""
if events_order is None:
events_order = self.group_order
# run over the groups
for group in self.group_order:
if g... |
nm6061/toolshare | app/views/account.py | Python | mit | 9,912 | 0.002825 | from collections import ChainMap
from django.conf import settings
from django.core.urlresolvers import reverse_lazy
from django.shortcuts import render, redirect, resolve_url
from django.contrib import messages
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.tokens import default_token_gene... | View, self).form_valid(form)
class ResetAccountView(FormView):
template_name = 'account/reset.html'
success_url = reverse_lazy('acco | unt:signin')
success_message = 'The password on your ToolShare account was successfully reset. Please <strong>sign in' \
'</strong> with your new password.'
failure_url = reverse_lazy('account:recover')
failure_message = 'It appears that the URL you used to recover the account is no lo... |
dostavro/dotfiles | sublime2/Packages/SublimeCodeIntel/libs/codeintel2/lang_php.py | Python | mit | 147,750 | 0.000799 | #!/usr/bin/env python
# ***** BEGIN LICENSE BLOCK * | ****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this f | ile are subject to the Mozilla Public License
# Version 1.1 (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.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY K... |
ptrendx/mxnet | dev_menu.py | Python | apache-2.0 | 9,244 | 0.007248 | #!/usr/bin/env python3
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "... | xe and pyexe and venv):
logging.warn("Skipping creation of virtualenv")
return
check_call([venv_exe, '-p', pyexe, venv])
activate_this_py = os.path.join(venv, 'bin', 'activate_this.py')
# Activate virt | ualenv in this interpreter
exec(open(activate_this_py).read(), dict(__file__=activate_this_py))
check_call(['pip', 'install', '--upgrade','--force-reinstall', '-e', 'python'])
check_call(['pip', 'install', '-r', 'tests/requirements.txt'])
def create_virtualenv_default():
create_virtualenv('virtualenv',... |
x6herbius/afterburner | tools/bsp/libbsp/structutils.py | Python | gpl-3.0 | 11,421 | 0.024604 | import struct
import re
from .core import NamedItemList
from copy import deepcopy
_SINGLE_MEMBER_REGEX = re.compile(r"^[@=<>!]?([0-9]*)([xcbB\?hHiIlLqQnNefdspP])$")
def __isSingleMemberFormatString(format):
return bool(_SINGLE_MEMBER_REGEX.match(format))
def formatStringForMembers(members):
formatString = ""
for... | (member[0], member)
self.__generateMemberGroupInfo()
if startZeroed:
self.setToZero()
def valueByName(self, memberName):
if not isinstance(memberName, str):
raise TypeError("Member must be specified as a string.")
if not self.__memberList.hasItemWithName(memberName):
raise ValueError("Member '" + ... | ce(index, int):
raise TypeError("Member index must be an integer.")
if index < 0 or index >= len(self):
raise ValueError("Member index " + str(index) + " is out of range.")
data = self.data()
if data is None:
raise ValueError("No member data has been set.")
return deepcopy(data[index])
def hasMem... |
ProfessorX/Config | .PyCharm30/system/python_stubs/-1247972723/samba/dcerpc/dnsserver/__init__.py | Python | gpl-2.0 | 7,216 | 0.007068 | # encoding: utf-8
# module samba.dcerpc.dnsserver
# from /usr/lib/python2.7/dist-packages/samba/dcerpc/dnsserver.so
# by generator 1.135
""" dnsserver DCE/RPC """
# imports
import dcerpc as __dcerpc
import talloc as __talloc
# Variables with simple values
DNSSRV_TYPEID_ADDRARRAY = 34
DNSSRV_TYPEID_AUTOCONFIGURE = 4... | NS_RPC_ZONE_PAUSED = 1
DNS_RPC_ZONE_READONLY = 256
DNS_RPC_ZONE_REVERSE = 4
DNS_RPC_ZONE_SHUTDOWN = 2
DNS_RPC_ZONE_UPDATE_SECURE = 128
DNS_RPC_ZONE_UPDATE_UNSECURE = 64
DNS_ZONE_NOTIFY_ALL_SECONDARIES = 1
DNS_ZONE_NOTIFY_LIST_ONLY = 2
DNS_ZONE_NOTIFY_OFF = 0
DNS_ZONE_REQUEST_AUTO = 8
DNS_ZONE_REQUEST_CACHE = 4
DN... | D = 16
DNS_ZONE_REQUEST_FORWARDER = 64
DNS_ZONE_REQUEST_LEGACY_DP = 8192
DNS_ZONE_REQUEST_NON_DS = 512
DNS_ZONE_REQUEST_PRIMARY = 1
DNS_ZONE_REQUEST_REVERSE = 32
DNS_ZONE_REQUEST_SECONDARY = 2
DNS_ZONE_REQUEST_STUB = 128
DNS_ZONE_SECSECURE_LIST_ONLY = 2
DNS_ZONE_SECSECURE_NO_SECURITY = 0
DNS_ZONE_SECSECURE_NO_XFER... |
joachimmetz/dfvfs | tests/vfs/data_stream.py | Python | apache-2.0 | 883 | 0.005663 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for the VFS data stream interface."""
import unittest
from dfvfs.vfs import data_stream
from tests import test_lib as shared_test_lib
class DataStreamTest(shared_test_lib.BaseTestCase):
"""Tests the VFS data stream interface."""
def testName(self):
""... | unction."""
test_data_stream = data_stream.DataStream(None)
result = test_data_stream.IsDefault()
self.assertTrue(result | )
if __name__ == '__main__':
unittest.main()
|
mesonbuild/meson | mesonbuild/minit.py | Python | apache-2.0 | 7,660 | 0.003394 | # Copyright 2017 The Meson development team
# 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 ... | if f.suffix == '.rs':
options.language = 'rust'
break
if f.suffix == '.m':
options.language = ' | objc'
break
if f.suffix == '.mm':
options.language = 'objcpp'
break
if f.suffix == '.java':
options.language = 'java'
break
if f.suffix == '.vala':
options.language = 'vala'
... |
wlonk/are_there_spiders | are_there_spiders/are_there_spiders/context_processors.py | Python | mit | 206 | 0 | from django.core.urlresolvers im | port reverse
def login_next(request):
if request.path == reverse('auth_ | logout'):
return {'login_next': ''}
return {'login_next': '?next=%s' % request.path}
|
cthtuf/django-cv | main/models.py | Python | mit | 22,628 | 0 | from django.db import models
from django.core.validators import MaxValueValidator
class MainSliderBlock(models.Model):
is_active = models.BooleanField(
verbose_name="Отображать блок",
default=True,
)
class Meta:
verbose_name = verbose_name_plural = "Блок Слайдер"
def __str__(... | verbose_name="Отображать блок",
default=False,
)
video = models.FileField(
verbose_name="Файл видео",
upload_to="video",
blank=True,
null=True,
)
video_link = models.CharField(
verbose_name="Ссылка на видео",
max_length=255,
blank=... | verbose_name="Текст под видео",
max_length=1023,
)
background_image = models.ImageField(
verbose_name="Фоновое изображение для блока видео",
upload_to="video",
)
class Meta:
verbose_name = verbose_name_plural = "Блок Видео"
def __str__(self):
return "{0} #... |
Vauxoo/stock-logistics-warehouse | stock_reserve_rule/models/stock_quant.py | Python | agpl-3.0 | 951 | 0 | # Copyright 2019 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from collections import OrderedDict
from odoo import api, models
class StockQuant(models.Model):
_inherit = "stock.quant"
@api.model
def _group_by_location(self):
"""Return quants grouped by loca... | r of the quants (if we have more
than one quant per location, the order is based on the first quant seen
in the location). Thus, it can be used on a recordset returned by
_gather.
The returned format is: [(location, quants)]
"""
seen = OrderedDict()
for quant in... | seen[location] = seen[location] | quant
else:
seen[location] = quant
return [(loc, quants) for loc, quants in seen.items()]
|
eort/OpenSesame | openexp/_clock/psycho.py | Python | gpl-3.0 | 953 | 0.010493 | #-*- coding:utf-8 -*-
"""
This file is part of OpenSesame.
OpenSesame 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.
OpenSesame is distri... | n the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with OpenSesame. If not, see <http://www.... | libopensesame.py3compat import *
from openexp._clock.clock import clock
from psychopy import core
class psycho(clock):
"""
desc:
For docstrings, see openexp._clock.clock.
"""
def time(self):
return 1000.*core.getTime()
def sleep(self, ms):
core.wait(.001*ms)
|
COL-IU/XLSearch | library/Parameter.py | Python | mit | 1,380 | 0.069565 | param = dict(
useAIon=True,
verbose=False,
chargePreXlinkIons=[1, 3],
chargePostXlinkIons=[2, 5],
basepeakint = 100.0,
dynamicrange = 0.001,
missedsites = 2,
minlength = 4,
maxlength = 51,
modRes = '',
modMass = 0.0,
linkermass = 136.10005,
ms1tol = dict(measure='ppm', val=5),
ms2tol = dict(measure='da', ... | 565,
aa=set('ACDEFGHIKLMNPQRSTVWY'))))
mass = dict(
A=71.037114,
R=156.101111,
N=114.042927,
D=115.026943,
C=103.009184,
E=129.042593,
Q=128.058578,
G=57.0214 | 64,
H=137.058912,
I=113.084064,
L=113.084064,
K=128.094963,
M=131.040485,
F=147.068414,
P=97.052764,
S=87.032028,
T=101.047678,
W=186.079313,
Y=163.063329,
V=99.068414,
Hatom=1.007825032,
Oatom=15.99491462,
neutronmass = 1.008701,
BIonRes=1.0078246,
AIonRes=-26.9870904,
YIonRes=19.0183888,
isotopeInc... |
batmancn/MyLife | learn/demos/python_demo/core_python_programming_code/ch18/mtsleep5.py | Python | gpl-3.0 | 915 | 0.010929 | #!/usr/bin/env python
import threading
from time import sleep, ctime
loops = [ 4, 2 ]
# This is to use class instead of function as thread entry function.
class MyThread(threading.Thread):
def __init__(self, func, a | rgs, name=''):
threading.Thread.__init__(self)
self.name = name
self.func = func
self.args = args
def run(self):
apply(self.func, self.args)
def loop(nloop, nsec):
print 'start loop', nloop, 'at:', ctime()
sleep(nsec)
print 'loop', nloop, 'done at:', ctime()
de... | reads = []
nloops = range(len(loops))
for i in nloops:
t = MyThread(loop, (i, loops[i]),
loop.__name__)
threads.append(t)
for i in nloops:
threads[i].start()
for i in nloops:
threads[i].join()
print 'all DONE at:', ctime()
if __name__ == '__main__':
main... |
GoogleCloudPlatform/professional-services | tools/pubsub2inbox/processors/groups.py | Python | apache-2.0 | 5,644 | 0.000709 | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | : all_groups,
'groups_by_owner': groups_by_owner,
'groups_by_manager': groups_by_manager
}
retu | rn res
|
NatalieWolfe/scratch-space | crypt.py | Python | unlicense | 7,350 | 0.002857 | #! /usr/bin/python
from base64 import b64encode, b64decode
from Crypto import Random
from Crypto.Cipher import AES, PKCS1_OAEP
from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA
from Crypto.Random import random
from Crypto.Signature import PKCS1_v1_5
privateKeyStr = """-----BEGIN RSA PRIVATE KEY-----
MII... | crypted_payload)
padding_size = int(decrypted_payload[0], 16) + 1 # Plus 1 for the padding number itself.
payload = decrypted_payload[padding_size:]
return payload
def sign(data, private_key):
"""
App | ly SHA-256 hash to (base64 encoded) data and sign it using private_key.
Return base64 encoded signature using PKCS#1 v1.5.
"""
rsa_key = RSA.importKey(private_key)
signer = PKCS1_v1_5.new(rsa_key)
digest = SHA256.new()
digest.update(base64_decode(data)) # assume data was encrypted w/ library.
... |
kokushozero/mifsaDBProject | web2py/applications/welcome/models/menu.py | Python | gpl-2.0 | 6,204 | 0.004674 | # -*- coding: utf-8 -*-
# this file is released under public domain and you can use without limitations
#########################################################################
## Customize your APP title, subtitle and menus here
#########################################################################
response.logo... | Layouts'), False, 'http://web2py.com/layouts'),
(T('Recipes'), False, 'http://web2pyslices.com/'),
(T('Semantic'), False, 'http://web2py.com/semantic'),
]),
(T('Documentation'), False, 'http://www.web2py.com/book', [
(T('Preface'), False,
'ht... | /book/default/chapter/01'),
(T('Python'), False,
'http://www.web2py.com/book/default/chapter/02'),
(T('Overview'), False,
'http://www.web2py.com/book/default/chapter/03'),
(T('The Core'), False,
'http://www.web2py.com/book/default/chapter/... |
hugovk/coveragepy | coverage/annotate.py | Python | apache-2.0 | 3,381 | 0.000296 | # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt
"""Source file annotation for coverage.py."""
import os
import re
from coverage.files import flat_rootname
from coverage.misc import ensure_dir, isolate_module
fr... | cluded = sorted(analysis.excluded)
| if self.directory:
ensure_dir(self.directory)
dest_file = os.path.join(self.directory, flat_rootname(fr.relative_filename()))
if dest_file.endswith("_py"):
dest_file = dest_file[:-3] + ".py"
dest_file += ",cover"
else:
dest_file ... |
googleapis/python-tpu | google/cloud/tpu_v2alpha1/types/__init__.py | Python | apache-2.0 | 2,318 | 0 | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | ",
"NetworkConfig",
"NetworkEndpoint",
"Node",
"OperationMetadata",
"RuntimeVersion",
"SchedulingConfig",
"ServiceAccount",
"ServiceIdentity",
"StartNodeRequest",
"StopNodeRequest",
"Sym | ptom",
"UpdateNodeRequest",
)
|
bill-mccloskey/searchfox | router/router.py | Python | mpl-2.0 | 20,106 | 0.002437 | #!/usr/bin/env python3
from __future__ import absolute_import
import six.moves.SimpleHTTPServer
from six.moves.BaseHTTPServer import HTTPServer
from six.moves.socketserver import ForkingMixIn
import six.moves.urllib.request, six.moves.urllib.parse, six.moves.urllib.error
import six.moves.urllib.parse
import sys
import... | in the more naive text search
results.
- line_modifier's bounds fixups as mentioned in `compile_result` are
applied which helps the bolding logic in the display logic on the
(web) client.
'''
count = 0
line_hash = {}
result = collections.OrderedDi... | get(pathkind, []):
paths = list(self.compiled[pathkind][qkind].keys())
paths.sort |
Donkyhotay/MoonPy | zope/documenttemplate/dt_util.py | Python | gpl-3.0 | 9,850 | 0.003046 | ##############################################################################
#
# Copyright (c) 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SO... | or to transform some basic data::
<dtml-var expr="phone[:3]">
Objects available in the document templates namespace may be used.
Subobjects of these objects may be used as well, although subobject
access is restricted by the optional validation method.
In addition, a special additional name, '_', is av... | ides access to the document template namespace as a
mapping object. This variable can be useful for accessing objects
in a document template namespace that have names that are not legal
Python variable names::
<dtml-var expr="_['sequence-number']*5">
This variable also has attributes that provide access... |
pidydx/grr | grr/lib/communicator_test.py | Python | apache-2.0 | 32,398 | 0.006389 | #!/usr/bin/env python
"""Test for client."""
import array
import pdb
import time
import requests
import logging
from grr.client import actions
from grr.client import comms
from grr.lib import aff4
from grr.lib import communicator
from grr.lib import config_lib
from grr.lib import flags
from grr.lib import front_e... | import crypto as rdf_crypto
from grr.lib.rdfvalues import flows as rdf_flows
# pylint: mode=test
def MakeHTTPException(code=500, msg="Error"):
"""A helper for creating a HTTPError exception."""
response = requests.Response()
response.status_code = code
return requests.ConnectionError(msg, response=response)... | tus_code = code
response._content = data
return response
class ClientCommsTest(test_lib.GRRBaseTest):
"""Test the communicator."""
def setUp(self):
"""Set up communicator tests."""
super(ClientCommsTest, self).setUp()
# These tests change the config so we preserve state.
self.config_stubber ... |
mariocesar/django-startup | startup/accounts/urls.py | Python | mit | 723 | 0.005533 | # | coding=utf-8
from django.conf.urls import patterns, url, include
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse_lazy
from django.views.generic import RedirectView
from startup.accounts.views import DetailUser, UpdateUser, CreateUser
urlpatterns = patterns(
... | tail'), permanent=False))),
url(r'^create/$', CreateUser.as_view(), name='account_create'),
url(r'^detail/$', login_required(DetailUser.as_view()), name='account_detail'),
url(r'^update/$', login_required(UpdateUser.as_view()), name='account_update'),
url(r'', include('django.contrib.auth.urls')),
)
|
dywisor/kernelconfig | kernelconfig/lang/cond.py | Python | gpl-2.0 | 3,328 | 0 | # This file is part of kernelconfig.
# -*- coding: utf-8 -*-
import abc
import collections.abc
import os.path
from . import parser
__all__ = [
"ConfigOptionConditionContext",
"IncludeFileConditionContext"
]
class BaseConditionContext(collections.abc.Mapping):
@abc.abstractproperty
def COND_OPS(cl... | n iter(self._evaluators)
def __len__(self):
return len(self._evaluators)
def __call__(self, cond_type, cond_func, cond_args):
return se | lf._evaluators[cond_type](cond_func, cond_args)
# --- end of BaseConditionContext ---
class ConfigOptionConditionContext(BaseConditionContext):
COND_OPS = [
parser.KernelConfigOp.condop_exists,
]
def get_context_desc(self):
return "config option"
def __init__(self, config_choices, ... |
sp4x/osnf | osnf/core.py | Python | apache-2.0 | 1,570 | 0.015287 | '''
Created on 13/set/2014
@author: Vincenzo Pirrone <pirrone.v@gmail.com>
'''
from conf.node import stations, NAME, DESCRIPTION
from osnf.api import Node, Network, set_network_object
class LocalNode(Node):
def _init_station(self, key, desc):
if not desc.has_key('enabled') or desc['enabled'... | '], data=data, monitors=monitors)
self.stations[key] = st
def __init__(self, name, description):
Node.__init__(self, name, description)
self.stations = {}
for key in stations.keys():
self._init_station(key, stations[key])
def get_station(sel... | top(self):
for st in self.stations.values():
st.stop()
class NetworkImpl(Network):
def __init__(self):
self.local_node = LocalNode(NAME, DESCRIPTION)
def get_node(self, name):
return self.local_node
def start(self):
self.local_node.start()
... |
timjinx/Sample-Repo | python/test_pysftp.py | Python | apache-2.0 | 2,864 | 0.022346 | import os
import pysftp
import sys
import subprocess
import glob
sys.path.append("C:\Users\jinkersont\.gnupg")
sys.path.append("C:\Users\jinkersont")
sys.path.append("C:\Program Files (x86)\gnupg\\bin")
print(sys.path)
UPLOAD = {
"SERVER": "192.168.80.33",
"PORT": 22,
"USERNAME": "sftpu... | on("-g", "--gpgkey", dest="gpgkey",
help="The GPG Key", metavar="GPGKEY")
(options, args) = parser.parse_args()
if not options.server :
options.server = UPLOAD['SERVER']
if not options.port :
options.port = UPLOAD['PORT']
| if not options.directory :
options.directory = UPLOAD['FOLDER']
if not options.transformation :
options.transformation = UPLOAD['TRANSFORMATION']
if not os.path.exists(options.transformation) :
print "Transformation file not found"
exit(-1)
if not options.gpgkey :
options.gpgkey = UPLOAD['G... |
belatrix/BackendAllStars | administrator/pagination.py | Python | apache-2.0 | 497 | 0 | from rest_framework.pagination import Limit | OffsetPagination
from rest_framework import status
from rest_framework.response import Response
class AdministratorPagination(LimitOffsetPagination):
def get_paginate | d_response(self, data):
return Response({
"status": True,
"code": status.HTTP_200_OK,
'next': self.get_next_link(),
'previous': self.get_previous_link(),
'count': self.count,
'results': data
})
|
quaddra/engage | python_pkg/engage/drivers/genforma/add_apt_repository.py | Python | apache-2.0 | 5,376 | 0.005208 |
"""Resource manager for using the add-apt-repository command (part of the
python-software-properties package).
"""
# Common stdlib imports
import sys
import os
import os.path
import re
import glob
# fix path if necessary (if running from source or running as test)
try:
import engage.utils
except:
sys.exc... | r class for the driver.
# If this driver is a service, inherit from service_manager.Manager.
# If the driver is just a resource, it should inherit from
# resource_ | manager.Manager. If you need the sudo password, add
# PasswordRepoMixin to the inheritance list.
#
class Manager(resource_manager.Manager, PasswordRepoMixin):
REQUIRES_ROOT_ACCESS = True
def __init__(self, metadata, dry_run=False):
package_name = "%s %s" % (metadata.key["name"],
... |
sangwook236/SWDT | sw_dev/python/rnd/test/machine_learning/keras/keras_conv_filter_visualization.py | Python | gpl-3.0 | 8,314 | 0.026101 | #!/usr/bin/env python
# coding: UTF-8
from __future__ import print_function
import time
import numpy as np
from PIL import Image as pil_image
from tensorflow.keras.preprocessing.image import save_img
from tensorflow.keras import layers
from tensorflow.keras.applications import vgg16
from tensorflow.keras import backen... | t to disk.
save_img('vgg_{0:}_{1:}x{1:}.png'.format(layer_name, n), stitched_filters)
# This is the placeholder for the input images.
assert len(model.inputs) == 1
input_img = model.inputs[0]
# Get the symbolic outputs of each "key" layer (we gave them unique n | ames).
layer_dict = dict([(layer.name, layer) for layer in model.layers[1:]])
output_layer = layer_dict[layer_name]
assert isinstance(output_layer, layers.Conv2D)
# Compute to be processed filter range.
filter_lower = filter_range[0]
filter_upper = (filter_range[1]
if filter_range[1] is not None
else ... |
zhengjue/mytornado | study/1/dnspython/demo1.py | Python | gpl-3.0 | 537 | 0.016771 | #!/usr/bin/env python
# _*_ coding:utf-8 _*-_
############################
# File Name: demo.py
# Author: lza
# Created Time: 2016-08-30 16:29:35
############################
import dns.resolver
domain = raw_input ('Please input an domain: ') #输入域名地址
MX = dns.resolver.query(domain , "MX") #指定查询类型为A记录
for i in M... | rence及exchanger信息
| print 'MX preference =', i.preference, 'mail exchanger =', i.exchange
if __name__ == "__main__":
pass
|
jjhelmus/artview | artview/scripts/gatefilter.py | Python | bsd-3-clause | 1,159 | 0 | """
gatefilter.py
Driver function that creates an ARTView display and initiates Gatefilter.
"""
import os
import sys
from ..core import Variable, QtGui, QtCore
from ..components import RadarDisplay, Menu
from ._common import _add_all_advanced_tools, _parse_dir, _parse_field
from ..plugins import GateFilt | er
def run(DirIn=None, filename=None, field=None):
"""
artview execution for filtering gates radar display
"""
DirIn = _parse_dir(DirIn)
app = QtGui.QApplication(sys.argv)
# start Menu and initiate Vradar
| menu = Menu(DirIn, filename, mode=("Radar",), name="Menu")
Vradar = menu.Vradar
field = _parse_field(Vradar.value, field)
# start Displays
Vtilt = Variable(0)
plot1 = RadarDisplay(Vradar, Variable(field), Vtilt, name="Display",
parent=menu)
filt = GateFilter(Vradar... |
Coteh/timetable | src/time_converter.py | Python | mit | 1,745 | 0.004585 | import math
from src.timetable_exceptions import InvalidTimeException
## Right now I'm not using datetime because the time of day for the class
# should be timestamp-independent
## 1440 is the amount of minutes in a single day, starting from 0
def getHoursAndMins(timeNum):
amt | OfHours = math.fl | oor(timeNum / 60)
amtOfMins = timeNum % 60
return amtOfHours, amtOfMins
def getPrintedTime(amtOfHours, amtOfMins):
amtOfHoursStr = "0" + str(amtOfHours) if (amtOfHours < 10) else str(amtOfHours)
amtOfMinsStr = "0" + str(amtOfMins) if (amtOfMins < 10) else str(amtOfMins)
return (amtOfHoursStr + ":" ... |
dominikl/openmicroscopy | components/tools/OmeroPy/test/integration/gatewaytest/test_chgrp.py | Python | gpl-2.0 | 12,030 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright (C) 2012 University of Dundee & Open Microscopy Environment.
All Rights Reserved.
Copyright 2013 Glencoe Software, Inc. All rights reserved.
Use is subject to license terms supplied in LICENSE.txt
pytest fixtures used as def... | waywrapper):
"""
Create a new group with the User as member. Test move t | he Dataset/Image to
new group.
"""
gatewaywrapper.loginAsAuthor()
dataset = gatewaywrapper.createPDTree(dataset="testDatasetChgrp")
image = gatewaywrapper.createTestImage(dataset=dataset)
ctx = gatewaywrapper.gateway.getAdminService().getEventContext()
uuid = ctx.sessionUuid
gatewaywrap... |
toddpalino/kafka-tools | kafka/tools/assigner/actions/clone.py | Python | apache-2.0 | 2,839 | 0.00317 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | help="List of source broker IDs", required=True, type=int, nargs='*')
parser.add_argument('-t', '--to_broker', help="Broker ID to copy partitions to", required=True, type=int)
def process_cluster(self):
source_set = set(self.sources)
for partition in self.cluster.partitions(self.args.exclu... | og.warn("Target broker (ID {0}) is already in the replica list for {1}:{2}".format(self.to_broker.id, partition.topic.name, partition.num))
# If the broker is already in the replica list, it ALWAYS becomes the leader
if self.to_broker != partition.replicas[0]:
... |
jamtot/DailyChallenge | rektangles (18jul2016)/rekt.py | Python | mit | 303 | 0.019802 | def rektangle(word, x, y):
| wlen=len(word)
length=wlen*y - (wlen- | 1)
width=wlen*x - (wlen-1)
# continue this
if __name__ == "__main__":
while True:
inputs = raw_input().split()
word=inputs.pop()
xy = map(int,inputs)
print rektangle(word, xy[0], xy[1])
|
TheLaunchNinja/exosphere | exosphere/cli.py | Python | gpl-3.0 | 225 | 0 | import clize
from . import stacks
def update(stack_type, *args):
stacks.get(stack | _type).update(*args)
def main():
clize.run([stacks.staticsite, stacks.staticsi | tewithemail])
if __name__ == '__main__':
main()
|
awagnon/maraschino | modules/sabnzbd.py | Python | mit | 5,990 | 0.004841 | try:
import json
except ImportError:
import simplejson as json
from flask import jsonify, render_template, request
import urllib
import urllib2
from jinja2.filters import FILTERS
from Maraschino import app
from maraschino.tools import *
from maraschino import logger
def sab_http():
if get_setting_value(... | sabnzbd = json.JSONDecoder().decode(result)
except:
pass
else:
| try:
result = urllib.urlopen(sabnzbd_url('config', '&name=set_pause&value=' + time)).read()
sabnzbd = json.JSONDecoder().decode(result)
except:
pass
if sabnzbd:
return jsonify({'status': sabnzbd['status']})
return jsonify({'status': False})
@app.rou... |
randpdevs/chopper | manage.py | Python | mit | 252 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTING | S_MODULE", "mathathon.settings")
from django.core.manag | ement import execute_from_command_line
execute_from_command_line(sys.argv)
|
ktan2020/legacy-automation | win/Lib/site-packages/wx-3.0-msw/wx/lib/colourselect.py | Python | mit | 5,498 | 0.006366 | #----------------------------------------------------------------------------
# Name: ColourSelect.py
# Purpose: Colour Box Selection Control
#
# Author: Lorne White, Lorne.White@telusplanet.net
#
# Created: Feb 25, 2001
# Licence: wxWindows license
#--------------------------------... |
self.colour = colour
bmp = self.MakeBitmap()
self.SetBitmap(bmp)
def SetLabel(self, label):
self.label = label
def GetLabel(self):
return self.label
def MakeBitmap(self):
bdr = 8
width, height = self.GetSize()
#... | wx.EmptyBitmap(width-bdr, height-bdr)
dc = wx.MemoryDC()
dc.SelectObject(bmp)
dc.SetFont(self.GetFont())
label = self.GetLabel()
# Just make a little colored bitmap
dc.SetBackground(wx.Brush(self.colour))
dc.Clear()
if label:
# Add ... |
anguoyang/SMQTK | OLD_ROOT/Backend/SMQTK_Backend/FeatureMemory.py | Python | bsd-3-clause | 80,904 | 0.00068 | """
LICENCE
-------
Copyright 2013 by Kitware, Inc. All Rights Reserved. Please refer to
KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
"""
# -*- coding: utf-8 -*-
from _abcoll import Iterable
from collections import deque
import l... | urpose of
acquiring a write lock in the presence of readers.
"""
def __init__(self):
""" Initialize lock state
"""
# NOTE: If ever we want an equal access priority instead of giving
# access priority to the writers, we could have a global queue FIFO
# queu | e instead of just the pending writers queue. This would move this
# from a case-2 RWLock problem to a case-3, ensuring zero starvation of
# either lock.
# Condition lock on internal variables
# noinspection PyUnresolvedReferences
self.__cond = multiprocessing.Condition()
... |
openstack/tempest-lib | tempest_lib/services/compute/certificates_client.py | Python | apache-2.0 | 1,435 | 0 | # Copyright 2013 IBM Corp
# 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 appl... | expr | ess or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_serialization import jsonutils as json
from tempest_lib.api_schema.response.compute.v2_1 import certificates as schema
from tempest_lib.common import rest_client
class CertificatesC... |
franck-talbart/codelet_tuning_infrastructure | ctr-common/plugins/5b5a1158-32f7-11e2-bae0-0022191169c2/main.py | Python | gpl-3.0 | 2,464 | 0.00974 | #************************************************************************
# Codelet Tuning Infrastructure
# Copyright (C) 2010-2015 Intel Corporation, CEA, GENCI, and UVSQ
#
# 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
# th... | atplotlib to not use any Xwindows backend.
matplotlib.use('Agg')
import bargraph, histogram, piechart
class PlotPlugin(HapiPlugin):
@hapi_command("histogram")
def histogram(self, params):
""" Create a PNG file containing a histogram
Args:
self: class of the plugin
... | ---------------------------------------------------------
@hapi_command("bargraph")
def bargraph(self, params):
""" Create a PNG file containing a histogram
Args:
self: class of the plugin
params: working parameters
Returns:
Nothing
... |
rogerhu/django | tests/aggregation_regress/tests.py | Python | bsd-3-clause | 47,311 | 0.002811 | from __future__ import unicode_literals
import datetime
import pickle
from decimal import Decimal
from operator import attrgetter
from django.core.exceptions import FieldError
from django.contrib.contenttypes.models import ContentType
from django.db.models import Count, Max, Avg, Sum, StdDev, Variance, F, Q
from djan... | 59',
mean_auth_age=45.0,
name='Sams Teach Yourself Django in 24 Hours',
pages=528,
price=Decimal("23.09"),
pubdate=datetime.date(2008, 3, 3),
publisher_id=2,
rating=3.0
)
# Different DB backends return different types fo... | es queries can be combined with annotate and extra
obj = Book.objects.annotate(mean_auth_age=Avg('authors__age')).extra(select={'manufacture_cost': 'price * .5'}).values().get(pk=2)
manufacture_cost = obj['manufacture_cost']
self.assertTrue(manufacture_cost == 11.545 or manufacture_cost == Decim... |
JiwonYeom/TIL | python/python-class.py | Python | mit | 629 | 0.009539 | import webbrowser
# Class
class Book():
""" This class provides Book information from the Golden Lion publisher. """
# Constructor
def __init__(self, book_title, book_summary, book_author, book_release_date, book_url):
# instance variable | s - relative to the instances
self.title = book_title
self.summary = book_summary
self.author = book_author
self.release_date = book_release_date
self.url = book_ur | l
# instance method
def show_summary(self):
webbrowser.open(self.url)
# Class Variables (all instances share)
PUBLISHER = ["Golden Lion"] |
andreasvc/cython | tests/run/set_literals.py | Python | apache-2.0 | 2,234 | 0.002238 | # Py2.7+ only
import s | ys
def test_set_literal():
"""
>>> type(test_set_literal()) is set
True
>>> sorted(test_set_literal())
['a', 'b', 1]
"""
s1 = {1, 'a', 1, 'b', 'a'}
return s1
def test_set_add():
"""
>>> type(test_set_add()) is set
True
>>> sorted(test_set_add())
['a', 1, (1, 2)]
... | s1.add((1, 2))
return s1
def test_set_comp():
"""
>>> type(test_set_comp()) is set
True
>>> sorted(test_set_comp())
[0, 1, 2]
"""
s1 = {i % 3 for i in range(5)}
return s1
def test_frozenset_set_comp():
"""
>>> type(test_frozenset_set_comp()) is frozenset
True
>>>... |
auto-mat/django-webmap-corpus | webmap/migrations/0012_line_to_multiline.py | Python | mit | 736 | 0.004076 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.contrib.gis.geos import GeometryCollection
def change_line_to_multiline(apps, schema_editor):
# We can't import the Person model directly as it may be a newer
# version than this migration expe... | = GeometryCollection([poi.geom, ])
poi.save()
cla | ss Migration(migrations.Migration):
dependencies = [
('webmap', '0011_auto_20160101_0521'),
]
operations = [
migrations.RunPython(change_line_to_multiline),
]
|
cst13/canstel | setup_template.py | Python | mit | 1,030 | 0.001942 | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import sys
extra_install = []
if sys.version_info <= (3,1):
extra_install.append('futures')
if sys.version_info <= (3,6):
extra_install.append('pysha3')
setup(
name="moneywagon",
version='{{ version }}',
description='Next Gener... | d').read(),
author='Chris Priest',
author_email='cp36820 | 2@ohiou.edu',
url='https://github.com/priestc/moneywagon',
packages=find_packages(),
scripts=['bin/moneywagon'],
include_package_data=True,
license='LICENSE',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Programming Language :: Python',
'Programming Langu... |
ktosiek/pytest-freezegun | tests/test_freezegun.py | Python | mit | 7,458 | 0 | # -*- coding: utf-8 -*-
import re
from datetime import datetime
def test_freezing_time(testdir):
testdir.makepyfile("""
import pytest
from datetime import date, datetime
@pytest.mark.freeze_time('2017-05-20 15:42')
def test_sth():
assert datetime.now().date() == date(... | 2)] = float(match.group(1))
# It should take a non-negative amount of time for each of the steps,
# but it also should never take longer than a second
assert 0 <= durations['setup'] <= 1
assert 0 <= durations['call'] <= 1
assert 0 <= durations['teardown'] <= 1
def test_marker_durations(testdir):
... | ld be frozen for the pytest itself too.
That caused it to report weird durations for test runs,
namely very large numbers for setup and very large
NEGATIVE numbers for teardown.
"""
testdir.makepyfile("""
import pytest
from datetime import date, datetime
@pytest.mark.freeze_... |
stackArmor/security_monkey | security_monkey/tests/watchers/rds/test_rds_subnet_group.py | Python | apache-2.0 | 1,888 | 0 | # Copyright 2016 Bridgewater Associates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | conn = boto.rds.connect_to_region(AWS_DEFAULT_REGION)
conn.create_db_subnet_group("db_subnet", "my db subnet", subnet_ids)
watcher = RDSSubnetGroup(accounts=[self.account.name])
item_list, exception_map = watcher.slurp()
self.assertIs(
expr1=len(item_list),
... | expr2=1,
msg="Watcher should have 1 item but has {}".format(len(item_list)))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.