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
ctools/ctools
test/science_verification.py
Python
gpl-3.0
24,640
0.002476
#! /usr/bin/env python # ========================================================================== # This script performs the ctools science verification. It creates and # analyses the pull distributions for a variety of spectral and spatial # models. Test are generally done in unbinned mode, but also a stacked # anal...
# Get pull distribution table table = fits.table('PULL_DISTRIBUTION') nrows = table.nrows() ncolumns = table.ncols() # Loop over columns for i in range(ncolumns
): # Get table column column = table[i] # Get column names and initialise mean and standard deviations colnames.append(column.name()) # Compute means and standard deciation mean = 0.0 std = 0.0 samples = 0.0 for row in range(nrows): ...
spk/flask-recipes
app/views.py
Python
mit
2,282
0
from flask import render_template, request, jsonify, Blueprint from .models import Recipe, Category from .schemas import RecipeSchema, PaginationSchema recipes = Blueprint("recipes", __name__) DEFAULT_PER_PAGE = 10 MAX_PER_PAGE = 1000 @recipes.route('/api/v1/<int:id>') def api_get_recipe(id): recipe = Recipe.q...
ginationSchema().dump(pagination) return jsonify(result) @recipes.route('/random') def random(): recipe = Recipe.random().first_or_404() return render_temp
late('show.html', recipe=recipe) @recipes.route('/recipes/<id>') def show(id): recipe = Recipe.query.get_or_404(id) return render_template('show.html', recipe=recipe) @recipes.route('/categories/', defaults={'page': 1}) @recipes.route('/categories/page/<int:page>') def categories(page): per_page = get_p...
chadmv/plow
lib/python/plow/rndaemon/server.py
Python
apache-2.0
2,191
0.003651
#!/usr/bin/env python import logging import sys import os import signal import conf import core from thrift.transport import TSocket from thrift.transport import TTransport from thrift.pr
otocol.TBinaryProtocol import TBinaryProtocolAcceleratedFactory from thrift.server import TServer from rpc import RndNodeApi logger = logging.getLogger(__name__) class RndProcessHandler(object): def runTask(self, rtc): logger.debug("starting core.ProcessMgr.runProcess(rtc): %s", rtc.taskId) cor...
ef killRunningTask(self, procId, reason): core.ProcessMgr.killRunningTask(procId, reason) def getRunningTasks(self): logger.debug("starting core.ProcessMgr.getRunningTasks()") tasks = core.ProcessMgr.getRunningTasks() logger.debug("finished core.ProcessMgr.getRunningTasks()") ...
sindresf/The-Playground
Python/Machine Learning/LSTM Music Visualizer/LSTM Music Visualizer/graphics_module/initialization.py
Python
mit
576
0.026042
from graphics_module.objects import * import numpy as np def make_pixels_array_basic(amount): return np.full(10,Pixel(), dtype=np.object) def make_pixels_ar
ray_config_based(config): if config.colorscheme == "b&w": c = Color() elif config.colorscheme == "light": c = Color(r=245,g=235,b=234,a=0.85) #"light" or whatever to be slightly colorized dots if config.aplha == True: lol = 4 #random influenced aplha #and so on def get_color(co...
lower_limit = 230
sio2project/oioioi
oioioi/problems/menu.py
Python
gpl-3.0
162
0
from
django.utils.translation impor
t ugettext_lazy as _ from oioioi.base.menu import MenuRegistry navbar_links_registry = MenuRegistry(_("Navigation Bar Menu"))
qedsoftware/commcare-hq
corehq/form_processor/change_publishers.py
Python
bsd-3-clause
4,539
0.001542
from casexml.apps.case.xform import get_case_ids_from_form from corehq.apps.change_feed import topics from corehq.apps.change_feed.producer import producer from corehq.apps.change_feed import data_sources from corehq.form_processor.interfaces.dbaccessors import FormAccessors, CaseAccessors from corehq.form_processor.si...
='form-sql', document_type='XFormInstance-Deleted', domain=domain, is_deletion=True, )) def publish_case_saved(case, send_post_save_signal=True): """ Publish the change to kafka and run case post-save signals. """ producer.send_change(topics.CASE_SQL, change_meta_from_sql_c...
se_post_save.send(case.__class__, case=case) def change_meta_from_sql_case(case): return ChangeMeta( document_id=case.case_id, data_source_type=data_sources.CASE_SQL, data_source_name='case-sql', # todo: this isn't really needed. document_type='CommCareCase', document_subt...
okuta/chainer
tests/chainer_tests/functions_tests/loss_tests/test_contrastive.py
Python
mit
6,422
0
import math import unittest import numpy import six import chainer from chainer.backends import cuda from chainer import functions from chainer import gradient_check from chainer import testing f
rom chainer.testing import attr @testing.parameterize(*testing.product_dict( [{'dtype': numpy.float
16, 'forward_options': {'rtol': 1e-2, 'atol': 1e-2}, 'backward_options': {'rtol': 1e-2, 'atol': 1e-3}, 'double_backward_options': {'rtol': 3e-1, 'atol': 3e-1}}, {'dtype': numpy.float32, 'forward_options': {'rtol': 1e-2}, 'backward_options': {'rtol': 1e-2, 'atol': 1e-3}, 'double_...
lduarte1991/edx-platform
lms/envs/devstack_docker.py
Python
agpl-3.0
2,419
0.000827
""" Overrides for Docker-based devstack. """ from .devstack import * # pylint: disable=wildcard-import, unused-wildcard-import # Docker does not support the syslog socket at /dev/log. Rely on the console. LOGGING['handlers']['local'] = LOGGING['handlers']['tracking'] = { 'class': 'logging.NullHandler', } LOGGIN...
donate', 'ENTERPRISE': '/enterprise', 'FAQ': '/student-faq', 'HONOR': '/edx-terms-service', 'HOW_
IT_WORKS': '/how-it-works', 'MEDIA_KIT': '/media-kit', 'NEWS': '/news-announcements', 'PRESS': '/press', 'PRIVACY': '/edx-privacy-policy', 'ROOT': MARKETING_SITE_ROOT, 'SCHOOLS': '/schools-partners', 'SITE_MAP': '/sitemap', 'TOS': '/edx-terms-service', 'TOS_AND_HONOR': '/edx-terms-se...
benzrf/Lispnoria
parthial_ext.py
Python
gpl-3.0
3,208
0.003117
import supybot.callbacks as callbacks import supybot.ircutils as ircutils import supybot.ircmsgs as ircmsgs from parthial.vals import LispSymbol, LispList, LispFunc, LispBuiltin from parthial.errs import LimitationError from parthial import built_ins import re import threading parseMessage = re.compile('%s: (?P<conten...
**kwargs): return self.d.__delitem__(*args, **kwargs) def __contai
ns__(self, k): d_contains = self.d.__contains__(k) if d_contains: return d_contains else: return self.cmd_exists(k) underlying = built_ins.default_globals.copy() underlying['cmd'] = LispBuiltin(lisp_cmd, 'cmd') @built_ins.built_in(underlying, 'src') def lisp_src(self, c...
dsanders11/easypost-python
tests/conftest.py
Python
mit
1,864
0
# setup for py.test import os import pytest import easypost TEST_API_KEY = os.environ["TEST_API_KEY"] PROD_API_KEY = os.environ["PROD_API_KEY"] def pytest_sessionstart(session): # this is for local unit testing with google appengine, otherwise you get a # 'No api proxy found for service "urlfetch"' respon...
xture is auto-loaded by all tests; it
sets up the api key @pytest.yield_fixture(autouse=True) def setup_api_key(): default_key = easypost.api_key easypost.api_key = TEST_API_KEY yield easypost.api_key = default_key # if a test needs to use the prod api key, make it depend on this fixture @pytest.yield_fixture() def prod_api_key(): de...
dtysky/Gal2Renpy
Gal2Renpy/DefineSyntax/MovieDefine.py
Python
mit
678
0.060472
#coding:utf-8 ################################# #Copyright(c) 2014 dtysky ################################# import G2R,os class MovieDefine(G2R.DefineSyntax): def Creat(self,Flag,US,FS,DictHash): DictHash=G2R.DefineSyntax.Creat(self,Flag,US,FS,DictHash) if DictHash[Flag]==G2R.DHash(US.Args[Flag]): return DictH...
lepath=US.Args['pathmode']['MoviePath'] Args=US.Args[Flag] so='' for ele in Args: if Args[ele]=='StopMoive':
continue so+='define movie_'+os.path.splitext(Args[ele])[0]+' = ' so+="'"+elepath+Args[ele]+"'\n" FS.Open(path,'w') FS.Write(so) FS.Close() return DictHash
weso/CWR-DataApi
tests/grammar/factory/record/test_npa.py
Python
mit
4,113
0.00073
# -*- coding: utf-8 -*- import unittest from pyparsing import ParseException from tests.utils.grammar import get_record_grammar """ CWR Non-Roman Alphabet Agreement Party Name grammar tests. The following cases are tested: """ __author__ = 'Bernardo Martínez Garrido' __license__ = 'MIT' __status__ = 'Development' ...
ES' result = self.grammar.parseString(record)[0] self.assertEqual('NPA', result.record_type) self.assertEqual(1234, result.transaction_sequence_n) self.assertEqual(23, result.record_sequence_n) ...
self.assertEqual('ES', result.language_code) def test_valid_min(self): """ Tests that IPA grammar decodes correctly formatted record prefixes. This test contains none of the optional fields. """ record = 'NPA0000123400000023000000000PARTY NAME ...
fingeronthebutton/RIDE
src/robotide/lib/robot/running/arguments/argumentmapper.py
Python
apache-2.0
2,517
0.000397
# Copyright 2008-2015 Nokia Solutions and Networks # # 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 l...
ll_named(self, named): for name, value in named.items(): if name in self._positional and self._supports_named: index = self._positional.index(name) self.args[index] = value elif self._supports_kwargs: self.kwargs[name] = value e...
aError("Non-existing named argument '%s'." % name) def prune_trailing_defaults(self): while self.args and isinstance(self.args[-1], Default): self.args.pop() def fill_defaults(self): self.args = [arg if not isinstance(arg, Default) else arg.value for arg in sel...
cliburn/flow
src/plugins/projections/Princomp/Main.py
Python
gpl-3.0
631
0.011094
from plugin import Projections import pca class Pca(Project
ions): name = "Pca" def Main(self,model): self.model = model pca_data = pca.pca(self.model.GetCurrentData()[:]) fields = ['Comp%02d' % c for c in range(1, pca_data.shape[1]+1)] self.model.updateHDF('PCA', pca_data, fields=fields) # self.model.NewGroup('PCA') # da...
a[0]))]) # self.model.current_array = data # self.model.update()
yuraic/koza4ok
skTMVA/sci_bdt_electron_DecisionTree.py
Python
mit
1,980
0.004545
from array import array import numpy as np import matplotlib.pyplot as plt from sklearn import datasets from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import AdaBoostClassifier from sklearn.metrics import classification_report, roc_auc_score, roc_curve from sklearn import tree import cPickle ...
n the rest X_train, y_train = data['data_training'], data['isprompt_training'].ravel() X_test, y_test = data['data_testing'][0:1000], data['isprompt_testing'][0:1000].ravel() # sklearn dt = DecisionTreeClassifier(max_depth=3, min_samples_leaf=100) #min_samples_le...
_toTMVA.pkl', 'wb') as fid: cPickle.dump(dt, fid) else: print "Loading DecisionTree..." # load it again with open('electrons_toTMVA.pkl', 'rb') as fid: dt = cPickle.load(fid) #sk_y_predicted = dt.predict(X_test) #sk_y_predicted = dt.predict_proba(X_test)[:, 1] sk_y_predicted = dt.predict_pr...
ksu-mechatronics-research/deep-visual-odometry
models/hand_crafted/quat_rot_models/vggVO_0/model.py
Python
mit
4,152
0.010116
from keras.layers import Input from keras.layers.core import Flatten, Dense, Dropout, Lambda from keras.layers.convolutional import Convolution2D, MaxPooling2D, ZeroPadding2D from keras.layers.normalization import BatchNormalization from keras.models import Model from keras import backend as
K from keras.optimizers import Adam def VGG_16(): input_img = Input(shape=(128, 128, 6), name='input_img') x = ZeroPadding2D((1,1),input_shape=(128,128,6))(input_img) x = Convolution2D(64, 3, 3, activation='relu')(x) x = BatchNormalization()(x) x = ZeroPadding2D((1,1))(x)
x = Convolution2D(64, 3, 3, activation='relu')(x) x = BatchNormalization()(x) x = MaxPooling2D((2,2), strides=(2,2))(x) x = ZeroPadding2D((1,1))(x) x = Convolution2D(128, 3, 3, activation='relu')(x) x = BatchNormalization()(x) x = ZeroPadding2D((1,1))(x) x = Convolution2D(128, 3, 3, activ...
GFZ-Centre-for-Early-Warning/REM_RRVS
scripts/prepareinput.py
Python
bsd-3-clause
3,970
0.011089
''' ----------------------------------------------------------------------------- WARNING: OUTDATED SCRIPT but might be of value for some (M.Haas 26.02.16) Prepare input files for RRVS survey ----------------------------------------------------------------------------- Created on 24.04.2015 Last modified on 24.04....
ect to database' cur = conn.cursor() #create geojson file from buildings selection #TODO: add a where "gid IN (building_gid)" statement here cur.execute("DROP TABLE IF EXISTS panoimg.geojson;") cur.execute("SELECT * INTO panoimg.geojson FROM (" + "SELECT row_to_json(fc) " + "FROM (S...
OM (SELECT 'Feature' AS type, ST_AsGeoJSON(lg.the_geom)::json AS geometry, " + "row_to_json((SELECT l FROM (SELECT gid) AS l)) AS properties " + "FROM object_res1.ve_resolution1 AS lg) AS f) AS fc " + ") a;") #TODO: define path relative to application in...
nischu7/paramiko
tests/test_buffered_pipe.py
Python
lgpl-2.1
2,696
0.001113
# Copyright (C) 2006-2007 Robey Pointer <robeypointer@gmail.com> # # This file is part of paramiko. # # Paramiko 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 Free # Software Foundation; either version 2.1 of the License, or (a...
threading.Thread(target=delay_thread, args=(p,)).start() self.assertEquals(b'a', p.read(1, 0.1)) try: p.read(1, 0.1) self.assert_(False) except PipeTimeout: pass self.assertEquals(b'b', p.read(1, 1.0)) self.assertEquals(b'', p.read(1)) d...
g.Thread(target=close_thread, args=(p,)).start() data = p.read(1, 1.0) self.assertEquals(b'', data) def test_4_or_pipe(self): p = pipe.make_pipe() p1, p2 = pipe.make_or_pipe(p) self.assertFalse(p._set) p1.set() self.assertTrue(p._set) p2.set() ...
SMALLplayer/smallplayer-image-creator
storage/.xbmc/addons/plugin.audio.tuneinradio.smallplayer/resources/lib/tunein.py
Python
gpl-2.0
37,835
0.002669
#/* # * # * TuneIn Radio for XBMC. # * # * Copyright (C) 2013 Brian Hornsby # * # * 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...
self._global_params = [] self._global_params.append({'param': 'partnerId', 'value': partnerid}) if serial is not None: self._global_params.append({'param': 'serial', 'value': serial}) self._global_params.append({'param': 'render', 'value': 'json'}) self._global_params.append...
self._global_params.append({'param': 'formats', 'value': formats}) self._debug = debug self.log_debug('Protocol: %s' % self._protocol) self.log_debug('Global Params: %s' % self._global_params) def __add_params_to_url(self, method, fnparams=None, addrender=True, addserial=True): ...
karpelescoin/karpelescoin
contrib/bitrpc/bitrpc.py
Python
mit
7,846
0.038109
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...
mc = raw_input("Minimum confirmations (optional): ") try: print access.getrec
eivedbyaddress(addr, mc) except: print access.getreceivedbyaddress() except: print "\n---An error occurred---\n" elif cmd == "gettransaction": try: txid = raw_input("Enter a transaction ID: ") print access.gettransaction(txid) except: print "\n---An error occurred---\n" elif cmd == "getwork": try: ...
csakatoku/uamobile
uamobile/scrapers/base.py
Python
mit
543
0.003683
# -*- coding: utf-8 -*- import urllib2 from lxml import etree class Scraper(object): # subclass must override this property url = None def scrape(self): stream = self.get_stream() doc = self.get_document(stream) return
self.do_scrape(doc) def get_document(self, stream): doc = etree.parse(stream, etree.HTMLParser(remove_comments=True)) return doc d
ef get_stream(self): return urllib2.urlopen(self.url) def do_scrape(self, doc): raise NotImplementedError()
ianadmu/bolton_bot
bot/emoji_master.py
Python
mit
3,263
0.000306
import random import json import os.path class Response: names = ["bolton", "qbot"] def __init__(self, emoji, responses, added, removed): self.emoji = emoji self.responses = responses self.added = added self.removed = removed def get_response(self, message, tokens, user)...
end = event["End"] phrases = [] words = [] responses = [] if "Words" in event["Triggers"]: for w in event["Triggers"]["Words"]: words.append(w) if "Phrases" in event["Triggers"]: ...
ppend(r) self.events.append( Response( phrases, words, responses, use_hash, named, start, end ) ) except: msg_writer.write_error("Error loading JSON file") self.events = [] def get_respon...
dbiesecke/plugin.video.xstream
sites/bundesliga_de.py
Python
gpl-3.0
7,292
0.006175
# -*- coding: utf-8 -*- from resources.lib.parser import cParser from resources.lib.handler.requestHandler import cRequestHandler from resources.lib.gui.guiElement import cGuiElement from resources.lib.gui.gui import cGui from resources.lib.util import cUtil from resources.lib.handler.ParameterHandler import Parameter...
tTitle(sTitle) oGuiElement.setDescription(sDescription) oGuiElement.setThumbnail(sThumbnail) oOutputParameterHandler = ParameterHandler() oOutputParameterHandler.setParam('sUrl', sUrl)
oOutputParameterHandler.setParam('sTitle', sTitle) oGui.addFolder(oGuiElement, oOutputParameterHandler, bIsFolder = False) oGui.setView('movies') oGui.setEndOfDirectory() def play(): params = ParameterHandler() if (params.exist('sUrl') and params.exi...
xiaoxiangs/devops
pedevops/devops/form.py
Python
mpl-2.0
2,621
0.046055
#!/usr/bin/python #coding: utf-8 from django import forms from models import deletelogapply class deletelogform(forms.Form): log_host = forms.CharField(label=u'日志主机',error_messages={'required':u'日志主机不可为空'}, widget = forms.TextInput(attrs={'class':'form-control','placeholder':'必填,不可为空(hostname or ip)'})) ...
x_length=255,required=False, widget = forms.TextInput(attrs={'class':'form-control'})) def __init__(self,*args,**kwargs): super(proxy_updateform,self).__
init__(*args,**kwargs)
sharifelgamal/runtimes-common
ftl/php/builder.py
Python
apache-2.0
2,878
0
# Copyright 2017 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 ag...
vendor_dir] ftl_util.run_command('rm_vendor_dir', rm_cmd) os.makedirs(os.path.join(vendor_dir)) if ftl_util.has_pkg_descriptor(self._descripto
r_files, self._ctx): layer_builder = php_builder.PhaseOneLayerBuilder( ctx=self._ctx, descriptor_files=self._descriptor_files, directory=self._args.directory, destination_path=self._args.destination_path, cache_key_version=self....
gorocacher/payload
payload/api/controllers/v1/queue/__init__.py
Python
apache-2.0
3,397
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (C) 2013 PolyBeacon, 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...
sentation of a queue.""" description = wtypes.text disabled = bool name = wtypes.text project_id = wtypes.text user_id = wtypes.text uuid = wtypes.
text def __init__(self, **kwargs): self.fields = vars(models.Queue) for k in self.fields: setattr(self, k, kwargs.get(k)) class QueuesController(rest.RestController): """REST Controller for queues.""" callers = caller.QueueCallersController() members = member.QueueMembers...
olafhauk/mne-python
mne/minimum_norm/inverse.py
Python
bsd-3-clause
66,037
0
# -*- coding: utf-8 -*- # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Matti Hämäläinen <msh@nmr.mgh.harvard.edu> # Teon Brooks <teon.brooks@gmail.com> # # License: BSD (3-clause) from copy import deepcopy from math import sqrt import numpy as np from scipy import linalg from ._eloret...
oordinate frame # tag = find_tag(fid, invs, FIFF.FIFF_MNE_COORD_FRAME) if tag is None: raise Exc
eption('Coordinate frame tag not found') inv['coord_frame'] = tag.data # # Units # tag = find_tag(fid, invs, FIFF.FIFF_MNE_INVERSE_SOURCE_UNIT) unit_dict = {FIFF.FIFF_UNIT_AM: 'Am', FIFF.FIFF_UNIT_AM_M2: 'Am/m^2', FIFF.FIFF_UN...
sarielsaz/sarielsaz
test/functional/net.py
Python
mit
4,213
0.001899
#!/usr/bin/env python3 # Copyright (c) 2017 The Sarielsaz Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/li
censes/mit-license.php. """Test RPC calls related to net. Tests correspond to code in rpc/net.cpp. """ import time from test_framework.test_framework import SarielsazTestFramework from test_framework.util import ( assert_equa
l, assert_raises_rpc_error, connect_nodes_bi, p2p_port, ) class NetTest(SarielsazTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 2 def run_test(self): self._test_connection_count() self._test_getnettotals() self._tes...
dracidoupe/graveyard
ddcz/migrations/0103_letters_col_rename.py
Python
mit
800
0
# Generated by Django 2.0.13 on 2021-08-08 15:41 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("ddcz", "0102_letters_of_postal_service"), ] operations = [ migrations.RenameField( model_name="letters",
old_name="datum", new_name="date", ), migrations.RenameField( model_name="letters", old_name="prijemce", new_name="receiver", ), migrations.RenameField( model_name="letters", old_name="odesilatel", ...
Field( model_name="letters", old_name="viditelnost", new_name="visibility", ), ]
mtresch/probfit
doc/pyplots/costfunc/ulh.py
Python
mit
726
0.00551
from iminuit import Minuit from probfit import UnbinnedLH, gaussian, Extended from matplotlib import pyplot as plt from numpy.random import randn data = randn(1000)*2 + 1 ulh = UnbinnedLH(gaussian, data
) m = Minuit(ulh, mean=0., sigma=0.5) plt.figure(figsize=(8, 6)) plt.subplot(221) ulh.draw(m) plt.title('Unextended Before') m.migrad() # fit plt.subplot(222) ulh.draw(m) plt.title('Unextended After') #Extended data = randn(2000)*2 + 1 egauss = Extended(gaussian) ulh = UnbinnedLH(egauss, data, extended=True, exten...
.draw(m) plt.title('Extended After')
KWierso/treeherder
tests/etl/conftest.py
Python
mpl-2.0
561
0
import datetime import pytest
from tests.test_utils import create_generic_job
from treeherder.model.models import Push @pytest.fixture def perf_push(test_repository): return Push.objects.create( repository=test_repository, revision='1234abcd', author='foo@bar.com', time=datetime.datetime.now()) @pytest.fixture def perf_job(perf_push, failure_classification...
hittu123/ruhive
src/basic/events/models.py
Python
mit
1,838
0.000544
import datetime from django.db import models from django.utils.translation import ugettext_lazy as _ from django.db.models import permalink from django.contrib.auth.models import User from tagging.fields import TagField from src.basic.places import Place class Event(models.Model): """Event model""" title = m...
start = models.DateTimeField() end = models.DateTimeField(blank=True, null=True) is_all_day = models.BooleanField(default=False) class Meta: verbose_name = _('event time') verbose_name_plural = _('event times') db_table = 'event_times' @property def is_past(self): ...
urn True return False def __unicode__(self): return u'%s' % self.event.title @permalink def get_absolute_url(self): return ('event_detail', None, { 'year': self.start.year, 'month': self.start.strftime('%b').lower(), 'day': self.start.day, ...
vhaupert/mitmproxy
mitmproxy/net/http/request.py
Python
mit
16,075
0.002115
import time import urllib.parse from dataclasses import dataclass from typing import Dict, Iterable, Optional, Tuple, Union import mitmproxy.net.http.url from mitmproxy.coretypes import multidict from mitmproxy.net.http import cookies, multipart from mitmproxy.net.http import message from mitmproxy.net.http.headers im...
de("utf-8", "surrogateescape"), b"", b"", b"", b"HTTP/1.1", headers,
b"", None, time.time(), time.time(), ) req.url = url # Assign this manually to update the content-length header. if isinstance(content, bytes): req.content = content elif isinstance(content, str): req.text = content...
planaspa/Data-Mining
tests/test_graphDb.py
Python
mit
4,201
0
from src.graphDb import * db = 'db/test.db' def test_text_format(): assert text_format("asdkjhaeih") == "asdkjhaeih" assert text_format("as&amp;dkj&gt;hae&lt;ih") == "as&dkj>hae<ih" assert text_format("") == "" def test_creatingGroups(): conn = sqlite3.connect(db) conn.execute("INSERT INTO TW...
", LAT, LONG, FOLLOWERS) " "VALUES(0, 'test2 test0',0 , 0,-5.6, 6.12, 105)") conn.execute("INSERT INTO TWEETS(ID, TWEET_TEXT, FAVS, RTS" ", FOLLOWERS) " "VALUES(1, 'test2 test0',0 , 0, 5)") conn.execute("INSERT INTO TWEETS(ID, TWEET_TEXT, FAVS, RTS" ...
0, 30)") c = conn.cursor() groups1 = creatingGroups(c, 2) groups2 = creatingGroups(c, 4) conn.execute("DELETE FROM TWEETS WHERE ID=0") conn.execute("DELETE FROM TWEETS WHERE ID=1") conn.execute("DELETE FROM TWEETS WHERE ID=2") # Closing the connection conn.close() assert groups1...
kaedroho/wagtail
wagtail/admin/localization.py
Python
bsd-3-clause
3,698
0.000812
import pytz from django.conf import settings from django.utils.dates import MONTHS, WEEKDAYS, WEEKDAYS_ABBR from django.utils.translation import gettext as _ from django.utils.translation import gettext_lazy # Wagtail languages with >=90% coverage # This list is manually maintained WAGTAILADMIN_PROVIDED_LANGUAGES = ...
version.'), 'BROKEN_LINK': _('Broken link'), 'MISSING_DOCUMENT': _('Missing document'), 'CLOSE': _('Close'), 'EDIT_PAGE': _('Edit \'{title}\''), 'VIEW_CHILD_PAGES_OF_PAGE
': _('View child pages of \'{title}\''), 'PAGE_EXPLORER': _('Page explorer'), 'MONTHS': [str(m) for m in MONTHS.values()], # Django's WEEKDAYS list begins on Monday, but ours should start on Sunday, so start # counting from -1 and use modulo 7 to get an array index 'WEEKDAYS': ...
podhmo/kamo
demo/fizzbuzz.py
Python
mit
224
0
from kamo import Template template = Template(""" %for x in range(1, N): %if x % 15 == 0: "fizzbuzz" %elif x % 3 == 0: "fizz" %elif x % 5 == 0: "buzz" %else: ${x
} %endif %endfor """) print(template.re
nder(N=100))
tvtsoft/odoo8
addons/website_sale_digital/controllers/main.py
Python
agpl-3.0
4,318
0.002547
# -*- coding: utf-8 -*- import base64 from openerp.addons.web import http from openerp.addons.web.http import request from openerp.addons.website.controllers.main import Website from openerp.addons.website_portal.controllers.main import website_account from openerp.addons.website_sale.controllers.main import website_s...
est.env['product.product'] template_ids = map(lambda x: P.browse(x).product_tmpl_id.id, purchased_products) if res_id not in template_ids: return redirect(self.orders_page) else: return redirect(self.orders_page)
# The client has bought the product, otherwise it would have been blocked by now if attachment["type"] == "url": if attachment["url"]: return redirect(attachment["url"]) else: return request.not_found() elif attachment["datas"]: data =...
andyzsf/django
tests/template_tests/syntax_tests/test_template_tag.py
Python
bsd-3-clause
2,410
0.00083
from django.template.base import TemplateSyntaxError from django.template.loader import get_template from django.test import SimpleTestCase from .utils import render, setup class TemplateTagTests(SimpleTestCase): @setup({'templatetag01': '{% templatetag openblock %}'}) def test_templatetag01(self): ...
closebrace %}'}) def test_templatetag08(self): output = render('templatetag08') self.assertEqual(output, '}') @setup({'templatetag09': '{% templatetag openbrace %}{% templatetag openbrace %}'}) def test_templatetag09(self): output = render('templatetag09') self.asse
rtEqual(output, '{{') @setup({'templatetag10': '{% templatetag closebrace %}{% templatetag closebrace %}'}) def test_templatetag10(self): output = render('templatetag10') self.assertEqual(output, '}}') @setup({'templatetag11': '{% templatetag opencomment %}'}) def test_templatetag11(se...
rvmoura96/projeto-almoxarifado
almoxarifado/migrations/0002_auto_20170929_1929.py
Python
mit
1,726
0
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-09-29 22:29 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('almoxarifado', '0001_initial'), ] operations = [ migrations.A...
field=models.DateTimeField(default=None), ), migrations.AlterField( model_name='equipamento', name='data_retirada', field=models
.DateTimeField(default=None), ), migrations.AlterField( model_name='equipamento', name='localizacao', field=models.CharField(default=None, max_length=150), ), migrations.AlterField( model_name='equipamento', name='obser...
sc0w/pluma
tools/generate-plugin.py
Python
gpl-2.0
5,946
0.005383
#!/usr/bin/env python # -*- coding: utf-8 -*- # generate-plugin.py - pluma plugin skeletton generator # This file is part of pluma # # Copyright (C) 2006 - Steve Frécinaux # # pluma 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...
blic License # along with pluma; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fift
h Floor, # Boston, MA 02110-1301 USA import re import os import sys import getopt from datetime import date import preprocessor # Default values of command line options options = { 'language' : 'c', 'description' : 'Type here a short description of your plugin', 'author' : os....
KentaYamada/Siphon
app/config.py
Python
mit
1,835
0
""" Siphon config.py Siphon app config Author: Kenta Yamada See configration options Flask https://flask.palletsprojects.com/en/1.1.x/config/#builtin-configuration-values Flask-JWT-extended https://flask-jwt-extended.readthedocs.io/en/latest/ """ from os import environ cla...
'dbname': 'siphon_test', 'user': 'kenta', 'password': 'kenta' } JWT_BLACKLIST_ENABLED = False JWT_SECRET_KEY = 'testing' class DevelopmentConfig(BaseConfig): DEBUG = True ENV = 'development' DATABASE = { 'host': 'localhost', 'dbname': 'siphon_dev', ...
ef get_config(): configs = { 'production': ProductionConfig(), 'test': TestConfig(), 'development': DevelopmentConfig()} app_env = environ.get('APP_TYPE') if app_env not in configs: raise RuntimeError() return configs[app_env]
eharney/nova
nova/tests/api/openstack/compute/contrib/test_extended_hypervisors.py
Python
apache-2.0
4,737
0
# Copyright 2014 IBM 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 t...
tail', use_admin_context=True) result = self.controller.detail(req) self.assertEqual(result, dict(hypervisors=[ dict(id=1, service=dict(id=1, host="compute1"), vcpus=4, m...
memory_mb_used=5 * 1024, local_gb_used=125, hypervisor_type="xen", hypervisor_version=3, hypervisor_hostname="hyper1", free_ram_mb=5 * 1024, free_disk...
OregonWalks/qgis_vector_selectbypoint
vector_selectbypoint.py
Python
gpl-3.0
4,244
0.005184
# -*- coding: utf-8 -*- """ /*************************************************************************** vector_selectbypoint A QGIS plugin Select vector features, point and click. ------------------- begin : 2014-04-07 copy...
# initialize plugin directory self.plugin_dir = os.path.dirname(__file__) # initialize locale
locale = QSettings().value("locale/userLocale")[0:2] localePath = os.path.join(self.plugin_dir, 'i18n', 'vector_selectbypoint_{}.qm'.format(locale)) if os.path.exists(localePath): self.translator = QTranslator() self.translator.load(localePath) if qVersion() > ...
NicovincX2/Python-3.5
Géométrie/Fractales/arbre.py
Python
gpl-3.0
261
0.007663
# -*- coding: utf-8 -*- import os from turtle import* def T(l): if l >
4: pensize(l / 6) fd(l) rt(33) T(l * .7) lt(66) T(l * .7) rt(33) bk(l) seth(90) goto(0, -99) T(99) os.
system("pause")
chaosdorf/chaospizza
src/config/settings/base.py
Python
mit
5,807
0.001033
""" Django settings for web-application project. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import environ # (chaosdorf-pizza/config/settings/base.py - 3 = ...
------------------------------------------------------------ EMAIL_BACKEND = env('DJANGO_EMAIL_BACKEND', default='django.cor
e.mail.backends.smtp.EmailBackend') EMAIL_SUBJECT_PREFIX = env('DJANGO_EMAIL_SUBJECT_PREFIX', default='[chaospizza]') DEFAULT_FROM_EMAIL = env('DJANGO_DEFAULT_FROM_EMAIL', default='chaospizza <noreply@pizza.chaosdorf.de>') SERVER_EMAIL = env('DJANGO_SERVER_EMAIL', default=DEFAULT_FROM_EMAIL) # PASSWORD STORAGE SETTIN...
dcf21/4most-4gp
src/pythonModules/fourgp_pipeline/fourgp_pipeline/pipeline.py
Python
mit
6,115
0.003434
# -*- coding: utf-8 -*- """ The `Pipeline` class represents a pipeline which runs a sequence of tasks for analysing spectra. By defining new descendents of the PipelineTask class, and appending them to a Pipeline, it is possible to configure which 4GP classes it uses to perform each task within the pipeline -- e.g. d...
st.append({'name': task_name, 'implementation': task_implementation}) def analyse_spectrum(self, input_spectrum, spectrum_identifier): """ Analyse a spectrum through the
4GP pipeline. :param input_spectrum: The Spectrum object we are to analyse. :type input_spectrum: Spectrum :param spectrum_identifier: Some string name that we can use in logging messages to identify which spectrum we are working on. :type spectrum_i...
Batterfii/tornado
tornado/platform/twisted.py
Python
apache-2.0
21,586
0.000278
# Author: Ovidiu Predescu # Date: July 2011 # # 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 ...
License. """Bridges between the Twisted reactor and Tornado IOLoop. This module lets you run applications and libraries written for Twisted in a Tornado application. It can be used in two modes, depending on which library's underlying event loop you want to use. This module ha
s been tested with Twisted versions 11.0.0 and newer. """ from __future__ import absolute_import, division, print_function, with_statement import datetime import functools import numbers import socket import sys import twisted.internet.abstract from twisted.internet.defer import Deferred from twisted.internet.posixb...
cartwheelweb/packaginator
apps/core/tests/__init__.py
Python
mit
32
0.03125
from core.t
ests.test_ga impo
rt *
SKIRT/PTS
do/core/makewavemovie.py
Python
agpl-3.0
2,769
0.005058
#!/usr/bin/env python # -*- coding: utf8 -*- # ***************************************************************** # ** PTS -- Python Toolkit for working with SKIRT ** # ** © Astronomical Observatory, Ghent University ** # ***************************************************************** ##...
argument contains a slash, the script processes all simulation output sets in the indicated directory. # If the first argument does not contain a slash, the script processes just the simulation in the current directory # with the indicated prefix. # # By default both axes of the SED plot and the luminosity of
the frames are autoscaled. You can hardcode specific # ranges in the script. # ----------------------------------------------------------------- # Import standard modules import sys # Import the relevant PTS classes and modules from pts.core.simulation.simulation import createsimulations from pts.core.plot.wavemovi...
tunegoon/asteria
asteria/wsgi.py
Python
mit
1,136
0.00088
""" WSGI config for asteria project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` ...
, or combine a Django application with an application of another framework. """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "asteria.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # settin...
# application = HelloWorldApplication(application)
ebmdatalab/openprescribing
openprescribing/dmd/build_search_filters.py
Python
mit
3,765
0.002125
from django.db.models import fields, ForeignKey, ManyToOneRel, OneToOneRel from .obj_types import clss from .search_schema import schema as search_schema def build_search_filters(cls): """Return list of dicts of options for a QueryBuilder filter. See https://querybuilder.js.org/#filters for details. ""...
lter_fk(field) def _build_search_filter_char(field): return { "type": "string", "label": field.help_text, "operators": ["contains"], "validation": {"min": 3}, } def _build_search_filter_date(field): return { "type": "date", "label": field.help_text, ...
): return { "type": "boolean", "label": field.help_text, "input": "radio", "values": [{1: "Yes"}, {0: "No"}], "operators": ["equal"], } def _build_search_filter_decimal(field): return { "type": "double", "label": field.help_text, "operators":...
reinbach/django-machina
machina/apps/forum_permission/checker.py
Python
bsd-3-clause
6,359
0.005032
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib.auth import get_user_model from django.db.models import Q from machina.conf import settings as machina_settings from machina.core.db.models import get_model ForumPermission = get_model('forum_permission', 'ForumPermission') GroupFor...
and p.forum is not None, group_perms)) per_forum_granted_group_perms = [ p.permission.codename for p in per_forum_granted_group_perms] per_forum_nongranted_group_perms = list( filter(lambda p: not p.has_perm and p.forum is not Non...
roup_perms = [ p.permission.codename for p in per_forum_nongranted_group_perms] granted_group_perms = [ c for c in globally_granted_group_perms if c not in per_forum_nongranted_group_perms] + per_forum_granted_group_perms ...
cloud9ers/gurumate
environment/share/doc/ipython/examples/lib/gui-tk.py
Python
lgpl-3.0
612
0.004902
#!/usr/bin/env python """Si
mple Tk example to manually test event loop integration. This is meant to run tests manually in ipython as: In [5]: %gui tk In [6]: %run gui-tk.py """ from Tkinter import * class MyApp: def __init__(self, root): frame = Frame(root) frame.pack() self.button = Button(frame, text="Hello"...
) root = Tk() app = MyApp(root) try: from IPython.lib.inputhook import enable_tk; enable_tk(root) except ImportError: root.mainloop()
meguiraun/mxcube3
mxcube3/video/streaming.py
Python
gpl-2.0
7,123
0.001544
# -*- coding: utf-8 -*- """Functions for video streaming.""" import cStringIO import fcntl import os import signal import struct import subprocess import sys import time import types import json from PIL import Image import v
4l2 VIDEO_DEVICE = None VIDEO_STREAM_PROCESS = None VIDEO_INITIALIZED = False VIDEO_SIZE = "-1,-1" VIDEO_RESTART = False VIDEO_ORIGINAL_SIZE = 0,0 def open_video_device(path="/dev/video0"
): global VIDEO_DEVICE if os.path.exists(path): # binary, unbuffered write device = open(path, "wb", 0) VIDEO_DEVICE = device else: msg = "Cannot open video device %s, path do not exist. " % path msg += "Make sure that the v4l2loopback kernel module is loaded (modpro...
TE-ToshiakiTanaka/stve
project/col/client.py
Python
mit
829
0.018094
import websocket import thread import time import cv2 from StringIO import S
tringIO import base64 from PIL import Image import numpy as np import time def on_message(ws, message): img = base64.b64decode(message) print img def on_error(ws,
error): print error def on_close(ws): print "### closed ###" cv2.destroyAllWindows() def on_open(ws): ws.send('1920x1080/0') if __name__ == "__main__": cv2.namedWindow("img", cv2.WINDOW_NORMAL) websocket.enableTrace(True) ws = websocket.WebSocketApp("ws://localhost:9002/minicap", ...
kupiakos/pybcd
elements.py
Python
mit
10,086
0.00694
import struct from common import * from objects import ObjectAppType from bcddevice import BCDDevice # element types: # X X ???? XX # class format subtype # class: # 1 = Library # 2 = Application # 3 = Device # format: # 0 = Unknown # 1 = Device # 2 = String # 3 = Object # 4 = Object List # 5 = Integer # 6 = ...
m('Disabled', 'Basic', 'Standard')), # not in table 0x08: (5, 'bootmenupolicy', enum('TODO0', 'Standard', 'TODO2', 'TODO3')), } _memdiag = { 0x01: (5, 'passcount'), 0x02: (5, 'testmix', enum('Basic', 'Extended')), 0x03: (5, 'failurecount'), 0x04: (5, 'testtofail', enum('Stride', 'Mats', 'Invers...
domPattern', 'Checkerboard')), 0x05: (6, 'cacheenable'), } _ntldr = { 0x01: (2, 'bpbstring'), } _startup = { 0x01: (6, 'pxesoftreboot'), 0x02: (2, 'applicationname'), } _device = { 0x01: (5, 'ramdiskimageoffset'), 0x02: (5, 'ramdiskftpclientport'), 0x03: (1, 'ramdisksdidevice'), 0x04:...
9h37/pompadour-wiki
pompadour_wiki/pompadour_wiki/apps/utils/git_db.py
Python
mit
10,263
0.001754
# -*- coding: utf-8 -*- from django.utils.translation import ugettext from django.utils import simplejson as json from django.conf import settings from StringIO import StringIO from gitdb import IStream from git import * from git.exc import InvalidGitRepositoryError from collections import defaultdict from datetime ...
""" self.repo.index.remove([path.encode('utf-8'
)]) self.repo.index.commit(ugettext(u'Update Wiki: {0} deleted'.format(path)).encode('utf-8')) self.parse() def commit(self, message): """ Create an empty commit """ c = Commit.create_from_tree(self.repo, self.repo.tree(), message, head=True) def get_folder_tree(self, path): ...
tensorflow/adanet
adanet/core/ensemble_builder_test.py
Python
apache-2.0
31,597
0.00557
"""Test AdaNet ensemble single graph implementation. Copyright 2018 The AdaNet 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 https://www.apache.org/licenses/LIC...
t summary is not None return self._mixture_weights_train_op_fn(loss, var_list) class _BuilderPrunerAll(_Builder): """Removed previous ensemble completely.""" def prune_previous_ensemble(self, previous_ensemble): return [] class _BuilderPrunerLeaveOne(_Builder): """Removed previous ensemble completely...
" def scalar(self, name, tensor, family=None): return "fake_scalar" def image(self, name, tensor, max_outputs=3, family=None): return "fake_image" def histogram(self, name, values, family=None): return "fake_histogram" def audio(self, name, tensor, sample_rate, max_outputs=3, family=None): r...
z/github-loc
githubloc/config.py
Python
mit
345
0
import os import githubloc.util as util config_file = '.githubloc.ini' home = os.path.expanduser('~') config_file_with_path = os.path.join(home, config_file) util.check_
if_not_create(config_
file_with_path, 'config/githubloc.ini') config = util.parse_config(config_file_with_path) conf = { 'token': os.path.expanduser(config['token']), }
dinomite/uaParser
uaParser/test/test_user_agent_parser.py
Python
apache-2.0
6,889
0.001887
#!/usr/bin/python2.5 # # Copyright 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the 'License') # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
'Safari/534.1+,gzip(gfe),gzip(gfe)', {}), ) class ParseTest(unittest.TestCase):
def testStrings(self): for (family, v1, v2, v3), user_agent_string, kwds in TEST_STRINGS: self.assertEqual((family, v1, v2, v3), user_agent_parser.Parse(user_agent_string, **kwds)) class GetFiltersTest(unittest.TestCase): def testGetFiltersNoMatchesGiveEmptyDict(self):...
typefj/django-miniurl
shortener/models.py
Python
mit
702
0
from django.db import models from django.contrib.sites.models import Site # Create your models here. class Link(models.
Model): url = models.URLField(max_length=512) site = models.ForeignKey(Site, on_delete=models.SET_NULL, null=True) request_times = models.PositiveIntegerField(default=0) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): re...
ip = models.GenericIPAddressField(unique=True) start_time = models.DateTimeField() count = models.PositiveIntegerField(default=0) def __str__(self): return self.ip
manipopopo/tensorflow
tensorflow/contrib/gan/python/estimator/python/gan_estimator_impl.py
Python
apache-2.0
13,797
0.005074
# Copyright 2017 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...
eps) # Eva
luate resulting estimator. gan_estimator.evaluate(eval_input_fn) # Generate samples from generator. predictions = np.array([ x for x in gan_estimator.predict(predict_input_fn)]) ``` """ def __init__(self, model_dir=None, generator_fn=None, ...
PaddlePaddle/Paddle
python/paddle/fluid/tests/unittests/test_elementwise_nn_grad.py
Python
apache-2.0
12,057
0.001161
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
def func(self, place): # the shape of input variable should be clearly specified, not inlcude -1. shape = [2, 3, 4, 5] eps = 0.005 dtype = np.float64 x = layers.data('x', shape, False, dtype) y = layers.data('y', shape[:-1], False, dtype) x.persistable = True ...
x_arr = np.random.uniform(-1, 1, shape).astype(dtype) y_arr = np.random.uniform(-1, 1, shape[:-1]).astype(dtype) gradient_checker.double_grad_check( [x, y], out, x_init=[x_arr, y_arr], place=place, eps=eps) def test_grad(self): places = [fluid.CPUPlace()] if core.is_com...
asciinema/asciinema
tests/test_helper.py
Python
gpl-3.0
415
0
import sys from codecs import Strea
mReader from io import StringIO from typing import Optional, TextIO, Union stdout: Optional[Union[TextIO, StreamReader]] = None class Test: def setUp(self) -> None: global stdout # pylint: disable=glob
al-statement self.real_stdout = sys.stdout sys.stdout = stdout = StringIO() def tearDown(self) -> None: sys.stdout = self.real_stdout
benschmaus/catapult
telemetry/telemetry/testing/fakes/__init__.py
Python
bsd-3-clause
15,827
0.011183
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides fakes for several of Telemetry's internal objects. These allow code like story_runner and Benchmark to be run and tested without compiling or st...
me = 'FakeOS' self._device_type_name = 'abc' self._is_svelte = False self._is_aosp = True @property def is_host_platform(self): raise NotImplementedError @property def network_controller(s
elf): if self._network_controller is None: self._network_controller = _FakeNetworkController() return self._network_controller @property def tracing_controller(self): if self._tracing_controller is None: self._tracing_controller = _FakeTracingController() return self._tracing_controll...
angelblue05/Embytest.Kodi
resources/lib/librarysync.py
Python
gpl-2.0
55,974
0.003001
# -*- coding: utf-8 -*- ################################################################################################## import sqlite3 import threading from datetime import datetime, timedelta, time import xbmc import xbmcgui import xbmcvfs import api import utils import clientinfo import downloadutils import it...
f.logMsg window = utils.window settings = utils.setting
s # Only run once when first setting up. Can be run manually. emby = self.emby music_enabled = utils.settings('enableMusic') == "true" xbmc.executebuiltin('InhibitIdleShutdown(true)') screensaver = utils.getScreensaver() utils.setScreensaver(value="") window('emb...
mxrrow/zaicoin
src/deps/boost/tools/build/v2/test/symlink.py
Python
mit
845
0.001183
#!/usr/bin/python # Copyright 2003 Dave Abrahams # Copyright 2003 Vladimir Prus # Distributed u
nder the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) # Test the 'symlink' rule. import os import BoostBuild if os.name != 'posix': print "The symlink tests c
an be run on posix only." import sys sys.exit(1) t = BoostBuild.Tester() t.write("jamroot.jam", "import gcc ;") t.write("jamfile.jam", """ exe hello : hello.cpp ; symlink hello_release : hello/<variant>release ; symlink hello_debug : hello/<variant>debug ; symlink links/hello_release : hello/<variant>releas...
wilsonssun/baseball-gamethread
app.py
Python
bsd-3-clause
9,712
0.008237
import functools import os import re from collections import namedtuple from datetime import datetime, time, timedelta from flask import Flask, request, render_template, jsonify from raven.contrib.flask.utils import get_data_from_request from dateutil.parser import parse as parse_datetime import requests from pyqu...
mlb_home_shortcode, ) r = requests.get(mlb_url) if r.status_code == 500: return error("These teams don't seem to be playing each other tonight.") r.rais
e_for_status() info = re.search('(?<=<li id="preview-header-info">)[a-zA-Z0-9 /.,:]+', r.text).group(0) prob_url = PROB_URL.format( year=today.year, month=str(today.month).zfill(2), day=str(today.day).zfill(2), away=mlb_away_shortcode, home=mlb_home_shortcode, ) ...
1995parham/yepc
yepc/core/to_c.py
Python
gpl-3.0
5,989
0.002004
from ..domain.symtable import SymbolTable class YEPCToC: def __init__(self, quadruples, symtable): self.quadruples = quadruples self.symtable = symtable self.env = {} def store_env(self, symbol_table): # Push the environment from the symbol table self.env[symbol_table....
ype) in reversed(self.env[symbol_table.name]): if name == return_storage: code += '\tstack_pop(yepc_stack, NULL, 0);\n' else: code += '\tstack_pop(yepc_stack, &%s, sizeof(%s));\n' % (name, type) del self.env[symbol_
table.name] return code def to_c(self): c_code = "" # Objects array for allocating and deallocating objects = [] # Includes :) c_code += "#include <stdio.h>\n" c_code += "#include <stdlib.h>\n" c_code += "#include <setjmp.h>\n" c_code += '\n...
apache/incubator-airflow
airflow/migrations/versions/4446e08588_dagrun_start_end.py
Python
apache-2.0
1,372
0.001458
# # 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 use this file except in compliance...
e 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. S...
praekelt/jmbo-superhero
superhero/models.py
Python
bsd-3-clause
269
0
from django.utils.translation import ugettext as _ from django.db import models from jmbo.models import ModelBase class Sup
erhero(ModelBase): name = models.CharField(m
ax_length=256, editable=False) class Meta: verbose_name_plural = _("Superheroes")
nisavid/spruce-settings
spruce/settings/_conf.py
Python
lgpl-3.0
3,013
0.000996
"""Conf format The conf format is registered by default. It reads and writes settings using :mod:`ConfigParser` at locations that are similar to typical Unix configuration files---that is, in :file:`.conf` files specific to each component scope under :file:`/etc/{organization}` for system-wide settings and under :fil...
ization'): _os.path.join(_os.path.sep, 'etc', '{organization}', '{organization}{extension}'), ('system', 'application'): _os.path.join(_os.path.sep, 'etc', '{organization}', '{application}{extension}
'), ('system', 'subsystem'): _os.path.join(_os.path.sep, 'etc', '{organization}', '{application}', '{subsystem}{extension}'), ('user', 'organization'): _os.path.join(_homedir, '.{organization}', '{organization}{exten...
nimasmi/wagtail
wagtail/images/api/v2/views.py
Python
bsd-3-clause
747
0.002677
from wagtail.api.v2.filters import FieldsFilter, OrderingFilter, SearchFilter from wagtail.api.v2.views import BaseAPIViewSet from ... import get_image_model from .serializers import ImageSerializer class ImagesAPIViewSet(BaseAPIViewSet): base_serializer_class = ImageSerializer filter_backends
= [FieldsFilter, OrderingFilter, SearchFilter] body_fields = BaseAPIViewSet.body_fields + ['title', 'width', 'height'] meta_fields = BaseAPIViewSet.meta_fields + ['tags', 'download_url'] listing_def
ault_fields = BaseAPIViewSet.listing_default_fields + ['title', 'tags', 'download_url'] nested_default_fields = BaseAPIViewSet.nested_default_fields + ['title', 'download_url'] name = 'images' model = get_image_model()
neomacedo/ScriptsUteis
Python/checksum_comparator.py
Python
gpl-3.0
1,563
0.003839
""" Helcio Macedo Checksum Verifier v1.0 https://github.com/neomacedo/ScriptsUteis ----------------------------------------------------------- Script used to compare if local file its the same as remote. """ import hashlib import urllib2 import optparse # Remote address to file remote_url = 'https://raw.githubusercon...
) # Method who will return md5 Checksum [Remote] def get_remote_md5_sum(url): try: #
Parse Options opt = optparse.OptionParser() opt.add_option('--url', '-u', default=remote_url) options, args = opt.parse_args() remote = urllib2.urlopen(options.url) md5hash = hashlib.md5() data = remote.read() md5hash.update(data) return md5hash...
dschien/energy-aggregator
ep/tests/test_celery.py
Python
mit
3,630
0.003581
import json from decimal import Decimal from unittest import skip # from unittest.mock import patch import unittest.mock as mock from celery import current_app from django.conf import settings from django.test import TestCase from ep.models import Site, ScheduleDeviceParameterGroup, DeviceParameter, StateChangeEvent f...
ent_app.conf.CELERY_ALWAYS_EAGER = True # @skip('we can only run this on a fully deployed stack') def test_messaging(self): self.assertTrue(send_msg.delay(json.dumps({'test': 1}))) @skip('we can only run this on a fully deployed stack') def test_import(self): Site(name='goldney').save(...
update_device_data', wraps=inst.update_device_data) as update_device_data: # with patch('ep_secure_importer.controllers.secure_client.update_device_data') as update_device_data: update_device_data.return_value = ("server response", 200) SiteFactory.cre...
taschini/morepath
morepath/tests/test_compat.py
Python
bsd-3-clause
799
0
from morepath import compat def test_text_type(): assert isinstance(u'foo', compat.text_type) assert not isinstance(b'foo', compat.text_type) def test_string_types(): assert isinstance('foo', compat.string_types) assert isinstance(u'foo', compat.string_types) if compat.PY3: assert not is...
.bytes_(code) def test_withclass(
): class Meta(type): pass class Class(compat.with_metaclass(Meta)): pass assert type(Class) == Meta assert Class.__bases__ == (object,)
SMxJrz/Elasticd
test/__init__.py
Python
apache-2.0
566
0.0053
import unittest from elasticd.plugins import BasePlugin from elasticd.plugins import ResourceLo
cator from elasticd.plugins import Driver from elasticd.plugins import Datastore from elasticd.plugin_manager import PluginManager import os import ConfigParser def get_test_plugin_manager(): config_file = os.path.dirname(os.path.realpath(__file__)) + '/../conf/settings.cfg' config_file = os.path.realpath(conf...
) _plugin_manager = PluginManager(config) return _plugin_manager
xpybuild/xpybuild
tests/correctness/framework/DepGraph/run.py
Python
apache-2.0
306
0.026144
from pys
ys.constants import * from xpybuild.xpybuild_basetest import XpybuildBaseTest class PySysTest(XpybuildBaseTest): def execute(self): self.xpybuild(args=['--depgraph', 'depgraph-output.dot']) def validate(self): self.assertDiff(file1='depgraph
-output.dot', file2='ref-depgraph-output.dot')
ezequielpereira/Time-Line
libs/wx/tools/Editra/src/eclib/errdlg.py
Python
gpl-3.0
11,900
0.002353
############################################################################### # Name: errdlg.py # # Purpose: Error Reporter Dialog # # Author: Cody Precord <cprecord@editra.org> # ...
dy Precord <staff@editra.org> # # License: wxWindows License # ############################################################################### """ Editra Control Library: Error Reporter Dialog Dialog for displaying exc
eptions and reporting errors to application maintainer. This dialog is intended as a base class and should be subclassed to fit the applications needs. This dialog should be initiated inside of a sys.excepthook handler. Example: sys.excepthook = ExceptHook ... def ExceptionHook(exctype, value, trace): # Format t...
doctaphred/phredutils
zmqrpc.py
Python
gpl-3.0
1,764
0
import traceback from datetime import datetime from itertools import count import zmq def serve(procs, port=None, addr='tcp://*', context=None, debug=False): """Make some procedures available for remote calls via ØMQ.""" if context is None: contex
t = zmq.Context.instance() with context.socket(zmq.REP) as socket: if port is None: port = socket.bind_to_rando
m_port(addr) else: socket.bind('{}:{}'.format(addr, port)) print('Serving at {}:{}'.format(addr, port)) print('sending and receiving JSON') for i in count(1): idle = datetime.now() print('{}: waiting for request #{}...'.format(idle, i)) m...
arokem/PyEMMA
pyemma/_ext/sklearn/parameter_search.py
Python
bsd-2-clause
3,395
0.000589
""" -------------------------------------------------------------------------------------------- Extracted from skikit-learn to ensure basic compatibility without creating an explicit dependency. For the original code see http://scikit-learn.org/ and https://github.com/scikit-learn ----------------------------...
grid.""" # Product function that can handle iterables (np.product can't). product = partial(reduce, operator.mul) return sum(product(le
n(v) for v in p.values()) if p else 1 for p in self.param_grid)
mm22dl/MeinKPS
logger.py
Python
gpl-3.0
3,955
0.005057
#! /usr/bin/python # -*- coding: utf-8 -*- """ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Title: logger Author: David Leclerc Version: 0.1 Date: 13.04.2018 License: GNU General Public License, Version 3 (http://www.gnu.org/licenses...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ DEBUG ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ # Log message self.log("DEBUG", msg) def info(self, msg): """ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~...
self.log("INFO", msg) def warning(self, msg): """ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ WARNING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ # Log message self.log("WARNING", msg) ...
thingsboard/thingsboard-gateway
thingsboard_gateway/gateway/grpc_service/tb_grpc_manager.py
Python
apache-2.0
11,720
0.00384
# Copyright 2022. ThingsBoard # # # 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 ...
downlink_converter_config = {"message_type": [DownlinkMessageType.Response], "additional_message": msg} if msg.HasField("registerConnectorMsg"): self.__register_connector(session_id, msg.registerConnectorMsg.connectorKey) outgoing_message = True elif msg.H...
onnector(session_id, msg.unregisterConnectorMsg.connectorKey) outgoing_message = True elif self.sessions.get(session_id) is not None and self.sessions[session_id].get('name') is not None: if msg.HasField("response"): if msg.response.ByteSize() == 0: ...
funbaker/astropy
astropy/modeling/optimizers.py
Python
bsd-3-clause
7,182
0.000139
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Optimization algorithms used in `~astropy.modeling.fitting`. """ import warnings i
mport abc import numpy as np from ..utils.exceptions import AstropyUserWarning __all__ = ["Optimization", "SLSQP", "Simplex"] # Maximum number o
f iterations DEFAULT_MAXITER = 100 # Step for the forward difference approximation of the Jacobian DEFAULT_EPS = np.sqrt(np.finfo(float).eps) # Default requested accuracy DEFAULT_ACC = 1e-07 DEFAULT_BOUNDS = (-10 ** 12, 10 ** 12) class Optimization(metaclass=abc.ABCMeta): """ Base class for optimizers. ...
diegocortassa/TACTIC
src/pyasm/checkin/repo.py
Python
epl-1.0
6,768
0.008717
########################################################### # # Copyright (c) 2005, Southpaw Technology # All Rights Reserved # # PROPRIETARY INFORMATION. This software is proprietary to # Southpaw Technology, and is not to be reproduced, transmitted, # or disclosed in any way without written permi...
urred. %s' %e.__str__()) # check to see that the file exists. if not os.
path.exists( to_path ): if mode in ["inplace", "preallocate"]: raise CheckinException("File not found in repo at [%s]" % to_path ) else: raise CheckinException("Failed move [%s] to [%s]" % \ (files[i], to_path) ) file_o...
jucimarjr/IPC_2017-1
lista04/lista04_lista02_questao11.py
Python
apache-2.0
1,164
0.013974
#---------------------------------------------------------------------------------- # Introdução a Programação de Computadores - IPC # Universidade do Estado do Amazonas - UEA # # Adham Lucas da Silva Oliveira 1715310059 # Alexandre Marques Uchôa 1715310028 # André Luís Laborda Neves ...
fornecido abaixo, #com um espaço antes e um espaço depois da igualdade. #O valor deverá ser apresentado com 3 casas após o ponto. #---------------------------------------------------------------------------------- radius = float(input()) pi =
3.14159 volume = 4/(3*pi*radius**3) print('volume = %.3f' % volume)
melviso/phycpp
beatle/activity/models/ui/dlg/cc/IsClassMethods.py
Python
gpl-2.0
2,970
0.001684
"""Subclass of IsClassMethods, which is generated by wxFormBuilder.""" from beatle import model from beatle.lib import wxx from beatle.activity.models.ui import ui as ui from beatle.app.utils import cached_type # Implementing IsClassMethods class IsClassMethods(ui.IsClassMethods): """ This dialog allows to a...
kwargs['note'] = 'This method checks if the instance is specialized as {0}'.format(derivative.GetFullLabel()) kwargs['declare'] = True kwargs['implement'] = True kwargs['content'] = '\treturn ( dynamic_cast<const {0}*>(this) != nullptr );'.format(derivative.s...
v[1].Delete() return kwargs_list
Gebesa-Dev/Addons-gebesa
stock_warehouse_analytic_id/__openerp__.py
Python
agpl-3.0
763
0
# -*- coding: utf-8 -*- # © <YEAR(S)> <AUTHOR(S)> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Account Analytic Wareho
use", "summary": "Add analytic in stock_warehouse", "version": "9.0.1.0.0", "category": "Accounting", "website": "https://odoo-community.org/", "author": "<Deysy Mascorro>, Odoo Community Association (OCA)", "license": "AGPL-3", "application": Fa
lse, "installable": True, "external_dependencies": { "python": [], "bin": [], }, "depends": [ "base", "account", "stock" ], "data": [ "views/stock_warehouse_view.xml", "views/stock_location_view.xml", ], "demo": [ ], "qweb":...
jkandasa/integration_tests
cfme/middleware/provider/hawkular.py
Python
gpl-2.0
7,860
0.001781
import re from widgetastic_patternfly import Input, BootstrapSelect from wrapanapi.hawkular import Hawkular from cfme.common import TopologyMixin from cfme.common.provider import DefaultEndpoint, DefaultEndpointForm from cfme.utils.appliance import Navigatable from cfme.utils.appliance.implementations.ui import navig...
elf.hostname = hostname self.port = port self.provider_type = 'Hawkular' if not credentials: credentials = {} self.creden
tials = credentials self.key = key self.sec_protocol = sec_protocol if sec_protocol else 'Non-SSL' self.db_id = kwargs['db_id'] if 'db_id' in kwargs else None self.endpoints = self._prepare_endpoints(endpoints) @property def view_value_mapping(self): """Maps values to vi...
Neitsch/ASE4156
authentication/migrations/0002_profile_has_bank_linked.py
Python
apache-2.0
462
0
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-09-21 00:47 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('authentication', '0001_initial'), ] operations = [ migrations.AddField( model_name='pro...
field=models.NullBooleanField(default=False), ), ]
graphql-python/graphql-core
src/graphql/utilities/ast_to_dict.py
Python
mit
1,596
0.000627
from typing import Any, Collection, Dict, List, Optional, overload from ..language import Node, OperationType from ..pyutils import is_iterable __all__ = ["ast_to_dict"] @overload def ast_to_dict( node: Node, locations: bool = False, cache: Optional[Dict[Node, Any]] = None ) -> Dict: ... @overload def as...
elif node in cache: return cache[node] cache[node] = res = {} res.update( { key: ast_to_dict(getattr(node, key), locations, cache) for key in ("kind",) + n
ode.keys[1:] } ) if locations: loc = node.loc if loc: res["loc"] = dict(start=loc.start, end=loc.end) return res if is_iterable(node): return [ast_to_dict(sub_node, locations, cache) for sub_node in node] if isinstance(node, Ope...
weso/CWR-DataApi
tests/parser/dictionary/decoder/record/test_work_origin.py
Python
mit
1,959
0
# -*- coding: utf-8 -*- import unittest from cwr.parser.decoder.dictionary import
WorkOriginDictionaryDeco
der from cwr.other import VISAN """ Dictionary to Message decoding tests. The following cases are tested: """ __author__ = 'Bernardo Martínez Garrido' __license__ = 'MIT' __status__ = 'Development' class TestWorkOriginDictionaryDecoder(unittest.TestCase): def setUp(self): self._decoder = WorkOriginDict...
atodorov/anaconda
pyanaconda/ui/gui/spokes/datetime_spoke.py
Python
gpl-2.0
42,013
0.002428
# Datetime configuration spoke class # # Copyright (C) 2012-2013 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program i...
lse, False, 0) return (box, combo, suffix_label) class NTPconfigDialog(GUIObject, GUIDialogInputCheckHandler): builderObjects = ["ntpConfigDialog", "addImage", "serversStore"] mainWidgetName = "ntpConfigDialog" uiFile = "spokes/datetime_spoke.glade" def __init__(self, data, timezone_module): ...
n, and check for valid input in on_entry_activated add_button = self.builder.get_object("addButton") GUIDialogInputCheckHandler.__init__(self, add_button) #epoch is increased when serversStore is repopulated self._epoch = 0 self._epoch_lock = threading.Lock() self._timez...
ethifus/commentjson
commentjson/__init__.py
Python
mit
163
0
from commentjson import dump from commentjson import dumps from commentjson import JSONLibraryE
xception from co
mmentjson import load from commentjson import loads
trabucayre/gnuradio
gr-analog/python/analog/fm_emph.py
Python
gpl-3.0
9,632
0.006956
# # Copyright 2005,2007,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # SPDX-License-Identifier: GPL-3.0-or-later # # from gnuradio import gr, filter import math import cmath class fm_deemph(gr.hier_block2): r""" FM Deemphasis IIR filter Args: fs: sampling frequen...
f.connect(self, deemph, self) class fm_preemph(gr.hier_block2): r""" FM Preemphasis IIR filter. Args: fs: sampling frequency in Hz (float) tau: Time constant in seconds (75us in US, 50us in EUR) (float) fh: High frequency at which to flatten out (< 0 means default of 0.925*fs...
mphasis filter, that flattens out again at the high end: C +-----||------+ | | o------+ +-----+--------o | R1 | | +----/\/\/\/--+ \ / \ R2 ...
appsembler/symposion-openshift-quickstart
setup.py
Python
mit
618
0.02589
import os from setuptools import setup, find_packages from pip.req import parse_requirements #REQUIREMENTS_FILE = os.path.join( os.path.dirname(__file__), 'requirements.openshift.txt') PROJECT_NAME = '<your-project-name>' AUTHOR_NAME = '<your-name>' AUTHOR_EMAIL = '<your-email-address>' PROJECT_URL = '' DESCRIPTION =...
on>' PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) setup(name=PROJECT_NAME, version='1.0',
author=AUTHOR_NAME, author_email=AUTHOR_EMAIL, url=PROJECT_URL, packages=find_packages(), include_package_data=True, description=DESCRIPTION, )
hsoft/pdfmasher
qtlib/tree_model.py
Python
gpl-3.0
6,253
0.008316
# Created By: Virgil Dupras # Created On: 2009-09-14 # Copyright 2013 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "BSD" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.hardcoded.net/licens...
Returning DummyNode", row, column, node) parentNode = parent.internalPointer() if parent.isValid() else None dummy = self._createDummyNode(parentNode, row) self._dummyNodes.add(dummy) return self.createIndex(r
ow, column, dummy) def parent(self, index): if not index.isValid(): return QModelIndex() node = index.internalPointer() if node.parent is None: return QModelIndex() else: return self.createIndex(node.parent.row, 0, node.parent) def re...
StevenMaude/sale_GOGgles
GOGgles.py
Python
gpl-3.0
2,999
0.000333
#!/usr/bin/env python # encoding: utf-8 # Copyright 2013 Steven Maude # 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. ...
G_URL = 'http://www.gog.com' def get_front_page(): """ Returns content of gog.com front page. """ r = requests.get(GOG_URL) return
r.content def get_sale_game_title(content): """ Return the current on-sale game title """ title_xpath = "//div[@class='game__info']/a[@class='game__title']/text()" etree = lxml.html.fromstring(content) text = etree.xpath(title_xpath)[0].strip() return text def check_title_wanted(current...
tgquintela/pySpatialTools
pySpatialTools/tests/test_sampling.py
Python
mit
2,210
0.005882
""" Testing sampling ---------------- testing functions which helps in spatial sampling """ #import networkx as nx #from scipy.sparse import coo_matrix #from pySpatialTools.utils.artificial_data import\ # generate_random_relations_cutoffs import numpy as np from pySpatialTools.Sampling.sampling_from_space import ...
ons.relations) ########################################################################### ########################################################################### ############################## Test sampling ############################## #############################################################...
, n_e = 100, 1000 ngx, ngy = 100, 100 limits = np.array([[0.1, -0.1], [0.5, 0.6]]) disc = GridSpatialDisc((ngx, ngy), xlim=(0, 1), ylim=(0, 1)) p_cats = np.random.randint(0, 10, n_e) locs = np.random.random((n_e, 2)) region_weighs = np.random.random(ngx*ngy) point_weighs = np.random.rando...
guanxi55nba/db-improvement
pylib/cqlshlib/helptopics.py
Python
apache-2.0
30,976
0.000839
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
yyyy-mm-dd HH:mm:ss yyyy-mm-dd HH:mmZ yyyy-mm-dd HH:mm:ssZ yyyy-mm-dd'T'HH:mm yyyy-mm-dd'T'HH:mmZ yyyy-mm-dd'T'HH:mm:ss yyyy-mm-dd'T'HH:mm:ssZ yyyy-mm-dd yyyy-mm-ddZ The Z in these formats refers to an RFC-822 4-digit time zone...
om UTC. For example, a timestamp in Pacific Standard Time might be given thus: 2012-01-20 16:14:12-0800 If no time zone is supplied, the current time zone for the Cassandra server node will be used. """ def help_blob_input(self): print """ Blob input ...