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
Suwmlee/XX-Net
gae_proxy/local/scan_ip_log.py
Python
bsd-2-clause
1,921
0.003644
import os import shutil import time from xlog import getLogger xlog = getLogger("gae_proxy") from .config import config class Scan_ip_lo
g(): max_lines_per_log_file = 3000 def __init__(self): self.log_path = os.path.join(config.DATA_PATH,
"scan_ip.log") self.open_log() def get_log_content(self): if not os.path.isfile(self.log_path): return "" with open(self.log_path, "r") as fd: content = fd.read() return content def open_log(self): if os.path.isfile(self.log_path): ...
jimga150/HealthNet
HealthNet/messaging/admin.py
Python
mit
114
0
from django.contri
b import admin from .models import * # Register your models here. admin.site.regist
er(Message)
waprin/gcloud-python
gcloud/logging/handlers/handlers.py
Python
apache-2.0
4,411
0
# Copyright 2016 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 a...
:meth`gcloud.logging.handlers.transports.base.Transport.send` Defaults to BackgroundThread
Transport. The other option is SyncTransport. Example: .. doctest:: import gcloud.logging from gcloud.logging.handlers import CloudLoggingHandler client = gcloud.logging.Client() handler = CloudLoggingHandler(client) cloud_logger = logging.getLo...
angdraug/nova
nova/tests/api/openstack/compute/plugins/v3/test_pci.py
Python
apache-2.0
10,171
0
# Copyright 2013 Intel Corp. # # 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...
self.fake_objs = dict(hypervisors=[ dict(id=1, service=dict(id=1, host="compute1"), hypervisor_type="xen", hypervisor_version=3, hypervisor_hostname="hyper1")]) self.fake_obj = dict(hypervisor=dict( id=1, s...
ervisor_version=3, hypervisor_hostname="hyper1")) def test_show(self): def fake_get_db_compute_node(id): fake_compute_node['pci_stats'] = jsonutils.dumps( fake_compute_node['pci_stats']) return fake_compute_node req = fakes.HTTPRequestV3.blank('/...
claesenm/optunity-benchmark
benchmarks/optunity/covtype-2.py
Python
gpl-3.0
1,022
0.004892
import optunity import numpy as np import hpolib_generator as hpo import cloudpickle as pickle import sklearn.datasets import random positive_digit = 2 name='covtype-%d' % posit
ive_digit num_folds=5 budget = 150 npos = 500 nneg = 1000 search={'logC': [-8, 1], 'logGamma': [-8, 1]} covtype = sklearn.datasets.fetch_covtype() n = covtype.data.shape[0] positive_idx = [i for i in range(n) if covtype.target[i] == positive_digit] negative_idx = [i for i in range(n) if not covtype.target[i] == pos...
data[positive_idx + negative_idx, ...] data = original_data # + 10 * np.random.randn(original_data.shape[0], original_data.shape[1]) labels = [True] * len(positive_idx) + [False] * len(negative_idx) objfun = hpo.make_svm_objfun(data, labels, num_folds) hpo_search = hpo.svm_search_space(**search) hpo.setup_hpolib(hpo....
gale320/newfies-dialer
newfies/dialer_cdr/tasks.py
Python
mpl-2.0
26,987
0.004002
# # Newfies-Dialer License # http://www.newfies-dialer.org # # 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/. # # Copyright (C) 2011-2014 Star2Billing S.L. # # The Initia...
if event_name == 'BACKGROUND_JOB': #hangup cause come from body hangup_cause = body[5:] if hangup_cause == '': hangup_cause = body[5:] request_uuid = job_uuid opt_hangup_cause = hangup_cause debug_query(22) try: if callrequest_id == 0: callrequest = ...
) \ .get(request_uuid=request_uuid.strip(' \t\n\r')) else: #mainly coming here callrequest = Callrequest.objects \ .select_related('aleg_gateway', 'subscriber', 'campaign') \ .get(id=callrequest_id) except: logger.error("Cannot ...
Jasonmk47/OpenWPM
automation/DeployBrowsers/deploy_firefox.py
Python
gpl-3.0
6,296
0.004924
from ..MPLogger import loggingclient from ..Commands.profile_commands import load_profile import configure_firefox from selenium.webdriver.firefox.firefox_binary import FirefoxBinary from selenium import webdriver from pyvirtualdisplay import Display import shutil import os import random DEFAULT_SCREEN_RES = (1366, ...
file_path = fp.path + '/' status_queue.put(('STATUS','Profile Created',browser_profile_path)) profile_settings = None # Imported browser settings if browser_params['profile_tar'] and not crash_recovery: logger.debug("BROWSER %i: Loading initial browser profile from: %s" % (browser_params['crawl_id...
browser_params['profile_tar'], load_flash=browser_params['disable_flash'] is False) elif browser_params['profile_tar']: logger.debug("BROWSER %i: Loading recovered browser profile from: %s" % (browser_params['crawl_id'], browser_params...
dbdd4us/compose
compose/volume.py
Python
apache-2.0
4,745
0.000211
from __future__ import absolute_import from __future__ import unicode_literals import logging from docker.errors import NotFound from .config import ConfigurationError log = logging.getLogger(__name__) class Volume(object): def __init__(self, client, project, name, driver=None, driver_opts=None, ...
s def create(self): return self.client.create_volume( self.full_name, self.driver, self.driver_opts, labels=self.labels ) def remove(self): if self.external: log.info("Volume %s is external, skipping", self.full_name) return log.info("Removin...
t.inspect_volume(self.full_name) def exists(self): try: self.inspect() except NotFound: return False return True @property def external(self): return bool(self.external_name) @property def full_name(self): if self.external_name: ...
syscoin/syscoin
test/functional/feature_minchainwork.py
Python
mit
3,953
0.003036
#!/usr/bin/env python3 # Copyright (c) 2017-2021 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 logic for setting nMinimumChainWork on command line. Nodes don't consider themselves out of "init...
num_blocks_to_generate = int((self.node_min_work[1] - starting_chain_work) / REGTEST_WORK_PER_BLOCK) self.log.info(f"Generating {num_blocks_to_generate} blocks on node0") hashes = self.generate(self.nodes[0], num_blocks_to_generate, sync_fun=self.no_op) self.log.info(f"Node0 current chain ...
])['chainwork']}") # Sleep a few seconds and verify that node2 didn't get any new blocks # or headers. We sleep, rather than sync_blocks(node0, node1) because # it's reasonable either way for node1 to get the blocks, or not get # them (since they're below node1's minchainwork). ...
TheChymera/matrix2latex
matrix2latex/__init__.py
Python
gpl-3.0
1,122
0.002674
"""This file is part of matrix2latex. matrix2latex 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. matrix2latex is distributed in the hope ...
copy of the GNU General Public License along with matrix2latex. If not, see <http://www.gnu.org/licenses/>. """ __all__ = ['matrix2latex'] try: from matrix2latex import matrix2latex except ImportError: # Really ugly hack to please python3 import mechanisms import sys, os SCRIPT_DIR = os.path.dirname(...
matrix2latex = matrix2latex.matrix2latex del sys.path[0] # NOTE: ensure that matrix2latex does not change sys.path
hollowpoint/hollowpoint
hpt/hpt/wsgi.py
Python
apache-2.0
382
0
""" WSGI config for hpt project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.se
tdefault("DJANGO_SETTINGS_MODULE", "hpt.settings") application = get_wsgi_application()
kennym/itools
workflow/__init__.py
Python
gpl-3.0
870
0
# -*- coding: UTF-8 -*- # Copyright (C) 2007 Juan David Ibáñez Palomar <jdavid@itaapy.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option...
eral Public License for more details. # # You should have received a copy of the GNU General Public License # along with
this program. If not, see <http://www.gnu.org/licenses/>. # Import from itools from workflow import WorkflowError, Workflow, WorkflowAware __all__ = ['WorkflowError', 'Workflow', 'WorkflowAware']
flan/puukusoft-pyrc
pyrc_irc_abstract/irc_server.py
Python
gpl-3.0
71,250
0.041614
# -*- coding: utf-8 -*- """ PyRC module: pyrc_irc_abstract.irc_server Purpose ======= Establish and maintain a connection to an IRC server, generating events as they occur, and sending data as required. Legal ===== All code, unless otherwise indicated, is original, and subject to the terms of the GPLv2, which is...
:", 1) if len(channel_data) > 1: self._channel_manager.addChannel(channel_data[0], channel_data[1]) else: self._channel_manager.ad
dChannel(channel_data[0]) self._connect(False) def _connect(self, reconnection): """ This function handles the actual process of connecting to a server; it should only be called internally, first through connect(), and then by reconnect() all subsequent times. On an error, this function's thread will...
bitmazk/django-multilingual-tags
multilingual_tags/forms/mixins.py
Python
mit
5,178
0
"""Form mixins for the ``multilingual_tags`` app.""" from django import forms from django.forms.utils import ErrorList from django.contrib.contenttypes.models import ContentType from django.utils.text import slugify from django.utils.translation import get_language, ugettext_lazy as _ from .. import models class Tag...
tag=tag, content_type=self._instance_ctype, object_id=self.instance.id,
) ) else: taggeditem = models.TaggedItem( tag=tag, content_type=self._instance_ctype) self._taggeditems.append(taggeditem) if max_tags an...
Mikrobit/uwsgi.it
uwsgi_it_api/uwsgi_it_api/views_metrics.py
Python
mit
7,226
0.010518
from django.http import HttpResponseForbidden from django.core.cache import get_cache from uwsgi_it_api.config import UWSGI_IT_BASE_UID, UWSGI_IT_METRICS_CACHE from uwsgi_it_api.decorators import need_basicauth from uwsgi_it_api.utils import spit_json import datetime def metrics_container_do(request, container, qs, ...
= [] for m in qs.filter(year=year,month=month,day=day): j_list.append('{ "container": %d, "metrics": %s }' % (m.container.uid, m.json))
j = '[' + ','.join(j_list) + ']' cache.set("%s_%d_%d_%d_%d" % (prefix, domain.id, year, month, day ), j, expires) except: import sys print sys.exc_info() try: j_list = [] for m in qs.filter(year=year,month=month,day=day): j_list.append('{...
j08lue/poppy
scripts/save_regavg_timeseries.py
Python
gpl-2.0
2,149
0.009307
#!/usr/bin/env python from __future__ import print_function import numpy as np import argparse import glob import netCDF4 import poppy.metrics import poppy.grid import meta def _get_grid_cell_area(fname, grid, lonlim, latlim): with netCDF4.Dataset(fname) as ds: mask = poppy.grid.get_mask_lonlat(ds, lon...
ic == 'mean': reducefunc = _weightedmean elif args.metric == 'integral': reducefunc = _integral ts = poppy.metrics.get_timeseries( files,
varn=args.varn, grid=args.grid, reducefunc=reducefunc, **meta.regionlims[args.region]) ts.to_hdf(args.outfile, key='{0.varn}_{0.region}'.format(args), mode='w', format='table') print('Data saved to {}'.format(args.outfile))
aburrell/davitpy
davitpy/pydarn/plotting/fan.py
Python
gpl-3.0
29,354
0.000954
# -*- coding: utf-8 -*- # Copyright (C) 2012 VT SuperDARN Lab # Full license can be found in LICENSE.txt # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # ...
e,tFreqBands=[[10000,11000],[]]
) """ from davitpy import pydarn from davitpy import gme import datetime as dt import pickle from matplotlib.backends.backend_pdf import PdfPages import davitpy.models.aacgm as aacgm # Is this leftover from a debugging point? # Not sure where os is needed here. import os im...
Akrog/project-euler
common/fibonacci.py
Python
mit
101
0.029703
#/usr/bin/env python def fib(): a,b = 1, 1 whi
le True: yiel
d a a,b = b, a+b
houssine78/addons
res_users_case_insensitive/models/res_users.py
Python
agpl-3.0
1,300
0
# -*- coding: utf-8 -*- # © 2015-TODAY LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openerp import models, api, fields class ResUsers(models.Model): _inherit = 'res.users' login = fields.Char( 'Login', size=64, required=True, help='Use...
vals['login'] = vals.get('login', '').lower() return super(ResUsers, self).create(vals) @api.multi def write(self, vals, ): ''' Overload write to lowercase login ''' if vals.get('login'): vals['login'] =
vals['login'].lower() return super(ResUsers, self).write(vals)
FireCARES/harvester
setup.py
Python
gpl-2.0
2,346
0.000426
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup import re import os from setuptools import find_packages name = 'firecares-harvester' package = 'harvester' description = 'FireCARES Harvester' url = 'https://github.com/FireCARES/harvester' author = 'Prominent Edge' author_email = 'contact@pr...
walk(package) if not os.path.exists(os.path.join(dirpath, '__init__.py'))] f
ilepaths = [] for base, filenames in walk: filepaths.extend([os.path.join(base, filename) for filename in filenames]) return {package: filepaths} setup( name=name, version=get_version(package), url=url, license=license, description=description, author=...
YinongLong/scikit-learn
sklearn/manifold/setup.py
Python
bsd-3-clause
1,279
0.000782
import os from os.path import join import numpy from numpy.distutils.misc_util import Configuration from sklearn._build_utils import get_blas_info def configuration(parent_package="", top_path=None): config = Configuration("manifold", parent_package, top_path) libraries = [] if os.name == 'posix': ...
numpy.get_include()], libraries=libraries, extra_compile_args=["-O3"]) cblas_libs, blas_info = get_blas_in
fo() eca = blas_info.pop('extra_compile_args', []) eca.append("-O4") config.add_extension("_barnes_hut_tsne", libraries=cblas_libs, sources=["_barnes_hut_tsne.c"], include_dirs=[join('..', 'src', 'cblas'), ...
zofuthan/edx-platform
lms/djangoapps/lti_provider/outcomes.py
Python
agpl-3.0
9,222
0.000867
""" Helper functions for managing interactions with the LTI outcomes service defined in LTI v1.1. """ from hashlib import sha1 from base64 import b64encode import logging import uuid from lxml import etree from lxml.builder import ElementMaker from oauthlib.oauth1 import Client from oauthlib.common import to_unicode ...
key = request_params['usage_key'] course_key = request_params['course_key'] # Create a record of the outcome service if necessary outcomes, __ = OutcomeService.objects.get_or_create( lis_outcome_service_url=result_service, lti_consumer=lti_consumer ) Gra...
outcome_service=outcomes ) def generate_replace_result_xml(result_sourcedid, score): """ Create the XML document that contains the new score to be sent to the LTI consumer. The format of this message is defined in the LTI 1.1 spec. """ # Pylint doesn't recognize members in the LXML mo...
abutcher/loki
src/loki/models.py
Python
gpl-3.0
15,991
0.003064
# Copyright 2008-2010, Red Hat, Inc # Dan Radez <dradez@redhat.com> # # This software may be freely redistributed under the terms of the GNU # general public license. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 6...
ssume the file or the proc didn't exi
st pid = 0 sftp.close() self.ssh.close() return int(pid) class Master(Bot): host = models.ForeignKey(Host, related_name='masters') slave_port = models.IntegerField(max_length=5, blank=True, null=True, unique=True, help_text="blank value will auto...
superdesk/superdesk-ntb
server/ntb/io/feed_parsers/ntb_events_api_xml.py
Python
agpl-3.0
12,239
0.001471
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license from typing ...
item['dates']['start'] = local_to_utc(tz, get_date(_time
.text)) break for tag in ('stopDate', 'timeEnd'): _time = document.find(tag) if _time is not None: item['dates']['end'] = local_to_utc(tz, get_date(_time.text)) break def _fill_definition_short(self, document, item): content =...
miged/noter
noter/manager.py
Python
mit
1,378
0.004354
from flask import abort, session from noter import db from models import Entry, User from markdown2 import Markdown def EntryGetById(entryid): """Retrieve entry by id""" entry = Entry.query.filter_by(id=entryid).first() return entry def EntryGetByUserId(userid): """Retrieve entry by user id""" ent...
ged_in') or session['user_id'] != entry.user_id:
abort(404) entry.title = title entry.body = body db.session.commit() def EntryDelete(entryid): """Delete entry""" entry = Entry.query.filter_by(id=entryid).first() if not session.get('logged_in') or session['user_id'] != entry.user_id: abort(404) db.session.delete(entry) db.s...
pytroll/posttroll
posttroll/tests/test_bbmcast.py
Python
gpl-3.0
4,340
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2010-2011, 2014. # Author(s): # Martin Raspaud <martin.raspaud@smhi.se> # This file is part of pytroll. # Pytroll 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 So...
str(random.randint(0
, 255)) + "." + str(random.randint(0, 255))) self.assertRaises(error, bbmcast.mcast_receiver, mcport, mcgroup) mcgroup = (str(random.randint(240, 255)) + "." + str(random.randint(0, 255)) + "." + str(random.randint(0, 255)) + "." + ...
Autostew/autostew
autostew_web_session/models/session.py
Python
agpl-3.0
13,540
0.004062
import logging from django.core.urlresolvers import reverse from django.db import models from django.db.models import QuerySet, Max, Min import autostew_web_session.models.participant from autostew_web_enums.models import SessionState from autostew_web_session.models.member import Member class SessionSetup(models.M...
tr(self.id)]) def get_fields(self): return [(field.verbose_name, field._get_val_from_obj(self))
for field in self.__class__._meta.fields] def __str__(self): return "{} ({})".format(self.name, "template" if self.is_template else "instance") class Session(models.Model): class Meta: ordering = ['start_timestamp'] parent = models.ForeignKey('self', null=True, blank=True, related_name='...
eljrax/autoscale_setup
load_balancing/add_self_to_lb.py
Python
apache-2.0
5,035
0.007944
#!/usr/bin/env python ################################################################################### # # # This script should be executed as the last thing that happens during # # the configuration phase of a server. It will perform the health check # # defined in the load balanceri(s) co...
) host_header = None # Protocol to utilise in url check (over
ride LB health check) (optional) protocol = None ###################################################################### def get_addr(iface): ni.ifaddresses(iface) ip = ni.ifaddresses(iface)[2][0]['addr'] return ip def health_check(health_check, port=80): addr = get_addr(iface) if not health_chec...
ProfessorX/Config
.PyCharm30/system/python_stubs/-1247972723/gtk/gdk/__init__/Screen.py
Python
gpl-2.0
4,507
0.010872
# encoding: utf-8 # module gtk.gdk # from /usr/lib/python2.7/dist-packages/gtk-2.0/pynotify/_pynotify.so # by generator 1.135 # no doc # imports from exceptions import Warning import gio as __gio import gobject as __gobject import gobject._gobject as __gobject__gobject import pango as __pango import pangocairo as __p...
nknown pass def list_visuals(self, *args, **kwargs): # real signature unknown pass def make_display_name(self, *args, **kwargs): # real signature unknown pass def set_default_colormap(self, *args, **kwargs): # real signature unknown pass def set_font_options(self, *ar...
n pass def set_resolution(self, *args, **kwargs): # real signature unknown pass def supports_net_wm_hint(self, *args, **kwargs): # real signature unknown pass def __init__(self, *args, **kwargs): # real signature unknown pass __gtype__ = None # (!) real value is ''
tensorflow/tpu
models/hyperparameters/flags_to_params.py
Python
apache-2.0
2,887
0.006928
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
e: flag_dict[k] = flag_value
except AttributeError: flag_dict[k] = v return flag_dict
jullrich/dshieldhoneypot
kippo/kippo-0.8/kippo/commands/ssh.py
Python
gpl-2.0
3,350
0.007164
# Copyright (c) 2009 Upi Tamminen <desaster@gmail.com> # See the COPYRIGHT file for more information from kippo.core.honeypot import HoneyPotCommand from twisted.internet import reactor import time, re, hashlib, getopt commands = {} class command_ssh(HoneyPotCommand): def start(self): try: op...
(self.host, self.ip)) self.writeln('RSA key fingerprint is 9d:30:97:8a:9e:48:0d:de:04:8d:76:3a:7b:4b:30:f8.') self.write('Are you sure you want to continue connecting (yes/no)? ') self.callbacks = [self.yesno, self.wait] def yesno(self, line): self.writeln(
'Warning: Permanently added \'%s\' (RSA) to the list of known hosts.' % \ self.host) self.write('%s@%s\'s password: ' % (self.user, self.host)) self.honeypot.password_input = True def wait(self, line): reactor.callLater(2, self.finish, line) def finish(self, line): ...
JaneliaSciComp/Neuroptikon
Source/Scripts/Community.py
Python
bsd-3-clause
1,449
0.006211
# Copyright (c) 2010 Howard Hughes Medical Institute. # All rights reserved. # Use is subject to Janelia Farm Research Campus Software Copyright 1.1 license terms. # http://license.janelia.org/license/jfrc_copyright_1_1.html """ A script to demonstrate community detection.
Uses the community module bundled with Neuroptikon and written by Thomas Aynaud <http://perso.crans.org/aynaud/communities/>. """ import community updateProgress(gettext('Finding communities...'), forceDisplay = True) dendogram = community.generate_dendogram(network.simplifiedGraph()) updateProgress(gettext('Find
ing communities...')) partition = community.best_partition(dendogram) if any(partition): updateProgress(gettext('Isolating communities...')) for visibles in list(display.visibles.itervalues()): for visible in visibles: if visible.isPath() and not isinstance(visible.client, Stimulus): ...
mitchtz/ai3202
Assignment 8 - Hidden Markov Models/Zinser_Assignment8.py
Python
mit
10,004
0.037785
#Mitch Zinser #CSCI 3202 Assignment 8 #Worked with the Wikipedia Example and Brady Auen from math import log2 #For converting numbers to log base 2 '''PIPE TO EXTERNAL FILE WITH > filename.txt''' letters = 'abcdefghijklmnopqrstuvwxyz' '''File to read in data from, change this name to read from other files''' file_name ...
hidd) P[i][j] = prob temp_path[j] = path[state] + [j] # Don't need to remember the old paths path = temp_path #Find max prob in the last iteration of the list of dicts (P) n = len(evid)-1 (prob, state) = max((P[n][y], y) for y in hidd) #Return the probability for the best last state and the path for it a...
] #Function that takes in 2 strings of equal length and returns the error percent. String 1 is the correct string, string 2 is checked for errors def error_rate(correct, check): errors = 0 for i in range(0,len(correct)): if correct[i] != check[i]: errors += 1 return errors/len(correct) if __name__ == "__ma...
illicitonion/synapse
synapse/handlers/events.py
Python
apache-2.0
5,220
0.000383
# -*- coding: utf-8 -*- # Copyright 2014, 2015 OpenMarket Ltd # # 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/LI
CENSE-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 L...
lightnarcissus/PlayfulMesh
OpenWPM/automation/SocketInterface.py
Python
gpl-3.0
5,057
0.00435
import Queue import threading import socket import struct import json #TODO - Implement a cleaner shutdown for server socket # see: https://stackoverflow.com/questions/1148062/python-socket-accept-blocks-prevents-app-from-quitting class serversocket: """ A server socket to recieve and process string messages ...
ientsocket: def __init__(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def connect(self, host, port): self.sock.connect((host, port)) def send(self, msg): """ Sends an arbitrary python object to the connected socket. Serializes (json) if ...
pends msg len (4-bytes) and serialization status (1-byte). """ #if input not string, serialize to string if type(msg) is not str: msg = json.dumps(msg) is_serialized = True else: is_serialized = False #prepend with message length ...
pschmitt/home-assistant
homeassistant/components/netatmo/camera.py
Python
apache-2.0
8,323
0.000841
"""Support for the Netatmo cameras.""" import logging import pyatmo import requests import voluptuous as vol from homeassistant.components.camera import ( DOMAIN as CAMERA_DOMAIN, SUPPORT_STREAM, Camera, ) from homeassistant.const import ATTR_ENTITY_ID, STATE_OFF, STATE_ON import homeassistant.helpers.con...
attr = {} attr["id"] = self._camera_id attr["status"] = self._status attr["sd_status"] = self._sd_status attr["alim_status"] = self._alim_statu
s attr["is_local"] = self._is_local attr["vpn_url"] = self._vpnurl return attr @property def available(self): """Return True if entity is available.""" return bool(self._alim_status == "on") @property def supported_features(self): """Return supported fe...
justinpotts/mozillians
mozillians/users/es.py
Python
bsd-3-clause
7,571
0
from django.conf import settings from elasticsearch import TransportError from elasticsearch.exceptions import NotFoundError from elasticutils.contrib.django import Indexable, MappingType, S, get_es from mozillians.phonebook.helpers import langcode_to_name from mozillians.users.managers import MOZILLIANS, PUBLIC ES_...
x(cls, document,
id_=None, overwrite_existing=False, es=None, public_index=False): """ Overide elasticutils.index() to support more than one index for UserProfile model. """ if es is None: es = get_es() es.index(document, index=cls.get_index(public_index), ...
coursemdetw/reveal2
pelican/publishconf.py
Python
mit
1,515
0.005536
#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals # This file is only used if you use `make publish` or # explicitly specify it as your config file. import os AUTHOR = 'KMOL' SITENAME = '2015FALL KMOL 課程' SITEURL = '' PATH = 'content' TIMEZONE = 'Asia/Taipei' DEFAULT_LANG = '...
ETE_OUTPUT_DIRECTORY = True # Following items are often useful when publishing #DISQUS_SITENAME = "" DISQUS_SITENAME = "2015fall" #GOOGLE_ANALYTICS = "" # 必須絕對目錄或相對於設定檔案所在目錄 PLUGIN_PATHS = ['./../plugin'] PLUGINS = ['liquid_tags.notebook'] # 目錄設定相對於 reveal 下的 content 目錄 NOTEBOOK_DIR = 'notebook' ''' if not os.path.e...
.html not found.") else: EXTRA_HEADER = open('_nb_header.html', encoding="utf-8").read() '''
esplinr/foodcheck
wsgi/foodcheck_proj/south/tests/__init__.py
Python
agpl-3.0
3,147
0.004449
from __future__ import print_function #import unittest import os import sys from functools import wraps from django.conf import settings
from south.hacks import hacks # Make sure skipping tests is available. try: # easiest and best is unittest included in Django>=1.3 from django.utils import unittest except ImportError: # earlier django... use unittest from stdlib import unittest # however, skipUnless was only added in Python 2.7; # if ...
to do something else try: skipUnless = unittest.skipUnless #@UnusedVariable except AttributeError: def skipUnless(condition, message): def decorator(testfunc): @wraps(testfunc) def wrapper(self): if condition: # Apply method ...
igemsoftware2016/USTC-Software-2016
ncbiuploader.py
Python
agpl-3.0
464
0.002155
from plugins.dbupload.uploaddb import upload from plugins.dbu
pload.dbprofile import * from config import DATABASE_URI ''' Change filepath = your da
ta file from ncbi Change column_num = Column number of data file ''' filepath = r"" column_num = 0 if not DATABASE_URI.startswith('mysql+pymysql://'): DATABASE_URI = 'mysql+pymysql://'+DATABASE_URI.split('://')[1] upload(DATABASE_URI, filepath, gene_commit, column_num, cache_size=100000, echo=True, log=True)
ovnicraft/openerp-restaurant
point_of_sale/wizard/pos_receipt.py
Python
agpl-3.0
2,288
0.000874
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
@param self: The object pointer. @param cr: A database cursor @param uid: ID of
the user currently logged in @param context: A standard dictionary @return: New arch of view with new columns. """ order_lst = self. pool.get('pos.order').browse(cr, uid, context['active_id'], context=context) def print_report(self, cr, uid, ids, context=None): """ ...
jweslley/frogstarb
frogstarb/blogger.py
Python
mit
3,965
0.009584
import gdata.blogger.client import gdata.blogger.data import atom class Blog: """ A simple class for interacting with a Blogger blog. It uses the Google gdata API to create, update and delete posts. """ def __init__ (self, blog, client): self.client = client self.blog_id = blog.get_blog_id() ...
def get_blogs(self): """ List all blogs. """ return [blog.title.text for blog in self.client.get_blogs().entry] def get_blog(self,blog_name): """ Retrieve a blog by the name. """ blogs = [blog for b
log in self.client.get_blogs().entry if blog.title.text == blog_name] if len(blogs) > 0: return Blog(blogs[0], self.client) else: raise NoSuchBlogError("Blog not found: %s" % blog_name)
mhbu50/frappe
frappe/workflow/doctype/workflow/workflow.py
Python
mit
3,999
0.031258
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt import frappe from frappe import _ from frappe.m
odel.document import Document from frappe.model import no_value_fields class Workflow(Document): def validate(self): self.set_active() self.create_custom_field_for_wor
kflow_state() self.update_default_workflow_status() self.validate_docstatus() def on_update(self): self.update_doc_status() frappe.clear_cache(doctype=self.document_type) frappe.cache().delete_key('workflow_' + self.name) # clear cache created in model/workflow.py def create_custom_field_for_workflow_stat...
lory87/django-filer
filer/thumbnail_processors.py
Python
bsd-3-clause
5,654
0.000531
#-*- coding: utf-8 -*- import re try: from PIL import Image from PIL import ImageDraw except ImportError: try: import Image import ImageDraw except ImportError: raise ImportError("The Python Imaging Library was not found.") from django.utils import six from easy_thumbnails import...
subj_x - esize,
subj_y - esize), (subj_x + esize, subj_y + esize)), outline="#FF0000") im = im.crop(crop_box) return im def whitespace(image, size, whitespace=False, whitespace_color=None, **kwargs): if not whitespace: return image if whitespace_color is None: whitespace...
hakancelik96/coogger
core/cooggerapp/migrations/0001_initial.py
Python
mit
25,111
0.000996
# Generated by Django 2.0.12 on 2019-08-18 15:18 import django.db.models.deletion import django_md_editor.models from django.conf import settings from django.db import migrations, models import core.cooggerapp.models.common import core.cooggerapp.models.utils class Migration(migrations.Migration): initial = Tr...
models.CharField( choices=[ ("approved", "approved"), ("rejected", "rejected"), ("waiting", "waiting"), ],
default="approved", max_length=100, ), ), ], options={"ordering": ["-created"]}, bases=(core.cooggerapp.models.common.View, models.Model), ), migrations.CreateModel( name="Content", f...
pf4d/dolfin-adjoint
timestepping/python/timestepping/pre_assembled_adjoint.py
Python
lgpl-3.0
23,635
0.0055
#!/usr/bin/env python2 # Copyright (C) 2011-2012 by Imperial College London # Copyright (C) 2013 University of Oxford # Copyright (C) 2014 University of Edinburgh # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the...
f_x = f_solve.x() a_x = a_map[f_x] a_space = a_x.function_space() assert(not a_x in la_keys) if isinstance(f_solve, AssignmentSolver): la_a_forms.append(None) la_bcs.append([]) la_solver_parameters.append(None) ...
pend(dolfin.parameters["timesteppi
beiko-lab/gengis
bin/Lib/site-packages/numpy/doc/broadcasting.py
Python
gpl-3.0
5,688
0.000176
""" ======================== Broadcasting over arrays ======================== The term broadcasting describes how numpy treats arrays with different shapes during arithmetic operations. Subject to certain constraints, the smaller array is "broadcast" across the larger array so that they have compatible shapes...
]) >>> b = np.array([2.0, 2.0, 2.0]) >>> a * b array([ 2., 4., 6.]) NumPy's broadcasting rule relaxes this constraint when the arrays' shapes meet certain constraints. The simplest broadcasting example occurs when an array and a scalar value are combined in an oper
ation: >>> a = np.array([1.0, 2.0, 3.0]) >>> b = 2.0 >>> a * b array([ 2., 4., 6.]) The result is equivalent to the previous example where ``b`` was an array. We can think of the scalar ``b`` being *stretched* during the arithmetic operation into an array with the same shape as ``a``. The new elements in ...
drewp/tahoe-lafs
misc/simulators/ringsim.py
Python
gpl-2.0
8,203
0.004511
#! /usr/bin/python # used to discuss ticket #302: "stop permuting peerlist?" import time import math from hashlib import sha1, md5, sha256 myhash = md5 # md5: 1520 "uploads" per second # sha1: 1350 ups # sha256: 930 ups from itertools import count from twisted.python import usage def abbreviate_space(s, SI=True): ...
def list_servers(self): for i in range(len(self.servers)): s = self.servers[i] next_s = self.servers[(i+1)%len(self.servers)] diff = "%032x" % (int(next_s.nodeid,1
6) - int(s.nodeid,16)) s.next_diff = diff prev_s = self.servers[(i-1)%len(self.servers)] diff = "%032x" % (int(s.nodeid,16) - int(prev_s.nodeid,16)) s.prev_diff = diff print s, s.prev_diff print "sorted by delta" for s in sorted(self.servers, ...
vikingco/django-advanced-reports
advreport_test_project/advreport_test_project/settings.py
Python
bsd-3-clause
6,452
0.00124
# Django settings for advreport_test_project project. import importlib DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS
= ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'test.db', # Or path to database file if using sqlite3. # The following settings are not used with sqlite3: 'USER': '...
': '', 'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP. 'PORT': '', # Set to empty string for default. } } # Hosts/domain names that are valid for this site; required if DEBUG is False # See https://docs.dja...
RobWin/supervisorclusterctl
setup.py
Python
gpl-3.0
1,415
0.00636
#!/usr/bin/env python # -*- coding: utf-8 -*- from supervisorclusterctl import __version__, __author__, __programm_name__, __programm_description__ import os import sys try: from setuptools import setup, find_packages except ImportError: print "supervisorclusterctl needs setuptools in order to build. " \ ...
ogramm_name__, version=__version__, description=__programm_description__, long_description=README + '\n\n' + CHANGES, author=__author__, keywords = 'supervisor ansible', author_email='rbrtwnklr@gmail.com', url='https://github.com/RobWin/supervisorclusterctl.git', packages=find_packages(...
{ 'console_scripts': [ 'supervisorclusterctl = supervisorclusterctl.supervisorclusterctl:main' ], } )
behzadnouri/numpy
numpy/linalg/linalg.py
Python
bsd-3-clause
78,778
0.000965
"""Lite version of scipy.linalg. Notes ----- This module is a lite version of the linalg.py module in SciPy which contains high-level Python interface to the LAPACK library. The lite version only accesses the following LAPACK functions: dgesv, zgesv, dgeev, zgeev, dgesdd, zgesdd, dgelsd, zgelsd, dsyevd, zheevd, dgetr...
on class, programmatically raised in linalg functions when a Linear Algebra-related condition would prevent further correct execution
of the function. Parameters ---------- None Examples -------- >>> from numpy import linalg as LA >>> LA.inv(np.zeros((2,2))) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "...linalg.py", line 350, in inv return wrap(solve(a, identi...
riking/youtube-dl
youtube_dl/YoutubeDL.py
Python
unlicense
58,331
0.001869
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import collections import datetime import errno import io import json import locale import os import platform import re import shutil import subprocess import socket import sys import time import traceback if os.na...
nt information are always downloaded. None for no limit. download_arch
ive: File name of a file where all downloads are recorded. Videos already present in the file are not downloaded again. cookiefile: File name where cookies should be read from and dumped to. nocheckcertificate:Do not verify SSL certificates prefer_insecu...
xuwenyihust/lunaticlog
scripts/bandwidth.py
Python
mit
861
0.038328
from datetime import datetime import matplotlib.pyplot as plt def main(): f = open("../apache_push.log", 'r') lines = f.readlines() #for i in range(3): # print(lines[i]) time_li = [] for line in lines:
time_and_after = line.split('[')[1] time_and_0700 = time_and_after.split(']')[0] time = time_and_0700.split()[0] time
_li.append(time) #print(time_li[:5]) datetime_li = [datetime.strptime(x, "%d/%b/%Y:%H:%M:%S") for x in time_li] #print(datetime_li[0]) base = datetime_li[0] offset_li = [(x - base) for x in datetime_li] #print(offset_li[0].total_seconds()) offset_sec_li = [x.total_seconds() for x in offset_li] #print(offset...
neudesk/neucloud
openstack_dashboard/dashboards/project/loadbalancers/workflows.py
Python
apache-2.0
26,955
0.000223
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013, Big Switch Networks, 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...
bnet_id_choices protocol_choices = [('', _("Select a Protocol"))] [protocol_choices.append((p, p)) for p in AVAILABLE_PROTOCOLS] self.fields['protocol'].choices = protocol_choices lb_method_choices = [('', _("Select a Method"))] [lb_met
hod_choices.append((m, m)) for m in AVAILABLE_METHODS] self.fields['lb_method'].choices = lb_method_choices # provider choice try: if api.neutron.is_extension_supported(request, 'service-type'): provider_list = api.neutron.provider_list(request) provi...
stevengt/Go-Network
printPlaquettes.py
Python
mit
4,267
0.013827
import pickle from numpy import * def flipHorizontal(a): m = a.copy() return flipud(m) def flipVertical(a): m = a.copy() return fliplr(m) def rotateLeft(a): m = a.copy() return rot90(m) def rotate180(a): m = a.copy() return rot90(m,2) def rotateRight(a): m = a.copy() return...
[j]=k addToList(new,newList) listOfPlaquettes = listOfPlaquettes | newList for i,plaquette in enumerate(listOfPlaquettes): mapping[plaquette]=i reverseMapping[i]=plaquette dim = len(mapping) adjacencyMatrix = zeros((dim,dim)) retu...
listOfPlaquettes,reverseMapping,adjacencyMatrix = findPlaquettes() vector = pickle.load( open( "1.p", "rb" ) ) printTenPlaquettes(vector, reverseMapping)
Yas3r/OWASP-ZSC
lib/generator/windows_x86/dir_create.py
Python
gpl-3.0
135
0.014815
#!/usr/bin/env python ''' OWASP ZSC | ZCR S
hellcoder ZeroDay
Cyber Research Z3r0D4y.Com Ali Razmjoo ''' def run(dirname): return 'N'
erebus/erebus
run_erebus.py
Python
bsd-3-clause
360
0
# !/usr/bin/env python # -*-
coding: utf-8 -*- # # This file is part of Erebus, a web dashboard for tor relays. # # :copyright: (c) 2015, The Tor Project, Inc. # (c) 2015, Damian Johnson #
(c) 2015, Cristobal Leiva # # :license: See LICENSE for licensing information. import erebus if __name__ == '__main__': erebus.main()
Girolabs/MapaAsentamientosTecho
MapaAsentamientosTecho/settings.py
Python
mit
3,830
0.003655
""" Django settings for MapaAsentamientosTecho project. Generated by 'django-admin startproject' using Django 1.9.5. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ ""...
emplate.context_processors.request', 'django.contrib.auth.context_
processors.auth', 'django.contrib.messages.context_processors.messages', 'constance.context_processors.config', ], }, }, ] WSGI_APPLICATION = 'MapaAsentamientosTecho.wsgi.application' # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases ...
yukisakurai/hhana
statstools/tests/test_utils.py
Python
gpl-3.0
845
0.002367
import numpy as np from random import gauss, random from rootpy.plotting import Hist from mva.stats.utils import uniform_binning, zero_negs, kylefix from nos
e.tools import assert_equal, assert_almost_equal def test_uniform_binning(): a = Hist([0, 10, 100, 10000, 100000]) for v in [5, 20, 200, 20000]: a.Fill(v, gauss(10, 5)) b = uniform_binning(a) assert_equal(list(a), list(b)) assert_equal(list(a.yerrh()), list(b.yerrh())) def test_zero_negs...
sert_equal((np.array(list(a)) < 0).any(), True) b = zero_negs(a) assert_equal((np.array(list(b)) < 0).any(), False) def test_kylefix(): a = Hist(10, 0, 1) for w in xrange(1, 11): a.Fill(.5, w) b = kylefix(a) assert_equal(b[0], 5.5)
Mercy-Nekesa/sokoapp
sokoapp/invoicing/admin.py
Python
mit
3,672
0.005174
import datetime from django.contrib import admin from django.db.models import Q from django.utils.timezone import now from django.utils.translation import ugettext_lazy as _ from models import Invoice, InvoiceItem class InvoiceItemInline(admin.TabularInline): fieldsets = ( ( None, ...
, 'discount', 'credit', #'already_paid', 'payment_method', 'constant_symbol', 'variable_symbol', 'specific_symbol', 'reference', 'bank_name', 'bank_country', 'bank_city', 'bank_street', 'bank_zip', 'bank_iban', 'bank_swift_bic' ) }), (_(u'Suppl...
upplier_country', 'supplier_registration_id', 'supplier_tax_id', 'supplier_vat_id', 'supplier_additional_info' ) }), (_(u'Customer details'), { 'fields': ( 'customer_name', 'customer_street', 'customer_zip', 'customer_city', 'customer_country', ...
Lipen/LipenDev
Azeroth/Northrend/TP Olymp/TaskE.py
Python
gpl-3.0
687
0.043668
from math import * def f(e, x): return abs(eval(e.replace('^', '**').replace('x', '('+str(x)+')'))) def solve(e, a, b): N = 1999 t = f(e, a) + f(e, b) for i in range(1, 2*N): if i % 2 == 0: t += 2*f(e, a + (b-a)*i/2/N) else:
t += 4*f(e, a + (b-a)*i/2/N) return (b-a)*t/6/N def main(): ## with open('input.txt', 'r') as f: data = f.read().splitlines() a, b = map(int, data[0].split()) e = data[1] ## # a, b = map(int, input().split()) # e = input() ans = solve(e, a, b) # print(ans) ## ans = str(ans) with open('output.t...
ns) ## main()
protomouse/Flexget
flexget/plugins/metainfo/thetvdb_lookup.py
Python
mit
6,614
0.003629
from __future__ import unicode_literals, division, absolute_import import logging from flexget import plugin from flexget.event import event try: from flexget.plugins.api_tvdb import lookup_series, lookup_episode, get_mirror except ImportError: raise plugin.DependencyError(issued_by='thetvdb_lookup', missing=...
xample: thetvdb_lookup: yes Primarily used for passing thetvdb information to other plugins. Among these is the IMDB url for the series. This information is provided (via entry): series info: tvdb_series_name tvdb_rating tvdb_status (Continuing or Ended) tvdb_runtime (show...
b_banner_url tvdb_fanart_url tvdb_poster_url tvdb_airs_day_of_week tvdb_actors tvdb_language (en, fr, etc.) imdb_url (if available) zap2it_id (if available) episode info: (if episode is found) tvdb_ep_name tvdb_ep_overview tvdb_ep_directors tvdb_ep_w...
ionelmc/virtualenv
.appveyor/appveyor-bootstrap.py
Python
mit
3,284
0.002436
""" AppVeyor will at least have few Pythons around s
o there's no point of implementing a bootstrapper in PowerShell. This is a port of https://github.com/pypa/python-packaging-user-guide/blob/master/source/code/install.ps1 with various fixes and improvements that just weren't feasible to implement in PowerShell. """ from __future__ import print_function from os import ...
.path import exists from subprocess import check_call try: from urllib.request import urlretrieve except ImportError: from urllib import urlretrieve BASE_URL = "https://www.python.org/ftp/python/" GET_PIP_URL = "https://bootstrap.pypa.io/get-pip.py" GET_PIP_PATH = "C:\get-pip.py" URLS = { ("2.7", "64"): B...
metno/modelstatus
productstatus/core/lookup.py
Python
gpl-2.0
1,218
0.002463
import re import django.co
re.exceptions import productstatus.core.models UUID_REGEX = re.compile('[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}') def get_objects_from_field(field, value): results = [] for subclass in productstatus.core.models.BaseModel.__subclasses__(): try: qs = subclass.objects....
continue results += list(qs[:1000]) return results def lookup_uuid(query): matches = UUID_REGEX.search(query) if not matches: return [] return get_objects_from_field('id', matches.group(0)) def lookup_slug(query): return get_objects_from_field('slug', query) def looku...
mandli/sumatra-tsunami
setrun.py
Python
mit
14,161
0.005155
""" Module to set up run time parameters for Clawpack. The values set in the function setrun are then written out to data files that will be read in by the Fortran code. """ import os import clawpack.geoclaw.util as util try: CLAW = os.environ['CLAW'] except: raise Exception("*** Must first set CLAW envior...
of ghost cells (usually 2) clawdata.num_ghost = 2 # Choice of BCs at xlower and xupper: # 0 => user specified (must modify bcN.f to use this option) # 1 => extrapolation (non-reflecting outflow) # 2 => periodic (must specify this at both boundaries) # 3 => solid wall for systems where q
(2) is normal velocity clawdata.bc_lower[0] = 'extrap' clawdata.bc_upper[0] = 'extrap' clawdata.bc_lower[1] = 'extrap' clawdata.bc_upper[1] = 'extrap' # -------------- # Checkpointing: # -------------- # Specify when checkpoint files should be created that can be # used to rest...
SteveViss/readthedocs.org
readthedocs/rtd_tests/tests/test_api_version_compare.py
Python
mit
1,173
0
from django.test import TestCase from readthedocs.builds.constants import LATEST from readthedocs.projects.models import Project from readthedocs.restapi.views.footer_views import get_version_compare_data class VersionCompareTests(TestCase): fixtures = ['eric.json', 'test_data.json'] def test_not_highest(se...
t_version_compare_dat
a(project, version) self.assertEqual(data['is_highest'], True)
edublancas/python-ds-tools
src/dstools/pipeline/io.py
Python
mit
3,746
0.000801
""" Handling file I/O """ import csv from pathlib import Path import pyarrow as pa import pyarrow.parquet as pq from dstools.pipeline.util import safe_remove class FileIO: def __init__(self, path, chunked): self.path = Path(path) self.chunked = chunked # if the file (or if a dir) exist...
.path.mkdir() # only used when chunked self.i = 0 def write(self, data, headers): if self.chunked: path = self.path / '{i}.{ext}'.format(i=self.i, ext=self.extension) self.write_in_path(str(path), data, headers) self.i = self.i + 1 else: ...
method def write_in_path(cls, path, data, headers): raise NotImplementedError @property def extension(self): raise NotImplementedError class ParquetIO(FileIO): """parquet handler Notes ----- going from pandas.DataFrame to parquet has an intermediate apache arrow conv...
magnunor/hyperspy
hyperspy/signals.py
Python
gpl-3.0
2,490
0
""" The Signal class and its specilized subclasses: BaseSignal For generic data with arbitrary signal_dimension. All other signal classes inherit from this one. It should only be used with none of the others is appropriated. Signal1D For generic data with signal_dimension equal ...
ve as ComplexSignal2D can be reconstructed from them. """ # -*- coding: utf-8 -*- from hyperspy.signal import BaseSignal from hyperspy._signals.signal1d import Signal1D from hyperspy._signals.signal2d import Signal2D from hyperspy._signals.eels import EELSSpectrum from hyperspy._signals.eds_sem import EDSSEMSp...
signals.eds_tem import EDSTEMSpectrum from hyperspy._signals.complex_signal import ComplexSignal from hyperspy._signals.complex_signal1d import ComplexSignal1D from hyperspy._signals.complex_signal2d import ComplexSignal2D from hyperspy._signals.dielectric_function import DielectricFunction from hyperspy._signals.holog...
hahahzm/sub_iso
prover.py
Python
gpl-2.0
4,112
0.056907
import socket import sys import random import hashlib from thread import * path="graphs/" def openMatrix(file): global path with open(path + file,"r") as mat: data=mat.read() dimension=1 for c in data: if c=='\n': break dimension=dimension+1 dimension=dimension/2 m=[[0 for x in range(dimension)]...
open(secret,"r") as order: for data in order
: n=[0 for x in range(2)] for col,val in enumerate(data.split(' ')): n[col]=int(val) m.append(n) ct=ct+1 n=[0 for x in range(ct)] for line in m: n[line[0]]=alpha[line[1]] return n def permutation(size): result=[] for x in range(size): result.append(x) random.seed() random.shuffle(result...
jrwdunham/old-webapp
onlinelinguisticdatabase/controllers/collection.py
Python
gpl-3.0
26,844
0.003837
# Copyright (C) 2010 Joel Dunham # # This file is part of OnlineLinguisticDatabase. # # OnlineLinguisticDatabase 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 o...
chema): """SearchCollection is a Schema for validating the search terms entered at the Search Collections page. """ allow_extra_fields = True filter_extra_fields = True pre_validators = [variabledecode.NestedVariables()] searchTerm1 = UnicodeString() searchType1 = UnicodeString() s...
orEach(RestrictorStruct()) dateRestrictors = ForEach(DateRestrictorStruct()) integerRestrictors = ForEach(IntegerRestrictorStruct()) orderByColumn = UnicodeString() orderByDirection = UnicodeString() class AssociateCollectionFileForm(Schema): allow_extra_fields = True filter_extra_fields = True...
gogobook/wagtail
wagtail/wagtailimages/tests/test_blocks.py
Python
bsd-3-clause
1,867
0.001607
# -*- coding: utf-8 -* from __future__ import unicode_literals import os from django.test import TestCase from django.core import serializers from django.conf import settings from wagtail.wagtailimages.blocks import ImageChooserBlock from .utils import get_test_image_file, Image class TestImageChooserBlock(TestCa...
html = block.render(self.image) expected_html = '<img alt="Test image" src="{}" width="640" height="480">'.format( self.get_image_filename(self.image, "original") ) self.assertHTMLEqual(html, expect
ed_html) def test_render_missing(self): block = ImageChooserBlock() html = block.render(self.bad_image) expected_html = '<img alt="missing image" src="/media/not-found" width="0" height="0">' self.assertHTMLEqual(html, expected_html)
PearsonIOKI/compose-forum
askbot/management/commands/build_thread_summary_cache.py
Python
gpl-3.0
413
0.002421
from django.core.management.base import NoArgsCommand from askbot.models import Thread from askbot.utils.console import Progres
sBar class Command(NoArgsCommand): def handle_noargs(self, **options): message = "Rebu
ilding thread summary cache" count = Thread.objects.count() for thread in ProgressBar(Thread.objects.iterator(), count, message): thread.update_summary_html()
saga-survey/saga-code
bossanova/bossanova.py
Python
gpl-2.0
4,779
0.00837
from __future__ import division """ These functions are for BOSSANOVA (BOss Survey of Satellites Around Nearby Optically obserVable milky way Analogs) """ import numpy as np from matplotlib import pyplot as plt import targeting def count_targets(hsts, verbose=True, remove_cached=True, rvir=300, targetingkwargs={})...
00016, 'Canes Venatici II': -4.9199999999999982, 'Canis Major': -14.389999999999999, 'Carina': -9.1099999999999994, 'Coma Berenices': -4.0999999999999996, 'Draco': -8.7999999999999989, 'Fornax': -13.44, 'Hercules': -6.6000000000000014, 'LMC': -18.120
000000000001, 'Leo I': -12.02, 'Leo II': -9.8399999999999999, 'Leo IV': -5.8400000000000016, 'Leo V': -5.25, 'Pisces II': -5.0, 'SMC': -16.830000000000002, 'Sagittarius dSph': -13.500000000000002, 'Sculptor': -11.070000000000002, 'Segue I': -1.5, 'Segue II': -2.5, 'Sextans I': -9.2700000000000014, 'Ursa Maj...
KWARC/mwetoolkit
bin/libs/base/word.py
Python
gpl-3.0
20,032
0.011382
#!/usr/bin/python # -*- coding:UTF-8 -*- ################################################################################ # # Copyright 2010-2014 Carlos Ramisch, Vitor De Araujo, Silvio Ricardo Cordeiro, # Sandra Castellanos # # word.py is part of mwetoolkit # # mwetoolkit is free software: you can redistribute it and...
t WILDCARD, SEPARATOR # List of valid word attributes. Must appear in the same order as the # arguments for the Word class constructor. WORD_ATTRIBUTES = ["surface", "lemma", "pos", "syn"] ################################################################################ class Word(objec
t): """ An orthographic word (in languages for which words are separated from each other by a space) is the simplest lexical unit recognisable by a native speaker, and it is characterized by its surface form, its lemma and its Part Of Speech tag. """ ##########################...
LyleMi/Trafficker
Trafficker/layer/tcp.py
Python
mit
6,791
0.000151
import socket import struct from Trafficker.layer.layer import layer ''' TCP Header Format 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Source Port | ...
dstp, self.s
eqn, self.ackn, data_offset, flags, self.window, self.checksum, self.urgp) tcpChecksum = self.calChecksum(tcpHeader) ...
LSaldyt/qnp
scripts/run_qcl.py
Python
mit
96
0.020833
impo
rt subprocess def run_qcl(args): subprocess.call('qcl ' + ' '.join(args), shell=
True)
Iconik/eve-suite
src/model/dynamic/skills/skill_queue.py
Python
gpl-3.0
1,072
0.003731
import xml.etree.ElementTree as ElementTree from model.dynamic.api import api from model.dynamic.skills
.skill_queue_item import SkillQueueItem class SkillQueue(object): def __init__(self, user_id, api_key, character_id): api.fetch("char", "SkillQueue", user_i
d, api_key, character_id) tree = ElementTree.parse("%s/SkillQueue.xml.aspx" % \ api.build_path("char", user_id, character_id)) root = tree.getroot() rowset = root.find("result").find("rowset") self.skill_queue = list() if rowset.getchildren(): ...
reflexsc/reflex
src/rfxcmd/__init__.py
Python
agpl-3.0
45,284
0.003887
#!/usr/bin/env python3 #$#HEADER-START # vim:set expandtab ts=4 sw=4 ai ft=python: # # Reflex Configuration Event Engine # # Copyright (C) 2016 Brandon Gillespie # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as publ...
dditional information. * these scopes are available as st
andalone commands """ ############################################################################ # pylint: disable=missing-docstring def start(self, argv=None, opts=None): args = self.args.handle_parse(caller=self) scope = args.get('scope') if not args or args.get('--help') and no...
vladimiroff/humble-media
humblemedia/organizations/admin.py
Python
mit
103
0
from django
.contrib import admin from .models import Organization admin.site.register(Organization
)
C-o-r-E/OctoPrint
src/octoprint/gcodefiles.py
Python
agpl-3.0
17,854
0.027952
# coding=utf-8 import re __author__ = "Gina Häußge <osd@foosel.net>" __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' import os import Queue import threading import yaml import time import logging import octoprint.util as util import octoprint.util.gcodeInterpreter as gcodeInter...
ue if updated: updateCount += 1 self._saveMetadata() self._logger.info("Updated %d sets of metadata to new format" % updateCount) def _saveMetadata(self, force=False): if not self._metadataDirty and not force: return with self._metadataFileAccessMutex: with open(self._metadataTempFile, "wb") ...
default_flow_style=False, indent=" ", allow_unicode=True) self._metadataDirty = False util.safeRename(self._metadataTempFile, self._metadataFile) self._loadMetadata() def _getBasicFilename(self, filename): if filename.startswith(self._uploadFolder): return filename[len(self._uploadFolder + os.path.s...
DailyActie/Surrogate-Model
01-codes/scikit-learn-master/examples/svm/plot_rbf_parameters.py
Python
mit
8,095
0.001112
''' ================== RBF SVM parameters ================== This example illustrates the effect of the parameters ``gamma`` and ``C`` of the Radial Basis Function (RBF) kernel SVM. Intuitively, the ``gamma`` parameter defines how far the influence of a single training example reaches, with low values meaning 'far' a...
rom skle
arn.datasets import load_iris from sklearn.model_selection import GridSearchCV from sklearn.model_selection import StratifiedShuffleSplit from sklearn.preprocessing import StandardScaler from sklearn.svm import SVC # Utility function to move the midpoint of a colormap to be around # the values of interest. class Mid...
zapier/transformer
transformer/transforms/string/phone_number_extract.py
Python
gpl-3.0
3,211
0.004671
# -*- coding: utf-8 -*- import re from transformer.registry import register from transformer.transforms.base import BaseTransform # updated to include seperate regexes - testing is much easier here: # orig and default (UNI1): https://regex101.com/r/FCS4px/1 # uni2: https://regex101.com/r/sk6MVY/1 # na: https://regex1...
noun = 'Text' verb = 'find and copy a phone number from' def transform(self, str_input, regex='uni1', **kwargs): if is
instance(str_input, basestring): if regex=='uni2': match = re.search(URL_REGEX_UNI2, str_input) return match.group(0) if match else u'' elif regex=='na': match = re.search(URL_REGEX_NA, str_input) return match.group(0) if match else...
mark-burnett/filament-dynamics
actin_dynamics/database/parameters.py
Python
gpl-3.0
1,833
0.007638
# Copyright (C) 2011 Mark Burnett # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program i...
You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from sqlalchemy import orm as _orm from . import tables as _tables class Parameter(object): def __init__(self, name, value): self.name = name self.value...
ue=%s)" % ( self.__class__.__name__, self.id, self.name, self.value) _orm.mapper(Parameter, _tables.parameters_table, polymorphic_on=_tables.parameters_table.c.type) class SessionParameter(Parameter): pass _orm.mapper(SessionParameter, _tables.session_parameters_table, inheri...
GbalsaC/bitnamiP
venv/lib/python2.7/site-packages/sphinx/websupport/search/whooshsearch.py
Python
agpl-3.0
2,010
0
# -*- coding: utf-8 -*- """ sphinx.websupport.search.whooshsearch ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Whoosh search adapter. :copyright: Copyright 2007-2011 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """ from whoosh import index from whoosh.fields import Schema, ID...
self, pagename, title, text): self.index_writer.add_document(path=unicode(pagename), title=title, text=text) def handle_query(self, q): searcher = self.index.searcher() whoosh_results = searcher.search(self.qparse...
in whoosh_results: context = self.extract_context(result['text']) results.append((result['path'], result.get('title', ''), context)) return results
mkouhei/swiftsc
swiftsc/tests/test_utils.py
Python
gpl-3.0
1,071
0
# -*- coding: utf-8 -*- """swiftsc.utils unit tests.""" import unittest from swiftsc import utils as u from swiftsc.tests import test_vars as v class UtilsTests(unittest.TestCase): """Unit test of utils.py""" def test_check_mimetype(self): """test checking mimetype""" self.assertEqual(v.TEST...
YPE, u.check_mimetype_buffer(fileobj)) fileobj.close() def test_retrieve_info_from_buffer(self): """test retriving info from buffer""" fileobj = open(v.TEST_FILE, 'rb') file_content = fileobj.read() fileobj.seek(0) self.assertEqual((v.TEST_FI...
v.TEST_FILE_SIZE, file_content), u.retrieve_info_from_buffer(fileobj)) fileobj.close()
quincerly/unicorn-hat
python/examples/clock.py
Python
gpl-2.0
1,580
0.041772
#!/usr/bin/env python import unicornhat as unicorn from graphics import Drawing, Color import time, signal, threading class UnicornDrawing(Drawing): def __init__(self): Drawing.__init__(self,8,8) ''' All drawing operations use the pixel method so we override it for UnicornHat ''' def pixel(self, x, y...
lock, set to 0, 90, 180, 270, etc unicorn.rotation(0) def setBrightness(currenttime): currenthour = currenttime.tm_hour # if it's
between 10 am and 8 pm, # use dimmer brightness if(currenthour < 10 or currenthour > 20): unicorn.brightness(0.15) else: unicorn.brightness(0.5) def tick(): currenttime = time.localtime() currenthour = currenttime.tm_hour currentmin = currenttime.tm_min currentsec = currenttime.tm_sec # Set...
woddx/privacyidea
privacyidea/lib/auditmodules/base.py
Python
agpl-3.0
7,831
0.002938
# -*- coding: utf-8 -*- # # privacyIDEA is a fork of LinOTP # May 08, 2014 Cornelius Kölbel # License: AGPLv3 # contact: http://www.privacyidea.org # # 2014-10-17 Fix the empty result problem # Cornelius Kölbel, <cornelius@privacyidea.org> # # Copyright (C) 2010 - 2014 LSE Leading Security Experts G...
""" If the search_query returns an iterator with elements that are not a dictionary, the audit module needs to provide this function, to convert the audit entry to a dictionary. """ return {} def get_dataframe(self, start_time=date
time.now()-timedelta(days=7), end_time=datetime.now()): """ The Audit module can handle its data the best. This function is used to return a pandas.dataframe with all audit data in the given time frame. This dataframe then can be used for extracting statist...
m0re4u/SmartLight
client/modules/speech_recognizer.py
Python
mit
6,500
0.000154
#!/usr/bin/env python3 # NOTE: this example requires PyAudio because it uses the Microphone class import logging import speech_recognition as sr from threading import Thread, Event logger = logging.getLogger(__name__) class SpeechRecogniser(object): def __init__(self, config): # Read in config ...
candidates = speech_to_text['alternative']
logger.debug("Candidates: ") for can in candidates: logger.debug(can) self.recognize_command(candidates) # print("Stopped recognising.") global speech_recogniser speech_recogniser = None def start(config): gl...
whitmo/loaf
pavement.py
Python
bsd-3-clause
18,820
0.005048
""" Paver for setting up basic geo web stack """ from paver.easy import * try: import eventlet.util eventlet.util.wrap_socket_with_coroutine_socket() except ImportError: info("Socket not overridden") from functools import wraps, update_wrapper from paver.setuputils import setup from paver.tasks import Task...
d unpacker. """ url = options.conf_get(se
ction, name) cache = path('build') filename = url.split("/")[-1] dl_path = cache.abspath() / filename if not dl_path.exists(): info("Download %s" %name) urlgrab(url, dl_path, progress_obj=text_progress_meter()) eventlet.api.sleep(0) source_path = tarball_unpack(dl_path, src, True...
vint21h/django-djcopyright
tests/templatetags/test_djcopyright_tags.py
Python
gpl-3.0
707
0
# -*- coding: utf-8 -*- # django-djcopyright # tests/templatetags/test_djcopyright_tags.py from typing import List from django.test import TestCase from django.utils import timezone from djcopyright.templatetags.djcopyright_tags import djcopyright_years __all__: List[str] = ["DjcopyrightYearsTemplatetagTest"] ...
: """Djcopyright years templatetag tests.""" def test_djcopyright_years(self) -> None: """Must return formatted copyright tag."""
result: str = djcopyright_years() self.assertIsInstance(obj=result, cls=str) self.assertEqual(first=result, second=str(YEAR))
fooelisa/netmiko
netmiko/ssh_autodetect.py
Python
mit
9,711
0.003192
""" The ssh_autodetect module is used to auto-detect the netmiko device_type to use to further initiate a new SSH connection with a remote host. This auto-detection is based on a unique class called **SSHDetect**. Notes ----- The **SSHDetect** class is instantiated using the same parameters than a standard Netmiko co...
use further >>> print(guesser.potential_matches) # Dictionary of the whole matching result # Netmiko connection creation section >>> remote_device['device_type'] = best_match >>> connection = ConnectHandler(**remote_device) """ from __future__ import unicode_literals import re import time from netmiko.ssh_dispatcher ...
atch' key is the SSHDetect method to call. dispatch key will be popped off dictionary # remaining keys indicate kwargs that will be passed to dispatch method. SSH_MAPPER_BASE = { 'alcatel_aos': { "cmd": "show system", "search_patterns": ["Alcatel-Lucent"], "priority": 99, "dispatch":...
pchmieli/h2o-3
h2o-py/h2o/estimators/kmeans.py
Python
apache-2.0
4,684
0.016439
from .estimator_base import * class H2OKMeansEstimator(H2OEstimator): def __init__(self, model_id=None, k=None, max_iterations=None,standardize=None,init=None,seed=None, nfolds=None,fold_assignment=None, user_points=None,ignored_columns=None, score_each_iteration=None, keep_cross_valid...
lds"] = value @property def fold_assignment(self): return self._parms["fold_assignment"] @fold_assignment.setter def fold_assignment(self, value): self._parms["fold_assignment"] = value @property def user_points(self): return self._parms["user_points"] @user_points.setter def user_points...
nored_columns(self, value): self._parms["ignored_columns"] = value @property def score_each_iteration(self): return self._parms["score_each_iteration"] @score_each_iteration.setter def score_each_iteration(self, value): self._parms["score_each_iteration"] = value @property def keep_cross_vali...
tectronics/emporionacionaldelapizza
models/menu.py
Python
agpl-3.0
1,936
0.010853
# -*- 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.title...
dido'), []), (T('Ayuda'), False, URL(request.application,'default','ayuda'), []), (T('hexa662'), False, 'http://sites.google.com/site/hexa662', []), (T('Interfaces Web'), False, 'http://sites.google.com/site/hexa662/productos-web', []), (T('Más apicaciones'), False, 'http://sites.google.com/site/hexa662...
] ########################################## ## this is here to provide shortcuts ## during development. remove in production ## ## mind that plugins may also affect menu ########################################## ######################################### ## Make your own menus ######################################...
RedFantom/GSF-Parser
parsing/realtime.py
Python
gpl-3.0
51,914
0.001618
""" Author: RedFantom Contributors: Daethyra (Naiii) and Sprigellania (Zarainia) License: GNU GPLv3 as in LICENSE Copyright (C) 2016-2018 RedFantom """ # Standard Library from datetime import datetime, timedelta from multiprocessing import Event import os import six import sys from queue import Queue from threading imp...
TIMER_MARGIN = 20 SCREEN_DATA_DEF = { "tracking": "", "health": (None, None, None), "map": N
one} def __init__( self, char_db, char_data, ships_db, companions_db, spawn_callback=None, match_callback=None, file_callback=None, event_callback=None, minimap_share=False, minimap_u...
KevinJiao/SnapYak
SYSite/SYSite/wsgi.py
Python
mit
387
0.002584
""" WSGI config for SYSite project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangopro
ject.com/en/1.7/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "SYSite.settings") from django.core.wsgi import get_wsgi_applicatio
n application = get_wsgi_application()
whbruce/upm
examples/python/mhz16.py
Python
mit
2,680
0.004104
#!/usr/bin/python # Author: Zion Orent <zorent@ics.com> # Copyright (c) 2015 Intel Corporation. # # 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 limi...
ULAR 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. from __future__ im...
ort print_function import time, sys, signal, atexit from upm import pyupm_mhz16 as upmMhz16 def main(): # Instantiate a MHZ16 serial CO2 sensor on uart 0. # This example was tested on the Grove CO2 sensor module. myCO2 = upmMhz16.MHZ16(0) ## Exit handlers ## # This stops python from printing a sta...
mcclurmc/xcp-console
XSConsoleConfig.py
Python
gpl-2.0
2,099
0.012863
# Copyright (c) 2007-2009 Citrix Systems Inc. # # 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; version 2 only. # # This program is distributed in the hope that it will be useful, # but WITHOUT ...
Colours specified as name : (red, green, blue), value range 0..999 'fg_dark' : (400, 400, 360), 'fg_normal' : (600, 600, 550), 'fg_bright' : (999, 999, 800), 'bg_dark' : (0, 0, 0), 'bg_normal' : (0, 168, 325), 'bg_bright' : (0, 200, 400), ...
cls.instance = Config() return cls.instance @classmethod def Mutate(cls, inConfig): cls.instance = inConfig def Colour(self, inName): return self.colours[inName] def FTPServer(self): return self.ftpserver def BrandingMap(self): ...
jhroot/elife-bot
workflow/workflow_PublishPerfectArticle.py
Python
mit
5,903
0.000339
import workflow """ PublishPerfectArticle workflow """ class workflow_PublishPerfectArticle(workflow.workflow): def __init__(self, settings, logger, conn=None, token=None, decision=None, maximum_page_size=100): workflow.workflow.__init__(self, settings, logger, conn, token, decision, max...
"version": "1", "input": data, "control": None, "heartbeat_timeout": 60 * 5, "schedule_to_close_timeout": 60 * 5, "schedule_to_start_timeout": 300, "st...
{ "requirements": None } } self.load_definition(workflow_definition)
andreasots/lrrbot
common/postgres.py
Python
apache-2.0
1,730
0.02659
import functools import warnings import sqlalchemy from common.config import config def new_engine_and_metadata(): """ Create new SQLAlchemy engine and metadata. NOTE: Every process should have AT MOST one engine. """ engine = sqlalchemy.create_engine(config["postgres"], echo=config["debugsql"], execution_opti...
scalar(sqlalchemy.select([1])) except sqlalchemy.exc.DBAPIError as err: if err.connection_invalidated: # connection not valid, for
ce reconnect. connection.scalar(sqlalchemy.select([1])) else: raise _engine_and_metadata = None def get_engine_and_metadata(): """ Return the SQLAlchemy engine and metadata for this process, creating one if there isn't one already. """ if _engine_and_metadata is None: set_engine_and_metadata(*new_engine...
terzeron/FeedMaker
bin/test_new_list_collector.py
Python
gpl-2.0
4,610
0.001565
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os import unittest from unittest.mock import patch, call import logging.config from pathlib import Path from typing import List, Tuple from feed_maker_util import Config from new_list_collector import NewListCollector logging.config.fileConfig(os.enviro...
um.net/webtoon/view/haksajaeseng\t학사재생 http://cartoon.media.daum.net/webtoon/view/exchangerate\t환율이 바뀌
었나요? http://cartoon.media.daum.net/webtoon/view/mujigaebridge\t무지개다리 파수꾼 ''' actual = self.collector.split_result_into_items(test_input) self.assertEqual(4, len(actual)) for item in actual: self.assertEqual(2, len(item)) # abnormal input test_input = ''' http://carto...