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 |
|---|---|---|---|---|---|---|---|---|
TomckySan/python-training | string.py | Python | mit | 278 | 0 | # coding: utf-8
# | ζεεγ―""γ§γ''γ§γγγγ
print "hello" + ' world'
print u"γ»γ" * 5
print u"ζζ₯γ\tγγ£γ¨\tγγ¬γ«γ€\n\"\\\\γγ―γ―γ―γ\""
# θ€ζ°θ‘γ«ζΈ‘γγ¨γγ―"γ3εηΆγγγ°γγ
print u"""
δ»ζ₯γ
γγ
ε€©ζ° |
γ§γ
γ
"""
|
octomike/hellodjango | paste/models.py | Python | mit | 341 | 0.014663 | from django.db import models
from uuid import uuid4
def get_short_uuid():
return str(uuid4())[0:5]
class Code(models.Model):
key = models.CharField(max_length=6, primary_key=True, default=get_short_uuid)
lang = models.CharField(max_length=32, default='bas | h')
code = models.Text | Field(max_length=2048, help_text="some Code")
|
lcrees/twoq | twoq/tests/lazy/auto/test_filtering.py | Python | bsd-3-clause | 962 | 0.00104 | # -*- coding: utf-8 -*-
from twoq.support import unittest
#pylint: disable-msg=w0614,w0401
from twoq.tests.auto.filtering import * # @UnusedWildImport
from twoq.tests.auto.queuing import AQMixin
class TestAutoFilterQ(unittest.TestCase, AQMixin, AFilterQMixin):
def setUp(self):
self.maxDiff = None
... | ff = None
from twoq.lazy.filtering import collectq
self.qclass = collectq
class TestAutoSetQ(u | nittest.TestCase, AQMixin, ASetQMixin):
def setUp(self):
from twoq.lazy.filtering import setq
self.qclass = setq
if __name__ == '__main__':
unittest.main()
|
ff0000/red-fab-deploy | fab_deploy/base/snmp.py | Python | mit | 2,394 | 0.002506 | import os
from fab_deploy import funct | ions
from fab_deploy.config import CustomConfig
from fab_deploy.base.file_based import BaseUpdateFiles
from fabric.api import run, sudo, env, put, execute, | local
from fabric.tasks import Task
class SNMPSingleSync(Task):
"""
Sync a snmp config file
Takes one required argument:
* **filename**: the full path to the file to sync.
"""
name = 'sync_single'
remote_config_path = '/etc/sma/snmp/snmpd.conf'
def _add_package(self):
rais... |
Comunitea/CMNT_00040_2016_ELN_addons | product_price_history_analysis/__init__.py | Python | agpl-3.0 | 1,005 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2004-2016 QUIVAL, S.A. All Rights Reserved
# $Pedro GΓ³mez Campos$ <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of th... | e useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not,... | ##################################################
from . import report
|
agurfinkel/brunch | exp/bencher.py | Python | mit | 2,706 | 0.000739 | #! /usr/bin/env python3
# Suggest name to z3 binary based on it its sha
import sys
import words
import subprocess
import argparse
import os.path
import shutil
from pathlib import Path
import yaml
class Bencher(object):
def __init__(self):
self._name = 'bencher'
self._help = 'Make benchmark di... | ts=True, exist_ok=True)
prefix = args.prefix
suffix = args.suffix
# pick an action to apply to each file
if args.dry_run:
def _dry_ | run_action(src, dst):
pass
file_action = _dry_run_action
elif args.mv:
file_action = shutil.move
else:
file_action = shutil.copy2
inverse = dict()
for id, src in enumerate(args.files):
idx_str = num_fmt.format(idx=id)
... |
sternshus/arelle2.7 | svr-2.7/arelle/ValidateFilingText.py | Python | apache-2.0 | 33,886 | 0.006758 | u'''
Created on Oct 17, 2010
@author: Mark V Systems Limited
(c) Copyright 2010 Mark V Systems Limited, All rights reserved.
'''
#import xml.sax, xml.sax.handler
from __future__ import with_statement
from lxml.etree import XML, DTD, SubElement, XMLSyntaxError
import os, re, io
from arelle import XbrlConst
f... | r'),
'alink': ('body'),
'alt': ('img'),
'bgcolor': ('body','table', 'tr', 'th', 'td'),
'border': ('table', 'img'),
'cellpadding': ('table'),
'cellspacing': ('table'),
'class': ('*'),
'clear': ('br'),
'color': ('font'),
'colspan': ('td','th'),
'compact': ('dir','dl'... | ': ('h1','h2','h3','h4','h5','h6','hr','p','img','caption','div','table','td','th','tr','font',
'center','ol','li','ul','bl','a','big','pre','dir','address','blockqoute','menu','blockquote',
'em', 'strong', 'dfn', 'code', 'samp', 'kbd', 'var', 'cite', 'sub', 'sup', 'tt', 'i', 'b', 'small', '... |
shivekkhurana/learning | python/network-security/ceaser.py | Python | mit | 1,385 | 0.01083 |
import string
import itertools
class Ceaser:
def __init__(self, payload, by=3, direction="right"):
self.payload = payload
self.by = by
self.direction = direction
def _encrypt_alphabet(self, alphabet):
ord_val = ord(alphabet) + self.by
if self.direction == 'left': ord_v... | crypt_alphabet(self, alphabet):
ord_val = ord(alphabet) + self.by
if self.direction == 'right': ord_val = ord(alphabet) - self.by
if ord_val > 256 or ord_val < 0: ord_val = ord_val%256
| return chr(ord_val)
def encrypt(self):
return ''.join([self._encrypt_alphabet(a) for a in self.payload])
def decrypt(self):
return ''.join([self._decrypt_alphabet(a) for a in self.payload])
def main():
payload = str(raw_input("Enter Payload : "))
by = int(raw_... |
poxstone/ANG2-TEMPLATE | myApp/tests/unit/__init__.py | Python | apache-2.0 | 30 | 0 | __auth | or__ = | 'davidcifuentes'
|
lfairchild/PmagPy | programs/__init__.py | Python | bsd-3-clause | 1,586 | 0.011349 | #!/usr/bin/env pythonw
import sys
from os import path
import pkg_resources
command = path.split(sys.argv[0])[-1]
from .program_envs import prog_env
if command.endswith(".py"):
mpl_env = prog | _env.get(command[:-3])
elif command.endswith("_a"):
mpl_env = prog_env.get(command[:-2])
else:
mpl_env = prog_env.get(command)
import matplotlib
# if backend was already set, skip this step
if matplotlib.get_backend() in ('WXAgg', 'TKAgg'):
pass
# if backend wasn't set yet, set it appropriately
| else:
if mpl_env:
matplotlib.use(mpl_env)
else:
matplotlib.use("TKAgg")
if "-v" in sys.argv:
print("You are running:")
try:
print(pkg_resources.get_distribution('pmagpy'))
except pkg_resources.DistributionNotFound:
pass
try:
print(pkg_resources.get_distri... |
elkingtowa/azove | features/steps/peer.py | Python | mit | 12,702 | 0.000315 | from utils import instrument
from azove.utils import recursive_int_to_big_endian
import mock
@given(u'a packet') # noqa
def step_impl(context):
context.packet = context.packeter.dump_packet('this is a test packet')
@when(u'peer.send_packet is called') # noqa
def step_impl(context):
context.peer.send_packe... | = [packeter.cmd_map_by_name['Hello'],
'incompatible_protocal_version',
packeter.NETWORK_ID,
packeter.CLIENT_ID,
packeter.config.getint('network', 'listen_port'),
packeter.CAPABILITIES,
packeter.config.g | et('wallet', 'coinbase')
]
context.packet = packeter.dump_packet(data)
@given(u'a Hello packet with network id incompatible') # noqa
def step_impl(context):
packeter = context.packeter
data = [packeter.cmd_map_by_name['Hello'],
packeter.PROTOCOL_VERSION,
'incompatible_... |
mivade/streamis | streamis.py | Python | mit | 4,156 | 0.000481 | """Streamis - Subscribe to Redis pubsub channels via HTTP and EventSource."""
import logging
import asyncio
from asyncio import Queue
import aioredis
from tornado.platform.asyncio import AsyncIOMainLoop
from tornado import web
from tornado.iostream import StreamClosedError
from tornado.options import options, define... | and broadcast to all
HTTP listen | ers.
"""
while len(self.listeners) > 0:
msg = await self.channel.get()
logger.debug("Got message: %s" % msg)
closed = []
for listener in self.listeners:
try:
listener.queue.put_nowait(msg)
except:
... |
fbradyirl/home-assistant | homeassistant/components/tplink/config_flow.py | Python | apache-2.0 | 364 | 0 | """Config flow for TP-Link."""
from homeassistant.helpers import config_entry_flow
from homeassistant import config_entries
from .const import DOMAIN
from .common import async_get_discoverable_devices
config_entry_flow.register | _discovery_flow(
DOMAIN,
"TP-Link Smart | Home",
async_get_discoverable_devices,
config_entries.CONN_CLASS_LOCAL_POLL,
)
|
mjumbewu/django-subscriptions | subscriptions/feeds/__init__.py | Python | bsd-2-clause | 252 | 0.003968 | from readers import (autodiscover, FeedReader, TimestampedModelFeedReader,
RSSFeedReader)
from library import (FeedLibrary)
from dispatch import (Subscripti | onDispatc | her, SubscriptionEmailer)
from utils import (FeedRecordUpdater, FeedRecordCleaner)
|
mstritt/orbit-image-analysis | src/main/python/deeplearn/utils/image_reader.py | Python | gpl-3.0 | 7,239 | 0.00746 | import os
import numpy as np
import tensorflow as tf
def image_scaling(img, label):
"""
Randomly scales the images between 0.5 to 1.5 times the original size.
Args:
img: Training image to scale.
label: Segmentation mask to scale.
"""
scale = tf.random_uniform([1], minval=0.5, max... | lueError: # Adhoc for test.
image = mask = line.strip("\n")
images.append(data_dir + image)
masks.append(data_dir + mask)
return images, masks
def read_images_from_disk(input_queue, input_size, random_scale, random_mirror, ignore_label): # optional pre-processing arguments
"""Read o... | ut_size: a tuple with (height, width) values.
If not given, return images of original size.
random_scale: whether to randomly scale the images prior
to random crop.
random_mirror: whether to randomly mirror the images prior
to random crop.
igno... |
waltermoreira/serfnode | serfnode/me.py | Python | mit | 345 | 0 | #!/usr/bin/python
import json
import os
import time
def main():
while not os.path.exists('/agent_up'):
time.sleep(0.1)
node_id = json.load(open('/me.json'))['id']
node = json.load(open('/serfnodes_by_id.json'))[node_id]
| print('{}:{}'.format(node | ['serf_ip'], node['serf_port']))
if __name__ == '__main__':
main()
|
sandvine/horizon | openstack_dashboard/dashboards/project/routers/tests.py | Python | apache-2.0 | 38,873 | 0.000077 | # Copyright 2012, Nachi Ueno, NTT MCL, 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 applic... | res = self.client.get(self.INDEX_URL)
| table_data = res.context['table'].data
self.assertEqual(len(table_data), 1)
self.assertIn('(Not Found)',
table_data[0]['external_gateway_info']['network'])
self.assertTemplateUsed(res, '%s/routers/index.html' % self.DASHBOARD)
self.assertMessageCount(res, error=... |
sornars/urllib3 | test/test_response.py | Python | mit | 21,348 | 0.000843 | import unittest
from io import BytesIO, BufferedReader
try:
import http.client as httplib
except ImportError:
import httplib
from urllib3.response import HTTPResponse
from urllib3.exceptions import DecodeError, ResponseNotChunked
from base64 import b64decode
# A known random (i.e, not-too-compressible) pay... | 81MUOnK3SGWLH8HeWPa1t5KcW
S5moAj5HexY/g/F8TctpxwsvyZp38dXeLDjSQvEQIkF7XR3YXbeZgKk3V34KGCPOAeeuQDIgyVhV
nP4HF2uWHA==""")
class TestLegacyResponse(unittest.TestCase):
def test_getheaders(self):
headers = {'host': 'example.com'}
r = HTTPResponse(headers=headers)
self.assertEqual(r.getheaders(... | lass TestResponse(unittest.TestCase):
def test_cache_content(self):
r = HTTPResponse('foo')
self.assertEqual(r.data, 'foo')
self.assertEqual(r._body, 'foo')
def test_default(self):
r = HTTPResponse()
self.assertEqual(r.data, None)
def test_none(self):
r = HT... |
yotchang4s/cafebabepy | src/main/python/sndhdr.py | Python | bsd-3-clause | 7,088 | 0.003245 | """Routines to help recognizing sound files.
Function whathdr() recognizes various types of sound file headers.
It understands almost all headers that SOX can decode.
The return tuple contains the following items, in this order:
- file type (as SOX understands it)
- sampling rate (0 if unknown or hard to decode)
- nu... | = namedtuple('SndHeaders',
'filetype framerate nchan | nels nframes sampwidth')
SndHeaders.filetype.__doc__ = ("""The value for type indicates the data type
and will be one of the strings 'aifc', 'aiff', 'au','hcom',
'sndr', 'sndt', 'voc', 'wav', '8svx', 'sb', 'ub', or 'ul'.""")
SndHeaders.framerate.__doc__ = ("""The sampling_rate will be either the actual
value or 0 if u... |
tongwang01/tensorflow | tensorflow/contrib/bayesflow/examples/reinforce_simple/reinforce_simple_example.py | Python | apache-2.0 | 5,012 | 0.009777 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | nse for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Simple examples of the REINFORCE algorithm."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print... | tf.contrib.distributions
sg = tf.contrib.bayesflow.stochastic_graph
st = tf.contrib.bayesflow.stochastic_tensor
def split_apply_merge(inp, partitions, fns):
"""Split input according to partitions. Pass results through fns and merge.
Args:
inp: the input vector
partitions: tensor of same length as input... |
lakewik/storj-gui-client | UI/qt_interfaces/logs_table_ui.py | Python | mit | 3,651 | 0.002465 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'logs_table.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s)... | ate("Logs", "Save logs as...", None))
self.logs_settings_bt.setText(_translate("Logs", "Logs settings", None))
self.label_2.setText(_translate("Logs", "<html><head/><body><p align=\"center\"><span style=\" font-size:14pt; font-weight:600;\">Total log positions:</span></p></body></html>", None))
... | t-weight:600;\">0</span></p></body></html>", None))
self.clear_logs_bt.setText(_translate("Logs", "Clear logs", None))
|
desihub/desisurvey | py/desisurvey/scripts/surveymovie.py | Python | bsd-3-clause | 24,365 | 0.001313 | """Script wrapper for creating a movie of survey progress.
To run this script from the command line, use the ``surveymovie`` entry point
that is created when this package is installed, and should be in your shell
command search path.
The optional matplotlib python package must be installed to use this script.
The ex... | severity >= info')
parser.add_argument('--debug', action='store_true',
help='display log messages with severity >= debug (implies verbose) | ')
parser.add_argument('--log-interval', type=int, default=100, metavar='N',
help='interval for logging periodic info messages')
parser.add_argument(
'--exposures', default='exposures_surveysim.fits', metavar='FITS',
help='name of FITS file with list of exposures taken')
parser.add_a... |
rwl/PyCIM | CIM15/IEC61970/Wires/ProtectedSwitch.py | Python | mit | 4,514 | 0.00288 | # Copyright (C) 2010-2011 Richard Lincoln
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish... | ectionEquipments
self._RecloseSequences = []
self.RecloseSequences = [] if RecloseSequences is None else RecloseSequences
super(ProtectedSwitch, self).__init__(*args, **kw_args)
_attrs = ["breakingCapacity"]
_attr_types = {"breakingCapacity": float}
_defaults = {"breakingCapacity"... | "RecloseSequences"]
_many_refs = ["ProtectionEquipments", "RecloseSequences"]
def getProtectionEquipments(self):
"""Protection equipments that operate this ProtectedSwitch.
"""
return self._ProtectionEquipments
def setProtectionEquipments(self, value):
for p in self._Prote... |
apllicationCOM/youtube-dl-api-server | youtube_dl_server/youtube_dl/extractor/anysex.py | Python | unlicense | 2,085 | 0.002398 | from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
parse_duration,
int_or_none,
)
class AnySexIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?anysex\.com/(?P<id>\d+)'
_TEST = {
| 'url': 'http://anysex.com/156592/',
'md5': '023e9fbb7f7987f5529a394c34ad3d3d',
'info_dict': {
'id': '156592',
'ext': 'mp4',
'title': 'Busty and sexy blon | die in her bikini strips for you',
'description': 'md5:de9e418178e2931c10b62966474e1383',
'categories': ['Erotic'],
'duration': 270,
'age_limit': 18,
}
}
def _real_extract(self, url):
mobj = re.match(self._VALID_URL, url)
video_id = mobj.g... |
wangy1931/tcollector | collectors/0/couchbase.py | Python | lgpl-3.0 | 4,853 | 0.013188 | #!/usr/bin/env python
"""
Couchbase collector
Refer to the following cbstats documentation for more details:
http://docs.couchbase.com/couchbase-manual-2.1/#cbstats-tool
"""
import os
import sys
import time
import subprocess
import re
from collectors.etc import couchbase_conf
from collectors.lib import utils
CONF... | total_free_bytes',
'total_allocated_bytes',
'total_fragmentation_bytes',
'tcmalloc_current_thread_cache_bytes',
'tcmalloc_max_thread_cache_bytes',
'tcmalloc_unmapped_bytes',
] )
def find_couchbase_pid():
"""Fi... | LE)
for line in fd:
if line.startswith("exec"):
init_script = line.split()[1]
fd.close()
except IOError:
utils.err("Check permission of file (%s)" % COUCHBASE_INITFILE)
return
try:
fd = open(init_script)
for line in fd:
if line.startswith("PIDFILE"):
pid_file = l... |
shackra/thomas-aquinas | tests/test_draw_line.py | Python | bsd-3-clause | 667 | 0.028486 | # This code is so you can run the samples without installing the package
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
#
testinfo = "s, q"
tags = "Draw, Line"
import summa
from summa.director import director
from summa import draw
import pyglet, math
class TestLayer(summa.la... | aw.Line((0,0), (100,100), (255,255,255,255))
self.add( line )
def main():
director.init()
test_layer = TestLayer ()
main_scene = summa.scene.Scene (test_layer)
director.run (main_scene)
if __ | name__ == '__main__':
main()
|
ArchiFleKs/magnum | contrib/drivers/k8s_opensuse_v1/version.py | Python | apache-2.0 | 683 | 0 | # Copyright 2016 - SUSE Linux GmbH
#
# Licensed under the Apache License, | Version 2.0 (the "License");
# you may not use this fil | e except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITI... |
transistorfet/nerve | nerve/base/controllers/files.py | Python | gpl-3.0 | 1,042 | 0.004798 | #!/usr/bin/py | thon3
# -*- coding: utf-8 -*-
import nerve
from nerve.http i | mport PyHTML
import os.path
import mimetypes
class FileController (nerve.Controller):
@classmethod
def get_config_info(cls):
config_info = super().get_config_info()
config_info.add_setting('root', "Root Directory", default='nerve/http/wwwdata')
return config_info
def do_request(s... |
subeax/grab | test/case/proxy.py | Python | mit | 3,521 | 0.000568 | # coding: utf-8
from unittest import TestCase
#import string
import json
import re
from grab import Grab, GrabMisuseError
from t | est.util import TMP_FILE, GRAB_TRANSPORT, get_temp_file
from t | est.server import SERVER
from grab.proxy import ProxyList
DEFAULT_PLIST_DATA = \
'1.1.1.1:8080\n'\
'1.1.1.2:8080\n'
class GrabProxyTestCase(TestCase):
def setUp(self):
SERVER.reset()
def generate_plist_file(self, data=DEFAULT_PLIST_DATA):
path = get_temp_file()
with open(path,... |
xuerenlv/PaperWork | datamining_assignments/datamining_final/pandas_other.py | Python | apache-2.0 | 3,159 | 0.010763 | '''
Created on Jan 7, 2016
@author: nlp
'''
import pandas as pd
import numpy as np
import xgboost as xgb
from scipy.optimize import fmin_powell
from ml_metrics import quadratic_weighted_kappa
def eval_wrapper(yhat, y):
y = np.array(y)
y = y.astype(int)
yhat = np.array(yhat)
yhat = np.clip(np.round... | ratic_weighted_kappa(yhat, y)
def get_params():
params = {}
params["objective"] = "reg:linear"
params["eta"] = 0.1
params["min_child_weight"] = 80
params["subsample"] = 0.75
params["colsample_bytree"] = 0.30
params["silent"] = 1
params["max_depth"] = 9
return list(params.i... | as the format of pred=0, offset_pred=1, labels=2 in the first dim
data[1, data[0].astype(int)==sv] = data[0, data[0].astype(int)==sv] + bin_offset
score = scorer(data[1], data[2])
return score
# global variables
columns_to_drop = ['Id', 'Response']
xgb_num_rounds = 250
num_classes = 8
print("Load the data... |
ecolitan/fatics | venv/lib/python2.7/site-packages/netaddr/ip/iana.py | Python | agpl-3.0 | 14,149 | 0.002332 | #!/usr/bin/env python
#-----------------------------------------------------------------------------
# Copyright (c) 2008-2012, David P. D. Moss. All rights reserved.
#
# Released under the BSD license. See the LICENSE file for details.
#-----------------------------------------------------------------------------
... | allback(self._record)
self._record = None
elif self._level == self._tag_level + 1:
if name != 'xref':
self._record[name] = ''.join(self._tag_payload)
self._tag_payload = None
self._tag_feeding = False
self._... | e Parser that understands how to parse XML based records.
"""
def __init__(self, fh, **kwargs):
"""
Constructor.
fh - a valid, open file handle to XML based record data.
"""
super(XMLRecordParser, self).__init__()
self.xmlparser = make_parser()
self.xmlp... |
gorserg/openprocurement.tender.competitivedialogue | openprocurement/tender/competitivedialogue/views/stage1/complaint.py | Python | apache-2.0 | 1,110 | 0 | # -*- coding: utf-8 -*-
from openprocurement.tender.core.utils import optendersresource
from openprocurement.tender.openeu.views.complaint import (
TenderEUComplaintResource
)
from openprocurement.tender.competitivedialogue.constants import (
CD_EU_TYPE, CD_UA_TYPE
)
@optendersresource(name='{}:Tender Complai... | ',
path='/tenders/{tender_id}/complaints/{complaint_id}',
procurementMethodType=CD_EU_TYPE,
description="Competitive Dia | logue EU complaints")
class CompetitiveDialogueEUComplaintResource(TenderEUComplaintResource):
pass
@optendersresource(name='{}:Tender Complaints'.format(CD_UA_TYPE),
collection_path='/tenders/{tender_id}/complaints',
path='/tenders/{tender_id}/complaints/{complaint_id}',
... |
dhamaniasad/caniusepython3 | caniusepython3/test/test_command.py | Python | apache-2.0 | 1,792 | 0.001116 | # Copyright 2014 Google Inc. All rights reserved.
# Licensed under the Apache License, Version 2.0 | (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WI... | License for the specific language governing permissions and
# limitations under the License.
from __future__ import unicode_literals
from caniusepython3 import command
from caniusepython3.test import unittest, skip_pypi_timeouts
from distutils import dist
def make_command(requires):
return command.Command(dist.... |
chingchai/workshop | qgis-scripts/generate_stripmap_index.py | Python | mit | 2,746 | 0.006555 | #!python
# coding: utf-8
# edit by gistnu
# reference from lejedi76
# https://gis.stackexchange.com/questions/173127/generating-equal-sized-polygons-along-line-with-pyqgis
from qgis.core import QgsMapLayerRegistry, QgsGeometry, QgsField, QgsFeature, QgsPoint
from PyQt4.QtCore import QVariant
def getAllbbox(layer, widt... | endpoint = geom.interpolate((curs+step)*geom.length())
x_start = startpoint.asPoint().x()
y_start = startpoint.asPoint().y()
x_end = endpoint.asPoint().x()
y_end = endpoint.asPoint().y()
print 'x_start :' + str(x_start)
print 'y_start :' | + str(y_start)
currline = QgsGeometry().fromWkt('LINESTRING({} {}, {} {})'.format(x_start, y_start, x_end, y_end))
currpoly = QgsGeometry().fromWkt(
'POLYGON((0 0, 0 {height},{width} {height}, {width} 0, 0 0))'.format(height=height, width=width))
currpoly.translate(0... |
bnorthan/projects | Scripts/Jython/Grand_Challenge/DeconvolveChallengeImages_reflection.py | Python | gpl-2.0 | 1,894 | 0.016367 | # @StatusService status
# @DatasetService data
# @CommandService command
# @DisplayService display
# @IOService io
# this script deconvolves an image.
#
# It is assumed the images have allready been extended. See ExtendChallengeImages_reflection
rootImageDir="/home/bnorthan/Brian2014/Images/General/Deconvolution/Gra... | lay the psf
psf=data.open(psfName)
display.createDisplay(psf.getName(), psf);
# call RL with total variation
deconvolved = command.run("com.truenorth.commands.fft.TotalVariationRLCommand", True, "input", inputData, "psf", ps | f, "truth", None,"firstGuess", None, "iterations", iterations, "firstGuessType", "constant", "convolutionStrategy", "circulant", "regularizationFactor", regularizationFactor, "imageWindowX", 0, "imageWindowY", 0, "imageWindowZ", 0, "psfWindowX", 0, "psfWindowY", 0, "psfWindowZ", 0).get().getOutputs().get("output");
io.... |
thombashi/typepy | test/converter/test_bool.py | Python | mit | 2,806 | 0.000356 | """
.. codeauthor:: Tsuyoshi Hombashi <[email protected]>
"""
import pytest
import typepy
from ._common import convert_wrapper
class Test_Bool:
@pytest.mark.parametrize(
["method", "strict_level", "value", "expected"],
[
["convert", 0, True, True],
["convert", ... | 1, 1, None],
["try_convert", 1, 1.1, None],
["try_convert", 1, None, None],
["try_convert", 2, True, True],
| ["try_convert", 2, "true", None],
["try_convert", 2, "FALSE", None],
["try_convert", 2, 1, None],
["try_convert", 2, 1.1, None],
["try_convert", 2, None, None],
["force_convert", 0, True, True],
["force_convert", 0, "true", True],
... |
cedricbonhomme/services | freshermeat/web/views/api/v1/language.py | Python | agpl-3.0 | 1,163 | 0 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Freshermeat - An open source software directory and release tracker.
# Copyright (C) 2017-2020 CΓ©dric Bonhomme - https://www.cedricbonhomme.org
#
# For more information: https://sr.ht/~cedric/freshermeat
#
# This program is free software: you can redistribute it and/or ... | gram. If not, s | ee <http://www.gnu.org/licenses/>.
from freshermeat.bootstrap import manager
from freshermeat.models import Language
from freshermeat.web.views.api.v1.common import url_prefix
blueprint_language = manager.create_api_blueprint(
Language, url_prefix=url_prefix, methods=["GET"]
)
|
kelvinongtoronto/numbers | letters.py | Python | artistic-2.0 | 650 | 0.010769 | print " A BBBBBB CCCC DDDDD EEEEEEE FFFFFFF GGGG H H IIIII JJJJJJ"
print " A A B B C C D D E F G G H H I J"
print " A A B B C D D E F G H H I J"
print "AAAAAAA BBBBBB C D D... | FFFFF G GGG HHHHHHH I J"
print "A A B B C D D E F G | G H H I J"
print "A A B B C C D D E F G G H H I J J"
print "A A BBBBBB CCCC DDDDD EEEEEEE F GGGG H H IIIII JJJJ"
|
tavisrudd/eventlet | eventlet/db_pool.py | Python | mit | 15,932 | 0.005649 | from collections import deque
import sys
import time
from eventlet.pools import Pool
from eventlet import timeout
from eventlet import greenthread
class ConnectTimeout(Exception):
pass
class BaseConnectionPool(Pool):
def __init__(self, db_module,
min_size = 0, max_size = 4,
... | "
try:
conn.close()
except (KeyboardInterrupt, SystemExit):
| raise
except AttributeError:
pass # conn is None, or junk
except:
if not quiet:
print "Connection.close raised: %s" % (sys.exc_info()[1])
def get(self):
conn = super(BaseConnectionPool, self).get()
# None is a flag value that means ... |
SophieBartmann/Faust-Bot | FaustBot/Modules/PrivMsgObserverPrototype.py | Python | gpl-3.0 | 744 | 0 | from FaustBot.Communication.Connection import Connection
from FaustBot.Modules.ModulePrototype import ModulePrototype
from FaustBot.Modules.ModuleType import ModuleType
class PrivMsgObserverPrototype(ModulePrototype):
"""
The Prototype of a Class who can react to every action
"""
@staticmethod
de... | sto be implemented by subclasses!")
@staticmethod
def get_module_types():
return [ModuleType.ON_MSG]
def __init__(self):
super().__init__()
def update_on_priv_msg(self, data, connection: Connection):
raise NotImplementedError("So | me module doesn't do anything")
|
FinancialSentimentAnalysis-team/Finanical-annual-reports-analysis-code | luowang/Data_Processing/AllPdfToTxt.py | Python | apache-2.0 | 2,612 | 0.012251 | from pdf2txt import pdfTotxt1, pdfTotxt2
import os
def AllPdftoTxt(stock_dir, dir, root_txt_path):
'''
function: translate all pdf file to txt file in stock_dir directory
stock_dir:the stock number list
dir: the root directory of all reports
root_txt_path: the target directory where the result txt... | reports/demo_68_txt/txt/'
if not os.path.exists(target_txt_dir):
os.mkdir(target_txt_dir)
for stock in os.listdir(root_txt | _path):
for year in os.listdir(root_txt_path+stock):
for type in os.listdir(root_txt_path+stock+'/'+y):
temp_root_dir=root_txt_path+stock+'/'+y+'/'+type
target_txt_path=target_txt_dir+stock+'_'+year+'_'+type+'_chairman_statement.txt'
MergeFile(temp_roo... |
mfem/PyMFEM | mfem/_ser/stable3d.py | Python | bsd-3-clause | 5,714 | 0.005425 | # This file was automatically generated by SWIG (http://www.swig.org).
# Version 4.0.2
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info as _swig_python_version_info
if _swig_python_version_info < (2, 7, 0):
raise Runtime... | _
_swig_new_instance_method = _stable3d.SWIG_PyInstanceMethod_New
_swig_new_static_method = _stable3d.SWIG_PyStaticMethod_New
def _swig_repr(self):
try:
strthis = "proxy of " + self.this.__repr__()
except __builtin__.Exception:
strthis = ""
return "<%s. | %s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)
def _swig_setattr_nondynamic_instance_variable(set):
def set_instance_attr(self, name, value):
if name == "thisown":
self.this.own(value)
elif name == "this":
set(self, name, value)
elif hasa... |
laijingtao/landlab | landlab/components/overland_flow/generate_overland_flow_kinwave.py | Python | mit | 7,019 | 0.004132 | # -*- coding: utf-8 -*-
"""
Landlab component for overland flow using the kinematic-wave approximation.
Created on Fri May 27 14:26:13 2016
@author: gtucker
"""
from landlab import Component
import numpy as np
class KinwaveOverlandFlowModel(Component):
"""
Calculate water flow over topography.
Lan... | Store grid and parameters and do unit conversion
self._grid = grid
self.precip = precip_rate / 3600000.0 # convert to m/s
self.precip_duration = precip_duration * 3600.0 # h->s
self.infilt = infilt_rate / 3600000.0 # convert to m/s
self.vel_coef = 1.0 / | roughness # do division now to save time
# Create fields...
# Elevation
if 'topographic__elevation' in grid.at_node:
self.elev = grid.at_node['topographic__elevation']
else:
self.elev = grid.add_zeros('node',
'topographi... |
LockScreen/Backend | venv/bin/rst2xetex.py | Python | mit | 826 | 0.001211 | #!/Users/Varun/Documents/GitHub/LockScreen/venv/bin/python
# $Id: rst2xetex.py 7038 2011-05-19 09:12:02Z milde $
# Author: Guenter Milde
# Copyright: This module has been placed in the public domain.
"""
A minimal front end to the Docutils Publisher, producing XeLaTeX source code.
"""
try:
import lo | cale
locale.setlocale(locale.LC_ALL, '')
except:
pass
from docutils.core import publish_cmdline
description = ('Generates XeLaTeX documents from standalone reStructuredText '
'sources. '
'Reads from <source> (default is stdin) and writes to '
'<destination> (defaul... | sh_cmdline(writer_name='xetex', description=description)
|
jonathanslenders/python-prompt-toolkit | examples/print-text/print-frame.py | Python | bsd-3-clause | 331 | 0 | #!/usr/bin/env python
""" |
Example usage of 'print_container', a tool to print
any layout in a non-interactive way.
"""
from prompt_toolkit.shortcuts import print_container
from prompt_toolkit.widgets import Frame, TextArea
print_container(
Frame(
TextArea(text="Hello world!\n"),
title="Stage: parse",
)
)
| |
eduherraiz/naniano | src/apconf/mixins/database.py | Python | gpl-2.0 | 800 | 0 | # -*- coding: utf-8 -*-
from apconf import Options
opts = Options()
def get(value, d | efault):
return opts.get(value, default, section='Database')
class DatabasesMixin(object):
def DATABASES(self):
engine = get('DATABASE_ENGINE', 'sqlite3')
if 'django.db.backends' in engine:
ENGINE = engine
else:
ENGINE = 'django.db.backends.' + engine
... | turn {
'default': {
'ENGINE': ENGINE,
'NAME': get('DATABASE_NAME', 'db.sqlite'),
'USER': get('DATABASE_USER', None),
'PASSWORD': get('DATABASE_PASSWORD', ''),
'HOST': get('DATABASE_HOST', ''),
'PORT': get('DATABA... |
kevinmcain/graal | mxtool/mx.py | Python | gpl-2.0 | 148,173 | 0.005851 | #!/usr/bin/python
#
# ----------------------------------------------------------------------------------------------------
#
# Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute... |
"""
A dependency is a library or project specified in a suite.
"""
class Dependency:
def __init__(self, suite, name):
self.name = name
self.suite = suite
def __str__(self):
return self.name
def __eq__(self, other):
return self.name == other.name
def __ne__(self, ... | def isLibrary(self):
return isinstance(self, Library)
def isProject(self):
return isinstance(self, Project)
class Project(Dependency):
def __init__(self, suite, name, srcDirs, deps, javaCompliance, workingSets, d):
Dependency.__init__(self, suite, name)
self.srcDirs = srcD... |
bokeh/bokeh | tests/unit/bokeh/client/test_states.py | Python | bsd-3-clause | 3,726 | 0.008588 | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2022, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-------------------------------------------------------------------... | AITING_FOR_REPLY() -> None:
s = bcs.WAITING_FOR_REPLY("reqid")
assert s.reply == None
assert s.reqid == "reqid"
c = MockConnection()
await s.run(c)
assert c.state == "_transition_to_disconnected"
assert s.reply is None
m = MockMessage()
c = MockConnection(to_pop=m)
await s.run(... | tion(to_pop=m)
await s.run(c)
assert c.state == "_next"
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# C... |
tardyp/buildbot | master/buildbot/db/steps.py | Python | gpl-2.0 | 7,224 | 0.000277 | # This file is part of Buildbot. Buildbot 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, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... | a buildstep.
# so threading.lock is used, as we are in the thread pool
if self.url_lock is None:
# this runs in reactor thread, so no race here..
self.url_lock = defer.DeferredLock()
def thd(conn):
tbl = self.db.model.steps
wc = (tbl.c.id == step... | ne()
if _racehook is not None:
_racehook()
urls = json.loads(row.urls_json)
url_item = dict(name=name, url=url)
if url_item not in urls:
urls.append(url_item)
q = tbl.update(whereclause=wc)
conn.execute(q, ... |
johnnygreco/hugs | scripts/runner.py | Python | mit | 6,693 | 0.004333 | """
Run hugs pipeline.
"""
from __future__ import division, print_function
import os, shutil
from time import time
import mpi4py.MPI as MPI
import schwimmbad
from hugs.pipeline import next_gen_search, find_lsbgs
from hugs.utils import PatchMeta
import hugs
def ingest_data(args):
"""
Write data to database w... | else:
synth_ids | = None
else:
synth_ids = None
patch_meta = PatchMeta(
x0 = pm.x0,
y0 = pm.y0,
small_frac = pm.small_frac,
cleaned_frac = pm.cleaned_frac,
bright_obj_frac = pm.bright_obj_frac,
good_data_frac = pm.good_data_frac
)
meta_data = [
config.run_... |
MGautier/Programacion | Python/salida_estandar.py | Python | mit | 1,308 | 0.009174 | #!/usr/bin/env python
print "Hola\n\n\tmundo"
#Para que la impresion se realizara en la misma linea tendriamos
# que colocar una coma al final de la sentencia
for i in range(3):
print i,
print "\n"
for i in range(3):
print i
#Diferencias entre , y el + en las cadenas: al utilizar las comas
#print introduce ... | 10s mundo" % "Hola" #Numero de caracteres de esa cadena
# en este caso | al ser de 4 establecera una separacion de 6 caracteres
# a mundo
from math import pi
print "%.4f" % pi # el .4f especifica el numero de decimales
print "%.4s" % "hola mundo" #especifica el tam maximo de la cadena parametro
|
eJRF/ejrf | questionnaire/features/locations_steps.py | Python | bsd-3-clause | 2,468 | 0.004457 | from lettuce import step, world
from questionnaire.features.pages.locations import ListRegionsPage, ListCountriesPage
from questionnaire.features.pages.step_utils import create_user_with_no_permissions, assign
from questionnaire.features.pages.users import LoginPage
from questionnaire.models.locations import Region, Co... | name="AFRO", organization=world.org)
world.uganda = Country.objects.create(name="Uganda", code="UGX")
world.uganda.regions.add(world.afro)
world.kenya = Country.objects.create(name="Kenya", code="KSX")
world.kenya.regions.add(world.afro)
@step(u | 'And I visit the list countries page in that region')
def and_i_visit_the_list_countries_page_in_that_region(step):
world.page = ListCountriesPage(world.browser, world.afro)
world.page.visit()
@step(u'Then I should see the list of countries in that region')
def then_i_should_see_the_list_of_countries_in_that_r... |
oliverlee/antlia | python/antlia/dtc.py | Python | bsd-2-clause | 2,572 | 0.000778 | # -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.cluste | r import KMeans
def di | st(a, b=None):
if b is None:
# assume 'a' is a pair
assert len(a) == 2
b = a[1]
a = a[0]
ax, ay = a
bx, by = b
return np.sqrt((ax - bx)**2 + (ay - by)**2)
def bcp(cluster_a, cluster_b):
min_dist = np.inf
pair = None
for a in cluster_a:
for b in clu... |
CroissanceCommune/autonomie | autonomie/alembic/versions/1_7_client_to_custom_3f746e901aa6.py | Python | gpl-3.0 | 3,301 | 0.003029 | """1.7 : Client to Customer
Revision ID: 3f746e901aa6
Revises: 2b29f533fdfc
Create Date: 2010-10-14 14:47:39.964827
"""
# revision identifiers, used by Alembic.
revision = '3f746e901aa6'
down_revision = '29299007fe7d'
from alembic import op
import sqlalchemy as sa
foreign_key_names = (
("invoice", "inv... | voice", "cancelinvoice_ibfk_4",),
("manualinv", "manualinv_ibfk_2",),
)
def remove_foreign_key(table, key):
q | uery = "alter table %s drop foreign key %s;" % (table, key)
try:
op.execute(query)
has_key = True
except:
import traceback
traceback.print_exc()
print "An error occured dropping foreign key"
has_key = False
return has_key
def upgrade():
from autonomie.al... |
jimboatarm/workload-automation | wlauto/workloads/applaunch/__init__.py | Python | apache-2.0 | 7,678 | 0.003126 | # Copyright 2015 ARM Limited
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | er.get(wlauto.common.android.resources.ApkFile(self.workload, uiauto=True))
if not self.workload.uiauto_file:
raise ResourceError('No UI automation Uiauto APK file found for worklo | ad {}.'.format(self.workload.name))
self.workload.device_uiauto_file = self.device.path.join(self.device.working_directory, os.path.basename(self.workload.uiauto_file))
if not self.workload.uiauto_package:
self.workload.uiauto_package = os.path.splitext(os.path.basename(self.workload.uiauto_... |
gaursagar/cclib | src/cclib/parser/logfileparser.py | Python | bsd-3-clause | 18,434 | 0.003743 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2017, the cclib development team
#
# This file is part of cclib (http://cclib.github.io) and is distributed under
# the terms of the BSD 3-Clause License.
"""Generic output file parser and related tools"""
import bz2
import fileinput
import gzip
import inspect
import io
impor... | thon2 and 3. Yet another reason to drop Python 2 soon!
try:
self.src.seek(pos, ref)
except:
if ref == 2:
| self.src.read()
else:
raise
if ref == 0:
self.pos = pos
if ref == 1:
self.pos += pos
if ref == 2 and hasattr(self, 'size'):
self.pos = self.size
def openlogfile(filename, object=None):
"""Return a file object g... |
lumidify/fahrenheit451 | EditorClasses.py | Python | gpl-2.0 | 37,759 | 0.005058 | import os
import sys
import math
import pygame
import loader
import importlib
import tkinter as tk
from QuadTree import *
from tkinter import ttk
from CONSTANTS import *
from pygame.locals import *
TILEWIDTH = 128
TILEHEIGHT = 64
def load_module(path):
spec = importlib.util.spec_from_file_location("module.name", ... | tile_dict = tile_dict["images"][0]
isox = (tile_index - line_index) * (TILEWIDTH // 2) + tile_dict["offset"][0]
isoy = (tile_index + line_index) * (TILEHEIGHT // 2) + tile_dict["offset"][1] + TILEHEIGHT // 2
self.screen.blit(tile_dict["... | self.layers[0])):
for x in range(len(self.layers[0][0])):
isox = (x - y) * (TILEWIDTH // 2) - 64
isoy = (x + y) * (TILEHEIGHT // 2)
self.screen.blit(self.default_tile, (isox + screen_offset[0], isoy + screen_offset[1]))
class BasicObstacle():
... |
tensorflow/privacy | tensorflow_privacy/privacy/dp_query/tree_range_query_test.py | Python | apache-2.0 | 7,555 | 0.006089 | # Copyright 2021, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | tree, tf.float32)
elif inner_query == 'distributed':
query = tree_range_qu | ery.TreeRangeSumQuery.build_distributed_discrete_gaussian_query(
10., 0., arity)
record = tf.constant([1, 0, 0, 0], dtype=tf.int32)
global_state = query.initial_global_state()
params = query.derive_sample_params(global_state)
preprocessed_record = query.preprocess_record(params, record)
... |
unitecoin-org/Unitecoin | contrib/bitrpc/bitrpc.py | Python | mit | 7,840 | 0.038138 | from jsonrpc import ServiceProxy
import sys
import string
# ===== BEGIN USER SETTINGS =====
# if you do not set these you will be prompted for a password for every command
rpcuser = ""
rpcpass = ""
# ====== END USER SETTINGS ======
if rpcpass == "":
access = ServiceProxy("http://127.0.0.1:9332")
else:
access = Ser... | d, optional):")
try:
print access.setgenerate(gen, cpus)
except:
print access.setgenerate(gen)
except:
print "\n---An error occurred---\n"
elif cmd == "settxfee":
try:
amt = raw_input("Amount:")
print access.settxfee(amt)
except:
print "\n---An error occurred---\n"
elif cmd == "stop":
try:
pri... | "validateaddress":
try:
addr = raw_input("Address: ")
print access.validateaddress(addr)
except:
print "\n---An error occurred---\n"
elif cmd == "walletpassphrase":
try:
pwd = raw_input("Enter wallet passphrase: ")
access.walletpassphrase(pwd, 60)
print "\n---Wallet unlocked---\n"
except:
print "\n--... |
Sookhaal/auri_maya_rigging_scripts | general/center_of_gravity.py | Python | mit | 5,456 | 0.002933 | """
:created: 2017-09
:author: Alex BROSSARD <[email protected]>
"""
from PySide2 import QtWidgets, QtCore
from pymel import core as pmc
from auri.auri_lib import AuriScriptView, AuriScriptController, AuriScriptModel, grpbox
from auri.scripts.Maya_Scripts import rig_lib
from auri.scripts.Maya_Scripts.rig_lib import ... | guide_name)
self.guide.setAttr("translate", (0, 7.5, 0))
self.guides_grp = self.group_guides(self.guide)
self.view.refresh_view()
pmc.select(cl=1)
def execute(self):
self.prebuild()
self.delete_e | xisting_objects()
self.connect_to_parent()
cog_shape = rig_lib.large_box_curve("{0}_CTRL_shape".format(self.model.module_name))
cog_ctrl = rig_lib.create_jnttype_ctrl(name="{0}_CTRL".format(self.model.module_name), shape=cog_shape,
drawstyle=2)
... |
yashchandak/GNN | Sample_Run/path_attn/Config.py | Python | mit | 4,900 | 0.008163 | import tensorflow as tf
import sys, os, shutil
class Config(object):
def __init__(self, args):
self.codebase_root_path = args.path
sys.path.insert(0, self.codebase_root_path)
#### Directory paths ####
# Folder name and project name is the same
self.project_name = args.pro... | self.improvement_threshold = args.pat_improve # a relative improvement of this much is considered significant
self.metrics = ['coverage', 'average_precision', 'ranking_loss', 'micro_f1', 'macro_f1', 'micro_precision',
'macro_precision', 'micro_recall', 'macro_recall', 'p@1', 'p@3', 'p@5',... | acy']
class Solver(object):
def __init__(self, args):
# Initial learning rate
self.learning_rate = args.lr
self.label_update_rate = args.lu
# optimizer
if args.opt == 'adam': self.opt = tf.train.AdamOptimizer
... |
kerneltask/micropython | tests/basics/async_with.py | Python | mit | 750 | 0.005333 | # test simple async with execution
class AContext:
async def __aenter__(self):
print('enter')
return 1
async def __aexit__(self, exc_type, exc, tb):
print('exit', exc_type, exc) |
async def f():
async with AContext():
print('body')
o = f()
try:
o.send(None)
except StopIteration:
print('finished')
async def g():
async with AContext() as ac:
print(ac)
raise ValueError('error')
o = g()
try:
o.send(None)
except ValueError:
print('ValueError')
# t... | nd(None)
except BaseException:
print('BaseException')
|
nop33/indico | indico/web/fields/base.py | Python | gpl-3.0 | 5,600 | 0.00125 | # This file is part of Indico.
# Copyright (C) 2002 - 2017 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... | lue if value is not None else ''
def _make_wtforms_field(self, field_cls, validators=None, **kwargs):
"""Util to instantiate a WTForms field.
This creates a field with the proper title, description and
if applicable a DataRequired validator.
|
:param field_cls: A WTForms field class
:param validators: A list of additional validators
:param kwargs: kwargs passed to the field constructor
"""
validators = list(validators) if validators is not None else []
if self.object.is_required:
validators.append(... |
angdraug/nova | nova/api/auth.py | Python | apache-2.0 | 6,074 | 0 | # Copyright (c) 2011 OpenStack Foundation
#
# 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 ... | stone.'),
cfg.BoolOpt('use_forwarded_for',
default=False,
help='Treat X-Forwarded-For as the canonical remote address. '
'Only enable this if you have a sanitizing proxy.'),
]
CONF = cfg.CONF
CONF.register_opts(auth_opts)
LOG = logging.getLogger(__name__)
def... | 1])
filters.reverse()
for filter in filters:
app = filter(app)
return app
def pipeline_factory(loader, global_conf, **local_conf):
"""A paste pipeline replica that keys off of auth_strategy."""
pipeline = local_conf[CONF.auth_strategy]
if not CONF.api_rate_limit:
limit_name = C... |
dsibournemouth/autoweka | scripts/launch_default_experiments.py | Python | gpl-3.0 | 782 | 0.001279 | import argparse
import os
from config import *
def main():
parser = argparse | .Argume | ntParser(prog=os.path.basename(__file__))
globals().update(load_config(parser))
parser.add_argument('--dataset', choices=datasets, required=False)
args = parser.parse_args()
# override default values
if args.dataset:
selected_datasets = [args.dataset]
else:
selected_datasets = ... |
AlexisEidelman/Til | til/tests/test_liam2.py | Python | gpl-3.0 | 1,074 | 0.007449 | # -*- coding: ut | f-8 -*-
import os
import pkg_resources
from liam2.simulation import Simulation
def test_liam2_demo_files():
liam2_demo_directory = os.path.join(
pkg_resources.get_distribution('liam2').location,
'..',
'tests',
'examples'
)
excluded_files = [
'demo_import.yml... |
if os.path.isfile(os.path.join(liam2_demo_directory, _file))
and _file.endswith('.yml')
and _file not in excluded_files]
print yaml_files
for yaml_file in yaml_files:
print yaml_file
simulation = Simulation.from_yaml(
yaml_file,
input_dir = os.pat... |
apitrace/apitrace | specs/wglenum.py | Python | mit | 9,086 | 0.00011 | ##########################################################################
#
# Copyright 2008-2011 VMware, Inc.
# All Rights Reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software withou... | IED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, | TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
##########################################################################/
"""WGL enum description"""
from .stdapi import *
WGLenum = FakeEnum(Int, [
"WGL_GPU_VENDOR_AMD", # 0x1F00
... |
endlessm/chromium-browser | native_client/src/trusted/service_runtime/linux/ld_bfd.py | Python | bsd-3-clause | 2,039 | 0.013242 | #!/usr/bin/python
# Copyright (c) 2011 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Wrapper for invoking the BFD loader
A simple script to invoke the bfd loader instead of gold.
This script is in a filename "ld... | mport sys
def PathTo(fname):
if fname[0] == os.pathsep:
return fname
for p in os.environ["PATH"].split(os.pathsep):
fpath = os.path.join(p, fname)
if os.path.exists(fpath):
return fpath
return fname
def GccPrintName(cxx_bin, what, switch, defresult):
popen = subprocess.Popen(cxx_bin + ' ' +... | shell=True,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE)
result, error = popen.communicate()
if popen.returncode != 0:
print("Could not find %s: %s" % (what, error))
return defresult
return result.strip()
def FindLDBFD(cxx_bin):
ld =... |
jeremiak/regulations-site | regulations/generator/versions.py | Python | cc0-1.0 | 1,918 | 0.000521 | from datetime import datetime
from regulations.generator import api_reader
from regulations.generator.layers.utils import convert_to_python
def fetch_regulations_and_future_versions():
""" Returns a dict for all the regulations in the API. The dict includes
lists of future versions for each regulation. """
... | else:
version['timeline'] = 'past'
for notice in client.notices(part)['results']:
notice = convert_to_python(notice)
for v in (v for v in versions
if v['by_date'] == notice['effective_on']):
v['notices'].append(notice)
for version in versions:
... | return versions
|
DiCarloLab-Delft/PycQED_py3 | pycqed/measurement/VNA_module.py | Python | mit | 12,353 | 0.003319 | import numpy as np
from pycqed.analysis import measurement_analysis as ma
from pycqed.analysis_v2 import measurement_analysis as ma2
from pycqed.measurement import sweep_functions as swf
from pycqed.measurement import detector_functions as det
MC_instr = None
VNA_instr = None
def acquire_single_linear_frequency_span... | span=None, nr_avg=1, sweep_mode='auto',
nbr_points=101, power=-20,
bandwidth=100, measure='S21',
options_dict=None):
"""
Acquires a single trace from the VNA.
Inputs:... | |
nathanaevitas/odoo | custom_addons/phaply/models.py | Python | agpl-3.0 | 1,552 | 0.011598 | # -*- coding: utf-8 -*-
from openerp import models, fields, api
class phaply(models.Model):
"""
This class will create a new table in DB with the same and replace the '.' with '_'
"""
_name = 'phaply.phaply'
name = fields.Char(string='Ten KH')
ngaysinh = fields.Date(string='Ngay sinh')
... | , comodel_name='phaply.nguon')
dv_thietke = fields.Boolean(string='Da co thiet ke')
dv_thicong = fields.Boolean(string='Da co thi cong')
dv_doitac = fields.Char(string='Doi tac' | )
dichvu = fields.Many2one(string='Dich vu', comodel_name='phaply.dichvu')
phutrach = fields.Many2one(string='Nguoi phu trach', comodel_name='hr.employee')
da_chot = fields.Boolean(string='Da chot')
class nguon(models.Model):
"""
Luu tru nguon khach hang
"""
_name = 'phaply.ng... |
fengjz1/eloipool-litecoin | networkserver.py | Python | agpl-3.0 | 11,206 | 0.041585 | # Eloipool - Python Bitcoin pool server
# Copyright (C) 2011-2013 Luke Dashjr <[email protected]>
#
# 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
# L... | self):
self.close()
def handle_write(self):
if self.wbuf is None:
# Socket was just closed by remote peer
return
bs = self.socket.send(self.wbuf)
self.wbuf = self.wbuf[bs:]
if not len(self.wbuf):
if self.closeme:
self.close()
return
self.se | rver.register_socket_m(self.fd, EPOLL_READ)
recv = asynchat.async_chat.recv
def close(self):
if self.wbuf:
self.closeme = True
return
if self.fd == -1:
# Already closed
return
try:
del self.server.connections[id(self)]
except:
pass
self.server.unregister_socket(self.fd)
self.changeTa... |
mxm/incubator-beam | sdks/python/apache_beam/testing/load_tests/co_group_by_key_test.py | Python | apache-2.0 | 7,004 | 0.004426 | #
# 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... | sMonitor(
project_name=metrics_project_id,
table=self.metrics_namespace,
dataset=metrics_dataset,
schema_map=measured_values
)
else:
logging.error('One or more of parameters for collecting metrics '
'are empty. Metrics will not be collected')
... | , element):
values = element[1]
inputs = values.get(INPUT_TAG)
co_inputs = values.get(CO_INPUT_TAG)
for i in inputs:
yield i
for i in co_inputs:
yield i
def testCoGroupByKey(self):
with self.pipeline as p:
pc1 = (p
| 'Read ' + INPUT_TAG >> beam.io.... |
ONSdigital/ras-frontstage | frontstage/common/cryptographer.py | Python | mit | 2,059 | 0.001457 | from base64 import b64decode, b64encode
from hashlib import sha256
from Crypto import Random
from Crypto.Cipher import AES
from frontstage import app
class Cryptographer:
"""Manage the encryption and decryption of random byte strings"""
def __init__(self):
"""
| S | et up the encryption key, this will come from an .ini file or from
an environment variable. Change the block size to suit the data supplied
or performance required.
:param key: The encryption key to use when encrypting the data
"""
key = app.config["SECRET_KEY"]
self._ke... |
gnychis/grforwarder | gr-audio/examples/python/dial_tone_daemon.py | Python | gpl-3.0 | 2,052 | 0.00731 | #!/usr/bin/env python
#
# Copyright 2004,2005,2007,2008 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GN | U Radio 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, or (at your option)
# any later version.
#
# GNU Radio is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; ... | AR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
from gnuradio import gr, ... |
liuhll/BlogAndArticle | Notes/Python/src/exercise/string_repalce_by_resub.py | Python | mit | 537 | 0.02457 | # -*- coding:utf-8 -*-
from re import sub
f | rom itertools import islice
'''
ε¦δ½θ°ζ΄ε符串ηζζ¬ζ ΌεΌ
'''
# ε°ζ₯εΏζδ»ΆδΈηζ₯ζζ ΌεΌθ½¬εδΈΊηΎε½ζ₯ζζ ΌεΌmm/dd/yyyy
# δ½Ώη¨ζ£ε葨达εΌζ¨‘εδΈηsubε½ζ°θΏθ‘ζΏζ’ε符串
with open("./log.log","r") as f:
for line in islice(f,0,None):
#print sub("(\d{4})-(\d{2})-(\d{2})",r"\2/\3/\1",line)
# ε―δ»₯δΈΊζ―δΈͺεΉι
η»θ΅·δΈδΈͺε«ε
print sub("(?P<year>\d{4})-(?P<month>\d{2})-(?P<d... | /\g<day>/\g<>",line)
|
CodeforChemnitz/TheaterWecker | scraper/app.py | Python | mit | 3,322 | 0.00301 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import datetime
import calendar
import json
import locale
import re
import requests
from bs4 import BeautifulSoup
# Use German month names
locale.setlocale(locale.LC_ALL, 'de_DE.utf8')
URL = "http://www.theater-chemnitz.de/spielplan/repertoire"
BASE_URL = "http://www.t... | li',
'august',
'september',
'oktober',
'november',
'dezember'
]
def get_plays(year, month):
plan = requests.get("{}/{}/{:02d}/".format(URL, year, month))
if plan.status_code != 200:
logger.error('got non-200 return code while scraping', exc_info=True)
return []
soup = B... | :
date = block_top.find("div", class_="cc_news_date")
if date:
day = int(date.find(class_="cc_day").get_text().strip('.'))
play = {
"month": month,
"day": day,
"year": year
}
time_raw = date.find(class_="cc_t... |
caesar2164/edx-platform | scripts/migrate_score_override.py | Python | agpl-3.0 | 9,522 | 0.002941 | #!/usr/bin/env python
"""
Script to update old score overrides to match upstream overrides.
"""
import datetime
import itertools
import os
import django
from django.db import transaction
from opaque_keys.edx.keys import CourseKey
from openedx.core.djangoapps.monkey_patch import django_db_models_options
def main():
... | eted_at = score.created_at
staff_step.submitter_completed_at = score.created_at
staff_step.save()
except AssessmentWorkflowStep.DoesNotExist:
for step in workflow.steps.all():
step.assessment_completed_at = score.created... | step.save()
workflow.steps.add(
AssessmentWorkflowStep(
name='staff',
order_num=0,
assessment_compl |
google-research/mint | mint/ctl/single_task_evaluator_test.py | Python | apache-2.0 | 2,149 | 0.001396 | # 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 in writing... | leTaskTrainer(
train_ds,
label_key='label',
model=model,
loss_fn=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
optimizer=tf.keras.optimizers.SGD(
learning_rate=tf.keras.optimizers.schedules.PiecewiseConstantDecay(
[0], [0.01, 0.01]))... | calAccuracy()])
controller = orbit.Controller(
trainer=trainer,
evaluator=evaluator,
steps_per_loop=100,
global_step=trainer.optimizer.iterations)
controller.train(train_ds.cardinality().numpy())
controller.evaluate()
accuracy = evaluator.metrics[0].result().numpy()
... |
samdroid-apps/something-for-reddit | redditisgtk/main.py | Python | gpl-3.0 | 14,799 | 0.000609 | # Copyright 2016 Sam Parkinson <[email protected]>
#
# This file is part of Something for Reddit.
#
# Something for Reddit 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 ... | r import get_read_controller
from redditisgtk.identity import IdentityController
from r | edditisgtk.identitybutton import IdentityButton
from redditisgtk.comments import CommentsView
from redditisgtk.settings import get_settings, show_settings
from redditisgtk import webviews
VIEW_WEB = 0
VIEW_COMMENTS = 1
class RedditWindow(Gtk.Window):
def __init__(
self,
ic: IdentityCont... |
SarahBA/b2share | b2share/modules/records/errors.py | Python | gpl-2.0 | 2,455 | 0.001222 | # -*- coding: utf-8 -*-
#
# This file is part of EUDAT B2Share.
# Copyright (C) 2016 CERN.
#
# B2Share is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any... | cord update changes what is considered
immutable record data."""
class EpicPIDError(Exception):
"""Raise when a record has no community."""
class UnknownRecordType(B2ShareRecordsError):
"""Error raised when a record type cannot be determined.
The two main record types are "published record" and ... | enticated users can search for drafts.'
def register_error_handlers(app):
@app.errorhandler(ValidationError)
def handle_validation_error(err):
field = '/'.join([str(x) for x in err.path])
if err.validator == 'required' or err.validator == 'additionalProperties':
try:
... |
Xarthisius/girder | pytest_girder/pytest_girder/assertions.py | Python | apache-2.0 | 1,022 | 0 | import json
from .utils import getResponseBody
def assertStatus(response, code):
"""
Call this to assert that a given HTTP status code was returned.
:param response: | The response object.
:param code: The status code.
:type code: int or str
"""
# Hide tracebacks for this function within pytest
__tracebackhide__ = True
code = str(code)
if not response.output_status.startswith(code.encode()):
msg = 'Response status was %s, no | t %s.' % (response.output_status,
code)
if hasattr(response, 'json'):
msg += ' Response body was:\n%s' % json.dumps(
response.json, sort_keys=True, indent=4,
separators=(',', ': '))
else:
msg += '... |
Goldcap/django-operis | operis/management/commands/generate-api.py | Python | mit | 11,299 | 0.014249 | import datetime
import sys
import os.path
import pprint
from inspect import getmembers, isclass
from collections import defaultdict
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.contrib.contenttypes.models import Content... | index_list = ['id']
index_converted = ''
fields = ['id']
fields_converted = ''
filter_fields = ['id']
filter_fields_conv... |
singular = None
plural = None
fixture_seed = 1
if hasattr(obj._meta ,"verbose_name"):
singular = str(obj._meta.ver... |
hombin/kickstarter | KickStarter/middlewares.py | Python | mit | 1,909 | 0 | # -*- coding: utf-8 -*-
# Define here the models for your spider middleware
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/spider-middleware.html
from scrapy import signals
class KickstarterSpiderMiddleware(object):
# Not all methods need to be define | d. If a method is not defined,
# scrapy acts as if the spider middleware does not modify the
# passed objects.
@classmethod
def from_crawler(cls, crawler):
# This method is used by Scrapy to create your spiders.
s = cls()
crawler.signals.connect(s.spider_opened, signal=signals.s... | each response that goes through the spider
# middleware and into the spider.
# Should return None or raise an exception.
return None
def process_spider_output(self, response, result, spider):
# Called with the results returned from the Spider, after
# it has processed the r... |
zlatiadam/PyPortfolio | pyportfolio/__init__.py | Python | gpl-2.0 | 863 | 0.008111 | # -*- coding: utf-8 -*-
"""
Created on Sat Nov 28 21:34:36 2015
@author: Zlati
"""
from .portfolios.offline.equal_weights_portfoli | o import EqualWeightsPor | tfolio
from .portfolios.offline.tangency_portfolio import TangencyPortfolio
from .portfolios.offline.minimum_variance_portfolio import MinimumVariancePortfolio
from .portfolios.offline.smallest_eigenvalue_portfolio import SmallestEigenvaluePortfolio
from .portfolios.offline.mean_variance_portfolio import MeanVariancePo... |
kiddingmu/leetcode | 43_valid_palindrome/valid_palindrome.py | Python | gpl-2.0 | 509 | 0.007859 | class Solution:
# @param s, a string
# @return a boolean
def isPalindrome(self, s):
s = [x.lower() for x in s if x.isalpha() or x.isdigit()]
size = len(s)
for i in xrange(size):
if s[i] != s[size-1-i]:
ret | urn False
return True
if __name__ == "__main__":
solution = Solution()
#s = "A man, a plan, a canal: Panama" |
#s = "race a car"
#s = "1a2"
s = "A man a plan, 11a canal: Panama"
print solution.isPalindrome(s)
|
madduck/reclass | reclass/constants.py | Python | artistic-2.0 | 444 | 0.002268 | #
# -*- coding: utf-8 -*-
#
# Thi | s file is part of reclass (http://github.com/madduck/reclass)
#
# Copyright Β© 2007β14 martin f. krafft <[email protected]>
# Released under the terms of the Artistic Licence 2.0
#
class _Constant(object):
def __init__(self, displayname):
self._repr = display | name
__str__ = __repr__ = lambda self: self._repr
MODE_NODEINFO = _Constant('NODEINFO')
MODE_INVENTORY = _Constant('INVENTORY')
|
TimothyXu/nurdCase | nurdCase.py | Python | gpl-3.0 | 2,385 | 0.012998 | #!/usr/bin/env python3
#######################################################################
#Copyright (C) 2015 Timothy Xu #
# #
#This program is free software: you can redistribute it and/or modify #
#it under... | py -s(can)\nWrite to \'converted\' in cwd: cat /path/to/file | /path/to/this/script | .py -w(rite)')
else:
if mode == '-s' or mode == '-scan':
scan()
if mode == '-w' or mode == '-write':
write() |
chrsbats/connorav | connorav/__init__.py | Python | mit | 138 | 0.007246 | from __future__ import absolute_import
from .distribution import MSSKDistribution
from .correl_rv import CorrelatedNo | nNormal | RandomVariates |
aluminiumgeek/horo-modules | test/test.py | Python | gpl-3.0 | 370 | 0.002703 | # test.py (c) Mikhail Mezyakov <[email protected]>
# Released under the | GNU GPL v.3
#
# | Module sends "success" message to user on a channel
def horo(channel, user, args):
"""Send "success" message if everything is ok"""
return u'PRIVMSG {channel} :{user}: success'.format(channel=channel,
user=user)
|
Stargrazer82301/CAAPR | CAAPR/CAAPR_AstroMagic/PTS/pts/modeling/analysis/heating/cell.py | Python | mit | 30,102 | 0.00485 | #!/usr/bin/env python
# -*- coding: utf8 -*-
# *****************************************************************
# ** PTS -- Python Toolkit for working with SKIRT **
# ** Β© Astronomical Observatory, Ghent University **
# *****************************************************************
##... | z coordinate of cell center (pc)
# column 4: Absorbed bolometric luminosity (W)
contribution_tables = dict()
# Loop over the different contributions
for contribution in | self.contributions:
# Skip the simulation of the total unevolved (young + ionizing) stellar population
if contribution == "unevolved": continue
# Debugging
log.debug("Loading the SKIRT absorption table for the simulation of the " + contribution + " stellar population ..... |
ActiveState/code | recipes/Python/498261_Deeply_applying_str_across/recipe-498261.py | Python | mit | 7,274 | 0.004812 | """Utilities for handling deep str()ingification.
Danny Yoo ([email protected])
Casual Usage:
from deepstr import deep_str
print deep_str(["hello", "world"])
Very unusual usage:
import deepstr
import xml.sax.saxutils
def handle_list(obj, deep_str):
if isinstance(obj, lis... | "
return self.deepstr(obj, {})
def deepstr(self, obj, seen):
## Notes: this code is a little trickier than I'd like, but
## I don't see a good way of simplifying it yet. Subtle parts
## include the construction of substructure_deepstr, and | use
## of a fresh dictionary in 'new_seen'.
if id(obj) in seen:
## TRICKY CODE: the recursive function is taking in a
## stringifier whose 'seen' dictionary is empty.
def fresh_deepstr(sub_obj):
return self.deepstr(sub_obj, {})
return self.... |
cstipkovic/spidermonkey-research | testing/mozharness/configs/web_platform_tests/prod_config_windows.py | Python | mpl-2.0 | 1,629 | 0.001842 | # ***** BEGIN LICENSE BLOCK *****
# 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/.
# ***** END LICENSE BLOCK *****
# This is a template config file for web-platfor... | prefs-root=%(test_path)s/prefs",
"--processes=1",
"--config=%(test_path)s/wptrunner.ini",
"--ca-cert-path=%(test_path)s/certs/cacert.pem",
"--host-key-path=%(test_path)s/certs/web-platform.test.key",
"--host-cer | t-path=%(test_path)s/certs/web-platform.test.pem",
"--certutil-binary=%(test_install_path)s/bin/certutil",
],
"exes": {
'python': sys.executable,
'virtualenv': [sys.executable, 'c:/mozilla-build/buildbotve/virtualenv.py'],
'hg': 'c:/mozilla-build/hg/hg',
'mozinst... |
sandordargo/family-tree | tests/test_horizontal_sorter.py | Python | mit | 14,566 | 0.004668 | import unittest
from tree import horizontal_sorter
from tree import person_node
class TestHorizontalSorter(unittest.TestCase):
def setUp(self):
self.edges = {}
@staticmethod
def only_even_numbers_in_dict(dict_to_check):
for key in dict_to_check:
if dict_to_check[key] % 2 != 0:... | person_horizontal_position_dict = {'1': 2, '3': 3, '2': 2, '5': 1, '4': 3}
person_nodes = self.build_person_nodes_dict(person_horizontal_position_dict)
sorter = horizontal_sorter.HorizontalSorter(person_level_dict, self.edges, person_nodes)
sorter.person_horizontal_positi | on_dict = person_horizontal_position_dict
sorter.position_person_dict = position_person_dict
sorter.move('5', 2)
expected_position_person_dict = {1: [], 2: ['1', '2'], 3: ['4', '5'], 5: ['3']}
expected_person_horizontal_position_dict = {'1': 2, '3': 5, '2': 2, '5': 3, '4': 3}
s... |
google-research/google-research | cache_replacement/policy_learning/cache/traces/train_test_split.py | Python | apache-2.0 | 4,756 | 0.012616 | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | , default=16,
help="Associativity of the cache.")
parser.add_argument(
"-c", "--capacity", default=2 * 1024 * 1024,
help="Capacity of the cache.")
parser.add_argument(
"-l", "--cache_line_size", default=64,
help="Size of the cache lines in bytes.")
parser.add_argument(
"-b", "-... | and test.csv contain a number"
" of accesses that is a multiple of this. Use 1 to avoid this."))
args = parser.parse_args()
PREFIX = "_filter_traces"
output_filenames = ["train.csv", "valid.csv", "test.csv", "all.csv"]
output_filenames += [PREFIX + str(i) for i in range(10)]
for output_filename ... |
CyriusG/frontpage_backend | frontpage_backend/settings.template.py | Python | mit | 4,611 | 0.001301 | """
Django settings for frontpage_backend project.
Generated by 'django-admin startproject' using Django 1.10.3.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
... | = '127.0.0.1'
PLEX_PORT = '32400'
# Couchpotato settings
COUCHPOTATO_HOST = '127.0.0.1'
COUCHPOTATO | _PORT = '5050'
COUCHPOTATO_API_KEY = ''
# Sonarr settings
SONARR_HOST = '127.0.0.1'
SONARR_PORT = '8989'
SONARR_API_KEY = ''
SONARR_PATH = ''
SONARR_QUALITY = 1
# CORS Settings
CORS_ORIGIN_ALLOW_ALL = False
# Change this to whatever domain the cross origin requests originate from.
CORS_ORIGIN_WHITELIST = (
'local... |
TheAlgorithms/Python | conversions/decimal_to_octal.py | Python | mit | 1,211 | 0 | """Convert a Decimal Number to an Octal Number."""
import math
# Modified from:
# https://github.com/TheAlgorithms/Javascript/blob/master/Conversions/DecimalToOctal.js
def decimal_to_octal(num: int) -> str:
"""Convert a Decimal Number to an Octal Number.
>>> all(decimal_to_octal(i) == oct(i) for i
... ... | ounter = 0
while num > 0:
remainder = num % 8
octal = octal + (remainder * math.floor(math.pow(10, counter)))
counter += 1
num = math.floor(num / 8) # basically /= 8 without remainder if any
# This formatting removes trailing '.0' from `octal`.
return f"0o{int(octal)}"
... | numbers."""
print("\n2 in octal is:")
print(decimal_to_octal(2)) # = 2
print("\n8 in octal is:")
print(decimal_to_octal(8)) # = 10
print("\n65 in octal is:")
print(decimal_to_octal(65)) # = 101
print("\n216 in octal is:")
print(decimal_to_octal(216)) # = 330
print("\n512 in octal... |
opencord/voltha | voltha/extensions/alarms/olt/olt_los_alarm.py | Python | apache-2.0 | 1,492 | 0.002681 | # Copyright 2017-present Adtran, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this f | ile except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES | OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from voltha.protos.events_pb2 import AlarmEventType, AlarmEventSeverity, AlarmEventCategory
from voltha.extensions.alarms.adapter_alarms import AlarmBase
class... |
vincepandolfo/django | django/db/models/options.py | Python | bsd-3-clause | 29,986 | 0.001301 | from __future__ import unicode_literals
from bisect import bisect
from collections import OrderedDict, defaultdict
from itertools import chain
from django.apps import apps
from django.conf import settings
from django.core.exceptions import FieldDoesNotExist
from django.db import connections
from django.db.models.fiel... | (concrete or abstract base classes). `managers`
# keeps a list of 3-tuples of the form:
# (creation_counter, instance, abstract | (=True))
self.managers = []
# List of all lookups defined in ForeignKey 'limit_choices_to' options
# from *other* models. Needed for some admin checks. Internal use only.
self.related_fkey_lookups = []
# A custom app registry to use, if you're making a separate model set.
... |
eykomm/ctf_prep | scripts/tcp_client.py | Python | apache-2.0 | 246 | 0.028455 | import socket
target_host=""
target_port=
client=socke | t.socket(socket.AF_INET,socket.SOCK_STREAM)
client.connec | t((target_host,target_port))
client.send("GET / HTTP/1.1\r\nHost: google.com\r\n\r\n")
response=client.recv(4096)
print response |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.