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
tensorflow/datasets
tensorflow_datasets/image_classification/imagenet_sketch/__init__.py
Python
apache-2.0
744
0.001344
# coding=utf-8 # Copyright 2022 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless
required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ImageNet-...
etch.imagenet_sketch import ImagenetSketch
graik/biskit
archive_biskit2/Biskit/AmberEntropySlave.py
Python
gpl-3.0
3,638
0.015118
## ## Biskit, a toolkit for the manipulation of macromolecular structures ## Copyright (C) 2004-2018 Raik Gruenberg & Johan Leckner ## ## 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 v...
) except Exception, why: self.reportError( 'ERROR '+str(type(why)), id ) print "\navg time for last %i jobs: %f s" %\ ( len(jobs), (time.time()-startTime)/len(jobs)) return resu
lt if __name__ == '__main__': import sys if len(sys.argv) == 2: nice = int(sys.argv[1]) os.nice(nice) slave = AmberEntropySlave() slave.start()
chaluemwut/fbserver
venv/lib/python2.7/site-packages/sklearn/cross_decomposition/pls_.py
Python
apache-2.0
28,612
0.00021
""" The :mod:`sklearn.pls` module implements Partial Least Squares (PLS). """ # Author: Edouard Duchesnay <[email protected]> # License: BSD 3 clause from ..base import BaseEstimator, RegressorMixin, TransformerMixin from ..utils import check_arrays from ..externals import six import warnings from abc import ...
mates the weights vectors. This can be done with two algo. (a) the inner loop of the original NIPALS algo. or (b) a SVD on residuals cross-covariance matrices. n_components : int, number of components to keep. (default 2). scale : boolean, scale data
? (default True) deflation_mode : str, "canonical" or "regression". See notes. mode : "A" classical PLS and "B" CCA. See notes. norm_y_weights: boolean, normalize Y weights to one? (default False) algorithm : string, "nipals" or "svd" The algorithm used to estimate the weights. It will be ca...
spectrumone/online-shop-template
myshop/orders/migrations/0002_auto_20160213_1225.py
Python
mit
390
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [
('orders', '0001_initial'), ] operations = [ migrations.AlterField(
model_name='order', name='paid', field=models.BooleanField(default=False), ), ]
ZmG/openwhisk-tutorial
deploy_settings/base.py
Python
apache-2.0
6,242
0.002884
# Django settings for trywsk project. DEBUG = False TEMPLATE_DEBUG = DEBUG import os from unipath import Path PROJECT_ROOT = Path(__file__).ancestor(2) PROJECT_ROOT = os.path.join(PROJECT_ROOT,'whisk_tutorial') ADMINS = ( ('IBM jStart', '[email protected]'), ) MANAGERS = ADMINS DATABASES = {} TEST_RUNNER = ...
, 'LOCATION': 'dbcache1', }, 'LocMemCache': { # used for storing the mailchimp object 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake' }, 'disk_cache': { # former tweet cache 'BACKEND': 'django.core.cache.backends.filebased.File...
_URLCONF = 'deploy_settings.urls' # Python dotted path to the WSGI application used by Django's runserver. WSGI_APPLICATION = 'deploy_settings.wsgi.application' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows....
cowboysmall/rosalind
src/stronghold/rosalind_splc.py
Python
mit
466
0.01073
import os import sys sys.path.append(os.path.join(os.path.dirname(__file__
), '../tools')) import fasta import genetics import table def main(argv): codon = table.codon(argv[0]) strings = fasta.read_ordered(argv[1]) dna = strings[0] introns = strings[1:] for intro
n in introns: dna = dna.replace(intron, '') print genetics.encode_protein(genetics.dna_to_rna(dna), codon) if __name__ == "__main__": main(sys.argv[1:])
seddonym/bobsleigh-seddonym
bobsleigh_seddonym/settings/base.py
Python
bsd-2-clause
2,877
0.004171
"""Base settings shared by all environments. This is a reusable basic settings file. """ from django.conf.global_settings import * import os import sys import re # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name TIME_ZONE = 'GB' USE_TZ = True US...
.contrib.staticfiles', 'django.contrib.admin', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.midd
leware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', )
kerneltask/micropython
tests/extmod/ure_sub_unmatched.py
Python
mit
419
0.002387
# test re.sub with unmatched groups, behaviour changed in CPython 3.5 try:
import ure as re except ImportError: try: import re except ImportError: print("SKIP") raise SystemExit try: re.sub except AttributeError: print("SKIP") raise SystemExit # first group matches, second optional group doesn't so is replaced with a b
lank print(re.sub(r"(a)(b)?", r"\2-\1", "1a2"))
jjgomera/pychemqt
tools/terminal.py
Python
gpl-3.0
2,742
0.000365
#!/usr/bin/python3 # -*- coding: utf-8 -*- '''Pychemqt, Chemical Engineering Process simulator Copyright (C) 2009-2017, Juan José Gómez Romera <[email protected]> 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 Softwar...
') + "/.pychemqt/" pychemqt_dir = os.environ["PWD"] + "/" preferences = ConfigParser() preferences.read(conf_dir+"pychemqtrc") terminal = XTerm(preferences)
app.exec_()
Venturi/cms
env/lib/python2.7/site-packages/aldryn_people/south_migrations/0026_auto__del_field_person_slug__del_field_person_name.py
Python
gpl-2.0
15,554
0.007651
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'Person.slug' db.delete_column(u'aldryn_people_person', ...
models.fields.related.ForeignKey', [], {'default': 'None', 'to': "orm['filer.Image']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}), 'website': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}) }, u'aldryn_people.persontrans...
unique_together': "[(u'language_code', u'master')]", 'object_name': 'PersonTranslation', 'db_table': "u'aldryn_people_person_translation'"}, 'description': ('djangocms_text_ckeditor.fields.HTMLField', [], {'default': "u''", 'blank': 'True'}), 'function': ('django.db.models.fields.CharField', [],...
wandb/client
tests/test_telemetry_full.py
Python
mit
3,333
0.0009
""" telemetry full tests. """ import platform import sys from unittest import mock import pytest import wandb def test_telemetry_finish(runner, live_mock_server, parse_ctx): with runner.isolated_filesystem(): run = wandb.init() run.finish() ctx_util = parse_ctx(live_mock_server.get_ctx()...
t() run.name = "test-name" run.tags = ["tag1"] wandb.config.update = True run.finish() ctx_util = parse_ctx(live_mock_server.get_ctx()) telemetry = ctx_util.telemetry assert telemetry and 17 in telemetry.get("3", []) # name assert telemetry and 18 in te...
assert telemetry and 19 in telemetry.get("3", []) # config update
xmbcrios/xmbcrios.repository
script.module.urlresolver/lib/urlresolver/plugins/crunchyroll.py
Python
gpl-2.0
2,694
0.012621
''' Crunchyroll urlresolver plugin Copyright (C) 2013 voinage This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is ...
:"(.+?)","h"').findall(html.replace('\\',''))[0] return mp
4 def get_url(self, host, media_id): return 'http://www.crunchyroll.com/android_rpc/?req=RpcApiAndroid_GetVideoWithAcl&media_id=%s' % media_id def get_host_and_id(self, url): r = re.match(r'http://www.(crunchyroll).+?/.+?/.+?([^a-zA-Z-+]{6})', url) if r: return r.gr...
jajadinimueter/recipe
apps/basex/basex.py
Python
mit
239
0
from django.apps import apps from contextlib import contextmanager def session(): return apps.get_app_c
onfig('basex').basex @contextmanager def recipe_db(): s = session() s.execute('open recipe') yie
ld s s.close()
12019/pyscard
smartcard/Examples/framework/sample_ExclusiveCardConnection.py
Python
lgpl-2.1
2,465
0.001623
#! /usr/bin/env python """ Sample script that illustrates exclusive card connection decorators. __author__ = "http://www.gemalto.com" Copyright 2001-2010 gemalto Author: Jean-Daniel Aussel, mailto:[email protected] This file is part of pyscard. pyscard is free software; you can redistribute it and/or m...
nection)
) # connect to the card and perform a few transmits cardservice.connection.connect() print 'ATR', toHexString(cardservice.connection.getATR()) try: cardservice.connection.lock() apdu = SELECT + DF_TELECOM response, sw1, sw2 = cardservice.connection.transmit(apdu) if sw1 == 0x9F: apdu = GET_...
okfn/ckanext-s3filestore
ckanext/s3filestore/tests/test_controller.py
Python
agpl-3.0
3,472
0.000288
import os from nose.tools import (assert_equal, assert_true) from ckantoolkit import config import ckan.tests.helpers as helpers import ckan.tests.factories as factories import ckanapi import boto from moto import mock_s3 import logging log = logging.getLogger(__name__) class TestS3Control...
urce, demo, app = self._upload_resource() resource_file_url = '/dataset/{0}/resource/{1}/download' \ .format(resource['package
_id'], resource['id']) file_response = app.get(resource_file_url) assert_equal(file_response.content_type, 'text/csv') assert_true('date,price' in file_response.body) @mock_s3 def test_resource_download_url_link(self): '''A resource with a url (not file) is redirected correctl...
paluh/code-formatter
code_formatter/extras/__init__.py
Python
bsd-3-clause
12,919
0.005573
"""All formatters from this pacakge should be easily mixed whith default ones using this pattern: >>> from code_formatter.base import formatters >>> from code_formatter import extras >>> custom_formatters = formatters.copy() >>> custom_formatters.register(extras.UnbreakableTupleFormatter, ...
ithLinebreakingFallback(base.CallFormatter): def _format_code(self, width, continuation, suffix): try: return super(CallFormatterWithLinebreakingFallback, self)._format_code(width, continuation, suffix) except NotEnoughSpace: if not self._arguments_formatters: ...
._func_formatter.format_code(curr_width) block.append_tokens('(') try: subblock = self._arguments_formatter.format_code(width - len(CodeLine.INDENT), ...
magfest/panels
panels/site_sections/schedule.py
Python
agpl-3.0
14,930
0.004019
from uber.custom_tags import normalize_newlines from panels import * @all_renderable(c.STUFF) class Root: @unrestricted def index(self, session, message=''): if c.ALT_SCHEDULE_URL: raise HTTPRedirect(c.ALT_SCHEDULE_URL) else: raise HTTPRedirect("internal") @cached ...
n=None): if when: now = c.EVENT_TIMEZONE.localize(datetime(*map(int, when.split(',')))) else: now = c.EVENT_TIMEZONE.localize(datetime.combine(localized_now().date(), time(localized_now().hour))) current, upcoming = [], []
for loc, desc in c.EVENT_LOCATION_OPTS: approx = session.query(Event).filter(Event.location == loc, Event.start_time >= now - timedelta(hours=6), Event.start_time <= now).all() for event in ...
riccardomc/moto
tests/test_ec2/test_vpcs.py
Python
apache-2.0
8,856
0.000339
from __future__ import unicode_literals # Ensure 'assert_raises' context manager support for Python 2.6 import tests.backport_assert_raises # flake8: noqa from nose.tools import assert_raises import boto3 import boto from boto.exception import EC2ResponseError import sure # noqa from moto import mock_ec2 SAMPLE_DO...
='10.0.0.0/16') # Test default values for VPC attributes response = vpc.describe_attribute(Attribute='enableDnsSupport') attr = response.get('EnableDnsSupport') attr.get('Value').should.be.ok vpc.modify_attribute(
EnableDnsSupport={'Value': False}) response = vpc.describe_attribute(Attribute='enableDnsSupport') attr = response.get('EnableDnsSupport') attr.get('
kfdm/hatarake
hatarake/cli.py
Python
mit
4,255
0.00047
import datetime import logging import textwrap import time import click import hatarake import hatarake.net as requests from hatarake.config import Config logger = logging.getLogger(__name__) @click.group() @click.option('-v', '--verbosity', count=True) def main(verbosity): logging.basicConfig(level=logging.WA...
st( config.get('stat', 'api'), headers={ 'Authorization': 'Token %s' % config.get('stat', 'token'), }, data={ 'key': key, 'value': value, } ) logger.info('POSTing to %s %s', response.request.url, response.request.body) response.rais...
@click.argument('name', default='heartbeat') def heartbeat(name): config = Config(hatarake.CONFIG_PATH) url = config.get('prometheus', 'pushgateway') payload = textwrap.dedent(''' # TYPE {name} gauge # HELP {name} Last heartbeat based on unixtimestamp {name} {time} ''').format(name=name, t...
manolama/dd-agent
checks.d/php_fpm.py
Python
bsd-3-clause
4,587
0.002616
# (C) Datadog, Inc. 2010-2016 # All rights reserved # Licensed under Simplified BSD License (see LICENSE) # 3p import requests # project from checks import AgentCheck from util import headers class PHPFPMCheck(AgentCheck): """ Tracks basic php-fpm metrics via the status module Requires php-fpm pools to ...
gs = instance.get('tags', []) http_host = instance.get('http_host') if user and password: auth = (user, password) if status_url is None and ping_url is None: ra
ise Exception("No status_url or ping_url specified for this instance") pool = None status_exception = None if status_url is not None: try: pool = self._process_status(status_url, auth, tags, http_host) except Exception as e: status_excepti...
sccn/SNAP
src/modules/MBF/MBF2_A.py
Python
bsd-3-clause
69,902
0.017625
# # # # from framework.deprecated.controllers import CommScheduler, CheckpointDriving, VisualSearchTask from framework.latentmodule import LatentModule from framework.convenience import ConvenienceFunctions from framework.ui_elements.EventWatcher import EventWatcher from framework.ui_elements.ScrollPresenter import S...
'direction':0.0}, # parameters for the sound() command # response handling snd_hit='click2s.wav', # sound when the user correctly detected the warning state snd_wrongcue='xBuzz01.wav', # the sound that is ...
# key to press in case of an event timeout=2.5, # response timeout for the user hit_reward=0, # reward if hit miss_penalty=-20, # penalty if missed ...
bundgus/python-playground
sqlite-playground/sqlite_logfile_write.py
Python
mit
511
0.007828
import sqlite3 imp
ort time conn = sqlite3.connect('log.db') c = conn.cursor() # Create table c.execute("CREATE TABLE if not exists log (log_timestamp DECIMAL(12,8), " "log_source text, msg_sequence integer, log_message text, stat
us text)") for x in range(0, 1000): insertquery = "INSERT INTO log (log_timestamp, log_source, msg_sequence, log_message) " \ "VALUES ({0},'tst source', {1}, 'log message')".format(time.time(), x) c.execute(insertquery) conn.commit() conn.close()
erinspace/osf.io
website/search/views.py
Python
apache-2.0
8,117
0.00271
# -*- coding: utf-8 -*- import functools import httplib as http import logging import time import bleach from django.db.models import Q from flask import request from framework.auth.decorators import collect_auth from framework.auth.decorators import must_be_logged_in from framework.exceptions import HTTPError from f...
nodes: matching_title = matching_title & ~Q(_id=node_id) my_projects = [] my_project_count = 0 publi
c_projects = [] if include_contributed == 'yes': my_projects = AbstractNode.objects.filter( matching_title & Q(_contributors=user) # user is a contributor )[:max_results] my_project_count = my_project_count if my_project_count < max_results and include_public =...
salilab/rmf
test/test_aliases.py
Python
apache-2.0
1,442
0.000693
from __future__ import print_function import unittest import RMF class Tests(unittest.TestCase): def test_multiparent(self): """Test that nodes with multiple parents can be used and resolve""" for suffix in RMF.suffixes: path = RMF._get_temporary_file_path("alias2." + suffix) ...
PRESENTATION) nh.add_child(rh) ch = nh.get_children() self.assertEqual(len(ch), 1)
print(ch) self.assertEqual(ch[0], rh) def test_aliases(self): """Test that aliases can be used and resolve""" for suffix in RMF.suffixes: path = RMF._get_temporary_file_path("alias." + suffix) print(path) fh = RMF.create_rmf_file(path) ...
Gnomescroll/Gnomescroll
server/waflib/Tools/clang.py
Python
gpl-3.0
4,637
0.014449
#!/usr/bin/env python # encoding: utf-8 # Thomas Nagy, 2006-2010 (ita) # Ralf Habacker, 2006 (rh) # Yinon Ehrlich, 2009 """ clang/llvm detection. """ import os, sys from waflib import Configure, Options, Utils from waflib.Tools import ccroot, ar from waflib.Configure import conf @conf def find_clang(conf): """ ...
# * the destination platform is detected automatically by looking at the macros the compiler predefines, # and if it's not recognised, it fallbacks to sys.platform. clang_modifier_func = getattr(conf, 'clang_modifier_' + conf.env.DEST_OS, None) if clang_modifier_func: clang_modifier_func()...
ad_tools() conf.cc_add_flags() conf.link_add_flags()
NeilBryant/check_mk
modules/discovery.py
Python
gpl-2.0
52,283
0.004399
#!/usr/bin/python # -*- encoding: utf-8; py-indent-offset: 4 -*- # +------------------------------------------------------------------+ # | ____ _ _ __ __ _ __ | # | / ___| |__ ___ ___| | __ | \/ | |/ / | # | | | | '_ \ / _ \/ __| |/ /...
e do discovery on the nodes instead. nodes = [] for h in hostnames: nodes = nodes_of(h) if nodes: hostnames += nodes # Then remove clusters and make list unique hostnames = list(set([ h for h in hostnames if not is_cluster(h) ])) hostnames.sort() # Now loop through ...
try: verbose(tty_white + tty_bold + hostname + tty_normal + ":\n") if opt_debug: on_error = "raise" else: on_error = "warn" do_discovery_for(hostname, check_types, only_new, use_caches, on_error) verbose("\n") excep...
revarbat/mufsim
mufsim/insts/stack.py
Python
bsd-2-clause
11,103
0
import copy import mufsim.utils as util import mufsim.gamedb as db import mufsim.stackitems as si from mufsim.errors import MufRuntimeError from mufsim.insts.base import Instruction, instr class InstPushItem(Instruction): value = 0 def __init__(self, line, val): self.value = val super(InstPus...
able(Instruction): def execute(self, fr): vnum = fr.data_pop(int) fr.data_push(si.GlobalVar(vnum)) @instr("localvar") class InstLoca
lVar(Instruction): def execute(self, fr): vnum = fr.data_pop(int) fr.data_push(si.GlobalVar(vnum)) @instr("caller") class InstCaller(Instruction): def execute(self, fr): fr.data_push(fr.caller_get()) @instr("prog") class InstProg(Instruction): def execute(self, fr): fr.da...
csherwood-usgs/landlab
landlab/components/stream_power/fastscape_stream_power.py
Python
mit
18,923
0.000053
#! /usr/env/python """ This module attempts to "component-ify" GT's Fastscape stream power erosion. Created DEJH, March 2014. """ from __future__ import print_function import numpy import warnings from landlab import ModelParameterDictionary, Component from landlab.core.model_parameter_dictionary import MissingKeyErr...
ge_area', 'flow__receiver_node', and 'topographic__elevation' at the nodes in the grid. 'drainage_area' should be in area upstream, not volume (i.e., set runoff_rate=1.0 when calling FlowRouter.route_flow). The primary method of this class is :func:`run_one_step`. Construction:: F
astscapeEroder(grid, K_sp=None, m_sp=0.5, n_sp=1., threshold_sp=0., rainfall_intensity=1.) Parameters ---------- grid : ModelGrid A grid. K_sp : float, array, or field name K in the stream power equation (units vary with other parameters). m_sp : float, optio...
mazelife/django-belleville
belleville/projects/tests.py
Python
apache-2.0
1,492
0.004021
from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.test import TestCase from models import Project class ProjectsTest(TestCase): fixtures = ['test_data.json'] def test_project_listing(self): """ Verify that the project listing page contains a...
.published(): self.assertTrue(project in response.context['project_list']) def test_verify_author_detail_pages(self): """ Verify that each author has a detail page and that the author is contained within the page's context. """ for project in Project...
f project.published(): self.assertTrue(response.status_code == 200) try: self.failUnlessEqual(response.context['project'], project) except KeyError: self.fail("Template context did not contain project object.") else: ...
pumanzor/security
raspberrypi/relaycontrol.py
Python
mit
1,611
0.009932
import paho.mqtt.client as mqtt import json, time import RPi.GPIO as GPIO from time import sleep # The script as below using BCM GPIO 00..nn numbers GPIO.setmode(GPIO.BCM) # Set relay pins as output GPIO.setup(24, GPIO.OUT) # ----- CHANGE THESE FOR YOUR SETUP ----- MQTT_HOST = "190.97.168.236" MQTT_PORT = 1883 US...
------------------------------------ def on_connect(client, userdata, rc): print("\nConnected with result code " + str(rc) + "\n") #Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. client.subsc
ribe("/iot/control/") print("Subscribed to iotcontrol") def on_message_iotrl(client, userdata, msg): print("\n\t* Raspberry UPDATED ("+msg.topic+"): " + str(msg.payload)) if msg.payload == "gpio24on": GPIO.output(24, GPIO.HIGH) client.publish("/iot/status", "Relay gpio18on", 2) if msg.pay...
ARMmbed/greentea
src/htrun/host_tests_plugins/module_power_cycle_target.py
Python
apache-2.0
5,959
0.001175
# # Copyright (c) 2021 Arm Limited and Contributors. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # """Power cycle devices using the 'Mbed TAS RM REST API'.""" import os import json import time import requests from .host_test_plugins import HostTestPluginBase class HostTestPluginPowerCycleResetMethod(H...
else: self.print_plugin_error("HOST: Failed to reset device %s" % target_id) return result @staticmethod def __run_request(ip, port, request): headers = {"Content-t
ype": "application/json", "Accept": "text/plain"} get_resp = requests.get( "http://%s:%s/" % (ip, port), data=json.dumps(request), headers=headers ) resp = get_resp.json() if get_resp.status_code == 200: return resp else: return None def load...
segwit/atbcoin-insight
qa/rpc-tests/p2p-feefilter.py
Python
mit
4,317
0.003938
#!/usr/bin/env python3 # Copyright (c) 2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.mininode import * from test_framework.test_framework import BitcoinTestFramework from te...
s = [node1.sendtoaddress(node1.getnewaddress(),
1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Change tx fee rate to 10 sat/byte and test they are no longer received node1.settxfee(Decimal("0.00010000")) [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] sync_memp...
manishgs/pdf-processor
pdftools/PdfInfo.py
Python
mit
1,046
0.008604
import subprocess """ ideas from https://gist.github.com/godber/7692812 """ class PdfInfo: def __init__(self, filepath): self.filepath = filepath self.info = {} self.cmd = "pdfinfo" self.process() def process(self): labels = ['Title', 'Author', 'Creator', 'Producer', '...
utput.splitlines(): for label in labels: if label in line: self.info[label] = self.extract(line) def isEncrypted(self): return False if (self.info['Encrypted'][:2]=="no") else True def extract(self, row): return row.split(':', 1)[1].strip() ...
.strip())
google/ion
ion/dev/replace_strings.py
Python
apache-2.0
3,728
0.005633
# # 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...
'<@(_outputs)', '--input', '<@(_inputs)', ], }, ], """ import optparse import os import re import sys def main(argv): """Entry point. Args: argv: use sys.argv[1:]. See ArgumentParser below. """ parser = optparse.OptionParser() parser.add_option('--input') parser.add_op...
='append', default=[]) options, _ = parser.parse_args(argv) replacement_mapping = {} if options.replacement_mapping is not None: with open(options.replacement_mapping, 'r') as m: replacement_mapping = eval(m.read()) if options.output and not os.path.isdir(os.path.dirname(options.output)): os.ma...
GloryDream/generative_style_transfer
Project/generative_style_transfer/models/generative_model_v2.py
Python
apache-2.0
8,266
0.002662
#!/usr/bin/python # -*- coding:utf8 -*- import os import tensorflow as tf from keras import layers from keras.applications.imagenet_utils import _obtain_input_shape from keras.backend.tensorflow_backend import set_session from keras.engine.topology import get_source_inputs from keras.layers import * from keras.models ...
le_tensor if K.image_data_format() == 'channels_last': bn_axis = 3 else: bn_axis = 1 # TODO: replace BN with instance norm #
content branch x = Conv2D(32, (9, 9), activation='linear', padding='same', name='ct_conv1', strides=(1, 1))(content_input) x = BatchNormalization(axis=bn_axis, name="ct_batchnorm1")(x) x = Activation('relu')(x) x = Conv2D(64, (3, 3), activation='linear', padding='same', name='ct_conv2', strides=(2, 2))...
reyrodrigues/EU-SMS
temba/contacts/search.py
Python
agpl-3.0
10,018
0.002995
from __future__ import unicode_literals import ply.lex as lex import pytz from datetime import timedelta from decimal import Decimal from django.core.exceptions import ObjectDoesNotExist from django.db.models import Q from ply import yacc from temba.utils import str_to_datetime from temba.values.models import Value ...
:param value: the literal value, e.g. "Bob" :return: the query set """ # resolve identifier aliases, e.g. '>' -> 'gt' if identifier in PROPERTY_ALIASES.keys(): identifier = PROPERTY_ALIASES[identifier] if identifier in NON_FIELD_PROPERTIES: if identifier == 'urns__
path' and lexer.org.is_anon: raise SearchException("Cannot search by URN in anonymous org") q = generate_non_field_comparison(identifier, comparator, value) else: from temba.contacts.models import ContactField try: field = ContactField.objects.get(org=lexer.org, key=...
noba3/KoTos
addons/plugin.video.movie25/resources/libs/sports/fitnessblender.py
Python
gpl-2.0
7,228
0.022979
# -*- coding: cp1252 -*- import urllib,urllib2,re,cookielib,string,os,sys import xbmc, xbmcgui, xbmcaddon, xbmcplugin from resources.libs import main #Mash Up - by Mash2k3 2012. from t0mm0.common.addon import Addon from resources.universal import playbackengine, watchhistory addon_id = 'plugin.video.movie25' selfAddo...
link=link.replace('\r','').replace('\n','').replace('\t','').replace('&nbsp;','').replace('–','-') match=re.compile('src="http://www.youtube.com/embed/(.+?).?rel').findall(link) for url in match: url = "plugin://plugin.video.youtube/?path=/root/video&action=play_video&videoid="+url stream_url = ...
de='', year='',img=thumb,infolabels='', watchedCallbackwithParams=main.WatchedCallbackwithParams,imdb_id='') #WatchHistory if selfAddon.getSetting("whistory") == "true": wh.add_item(mname+' '+'[COLOR green]Fitness Blender[/COLOR]', sys.argv[0]+sys.argv[2], infolabels='', img=thumb, fanart='', is_fol...
geonition/geoforms
geoforms/admin.py
Python
mit
17,493
0.009089
from bs4 import BeautifulSoup from django.conf import settings from django.contrib.gis import admin from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse_lazy from django.forms.formsets import formset_factory from django.http import HttpResponseRedirect from django.utils.translation ...
form = TextElementForm def queryset(self, request): return self.model.objects.filter(element_type = 'text') admin.site.register(TextElementModel, TextElementAdmin) class TextareaAdmin(GeoformElementAdmin): """ This is the admin for ad
ding textareas """ form = TextareaForm def queryset(self, request): return self.model.objects.filter(element_type = 'textarea') admin.site.register(TextareaModel, TextareaAdmin) class NumberElementAdmin(GeoformElementAdmin): form = NumberElementForm fieldsets = ( (None, { ...
tensorflow/cloud
src/python/tensorflow_cloud/tuner/vizier_client_ucaip_interface.py
Python
apache-2.0
686
0
# Lint as: python3 # Co
pyright 2021 Google LLC. All Rights Reserved
. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed unde...
vileopratama/vitech
src/addons/account_analytic_default/__openerp__.py
Python
mit
847
0.002361
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Account Analytic Defaults', 'version': '1.0', 'category': 'Accounting', 'description': """ Set default values for yo
ur analytic accounts. ============================================== Allows to automatically select analytic accounts based on criterions: --------------------------------------------------------------------- * Product * Partner * User * Company * Date """, 'website': 'https://www.odoo.com/...
g', 'depends': ['sale_stock'], 'data': [ 'security/ir.model.access.csv', 'security/account_analytic_default_security.xml', 'account_analytic_default_view.xml' ], 'demo': [], 'installable': True, 'auto_install': False, }
ctn-archive/nengo_spinnaker_2014
nengo_spinnaker/assembler.py
Python
mit
6,294
0.000794
import collections import itertools import nengo import pacman103 from .config import Config import connection import ensemble import node import probe import utils class Assembler(object): """The Assembler object takes a built collection of objects and connections and converts them into PACMAN vertices and...
for c in self.connections if c.pre_obj == obj] Assembler.register_connection_builder(connection.generic_connection_builder) Assembler.register_object_builder(ensemble.EnsembleLIF.assemble, ensemble.IntermediateEnsembleLIF) Assembler.register_object_builder(node.FilterVertex.assemble...
node.IntermediateFilter) Assembler.register_object_builder(node.FilterVertex.assemble, node.FilterVertex) Assembler.register_object_builder(probe.DecodedValueProbe.assemble, probe.IntermediateProbe) def vertex_builde...
spirali/kaira
gui/process.py
Python
gpl-3.0
7,102
0.004365
# # Copyright (C) 2010, 2011, 2014 Stanislav Bohm # # This file is part of Kaira. # # Kaira 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 3 of the License, or # (at your option) any...
along with Kaira. If not, see <http://www.gnu.org/licenses/>. # import gtk import socket from subprocess import Popen, PIPE, STDOUT from threading import Thread, Lock class ReadLineThread(Thread): def __init__(self, stream): Thread.__init__(self) self.stream = stream self.lock = Lock(...
lf) def run(self): while True: line = self.stream.readline() if line == "": self.on_exit() return with self.lock: if self.exit_flag: return if not self.on_line(line, self.stream): ...
visdesignlab/TulipPaths
FindPaths0.py
Python
mit
500
0.004
from FindPathsPlugin
import FindPathsPlugin import tulipplugins class FindPaths0(FindPathsPlugin): """ Tulip plugin algorithm which searches for 1-hop paths """ def __init__(self, context): FindPathsPlugin.__init__(self, context, 0) # The line below does the magic to register the plugin to the plugin database # and upda...
mistercrunch/panoramix
tests/integration_tests/dashboards/security/security_dataset_tests.py
Python
apache-2.0
8,417
0.001069
# 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...
get_dashboards_response = self.get_resp(DASHBOARDS_API_URL) # assert self.assertIn(my_owned_dashboard.url, get_dashboards_response) self.assertNotIn(not_my_owned_dashboard.url, get_dashboards_response) def test_get_dashboards__owners_can_view_empty_dashboard(self): # arrange...
urity_manager.find_user("gamma") self.login(gamma_user.username) # act get_dashboards_response = self.get_resp(DASHBOARDS_API_URL) # assert self.assertNotIn(dashboard_url, get_dashboards_response) def test_get_dashboards__users_can_view_favorites_dashboards(self): ...
rockneurotiko/wirecloud
src/wirecloud/platform/wiring/views.py
Python
agpl-3.0
6,563
0.00381
# -*- coding: utf-8 -*- # Copyright (c) 2012-2016 CoNWeT Lab., Universidad Politécnica de Madrid # This file is part of Wirecloud. # Wirecloud is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either v...
rator['preferences'].keys()) - set(operator['preferences'].keys()) updated_preferences = set(operator['preferences'].keys()).intersection(old_operator['preferences'].keys()) else:
# New operator added_preferences = operator['preferences'].keys() removed_preferences = () updated_preferences = () for preference_name in added_preferences: if operator['preferences'][preference_name].get('readonly', False) or ...
napalm-automation/napalm-yang
napalm_yang/models/openconfig/vlans/vlan/members/member/interface_ref/__init__.py
Python
apache-2.0
5,581
0.001254
# -*- coding: utf-8 -*- from operator import attrgetter from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType from pyangbind.lib.yangtypes import RestrictedClassType from pyangbind.lib.yangtypes import TypedListType from pyangbind.lib.yangtypes import YANGBool from pyangbind.lib.yangtypes import YANGListTy...
six.PY3: import builtins as __builtin__ long = int elif six.PY2: import __builtin__ from . import state class interface_ref(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-vlan - based on the path /vlans/vlan/members/member/interface...
r element of the container is represented as a class variable - with a specific YANG type. YANG Description: Reference to an interface or subinterface """ __slots__ = ("_path_helper", "_extmethods", "__state") _yang_name = "interface-ref" _pybind_generated_by = "container" def __init__(self,...
swiftstack/swift3-stackforge
swift3/test/unit/test_obj.py
Python
apache-2.0
47,051
0.000043
# Copyright (c) 2014 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to ...
:hmac', 'Date': self.get_date_header()}) self.swift.register('HEAD', '/v1/AUTH_test/bucket/object', swob.HTTPServiceUnavailable, {}, None) status, headers, body = self.call_swift3(req) self.assertEqual(status.split()[0], '500') ...
self._test_object_GETorHEAD('HEAD') def _test_object_HEAD_Range(self, range_value): req = Request.blank('/bucket/object', environ={'REQUEST_
pombredanne/dGit
legit/helpers.py
Python
bsd-3-clause
618
0.001618
# -*- coding: utf-8 -*- """ legit.helpers ~~~~~~~~~~~~~ Various Python helpers. """ import os import platform _platform = platform.system().lower() is_osx = (_platform == 'darwin') is_win = (_platform == 'windows') is_lin = (_platform == 'linux') def find_path_above(*names): """Attempt to l
ocate given path by searching parent dirs.""" path = '.' while os.path.split(os.path.abspath(path))
[1]: for name in names: joined = os.path.join(path, name) if os.path.exists(joined): return os.path.abspath(joined) path = os.path.join('..', path)
dandfmd/Linfilesync
utils.py
Python
apache-2.0
2,486
0.020515
import json,os,shelve import asyncio,sys DATAFILENAME="data" def set_user_id(new_id): _local_data["user_id"]=new_id def set_login_token(token): _local_data["login_token"]=token def load_data(): global _l
ocal_data if(os.path.exists(os.path.join(get_current_path(),DATAFILENAME))): with open(os.path.join(get_current_path(),DATAFILENAME), 'r') as f:
try: _local_data=json.loads(f.read()) except: _local_data={} else:_local_data={} def save_data(): with open(os.path.join(get_current_path(),DATAFILENAME), 'w') as f: f.write(json.dumps(_local_data)) def get_user_id(): return _local_data.get("user_id") de...
kitaro-tn/msgiver
_docs/conf.py
Python
mit
4,844
0.000206
# -*- coding: utf-8 -*- # # Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup ------------------------------------------------------------...
MLHelp output -
-------------------------------------------- # Output file base name for HTML help builder. htmlhelp_basename = 'msgiverdoc' # -- Options for LaTeX output ------------------------------------------------ latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', ...
altanawealth/django-otp
django_otp/decorators.py
Python
bsd-2-clause
1,053
0.003799
from __future__ import absolute_import, division, print_function, unicode_literals from django.contrib.auth.decorators import user_passes_test from django_otp import user_has_device from django_otp.conf import settings def otp_required(view=None, redirect_field_name='next', login_url=None, if_configured=False): ...
with no confirmed OTP devices will be allowed. Default is ``False``. :type if_configured: bool """ if login_url is None: login_url = settings.OTP_LOGIN_URL def test(user): return user.is_verified() or (if_configured and user.is_authenticated() and not user_has_device(user)) ...
s None) else decorator(view)
russell/slick
slick/__init__.py
Python
gpl-3.0
74
0.027027
# impor
t common __version__ = common.version del commo
n import settings
tulsluper/sanscript
apps/fc/scripts/san_db.py
Python
gpl-3.0
1,228
0.001629
#!/usr/bin/env python3 import os import logging from datetime import datetime from settings import JSONDIR from defs import load_data from san_env import get_apps debug_records_flag = False def save(appname, relations): apps = get_apps() for filename, modelname, filters in relations: records = load_...
jects.all().delete() elif filters.get('before_delete'): model.objects.filter(**filters['before_delete']).delete() if debug_records_flag is False: model.objects.bulk_create([model(*
*record) for record in records]) else: for record in records: try: model(**record).save() except: print('== {} =='.format(modelname)) for key in sorted(record.keys()): print(key, recor...
zackchase/sparse-multilabel-sgd
src/sgd2.py
Python
mit
29,756
0.006486
#!/apollo/env/MLEnvImprovement/bin/python ''' Created on Jul 22, 2014 @author: galena This code implements proximal stochastic gradient descent with AdaGrad for very large, sparse, multilabel problems. The weights are stored in a sparse matrix structure that permits changing of the sparsity pattern on the fly, via ...
eta g *= -etaVec pos = 0 for xI in range(xInds.size):
x
jakeogh/anormbookmarker
anormbookmarker/test/tests/Tag/two_single_char_words.py
Python
mit
876
0
#!/usr/bin/env python3 from anormbookmarker.test.test_enviroment import * with self_contained_session(CONFIG.database_timestamp) as session: BASE.metadata.create_all(session.bind) # make a tag to make an alias to aa = Tag.construct(session=session, tag='a a') session.commit() db_result = [('select CO...
COUNT(*) from tag_relationship;', 0), ('select C
OUNT(*) from tagbookmarks;', 0), ('select COUNT(*) from tagword;', 2), ('select COUNT(*) from word;', 1), ('select COUNT(*) from wordmisspelling;', 0)] check_db_result(config=CONFIG, db_result=db_result)
jrversteegh/softsailor
deps/swig-2.0.4/Examples/test-suite/python/li_boost_shared_ptr_runme.py
Python
gpl-3.0
18,306
0.003988
import li_boost_shared_ptr import gc debug = False # simple shared_ptr usage - created in C++ class li_boost_shared_ptr_runme: def main(self): if (debug): print "Started" li_boost_shared_ptr.cvar.debug_shared = debug # Change loop count to run for a long time to monitor memory loopCount = 1 ...
", val) self.verifyCount(1, k) self.verifyCount(1, kret) # derived pass by ref k = li_boost_shared_ptr.KlassDerived("me oh my") kret = li_boost_shared_ptr.derivedreftest(k) val = kret.getValue() self.verifyValue("me oh my derivedreftest-Derived", val) self.verifyCount(
1, k) self.verifyCount(1, kret) # //////////////////////////////// Derived and base class mixed //////////////////////////////////////// # pass by shared_ptr (mixed) k = li_boost_shared_ptr.KlassDerived("me oh my") kret = li_boost_shared_ptr.smartpointertest(k) val = kret.getValue() self.ve...
JayVora-SerpentCS/vertical-hotel
hotel/wizard/sale_make_invoice_advance.py
Python
agpl-3.0
2,320
0
# -*- coding: utf-8 -*- # See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class SaleAdvancePaymentInv(models.TransientModel): _inherit = "sale.advance.payment.inv" @api.model def _get_advance_payment(self): ctx = self.env.context.copy() if ...
= self.env['hotel.folio'] hotel = hotel_fol.browse(self._context.get('active_ids', [])) ctx.update({'active_ids': [hotel.order_id.id],
'active_id': hotel.order_id.id}) return super(SaleAdvancePaymentInv, self.with_context(ctx))._get_advance_payment_method() advance_payment_method = fields.Selection([('delivered', 'Invoiceable lines'), ...
andyh616/cloudbrain
cloudbrain/apiservice/rest_api_server.py
Python
agpl-3.0
6,641
0.004367
import time import json import random from flask import Flask, request, current_app, abort from functools import wraps from cloudbrain.utils.metadata_info import (map_metric_name_to_num_channels, get_supported_devices, get_metrics_...
g_name": "label_1",
"metadata": {}, "start": int(time.time() * 1000) - 10, "end": int(time.time() * 1000) } return tag @app.route('/api/%s/users/<string:user_id>/tags' % _API_VERSION, methods=['GET']) @support_jsonp def get_tags(user_id): """Retrieve all tags for a specific user """ ...
jack51706/malware-analysis
Python/CherryPicker/cherryConfig.py
Python
gpl-3.0
3,456
0.000868
import sys import re # Copyright # ========= # Copyright (C) 2015 Trustwave Holdings, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public Lice
nse as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be
useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/license...
DavideCanton/Python3
num/pijavskij.py
Python
gpl-3.0
830
0.004819
from operator import itemgetter __author__ = 'davide' def pairwise(l): for t in zip(l, l[1:]): yield t def pijavskij(f, L, a, b, eps=1E-5): l = [(a, f(a)), (b, f(b))] while True: imin, Rmin, xmin = -1, float("inf"), -1 for i, t in enumerate(pairwise(l)):
(xi, fi), (xj, fj) = t R = (fi + fj - L * (xj - xi)) / 2 if R < Rmin: imin = i Rmin = R xmin = (xi + xj) / 2 - (fj - fi) / (2 * L) if l[imin + 1][0] - l[imin][0] < eps:
return l[imin], l[imin + 1] l.append((xmin, f(xmin))) l.sort(key=itemgetter(0)) print(l) if __name__ == "__main__": f = lambda x: x ** 4 t = pijavskij(f, 50, -100, 100, eps=1E-10) print(t)
DigFarmer/aircraft
tools/building.py
Python
gpl-2.0
23,177
0.010398
import os import sys import string from SCons.Script import * from utils import _make_path_relative BuildOptions = {} Projects = [] Rtt_Root = '' Env = None class Win32Spawn: def spawn(self, sh, escape, cmd, args, env): # deal with the cmd build-in commands which cannot be used in # subprocess.Po...
tconfig.EXEC_PATH.replace('bin40', 'armcc/bin') Env['LINKFLAGS']=Env['LINKFLAGS'].replace('RV31', 'armcc') # reset AR co
mmand flags env['ARCOM'] = '$AR --create $TARGET $SOURCES' env['LIBPREFIX'] = '' env['LIBSUFFIX'] = '.lib' env['LIBLINKPREFIX'] = '' env['LIBLINKSUFFIX'] = '.lib' env['LIBDIRPREFIX'] = '--userlibpath ' # patch for win32 spawn if env['PLATFORM'] == 'win32':...
rwl/PyCIM
CIM15/IEC61970/Wires/DCLineSegment.py
Python
mit
2,414
0.002486
# Copyright (C) 2010-2011 Richard Lincoln # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish...
= ["dcSegmentInductance", "dcSegmentResistance"] _attr_types = {"dcSegmentInduc
tance": float, "dcSegmentResistance": float} _defaults = {"dcSegmentInductance": 0.0, "dcSegmentResistance": 0.0} _enums = {} _refs = [] _many_refs = []
suhorng/vm14hw1
roms/seabios/tools/layoutrom.py
Python
gpl-2.0
15,541
0.00148
#!/usr/bin/env python # Script to analyze code and arrange ld sections. # # Copyright (C) 2008 Kevin O'Connor <[email protected]> # # This file may be distributed under the terms of the GNU GPLv3 license. import sys # LD script headers/trailers COMMONHEADER = """ /* DO NOT EDIT! This is an autogenerated file. See...
)" % ( name, align)
sys.exit(1) # Find freespace in fixed address area fixedsections.sort() # fixedAddr = [(freespace, sectioninfo), ...] fixedAddr = [] for i in range(len(fixedsections)): fixedsectioninfo = fixedsections[i] addr, section = fixedsectioninfo if i == len(fixedsections) - 1: ...
hdmy/LagouSpider
dataMining/train_data.py
Python
mit
756
0.005952
# -*- coding: utf-8 -*- """ Created on Sun Apr 23 11:27:24 2017 @author: hd_mysky """ import pymongo as mongo import pandas as pd import os from transform import harmonize_data BASE_DIR = os.path.dirname(__file__) #获取当前文件的父目录绝对路径 file_p
ath = os.path.join(BASE_DIR,'dataset','source_simple.csv') conn = mongo.MongoClient('mongodb://localhost:27017') jobs = conn.lagou.jobs cursor
= jobs.find({'positionTag': '技术'}) fields = ['workYear', 'education', 'city', 'positionTag', 'financeStage', 'companySize', 'salaryAvg'] train = pd.DataFrame(list(cursor), columns=fields) train_data = harmonize_data(train) train_data.to_csv(file_path) print('——————————数据转换成功——————————')
neighbordog/deviantart
tests/test_api.py
Python
mit
1,335
0.003745
from __future__ i
mport absolute_import import unittest import deviantart from .helpers import mock_response, optional from .api_credentials import CLIENT_ID, CLIENT_SECRET class ApiTest(unittest.TestCase): @optional(CLIENT_ID == "", mock_response('token')) def setUp(self): self.da = deviantart.Api(CLIENT_ID, CLIENT_...
onal(CLIENT_ID == "", mock_response('user_profile_devart')) def test_get_user(self): user = self.da.get_user("devart") self.assertEqual("devart", user.username) self.assertEqual("devart", repr(user)) @optional(CLIENT_ID == "", mock_response('deviation')) def test_get_deviation(self)...
GoogleCloudPlatform/buildpacks
builders/testdata/python/functions/with_env_var/main.py
Python
apache-2.0
705
0.004255
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. def testFunction(request): return "PASS" import os # os.environ["FOO"] i
s only available at runtime. print(os.environ["FOO"])
tomtor/QGIS
tests/src/python/test_qgsimagecache.py
Python
gpl-2.0
5,431
0.003498
# -*- coding: utf-8 -*- """QGIS Unit tests for QgsImageCache. .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. """ __a...
r.do_GET(self) class TestQgsImageCache(unittest.TestCase): @classmethod def setUpClass(cls): # Bring up a simple HTTP server, for remote SVG tests os.chdir(unitTestDataPath() + '') handler = SlowHTTPRequestHandler cls.httpd = socketserver.TCPServer(('localh
ost', 0), handler) cls.port = cls.httpd.server_address[1] cls.httpd_thread = threading.Thread(target=cls.httpd.serve_forever) cls.httpd_thread.setDaemon(True) cls.httpd_thread.start() def setUp(self): self.report = "<h1>Python QgsImageCache Tests</h1>\n" self.fetch...
mgracer48/panda3d
direct/src/controls/TwoDWalker.py
Python
bsd-3-clause
2,450
0.004082
""" TwoDWalker.py is for controling the avatars in a 2D Scroller game environment. """ from GravityWalker import * from panda3d.core import ConfigVariableBool class TwoDWalker(GravityWalker): """ The TwoDWalker is primarily for a 2D Scroller game environment. Eg - Toon Blitz minigame. TODO: This class is...
utton states: jump = inputState.isSet("forward") if self.lifter.isOnGround(): if self.isAirborne: self.isAirborne = 0 assert self.debugPrint("isAirborne 0 due to isOnGround() true") impact = self.lifter.getImpactVelocity() messe...
isAirborne == 0 self.priorParent = Vec3.zero() else: if self.isAirborne == 0: assert self.debugPrint("isAirborne 1 due to isOnGround() false") self.isAirborne = 1 return Task.cont def jumpPressed(self): """This function should be called f...
jmchrl/opb
grammalecte/graphspell/char_player.py
Python
gpl-3.0
10,597
0.002542
# list of similar chars # useful for suggestion mechanism import re import unicodedata _xTransCharsForSpelling = str.maketrans({ 'ſ': 's', 'ffi': 'ffi', 'ffl': 'ffl', 'ff': 'ff', 'ſt': 'ft', 'fi': 'fi', 'fl': 'fl', 'st': 'st' }) def spellingNormalization (sWord): return unicodedata.normalize("NFC", sWord.tran...
lmnñpqrstvwxzBCÇDFGHJKLMNÑPQRSTVWXZ") aDouble = set("bcdfjklmnprstzBCDFJKLMNPRSTZ") # letters that may be used twice successively # Similar chars d1to1 = { "1": "liîLIÎ", "2": "zZ", "3": "eéèêEÉÈÊ", "4": "aàâAÀÂ", "5": "sgSG", "6": "bdgBDG", "7": "ltLT", "8": "bB", "9": "gbdGBD",...
"á": "aAàÀâÂáÁäÄāĀæÆ", "Á": "AaÀàÂâÁáÄäĀ⯿", "ä": "aAàÀâÂáÁäÄāĀæÆ", "Ä": "AaÀàÂâÁáÄäĀ⯿", "æ": "æÆéÉaA", "Æ": "ÆæÉéAa", "b": "bB", "B": "Bb", "c": "cCçÇsSkKqQśŚŝŜ", "C": "CcÇçSsKkQqŚśŜŝ", "ç": "cCçÇsSkKqQśŚŝŜ", "Ç": "CcÇçSsKkQqŚśŜŝ", "d": "dDðÐ", "D": "DdÐð"...
daureg/illalla
diary/manage.py
Python
mit
2,888
0.003809
#! /usr/bin/python2 # vim: set fileencoding=utf-8 from dateutil.parser import parse from subprocess import check_output from shutil import copy import datetime import sys import os.path import isoweek DATE_FORMAT = '%Y%m%d' START = "
""\documentclass[a4paper,oneside,draft, notitlepage,11pt,svgnames]{scrreprt} \\newcommand{\workingDate}{\\today} \input{preambule} \\beg
in{document} """ END = """ \printbibliography{} \end{document}""" MD_ACTIVITY = """# Activity {.unnumbered} ~~~~ """ def create(date): filename = date.strftime(DATE_FORMAT) month = date.strftime('%B') day = date.strftime('%d') with open('template.tex', 'r') as t: content = t.read() co...
privateip/ansible
test/units/module_utils/common/arg_spec/test_validate_invalid.py
Python
gpl-3.0
3,830
0.002872
# -*- coding: utf-8 -*- # Copyright (c) 2021 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type import pytest from ansible.module_utils.common.arg_spec import ArgumentSpecVa...
: {}}, { 'badparam': '', 'another': '', }, { 'name': None, 'badparam': '', 'another': '', }, set(('another', 'badparam')), "another, badparam. Supported parameters include: name.", ), ( 'invalid-e...
"Elements value for option 'numbers' is of type <class 'dict'> and we were unable to convert to int: <class 'dict'> cannot be converted to an int" ), ( 'required', {'req': {'required': True}}, {}, {'req': None}, set(), "missing required arguments: req" ...
DmitryDmitrienko/usecasevstu
version_info.py
Python
apache-2.0
710
0.011268
# -*- coding: utf-8 -*- VSVersionInfo( ffi=FixedFileInfo( filevers=(4, 0, 0, 0), prodvers=(4, 0, 0, 0),
mask=0x3f, flags=0x0, OS=0x4, fileType=0x1, subtype=0x0, date=(0, 0) ), kids=[ StringFileInfo( [ StringTable( '040904b0', [StringStruct('CompanyName', u'CommandBrain'), StringStruct('FileDescription',...
]), VarFileInfo([VarStruct('Translation', [1033, 1200])]) ] )
Catch-up-TV-and-More/plugin.video.catchuptvandmore
resources/lib/channels/it/paramountchannel_it.py
Python
gpl-2.0
775
0.00129
# -*- coding: utf-8 -*- # Copyright: (c) 2018, SylvainCecchetto # GNU General Public License v2.0+ (see LICENSE.txt or https://www.gnu.org/licenses/gpl-2.0.txt) # This file is part of Catch-up TV & More from __future__ import unicode_literals import re from codequick import Resolver import urlquick from resources.l...
TO D
O # Add Replay URL_LIVE = 'https://www.paramountchannel.it/tv/diretta' @Resolver.register def get_live_url(plugin, item_id, **kwargs): resp = urlquick.get(URL_LIVE, max_age=-1) video_uri = re.compile(r'uri\"\:\"(.*?)\"').findall(resp.text)[0] account_override = 'intl.mtvi.com' ep = 'be84d1a2' r...
lahwaacz/tvnamer
tvnamer/__init__.py
Python
unlicense
275
0
#!/usr/bin/env python """tvnamer -
Automagical TV episode renamer Uses data from www.thetvdb.com (via tvdb_api) to rename TV episode files from "some.show.name.s01e01.blah.avi" to "Some Show Nam
e - [01x01] - The First.avi" """ __version__ = "3.0.0" __author__ = "dbr/Ben"
mlperf/training_results_v0.7
NVIDIA/benchmarks/transformer/implementations/pytorch/fairseq/optim/adam.py
Python
apache-2.0
7,859
0.00229
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import math import torch import to...
float, optional): weight decay (L2 penalty) (default: 0) amsgrad (boolean
, optional): whether to use the AMSGrad variant of this algorithm from the paper `On the Convergence of Adam and Beyond`_ .. _Adam\: A Method for Stochastic Optimization: https://arxiv.org/abs/1412.6980 .. _On the Convergence of Adam and Beyond: https://openreview.net/forum?id=ryQu7...
blefaudeux/Pinta
pinta/model/model_rnn.py
Python
gpl-3.0
2,323
0.001722
import logging from typing import List import numpy as np import torch import torch.nn as nn from pinta.model.model_base import NN LOG = logging.getLogger("ConvRNN") class ConvRNN(NN): """ Combination of a convolutional front end and an RNN (GRU) layer below >> see https://gist.github.com/spro/c87cc706...
dden_size, self.output_size) # Load from trained NN if required if filename is not None: self._valid = self.load(filename) if self._valid: return LOG.warning("Could not load the specified net, computing it from scratch") def forward(self, inputs...
hidden=None): # Run through Conv1d and Pool1d layers r1 = self.relu(self.conv1(inputs)) r2 = self.relu(self.conv2(r1)) # GRU/LSTM layer expects [batch, seq, inputs] r2 = r2.transpose(1, 2) output_rnn, hidden_out = self.gru(r2, hidden) output = self.out(output_r...
comp-imaging/ProxImaL
proximal/utils/__init__.py
Python
mit
24
0
from .utils
import Imp
l
wizardxbl/rtt-stm32f10x
tools/win32spawn.py
Python
gpl-2.0
5,808
0.003616
import os import threading import Queue # Windows import import win32file import win32pipe import win32api import win32con import win32security import win32process import win32event class Win32Spawn(object): def __init__(self, cmd, shell=False): self.queue = Queue.Queue() self.is_terminated = Fal...
se: assert False, "Unexpected return from WaitForMultipleObjects" # Wait for job to finish. Since this method blocks, it can to be called from another thread. # If the application wants to kill the process, it should call kill_subprocess(). def wait(self):
if not self.__wait_for_child(): # it's been killed result = False else: # normal termination self.exit_code = win32process.GetExitCodeProcess(self.h_process) result = self.exit_code == 0 self.close() self.is_terminated = True ...
Clpsplug/thefuck
tests/shells/test_tcsh.py
Python
mit
2,199
0
# -*- coding: utf-8 -*- import pytest from thefuck.shells.tcsh import Tcsh @pytest.mark.usefixtures('isfile', 'no_memoize', 'no_cache') class TestTcsh(object): @pytest.fixture def shell(self): return Tcsh() @pytest.fixture(autouse=True) def Popen(self, mocker): mock = mocker.patch('t...
rt 'alias fuck' in shell.app_alias('fuck') assert 'alias FUCK' in shell.app_alias('FUCK') assert 'thefuck' in shell.app_alias('fuck') def test_get_history(self, history_lines, shell): history_lines(['ls', 'rm']) assert list(shell.get_history()) == ['ls', 'rm'] def test_how_to_c...
fig_exists.return_value = True assert shell.how_to_configure().can_configure_automatically def test_how_to_configure_when_config_not_found(self, shell, config_exists): config_exists.return_value = False assert not shell.how_to_configure()....
google/ml-fairness-gym
distributions.py
Python
apache-2.0
3,400
0.01
# coding=utf-8 # Copyright 2022 The ML Fairness Gym Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
ple(self, rng): return rng.normal(self.mean, self.std) @attr.s class Bernoulli(Distribution): """A Bernoulli Distribution.""" p = attr.ib(validator=[_check_in_zero_one_range]) def __attrs_post_init__(self): self.dim = 1 def sample(self, rng): return rng.rand() < self.p @attr.s class Constant(...
def __attrs_post_init__(self): self.dim = len(self.mean) def sample(self, rng): del rng # Unused. return self.mean
wufangjie/leetcode
546. Remove Boxes.py
Python
gpl-3.0
6,064
0.001484
from collections import defaultdict class Solution(object): def removeBoxes(self, boxes): """ :type boxes: List[int] :rtype: int """ unq, cnt = [], [] for b in boxes: if not unq or b != unq[-1]: unq.append(b) cnt.append(1)...
# for i, b in enumerate(boxes): # if i == 0 or b != boxes[i - 1]: # dct[b].append([i, i+1]) # pre = i # else: # dct[b][-1][1] += 1 # idx, to_remove = set(), set() # ret = 0 # for k, v...
to_remove.add(k) # lo, hi = v[0] # idx.update(range(lo, hi)) # ret += (hi - lo) ** 2 # if ret: # return ret + dfs( # *(boxes[i] for i in range(len(boxes)) if i not in idx)) # for k, vs in dct.ite...
3dfxsoftware/cbss-addons
res_partner_btree/model/res_partner_btree.py
Python
gpl-2.0
1,459
0
# -*- encoding: utf-8 -*- ########################################################################### # Module Writen to OpenERP, Open Source Management Solution # # Copyright (c) 2013 Vauxoo - http://www.vauxoo.com/ # All Rights Reserved. # info Vauxoo ([email protected]) ####################################...
bute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be us
eful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see...
lennepkade/dzetsaka
scripts/domainAdaptation.py
Python
gpl-3.0
12,927
0.000851
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Mar 23 11:24:38 2018 @author: nkarasiak """ try: # if use in Qgis 3 from . import function_dataraster as dataraster from .mainfunction import pushFeedback except BaseException: import function_dataraster as dataraster from mainfunc...
s import mean_squared_error from itertools import product from sklearn.metrics import ( f1_score, cohen_kappa_score, accuracy_score) except BaseException: raise ImportError('Please install itertools and scikit-learn') self.transportAlgorithm = transpo...
ams if scaler: from sklearn.preprocessing import MinMaxScaler self.scaler = MinMaxScaler(feature_range=(-1, 1)) self.scalerTarget = MinMaxScaler(feature_range=(-1, 1)) else: self.scaler = scaler def learnTransfer(self, Xs, ys, Xt, yt=None): "...
manti-by/Churchill
churchill/api/v1/shots/views.py
Python
bsd-3-clause
2,706
0.00037
from datetime import timedelta from django.conf import settings from django.utils.timezone import now from rest_framework import status, pagination from rest_framework.generics import CreateAPIView, DestroyAPIView, ListAPIView from rest_framework.response import Response from churchill.api.v1.shots.serializers import...
ated_data) serializer = self.get_ser
ializer(shot) return Response(serializer.data, status=status.HTTP_201_CREATED) def destroy(self, request, *args, **kwargs): delete_shot(request.user, request.data["id"]) return Response() class ShotsItemPagination(pagination.PageNumberPagination): page_size = 100 class ShotsItemView...
rohitranjan1991/home-assistant
tests/components/modbus/test_binary_sensor.py
Python
mit
7,895
0.000633
"""Thetests for the Modbus sensor component.""" import pytest from homeassistant.components.binary_sensor import DOMAIN as SENSOR_DOMAIN from homeassistant.components.modbus.const import ( CALL_TYPE_COIL, CALL_TYPE_DISCRETE, CONF_INPUT_TYPE, CONF_LAZY_ERROR, CONF_SLAVE_COUNT, ) from homeassistant.c...
, { CONF_BINARY_SENSORS: [ { CONF_NAME: TEST_ENTITY_NAME, CONF_ADDRESS: 51, CONF_SLAVE: 10, CONF_INPUT_TYPE: CALL_TYPE_DISCRETE, CONF_DEVICE_CLASS: "door", CONF_LAZ...
bus): """Run config test for binary sensor.""" assert SENSOR_DOMAIN in hass.config.components @pytest.mark.parametrize( "do_config", [ { CONF_BINARY_SENSORS: [ { CONF_NAME: TEST_ENTITY_NAME, CONF_ADDRESS: 51, ...
sthalik/git-cola
cola/widgets/standard.py
Python
gpl-2.0
19,289
0.000259
from __future__ import division, absolute_import, unicode_literals import time from qtpy import QtCore from qtpy import QtGui from qtpy import QtWidgets from qtpy.QtCore import Qt from qtpy.QtCore import Signal from qtpy.QtWidgets import QDockWidget from .. import core from .. import gitcfg from .. import qtcompat f...
r view save/restor
e""" result = True try: self.resize(state['width'], state['height']) except: result = False try: self.move(state['x'], state['y']) except: result = False try: if state['maximized']: self.showMaxim...
turbokongen/home-assistant
homeassistant/components/ozw/fan.py
Python
apache-2.0
2,383
0.001259
"""Support for Z-Wave fans.""" import math from homeassistant.components.fan import ( DOMAIN as FAN_DOMAIN, SUPPORT_SET_SPEED, FanEntity, ) from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.util.percentage import ( percentag...
self, speed=None, percentage=None, preset_mode=None, **kwargs ): """Turn the device on.""" await self.async_set_percentage(percentage) async def async_turn_off(self, **kwargs): """Turn the device off.""" self.values.primary.send_value(0) @property def is_on(sel...
n (speed above 0).""" return self.values.primary.value > 0 @property def percentage(self): """Return the current speed. The Z-Wave speed value is a byte 0-255. 255 means previous value. The normal range of the speed is 0-99. 0 means off. """ return ranged_value_...
Numergy/openvsd
open_vsdcli/vsd_metadata.py
Python
apache-2.0
9,596
0
from open_vsdcli.vsd_common import * @vsdcli.command(name='metadata-list') @click.option('--entity', metavar='<name>', help="Can be any entity in VSD") @click.option('--id', metavar='<ID>', help="ID of the entity") @click.option('--global', 'is_global', is_flag=True, help="Show global metadata instead o...
TagIDs'] = ctx.obj['nc'].get(request)[0]['metadataTagIDs'] for t in tag: params['metadataTagIDs'].append(t) ctx.obj['nc'].put(request, params)
result = ctx.obj['nc'].get(request)[0] print_object(result, only=ctx.obj['show_only'], exclude=['blob']) @vsdcli.command(name='metadata-remove-tag') @click.argument('metadata-id', metavar='<metadata ID>', required=True) @click.option('--tag', metavar='<ID>', multiple=True, required=True, ...
saitoha/termprop
__init__.py
Python
mit
1,329
0.015049
#!/usr/bin/env python # -*- coding: utf-8 -*- # # ***** BEGIN LICENSE BLOCK ***** # Copyright (C) 2012-2014, Hayaki Saito # # Permission is hereby granted, free of charge, to any person obtain
ing a # copy of this
software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do s...
apache/incubator-airflow
tests/always/test_project_structure.py
Python
apache-2.0
17,394
0.005577
# 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...
ved from deprecated list"): expected_missing_modules = {pair[0] for pair in expected_missing_providers_modules} removed_deprecated_module = expected_missing_modules - modules_files if removed_deprecated_module: self.fail( "You've
removed a deprecated module:\n" f"{removed_deprecated_module}" "\n" "Thank you very much.\n" "Can you remove it from the list of expected missing modules tests, please?" ) def get_imports_from_file(filepath: str): wit...
stadtgestalten/stadtgestalten
grouprise/features/polls/migrations/0012_auto_20180104_1149.py
Python
agpl-3.0
437
0
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2018-01-04 10:49 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration):
dependencies = [ ('polls', '0011_remove_vote_endorse'), ] opera
tions = [ migrations.RenameField( model_name='simplevote', old_name='endorse_new', new_name='endorse', ), ]
satishgoda/adaofsw
tutorials/flashcard/sandbox/wordlists/data1.py
Python
mit
633
0.007899
# http://www.k12reader.com/dolch-word-list-sorted-alphabetically-by-grade-with-nouns/ f = open("da
ta1.txt") header = f.readline() from collections import OrderedDict database = OrderedDict() for item in header.split(): database[item] = [] for line in f.readlines(): items = line.rstrip().split('\t') for index, item in enumera
te(items): if not item: continue # Since there are two colums for nouns # And we collapsed into one if index > 5: index = 5 category = database.keys()[index] database[category].append(item)
rmarkello/pyls
pyls/tests/conftest.py
Python
gpl-2.0
1,115
0
# -*- coding: utf-8 -*- import numpy as np import pytest import pyls @pytest.fixture(scope='session') def testdir(tmpdir_factory): data_dir = tmpdir_factory.mktemp('data') return str(data_dir) @pytest.fixture(scope='session') def mpls_results(): Xf = 1000 subj = 100 rs = np.random.RandomState(1...
) return pyls.meancentered_pls(rs.rand(subj, Xf), n_cond=2, n_perm=10, n_boot=10, n_split=10) @pytest.fixture(scope='session') def bpls_results(): Xf = 1000 Yf = 100 subj = 1
00 rs = np.random.RandomState(1234) return pyls.behavioral_pls(rs.rand(subj, Xf), rs.rand(subj, Yf), n_perm=10, n_boot=10, n_split=10) @pytest.fixture(scope='session') def pls_inputs(): return dict(X=np.random.rand(100, 1000), Y=np.random.rand(100, 100), grou...
jacchwill/will-minecraft
1003.py
Python
gpl-3.0
552
0.047101
from mcpi.minecraft import Minecraft from time import sleep mc = Minecraft.create() class mic: x=0 y=0 z=0 u=1 def usid(self): t=mc.getPlayerEntityIds() print t def uspos(self,wkj): self.x,self.y,self.z = mc.e
ntity.getPos(wkj)
print self.x,self.y,self.z def wdfe(self,item): mc.setBlock(self.x,self.y,self.z, item) def tnt(self,item): mc.setBlock(self.x,self.y,self.z, item,1) s=mic() s.usid() #s.uspos(57369) s.uspos(1) s.wdfe(46) #s.uspos(20514)
Jet-Streaming/gyp
test/win/gyptest-cl-function-level-linking.py
Python
bsd-3-clause
1,647
0.010322
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Make sure function-level link
ing setting is extracted properly. """ import TestGyp import sys if sys.platform == 'win32': test = TestGyp.TestGyp(formats=['msvs', 'ninja'])
CHDIR = 'compiler-flags' test.run_gyp('function-level-linking.gyp', chdir=CHDIR) test.build('function-level-linking.gyp', test.ALL, chdir=CHDIR) def CheckForSectionString(binary, search_for, should_exist): output = test.run_dumpbin('/headers', binary) if should_exist and search_for not in outpu...
uppsaladatavetare/foobar-api
src/wallet/migrations/0006_auto_20170130_1430.py
Python
mit
899
0.001112
# -*- coding: utf-8 -*- # G
enerated by Django 1.9.12 on 2017-01-30 14:30 from __future__ import unicode_literals import enum from django.db import migrations import enumfields.fields class TrxType(enum.Enum): FINALIZED = 0 PENDING = 1 CANCELLATION = 2 class TrxStatus(enum.Enum): PENDING = 0 FINALIZED = 1 REJECTED = 2...
60309_1722'), ] operations = [ migrations.AlterField( model_name='wallettransaction', name='trx_status', field=enumfields.fields.EnumIntegerField(default=1, enum=TrxStatus), ), migrations.AlterField( model_name='wallettransaction', ...
deepmind/deepmind-research
nfnets/resnet.py
Python
apache-2.0
7,567
0.003965
# Copyright 2021 DeepMind Technologies Limited. 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 ...
t self.preactivation: out = self.activation(self.initial_bn(out, is_training, test_local_stats)) out = hk.max_pool(out, window_shape=(1, 3, 3, 1), strides=(1, 2, 2, 1), padding='SAME') if return_metrics: outputs.update(base.signal_metrics(out, 0)) # Blocks for i, b
lock in enumerate(self.blocks): out, res_var = block(out, is_training, test_local_stats) if return_metrics: outputs.update(base.signal_metrics(out, i + 1)) outputs[f'res_avg_var_{i}'] = res_var if self.preactivation: out = self.activation(self.final_bn(out, is_training, test_local_...
wronk/mne-python
mne/tests/test_docstring_parameters.py
Python
bsd-3-clause
5,347
0
# TODO inspect for Cython (see sagenb.misc.sageinspect) from __future__ import print_function from nose.plugins.skip import SkipTest from nose.tools import assert_true from os import path as op import sys import inspect import warnings import imp from pkgutil import walk_packages from inspect import getsource import...
ames)))) if not any(d in name_ for d in _docstring_ignores) and \ 'deprecation_wrapped' not in func.__code__.c
o_name: incorrect += [name_ + ' arg mismatch: ' + bad] else: for n1, n2 in zip(param_names, args): if n1 != n2: incorrect += [name_ + ' ' + n1 + ' != ' + n2] return incorrect def test_docstring_parameters(): """Test module docsting formatting""" if docsc...
LiuDongjing/myworks
样例代码/deepnet.py
Python
gpl-3.0
11,241
0.005861
""" Kaggle上的Quora question pairs比赛,按照Abhishek Thakur的思路,把整个流程跑通了 讲解的文章https://www.linkedin.com/pulse/duplicate-quora-question-abhishek-thakur。 里面有两个实现,基于传统机器学习模型的实现和基于深度学习的实现,这段脚本是后者。 基本的思路比
较简单,不清楚的地方也添加了注释。使用GloVe的词向量库,把每个句子转换成词向量 拼接起来的矩阵,之后就可以搭建神经网络了。自己在Convolution1D、LSTM和DropOut那一块儿还 有些迷糊。 """ import pandas as pd import numpy as np from tqdm import tqdm from keras.models import Sequential from keras.layers.core import Dense, Activation, Dropout from keras.layers.embeddings import Embe
dding from keras.layers.recurrent import LSTM, GRU from keras.layers.normalization import BatchNormalization from keras.utils import np_utils from keras.layers import Merge from keras.layers import TimeDistributed, Lambda from keras.layers import Convolution1D, GlobalMaxPooling1D from keras.callbacks import ModelCheckp...
openqt/algorithms
projecteuler/pe288-an-enormous-factorial.py
Python
gpl-3.0
477
0.008421
#!/usr/bin/env python # coding=utf-8 """288. An enormous factorial https://projecteuler.net/problem=288
For any prime p the number N(p,q) is defined by N(p,q) = ∑n=0 to q Tn*pn with Tn generated by the following random number generator: S0 = 290797 Sn+1 = Sn2 mod 50515093 Tn = Sn mod p Let Nfac(p,q) be the factorial of N(p
,q). Let NF(p,q) be the number of factors p in Nfac(p,q). You are given that NF(3,10000) mod 320=624955285. Find NF(61,107) mod 6110 """