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
kajgan/stbgui
lib/python/Plugins/SystemPlugins/CableScan/plugin.py
Python
gpl-2.0
11,601
0.025343
from Screens.Screen import Screen from Screens.MessageBox import MessageBox from Plugins.Plugin import PluginDescriptor from Components.Label import Label from Components.ActionMap import ActionMap from Components.NimManager import nimmanager from Components.MenuList import MenuList from Components.config import config...
self.progressbar.setValue(progress) def scanCompleted(self, result): self.done = True if result < 0: self.text.setText( _('Scanning failed!') + "\n" + _("Please press OK to continue.") ) else: self.text.setText(ngettext("Scanning completed, %d channel found", "Scanning com
pleted, %d channels found", result) % result) def destroy(self): pass def isDone(self): return self.done class CableScanStatus(Screen): skin = """ <screen position="center,center" size="580,130" title="Cable Scan"> <widget name="frontend" pixmap="skin_default/icons/scan-c.png" position="10,10" size="64,64" t...
wooga/airflow
tests/kubernetes/test_pod_generator.py
Python
apache-2.0
28,223
0.000425
# 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...
sult) # sort result_dict['spec']['containers'][0]['env'].sort(key=lambda x: x['name']) result_dict['spec']['containers'][0]['envFrom'].sort( key=lambda x: list(x.values())[0]['name'] ) self.assertDictEqual(self.expected, result_dict) @mock.patch('uuid.uuid4') ...
eturn_value = self.static_uuid pod_generator = PodGenerator( labels={'app': 'myapp'}, name='myapp-pod', image_pull_secrets='pull_secret_a,pull_secret_b', image='busybox', envs=self.envs, cmds=['sh', '-c', 'echo Hello Kubernetes!'], ...
stephenplaza/NeuTu
neurolabi/python/TaskManager.py
Python
bsd-3-clause
1,355
0.005904
import uuid import os import sys class Scheduler: def __init__(self): home = os.path.expanduser('~') self.jobDir = os.path.join(home, 'local/scheduled')
def submit(self, command, dependency = None, finishedFlag = None): if not isinstance(dependency, list): print 'depencency must be a list. Abort' return jobPath = os.path.join(self.jobDir, str(uuid.uuid4()) + '.sh') f = open(jobPath, 'w') if f: if de...
) f.write('touch ' + jobPath + '.started\n') if isinstance(command, str): f.write(command + '\n') elif isinstance(command, list): for line in command: f.write(line + '\n') if finishedFlag: f.write('if [...
startup-guide/django-ses-analytics
ses_analytics/urls.py
Python
mit
228
0.013158
fr
om django.conf.urls import patterns, url urlpatterns = patterns('', url(r'^img1x1$', 'ses_analytics.views.img1x1', name='img1x1'), # used to trace email opening # TODO: unsubscription a
nd SNS feedback notifications )
mohamed--abdel-maksoud/chromium.src
tools/telemetry/telemetry/core/platform/linux_platform_backend_unittest.py
Python
bsd-3-clause
1,851
0.009184
# 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. import os import unittest from telemetry import decorators from telemetry.core import util from
telemetry.core.platform import linux_platform_backend class TestBackend( linux_platform_backend.LinuxPlatformBackend): def __init__(self): super(TestBackend, self).__init__() self._mock_files = {}
def SetMockFile(self, filename, output): self._mock_files[filename] = output def GetFileContents(self, filename): return self._mock_files[filename] def IsThermallyThrottled(self): raise NotImplementedError() def HasBeenThermallyThrottled(self): raise NotImplementedError() def GetSystemCom...
jrbl/invenio
modules/bibauthorid/lib/bibauthorid_wedge.py
Python
gpl-2.0
11,722
0.003668
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2011, 2012 CERN. ## ## Invenio 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 opt...
ing obvious clusters done.") bibauthor_print("Sorting the value edges.") edges = sorted(edges,
key=edge_sorting, reverse=True) interval = 1000 wedge_print("Wedge: New wedge, %d edges." % len(edges)) for current, (v1, v2, unused) in enumerate(edges): if (current % interval) == 0: update_status(float(current) / len(edges), "Wedge...") assert unused != '+' and unused != '-...
dsanders11/django-autocomplete-light
test_remote_project/test_remote_project/settings.py
Python
mit
5,785
0.002593
# Django settings for test_remote_project project. import os.path import posixpath PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) FIXTURE_DIRS = [ os.path.join(PROJECT_ROOT, 'fixtures'...
r path to database file if using sqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Se...
although not all choices may be available on all operating systems. # On Unix systems, a value of None will cause Django to use the same # timezone as the operating system. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Chicago' # Language code for t...
informaticienzero/CodinGame
Communautaires/[UT] The lucky number.py
Python
mit
7,749
0.003742
import unittest from LuckyNumbers import count from typing import Dict, List class TestLuckyNumbers(unittest.TestCase): """ All the unit tests of the lucky numbers program. """ def test_count_0(self): """ Tests the simplest case, with 0. """ self.assertEqual(count(0), ...
00_000
result: int = 374_421 self.assertEqual(count(value), result, f'Between 0 and {value}, there are {result} lucky numbers.') def test_count_770_000(self): """ Test the fast method with 770000. """ value: int = 770_000 result: int = 410_562 self.assertEqual(coun...
AlmiS/siridb-server
grammar/siridbhelp.py
Python
mit
772
0.002591
'''Help module. Build help structure for SiriDB grammar. :copyright: 2016, Jeroen van der Heijden (Transceptor Technology) ''' import os import re import sys # # Created with ls -A1 # help_files = [f[:-3
] for f in os.listdir('../help') if f.endswith('.md')] help_files.sort() def _build_structure(help_files): '''Return a tree structure for the help files.''' _structure = {} def _walk(d, keys, i): i += 1 k = tuple(keys[:i]) if k not in d: d[
k] = {} if i < len(keys): _walk(d[k], keys, i) for help_file in help_files: _walk(_structure, help_file.split('_'), 0) return _structure help_structure = _build_structure(help_files) if __name__ == '__main__': print(help_structure)
fantuanmianshi/Daily
LeetCode/path_sum.py
Python
mit
1,167
0.001714
""" Given a binary tree and a sum, determine if th
e tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. For example: Given the below binary tree and sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1 return true, as there exist ...
ode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param {TreeNode} root # @param {integer} sum # @return {boolean} def hasPathSum(self, root, sum): if root is None: return False return self.solv...
alanudg/SmartCheckIn
app/models/User.py
Python
mit
638
0
from flask_security import UserMixin from app import config from app.models.Role import Role db = config.db class User(db.Document, UserMixin): email = db.StringField(max_length=255) password = db.StringField(max_length=512) active = db.BooleanField(default=True) last_login_at = db.StringField(max_le...
(max_length=255) current_login_ip = db.StringField(max_length=255) lo
gin_count = db.StringField(max_length=255) confirmed_at = db.DateTimeField() roles = db.ListField(db.ReferenceField(Role), default=[])
meteogrid/FTPRelayer
setup.py
Python
bsd-3-clause
813
0.02952
from setuptools import
setup, find_packages setup(name='FTPRelayer', version='0.2.1', description="Redistributes files which arrive at a machine to several machines", long_description="""\ """, classifiers=[], keywords='', author='Meteogrid', author_email='alberto@meteogrid.com', url='https://gi
thub.com/meteogrid/FTPRelayer', license='BSD3', packages=find_packages(), include_package_data=True, test_suite = "nose.collector", zip_safe=True, dependency_links = [ ], install_requires=[ "configobj", "ftputil", "pyinotify", "davclient", ], extras_re...
lnls-sirius/dev-packages
siriuspy/siriuspy/injctrl/main.py
Python
gpl-3.0
40,205
0
"""Main module of Machine Shift Application.""" import time as _time from threading import Thread as _Thread import logging as _log import numpy as _np from ..util import update_bit as _updt_bit, get_bit as _get_bit from ..namesys import SiriusPVName as _PVName from ..epics import PV as _PV from ..callbacks import Cal...
elf._egun_dev.pulse.pv_object('multiswstatus').add_callback( self._callback_update_type) self._egun_dev.pulse.pv_object('singleselstatus').add_callback( self._callback_update_type) self.
_egun_dev.pulse.pv_object('singleswstatus').add_callback( self._callback_update_type) self._egun_dev.trigmultipre.pv_object('State-Sts').add_callback( self._callback_update_type) self._egun_dev.trigmulti.pv_object('State-Sts').add_callback( self._callback_update_type)...
tboyce021/home-assistant
homeassistant/components/tuya/climate.py
Python
apache-2.0
7,772
0.000386
"""Support for the Tuya climate devices.""" from datetime import timedelta import logging from homeassistant.components.climate import ( DOMAIN as SENSOR_DOMAIN, ENTITY_ID_FORMAT, ClimateEntity, ) from homeassistant.components.climate.const import ( FAN_HIGH, FAN_LOW, FAN_MEDIUM, HVAC_MODE_...
def hvac_modes(self): """Return the list of available operation modes.""" return self.op
erations @property def current_temperature(self): """Return the current temperature.""" return self._tuya.current_temperature() @property def target_temperature(self): """Return the temperature we try to reach.""" return self._tuya.target_temperature() @property ...
Techcable/DiffUtils
diffutils/_myers.py
Python
apache-2.0
7,995
0.001501
# Copyright 2010 Dmitry Naumenko (dm.naumenko@gmail.com) # Copyright 2015 Techcable # # 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...
-d) or (k != d and diagonal[kminus].i < diagonal[kplus].i): i = diagonal[kplus].i pre
v = diagonal[kplus] else: i = diagonal[kminus].i + 1 prev = diagonal[kminus] diagonal[kminus] = None j = i - k node = create_diff_node(i, j, prev) # orig and rev are zero-based # but the algorithm is one-based ...
yosisa/pyfluent
setup.py
Python
apache-2.0
1,712
0.000584
# -*- coding: utf-8 -*- # Copyright 2012 Yoshihisa Tanaka # # 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 ...
verning permissions and # limitations under the License. import os from setuptools import find_packages, setup name = 'pyfluent' version = '0.2.1' readme = os.path.join(os.path.dirname(__file__), 'README.rst') long_descr
iption = open(readme).read() classifiers = [ 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: So...
onepercentclub/onepercentclub-site
onepercentclub/settings/testing.py
Python
bsd-3-clause
670
0.004478
#
# NOTE: This is the settings file for the server at https://testing.onepercentclub.com # This is not for running tests! # try: from .secrets import * except ImportError: import sys sys.exit('secrets.py settings file not found. Please run `prepare.sh` to create one.') from .server import * # # Put t...
ASE = 'https://testing.onepercentclub.com' COWRY_LIVE_PAYMENTS = False # Send email for real EMAIL_BACKEND = 'bluebottle.utils.email_backend.TestMailBackend' SESSION_COOKIE_NAME = 'bb-testing-session-id' SOUTH_TESTS_MIGRATE = False try: print "DEBUG", DEBUG except: pass
sacharya/nova
nova/virt/firewall.py
Python
apache-2.0
21,771
0.000322
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # Copyright (c) 2011 Citrix Systems, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you m...
self.dhcp_created = False self.iptables.ipv4['filter'].add_chain('sg-fallback') self.iptables.ipv4['filter'].add_rule('sg-fallback', '-j DROP') self.iptables.ipv6['filter'].add_chain('sg-fallback') self.iptables.ipv6['filter'].add_rule('sg-fallback', '-j DROP') def setup_basic_fi...
_info): """No-op. Everything is done in prepare_instance_filter.""" pass def filter_defer_apply_on(self): self.iptables.defer_apply_on() def filter_defer_apply_off(self): self.iptables.defer_apply_off() def unfilter_instance(self, instance, network_info): if self.i...
pichillilorenzo/JavaScript-Completions
helper/helper_class.py
Python
mit
105
0
H_SETTINGS_FOLD
ER_NAME = "helper" H_SETTINGS_FOLDER = os.path.join(PACKAGE_PATH, H_SETTINGS_FOLDER_NAME)
sebastian-code/jsonb-test
jsonb/emporium/models.py
Python
mit
986
0
from django.db import models from django.contrib.postgres.fields.jsonb import JSONField class Supplier(models.Model): name = models.CharField(max_length=50)
tax_id = models.CharField(max_length=10) def __
str__(self): return self.name class Bargain(models.Model): sku = models.CharField(max_length=20) price = models.DecimalField(max_digits=7, decimal_places=2) supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE, db_index=True) info = JSONField(db_inde...
multatronic/akurra
akurra/__init__.py
Python
mit
5,555
0.00144
"""Main module.""" import os import pygame import signal import logging import argparse from threading import Event from multiprocessing import Value from injector import Injector, singleton from ballercfg import ConfigurationManager from .locals import * # noqa from .events import EventManager, TickEvent from .mo...
nd(Akurra, to=self) # Start pygame (+ audio frequency, size, channels, buffersize) pygame.mixer.pre_init(44100, 16, 2, 4096) pygame.init() configure_logging(log_level=self.log_level) logger.info('Initializing..') self.configuration = self.container.get(Configuration) ...
self.modules = ModuleLoader( group=self.configuration.get('akurra.modules.entry_point_group', 'akurra.modules'), whitelist=self.configuration.get('akurra.modules.whitelist', None), blacklist=self.configuration.get('akurra.modules.blacklist', None), ) self.gam...
griest024/PokyrimTools
pyffi-develop/pyffi/formats/psk/__init__.py
Python
mit
7,404
0.00054
""" :mod:`pyffi.formats.psk` --- Unreal (.psk & .psa) ================================================= A .psk file contains static geometry data, a .psa contains animation keyframes. Implementation -------------- .. autoclass:: PskFormat :show-inheritance: :members: Regression tests ---------------- Read a ...
ad psk file >>> stream = open('tests/psk/examplemesh.psk', 'rb') >>> data = PskFormat.Data() >>> data.inspect(stream) >>> # do some stuff with header? >>> data.read(stream) # doctest: +ELLIPSIS >>> # do some stuff with data? Parse all PSK files in a directory tree ^^
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ >>> for stream, data in PskFormat.walkData('tests/psk'): ... print(stream.name) tests/psk/examplemesh.psk Create an PSK file from scratch and write to file ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ >>> data = PskFormat.Data() >>> from tempfile import TemporaryFile >>...
ksamdev/algorithms_old
ch4/python/ch4_ex4.1.4.py
Python
mit
1,523
0
#!/usr/bin/env python # # Created by Samvel Khalatyan on Mar 23, 2014 # Copyright (c) 2014 Samvel Khalatyan. All rights reserved # # Use of this source code is governed by a license that can be found in # the LICENSE file. import random import unittest from lib import unigraph class UnigraphExtra(unigraph.Unigraph)...
(random.randrange(self.graph.vertices()) for x in range(2)) self.graph.add_edge(f, t) def test_edge(self): for vertex in range(self.graph.vertices()): existing_vertices = set(self.graph._vertices[vertex]) all_vertices = set(range(self.graph.vertices())) miss...
_vertex in existing_vertices: self.assertTrue(self.graph.has_edge(vertex, adj_vertex)) for adj_vertex in missing_vertices: self.assertFalse(self.graph.has_edge(vertex, adj_vertex)) def test_self_loop(self): for vertex in range(self.graph.vertices()): ...
dicos/smirik
smirik/common_helpers.py
Python
bsd-2-clause
1,076
0.006506
#coding: utf8 import os from django.db import transaction def rel(*x): return os.path.abspath(os.path.join(os.path.abspath(os.path.dirname(__file__)), os.pardir, *x)) def nested_commit_on_success(func): """Like commit_on_success, but doesn't commit existing transactions. This decorator is used to ...
rollbacks, leaving that up to whoever is managing the active transaction. """ commit_on_success = transaction.commit_on_success(func) def _nested_commit_on_success(*args, **kwds): if
transaction.is_managed(): return func(*args,**kwds) else: return commit_on_success(*args,**kwds) return transaction.wraps(func)(_nested_commit_on_success)
erikgrinaker/python-chrono
tests/test_calendar/test_us.py
Python
gpl-3.0
6,175
0
#!/usr/bin/env python import chrono import unittest class USCalendarTest(unittest.TestCase): def test__subclass(self): "USCalendar is subclass of Calendar" self.assertTrue( issubclass(chrono.calendar.USCalendar, chrono.calendar.Calendar) ) class USCalendar_weekdateTest(uni...
def test_invalid(self): "USCalendar.weekdayname() raises DayError on invalid weekday" self.assertRaises( chrono.DayError, chrono.cal
endar.USCalendar.weekdayname, 8 ) class USCalendar_weeksTest(unittest.TestCase): def test_2010(self): "USCalendar.weeks() returns 52 for 2010" self.assertEquals(chrono.calendar.USCalendar.weeks(2010), 52) def test_2011(self): "USCalendar.weeks() returns 53 for 2011" ...
dbrumley/recfi
llvm-3.3/utils/lit/tests/shtest-format.py
Python
mit
1,371
0
# Check the various features of the ShTest format. # # RUN: not %{lit} -j 1 -v %{inputs}/shtest-format > %t.out # RUN: FileCheck < %t.out %s # # END. # CHECK: -- Testing: # CHECK: FAIL: shtest-format :: external_shell/fail.txt # CHECK: *** TEST 'shtest-format :: external_shell/fail.txt' FAILED *** # CHECK: Command Ou...
xt # CHECK: PASS: shtest-format :: requires-present.txt
# CHECK: UNSUPPORTED: shtest-format :: unsupported_dir/some-test.txt # CHECK: XFAIL: shtest-format :: xfail-feature.txt # CHECK: XFAIL: shtest-format :: xfail-target.txt # CHECK: XFAIL: shtest-format :: xfail.txt # CHECK: XPASS: shtest-format :: xpass.txt # CHECK: Testing Time # CHECK: Unexpected Passing Tests (1) # ...
uni-peter-zheng/tp-qemu
qemu/tests/qmp_basic.py
Python
gpl-2.0
14,858
0
from autotest.client.shared import error from virttest import qemu_monitor def run(test, params, env): """ QMP Specification test-suite: this checks if the *basic* protocol conforms to its specification, which is file QMP/qmp-spec.txt in QEMU's source tree. IMPORTANT NOTES: o Most tests depe...
""" Check the QMP greeting message version key which, according to QMP's documentation, should be: { "qemu": { "major": json-int, "minor": json-int, "micro": json-int } "package": json-string } """ check_key_is_dict(version, "qemu") for key in ("major", "mi...
ey) check_key_is_str(version, "package") def test_greeting(greeting): check_key_is_dict(greeting, "QMP") check_key_is_dict(greeting["QMP"], "version") check_key_is_list(greeting["QMP"], "capabilities") def greeting_suite(monitor): """ Check the greeting message ...
dietrichc/streamline-ppc-reports
examples/dfp/v201405/creative_wrapper_service/get_active_creative_wrappers.py
Python
apache-2.0
2,368
0.008024
#!/usr/bin/python # # Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
ntials and properties from a "googleads.yaml" file. By default, it looks for this file in your home directory. For more information, see the "Caching authentication information" section of our README. Tags: CreativeWrapperService.getCreativeWrappersByStatement """ __author__ = ('Nicholas Chen', 'Joseph ...
def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', version='v201405') # Create statement object to only select active creative wrappers. values = [{ 'key': 'status', 'value': { ...
rishig/zulip
zerver/management/commands/runtornado.py
Python
apache-2.0
5,167
0.003097
import logging import sys from typing import Any, Callable from django.conf import settings from django.core.management.base import BaseCommand, \ CommandError, CommandParser from tornado import ioloop from tornado.log import app_log # We must call zerver.tornado.ioloop_logging.instrument_tornado_ioloop # before...
%r is not a valid port number." % (port,)) xheaders = options.get('xheaders', True) no_keep_alive = options.get('no_keep_alive', False) quit_command = 'CTRL-C' if
settings.DEBUG: logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)-8s %(message)s') def inner_run() -> None: from django.conf import settings from django.utils import translation translation.activate(settings....
lucperkins/heron
heron/tools/tracker/src/python/handlers/jstackhandler.py
Python
apache-2.0
3,190
0.009091
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright 2016 Twitter. 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...
tornado.gen.coroutine def getInstanceJstack(self, topology_info, instance_id): """ Fetches Instance jstack from heron-shell. """ pid_response = yield getInstancePid(topology_info, instance_id) try: http_client
= tornado.httpclient.AsyncHTTPClient() pid_json = json.loads(pid_response) pid = pid_json['stdout'].strip() if pid == '': raise Exception('Failed to get pid') endpoint = utils.make_shell_endpoint(topology_info, instance_id) url = "%s/jstack/%s" % (endpoint, pid) response = yi...
edickie/ciftify
ciftify/__init__.py
Python
mit
338
0.002959
#!/usr/bin/env pyth
on3 """ The ciftify package uses tools from the Human Connectome Project (HCP) adapted for working with non-HCP datasets """ from . import config from . import utils from . import html from . import qc_config
from . import niio from . import filenames from . import meants from . import report #from commands import *
cbertinato/pandas
pandas/tests/indexes/period/test_indexing.py
Python
bsd-3-clause
25,316
0
from datetime import datetime, timedelta import numpy as np import pytest from pandas._libs.tslibs import period as libperiod import pandas as pd from pandas import ( DatetimeIndex, Period, PeriodIndex, Series, notna, period_range) from pandas.util import te
sting as tm class TestGetItem: def test_ellipsis(self): # GH#21282 idx = period_range('2011-01-01', '2011-01-31', freq='D', name='idx') result = idx[...] assert result.equals(idx) assert result is not idx def test_getitem(self): idx1...
'2011-01-31', freq='D', name='idx') for idx in [idx1]: result = idx[0] assert result == pd.Period('2011-01-01', freq='D') result = idx[-1] assert result == pd.Period('2011-01-31', freq='D') result = idx[0:5] ...
seisman/HinetPy
setup.py
Python
mit
1,864
0.001073
""" Build and install the project. """ from setuptools import find_packages, setup NAME = "HinetPy" AUTHOR = "Dongdong Tian" AUTHOR_EMAIL = "seisman.info@gmail.com" LICENSE = "MIT License" URL = "https://github.com/seisman/HinetPy" DESCRIPTION = ( "A Python package to request and process seismic waveform data from...
, "Topic :: Internet :: WWW/HTTP", "Topic :: Scientific/Engineering :: Physics", "Topic :: Utilities", ] INSTALL_REQUIRES = ["requests"] # Configuration for setuptools-scm SETUP_REQUIRES = ["setuptools_s
cm"] USE_SCM_VERSION = {"local_scheme": "node-and-date", "fallback_version": "unknown"} if __name__ == "__main__": setup( name=NAME, description=DESCRIPTION, long_description=LONG_DESCRIPTION, use_scm_version=USE_SCM_VERSION, author=AUTHOR, author_email=AUTHOR_EMAIL,...
Morenito88/full_stack_p5
full_stack_p3/db/setup.py
Python
mit
1,516
0.045515
import sys from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import create_engine Base = declarative_base() class User(Base): """docstring for User""" __tablename__ = 'users' id = Column(I...
user_id = Column(Integer, ForeignKey('users.id')) user = relationship(User) @property def serialize(self): return { 'id': self.id, 'title': self.title, 'description': self.description, 'p
icture': self.picture, 'category_id': self.category_id } engine = create_engine('postgresql://catalog:catalog@localhost/catalog') Base.metadata.create_all(engine)
emschorsch/scrapy
scrapy/http/response/text.py
Python
bsd-3-clause
3,212
0.002491
""" This module implements the TextResponse class which adds encoding handling and discovering (through HTTP
headers) to base Response class. See documentation in docs/topics/request-response.rst """ from w3lib.encoding import html_to_unicode, resolve_encoding, \ html_body_declared_encoding, http_content_type_encoding from scrapy.http.response i
mport Response from scrapy.utils.python import memoizemethod_noargs class TextResponse(Response): _DEFAULT_ENCODING = 'ascii' def __init__(self, *args, **kwargs): self._encoding = kwargs.pop('encoding', None) self._cached_benc = None self._cached_ubody = None super(TextRespon...
DayGitH/Python-Challenges
DailyProgrammer/DP20150401B.py
Python
mit
9,284
0.007324
""" [2015-04-01] Challenge #208 [Intermediate] ASCII Gradient Generator https://www.reddit.com/r/dailyprogrammer/comments/3104wu/20150401_challenge_208_intermediate_ascii/ # [](#IntermediateIcon) _(Intermediate)_: ASCII Gradient Generator A linear colour gradient is where an image transitions through a range of colou...
racters that make up the gradient 'colours', from start to finish (or from inside to outside, for a radial gradient), like this: (note the space at the start) .,:;xX&@ Any points outside the gradient will have the first/last character, depending on which side of the gradient they're on. After this, you will accept...
this: `radial x y r` Where **(`x`, `y`)** is the center of the gradient, and **`r`** is the radius of the gradient, both in pixels. * For a **linear** gradient, the next line will look like this: `linear x1 y1 x2 y2` Where **(`x1`, `y1`)** is the start point of the gradient, and **(`x2`, `y2`)** is the...
pferreir/indico-backup
indico/MaKaC/webinterface/rh/helpDisplay.py
Python
gpl-3.0
978
0.018405
# -*- coding: utf-8 -*- ## ## ## This file is part of Indico. ## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN). ## ## Indico is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; eith...
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 Indico;if not, see <http://www.gnu.org/licenses/>. import MaKaC.webinterface.rh.base as ba...
s help class RHHelp( base.RH ): def _process( self ): p = help.WPHelp(self) return p.display()
CodingVault/LeetCodeInPython
trap_rain_water.py
Python
apache-2.0
1,076
0.006506
#!/usr/bin/env python # encoding: utf-8 """ trap_rain_water.py Created by Shengwei on 2014-07-22. """ # https://oj.leetcode.com/problems/trapping-rain-water/ # tags: medium / hard, array, water, greedy, logic, tricky, edge cases """ Given n non-negative integers representing an elevation map where the width of each ...
hile left <= right: height = max(height, min(A[left], A[right])) total += height if A[left] < A[right]: left += 1 else: right -= 1
return total - sum(A)
wevial/bpython
bpython/curtsiesfrontend/manual_readline.py
Python
mit
10,524
0
"""implementations of simple readline edit operations just the ones that fit the model of transforming the current line and the cursor location based on http://www.bigsmoke.us/readline/shortcuts""" from bpython.lazyre import LazyReCompile import inspect from six import iteritems INDENT = 4 # TODO Allow user config...
line):
return (cursor_offset, line[:cursor_offset] + line[cursor_offset+1:]) @edit_keys.on('<BACKSPACE>') @edit_keys.on(config='backspace_key') def backspace(cursor_offset, line): if cursor_offset == 0: return cursor_offset, line if not line[:cursor_offset].strip(): # if just whitespace lef...
madhurrajn/samashthi
mysite/settings.py
Python
bsd-3-clause
4,756
0.001892
# Copyright 2015 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
implied. # See the L
icense for the specific language governing permissions and # limitations under the License. """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 1.8.5. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings...
eduNEXT/edunext-platform
scripts/xdist/get_worker_test_list.py
Python
agpl-3.0
1,941
0.002061
""" This script strips the console log of a pytest-xdist Jenkins run into the test lists of each pytest worker. Assumes the following format: [test-suite] [worker] RESULT test """ import io import os import re import shutil import click @click.command() @click.option( '--log-file', help="File name of conso...
log_file, 'r') as console_file: for line in conso
le_file: regex_search = re.search(fr'\[gw(\d+)] (PASSED|FAILED|SKIPPED|ERROR) (\S+)', line) if regex_search: worker_num_string = regex_search.group(1) if worker_num_string not in worker_test_dict: worker_test_dict[worker_num_string] = [] ...
sunlightlabs/horseradish
photolib/migrations/0001_initial.py
Python
bsd-3-clause
1,986
0.006042
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import datetime import photolib.models import taggit.managers class Migration(migrations.Migration): dependencies = [ ('taggit', '0001_initial'), ] operations = [ migrations.CreateMo...
d(upload_to=photolib.models.upload_path)), ('uploaded', models.DateTimeField(default=datetime.datetime.utcnow)), ('last_updated', models.DateTimeField(default=datetime.datetime.utcnow, blank=True)),
('photo_tags', taggit.managers.TaggableManager(verbose_name='Tags', to='taggit.Tag', help_text='A comma-separated list of tags.', through='taggit.TaggedItem', blank=True)), ], options={ 'ordering': ('-uploaded',), }, bases=(models.Model,), ...
TobyRoseman/PS4M
engine/analyzers/bayesScorer.py
Python
mit
3,041
0.003946
# Bayes' Theorem # P(A|B) = P(B|A) P(A) / P(B) # A = "like" # B = has key value B # P(A) = |liked| / |url| # P(B) = |key| / |url| # P(B|A) = |liked from B| / |liked| # P(A|B) = ((|liked from B| / |liked|) (|liked| / |url|)) / (|key| / |url|) # = (|liked from B| / |url|) / (|key| / |url|) = |liked from B| / |key|...
otes: for k in keyMaker(v.item): if k in self.userCounters[v.type]: self.userCounters[v.type][k] += 1 else: self.userCounters[v.type][k] = 1 # XXX: shouldn't take universe count def getScore(self, item, u
niverseKeyCount): keys = self.keyMaker(item) if(len(keys) < 1): return ScoredValue(0.0, '') debug_text = [] score_sum = self.init_score for k in keys: cur_score = self.getKeyScore(k) if cur_score != 0: debug_text.appe...
Open-E-WEB/django-powerpages
powerpages/sitemap_config.py
Python
mit
3,800
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.core.urlresolvers import reverse from powerpages.settings import app_settings class NamedURL(object): """Wrapper over named URLs to provide lazy reversion""" def __init__(self, name, *args, **kwargs): self.name = name ...
else: self.protocol = 'http' if self.domain is None: if app_settings.SITEMAP_DOMAIN
: self.domain = app_settings.SITEMAP_DOMAIN elif request: self.domain = request.get_host() else: self.domain = 'localhost' if self.changefreq is None: self.changefreq = app_settings.SITEMAP_DEFAULT_CHANGEFREQ if self.pri...
anirudhvenkats/clowdflows
workflows/subgroup_discovery/SubgroupDiscovery/CN2_SD.py
Python
gpl-3.0
4,116
0.01069
import orange import sys from SDRule import * true = 1 false = 0 class CN2_SD: def __init__(self,k): self.k = k self.counter = orange.newmetaid() self.weightID = orange.newmetaid() self.rbf = orange.RuleBeamFinder() self.rbf.evaluator = RuleEvaluator_WRAcc() ...
__________SN2-SD results_____
_________________" rules.printRules()
decvalts/landlab
landlab/components/potentiality_flowrouting/examples/drive_pot_fr_coupled2.py
Python
mit
3,187
0.005962
# -*- coding: utf-8 -*- """drive_pot_fr Drive the landlab potentiality flow routing component. Created on Wed Mar 4 2015 @author: danhobley """ from __future__ import print_function from landlab import RasterModelGrid, ModelParameterDictionary from landlab.plot.imshow import imshow_node_grid import numpy as np from...
() kd = mg.at_node['water__volume_flux_magnitude'] # 0.01 m2 per year # dt = np.nanmin(0.2*mg.dx*mg.dx/kd) # CFL condition dt = 0.5 g =
mg.calculate_gradients_at_active_links(mg.at_node['topographic__elevation']) map_link_end_node_max_value_to_link(mg, 'water__volume_flux_magnitude') kd_link = 1.e6*mg.at_link['water__volume_flux_magnitude'][mg.active_links] qs = -kd_link*g dqsdx = mg.calculate_flux_divergence_at_nodes(qs) dzdt = -dq...
epeios-q37/epeios
tools/xdhq/examples/PYH/ReversiIMG/main.py
Python
agpl-3.0
7,631
0.009042
""" MIT License Copyright (c) 2017 Hajime Nakagami<nakagami@gmail.com> Copyright (c) 2019 Claude SIMON (https://q37.info/s/rmnmqd49) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software withou...
0, -20, 120], ] class Reversi: def reset(self)
: self.board = [] for _ in range(8): self.board.append([EMPTY] * 8) self.board[3][3] = self.board[4][4] = BLACK self.board[4][3] = self.board[3][4] = WHITE def __init__(self, orig=None): self.reset() # copy constructor if orig: assert isinstance(orig, Reversi) ...
sajuptpm/neutron-ipam
neutron/tests/unit/test_extension_security_group.py
Python
apache-2.0
72,038
0.000042
# Copyright (c) 2012 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 ...
1db38eb087', direction='ingress', protocol=const.PROTO_NAME_TCP, port_range_min='22', port_range_max='22',
remote_ip_prefix=None, remote_group_id=None, fmt=None, no_delete=False, ethertype=const.IPv4): if not fmt: fmt = self.fmt rule = self._build_security_group_rule(security_group_id, direction, ...
krintoxi/NoobSec-Toolkit
NoobSecToolkit /tools/inject/lib/utils/api.py
Python
gpl-2.0
26,576
0.002483
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Copyright (c) 2006-2015 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import logging import os import re import shlex import sqlite3 import sys import tempfile import time import urllib2 from lib.core.common import dataT...
.bottle import hook from thirdparty.bottle.bottle import post from thirdparty.bottle.bottle import request from thirdparty.bottle.bottle import response from thirdparty.bottle.bottle import run RESTAPI_SERVER_HOST = "127.0.0.1" RESTAPI_SERVER_PORT = 8775 # global settings class DataStore(object): admin_id = "" ...
database is None else database self.connection = None self.cursor = None def connect(self, who="server"): self.connection = sqlite3.connect(self.database, timeout=3, isolation_level=None) self.cursor = self.connection.cursor() logger.debug("REST-JSON API %s connected to IPC...
pkom/gestionies
config/wsgi.py
Python
bsd-3-clause
1,468
0.002045
# coding=utf-8 """ WSGI config for Gestión IES project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``...
by any WSGI server configured to use this # fil
e. This includes Django's development server, if the WSGI_APPLICATION # setting points here. application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
peepall/FancyLogger
FancyLogger/__init__.py
Python
mit
27,844
0.005639
#!/bin/env/python # coding: utf-8 import logging import os import time import uuid from logging import Formatter from logging.handlers import RotatingFileHandler from multiprocessing import Queue from time import strftime import dill from .commands import * from .processing import MultiprocessingLogger class TaskP...
rogress = progress if _progress > self.total: _progress = self.total elif _progress < 0: _progress = 0 # Stop task chrono if needed if _progress == self.total and self.display_time: self.end_time = time.time() * 1000 # If the task has com...
o if not self.begin_time: self.begin_time = self.end_time has_changed = self.progress != _progress if has_changed: self.progress = _progress return has_changed class FancyLogger(object): """ Defines a multiprocess logger object. Logger uses a ...
DuCalixte/last_week_rotten_trailer
app/database_cleanup.py
Python
mit
311
0
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker import os import sys
import json import re import uuid impor
t base64 import models from models.movie_trailer_model import Base, MovieTrailerModel rows = models.delete_movie_trailers() print("%d rows were deleted from table", rows)
sindrig/spoppy
spoppy/logging_utils.py
Python
mit
1,088
0
import logging from logging.handlers import RotatingFileHandler import os from appdirs import user_cache_dir def configure_logging(): cache_dir = user_cache_dir(appname='spoppy') LOG_FILE_NAME = os.path.join( cache_dir, 'spoppy.log' ) LOG_LEVEL = getattr( logging, os.getenv(...
Handler(handler) logger.debug('Spoppy logger set up') requests_log = logging.getLog
ger('urllib3') requests_log.setLevel(LOG_LEVEL) requests_log.propagate = True requests_log.addHandler(handler) logger.debug('urllib3 logger set up')
dburr/SchoolIdolAPI
api/migrations/0129_auto_20160511_1442.py
Python
apache-2.0
956
0.001046
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('api', '0128_auto_20160419_1708'), ] operations = [ migrations.AlterField( model_name='usicalvote', n...
b7 Papillon'), (38, '\u273f\u0187\u043d\u03c3c\u03c3\u2113\u03b1\u0442 \u0191\u03c3\u03b7\u2202\u03b1\u03b7\u0442\u273f'), (40, 'NYAvigators'), (54, '\u30dfk\u03bc'), (56, 'lilaq
\u273f'), (57, 'Sock It 2 Me'), (59, '\u8336\u8336\u8336'), (61, 'AKB0033'), (62, 'Undefined Red'), (67, 'Midnight\u273fBlossoms')]), preserve_default=True, ), ]
dragondjf/PFramer
qframer/futil.py
Python
gpl-3.0
664
0
#!/usr/bin/python # -*- coding: utf-8 -*- import os import functools from PySide2.QtCore import * from PySide2.QtGui import * from PySide2.QtWidgets import * views = {} def collectView(func): @functools.wraps(func) def wrapper(*args, **kwargs): self = args[0] if hasattr(self, 'viewID'): ...
fd = open(qssfile, "r") style = fd.read() fd.close() QApplicatio
n.instance().setStyleSheet(style) else: QApplication.instance().setStyleSheet("")
ketancmaheshwari/hello-goog
src/python/timeit.py
Python
apache-2.0
276
0.003623
#!/bin/env python # mainly for sys.argv[], sys.argv[0] is the name of the program import sys import time # mainly for arrays i
mport numpy as np # Time the following methods def a(): print 'hello' de
f b(): print 'hi' if __name__ == '__main__': print 'hello'
gwpy/gwsumm
gwsumm/plot/core.py
Python
gpl-3.0
25,918
0
# -*- coding: utf-8 -*- # Copyright (C) Duncan Macleod (2013) # # This file is part of GWSumm. # # GWSumm 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) ...
return False return True def __repr__(self): return '<%s(%s)>' % (self.__class__.__name__, self.href) def __str__(self): return str(self.href) register_plot(Su
mmaryPlot) class DataPlot(SummaryPlot): """A `SummaryPlot` from instrumental data. Parameters ---------- channels : `list` a list of channel names that define the data sources for this `DataPlot` start : `float` GPS start time of this `DataPlot`. end : `float` ...
datascopeanalytics/scrubadub
scrubadub/detectors/__init__.py
Python
mit
796
0
from .catalogue import remove_detector, register_detect
or, detector_catalogue from .base import Detector, RegexDetector, RegionLocalisedRegexDetector from .credential import CredentialDetector from .credit_card import CreditCardDetector from .date_of_birth import DateOfBirthDetector from .drivers_licence import DriversLicenceDetector from .
email import EmailDetector from .phone import PhoneDetector from .postalcode import PostalCodeDetector from .skype import SkypeDetector from .tagged import TaggedEvaluationFilthDetector from .text_blob import TextBlobNameDetector from .twitter import TwitterDetector from .url import UrlDetector from .user_supplied impo...
hunter-cameron/Bioinformatics
python/interproscanner.py
Python
mit
7,965
0.007031
#!/usr/bin/env python3 class OutputParser(object): def __init__(self, fmt, file_to_parse): self.fmt = fmt.upper() self.file_to_parse = file_to_parse def parse(self): """ Wrapper function in case I want to be able to parse other formats at some time """ if self.fmt == "GFF3": ...
1 return list(terms.keys()) class InterproScanner(object): def __init__(self, # interproscan vars fasta_in, out_path="interproscan_results.txt", fmt="GFF3", bin="/proj/dangl_lab/apps/my_interproscan/interproscan-5.3-4
6.0/interproscan.sh", othr_args="", # bsub vars threads=8, queue="week", stdout="interproscanner_bsub.out", stderr="interproscanner_bsub.err", # batch vars seqs_per_file=25 ): self.ips_vars = { ...
NicWayand/xray
doc/examples/cartopy_example.py
Python
apache-2.0
351
0
import xarray as
xr i
mport matplotlib.pyplot as plt import cartopy.crs as ccrs air = (xr.tutorial .load_dataset('air_temperature') .air .isel(time=0)) ax = plt.axes(projection=ccrs.Orthographic(-80, 35)) ax.set_global() air.plot.contourf(ax=ax, transform=ccrs.PlateCarree()) ax.coastlines() plt.savefig('cartopy_exam...
hrpt-se/hrpt
apps/reminder/migrations/0003_userreminderinfo_user_as_onetoone_field.py
Python
agpl-3.0
614
0.001629
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-10-10 15:34 from __future__ import unicode_literals from django.conf import settings from
django.db import
migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('reminder', '0002_newlettertemplate_newsletter_plain_managers'), ] operations = [ migrations.AlterField( model_name='userreminderinfo', name='user', ...
Senseg/robotframework
src/robot/model/itemlist.py
Python
apache-2.0
2,357
0.000424
# Copyright 2008-2012 Nokia Siemens Networks Oyj # # 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...
_name__) return self._items[index] def __len__(self): return len(self._items) def __unicode__(self): r
eturn u'[%s]' % ', '.join(unicode(item) for item in self) def __str__(self): return unicode(self).encode('ASCII', 'replace')
mmerickel/flatland
flatland/schema/compound.py
Python
mit
10,797
0.000185
from functools import update_wrapper import operator from flatland.exc import AdaptationError from flatland.util import Unspecified, threading from .containers import Array, Mapping from .scalars import Date, Integer, Scalar, String class _MetaCompound(type): """Adds a class-level initialization hook """ _l...
und types.") def u(self): uni, value = self.compose() r
eturn uni def set_u(self, value): self.explode(value) u = property(u, set_u) del set_u def value(self): uni, value = self.compose() return value def set_value(self, value): self.explode(value) value = property(value, set_value) del set_value def set(...
daviddrysdale/python-phonenumbers
python/phonenumbers/data/region_BM.py
Python
apache-2.0
1,530
0.005229
"""Auto-generated file, do not edit by hand. BM metadata""" from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_BM = PhoneMetadata(id='BM', country_code=1, international_prefix='011', general_desc=PhoneNumberDesc(national_number_pattern='(?:441|[58]\\d\\d|900)\\d{7}', possible_l...
example_number='5002345678', possible_length=(10,)), national_prefix='1', national_prefix_for_parsing='1|([2-8]\\d{6})$', national_prefix_trans
form_rule='441\\1', leading_digits='441', mobile_number_portable_region=True)
factly/election-results-2017
manipur/manipur/spiders/results_spider.py
Python
mit
2,491
0.014051
import scrapy from scrapy import Request class CWACResultsSpider(scrapy.Spider): name = "cw-all-candidates" def start_requests(self): for i in range(60): if self.endpoint == 'archive': yield Request('https://web.archive.org/web/20160823114553/http://eciresults.ni...
lf.parse) def parse(self, response): results = response.css('#div1 > table > tr') for result in results[3:len(results)-1]: yield { 'state': results[0].css('td::text').extract_first().split(' - ')[0], 'constituency': results[0].css('td::text').extract_first().spli...
ract(), 'status': results[1].css('td::text').extract_first(), } class CWTrendsSpider(scrapy.Spider): name = "cw-trends" def start_requests(self): if self.endpoint == 'archive': yield Request('https://web.archive.org/web/20160823114553/http://eciresults.nic.in/StatewiseS03.htm'...
plotly/python-api
packages/python/plotly/plotly/validators/layout/scene/_annotations.py
Python
mit
9,045
0.000221
import _plotly_utils.basevalidators class AnnotationsValidator(_plotly_utils.basevalidators.CompoundArrayValidator): def __init__(self, plotly_name="annotations", parent_name="layout.scene", **kwargs): super(AnnotationsValidator, self).__init__( plotly_name=plotly_name, parent_name...
nnot ation.Hoverlabel` instance or dict with compatible properties hovertext Sets text to appear when hovering over this annotation. If omitted or blank, no hover label will appear. name When used in ...
items the figure already has in this array. You can modify these items in the output figure by making your own item with `templateitemname` matching this `name` alongside your modifications (including `visible: false` or `enabled: false...
evilhero/mylar
lib/get_image_size.py
Python
gpl-3.0
12,859
0.000156
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function """ get_image_size.py ==================== :Name: get_image_size :Purpose: extract image dimensions given a file path :Author: Paulo Scardine (based on code from Emmanuel VAÏSSE) :Created: 26/09/2...
# older PNGs imgtype = PNG w, h = struct.unpack(">LL", data[8:16]) width = int(w) height = int(h) elif (size >= 2) and data.startswith(b'\377\330'): # JPEG imgtype = JPEG
input.seek(0) input.read(2) b = input.read(1) try: while (b and ord(b) != 0xDA): while (ord(b) != 0xFF): b = input.read(1) while (ord(b) == 0xFF): b = input.read(1) ...
fujicoin/fujicoin
test/functional/wallet_listsinceblock.py
Python
mit
14,650
0.002526
#!/usr/bin/env python3 # Copyright (c) 2017-2020 The Fujicoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the listsinceblock RPC.""" from test_framework.address import key_to_p2wpkh from test_framework....
"42759cde25462784395a337460bde7
5f58e73d3f08bd31fdc3507cbac856a2c4") assert_raises_rpc_error(-5, "Block not found", self.nodes[0].listsinceblock, "0000000000000000000000000000000000000000000000000000000000000000") assert_raises_rpc_error(-8, "blockhash must be of length 64 (not 11, for 'invalid-hex')", ...
meduz/NeuroTools
src/analysis.py
Python
gpl-2.0
17,761
0.001914
""" NeuroTools.analysis ================== A collection of analysis functions that may be used by NeuroTools.signals or other packages. .. currentmodule:: NeuroTools.analysis Classes ------- .. autosummary:: TuningCurve Functions --------- .. autosummary:: :nosignatures: ccf crosscorrelate make_ker...
isi = np.diff(sua2) sua2_ = np.array([]) for ni in xrange(1,n_pred+1): idx = np.random.permutation(isi.size-1) sua2_ = np.append(sua2_, np.add(np.insert( (np.cumsum(isi[idx])), 0, 0), sua2.min() + ( np.random.exponential(isi.mean())))) #calcul...
nge(0, sua1.size): differences = np.append(differences, sua1[k] - sua2[np.nonzero( (sua2 > sua1[k] - lag) & (sua2 < sua1[k] + lag))]) if predictor == 'shuffle': for k in xrange(0, sua1.size): pred = np.append(pred, sua1[k] - sua2_[np.nonzero( (sua2_ > sua1[k] ...
tqchen/tvm
tests/python/frontend/coreml/test_forward.py
Python
apache-2.0
27,748
0.001874
# 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...
alpha=alpha, input_names=["input1", "input2"], output_name="output", mode="ADD" ) model = cm.models.MLModel(builder.spec) for target, ctx in tvm.testing.enabled_targets(): out = run_tvm_graph( model, target, ctx, [a_np1, a_np2], ["input1", "input2"], b_np.shape, dtype )
tvm.testing.assert_allclose(out, b_np, rtol=1e-5) @tvm.testing.uses_gpu def test_forward_AddLayerParams(): verify_AddLayerParams((1, 2, 2), 0) verify_AddLayerParams((1, 2, 2), 1) verify_AddLayerParams((1, 3, 3), 2) def verify_MultiplyLayerParams(input_dim, alpha): dtype = "float32" a_np1 = np....
Brother-Simon/django-dynamic-scraper
tests/scraper/scraper_req_options_run_test.py
Python
bsd-3-clause
3,155
0.005388
import os, unittest from scraper.models import Event from scraper.scraper_test import EventSpider, ScraperTest class ScraperReqOptionsRunTest(ScraperTest): def setUpWithRequestTypeMethodScraper(self, test_case): self.event_website.url = os.path.join('http://localhost:8010/scraper/request_type_method/', '...
pt_mp.save() self.run_event_spider(1) self.assertEqual(len(Event.objects.all()), 4) def test_with_form_data_pagination(self): self.setUpWithFormDataScraper('page') self.setUpWithFormDataPagination() self.run_event_spide
r(1) self.assertEqual(len(Event.objects.all()), 7) @unittest.skip("Skipped, cookies are not sent in test case environment, no solution yet!") def test_with_cookies_simple(self): self.setUpWithCookiesScraper('simple') self.run_event_spider(1) self.assertEqual(len(Event.objects.a...
kivarun/libvirt_metadata_api
test/test_arp.py
Python
gpl-3.0
2,723
0.005509
import unittest import utils import mock class ArpTestCase(unittest.TestCase): def setUp(self): self.linux_data = ('IP address HW type Flags HW address Mask Device\n' '192.168.0.94 0x1 0x2 aa:aa:aa:aa:aa:aa * br0\n' ...
{'192.168.0.230': 'cc:cc:cc:c
c:cc:cc', '192.168.0.250': 'bb:bb:bb:bb:bb:bb', '192.168.0.1': 'aa:aa:aa:aa:aa:aa'} ) def test_get_mac_address_linux(self): with mock.patch('__builtin__.open', mock.mock_open(read_data=self.linux_data)): for linux_platform in ('linux', 'linux2'): ...
edgedb/edgedb
edb/pgsql/compiler/config.py
Python
apache-2.0
17,269
0
# # This source file is part of the EdgeDB open source project. # # Copyright 2008-present MagicStack Inc. and the EdgeDB 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...
pgast.StringConstant): val = pgast.TypeCast( arg=val, type_name=pgast.TypeName(name=('text',)), ) fcall = pgast.FuncCall( name=('pg_catalog', 'set_config'), args=[ pgast.StringConstant(val=op.backend_setting), ...
val, pgast.BooleanConstant(val='false'), ], ) result = output.wrap_script_stmt( pgast.SelectStmt(target_list=[pgast.ResTarget(val=fcall)]), suppress_all_output=True, env=ctx.env, ) elif op.scope is qltypes.ConfigScope.INSTANCE...
ABlogiX/django-bigbluebutton
admin.py
Python
gpl-2.0
4,847
0.003714
from django.contrib import admin from django.conf import settings from django.core.mail import send_mail from django.utils.translation import ugettext as _ from django.contrib.sites.models import Site from django.shortcuts import render from django.http import HttpResponseRedirect from django_bigbluebutton.models im...
'_selected_action': request.POST.getlist(admin.ACTION_CHECKBOX_NAME)}) return render(reque
st, 'admin/send_mail.html', {'meetings': queryset, 'mail_form': form, 'action': 'send_inscription_mail'}) send_inscription_mail.short_description = _( 'Send a mail to selected meeting pre-registered users.' ) admin.site.register(Meeting, MeetingAd...
kevinarpe/kevinarpe-rambutan3
tests/check_args/annotation/test_NON_EMPTY_BUILTIN_FROZENSET_OF.py
Python
gpl-3.0
282
0.007092
from rambutan3.check_args.annotation.NON_EMPTY_BUILTIN_FROZENSET_OF import NON_EMPTY_BUILTIN_FROZENSET_OF from tests.check_args.annotation import RSetMatcherTestUtil def test(): RSetMatcherTestUtil.core_test_non_empty_s
et_of_
matcher(NON_EMPTY_BUILTIN_FROZENSET_OF, frozenset)
tjlane/thor
src/python/__init__.py
Python
gpl-2.0
581
0.003442
# THOR
base dir import logging import glob import os import sys # dump a few things into the THOR namespace from .xray import * # list all the files included in THOR __all__ = [os.path.basename(f)[:-3] for f in glob.glob(os.path.dirname(__file__) + "/*.py") if not f.endswith('__init__.py')] # set up the logger logger = l...
tdout) formatter = logging.Formatter(fmt='%(asctime)s - %(message)s', datefmt="%H:%M:%S") sh.setFormatter(formatter) logger.addHandler(sh) logger.propagate = False
oposs/pkg.oetiker.ch-build
build/samba4/patches/patch-buildtools_wafsamba_samba__conftests.py
Python
gpl-3.0
890
0.031461
$NetBSD: patch-buildtools_wafsamba_samba__conftests.py,v 1.2 2019/11/10 17:01:58 adam Exp $ Ensure defines are strings to avoid assertion failure, some returned values are unicode. --- buildtools/wafsamba/samba_conftests.py.orig 2019-07-09 10:08:41.000000000 +0000 +++ buildtools/wafsamba/samba_conftests.py @@ -97,
9 +97,9 @@ def CHECK_LARGEFILE(conf, define='HAVE_L if flag[:2] == "-D": flag_split = flag[2:].split('=') if len(flag_split) == 1: - conf.DEFINE(flag_split[0], '1') + conf.DEFINE(str(flag_split[0]), '1') ...
conf.DEFINE(str(flag_split[0]), str(flag_split[1])) if conf.CHECK_CODE('if (sizeof(off_t) < 8) return 1', define,
openstack/congress
congress/tests/api/test_api_utils.py
Python
apache-2.0
2,124
0
# Copyright (c) 2015 NTT, 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 agree...
id', 'datasource id') result = api_utils.get_id_from_context(context) self.assertEqual(expected, result) def test_get_id_from_context_policy_id(self): context = {'policy_id': 'policy id'} expected = ('__engine', 'policy id') result = api_utils.get_id_from_context(context) ...
context = {'invalid_id': 'invalid id'} self.assertRaises(webservice.DataModelException, api_utils.get_id_from_context, context)
spectralDNS/spectralDNS
tests/test_MHD.py
Python
lgpl-3.0
1,847
0.001083
import pytest import importlib from mpi4py import MPI from spectralDNS import config, get_solver, solve from TGMHD import initialize, regression_test, pi comm = MPI.COMM_WORLD if comm.Get_size() >= 4: params = ('uniform_slab', 'nonuniform_slab', 'uniform_pencil', 'nonuniform_pencil') else: param...
= 'slab' if len(pars) == 2: mpi = pars[1] _args = ['--decomposition', mpi] if mesh == 'uniform': _args += ['--M', '4', '4', '4', '--L', '2*pi', '2*pi', '2*pi'] else: _args += ['--M', '6', '5', '4', '--L', '6*pi', '4*pi', '2*pi'] _args += ['MHD'] retu
rn _args def test_MHD(sol): config.update( { 'nu': 0.000625, # Viscosity 'dt': 0.01, # Time step 'T': 0.1, # End time 'eta': 0.01, 'L': [2*pi, 4*pi, 6*pi], 'M': [4, 5, 6], 'conv...
Pawamoy/django-meerkat
src/meerkat/exceptions.py
Python
isc
71
0
# -*
- coding: utf-8 -*- class RateExceededError(E
xception): pass
stascrash/codeeval
roman_numerals.py
Python
gpl-3.0
1,983
0.026223
# https://www.codeeval.com/open_challenges/106/ import sys from collections import namedtuple test_cases = open(sys.argv[1], 'r') # test_cases = open('roman_numerals.txt', 'r') test_lines = (line.rstrip() for line in test_cases) def num_to_components(num): num_comp = namedtuple('NumComponents', ('thousands', 'hundre...
# for Tens if num_components.tens == 4: r_tens = 'XL' elif num_components.tens == 9: r_tens = 'XC' elif num_components.tens == 5: r_tens = 'L' elif num_components.tens <= 3: r_tens = 'X'*num_components.tens elif num_components.tens in range(6, 9): r_tens = 'L' + 'X' * (num_components.tens - 5) # for ...
elif num_components.singles == 5: r_singles = 'V' elif num_components.singles <= 3: r_singles = 'I'*num_components.singles elif num_components.singles in range(6, 9): r_singles = 'V' + 'I' * (num_components.singles - 5) roman_num = r_thousands + r_hundreds + r_tens + r_singles print(roman_num) if __name_...
wesleybowman/UTide
utide/robustfit.py
Python
mit
7,233
0
""" Robust MLR via iteratively reweighted least squares. """ import numpy as np from utide.utilities import Bunch # Weighting functions: def andrews(r): r = np.abs(r) r = max(np.sqrt(np.spacing(1)), r) w = (r < np.pi) * np.sin(r) / r return w def bisquare(r): r = np.abs(r) w = (r < 1) * (...
- rf.iter
ations: number of iterations completed """ if tune is None: tune = tune_defaults[weight_function] _wfunc = wfuncdict[weight_function] if X.ndim == 1: X = X.reshape((x.size, 1)) n, p = X.shape lev = leverage(X) out = Bunch( weight_function=weight_function, ...
0xPIT/Espruino
scripts/build_board_docs.py
Python
mpl-2.0
13,737
0.013758
#!/usr/bin/python # This file is part of Espruino, a JavaScript interpreter for Microcontrollers # # Copyright (C) 2013 Gordon Williams <gw@pur3.co.uk> # # 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 on...
d(ttid); e.style.display = "none"; } function drawLine(x
1, y1, x2, y2, hover) { if (x2 < x1) { var temp = x1; x1 = x2; x2 = temp; temp = y1; y1 = y2; y2 = temp; } var line = $('<div class="line" alt="'+hover+'"></div>').appendTo($("body")); var length = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 ...
tp81/openmicroscopy
components/tools/OmeroWeb/omeroweb/webclient/controller/__init__.py
Python
gpl-2.0
2,099
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # # # # Copyright (c) 2008-2011 University of Dundee. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or...
if total_size > (limit * 10): if page > 10: total.append(-1) for i in range((1, page-9)[page-9 >= 1], (t+1, page+10)[page+9 < t]): total.append(i)
if page < t-9: total.append(-1) elif total_size > limit and total_size <= (limit*10): for i in range(1, t+1): total.append(i) else: total.append(1) next = None if page_size == limit and (page*limit) < total_size: ...
tensorflow/tensorflow
tensorflow/python/framework/function_def_to_graph_test.py
Python
apache-2.0
10,231
0.004985
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
/ \ / \ # | d_1 e_1 a:1 a:0 # | \ | / | # | \ | / | #
| foo_2 | # | / \ | # Outputs: x d_2 e_2 a:0 x = array_ops.placeholder(dtypes.float32, name="x") y = array_ops.placeholder(dtypes.int32, name="y") z = array_ops.placeholder(dtypes.int32, name="z") d_1, e_1 = op_de...
sergeychipiga/selenium
setup.py
Python
apache-2.0
3,598
0.014452
#!/usr/bin/env python # Copyright 2008-2009 WebDriver committers # Copyright 2008-2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICEN...
', 'selenium.common', 'selenium.test', 'selenium.test.selenium', 'selenium.test.selenium.common', 'selenium.test.selenium.webdriver', 'selenium.test.s
elenium.webdriver.common', 'selenium.test.selenium.webdriver.ie', 'selenium.test.selenium.webdriver.support', 'selenium.webdriver', 'selenium.webdriver.android', 'selenium.webdriver.chrome', 'selenium.webdriver.common', 'seleniu...
mikedh/trimesh
tests/test_export.py
Python
mit
12,367
0.000647
try: from . import generic as g except BaseException: import generic as g class ExportTest(g.unittest.TestCase): def test_export(self): export_types = list( g.trimesh.exchange.export._mesh_exporters.keys()) meshes = list(g.get_meshes(8)) # make sure we've got somethin...
process=True, merge_norm=True, merge_tex=True) # if we exported as GLTF/dae it will come back as a Scene if isinstance(loaded, g.trimesh.Scene) and isins
tance( mesh, g.trimesh.Trimesh): assert len(loaded.geometry) == 1 loaded = next(iter(loaded.geometry.values())) if (not g.trimesh.util.is_shape(loaded._data['faces'], (-1, 3)) or not g.trimesh.util.is_shape(loaded._data...
LouisTrezzini/projet-mairie
api/franceocr/check_mrz_ocr.py
Python
bsd-3-clause
968
0.003099
import logging def same_ocr_mrz(mrz_data, zones): last_name_is_valid = mrz_data["last_name"][:25] == zones["last_name"]["value"][:25] logging.debug( "MRZ last name: {}; OCR last name: {}; matching {}".format( mrz_data["last_name"], zones["last_name"]["value"], last_name_is_valid )...
ocr = zones["first_name"]["value"].split() first_names_ocr_joined = "".join(first_names_ocr) first_names_mrz = mrz_data["first_name"].split() first_names_mrz_joined = "".join(first_names_mrz) length_checked = min([ len(first_names_mrz_joined), 12 ]) first_name_is_valid = first_na...
== first_names_ocr_joined[:length_checked] logging.debug( "MRZ first names: {}; OCR first names: {}; matching {}".format( first_names_mrz, first_names_ocr, first_name_is_valid ) ) return last_name_is_valid and first_name_is_valid
balajikris/autorest
src/generator/AutoRest.Python.Tests/Expected/AcceptanceTests/BodyDate/autorestdatetestservice/operations/date_model_operations.py
Python
mit
13,757
0.000582
# 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 cause incorrect behavior and will be lost if the code is # regenerated. # -------------...
masayoshi-nakamura/CognitiveArchitectureLecture
examples/brainsimulator_agent/pygazebo_agent.py
Python
apache-2.0
1,805
0.000554
import trollius from trollius import From import pygazebo.msg.joint_cmd_pb2 import numpy as np class SampleAgent(): def __init__(self, brica_agent, visual_comp, action_comp): self.brica_agent = brica_agent self.sensor_comp = visual_comp self.action_comp = action_comp def run(self): ...
sensor(self): return self.sensor_comp @trollius.coroutine def publish_loop(self): manager = yield From(pygazebo.connect()) def callback_pose(data): self.sensor_comp.callback(data) publisher = yield From( manager.advertise('/gazebo/default/turtle...
'gazebo.msgs.JointCmd')) subscriber_pose = manager.subscribe( '/gazebo/default/pose/info', 'gazebo.msgs.PosesStamped', callback_pose) yield From(subscriber_pose.wait_for_connection()) msg_left_wheel = pygazebo.msg.joint_cmd_pb2....
dbmi-pitt/DIKB-Micropublication
scripts/mp-scripts/Bio/PDB/StructureBuilder.py
Python
apache-2.0
9,884
0.00951
# Copyright (C) 2002, Thomas Hamelryck (thamelry@binf.ku.dk) # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. import sys __doc__=""" Consumer class that builds a Structure object. This is used by ...
# the Residue objects with the id (field, resseq, icode) in it. # These residues each should have non-blanc altlocs for all their atoms. # If not, the PDB file probably contains an error. if not self._is_completely_disordered(duplicate_residu...
esidue will be missing self.residue=None raise PDBConstructionException, "Blank altlocs in duplicate residue %s ('%s', %i, '%s')" % (resname, field, resseq, icode) self.chain.detach_child(res_id) new_residue=Residue(res_id, resname,...
jonnyao/Python-Scripts
bin/Blog_reader.py
Python
mit
615
0.006504
from bs4 import BeautifulSoup import requests import shutil page = requests.get("http://planet.dgplug.org/") soup = BeautifulSoup(page.content, 'html.parser') data = soup.find_all(class_=
"entrygroup") columns = shutil.get_terminal
_size().columns size = len(data)-1 for i in range(0, size): piu = data[i] heading = piu.find("a").get_text() for n in range(84): print ("-", end=" ") print ('{}{}'.format(' ' * (int(columns / 2 - len(heading) / 2)), heading)) for n in range(84): print ("-", end=" ") main_content ...
ahmedaljazzar/edx-platform
openedx/core/djangoapps/video_pipeline/config/waffle.py
Python
agpl-3.0
681
0.002937
""" This module contains configuration settings via waffle flags for the Video Pipeline app. """ from openedx.core.dj
angoapps.waffle_utils import WaffleFlagNamespace, CourseWaffleFlag # Videos Namespace WAFFLE_NAMESPACE = 'videos' # Waffle flag telling whether youtube is deprecated. DEPRECATE_YOUTUBE = 'depre
cate_youtube' def waffle_flags(): """ Returns the namespaced, cached, audited Waffle flags dictionary for Videos. """ namespace = WaffleFlagNamespace(name=WAFFLE_NAMESPACE, log_prefix=u'Videos: ') return { DEPRECATE_YOUTUBE: CourseWaffleFlag( waffle_namespace=namespace, ...
ivanlyon/exercises
kattis/k_different.py
Python
mit
1,053
0.002849
''' Absolute value of difference between 2 integers. Status: Accepted ''' ############################################################################### def difference(a, b): '''Absolute difference between 2 integers''' return abs(a - b) #####################################################################...
sys.stdin: a, b = [int(i
) for i in testcase.split()] print('The difference between {} and {} is: '.format(str(a), str(b)), end='', flush=True, file=sys.stderr) print(str(difference(a, b))) ###############################################################################
ge0rgi/cinder
cinder/tests/unit/compute/test_nova.py
Python
apache-2.0
8,409
0
# Copyright 2013 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import mock from cinder.compute import nova from cinder import context from cinder import test from novaclient import exceptions as nova_exceptions class Nov
aClientTestCase(test.TestCase): def setUp(self): super(NovaClientTestCase, self).setUp() self.ctx = context.RequestContext('regularuser', 'e3f0833dc08b4cea', auth_token='token', is_admin=False) self.ctx.service_catalog = \ [{'type': 'com...
jdavidrcamacho/Tests_GP
02 - Programs being tested/02 - optimization test files/optimization tests 3/Atempt_tests.py
Python
mit
8,673
0.021792
# -*- coding: utf-8 -*- """ Created on Wed Sep 28 15:26:46 2016 @author: camacho """ import Kernel;reload(Kernel);kl = Kernel import Kernel_likelihood;reload(Kernel_likelihood); lk= Kernel_likelihood import Kernel_opt as opt import numpy as np import matplotlib.pyplot as pl import george import george.kernels as ge ...
hood(kernel1, x1, x1, y1, yerr1) # ## Calculation using george #kernelg1 = 19.0**2*ge.ExpSquaredKernel(2.0**2) #gp = george.GP(kernelg1) #gp.compute(x1,yerr1) #print 'likelihood_george ->', gp.lnlikelihood(y1) #print 'gradient_george ->', gp.grad_lnlikelihood(y1) #print ' ' ############################################...
################### # ## EXEMPLO 2 - ExpSineSquared ## Calculation using our stuff #print '########## EXPSINESQUARED' #kernel2=kl.ExpSineSquared(15.0, 2.0, 10.0) #lk.likelihood(kernel2, x1, x1, y1, yerr1) #lk.gradient_likelihood(kernel2, x1, x1, y1, yerr1) # ## Calculation using george #kernelg2 = 15.0**2*ge.ExpSine2Ke...
nuagenetworks/monolithe
tests/base/sdk/python/tdldk/v1_0/fetchers/garoots_fetcher.py
Python
bsd-3-clause
598
0.003344
# -*- coding: utf-8 -*- # # __code_header example # put your license header here # it will be
added to all the generated files # from bambou import NURESTFetcher class GARootsFetcher(NURESTFetcher): """ Represents a GARoots fetcher Notes: This fetcher enables to fetch GARoot objects. See: bambou.NURESTFetcher """ @classmethod def managed_class(cls): ...
return GARoot
DGA-MI-SSI/YaCo
deps/swig-3.0.7/Examples/test-suite/python/li_cwstring_runme.py
Python
gpl-3.0
632
0.006329
from li_cwstring import * if count(u"ab\0ab\0ab\0", 0) != 3: raise RuntimeError if test1() != u"Hello World": raise RuntimeError if test2() != u" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_": raise RuntimeError if test3("hello") != u"hello-
suffix": raise
RuntimeError if test4("hello") != u"hello-suffix": raise RuntimeError if test5(4) != u'xxxx': raise RuntimeError if test6(10) != u'xxxxx': raise RuntimeError if test7() != u"Hello world!": raise RuntimeError if test8() != u" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_": ra...
belokop/indico_bare
indico/modules/events/layout/controllers/layout.py
Python
gpl-3.0
7,996
0.002001
# This file is part of Indico. # Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (a...
d_file(metadata['file
name'], BytesIO(event.logo), mimetype=metadata['content_type'], conditional=True) class RHLayoutCSSDisplay(RHConferenceBaseDisplay): def _process(self): event = self._conf.as_event if not event.has_stylesheet: raise NotFound data = BytesIO(event.stylesheet.encode('utf-8')) ...
vdrhtc/Measurement-automation
lib2/DispersiveRamseyFringes.py
Python
gpl-3.0
1,912
0.003661
from matplotlib import pyplot as plt, colorbar from lib2.VNATimeResolvedDispersiveMeasurement2D import * class DispersiveRamseyFringes(VNATimeResolvedDispersiveMeasurement2D): def __init__(self, name, sample_name, **devs_aliases_map): devs_alias
es_map["q_z_awg"] = None super().__init__(name, sample_name, devs_aliases_map) self._measurement_result = \ DispersiveRamseyFringesResult(name, sample_name) self._sequence_generator = IQPulseBuilder.build_dispersive_ramsey_sequences def set_fixed_parameters(self, pulse_sequence_...
nce_parameters, **dev_params) def set_swept_parameters(self, ramsey_delays, excitation_freqs): q_if_frequency = self._q_awg.get_calibration() \ .get_radiation_parameters()["if_frequency"] swept_pars = {"ramsey_delay": \ (self._output_pulse_sequence, ...