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 |
|---|---|---|---|---|---|---|---|---|
kvangent/PokeAlarm | tests/filters/__init__.py | Python | agpl-3.0 | 2,293 | 0 | import logging
class MockManager(object):
""" Mock manager for filter unit testing. """
def get_child_logger(self, name):
return logging.getLogger('test').getChild(name)
def generic_filter_test(test):
"""Decorator used for creating a generic filter test.
Requires the argument to be a functi... | t.__name__, event, filt))
# Test failing
for val in test.fail_vals:
event = self.gen_event({test.event_key: val})
self.assertFalse(
filt.check_event(event),
"fail_val passed check in {}: \n{} passed {}"
| "".format(test.__name__, event, filt))
return generic_test
def full_filter_test(test):
"""Decorator used for creating a full filter test.
Requires the argument to be a function that assigns the following
attributes when called:
filt = dict used to generate the filter,
pass_items = array of di... |
beheh/fireplace | tests/test_carddb.py | Python | agpl-3.0 | 1,192 | 0.025168 | from hearthstone.enums import CardType, GameTag, Rarity
import utils
CARDS = utils.fireplace.cards.db
def test_all_tags_known():
"""
Iterate through the card database and check that all specified GameTags
are known in hearthstone.enums.GameTag
"""
unknown_tags = set()
known_tags = list(GameTag)
known_rariti... | ARDS.values():
if card.scripts.activate:
assert card.type == CardType.HERO_POWER
elif card.scripts.play:
assert card.type | not in (CardType.HERO, CardType.HERO_POWER, CardType.ENCHANTMENT)
def test_card_docstrings():
for card in CARDS.values():
c = utils.fireplace.utils.get_script_definition(card.id)
name = c.__doc__
if name is not None:
if name.endswith(")"):
continue
assert name == card.name
|
GutenkunstLab/SloppyCell | Example/Gutenkunst2007/Lee_2003/reproduction.py | Python | bsd-3-clause | 1,316 | 0.00304 | from SloppyCell.ReactionNetworks import *
import Nets
traj2a = Dynamics.integrate(Nets.fig2a, [0, 3*60])
traj2b = Dynamics.integrate(Nets.fig2b, [0, 3*60])
traj2c = Dynamics.integrate(Nets.fig2c, [0, 3*60])
traj2d = Dynamics.integrate(Nets.fig2d, [0, 3*60])
traj2e = Dynamics.integrate(Nets.fig2e, [0, 3*60])
Plotting... | c = Dynamics.integrate(Nets.fig6c, [0, 16*60])
Plotting.figure(6, (5, 10))
Plotting. | subplot(2,1,1)
Plotting.plot(traj6a.get_times()/60., traj6a.get_var_traj('BCatenin'), '-k')
Plotting.plot(traj6b.get_times()/60., traj6b.get_var_traj('BCatenin'), '-r')
Plotting.plot(traj6c.get_times()/60., traj6c.get_var_traj('BCatenin'), '-g')
Plotting.axis([-1, 16, 34, 72])
Plotting.subplot(2,1,2)
Plotting.plot(traj... |
neno1978/pelisalacarta | python/main-classic/servers/googlevideo.py | Python | gpl-3.0 | 2,080 | 0.000962 | # -*- coding: utf-8 -*-
# ------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# Conector para Google Video basado en flashvideodownloader.org
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
# ------------------------------------------------------------
import re
from co... | r de flashvideodownloader.org
if page_url.startsw | ith("http://"):
url = 'http://www.flashvideodownloader.org/download.php?u=' + page_url
else:
url = 'http://www.flashvideodownloader.org/download.php?u=http://video.google.com/videoplay?docid=' + page_url
logger.info("url=" + url)
data = scrapertools.cache_page(url)
# Extrae el vídeo
... |
ingadhoc/odoo-logistic | logistic_project/wizard/__init__.py | Python | agpl-3.0 | 269 | 0.003717 | # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
########### | ######## | ########################################################### |
sohail-aspose/Aspose_Tasks_Cloud | SDKs/Aspose.Tasks_Cloud_SDK_for_Python/asposetaskscloud/TasksApi.py | Python | mit | 143,735 | 0.013247 | #!/usr/bin/env python
import sys
import os
import urllib
import json
import re
from models import *
from ApiClient import ApiException
class TasksApi(object):
def __init__(self, apiClient):
self.apiClient = apiClient
def DeleteProjectAssignment(self, name, assignmentUid, **kwargs):
"""D... | :
resourcePath = resourcePath.replace("{" + "fileName" + "}" , str(allParams['fil | eName']))
else:
resourcePath = re.sub("[&?]fileName.*?(?=&|\\?|$)", "", resourcePath)
method = 'DELETE'
queryParams = {}
headerParams = {}
formParams = {}
files = { }
bodyParam = None
headerParams['Accept'] = 'application/xml,applica... |
HarrisonHDU/myerp | apps/sims/urls.py | Python | mit | 526 | 0.001901 | __author__ = 'Administrator'
from django.conf.urls import patterns
from django.contrib.auth.v | iews import login, logout_then_login
urlpatterns = patterns('',
(r'^$', 'apps.sims.views.index_view'),
(r'index/$', 'apps.sims.views.index_view'),
(r'login/$', lo | gin, {'template_name': 'sims/login.html'}),
(r'logout/$', logout_then_login),
(r'stuinfo/$', 'apps.sims.views.student_info_list'),
(r'save/$', 'apps.sims.views.save_student'),
(r'delete/$', 'apps.sims.views.delete_student'),
)
|
mauzeh/formation-flight | runs/singlehub/z/run.py | Python | mit | 1,259 | 0.007943 | #!/usr/bin/env python
"""Simulation bootstrapper"""
from formation_flight.formation import handlers as formation_handlers
from formation_flight.aircraft import handlers as aircraft_handlers
from formation_flight.aircraft import generators
from formation_flight.hub import builders
from formation_flight.hub import alloc... | ngle_run():
sim.init()
aircraft_handlers.init()
formation_handlers.init()
statistics.init()
# Construct flight list
planes = generators.get_via_stdin()
# Find hubs
config.hubs = builders.build_hubs(planes, config.count_hubs, config.Z)
# Allocate hubs to flights
alloca... |
for flight in planes:
sim.events.append(sim.Event('aircraft-init', flight, 0))
sim.run()
sink.push(statistics.vars)
debug.print_dictionary(statistics.vars)
|
matrix-org/synapse | tests/util/test_file_consumer.py | Python | apache-2.0 | 5,022 | 0.000398 | # Copyright 2018 New Vector Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | resume_deferred
producer.resumeProducing.assert_called_once()
finally:
consumer.unregisterProducer()
yield consumer.wait()
self.assertTrue(string_file.closed)
class DummyPullProducer:
def __init__(self):
self.consumer = None
self.deferred = defer.... | rred()
d.callback(None)
def write_and_wait(self, bytes):
d = self.deferred
self.consumer.write(bytes)
return d
def register_with_consumer(self, consumer):
d = self.deferred
self.consumer = consumer
self.consumer.registerProducer(self, False)
retu... |
jarvisji/ScrapyCrawler | CrawlWorker/spiders/serverfault.py | Python | apache-2.0 | 396 | 0.002525 | __author__ = 'Ting'
from CrawlWorker.spiders.stackoverflow import StackOverflowSpider
class ServerFaultSpider(StackOverflowSpider):
name = 'ServerFaultSpider'
allowed_domains = ['serverfault.com']
def __init__(self, op=None, **kwargs):
StackOverflowSpider.__init__(self, op, **kwargs)
def ge... | //serverfault.com/questions'] | |
redbox-mint/redbox | config/src/main/config/home/harvest/workflows/simpleworkflow-rules.py | Python | gpl-2.0 | 356 | 0.030899 | import sys
import os
from com.googlecode.fascinator.common import FascinatorHome
sys.path.append( | os.path.join(FascinatorHome.getPath(),"harvest", "workflows"))
from | baserules import BaseIndexData
class IndexData(BaseIndexData):
def __activate__(self, context):
BaseIndexData.__activate__(self,context)
|
JamesClough/networkx | networkx/algorithms/tests/test_mis.py | Python | bsd-3-clause | 3,517 | 0.007108 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# $Id: test_maximal_independent_set.py 577 2011-03-01 06:07:53Z lleeoo $
"""
Tests for maximal (not maximum) independent sets.
"""
# Copyright (C) 2004-2016 by
# Leo Lopes <leo.lopes@monash.edu>
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.ed... | rt_equal(sorted(indep),
sorted(["Medici", "Bischeri", "Castellani", "Pazzi",
"Ginori", "Lamberteschi"]))
def test_bipartite(self):
G = nx.complete_bipartite_graph(12, 34)
indep = nx.maximal_independent_set(G, [4, 5, 9, 10])
assert_equal(sorted(inde... | ))
def test_random_graphs(self):
"""Generate 50 random graphs of different types and sizes and
make sure that all sets are independent and maximal."""
for i in range(0, 50, 10):
G = nx.random_graphs.erdos_renyi_graph(i*10+1, random.random())
IS = nx.maximal_independ... |
mcmaxwell/idea_digital_agency | idea/feincms/module/page/extensions/excerpt.py | Python | mit | 754 | 0 | """
Add an excerpt field to the page.
"""
from __future__ import absolute_import, unicode_literals
from django.db import models
from django.utils.translation import ugettext_laz | y as _
from feincms import extensions
class Extension(extensions.Extension):
def handle_model(self):
self.model.add_to_class(
'excerpt',
models.TextField(
_('excerpt'),
blank=True,
help_text=_(
'Add a brief excerp... | n.add_extension_options(_('Excerpt'), {
'fields': ('excerpt',),
'classes': ('collapse',),
})
|
Gebesa-Dev/Addons-gebesa | account_prepayment_return/models/__init__.py | Python | agpl-3.0 | 151 | 0 | # -*- coding: utf-8 -*-
# © <YEAR(S)> <AUTHOR(S)>
# License AGPL-3.0 | or later (http://www.gnu.org/licenses/agpl. | html).
from . import account_payment
|
rendermotion/RMPY | Core/data_save_load.py | Python | lgpl-3.0 | 3,429 | 0.001458 | from RMPY.representations import curve
from RMPY.creators import skinCluster
import pymel.core as pm
from RMPY.core import config
import os
def save_curve(*args):
"""
:param args: the scene objects that will be saved if nothing is provide it it will try to save the selection.
:return:
"""
if args:... | skin_cluster01 = skinCluster.SkinCluster.by_node(each_node)
if skin_cluster01:
| skin_cluster01.save('{}'.format(each_node))
saved_skin_cluster_list.append(each_node)
else:
print "object {} does'nt have a skincluster".format(each_node)
except RuntimeWarning('{} not saved'.format(each_node)):
pass
print 'following skin in nodes whe... |
tfiedor/perun | perun/collect/trace/systemtap/engine.py | Python | gpl-3.0 | 30,849 | 0.003695 | """ The SystemTap engine implementation.
"""
import time
import os
from subprocess import PIPE, STDOUT, DEVNULL, TimeoutExpired
import perun.collect.trace.systemtap.parse_compact as parse_compact
import perun.collect.trace.collect_engine as engine
import perun.collect.trace.systemtap.script_compact as stap_script_com... | .stp')
self.log = self._assemble_file_name('log', '.txt')
self.data = self._assemble_file_name('data', '.txt')
self.capture = self._assemble_file_name('capture', '.txt')
# Syst | emTap specific dependencies
self.__dependencies = ['stap', 'lsmod', 'rmmod']
# Locks
binary_name = os.path.basename(self.executable.cmd)
self.lock_binary = ResourceLock(LockType.Binary, binary_name, self.pid, self.locks_dir)
self.lock_stap = ResourceLock(
LockType.Sy... |
LoveKano/hs_django_blog | blog/apps.py | Python | mit | 156 | 0 | # -*- coding: utf-8 -*-
fro | m __future__ import unicode_literals
from django.apps import AppConfig
class BlogConfig(AppConfig):
| name = 'blog'
|
tomkralidis/geonode | geonode/monitoring/migrations/0003_monitoring_resources.py | Python | gpl-3.0 | 572 | 0.001748 | # -*- coding: utf-8 -*-
from django.db import migrations, models
class | Migration(migrations.Migration):
dependencies = [
('monitoring', '0002_monitoring_update'),
]
operations = [
migrations.RemoveField(
model_name='requestevent',
name='resources',
),
migrations.AddField(
model_name='requestevent',
... | p_text='List of resources affected', to='monitoring.MonitoredResource', null=True, blank=True),
),
]
|
ohjay/ohjay.github.io | cs61a/sp17/mt1_review/code.py | Python | mit | 754 | 0.007958 | """
Code for MT1 review worksheet.
Direct all complaints to Owen Jow (owenjow@berkeley).
"""
# Part 1: Control
x = (0 and 1 and 2) + (0 or 1 or 2)
((-4 or 0) and 4) / (-2 or (0 and 2))
if x <= 1:
| print('hello')
elif x <= 2:
print(' world')
if x <= 3:
print(' my name is inigo montoya')
else:
print(' from the other side')
# Part 2: HOF / Lambdas
def f(v, x):
def g(y, z):
return y(x, z)(z, x)
return g
u = lambda y, x: y * 4
v = lambda x, y: x * 3 + y
f(u, 1)(lambda x, y: lambda y, x:... | = 6, 7
f = f(3, [lambda: x * y])
g = f[-1]()[0][0][0]()
|
Azwok/Thremo | magnification_map.py | Python | gpl-2.0 | 249 | 0.004016 | import numpy as np
import unittest
import pycuda.driver as drv
import pycuda.compiler
impor | t pycuda.autoinit
import pycuda.gpuarray as gpuarray
import pycuda.cumath as cumath
from pycuda.compiler import Source | Module
__author__ = 'AlistairMcDougall' |
jinglining/flink | flink-python/pyflink/fn_execution/tests/test_process_mode_boot.py | Python | apache-2.0 | 6,732 | 0.002525 | ################################################################################
# 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... | n server, port
self.provision_server, self.provision_port = start_test_provision_server()
self.env = dict(os.environ)
self.env["python"] = sys.executable
self.env["FLINK_BOOT_TESTING"] = "1"
self.env["BOOT_LOG_DIR"] = os.path.join(self.env["FLIN | K_HOME"], "log")
self.tmp_dir = tempfile.mkdtemp(str(time.time()), dir=self.tempdir)
# assume that this file is in flink-python source code directory.
flink_python_source_root = os.path.dirname(
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
ru... |
jcherqui/searx | searx/engines/gigablast.py | Python | agpl-3.0 | 3,104 | 0.000966 | """
Gigablast (Web)
@website https://gigablast.com
@provide-api yes (https://gigablast.com/api.html)
@using-api yes
@results XML
@stable yes
@parse url, title, content
"""
import random
from json import loads
from time import time
from lxml.html import fromstring
from searx.url_utils impo... | language = language.split('-')[0]
if params['safesearch'] >= 1:
safesearch = 1
else:
safesearch = 0
# rxieu is some kind of hash from the search query, but accepts random atm
search_path = search_string.format(query=urlencode({'q': query}),
... | rxikd=int(time() * 1000),
rxieu=random.randint(1000000000, 9999999999),
ulse=random.randint(100000000, 999999999),
lang=language,
s... |
mjysci/ud-dlnd-side-proj | p2_miniflow_mnist/miniflow_old.py | Python | gpl-3.0 | 8,379 | 0.001193 | import numpy as np
class Node(object):
"""
Base class for nodes in the network.
Arguments:
`inbound_nodes`: A list of nodes with edges into this node.
"""
def __init__(self, inbound_nodes=[]):
"""
Node's constructor (runs when the object is instantiated). Sets
pro... | ound_nodes[2]] += np.sum(grad_cost, axis=0, keepdims=False)
class Sigmoid(Node):
"""
Represents a node that performs the sigmoid activation function.
"""
def __init__(self, node):
| # The base class constructor.
Node.__init__(self, [node])
def _sigmoid(self, x):
"""
This method is separate from `forward` because it
will be used with `backward` as well.
`x`: A numpy array-like object.
"""
return 1. / (1. + np.exp(-x))
def forward(... |
ritashugisha/ASUEvents | ASUEvents/managers/migrations/0012_auto_20150422_2019.py | Python | mit | 511 | 0.001957 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration | ):
dependencies = [
('managers', '0011_auto_20150422_2018'),
]
operations = [
migrations.AlterField(
model_name='managerprofile',
name='picture',
field=models.ImageField(default=b'/static/assets/admin/layout/img/avatar.jpg' | , upload_to=b'profiles'),
preserve_default=True,
),
]
|
murat1985/bagpipe-bgp | bagpipe/bgp/bgp_daemon.py | Python | apache-2.0 | 11,381 | 0.000088 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# encoding: utf-8
# Copyright 2014 Orange
#
# 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
#
# Un... | License for the specific language governing permissions and
# limitations under the License.
impor | t os.path
import sys
from logging import Logger
import logging.config
# import logging_tree
import traceback
from daemon import runner
import signal
from ConfigParser import SafeConfigParser, NoSectionError
from optparse import OptionParser
from bagpipe.bgp.common import utils
from bagpipe.bgp.common.looking_gla... |
google-research/understanding-transfer-learning | third_party/chexpert_data/chexpert.py | Python | apache-2.0 | 7,524 | 0.000665 | import os
import logging
import numpy as np
from torch.utils.data import Dataset
import cv2
from PIL import Image
import subprocess
import torchvision.transforms as tfs
np.random.seed(0)
def TransCommon(image):
image = cv2.equalizeHist(image)
image = cv2.GaussianBlur(image, (3, 3), 0)
return image
de... | # self._image_paths = [self._image_paths[i] for i in idx]
# self._labels = [self._labels[i] for i in idx]
# self._num_image = len(self._labels)
if cfg.cache_bitmap:
self._bitmap_cache = self._build_bitmap_cache()
else:
self._bitmap_cache = None
de... | return self._num_image
def _border_pad(self, image):
h, w, c = image.shape
if self.cfg.border_pad == 'zero':
image = np.pad(
image,
((0, self.cfg.long_side - h),
(0, self.cfg.long_side - w), (0, 0)),
mode='constant', cons... |
choldrim/jumpserver | apps/perms/apps.py | Python | gpl-2.0 | 126 | 0 | from __future__ import unicode_literals
from django.apps import AppConfig
|
class Per | msConfig(AppConfig):
name = 'perms'
|
marcelosandoval/tekton | backend/appengine/routes/campapel/show.py | Python | mit | 2,187 | 0.015546 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from config.template_middleware import TemplateResponse
from gaecookie.decorator import no_csrf
from gaepermission.decorator import login_not_required
from routes.campapel.home import returnIndex
from tekton import router
from tekton.gae.m... | h':router.to_path(salvar),
'erros':erros,
'camPapel':prop}
return TemplateResponse(contexto,'campapel/form.html')
else:
camPapel=camPapelF.fill_model()
camPapel.put()
return RedirectResponse(returnIndex())
@login_not_required
@no_csrf
def editar... | xto={'salvar_path':router.to_path(editar,camPapel_id),'camPapel':camPapel}
return TemplateResponse(contexto,template_path='campapel/form.html')
@login_not_required
def editar(camPapel_id,**prop):
camPapel_id=int(camPapel_id)
camPapel=CamPapel.get_by_id(camPapel_id)
camPapelF=CamPapelForm(**prop)
... |
ric2b/Vivaldi-browser | chromium/content/test/gpu/determine_gold_inexact_parameters.py | Python | bsd-3-clause | 4,018 | 0.007218 | #!/usr/bin/env vpython3
# Copyright 2020 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.
from __future__ import print_function
import argparse
import logging
import sys
import gold_inexact_matching.base_parameter_optimiz... | pts to remedy both issues by handling all of the trial and
# error and suggesting potential parameter values for the user to choose from.
def CreateArgumentParser():
parser = argparse.Argument | Parser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
script_parser = parser.add_argument_group('Script Arguments')
script_parser.add_argument('-v',
'--verbose',
dest='verbose_count',
default=0,
... |
srcLurker/home-assistant | homeassistant/components/camera/__init__.py | Python | mit | 5,960 | 0 | # pylint: disable=too-many-lines
"""
Component to interface with cameras.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/camera/
"""
import asyncio
import logging
from aiohttp import web
from homeassistant.helpers.entity import Entity
from homeassista... | camera_image(self):
"""Return bytes of camera image."""
raise NotImplementedError()
@asyncio.coroutine
def async_camera_image(self):
"""Return bytes of camera image.
This method must be run in the event | loop.
"""
image = yield from self.hass.loop.run_in_executor(
None, self.camera_image)
return image
@asyncio.coroutine
def handle_async_mjpeg_stream(self, request):
"""Generate an HTTP MJPEG stream from camera images.
This method must be run in the event loo... |
neuroo/equip | tests/test_visitors.py | Python | apache-2.0 | 2,730 | 0.005128 | import pytest
from testutils import get_co, get_bytecode
from equip import BytecodeObject, BlockVisitor
from equip.bytecode import MethodDeclaration, TypeDeclaration, ModuleDeclaration
from equip.bytecode.utils import show_bytecode
import equip.utils.log as logutils
from equip.utils.log import logger
logutils.enableL... | 2:
return 2
print "This is something else"
if __name__ == '__mai | n__':
main()
"""
def test_block_visitor():
co_simple = get_co(SIMPLE_PROGRAM)
assert co_simple is not None
bytecode_object = BytecodeObject('<string>')
bytecode_object.parse_code(co_simple)
class BlockPrinterVisitor(BlockVisitor):
def __init__(self):
BlockVisitor.__init__(self)
def new_co... |
ecolitan/fatics | src/command/game_command.py | Python | agpl-3.0 | 6,711 | 0.002086 | # -*- coding: utf-8 -*-
# Copyright (C) 2010 Wil Mahan <wmahan+fatics@gmail.com>
#
# This file is part of FatICS.
#
# FatICS is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the Lice... | ESS 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 FatICS. If not, see <http://www.gnu.org/licenses/>.
#
import re
import offer
import game
from command_parser import BadCommandError
f... | sion.game
if not g or g.gtype != game.PLAYED:
g = None
conn.write(_("You are not playing a game.\n"))
return g
def _game_param(self, param, conn):
""" Find a game from a command argument, currently being
played, examined, or observed, prioritized in that orde... |
motmot/fastimage | motmot/FastImage/util.py | Python | bsd-3-clause | 2,489 | 0.011651 | import glob, os, sys
def get_build_info(ipp_static=True, # static build requires static IPP libs
ipp_arch=None,
ipp_root=None,
):
"""get options to build Python extensions built with Intel IPP
ipp_static - True to build using static IPP library (requires I... | in ['i386','i686']:
ipp_arch = 'ia32'
else:
raise ValueError("unexpected linux architecture: %s"%machine)
elif sys.platform == 'win32':
ipp_arch = 'ia32'
else:
| raise NotImplementedError("auto-architecture detection not implemented on this platform")
vals = {}
if sys.platform.startswith('linux'):
libdirname = 'lib/%s_lin' % ipp_arch
else:
libdirname = 'lib'
incdirname = 'include'
ipp_define_macros = []
ipp_extra_link_args = []
ipp_... |
yujikato/DIRAC | src/DIRAC/WorkloadManagementSystem/JobWrapper/test/Test_Watchdog.py | Python | gpl-3.0 | 958 | 0.018789 | """ unit test for Watchdog.py
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# impor | ts
import os
from mock import MagicMock
# sut
from DIRAC.WorkloadManagementSystem.JobWrapper.Watchdog import Watchdog
mock_exeThread = MagicMock()
mock_spObject = MagicMock()
def test_calibrate():
pid = os.getpid()
wd = Watchdog(pid, mock_exeThread, mock_spObject, 5000) |
res = wd.calibrate()
assert res['OK'] is True
def test__performChecks():
pid = os.getpid()
wd = Watchdog(pid, mock_exeThread, mock_spObject, 5000)
res = wd.calibrate()
assert res['OK'] is True
res = wd._performChecks()
assert res['OK'] is True
def test__performChecksFull():
pid = os.getpid()
w... |
sgala/gajim | src/common/xmpp/simplexml.py | Python | gpl-3.0 | 18,852 | 0.039518 | ## simplexml.py based on Mattew Allum's xmlstream.py
##
## Copyright (C) 2003-2005 Alexey "Snake" Nezhdanov
##
## 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, or (... | return unicode(r,ENCODING)
return r
class Node(object):
| """ Node class describes syntax of separate XML Node. It have a constructor that permits node creation
from set of "namespace name", attributes and payload of text strings and other nodes.
It does not natively support building node from text string and uses NodeBuilder class for that purpose.
After creation node... |
wadobo/congressus | congressus/tickets/urls.py | Python | agpl-3.0 | 1,208 | 0.005795 | from django.urls import path
from tickets import views
urlpatterns = [
path('', views.last_event, name='last_event'),
path('event/<str:ev>/', views.event, name='event'),
path('event/<str:ev>/<str:space>/<str:session>/register/', views.register, name='register'),
path('ticket/<str:order>/payment/', v... | path('ticket/<str:order>/thanks/', views.thanks, name='thanks'),
path('ticket/confirm/', views.confirm, name='confirm'),
path('ticket/confirm/paypal/', views.confirm_paypal, name='confirm_paypal'),
path('ticket/<str:order>/confirm/stripe/', views.confirm_stripe, name='confirm_stripe'),
path('ticket/... | review'),
path('ticket/email-confirm/<int:id>/preview/', views.email_confirm_preview, name='email_confirm_preview'),
path('<str:ev>/', views.multipurchase, name='multipurchase'),
path('seats/<int:session>/<int:layout>/', views.ajax_layout, name='ajax_layout'),
path('seats/view/<int:map>/', views.seats... |
amitgroup/parts-net | scripts/train_and_test5.py | Python | bsd-3-clause | 12,277 | 0.013928 | from __future__ import division, print_function, absolute_import
#from pnet.vzlog import default as vz
import numpy as np
import amitgroup as ag
import itertools as itr
import sys
import os
#import gv
import pnet
import time
def test(ims, labels, net):
yhat = net.classify(ims)
return yhat == labels
if pnet... | min_prob=0.0005,
trees=10,
max_depth=3,
)),
pnet.PoolingLayer(shape=(4, 4), strides=(4, 4)),
... | raining_seed,
samples_per_image=40,
max_samples=200000,
train_limit=100000,
)),
... |
adelina-t/compute-hyperv | hyperv/tests/unit/test_eventhandler.py | Python | apache-2.0 | 7,212 | 0 | # Copyright 2015 Cloudbase Solutions Srl
# 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 r... |
if instance_found and not missing_uuid else None)
self.assertEqual(expected_uuid, instance_uuid)
def test_get_nova_created_instance_uuid(self):
self._test_get_instance_uuid() |
def test_get_deleted_instance_uuid(self):
self._test_get_instance_uuid(instance_found=False)
def test_get_instance_uuid_missing_notes(self):
self._test_get_instance_uuid(missing_uuid=True)
@mock.patch('nova.virt.event.LifecycleEvent')
def test_get_virt_event(self, mock_lifecycle_even... |
clreinki/GalaxyHarvester | udPassword.py | Python | agpl-3.0 | 2,630 | 0.001901 | #!/usr/bin/python
"""
Copyright 2010 Paul Willworth <ioscode@gmail.com>
This file is part of Galaxy Harvester.
Galaxy Harvester is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of th... | ']
except KeyError:
| url = ''
form = cgi.FieldStorage()
# Get Cookies
errorstr = ''
cookies = Cookie.SimpleCookie()
try:
cookies.load(os.environ['HTTP_COOKIE'])
except KeyError:
errorstr = 'no cookies\n'
if errorstr == '':
try:
currentUser = cookies['userID'].value
except KeyError:
currentUser = ''
... |
schets/LILAC | src/scripts/python/process_data.py | Python | bsd-3-clause | 2,106 | 0.012346 | import numpy as np
import scipy.io as sio
import pylab as pl
import itertools as it
import io
def ret_tru(inval):
return true
def get_next_ind(in_file, sep_ln="&", predicate = ret_tru):
lvals = []
for line in in_file:
line = line.strip()
if line == sep_ln:
break
if predic... | ]
print fbase
sio. | savemat(fbase, {'abl_vals':np.array(abl_val), 'neur_series':neur_mat, 'time_vec':time_vec})
ltest = get_next_ind(dat_file, "&", lambda x:(x.startswith("Ablation") or x.startswith("Func") or x.startswith("Time") or x.startswith("&&")))
|
brucetsao/python-devicecloud | devicecloud/test/unit/__init__.py | Python | mpl-2.0 | 312 | 0 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla. | org/MPL/2 | .0/.
#
# Copyright (c) 2015 Etherios, Inc. All rights reserved.
# Etherios, Inc. is a Division of Digi International.
|
sounak98/coala-bears | tests/c_languages/CPPLintBearTest.py | Python | agpl-3.0 | 843 | 0 | from bears.c_languages.CPPLintBear import CPPLintBear
from tests.LocalBearTestHelper import verify_local_bear
test_file = """
int main() {
return 0;
}
"""
CPPLintBearTest = verify_local_bear(CPPLintBear,
| valid_files=(),
invalid_files=(test_file,),
tempfile_kwargs={'suffix': '.cpp'})
CPPLintBea | rIgnoreConfigTest = verify_local_bear(
CPPLintBear,
valid_files=(test_file,),
invalid_files=(),
settings={'cpplint_ignore': 'legal'},
tempfile_kwargs={'suffix': '.cpp'})
CPPLintBearLineLengthConfigTest = verify_local_bear(
CPPLintBear,
valid_files=(),
invalid_files=(test_file,),
set... |
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2016_09_01/operations/_virtual_network_peerings_operations.py | Python | mit | 22,805 | 0.004955 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | , {})
_delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings/{virtualNetworkPeeringName}'} # type: ignore
def begin_delete(
self,
resource_group_name, # typ... | ]
"""Deletes the specified virtual network peering.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param virtual_network_name: The name of the virtual network.
:type virtual_network_name: str
:param virtual_network_peering_nam... |
padmec-reservoir/ELLIPTIc | docs/source/conf.py | Python | mit | 5,213 | 0 | # -*- coding: utf-8 -*-
#
# ELLIPTIc documentation build configuration file, created by
# sphinx-quickstart on Sat Mar 25 15:56:12 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# ... |
man_pages = [
(master_doc, 'elliptic', u'ELLIPTIc Documentation',
[author], 1)
]
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, cate... | r_doc, 'elliptic', u'ELLIPTIc Documentation',
author, 'elliptic', 'The Extensible LIbrary for Physical simulaTIons.',
'Miscellaneous'),
]
|
mayankjohri/LetsExplorePython | Section 2 - Advance Python/Chapter S2.06 - Web Development/code/flask/flask_login/sample_2/app.py | Python | gpl-3.0 | 2,215 | 0 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 30 09:53:39 2018
@author: mayank
"""
from forms import SignupForm
from flask import Flask, request, render_template
from flask_login import LoginManager, login_user, login_required, logout_user
app = Flask(__name__)
app.secret_key = 'gMALVWEuxBSx... | ute("/logout")
@login_required
def logout():
logout_user()
return "Logged out"
@app.route('/protected')
@login_required
def protected():
return "protected area"
def init_db():
| db.init_app(app)
db.app = app
db.create_all()
if __name__ == '__main__':
from models import db, User
init_db()
app.run(port=5000, host='localhost')
|
DearBytes/Remote-Integrity-Tool | dear/remote_integrity/models.py | Python | lgpl-3.0 | 6,183 | 0.001132 | #!/usr/bin/env python
# Copyright (C) 2017 DearBytes B.V. - All Rights Reserved
import os
from datetime import datetime
from sqlalchemy import Column
from sqlalchemy import DateTime
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy import create_engine
from ... | :type event: int
:type description: str
:type checksum: models.Checksum
:return: Returns the instance of the event
"""
record = cls(event=event, description=desc | ription, checksum=checksum, timestamp=datetime.now())
session.add(record)
return record
def create_database():
""""
Create a new database or overwrite the existing one
:return: None
"""
Base.metadata.create_all(engine)
def database_exists():
"""
Check if the database exis... |
wavefrontHQ/wavefront-collector | wavefront/awsmetrics.py | Python | apache-2.0 | 18,849 | 0.000955 | """
This module calls the AWS ListMetrics() API followed by multiple calls to
GetMetricStatistics() to get metrics from AWS.
A dictionary configu | red by the 'metrics' key in the configuration file is
used to determine which metrics should lead to a call to GetMetricStatistics().
Each metric value returned from GetMetricStatistics() is sent to the Wavefront
proxy on port 2878 (or other port if configured differently). Point tags
are picked up from the Dimension... | ce is determined by searching
the point tags for a list of "accepted" source locations
(e.g., 'Service', 'LoadBalancerName', etc).
The last run time is stored in a configuration file in
/opt/wavefront/etc/aws-metrics.conf and will be used on the next run to
determine the appropriate start time. If no configuration fi... |
kerwinxu/barcodeManager | zxing/cpp/scons/scons-local-2.0.0.final.0/SCons/Tool/SCCS.py | Python | bsd-2-clause | 2,443 | 0.004912 | """SCons.Tool.SCCS.py
Tool-specific initialization for SCCS.
There normally shouldn't be any need to import this module direct | ly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
|
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# 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
# witho... |
cmheisel/agile-analytics | docs/conf.py | Python | mit | 9,780 | 0.000102 | # -*- coding: utf-8 -*-
#
# agile-analytics documentation build configuration file, created by
# sphinx-quickstart on Fri Jun 17 13:58:53 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated fil... | nx'
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
# If true, keep warnings as "sy | stem message" paragraphs in the built documents.
# keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documen... |
madi/DeadTrees-BDEOSS | clipshape.py | Python | gpl-3.0 | 4,289 | 0.006761 | __author__ = "Laura Martinez Sanchez"
__license__ = "GPL"
__version__ = "1.0"
__email__ = "lmartisa@gmail.com"
from osgeo import gdal, gdalnumeric, ogr, osr
import numpy as np
from PIL import Image, ImageDraw
from collections import defaultdict
import pickle
import time
from texture_common import *
#Uses a gdal ge... | 0
#Convert the layer extent to image pixel coordinates, we read only de pixels needed
for feature in layer:
minX, maxX, minY, maxY = feature.GetGeometryRef().GetEnvelope()
geoTrans = img.GetGeoTransform()
ulX, ulY = world2Pixel(geoTrans, minX, maxY)
lrX, lrY = world2Pixel(g | eoTrans, maxX, minY)
#print ulX,lrX,ulY,lrY
# Calculate the pixel size of the new image
pxWidth = int(lrX - ulX)
pxHeight = int(lrY - ulY)
clip = ReadClipArray(lrY, ulY, lrX, ulX, img)
#EDIT: create pixel offset to pass to new image Projection info
xoffset = ... |
jagg81/translate-toolkit | translate/lang/fa.py | Python | gpl-2.0 | 2,471 | 0.002034 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2007, 2010 Zuza Software Foundation
#
# This file is part of translate.
#
# translate 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 ... | 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 translate; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA ... | his module represents Persian language.
For more information, see U{http://en.wikipedia.org/wiki/Persian_language}
"""
from translate.lang import common
import re
def guillemets(text):
def convertquotation(match):
prefix = match.group(1)
# Let's see that we didn't perhaps match an XML tag prope... |
chadversary/chromiumos.chromite | scripts/cbuildbot.py | Python | bsd-3-clause | 73,676 | 0.007397 | #!/usr/bin/python
# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Main builder code for Chromium OS.
Used by Chromium OS buildbot configuration for all Chromium OS builds including
full and pre... | hromite.lib import commandline
from chromite.lib import cros_build_lib
from chromite.lib import gclient
from chromite.lib import gerrit
from chromite.lib import git
from chromite.lib import osutils
from c | hromite.lib import patch as cros_patch
from chromite.lib import parallel
from chromite.lib import sudo
from chromite.lib import timeout_util
import mock
_DEFAULT_LOG_DIR = 'cbuildbot_logs'
_BUILDBOT_LOG_FILE = 'cbuildbot.log'
_DEFAULT_EXT_BUILDROOT = 'trybot'
_DEFAULT_INT_BUILDROOT = 'trybot-internal'
_BUILDBOT_REQU... |
lucdom/xCrawler | xcrawler/compatibility/string_converter/string_converter_python3.py | Python | gpl-2.0 | 509 | 0.003929 |
from xcrawler.compatibility.string_converter.compatible_string_converter import CompatibleStringConverter
class StringConverterPython3(CompatibleStringConverter):
"""A Python 3 compatible class for converting a string to a specified type.
"""
def convert_to_s | tring(self, string):
string = self.try_convert_to_unicode_string(string)
return string
def list_convert | _to_string(self, list_strings):
return [self.try_convert_to_unicode_string(s) for s in list_strings]
|
AustinHartman/randomPrograms | primFinder.py | Python | gpl-3.0 | 209 | 0.004785 | upperLimit = 1000
oddCounter = 3
oddList = []
n = 0
while upperLimit >= oddCount | er:
oddList.append(oddCounter)
oddCounter += 2
while oddList(n) < (upperLimit - 1):
if oddList(n) | %
print(oddList) |
openqt/algorithms | leetcode/python/lc295-find-median-from-data-stream.py | Python | gpl-3.0 | 1,385 | 0.00722 | # coding=utf-8
import unittest
"""295. Find Median from Data Stream
https://leetcode.com/problems/find-median-from-data-stream/description/
Median is the middle value in an ordered integer list. If the size of the list
is even, there is no middle value. So the median is the mean of the two middle
value.
For example,... | edianFinder(object):
def __init__(self):
"""
initialize your data structure | here.
"""
def addNum(self, num):
"""
:type num: int
:rtype: void
"""
def findMedian(self):
"""
:rtype: float
"""
# Your MedianFinder object will be instantiated and called as such:
# obj = MedianFi... |
caglar10ur/func | func/minion/modules/nm/logger.py | Python | gpl-2.0 | 3,426 | 0.017805 | """A very simple logger that tries to be concurrency-safe."""
import os, sys
import time
import traceback
import subprocess
import select
LOG_FILE = '/var/log/nodemanager.func'
# basically define 3 levels
LOG_NONE=0
LOG_NODE=1
LOG_VERBOSE=2
# default is to log a reasonable amount of stuff for when running on oper... | .time()+timeout
result = False
try:
child = subprocess.Popen(command, bufsize=1,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True)
buffer = Buffer()
| while True:
# see if anything can be read within the poll interval
(r,w,x)=select.select([child.stdout],[],[],poll)
if r: buffer.add(child.stdout.read(1))
# is process over ?
returncode=child.poll()
# yes
if returncode != None:
... |
PaulBrownMagic/LED_Arcade | displays/writer.py | Python | gpl-3.0 | 1,026 | 0.000975 | import numpy as np
from displays.letters import ALPHABET
class Writer:
"""Produce scrolling text for the LED display, frame by frame"""
def __init__(self):
self.font = ALPHABET
self.spacer = np.zeros([8, 1], dtype=int)
self.phrase = None
def make_phrase(self, phrase): |
"""Convert a string into a long numpy array with spacing"""
| # phrase.lower() called because ALPHABET currently doesn't have capitals
converted = [np.hstack([self.font[letter], self.spacer])
for letter in phrase.lower()]
self.phrase = np.hstack(converted)
def generate_frames(self):
"""Produce single 8*8 frames scrolling across p... |
jalanb/jab | src/python/site/οs.py | Python | mit | 291 | 0 | """Handle nice names"""
import bas | e64
from pysyte.oss import platforms
def nice(data):
return bas | e64.b64encode(bytes(data, 'utf-8'))
def name(data):
return base64.b64decode(data).decode('utf-8')
def chmod(data, *_):
platforms.put_clipboard_data(name(data))
return ''
|
hfp/tensorflow-xsmm | tensorflow/contrib/seq2seq/python/kernel_tests/beam_search_ops_test.py | Python | apache-2.0 | 5,574 | 0.005203 | # 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... | t32),
parent_ids=parent_ids.astype(np.int32),
max_sequence_lengths=max_sequence_lengths,
end_token=end_token)
self. | assertEqual((max_time, batch_size, beam_width), beams.shape)
beams_value = beams.eval()
for b in range(batch_size):
# Past max_sequence_lengths[b], we emit all end tokens.
b_value = beams_value[max_sequence_lengths[b]:, b, :]
self.assertAllClose(b_value, end_token * np.ones_like(b_va... |
LeGoldFish/DTR2Sync | setup.py | Python | mit | 79 | 0 | from distutil | s.core import setup
import py2exe
setup(console=['DTR2Sync.py | '])
|
Mester/demo-day-vikings | tests/test_post.py | Python | unlicense | 671 | 0.004471 | import unittest
from music_app.post import Post
class TestPost(unittest.TestCase):
"""Class to test the Post Class"""
def test_object_creation(self):
p = Post('Promises', 'Dreamers', 'rock', '2014', 8, 'http://example.com', 146666666.66, 'https://www.youtube.com')
self.assertEqual(p.title,... | sertEqual(p.year, '2014')
self.assertEqual(p.score, 8)
self.asser | tEqual(p.thumbnail, 'http://example.com')
self.assertEqual(p.timestamp, 146666666.66)
self.assertEqual(p.url, 'https://www.youtube.com')
|
spookylukey/django-paypal | paypal/standard/pdt/tests/test_urls.py | Python | mit | 755 | 0.001325 | from __future__ import unicode_literals
try:
from django.urls import re_path
except ImportError:
from django.conf.urls import url as re_path
from django.shortcuts import render
from django.views.decorators.http import require_GET
from paypal.standard.pdt.vi | ews import process_pdt
@require_GET
def pdt(request, template="pdt/pdt.html", context=None):
" | ""Standard implementation of a view that processes PDT and then renders a template
For more advanced uses, create your own view and call process_pdt.
"""
pdt_obj, failed = process_pdt(request)
context = context or {}
context.update({"failed": failed, "pdt_obj": pdt_obj})
return render(request, ... |
listyque/TACTIC-Handler | thlib/side/python_minifier/rename/renamer.py | Python | epl-1.0 | 6,672 | 0.000899 | import ast
from python_minifier.rename.binding import NameBinding
from python_minifier.rename.name_generator import name_filter
from python_minifier.rename.util import is_namespace
def all_bindings(node):
"""
All bindings in a module
:param node: The module to get bindings in
:type node: :class:`ast... | to get bindings in
:type module: :class:`ast.AST`
:rtype: Iterable[ast.AST, Binding]
"""
def comp(tup):
namespace, binding = tup
return len(binding.references)
return sorted(all_bindings(module), key=comp, reverse=True)
def reservation_scope(namespace, binding):
"""
Get ... | able in
:param namespace: The local namespace of a binding
:type namespace: :class:`ast.AST`
:param binding: The binding to get the reservation scope for
:type binding: Binding
:rtype: set[ast.AST]
"""
namespaces = set([namespace])
for node in binding.references:
while node i... |
jmschrei/scikit-learn | sklearn/neural_network/multilayer_perceptron.py | Python | bsd-3-clause | 49,926 | 0.00002 | """Multi-layer Perceptron
"""
# Authors: Issam H. Laradji <issam.laradji@gmail.com>
# Andreas Mueller
# Jiyuan Qian
# Licence: BSD 3 clause
import numpy as np
from abc import ABCMeta, abstractmethod
from scipy.optimize import fmin_l_bfgs_b
import warnings
from ..base import BaseEstimator, Classifi... | output activation
function, which is either the softmax function or the
logistic function
"""
hidden_activation = ACTIVATIONS[self.activation]
# Iterate over the hidden layers
for i in range(self.n_layers_ - 1):
activations[i + 1] = safe_sparse_dot(act... | self.coefs_[i])
activations[i + 1] += self.intercepts_[i]
# For the hidden layers
if (i + 1) != (self.n_layers_ - 1):
activations[i + 1] = hidden_activation(activations[i + 1])
# For the last layer
if with_output_activation:
output_a... |
stormi/tsunami | src/primaires/pnj/editeurs/pedit/edt_stats.py | Python | bsd-3-clause | 3,848 | 0.002865 | # -*-coding:Utf-8 -*
# Copyright (c) 2010 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# l... | E USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""Fichier contenant le contexte éditeur | EdtStats"""
from primaires.interpreteur.editeur import Editeur
from primaires.format.fonctions import contient
class EdtStats(Editeur):
"""Classe définissant le contexte éditeur 'stats'.
Ce contexte permet d'éditer les stats d'une race.
"""
def __init__(self, pere, objet=None, attribut... |
rachel3834/mulens-tom | scripts/log_utilities.py | Python | gpl-3.0 | 2,938 | 0.017699 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 17 00:00:05 2016
@author: rstreet
"""
import logging
from os import path, remove
from sys import exit
from astropy.time import Time |
from datetime import datetime
import glob
def start_day_log( config, log_name, version=None ):
"""Function to initialize a new log file. The naming convention for the
file is [log_name]_[UTC_date].log. A new file is automatically created
if none for the current UTC day already exist, otherwise output i... | provide timestamps for
all entries.
Parameters:
config dictionary Script configuration including parameters
log_directory Directory path
log_root_name Name of the log file
log_name string Name applied to the... |
WPTechInnovation/worldpay-within-sdk | wrappers/python_2-7/EventServer.py | Python | mit | 3,460 | 0.011561 | from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
import threading
from wpwithin.WPWithinCallback import Client
from wpwithin.WPWithinCallback import Processor
class CallbackHandler:
d... | itsToSupply: {0}\n".format(unitsToSupply)
print "SDT.Key: {0}\n".format(serviceDeliveryToken.key)
print "SDT.Expiry: {0}\n".format(serviceDeliveryToken.expiry)
print "SDT.Issued: {0}\n".format(serviceDeliveryToken.issued)
print "SDT.Signature: {0}\n".format(serviceDeliver... | ry)
except Exception as e:
print "doBeginServiceDelivery failed: " + str(e)
def endServiceDelivery(self, serviceId, serviceDeliveryToken, unitsReceived):
try:
print "event from core - onEndServiceDelivery()"
print "ServiceID: {0}\n".format(serviceId)
print "Un... |
mabuchilab/Instrumental | instrumental/__about__.py | Python | gpl-3.0 | 374 | 0.002674 | # -*- coding: utf-8 -* | -
# Copyright 2016-2017 Nate Bogdanowicz
import datetime
__distname__ = "Instrumental-lib"
__version__ = "0.6"
__author__ = "Nate Bogdanowicz"
__email__ = "natezb@gmail.com"
__url__ = 'https://github.c | om/mabuchilab/Instrumental'
__license__ = "GPLv3"
__copyright__ = "Copyright 2013-{}, {}".format(datetime.date.today().year, __author__)
|
beeftornado/sentry | src/sentry_plugins/jira_ac/utils.py | Python | bsd-3-clause | 2,784 | 0.000359 | from __future__ import absolute_import
import hashlib
import jwt
from six.moves.urllib.parse import quote
from sentry.shared_integrations.exceptions import ApiError
def percent_encode(val):
# see https://en.wikipedia.org/wiki/Percent-encoding
return quote(val.encode("utf8", errors="replace")).replace("%7E"... | k != "jwt":
| if isinstance(v, list):
param_val = [percent_encode(val) for val in v].join(",")
else:
param_val = percent_encode(v)
sorted_query.append("%s=%s" % (percent_encode(k), param_val))
query_string = "%s&%s&%s" % (method, uri, "&".join(sorted_query))
return h... |
CarterBain/Medici | ib/ext/EReader.py | Python | bsd-3-clause | 38,033 | 0.001052 | #!/usr/bin/env python
""" generated source for module EReader """
#
# Original file copyright original author(s).
# This file copyright Troy Melhase, troy@gci.net.
#
# WARNING: all changes to this file will be lost.
from ib.lib import Boolean, Double, DataInputStream, Integer, Long, StringBuffer, Thread
from ib.lib.ov... | TA = 20
TICK_OPTION_COMPUTATION = 21
TICK_GENERIC = 45
TICK_STRING = 46
TICK_EFP = 47
CURRENT_T | IME = 49
REAL_TIME_BARS = 50
FUNDAMENTAL_DATA = 51
CONTRACT_DATA_END = 52
OPEN_ORDER_END = 53
ACCT_DOWNLOAD_END = 54
EXECUTION_DATA_END = 55
DELTA_NEUTRAL_VALIDATION = 56
TICK_SNAPSHOT_END = 57
MARKET_DATA_TYPE = 58
COMMISSION_REPORT = 59
m_parent = None
m_dis = None
... |
charanpald/features | setup.py | Python | gpl-3.0 | 474 | 0.004219 | #!/usr/bin/env python
from setuptools import setup
se | tup(name='features',
version='0.1',
description='A collection of feature extraction/selection algorithms',
author='Charanpal Dhanjal',
author_email='charanpal@gmail.com',
url='https://github.com/charanpald/features',
install_requires=['numpy>=1.5.0', 'scipy>=0.7.1'],
platforms=... |
)
|
samyoyo/3vilTwinAttacker | Modules/ModuleProbeRequest.py | Python | mit | 4,383 | 0.013461 | #The MIT License (MIT)
#Copyright (c) 2015-2016 mh4x0f P0cL4bs Team
#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, mo... | lass frm_PMonitor(QWidget):
def __init__(self, parent=None):
super(frm_PMonitor, self).__init__(parent)
self.Main = QVBoxLayout()
self.setWindowTitle("Probe Request wifi Monitor")
self.setWindowIcon(QIcon('rsc/icon.ico'))
self.confi | g = frm_Settings()
self.interface = str(self.config.xmlSettings("interface", "monitor_mode", None, False))
self.loadtheme(self.config.XmlThemeSelected())
self.setupGUI()
def loadtheme(self,theme):
sshFile=("Core/%s.qss"%(theme))
with open(sshFile,"r") as fh:
self... |
hoelsner/product-database | app/productdb/models.py | Python | mit | 40,316 | 0.002828 | import hashlib
import re
from collections import Counter
from datetime import timedelta
from django.contrib.auth.models import User
from django.conf import settings
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.core.validators import MinValueValidator, MaxVal... | ndor]
if len(products_with_different_vendor) != 0:
raise ValidationError({
"vendor": ValidationError("cannot set new vendor as long as there are products associated to it")
})
def __str__(self):
return self.name
class Meta:
verbos... | f Support"
END_OF_SALE_STR = "End of Sale"
END_OF_NEW_SERVICE_ATTACHMENT_STR = "End of New Service Attachment Date"
END_OF_SW_MAINTENANCE_RELEASES_STR = "End of SW Maintenance Releases Date"
END_OF_ROUTINE_FAILURE_ANALYSIS_STR = "End of Routine Failure Analysis Date"
END_OF_SERVICE_CONTRACT_RENEWAL_... |
qiime2/q2-types | q2_types/sample_data/_type.py | Python | bsd-3-clause | 832 | 0 | # ----------------------------------------------------------- | -----------------
# Copyright (c) 2016-2021, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software. |
# ----------------------------------------------------------------------------
from qiime2.plugin import SemanticType
from ..plugin_setup import plugin
from . import AlphaDiversityDirectoryFormat
SampleData = SemanticType('SampleData', field_names='type')
AlphaDiversity = SemanticType('AlphaDiversity',
... |
DigitalCampus/django-oppia | tests/test_course_upload.py | Python | gpl-3.0 | 14,057 | 0.001636 | import pytest
from django.urls import reverse
from gamification.models import CourseGamificationEvent, \
MediaGamificationEvent, \
ActivityGamificationEvent
from oppia.test import OppiaTestCase
from oppia.models import Course, CoursePublishingLog, Quiz, A... | mark.xfail(reason="works on local but not on github workflows")
def test_course_with_custom_points(self):
course_game_events_start = CourseGamificationEvent. \
objects.all().count()
media_game_events_start = MediaGamificationEvent. \
objects.all(). | count()
activity_game_events_start = ActivityGamificationEvent. \
objects.all().count()
with open(self.course_with_custom_points, 'rb') as course_file:
self.client.force_login(self.admin_user)
response = self.client.post(reverse('oppia:upload'),
... |
e0ne/cinder | cinder/tests/test_smbfs.py | Python | apache-2.0 | 22,226 | 0 | # Copyright 2014 Cloudbase Solutions Srl
#
# 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 ... | AL_AVAILABLE = '1024'
_FAKE_TOTAL_ALLOCATED = 1024
_F | AKE_VOLUME = {'id': '4f711859-4928-4cb7-801a-a50c37ceaccc',
'size': 1,
'provider_location': _FAKE_SHARE,
'name': _FAKE_VOLUME_NAME,
'status': 'available'}
_FAKE_MNT_POINT = os.path.join(_FAKE_MNT_BASE, 'fake_hash')
_FAKE_VOLUME_PATH... |
regardscitoyens/sunshine-data | scripts/format_pharmaciens.py | Python | agpl-3.0 | 1,072 | 0.001866 | # -*- coding: utf-8 -*-
import pandas as pd
import sys
from builtins import str as text
from utils import find_zipcode, str2date
header_mapping = {
'origin': 'ORIGIN',
'company_name': 'LABO',
'lastname_firstname': 'BENEF_PS_QUALITE_NOM_PRENOM',
'address': 'BENEF_PS_ADR',
'job': 'BENEF_PS_QUALIFIC... | BENEF_PS_RPPS',
'value': 'DECL_AVANT_MONTANT',
'date': 'DECL_AVANT_DATE',
'kind': 'DECL_AVANT_NATURE',
'BENEF_PS_CODEPOSTAL': 'BENEF_PS_CODEPOSTAL'
}
input_filename = sys.argv[1]
output_filename = sys.argv[2]
df = pd.read_csv(input_filename, encoding | ='utf-8')
df['lastname_firstname'] = df['name'] + ' ' + df['firstname']
df['origin'] = 'Pharmacien'
df['date'] = df['date'].apply(str2date)
df['BENEF_PS_CODEPOSTAL'] = df['address'].apply(find_zipcode)
for origin, target in header_mapping.items():
df[target] = df[origin]
df[target] = df[target].apply(text).ap... |
giuserpe/leeno | src/Ultimus.oxt/python/pythonpath/LeenoPdf.py | Python | lgpl-2.1 | 8,880 | 0.003154 | import os
import LeenoUtils
import DocUtils
import SheetUtils
import Dialogs
import LeenoSettings
import LeenoConfig
_EXPORTSETTINGSITEMS = (
'npElencoPrezzi',
'npComputoMetrico',
'npCostiManodopera',
'npQuadroEconomico',
'cbElencoPrezzi',
'cbComputoMetrico',
'cbCostiManodopera',
'cbQua... | eet.PrintAreas) > 0:
print("PAGE HAS PRINT AREA")
nDoc.Sheets[pos].P | rintAreas = sheet.PrintAreas
# replaces all placeholders with settings ones
settings = LeenoSettings.loadPageReplacements(oDoc)
for key, val in docSubst.items():
settings[key] = val
SheetUtils.replaceText(nDoc.Sheets[pos], settings)
# close cover document and return
cDoc.close(False)
... |
vup1120/oq-hazardlib | openquake/hazardlib/gsim/zhao_2006_swiss.py | Python | agpl-3.0 | 6,612 | 0.003479 | # -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (C) 2014-2016 GEM Foundation
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the Licen... | FS_ROCK_SWISS05,
COEFFS_FS_ROCK_SWISS03,
COEFFS_FS_ROCK_SWISS08
)
from openquake.hazardlib.gsim.utils_swiss_gmpe import _apply_adjustments
class ZhaoEtAl2006AscSWISS05(ZhaoEtAl2006Asc):
"""
This class extends :class:ZhaoEtAl2006Asc,
adjusted to be used for the Swiss Hazard Model [2014].
This ... | 700m/s
#. kappa value
K-adjustments corresponding to model 01 - as prepared by Ben Edwards
K-value for PGA were not provided but infered from SA[0.01s]
the model applies to a fixed value of vs30=700m/s to match the
reference vs30=1100m/s
#. small-magnitude correction
#. singl... |
aspose-words/Aspose.Words-for-Java | Plugins/Aspose_Words_Java_for_Jython/asposewords/quickstart/UpdateFields.py | Python | mit | 2,621 | 0.007631 | from asposewords import Settings
from com.aspose.words import Document
from com.aspose.words import BreakType
from com.aspose.words import DocumentBuilder
from com.aspose.words import StyleIdentifier
class UpdateFields:
def __init__(self):
dataDir = Settings.dataDir + 'quickstart/'
# Demo... | )
builder.insertField("DATE")
# Start the actual document content on the second page.
builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE)
# Build a document with complex structure by applying different heading styles thus creating TOC entries.
builder.getParag... | ragraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_2)
builder.writeln("Heading 1.1")
builder.writeln("Heading 1.2")
builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_1)
builder.writeln("Heading 2")
builder.writeln("Heading 3")
# Move... |
kcsaff/getkey | tests/unit/test_getkey.py | Python | mit | 1,320 | 0 | # -*- coding: utf-8 -*-
import unittest
from getkey.platforms import PlatformTest
def readchar_fn_factory(stream):
v = [x for x in stream]
def inner(blocking=False):
return v.pop(0)
return inner
class TestGetkey(unittest.TestCase):
def test_basic_character(self):
getkey = Platform... | combo_character(self):
char = '\x1b\x01'
getkey = PlatformTest(char + 'foo').getkey
result = getkey()
self.assertEqual(char, result)
def test_special_key(self):
char = '\x1b\x5b\x41'
getkey = PlatformTest(char + 'foo').getkey
result | = getkey()
self.assertEqual(char, result)
def test_special_key_combo(self):
char = '\x1b\x5b\x33\x5e'
getkey = PlatformTest(char + 'foo').getkey
result = getkey()
self.assertEqual(char, result)
def test_unicode_character(self):
text = u'Ángel'
getkey... |
JesGor/test_rest | apprest/models.py | Python | gpl-2.0 | 432 | 0.032407 | from django.db import models
class Empresa(models.Model):
nombre = models.CharField(max_length=100)
ciudad = models.CharField(max_length=50)
sector = models.CharField(max_length=200)
def __str__(self):
return s | elf.nombre
class Calificacion(models.Model):
alumno = models.CharField(max_length=100)
calificacion = models.IntegerField(default=0)
empresa = models.ForeignKey(Empresa)
def __str__(self):
| return self.alumno
|
espenak/django_seleniumhelpers | seleniumhelpers/__init__.py | Python | bsd-3-clause | 150 | 0 | fr | om seleniumhelpers import SeleniumTestCase
from seleniumhelpers import get_default_timeout
from seleniumhelpers import get_setting_with_envfa | llback
|
Conchylicultor/MusicGenerator | deepmusic/modules/decoder.py | Python | apache-2.0 | 7,461 | 0.002949 | # Copyright 2016 Conchylicultor. 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 ... | state) # Should we do the activation sigmoid here ? Maybe not because the loss function does it
return next_keyboard, next_state_deco
class Lstm(DecoderNetwork):
""" Multi-layer Lstm. Just a wrapper around the official tf
"""
@staticmethod
def get_module_id():
return 'lstm'
def ... | args)
self.args = args
self.rnn_cell = None
self.project_keyboard = None # Fct which project the decoder output into the ouput space
def build(self):
""" Initialize the weights of the model
"""
# TODO: Control over the the Cell using module arguments instead of glo... |
ionomy/ion | test/functional/p2p-fingerprint.py | Python | mit | 5,852 | 0.001025 | #!/usr/bin/env python3
# Copyright (c) 2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test various fingerprinting protections.
If an stale block more than a month old or its header are requeste... | test_function = lambda: self.last_header_equals(stale_hash, node0)
wait_until(test_function, timeout=3)
# Longest chain is extended so stale is much older than chain tip
self.nodes[0].setmocktime(0)
tip = self.nodes[0].generate(nblocks=1)[0]
assert_equal(self.nodes[0].getblockc... | end_header_request(block_hash, node0)
node0.sync_with_ping()
# Request for very old stale block should now fail
self.send_block_request(stale_hash, node0)
time.sleep(3)
assert not self.last_block_equals(stale_hash, node0)
# Request for very old stale block header should... |
jluscher/SCANIT | scanit_v033.py | Python | cc0-1.0 | 86,949 | 0.018045 | #! /usr/bin/env python3
#
# SCANIT - Control A spectrometer and collect data
#
# LICENSE:
# This work is licensed under the Creative Commons Zero License
# Creative Commons CC0.
# To view a copy of this licen | se, visit
# http://directory.fsf.org/wiki/License:CC0
# or send a letter to:
# Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
#
# Author: James Luscher, jluscher@gmail.com
#
import sys, string, time
import serial
#
from pathlib import Path
#
from tkinter import *
from tkinter import font
from tkinter impo... | tkinter.ttk import Progressbar
# from tkinter import ttk
# from tkinter.scrolledtext import *
import tkinter.messagebox as mBox
# import tkinter.simpledialog as simpledialog
import matplotlib
from matplotlib.widgets import Cursor
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg... |
leandroreox/gnocchi | gnocchi/incoming/file.py | Python | apache-2.0 | 7,168 | 0 | # -*- encoding: utf-8 -*-
#
# 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, so... | s.rename | (tmpfile.name, path)
break
except OSError as e:
if e.errno != errno.ENOENT:
raise
try:
os.mkdir(self._build_measure_path(metric.id))
except OSError as e:
# NOTE(jd) It's possible that ... |
HopeFOAM/HopeFOAM | ThirdParty-0.1/ParaView-5.0.1/Examples/Catalyst/PythonDolfinExample/simulation-catalyst-step1.py | Python | gpl-3.0 | 4,910 | 0.003259 | """This demo program solves the incompressible Navier-Stokes equations
on an L-shaped domain using Chorin's splitting method."""
# Copyright (C) 2010-2011 Anders Logg
#
# This file is part of DOLFIN.
#
# DOLFIN is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Publi... | import of both Dolfin and ParaView
execfile("simulation-env.py")
# [SC14-Catalyst] import paraview, vtk and paraview's simple API
import sys
imp | ort paraview
import paraview.vtk as vtk
import paraview.simple as pvsimple
# [SC14-Catalyst] check for command line arguments
if len(sys.argv) != 3:
print "command is 'python",sys.argv[0],"<script name> <number of time steps>'"
sys.exit(1)
# [SC14-Catalyst] initialize and read input parameters
paraview.option... |
almet/whiskerboard | settings/live.py | Python | mit | 161 | 0.006211 | from __future__ import absolute_import
from .base import *
from .local import *
CACHE_B | ACKEND = 'redis_cache.cache://127.0.0.1:6379/?ti | meout=15'
DEBUG = False
|
llv22/python3_learning | chapter4/sample.py | Python | apache-2.0 | 1,306 | 0.006126 | """
Learning python3
"""
def document_it(func):
'''
decractor for func, only print doc of func.
'''
def new_function(*args, **kwargs):
'''
internal function for wrappering of func and print out function parameter and result.
'''
print('Running functions:', func.__name__)
... | ord arguments:', kwargs)
result = func(*args, **kwargs)
print('Result:', result)
return result
return new_funct | ion
@document_it
def add_ints0(add_a, add_b):
'''
add with decrator of @document_it.
'''
return add_a + add_b
def square_it(func):
'''
decractor for func, return square of func returned value.
'''
def new_function(*args, **kwargs):
'''
internal function for wrappering o... |
Jokeren/neon | tests/test_gru.py | Python | apache-2.0 | 16,734 | 0.000418 | # ----------------------------------------------------------------------------
# Copyright 2015-2016 Nervana Systems 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.apa... | U bprop deltas to the gradients
estimated by finite differences.
The numpy reference GRU contains static methods for forward pass
and backward pass.
It runs a SINGLE layer of GRU and compare numerical values
The following are made sure to be the same in both GRUs
- initial h values (all zeros)
- initial W,... | nput_size.
Need transpose
- the data shape inside GRU (neon) is is batch_size, seq_len * batch_size
"""
import itertools as itt
import numpy as np
from neon import NervanaObject, logger as neon_logger
from neon.initializers.initializer import Constant, Gaussian
from neon.layers import GRU
from neon.tran... |
kerneltask/micropython | tests/unicode/unicode_subscr.py | Python | mit | 336 | 0 | a = "¢пр"
print(a[0], a[0:1])
print(a[1], a[1:2])
print( | a[2], a[2:3])
try:
print(a[3])
except IndexError:
print("IndexError")
print(a[3:4])
print(a[-1])
print(a[-2], a[-2:-1])
print(a[-3], a[-3:-2])
try:
print(a[-4])
except IndexError:
print("IndexError")
print(a[-4:-3])
| print(a[0:2])
print(a[1:3])
print(a[2:4])
|
chrisjaquet/FreeCAD | src/Mod/Arch/ArchSite.py | Python | lgpl-2.1 | 5,788 | 0.017623 | # -*- coding: utf8 -*-
#***************************************************************************
#* *
#* Copyright (c) 2011 *
#* Yorik van Havre <yorik@uncreated.net> ... | lse:
def transla | te(ctxt,txt):
return txt
__title__="FreeCAD Site"
__author__ = "Yorik van Havre"
__url__ = "http://www.freecadweb.org"
def makeSite(objectslist=None,baseobj=None,name="Site"):
'''makeBuilding(objectslist): creates a site including the
objects from the given list.'''
obj = FreeCAD.ActiveDocument.ad... |
sjirjies/pyJacqQ | tests/generate_null_dataset.py | Python | gpl-3.0 | 4,011 | 0.00374 | # This file is part of jacqq.py
# Copyright (C) 2015 Saman Jirjies - sjirjies(at)asu(dot)edu.
#
# 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 opt... | )
finally:
csv_file.close()
# Generate time series data
csv_file = open(args.histories_data, 'w')
try:
writer = csv.writer(csv_file)
writer.writerow((' | ID', 'start_date', 'end_date', 'x', 'y'))
start_date = '20150101'
end_date = '20150102'
for id_index, case_point in enumerate(case_locations):
writer.writerow(('case_'+str(id_index+1), start_date, end_date, case_point[0], case_point[1]))
writer.writerow(('control_'+str(id... |
astropy/photutils | photutils/centroids/tests/test_gaussian.py | Python | bsd-3-clause | 4,408 | 0 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Tests for the core module.
"""
import itertools
from contextlib import nullcontext
from astropy.modeling.models import Gaussian1D, Gaussian2D
from astrop | y.utils.exceptions import A | stropyUserWarning
import numpy as np
from numpy.testing import assert_allclose
import pytest
from ..gaussian import centroid_1dg, centroid_2dg, _gaussian1d_moments
from ...utils._optional_deps import HAS_SCIPY # noqa
XCEN = 25.7
YCEN = 26.2
XSTDS = [3.2, 4.0]
YSTDS = [5.7, 4.1]
THETAS = np.array([30., 45.]) * np.pi... |
SEMAFORInformatik/femagtools | femagtools/plot.py | Python | bsd-2-clause | 54,354 | 0.000515 | # -*- coding: utf-8 -*-
"""
femagtools.plot
~~~~~~~~~~~~~~~
Creating plots
"""
import numpy as np
import scipy.interpolate as ip
import logging
try:
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from mpl_toolkits.mplot3d import Axes3D
matplotlibversion... | ))
if slope_degrees < 0:
slope_degrees += 180
if 90 < slope_degrees <= 270:
slope_degrees += 180
x_offset = np.sin(np.deg2rad(slope_degrees))
y_offset = np.cos(np.deg2rad(slope_degrees))
bbox_props = dict(boxstyle="Round4, pad=0.1", fc="white", lw=0)
... | size=size, color=color,
horizontalalignment='center',
verticalalignment='center',
fontfamily='monospace', fontweight='bold', bbox=bbox_props)
text.set_rotation(slope_degrees)
return text
if ax == 0:
... |
nke001/attention-lvcsr | libs/Theano/theano/gof/__init__.py | Python | mit | 2,704 | 0 | """
gof.py
gof stands for Graph Optimization Framework
The gof submodule of theano implements a framework
for manipulating programs described as graphs. The
gof module defines basic theano graph concepts:
-Apply nodes, which represent the application
of an Op to Variables. Together these make up a
graph.
-The... | WrapLinker, WrapLinkerMany
from | theano.gof.op import \
Op, OpenMPOp, PureOp, COp, ops_with_inner_function
from theano.gof.opt import (
Optimizer,
optimizer, inplace_optimizer,
SeqOptimizer,
MergeOptimizer,
LocalOptimizer, local_optimizer, LocalOptGroup,
OpSub, OpRemove, PatternSub,
NavigatorOptimizer, TopoOptimizer, E... |
appop/bitcoin | qa/rpc-tests/test_framework/siphash.py | Python | mit | 2,010 | 0.001493 | #!/usr/bin/env python3
# Copyright (c) 2016 The nealcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Specialized SipHash-2-4 implementations.
This implements SipHash-2-4 for 256-bit integers.
"""
def rotl64... | 1, v2, v3)
v0 ^= n2
v3 ^= n3
v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3)
v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3)
v0 ^= n3
v3 ^= 0x2000000000000000
v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3)
v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3)
v0 ^= 0x2000000000000000
v2 ^... | h_round(v0, v1, v2, v3)
return v0 ^ v1 ^ v2 ^ v3
|
Teamxrtc/webrtc-streaming-node | third_party/webrtc/src/chromium/src/third_party/closure_compiler/processor_test.py | Python | mit | 3,825 | 0.00366 | #!/usr/bin/env python
# Copyright 2014 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.
"""Test resources processing, i.e. <if> and <include> tag handling."""
import unittest
from processor import FileCache, Processor, Lin... | f assertLineNumber(self, abs_line, expected_line):
actual_line = self._processor.get_file_from_line(abs_line)
self.assertEqual(expected_line.file, actual_line.file)
self.a | ssertEqual(expected_line.line_number, actual_line.line_number)
def testGetFileFromLine(self):
"""Verify that inlined files retain their original line info."""
self.assertLineNumber(1, LineNumber("/checked.js", 1))
self.assertLineNumber(5, LineNumber("/checked.js", 5))
self.assertLineNumber(6, LineNum... |
kreatorkodi/repository.torrentbr | plugin.video.youtube/resources/lib/youtube_plugin/kodion/utils/access_manager.py | Python | gpl-2.0 | 12,104 | 0.003057 | import uuid
import time
from hashlib import md5
from ..json_store import LoginTokenStore
__author__ = 'bromix'
class AccessManager(object):
def __init__(self, context):
self._settings = context.get_settings()
self._jstore = LoginTokenStore()
self._json = self._jstore.get_data()
... | d
self._ | jstore.save(self._json)
self._settings.set_string('youtube.folder.watch_later.playlist', '')
return self._json['access_manager']['users'].get(self._user, {}).get('watch_later', ' WL')
def set_watch_later_id(self, playlist_id):
"""
Sets the current users watch later playlist id
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.