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 |
|---|---|---|---|---|---|---|---|---|
prospero78/pyPC | pak_pc/pak_gui/pak_win_idc/__init__.py | Python | lgpl-3.0 | 127 | 0 | # -*- coding: utf | 8 -*-
''' |
Инициализация пакета интерфейса дисковго кластера.
'''
|
robcarver17/pysystemtrade | sysdata/mongodb/mongo_process_control.py | Python | gpl-3.0 | 1,876 | 0.001599 | from sysobjects.production.process_control import controlProcess
from sysdata.production.process_control_data import controlProcessData
| from syscore.objects import arg_not_supplied, missing_data
from sysdata.mongodb.mongo_generic import mongoDataWithSingleKey
from syslogdiag.log_to_screen import logtoscreen
PROCESS_CONTROL_COLLECTION = "process_control"
PROCESS_CO | NTROL_KEY = "process_name"
class mongoControlProcessData(controlProcessData):
"""
Read and write data class to get process control data
"""
def __init__(
self, mongo_db=arg_not_supplied, log=logtoscreen("mongoControlProcessData")
):
super().__init__(log=log)
self._mong... |
Mafarricos/Mafarricos-xbmc-addons | plugin.video.videosinfantis/main.py | Python | gpl-2.0 | 4,836 | 0.0366 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# by Mafarricos
# email: [email protected]
# Thanks to enen92 and fightnight
# 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... | Dir('CanalPanda.pt',siteur | l3,12,addonfolder+artfolder+'iconpanda.png')
##################################################
#FUNCOES
def play(url,name):
if 'gatodasbotas' in url: url=ogatodasbotas.encontrar_tipo_da_fonte(url)
listitem = xbmcgui.ListItem()
listitem.setPath(url)
listitem.setInfo("Video", {"Title":name})
listitem.setPr... |
toboso-team/toledo | toledo/__init__.py | Python | mit | 97 | 0 | from . import graphics
from . | import input
from . import util
from .controll | er import Controller
|
dougthor42/CodeSort | codesort/find_fold_points.py | Python | mit | 2,335 | 0 | # -*- coding: utf-8 -*-
"""
@name: find_fold_points.py
@vers: 0.1
@author: Douglas Thor
@created: Sun Jun 29 17:03:12 2014
@modified: Sun Jun 29 17:03:12 2014
@descr: Returns the fold points - where code gets indented and
dedented - of a .py file.
"""... | e pop off
# th | e last indent from the stack
indent_level -= 1
matched_indent = indents.pop()
result.append((matched_indent,
srowcol[0] - 1 - nl_counter,
indent_level + 1))
if toknum not in token_whitelist:
nl_counter =... |
jmluy/xpython | exercises/practice/knapsack/knapsack.py | Python | mit | 51 | 0 | def maximum | _va | lue(maximum_weight, items):
pass
|
pipermerriam/web3.py | web3/utils/blocks.py | Python | mit | 1,270 | 0.001575 | from eth_utils import (
is_hex,
is_string,
is_integer,
remove_0x_prefix,
force_text,
)
def is_predefined_block_number(value):
if not is_string(value):
return False
return force_text(value) in {"latest", "pending", "earliest"}
def is_hex_encoded_block_hash(value):
if not is_st... | lock_hash(value):
return False
try:
value_as_int = int(value, 16)
except ValueError:
return False
return 0 <= value_as_int < 2**256
def select_method_for_block_identifier(value, if_hash, if_number, if_predefined):
if is_predefined_block_number(value):
return if_predefin... | d (0 <= value < 2**256):
return if_number
elif is_hex_encoded_block_number(value):
return if_number
else:
raise ValueError(
"Value did not match any of the recognized block identifiers: {0}".format(value)
)
|
wanghe4096/website | aliyun/api/rest/Ecs20140526DeleteSnapshotRequest.py | Python | bsd-2-clause | 334 | 0.026946 | '''
Created by auto_sdk on 2015.04.21
'''
from aliyun.api.base import RestApi
class Ecs20140526DeleteSnapshotRequest(RestApi):
def __init__(self,domain='ecs.aliyuncs.com',port=80):
RestApi.__init__(self,domain, port) |
self.SnapshotId = None
def getapiname(self):
return 'ecs.aliyuncs.com.DeleteSnapshot.2014-0 | 5-26'
|
tapomayukh/projects_in_python | sandbox_tapo/src/skin_related/BMED_8813_HAP/Scaling/results/cross_validate_objects_BMED_8813_HAP_scaled_method_I.py | Python | mit | 3,959 | 0.017934 |
# Principal Component Analysis Code :
from numpy import mean,cov,double,cumsum,dot,linalg,array,rank,size,flipud
from pylab import *
import numpy as np
import matplotlib.pyplot as pp
#from enthought.mayavi import mlab
import scipy.ndimage as ni
import roslib; roslib.load_manifest('sandbox_tapo_darpa_m3')
import ro... | ethod used'
val,vec = linalg.eig(Mcov)
#return the projection matrix, the variance and the mean
return vec,val,mean_X, M, Mcov
if __name__ == '__main__':
Fmat = Fmat_original
# Checking the Data-Matrix
m_tot, n_tot = np.shape(Fmat)
print 'Total_Matrix_Shape:',m_tot,n_tot
e... | = pca(Fmat)
#print eigvec_total
#print eigval_total
#print mean_data_total
m_eigval_total, n_eigval_total = np.shape(np.matrix(eigval_total))
m_eigvec_total, n_eigvec_total = np.shape(eigvec_total)
m_mean_data_total, n_mean_data_total = np.shape(np.matrix(mean_data_total))
print 'Eigen... |
titiwu/simpl | simpl/diagnose.py | Python | gpl-3.0 | 1,732 | 0 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 19 21:03:22 2017
Stolen from jasper
@author: mb
"""
import sys
import socket
import logging
if sys.version_info < (3, 3):
from distutils.spawn import find_executable
else:
from shutil import which as find_executable
def check_network_connection(server="www. | google.com"):
"""
Checks if jasper can connect a network server.
Arguments:
server -- (optional) the server to connect with (Default:
| "www.google.com")
Returns:
True or False
"""
logger = logging.getLogger(__name__)
logger.debug("Checking network connection to server '%s'...", server)
try:
# see if we can resolve the host name -- tells us if there is
# a DNS listening
host = socket.gethostbyname(... |
ktan2020/legacy-automation | win/Lib/site-packages/wx-3.0-msw/wx/tools/Editra/src/extern/pygments/styles/borland.py | Python | mit | 1,613 | 0 | # -*- coding: utf-8 -*-
"""
pygments.styles.borland
~~~~~~~~~~~~~~~~~~~~~~~
Style similar to the style used in the Borland IDEs.
:copyright: Copyright 2006-2010 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.style import Style
from pygment... | tyles = {
Whitespace: '#bbbbbb',
Comment: 'italic #008800',
Comment.Preproc: 'noitalic #008080',
Comment.Special: 'noitalic bold',
String: '#0000FF',
String.Char: '#800080',
Number: ... | ld #000080',
Name.Attribute: '#FF0000',
Generic.Heading: '#999999',
Generic.Subheading: '#aaaaaa',
Generic.Deleted: 'bg:#ffdddd #000000',
Generic.Inserted: 'bg:#ddffdd #000000',
Generic.Error: '#aa0000',
Generic.Em... |
SphinxKnight/kuma | kuma/core/views.py | Python | mpl-2.0 | 1,861 | 0.001612 | from __future__ import unicode_literals
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_exempt
from django.v... | ws.decorators.http import require_POST
from .i18n import get_kuma_languages
@n | ever_cache
def _error_page(request, status):
"""
Render error pages with jinja2.
Sometimes, an error is raised by a middleware, and the request is not
fully populated with a user or language code. Add in good defaults.
"""
if not hasattr(request, 'user'):
request.user = AnonymousUser()
... |
charany1/Bookie | dbversions/versions/11087341e403_add_private_bookmark_support_to_bmarks_.py | Python | agpl-3.0 | 906 | 0.003311 | """add private bookmark support to bmarks table
Revision ID: 11087341e403
Revises: 44dccb7b8b82
Create Date: 2014-05-23 07:18:38.743431
"""
# revision identifiers, used by Alembic.
revision = '11087341e403'
down_revision = '44dccb7b8b82'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_col... | context = op.get_context()
meta = current_context.opts['target_metadata']
bmarks = sa.Table('bmarks', meta, autoload=True)
sel = sa.select([bmarks])
stmt = bmarks.update().\
values(is_private=False)
connection.execute(stmt)
def downgrade():
try:
| op.drop_column('bmarks', 'is_private')
except sa.exc.OperationalError as exc:
pass
|
t3dev/odoo | addons/account/tests/test_account_fiscal_year.py | Python | gpl-3.0 | 4,107 | 0.001217 | # -*- coding: utf-8 -*-
from odoo.addons.account.tests.account_test_classes import AccountingTestCase
import odoo.tests
from odoo import fields
from datetime import datetime
@odoo.tests.tagged('post_install', '-at_install')
class TestFiscalPosition(AccountingTestCase):
def check_compute_fiscal_year(self, compa... | company,
'2017-11-01',
'2017-06-01',
'2017-12-31',
)
# Create custom fiscal year covering the 3 last months of 2017.
self.env['account.fiscal.year'].create({
'name': 'last 3 month 2017',
'date_from': '2017-10-01',
... |
})
# Check inside the custom fiscal years.
self.check_compute_fiscal_year(
company,
'2017-07-01',
'2017-06-01',
'2017-09-30',
)
|
vejmelkam/wrfxpy | src/ingest/level0_source.py | Python | mit | 36,889 | 0.006154 | #
# Dalton Burke, CU Denver
#
# CONUS = [-124.7844079,-66.9513812,24.7433195,49.3457868]
from __future__ import absolute_import
from utils import ensure_dir, symlink_unless_exists
from .downloader import download_url, DownloadError, get_dList
# fast searching of dList
from bisect import bisect
from datetime import d... | Attempts to retrieve geolocation files in the time range
First, check if they're available locally, if unavailable proceed to download
: | param from_utc: start time
:param to_utc: end time
:return: a list of paths to local geolocation files
"""
pass
def compute_geo_manifest(from_utc, to_utc):
"""
Get list of geolocation file names for the given time frame
:param from_utc: start time UTC
... |
mekanix/flask-bootstrap-sql-rest | freenit/schemas/base.py | Python | gpl-3.0 | 236 | 0 | from marshmallow | import EXCLUDE, Schema
from ..fields.objectid import ID
class BaseSchema(Schema):
id = ID(description='ID', dump_only=True)
class Meta:
strict = True
ordered = True
| unknown = EXCLUDE
|
pytest-dev/pytest-qt | src/pytestqt/qt_compat.py | Python | mit | 6,366 | 0.001414 | """
Provide a common way to import Qt classes used by pytest-qt in a unique manner,
abstracting API differences between PyQt5 and PySide2/6.
.. note:: This module is not part of pytest-qt public API, hence its interface
may change between releases and users should not rely on it.
Based on from https://github.com/epag... | rs = "\n".join(
f" {module}: {reason}"
for module, reason in sorted(self._import_errors.items())
)
msg = (
"pytest-qt requires either | PySide2, PySide6, PyQt5 or PyQt6 installed.\n"
+ errors
)
raise pytest.UsageError(msg)
_root_modules = {
"pyside6": "PySide6",
"pyside2": "PySide2",
"pyqt6": "PyQt6",
"pyqt5": "PyQt5",
}
_root_module = _root... |
eadgarchen/tensorflow | tensorflow/python/layers/core_test.py | Python | apache-2.0 | 20,438 | 0.007877 | # Copyright 2015 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... | se1/Relu')
dense = core_layers.Dense(2, name='dense2')
inputs = random_ops.random_uniform((5, 3), seed=1)
outputs = dense(inputs)
if context.in_graph_mode():
self.assertEqual(outputs.op.name, 'dense2/BiasAdd')
def testActivityRegularizer(self):
regularizer = lambda x: math_ops.reduce_sum(x... | inputs = random_ops.random_uniform((5, 3), seed=1)
_ = dense(inputs)
loss_keys = ops.get_collection(ops.GraphKeys.REGULARIZATION_LOSSES)
self.assertEqual(len(loss_keys), 1)
self.assertListEqual(dense.losses, loss_keys)
def testKernelRegularizer(self):
regularizer = lambda x: math_ops.reduce_sum... |
yaoguai/sanzang-utils | setup.py | Python | mit | 2,044 | 0 | #!/usr/bin/env python3
""" Sanzang Utils setup script for packaging and installation. """
from distutils.core import setup
with open('README.rst', 'r', encoding='utf-8') as fin:
LONG_DESCRIPTION = fin.read()
setup(
#
# B | asic information
#
name='sanzang-utils',
version='1.3.3',
author='yaoguai',
author_email='[email protected]',
url='https://github.com/yaoguai/sanzang-utils',
license='MIT',
#
# Descriptions & classifiers
#
description='Machine Translation from Chinese, Japanese, or K... | tus :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: Education',
'Intended Audience :: Religion',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Natural Language :: E... |
rogerthat-platform/rogerthat-backend | src/rogerthat/api/location.py | Python | apache-2.0 | 2,005 | 0.002494 | # -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# 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... | d_from_app_user
@expose(('api',))
@returns(GetFriendLocationResponseTO)
@arguments(request=GetFriendLocationRequestTO)
def get_friend_location(request):
from rogerthat.rpc import users
from rogerthat.bizz.location import get_friend_location as bizz_get_friend_location
user = users.get_current_user()
b... | from_app_user(user)),
target=GetLocationRequestTO.TARGET_MOBILE)
response = GetFriendLocationResponseTO()
response.location = None # for backwards compatibility reasons
return response
@expose(('api',))
@returns(GetFriendsLocationResponseTO)
@arguments(request=GetFriendsLocat... |
onshape-public/onshape-clients | python/onshape_client/oas/models/bt_spline_description2118_all_of.py | Python | mit | 5,381 | 0 | # coding: utf-8
"""
Onshape REST API
The Onshape REST API consumed by all clients. # noqa: E501
The version of the OpenAPI document: 1.113
Contact: [email protected]
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re # noqa: F401
im... | yword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_t | o_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from t... |
beiko-lab/gengis | bin/Lib/site-packages/pybioclim-20131009220535_53eb0b0-py2.7-win32.egg/pybioclim/__init__.py | Python | gpl-3.0 | 97 | 0 | from config import *
from get_values impor | t *
from map_d | ata import *
from read_data import *
|
jessamynsmith/eggtimer-server | selenium/test_signup.py | Python | mit | 6,622 | 0.000755 | # -*- coding: iso-8859-15 -*-
import datetime
import selenium_settings
from base_test import SeleniumBaseTest
class SignupTest(SeleniumBaseTest):
PASSWORD = 's3l3n1uM'
PASSWORD2 = 'sel3n1uM2'
PASSWORD3 = 'sel3n1uM3'
def setUp(self):
super(SignupTest, self).setUp()
self.admin_login()... | _contains("A use | r is already registered with this e-mail address.")
# Activate account
self.activate_user(self.USERNAME)
# Log in successfully
self.login(self.USERNAME, self.PASSWORD)
self.wait_for_load(title)
# TODO Fix and enable tests
# # Change password
# self.clic... |
hankcs/HanLP | hanlp/components/mtl/tasks/ner/biaffine_ner.py | Python | apache-2.0 | 5,752 | 0.005216 | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-08-05 01:49
import logging
from copy import copy
from typing import Dict, Any, Union, Iterable, List
import torch
from torch.utils.data import DataLoader
from hanlp.common.dataset import SamplerBuilder, PadSequenceDataLoader
from hanlp.common.transform import Vocab... | training=True, **kwargs) -> torch.nn.Module:
return BiaffineNamedEntityRecognitionDecoder(encoder_size, self.config.ffnn_size, len(self.vocabs.label),
self.config.loss_reduction)
def build_metric(self, **kwargs):
return | BiaffineNamedEntityRecognizer.build_metric(self, **kwargs)
def input_is_flat(self, data) -> bool:
return BiaffineNamedEntityRecognizer.input_is_flat(data)
def prediction_to_result(self, prediction: Dict[str, Any], batch: Dict[str, Any]) -> List:
results = []
BiaffineNamedEntityRecogni... |
pedrox/meld | meld/ui/msgarea.py | Python | gpl-2.0 | 8,901 | 0.001573 | # This file is part of the Hotwire Shell user interface.
#
# Copyright (C) 2007,2008 Colin Walters <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the ... | % (secondary_text,)
secondary_label = WrapLabel(secondary_markup)
secondary_label.show()
vbox.pack_start(secondary_label | , True, True, 0)
secondary_label.set_flags(gtk.CAN_FOCUS)
secondary_label.set_use_markup(True)
secondary_label.set_line_wrap(True)
secondary_label.set_selectable(True)
secondary_label.set_alignment(0, 0.5)
self.__labels.append(secondary_label)
... |
liuzz1983/open_vision | openvision/datasets/utils.py | Python | mit | 1,945 | 0.005656 | class ImageClass():
"Stores the paths to images for a given class"
def __init__(self, name, image_paths):
self.name = | name
self.image_paths = image_paths
def __str__(self):
return self.name + ', ' + str(len(self.image_pa | ths)) + ' images'
def __len__(self):
return len(self.image_paths)
def get_dataset(paths):
dataset = []
for path in paths.split(':'):
path_exp = os.path.expanduser(path)
classes = os.listdir(path_exp)
classes.sort()
nrof_classes = len(classes)
for i in ra... |
nuxly/nuxly-odoo-addons | nuxly/models/__init__.py | Python | agpl-3.0 | 106 | 0.009434 | from . impor | t hr_analytic_timesheet
from . import global_time | sheet_state
from . import crm_lead_suivi_gdoc |
ericdill/databroker | databroker/tests/test_v2/generic.py | Python | bsd-3-clause | 11,121 | 0.00054 | import collections
import event_model
import itertools
from bluesky.plans import count
from intake.catalog.utils import RemoteCatalogError
import numpy
import ophyd.sim
import os
import pytest
import time
import uuid
def normalize(gen):
"""
Converted any pages to singles.
"""
for name, doc in gen:
... | )
list(cat)
def test_len(bundle):
"""
Test that Catalog implements __len__.
Otherwise intake will loop it as `sum(1 for _ in catalog)` which is likely
less efficient.
"""
cat = bundle.cat['xyz']()
len(cat) # If not implemented, will raise TypeError
def test_getitem_sugar(bundle):
... | at[-1]
with pytest.raises((IndexError, RemoteCatalogError)):
cat[-(1 + len(cat))] # There aren't this many entries
# Test lookup by integer, not globally-unique, 'scan_id'.
expected = cat[bundle.uid]()
scan_id = expected.metadata['start']['scan_id']
actual = cat[scan_id]()
assert actua... |
eightnoteight/aschedule | tests/testing_ext.py | Python | mit | 2,983 | 0.002011 | # -*- coding: utf-8 -*-
from unittest.mock import patch
from datetime import timedelta
import unittest
import asyncio
import aschedule
class TestingExt(unittest.TestCase):
_multiprocess_shared_ = True
def setUp(self):
self.loop = asyncio.get_event_loop()
async def get_coro(self):
pass
... | ck.call_count)
def test_every_week(self):
self.every_patcher = patch('aschedule.ext.every')
self.addCleanup(self.every_patcher.stop)
self.every_mock = self.every_patcher.start()
from aschedule.ext import every_week
schedule1 = every_week(self.get_coro)
self.every_mo... | lf.every_mock.assert_called_with(self.get_coro, timedelta=timedelta(days=7), loop=self.loop)
self.loop.run_until_complete(asyncio.sleep(1))
schedule1._cancel(running_jobs=True)
schedule2._cancel(running_jobs=True)
self.loop.run_until_complete(asyncio.sleep(1))
self.assertEqual(2,... |
mpetyx/pyrif | 3rdPartyLibraries/FuXi-master/examples/example7.py | Python | mit | 149 | 0 | from FuXi.Hor | n.HornRules import HornFromN3
rules = HornFromN3(
'http://www.agfa.com/w3c/euler/rdfs-rules.n3')
for rule in r | ules:
print(rule)
|
locolan/pokepy | pokepy/migrations/0002_auto_20150503_0002.py | Python | mit | 1,743 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('pokepy', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='pokemon',
name='abilitie... | migrations.AddField(
model_name='pokemon',
name='moves',
field=models.ManyToManyField(to='pokepy.Moves'),
),
migrations.AddField(
model_name='pokemon',
name='name',
field=models.CharField(default=b'digimon', max_length=50),
... | model_name='pokemon',
name='type1',
field=models.CharField(default=b'normal', max_length=50),
),
migrations.AddField(
model_name='pokemon',
name='type2',
field=models.CharField(default=b'normal', max_length=50),
),
migratio... |
nmandavia/kafka-python | test/test_producer.py | Python | apache-2.0 | 8,543 | 0.002109 | # -*- coding: utf-8 -*-
import collections
import logging
import time
from mock import MagicMock, patch
from . import unittest
from kafka import KafkaClient, SimpleProducer
from kafka.common import (
AsyncProducerQueueFull, FailedPayloadsError, NotLeaderForPartitionError,
ProduceResponse, RetryOptions, Topic... | the batches above = (1 + 3 retries) * 4 batches = 16
self.assertEqual(self.client.send_produce_request.call_count, 16)
def test_async_producer_not_leader(self):
for i in | range(10):
self.queue.put((TopicAndPartition("test", i), "msg %i", "key %i"))
# Mock offsets counter for closure
offsets = collections.defaultdict(lambda: collections.defaultdict(lambda: 0))
self.client.is_first_time = True
def send_side_effect(reqs, *args, **kwargs):
... |
open-synergy/opnsynid-hr | hr_employee_pob_from_home_address/__openerp__.py | Python | agpl-3.0 | 563 | 0 | # -*- coding: utf-8 -*-
# Copyright 2018 OpenSynergy Indonesia
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
# pylint: disable=locally-disabled, manifest-required-author
{
| "name": "Employee Place of Birth From Home Address",
"version": "8.0 | .2.0.0",
"category": "Human Resource",
"website": "https://simetri-sinergi.id",
"author": "PT. Simetri Sinergi Indonesia,OpenSynergy Indonesia",
"license": "AGPL-3",
"installable": True,
"depends": [
"hr",
"partner_place_of_birth",
],
"data": [],
}
|
GoogleCloudPlatform/psq | psq/psqworker.py | Python | apache-2.0 | 2,499 | 0 | #!/usr/bin/env python
# Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | ',
help='Import path. By default, this is the current working directory.')
@click.option(
'--pid',
help='Write the process ID to the specified file.')
@click.argument(
'queue',
nargs=1,
required=True)
def main(path, pid, queue):
"""
Standalone PSQ worker.
The queue argument must be ... | ull importable path to a psq.Queue
instance.
Example usage:
psqworker config.q
psqworker --path /opt/app queues.fast
"""
setup_logging()
if pid:
with open(os.path.expanduser(pid), "w") as f:
f.write(str(os.getpid()))
if not path:
path = os.getcwd... |
viswimmer1/PythonGenerator | data/python_files/33855741/web_reserver-bak.py | Python | gpl-2.0 | 1,001 | 0.026973 | import web
import json
import datetime
import time
import uuid
#from mimerender import mimerender
#import mimerender
from onsa_jeroen import *
render_xml = lambda result: "<result>%s</result>"%result
render_json = lambda **result: json.dumps(result,sort_keys=True,indent=4)
render_html = lambda result: "<html><body>%s<... | sleep(1)
#return result
return sync_func
@syncmyCall
@defer.inlineCallbacks
def query (nsa):
global result
client,client_nsa = createClient()
nsa = getNSA(nsa)
qr = yield client.query(client_nsa, nsa, None, "Summary", connection_ids = [] )
#result = qr
result = "blaaa"
print qu... | k")
#if __name__ == "__main__":
|
named-data/ndn-atmos | lib/ndn_cmmap_translators/atmos2ndn_parser/conf_file_parser.py | Python | gpl-3.0 | 4,328 | 0.008549 | #!/usr/bin/env python3
# -*- Mode:python; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
#
# Copyright (c) 2015, Colorado State University.
#
# This file is part of ndn-atmos.
#
# ndn-atmos is free software: you can redistribute it and/or modify it under the
# terms of the GNU Lesser General Public License as publish... | perators'].replace(" ", "").split(',')
#reads which translator to use
self.translator = self.fullConf['Translator']['translator'].replace(" ", "")
except KeyError:
print("Key %s is not found in config file" %(name))
print(sys.exc_info()[2])
except TypeErro... | print(sys.exc_info()[2])
def getMappings(self, confName):
'''parses the schema file and provides name mappings'''
fullConf = self._parseConf()
#if dict is not empty
if fullConf:
res = self._doParsing()
if len(self.filenameMap) == 0 or len(self.ndnNameMap) ... |
petrutlucian94/nova_dev | nova/api/openstack/compute/contrib/user_data.py | Python | apache-2.0 | 949 | 0 | # Copyright 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 ... | extensions
class User_data(extensions.ExtensionDescriptor):
"""Add user_data to the Create Server v1.1 API."""
name = "UserData"
alias = "os-user-data"
namespace = ("http://docs. | openstack.org/compute/ext/"
"userdata/api/v1.1")
updated = "2012-08-07T00:00:00+00:00"
|
2deviant/Mathematica-Trees | converters.py | Python | mit | 673 | 0.004458 | """
Code converter module for trees.py
"""
def _mathematica_line_segments(tree):
"""
Produce Mathematica graphics obje | ct elements.
"""
for branch in tree:
[depth, [[x0, y0], [x1, y1]]] = branch
yield '{{Thickness[{}/300.], Line[{{{{{},{}}},{{{},{}}}}}]}}'.format(
depth, x0, y0, x1, y1
)
def to_mathematica(tree):
"""
Produce Mathematica code to draw the tree.
"""
segments... | de = 'tree = {{\n{}\n}};\n\nShow[Graphics[tree], AspectRatio -> 1, PlotRange -> All]\n'.format(
',\n'.join(segments)
)
return code
|
googlevr/tilt-brush | Support/bin/hack_tilt.py | Python | apache-2.0 | 1,720 | 0.011047 | #!/usr/bin/env python
# Copyright 2020 The Tilt Brush Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# | http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permis... | glevr/tilt-brush-toolkit)"
print "and then put its Python directory in your PYTHONPATH."
sys.exit(1)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--set-min-y', dest='desired_min_y', type=float,
default=None,
help='Move sketch up/down to match ... |
sullivanmatt/splunk-sdk-python | tests/test_storage_passwords.py | Python | apache-2.0 | 9,282 | 0.000431 | #!/usr/bin/env python
#
# Copyright 2011-2015 Splunk, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"): you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | True(p.name in self.storage_passwords)
# Name works with or without a trailing colon
self.assertTrue((":" + username + ":") in self.storage_passwords)
self.as | sertTrue((":" + username) in self.storage_passwords)
p.delete()
self.assertEqual(start_count, len(self.storage_passwords))
def test_update(self):
start_count = len(self.storage_passwords)
realm = testlib.tmpname()
username = testlib.tmpname()
p = self.storage_passw... |
rrajath/PyFileSearch | src/FileSearch.py | Python | mit | 3,158 | 0.007916 | '''
Created on Sep 16, 2013
@author: rajath
'''
import os, fnmatch
# This function takes rootpath and pattern as argument and returns a 'list' of filenames that match the pattern
# For example, if you search for all the *.py files in your workspace, then it returns a list of strings which
# are full paths to these fi... | try:
tmp = dict_files[filetype]
dict_files[filetype] = tmp.append(file_path)
except | :
tmp = []
tmp.append(file_path)
dict_files[filetype] = tmp
return dict_files
#end
# This function takes rootpath as argument and returns a dictionary with directories as keys and its files as values.
def dirs_dict(rootpath):
dict_dirs = {}
for root, dirs, fi... |
vitorfs/bootcamp | bootcamp/messager/models.py | Python | mit | 3,617 | 0.000553 | import uuid
from django.conf import settings
from django.contrib.auth import get_user_model
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.db import transaction
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
class MessageQueryS... | self.unread = False
self.save()
@staticmethod
def send_message(sender, recipient, message):
"""Method to create a new message in a conversation.
:requires:
:param sender: | User instance of the user sending the message.
:param recipient: User instance of the user to recieve the message.
:param message: Text piece shorter than 1000 characters containing the
actual message.
"""
new_message = Message.objects.create(
sender=s... |
huiyiqun/check_mk | web/htdocs/availability.py | Python | gpl-2.0 | 81,172 | 0.010866 | #!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# | ____ _ _ __ __ _ __ |
# | / ___| |__ ___ ___| | __ | \/ | |/ / |
# | | | | '_ \ / _ \/ __| |/ /... | see the file COPYING. If not, write
# to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
# Boston, MA 02110-1301 USA.
import utils
import bi, views, visuals
import sites
from valuespec import *
import cmk.defines as defines
import cmk.paths
import cmk.store as store
# .--Declarations---------... | | | _ \ ___ ___| | __ _ _ __ __ _| |_(_) ___ _ __ ___ |
# | | | | |/ _ \/ __| |/ _` | '__/ _` | __| |/ _ \| '_ \/ __| |
# | | |_| | __/ (__| | (_| | | | (_| | |_| | (_) | | | \__ \ |
# | |____/ \___|\___|_|\__,_|_| \__,_|\__|_|\___/|_| |_|___/ |
# | ... |
yashpatel5400/synalyze | app/segment/settings.py | Python | mit | 420 | 0.009524 | """
__authors__ = Yash, Will, Peter
__description__ = Global variables for the Python files (largely for
doing organization) for segmentation
"""
# ------------------------------ Directory variables -----------------------------
INPUT_DIR = "a | pp/segment/audio"
OUTPUT_DIR = "app/segment | /output"
# ------------------------------ Ruby diarizer ---=-----------------------------
DIARIZER = "app/segment/segment.rb"
|
fnp/redakcja | src/documents/templatetags/common_tags.py | Python | agpl-3.0 | 336 | 0.00597 | # This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
#
from django impor | t template
register = template.Library()
@register.filter
def username(user):
return (" | %s %s" % (user.first_name, user.last_name)).lstrip() or user.username
|
andrewdotn/vmreflect | vmreflect/tests/test_end_to_end.py | Python | bsd-2-clause | 5,318 | 0.002445 | # coding: UTF-8
"""
Full end-to-end test: start a server, tunnel, and connect from the VM
"""
import argparse
import SocketServer
import contextlib
import os
import pkg_resources
import socket
import string
import tempfile
import threading
import time
import unittest
from path import path
from vmreflect import Tunn... | ue')
parser.add_argument('--port', type=int, default=0)
args = parser.parse_args()
server = Server(verbose=True, port=args.port)
print client(server.ip, server.port, "Hello World 1")
try:
if args.keep_alive:
| while 1:
time.sleep(60)
finally:
server.close()
if __name__ == '__main__':
main()
|
MarcoBuster/OrarioTreniBot | src/updates/global_messages.py | Python | mit | 3,165 | 0.001896 | # Copyright (c) 2016-2017 The OrarioTreniBot Authors (see AUTHORS)
#
# 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, cop... | _mode,
"disable_web_page_preview": disable_web_page_preview,
"reply_markup": json.dumps(reply_markup) if reply_markup else ""
})
except botogram.APIError:
r.hset(user_hash, "active", False)
| finally:
time.sleep(0.5)
if message:
message.edit(
"<b>Sending global message...</b>"
"\n<b>{value}/{max_value}</b> ({percentage}%)"
.format(value=bar.value, max_value=bar.max_value, percentage=round(bar.percentage, 1))
)
time.sleep(0.1)
|
Baloc/TouSIX-Manager | tousix_manager/Rules_Generation/Statistics/manager.py | Python | gpl-3.0 | 3,475 | 0.000576 | # Copyright 2015 Rémy Lapeyrade <remy at lapeyrade dot net>
# Copyright 2015 LAAS-CNRS
#
#
# This file is part of TouSIX-Manager.
#
# TouSIX-Manager 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 Founda... | stination": peer_dst.idPeer}
rules.append(rule)
for peer_src in peers:
if peer_src != peer_dst:
if enabled["Stats"].get('IPv6') is True:
| rule = {"module": "Statistics_IPv6",
"rule": ipv6.create_stat(dpid, peer_src, peer_dst),
"source": peer_src.idPeer,
"destination": peer_dst.idPeer}
rules.append(rule)
... |
CMUSV-VisTrails/WorkflowRecommendation | examples/vtk_examples/Rendering/TPlane.py | Python | bsd-3-clause | 1,344 | 0 | #!/usr/bin/env python
# This simple example shows how to do basic texture mapping.
import vtk
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
# Load in the texture map. A texture is any unsigned char image. If it
# is not of this type, you will have to map it through a lookup table
# or by ... | e renderer, set the background and size
ren.AddActor(planeActor)
ren.SetBackground(0.1, 0.2, 0.4)
renWin.SetSize(500, 500)
ren.ResetCamera()
cam1 = ren.GetActiveCamera()
cam1.Elevation(-30)
cam1.Roll(-20)
ren.ResetCameraClippingRange()
| iren.Initialize()
renWin.Render()
iren.Start()
|
apark263/tensorflow | tensorflow/contrib/tensorrt/test/memory_alignment_test.py | Python | apache-2.0 | 2,982 | 0.003018 | # 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... | b.tensorrt.test import tf_trt_integration_test_base as trt_test
from tensorflow.python.framework | import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import nn
from tensorflow.python.platform import test
class MemoryAlignmentTest(trt_test.TfTrtIntegrationTestBase):
def GetParams(sel... |
chemelnucfin/tensorflow | tensorflow/python/keras/layers/local_test.py | Python | apache-2.0 | 17,770 | 0.009285 | # Copyright 2016 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... | zer': 'l2',
'strides': strides,
'data_format': data_format,
'implementation': implementation
}
if padding == 'same' and implementation == 1:
self.assertRaises(ValueError, keras.layers.LocallyConnected2D,
**kwargs)
else:
... | m_samples, num_row, num_col, stack_size))
@parameterized.parameters(_DATA_FORMAT_PADDING_IMPLEMENTATION)
def test_locallyconnected_2d_channels_first(self, data_format, padding,
implementation):
with self.cached_session():
num_samples = 8
filters = 3
... |
dadadel/pyment | tests/docs_already_javadoc.py | Python | gpl-3.0 | 329 | 0.00304 | def func | 1(param1):
"""Function 1
with 1 param
@param param1: 1st parameter
@type param1: type
@return: None
"""
return None
def func2(param1, param2):
"""Function 2
with 2 params
@p | aram param1: 1st parameter
@type param1: type
@param param2: 2nd parameter
"""
pass
|
jcfr/mystic | examples2/g01_alt.py | Python | bsd-3-clause | 2,107 | 0.011391 | #!/usr/bin/env python
#
# Problem definition:
# A-R Hedar and M Fukushima, "Derivative-Free Filter Simulated Annealing
# Method for Constrained Continuous Global Optimization", Journal of
# Global Optimization, 35(4), 521-549 (2006).
#
# Original Matlab code written by A. Hedar (Nov. 23, 2005)
# http://www-optima.amp.... | rn -2*x[3] - x[4] + x[9]
def penalty8(x): # <= 0.0
return -2*x[5] - x[6] + x[10]
def penalty9(x): # <= 0.0
return -2*x[7] - x[8] + x[11]
@quadratic_inequality(penalty1)
@quadratic_inequality(penalty2)
@quadratic_inequality(penalty3)
@quadratic_inequality(penalty4)
@quadratic_inequality(penalty5)
@quadratic_i... | quadratic_inequality(penalty8)
@quadratic_inequality(penalty9)
def penalty(x):
return 0.0
solver = as_constraint(penalty)
if __name__ == '__main__':
x = [0]*len(xs)
from mystic.solvers import fmin_powell
from mystic.math import almostEqual
result = fmin_powell(objective, x0=x, bounds=bounds, p... |
kickstandproject/ripcord | ripcord/tests/api/v1/subscribers/test_get.py | Python | apache-2.0 | 5,736 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2013 PolyBeacon, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless... | -1c61b5f4015e'
params = {
'name': domain_name,
}
headers = {
'X-Tenant-Id': project_id,
'X-User-Id': user_id,
}
res = self.post_json(
'/domains', params=params, status=200, headers=headers)
json = {
'descripti... | 81e06c22c017c137b',
'ha1b': '88bb93a6b9273446665753b5972265a8',
'password': 'foobar',
'project_id': project_id,
'rpid': '[email protected]',
'updated_at': None,
'user_id': user_id,
'username': 'alice',
}
params = {
... |
Shashwat986/thesis | vectoralign/get_nn.py | Python | mit | 1,185 | 0.032911 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import scipy
from sklearn.neighbors import KNeighborsClassifier
from scipy.cluster import hierarchy as hier
from scipy.spatial import distance
import json
import codecs
import sys
if le... | pen(sys.argv[1],"r","utf-8")
words = []
data = []
for line in fi:
if not len(line.strip()): continue
k = line.strip().split()
words | .append(k[0])
data.append([float(i) for i in k[-200:]])
fi.close()
vectors = np.array(data)
print "Pre-processing done"
# Calculate the distance matrix
def dist(x,y):
return np.dot(x,y)
knn = KNeighborsClassifier()
knn.fit(vectors,[0]*len(vectors))
fo = codecs.open(out_file,"w","utf-8")
for i,word in enumerate(... |
shimpe/frescobaldi | frescobaldi_app/cursortools.py | Python | gpl-2.0 | 7,435 | 0.004304 | # cursortools.py -- QTextCursor utility functions
#
# Copyright (c) 2008 - 2014 by Wilbert Berendsen
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at y... | return
text = cursor.selection().toPlainText()
if not text.strip(chars):
return
l = len(text) - len(text.lstrip(chars))
r = len(text) - | len(text.rstrip(chars))
s = cursor.selectionStart() + l
e = cursor.selectionEnd() - r
if cursor.position() < cursor.anchor():
s, e = e, s
cursor.setPosition(s)
cursor.setPosition(e, QTextCursor.KeepAnchor)
def strip_indent(cursor):
"""Moves the cursor in its block to the first non-spac... |
chrxr/wagtail | wagtail/utils/pagination.py | Python | bsd-3-clause | 1,095 | 0 | from __future__ import absolute_import, unicode_literals
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.utils.http import urlencode
from django.utils.six.moves.urllib.parse import parse_qs
DEFAULT_PAGE_KEY = 'p'
def paginate(request, items, page_key=DEFAULT_PAGE_KEY, per_page=... | aginator.num_pages)
return paginator, page
def replace_page_in_query(query, page_number, page_key=DEFAULT_PAGE_KEY):
"""
Replaces ``page_key` | ` from query string with ``page_number``.
>>> replace_page_in_query("p=1&key=value", 2)
'p=2&key=value'
>>> replace_page_in_query("p=1&key=value", None)
'key=value'
"""
getvars = parse_qs(query)
if page_number is None:
getvars.pop(page_key, None)
else:
getvars[page_key] ... |
ngageoint/geoq | geoq/core/forms.py | Python | mit | 8,191 | 0.007447 | # -*- coding: utf-8 -*-
# This technical data was produced for the U. S. Government under Contract No. W15P7T-13-C-F600, and
# is subject to the Rights in | Technical Data-Noncommercial Items clause at DFARS 252.227-7013 (FEB 2012)
from django import forms
from django.forms.widgets import (RadioSelect, CheckboxInput,
CheckboxSelectMultiple)
from django.contrib.auth.models import User, Group
from django.utils.html import escape, conditional_escape
from django.db.models... | s import FilteredSelectMultiple
no_style = [RadioSelect, CheckboxInput, CheckboxSelectMultiple]
class StyledModelForm(forms.ModelForm):
"""
Adds the span5 (in reference to the Twitter Bootstrap element)
to form fields.
"""
cls = 'span5'
def __init__(self, *args, **kwargs):
super(Style... |
bobmyhill/burnman | burnman/classes/layer.py | Python | gpl-2.0 | 36,384 | 0.000082 | from __future__ import print_function
# This file is part of BurnMan - a thermoelastic and thermodynamic toolkit for
# the Earth and Planetary Sciences
# Copyright (C) 2012 - 2017 by the BurnMan team, released under the GNU
# GPL v2 or later.
import numpy as np
from scipy.integrate import odeint
from scipy.integrate i... | self.temperature_mode} temperatures and '
f'{self.pressure_mode} pressures\n')
return writing
def reset(self):
"""
Resets all cached material properties.
It is typically not required for the user to call this function.
"""
self._cached = {}
... | def set_material(self, material):
"""
Set the material of a Layer with a Material
"""
assert(isinstance(material, Material))
self.material = material
self.reset()
def set_temperature_mode(self, temperature_mode='adiabatic',
temperatur... |
minidron/django-geoaddress | setup.py | Python | gpl-2.0 | 1,074 | 0 | # --coding: utf8--
from setuptools import setup, find_packages
setup(
name='django-geoaddress',
version='0.1.14',
description=('Address field with GEO coordinates'),
long_description=open('README.md').read(),
author='Pavel ALekin',
maintainer='Pavel Alek | in',
maintainer_email='[email protected]',
url='https://github.com/minidron/django-geoaddress',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Web Environment",
"Intended Audience :... | c :: Database :: Front-Ends",
"Topic :: Documentation",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
"Topic :: Internet :: WWW/HTTP :: Site Management",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
"Operating System :: OS Independent",
]
)
|
naparuba/opsbro | opsbro/topic.py | Python | mit | 4,562 | 0.013245 | # -*- coding: utf-8 -*-
import random
import itertools
from .misc.lolcat import lolcat
TOPIC_SERVICE_DISCOVERY = 0x1 << 0
TOPIC_AUTOMATIC_DECTECTION = 0x1 << 1
TOPIC_MONITORING = 0x1 << 2
TOPIC_METROLOGY = 0x1 << 3
TOPIC_CONFIGURATION_AUTOMATION = 0x1 << 4
TOPIC_SYSTEM_COMPLIANCE = 0x1 << 5
TOPIC_GENERIC = 0x1 << 6 ... | ROLOGY,
TOPIC_CONFIGURATION_AUTOMATION, TOPIC_SYSTEM_COMPLIANCE]
VERY_ALL_TOPICS = TOPICS[:]
VERY_ALL_TOPICS.append(TOPIC_GENERIC)
TOPICS_LABELS = {
TOPIC_SERVICE_DISCOVERY : u'service discovery',
TOPIC_AUTOMATIC_DECTECTION : u'automatic detection',
TOPIC_MONITORING : u'mon... | PIC_CONFIGURATION_AUTOMATION: u'configuration automation',
TOPIC_SYSTEM_COMPLIANCE : u'system compliance',
TOPIC_GENERIC : u'generic',
}
TOPIC_ID_BY_STRING = {
u'service discovery' : TOPIC_SERVICE_DISCOVERY,
u'automatic detection' : TOPIC_AUTOMATIC_DECTECTION,
u'moni... |
Araneidae/cothread | cothread/input_hook.py | Python | gpl-2.0 | 5,250 | 0.002667 | # This file is part of the Diamond cothread library.
#
# Copyright (C) 2007 James Rowland, 2007-2012 Michael Abbott,
# Diamond Light Source Ltd.
#
# The Diamond cothread library 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 Soft... | the Qt event loop.'''
import sys
import os
from . import cothread
from . import coselect
__all__ = [
'iqt', # Enable interactive Qt loop
]
# When Qt is running in its own stack it really needs quite a bit of room.
QT_STACK_SIZE = int(os.environ.get('COTHREAD_QT_STACK', 1024 * 1024))
def _readli... | is available.'''
coselect.poll_list([(0, coselect.POLLIN)])
def _install_readline_hook(enable_hook = True):
'''Install readline hook. This allows the scheduler to run in parallel
with interactive python: while readline is waiting for input, the
scheduler still operates.
This routine can also... |
roadhead/satchmo | satchmo/recentlist/middleware.py | Python | bsd-3-clause | 1,327 | 0.002261 | from django.core.urlresolvers import NoReverseMatch, reverse
from satchmo.configuration import config_value
import logging
import re
log = logging.getLogger('recentlist.middleware')
try:
producturl = reverse('satchmo_product',
kwargs={'product_slug': 'FAKE'})
produ | cturl = "^" + producturl.replace("FAKE", r'(?P<slug>[-\w]+)')
log.debug('Product url is %s', | producturl)
urlre = re.compile(producturl)
except NoReverseMatch:
log.debug("Could not find product url.")
urlre = None
class RecentProductMiddleware(object):
"""Remember recent products"""
def process_response(self, request, response):
if urlre is not None: # If the product url was found ... |
Melisius/SlowQuant | slowquant/geometryoptimization/GeometryOptimization.py | Python | bsd-3-clause | 1,721 | 0.010459 | import numpy as np
import time
import slowquant.derivatives.runForce as F
from slowquant.numerical.numForce import nForce
def GeoOpt(input, set, results):
maxstep = int(set['Max iteration GeoOpt'])+1
GeoOptol = float(set['Geometry Tolerance'])
stepsize = float(set['Gradient Descent Step'])
... | t[j,3] = input[j,3] - stepsize*dZ[j]
|
output = open('out.txt', 'a')
for j in range(1, len(dX)):
output.write("{: 12.8e}".format(dX[j]))
output.write("\t \t")
output.write("{: 12.8e}".format(dY[j]))
output.write("\t \t")
output.write("{: 12.8e}".forma... |
acuriel/Nixtla | nixtla/core/tools/pympi/Elan.py | Python | gpl-2.0 | 33,330 | 0.00003 | # -*- coding: utf-8 -*-
import time
import EafIO
import warnings
class Eaf:
"""Read and write Elan's Eaf files.
.. note:: All times are in milliseconds and can't have decimals.
:var dict annotation_document: Annotation document TAG entries.
:var dict licences: Licences included in the file.
:va... | ``{stereotype -> description}``.
:var dict controlled_vocabularies: Controlled vocabulary data of the
form: ``{id ->
(descriptions, entries, ext_ref)}``,
descriptions of the form:
... | entries of the form:
``{id -> (values, ext_ref)}``,
values of the form:
``[(lang_ref, description, text)]``.
:var list external_refs: External references, where every reference is... |
canturkisci/agentless-system-crawler | tests/unit/test_plugins.py | Python | apache-2.0 | 72,595 | 0.00135 | import types
import unittest
from collections import namedtuple
import os
import sys
import tempfile
from zipfile import ZipFile, ZipInfo
from utils import jar_utils
sys.path.append('tests/unit/')
import mock
from plugins.systems.config_container_crawler import ConfigContainerCrawler
from plugins.systems.config_host... | ler
from plugins.systems.dockerps_host_crawler import DockerpsHostCrawler
from plugins.systems.file_container_crawler import FileContainerCrawler
from plugins.systems.file_host_crawler import FileHostCrawler
from plugins.systems.interface_container_crawler import InterfaceContainerCrawler
from plugins.systems.interface... | ainer_crawler import JarContainerCrawler
from plugins.systems.jar_host_crawler import JarHostCrawler
from plugins.systems.load_container_crawler import LoadContainerCrawler
from plugins.systems.load_host_crawler import LoadHostCrawler
from plugins.systems.memory_container_crawler import MemoryContainerCrawler
from plug... |
Pharylon/PiClock | clock.py | Python | mit | 1,209 | 0.013234 | import datetime
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
#GPIO.cleanup()
ypins = [17, 18, 27, 22, 23, 24, 25]
xpins = [5, 6, 12]
def | setArray(myInt, array):
asBinary = "{0:b}".format(myInt).zfill(7)
for i in range(0, 7):
if (asBinary[i] == "0"):
array[i] = False
else:
array[i] = True
for i in xpins:
GPIO.setup(i, GPIO.IN)
#GPIO.output(i, False)
for i in ypins:
GPIO.setup(i, GPIO.IN)
#GPIO.output(i, False... | put(17, False)
GPIO.output(5, True)
time.sleep(1)
'''
while True:
now = datetime.datetime.now()
setArray(now.hour, grid[0])
setArray(now.minute, grid[1])
setArray(now.second, grid[2])
for i in range(0, 7):
for j in range(0, 3):
if (grid[j][i]):
GPI... |
maxim5/hyper-engine | hyperengine/tests/named_dict_test.py | Python | apache-2.0 | 3,262 | 0.007357 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'maxim'
import six
import unittest
import numpy as np
import hyperengine as hype
from hyperengine.base import NamedDict
class NamedDictTest(unittest.TestCase):
def test_embedded_dict(self):
spec = hype.spec.new({
'foo': {
'bar': {
... | arning_rate'), 0.001)
self.assertEqua | l(instance.foo, None)
self.assertEqual(instance.get('foo'), None)
self.assertEqual(instance.get('foo', 'bar'), 'bar')
six.assertCountEqual(self, instance.conv.keys(), ['filters', 'residual'])
self.assertEqual(instance.conv.filters, [20, 64])
self.assertEqual(instance.conv.filters[0], 20)
self.a... |
cgwalters/anaconda | pyanaconda/regexes.py | Python | gpl-2.0 | 7,533 | 0.00292 | #
# regexes.py: anaconda regular expressions
#
# Copyright (C) 2013 Red Hat, Inc. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (... | llar sign or up to 31 portable characters,
# both for a maximum total of 32. The empty string is not allowed. "root" is not
# allowed.
# a base expression without anchors, helpful for building other expres | sions
# If the string is the right length to match "root", use a lookback expression
# to make sure it isn't.
_USERNAME_BASE = r'[a-zA-Z0-9._](([a-zA-Z0-9._-]{0,2})|([a-zA-Z0-9._-]{3}(?<!root))|([a-zA-Z0-9._-]{4,31})|([a-zA-Z0-9._-]{,30}\$))'
USERNAME_VALID = re.compile(r'^' + _USERNAME_BASE + '$')
GROUPNAME_VALID = U... |
nhenezi/pymapper | validator.py | Python | mit | 669 | 0.019432 | #! /usr/bin/python
from urlparse import urlparse
def fullPath(baseUrl, link):
# converts baseUrl string to ParseResult (urlparse object)
# for constructing simple links we can ignore everything after
# last slash, i.e. on http://test.com/super.ext?mag=ic
# relative links are constructed with http://test.com/... | turn None
if link.starts | with('/'):
return "http://" + baseUrl.netloc + link
return baseUrl.geturl() + link
|
inducer/codery | pieces/admin.py | Python | mit | 1,253 | 0.002394 | from django.contrib import admin
from pieces.models import (
PieceTag,
Piece, Venue, Study, Keyword,
PieceToStudyAssociation)
# {{{ studies
class KeywordInline(admin.TabularInline):
model = Keyword
extra = 10
class StudyAdmin(admin.ModelAdmin):
list_display = ("id", "name", "st... | tent', 'id')
date_hierarchy = "pub_date"
filter_horizontal = ("tags",)
save_on_top = True
inlines = [PieceToStudyInline]
admin.site.register(Piece, PieceAdmin)
# }}}
class VenueAdmin(admin.ModelAdmin):
list_display = ("id", "name")
list_display_links = ("id", "name")
search_fields = ... | hod=marker
|
Yalnix/BarryBot | config.py | Python | mpl-2.0 | 290 | 0.003448 | # Details used to log into Reddit.
reddit_client_id = ""
reddit_client_secret = ""
r | eddit_user = ""
reddit_pass = ""
# Auth key used to log into Discord.
discord_key = ""
# Command/feature modules.
module_names = (
"default",
)
# Do not c | hange this value!
config_version = 2
|
AutorestCI/azure-sdk-for-python | azure-mgmt-compute/azure/mgmt/compute/v2017_03_30/models/virtual_machine_scale_set_managed_disk_parameters.py | Python | mit | 1,259 | 0.000794 | # 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 ... | -----------------
from msrest.serialization import Model
class VirtualMachineScaleSetManagedDiskParameters(Model):
"""Describes the parameters of a ScaleSet managed disk.
:param storage_account_type: Specifies the storage account type for the
managed disk. Possible values are: Standard_LRS or Premium_L... | ute_map = {
'storage_account_type': {'key': 'storageAccountType', 'type': 'StorageAccountTypes'},
}
def __init__(self, storage_account_type=None):
super(VirtualMachineScaleSetManagedDiskParameters, self).__init__()
self.storage_account_type = storage_account_type
|
benagricola/exabgp | qa/self/operational/operational-send.py | Python | bsd-3-clause | 1,319 | 0.015163 | #!/usr/bin/env python
import os
import sys
import time
# When the parent dies we are seeing continual newlines, so we only access so many before stopping
counter = 1
# sleep a little bit or we will never see the asm in the configuration file
# and the message | received just before we go to the established loop will be printed twice
time.sleep(1)
print 'announce operational rpcq afi ipv4 safi unicast sequence %d' % counter
print 'announce operational rpcp afi ipv4 safi unicast se | quence %d counter 200' % counter
time.sleep(1)
counter += 1
print 'announce operational apcq afi ipv4 safi unicast sequence %d' % counter
print 'announce operational apcp afi ipv4 safi unicast sequence %d counter 150' % counter
time.sleep(1)
counter += 1
print 'announce operational lpcq afi ipv4 safi unicast sequen... |
jcdouet/pyDatalog | pyDatalog/examples/datalog.py | Python | lgpl-2.1 | 2,172 | 0.01151 | """
This file shows how to use pyDatalog using facts stored in datalog.
It has 3 parts:
1. create facts for 2 employees in the datalog engine
2. define business rules
3. Query the datalog engine
"""
from pyDatalog import pyDatalog
""" 1. create facts for 3 employees in the datalog engine """
pyDatalog.cre... | what is the salary class of John ?
print(salary_class['John'] == Y) # Y is 6
# who has a salary of 6300 ?
print(salary[X] == 6300) # X is Mary
# who are the indirect managers of Mary ?
print(indirect_manager('Mary', X)) # X is John
# Who are the employees of John with a salary below 6000 ?
print((salary[X] < 6000) &... | # who is his own indirect manager ?
print(indirect_manager('X', X)) # prints []
# who has 2 reports ?
print(report_count[X] == 2) # X is John
# what is the total salary of the employees of John ?
(budget[X] == sum_(N, for_each=Y)) <= (indirect_manager(Y, X)) & (salary[Y]==N)
print(budget['John']==N) # N is 12200
# ... |
VitalPet/addons-onestein | account_activity_based_costing/tests/__init__.py | Python | agpl-3.0 | 189 | 0 | # - | *- coding: utf-8 -*-
# Copyright 2017 Onestein (<http://www.onestein.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
f | rom . import test_activity_based_costing
|
zedshaw/learn-python3-thw-code | ex51/gothonweb/form_test.py | Python | mit | 379 | 0.005277 | from flask import Flask
fro | m flask import render_template
from flask import request
app = Flask(__name__)
@app.route("/")
def index():
name = request.args.get('name', 'Nobody')
if name:
greeting = f"Hello, {name}"
else:
greet | ing = "Hello World"
return render_template("index.html", greeting=greeting)
if __name__ == "__main__":
app.run()
|
meine-stadt-transparent/meine-stadt-transparent | mainapp/migrations/0025_auto_20190917_2038.py | Python | mit | 564 | 0 | # Generated by Django 2.1.11 on 2019-09-17 18:38
from django.db import migrations, models
class Migr | ation(migrations.Migration):
dependencies = [
('mainapp', '0024_merge_20190405_0941'),
]
operations = [
migrations.AlterField(
model_name='historicalmeeting',
name='cancelled',
field=models.BooleanField(default=False),
),
migrations.AlterF... | ]
|
tux-00/ansible | lib/ansible/plugins/connection/chroot.py | Python | gpl-3.0 | 7,616 | 0.002495 | # Based on local.py (c) 2012, Michael DeHaan <[email protected]>
# (c) 2013, Maykel Moya <[email protected]>
# (c) 2015, Toshio Kuratomi <[email protected]>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public ... | is only needed for implementing
put_file() get_file() so that we don't have to read the whole file
into memory.
compared to exec_command() it looses some niceties like being able to
return the process's exit code immediately.
'''
executable = C.DEFAULT_EXECUTABLE.split(... | local_cmd = [to_bytes(i, errors='surrogate_or_strict') for i in local_cmd]
p = subprocess.Popen(local_cmd, shell=False, stdin=stdin,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return p
def exec_command(self, cmd, in_data=None, sudoable=False):
''' run a c... |
metaperl/metaperl-proxy | myapp.py | Python | mit | 797 | 0.007528 | # imports
## core
import importlib
import logging
import os
import pprint
import sys
import StringIO
## 3rd party
import cherrypy
import requests
## local
def full_path(*extra):
return os.path.join(os.path.dirname(__file__), *extra)
sys.path.insert(0, full_path())
import db
logging.basicConfig()
sorry = 'Thi... | ot(object):
@cherrypy.expose
def index(self, tag):
redirect_url = db.urls[tag]
ip = | cherrypy.request.headers['Remote-Addr']
request_url = 'http://ipinfo.io/{0}/country'.format(ip)
r = requests.get(request_url)
country = r.text.strip()
if country == 'US':
raise cherrypy.HTTPRedirect(redirect_url)
else:
return sorry
|
emillynge/pyangular | backend/googleauth.py | Python | apache-2.0 | 12,555 | 0.000956 | # Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | vloop
from aiohttp import ClientSession, ClientResponse
from google.auth import exceptions, _helpers
from google.auth import jwt
from google.oauth2 import service_account
from google.oauth2._client import _JWT_GRANT_TYPE, _URLENCODED_CONTENT_TYPE, _handle_error_res | ponse, _parse_expiry, \
_REFRESH_GRANT_TYPE
from google.oauth2.service_account import Credentials as _Credentials, _DEFAULT_TOKEN_LIFETIME_SECS
# The URL that provides public certificates for verifying ID tokens issued
# by Google's OAuth 2.0 authorization server.
_GOOGLE_OAUTH2_CERTS_URL = 'https://www.googleap... |
JackDanger/sentry | src/sentry/south_migrations/0029_auto__del_field_projectmember_is_superuser__del_field_projectmember_pe.py | Python | bsd-3-clause | 12,133 | 0.008077 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'ProjectMember.is_superuser'
db.delete_column('sentry_projectmember', 'is_superuser')
# ... | o.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'db_column': "'view'", 'blank': 'True'}),
'data': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'datetime': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', ... | ex': 'True'}),
'event_id': ('django.db.models.fields.CharField', [], {'max_length': '32', 'unique': 'True', 'null': 'True', 'db_column': "'message_id'"}),
'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'blank': 'True', 'related_name': "'event_set'", 'null': 'True', 'to': "orm['sent... |
misaksen/umediaproxy | mediaproxy/interfaces/__init__.py | Python | gpl-2.0 | 113 | 0.00885 | # Copyright (C) 2008 AG-Projects.
#
"""Interfaces between Mediaproxy a | nd the other compon | ents in the system"""
|
mabuchilab/Instrumental | instrumental/drivers/cameras/_pixelfly/_cffi_build/build_errortext.py | Python | gpl-3.0 | 586 | 0 | import sys
import os.path
import setuptools # Fix distutils issues
from cffi import FFI
ffi = FFI()
mod_name = 'instrumental.drivers.cameras._ | pixelfly.errortext'
if sys.platform.startswith('win'):
ffi.set_source(mod_name, """
#define PCO_ERR_H_CREATE_OBJECT
#define PCO_ERRT_H_CREATE_OBJECT
#include <windows.h>
#include "PCO_errt.h"
""", include_dirs=[os.path.dirname(__file__)])
ffi.cdef("void PCO_GetErrorText(DWOR... | e:
ffi.set_source(mod_name, '')
if __name__ == '__main__':
ffi.compile()
|
skraghu/softlayer-python | SoftLayer/fixtures/SoftLayer_Virtual_Guest_Block_Device_Template_Group.py | Python | mit | 820 | 0 | IMAGES = [{
'accountId': 1234,
'blockDevices': [],
'createDate': '2013-12-05T2 | 1:53:03-06:00',
'globalIdentifier': '0B5DEAF4-643D-46CA-A695-CECBE8832C9D',
'id': 100,
'name': 'test_image',
'parentId': '',
'publicFlag': True,
}, {
'accountId': 1234,
'blockDevices': [],
'createDate': '2013-12-05T21:53:03-06:00',
'globalIdentifier': 'EB3841 | 4C-2AB3-47F3-BBBD-56A5F689620B',
'id': 101,
'name': 'test_image2',
'parentId': '',
'publicFlag': True,
}]
getObject = IMAGES[0]
getPublicImages = IMAGES
deleteObject = {}
editObject = True
setTags = True
createFromExternalSource = [{
'createDate': '2013-12-05T21:53:03-06:00',
'globalIdentifier'... |
wfxiang08/ansible | lib/ansible/executor/playbook_executor.py | Python | gpl-3.0 | 12,206 | 0.004424 | # (c) 2012-2014, Michael DeHaan <[email protected]>
#
# This file is part of Ansible
#
# Ansible 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) an... | if 'name' not in var:
raise AnsibleError("'vars_prompt' item is missing 'name:'", obj=play._ds)
vname = var['name']
| prompt = var.get("prompt", vname)
default = var.get("default", None)
private = var.get("private", True)
confirm = var.get("confirm", False)
encrypt = var.get("encrypt", None)
... |
kidchang/compassv2-api | compass/db/api/database.py | Python | apache-2.0 | 9,312 | 0.000537 | # Copyright 2014 Huawei Technologies Co. 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 ... | e
@contextmanager
def session():
"""database session scope.
.. note::
To operate database, it should be called in database session.
"""
import traceback
if has | attr(SESSION_HOLDER, 'session'):
logging.error('we are already in session')
raise exception.DatabaseException('session already exist')
else:
new_session = SCOPED_SESSION()
setattr(SESSION_HOLDER, 'session', new_session)
try:
yield new_session
new_session.commit()... |
almarklein/scikit-image | skimage/segmentation/tests/test_slic.py | Python | bsd-3-clause | 4,145 | 0.000241 | import itertools as it
import warnings
import numpy as np
from numpy.testing import assert_equal, assert_raises
from skimage.segmentation import slic
def test_color_2d():
rnd = np.random.RandomState(0)
img = np.zeros((20, 21, 3))
img[:10, :10, 0] = 1
img[10:, :10, 1] = 1
img[10:, 10:, 2] = 1
i... | [0, 0, 1, 1, 1]], np.int)
result_spaced = np.array([[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1]], np.int)
img += 0.1 * rnd.normal( | size=img.shape)
seg_non_spaced = slic(img, n_segments=2, sigma=0, multichannel=False,
compactness=1.0)
seg_spaced = slic(img, n_segments=2, sigma=0, spacing=[1, 500, 1],
compactness=1.0, multichannel=False)
assert_equal(seg_non_spaced, result_non_spaced)
a... |
flavoi/diventi | diventi/ebooks/migrations/0016_auto_20190505_1854.py | Python | apache-2.0 | 830 | 0.00241 | # Generated by Django 2.1.7 on 2019-05-05 16:5 | 4
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('ebooks', '0015_remove_book_category'),
]
operations = [
migrations.AlterField(
model_name='book',
name='book_product',
... | =True, on_delete=django.db.models.deletion.SET_NULL, related_name='books', to='products.Product', verbose_name='product'),
),
migrations.AlterField(
model_name='chapter',
name='chapter_book',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.de... |
UrLab/beta402 | users/urls.py | Python | agpl-3.0 | 278 | 0 | from dja | ngo.urls import path
import users.views
urlpatterns = [
path("settings/", users.views.user_settings, name="settings"),
path("reset_token/", users.views.r | eset_token, name="reset_token"),
path("panel_hide/", users.views.panel_hide, name="hide_new_panel"),
]
|
ETegro/ETConf | giver/urls.py | Python | agpl-3.0 | 1,178 | 0.012733 | # ETConf -- web-based user-friendly computer hardware configurator
# Copyright (C) 2010-2011 ETegro Technologies, | PLC <http://etegro.com/>
# Sergey Matveev <[email protected]>
#
# 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 (at... | TABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from django.conf.urls.defaults import *
urlpatterns = patte... |
sajuptpm/murano | murano/dsl/exceptions.py | Python | apache-2.0 | 3,632 | 0 | # Copyright (c) 2014 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# | http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for | the specific language governing permissions and limitations
# under the License.
class InternalFlowException(Exception):
pass
class ReturnException(InternalFlowException):
def __init__(self, value):
self._value = value
@property
def value(self):
return self._value
class BreakE... |
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractMtllightnovelCom.py | Python | bsd-3-clause | 635 | 0.029921 | def extractMtllightnovelCom(item):
'''
Parser for 'mtllightnovel.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
t | agmap = [
('devil\'s son-in-law', 'Devil\'s Son-in-Law', 'translated'),
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in | tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False |
hail-is/hail | datasets/load/old/load.gtex_v7_transcript_tpm.GRCh38.liftover.py | Python | mit | 415 | 0.007229 |
import hail as hl
mt = hl.read_matrix_table('gs://hail-datasets/hail-data/gtex_v7_transcript_tpm.GRCh37.mt')
b37 = hl.get_ref | erence('GRCh37')
b37.add_liftover('gs://hail-common/references/grch37_to_grch38.over.chain.gz', 'GRCh38')
mt = mt.annotate_rows(interval=hl.liftover(mt.interval, 'GRCh38'))
mt.describe()
mt.write('gs://hail-datasets/hail-data/gtex_v7_transcript_tpm.GRCh38.liftover.mt', overwrite | =True)
|
tazmanrising/ppa | genCSV/FileParsers/Cadence/SignOffSum.py | Python | mit | 1,596 | 0.006266 | from FileParsers.Parser import Parser
class CadenceSignOffSum(Parser):
def __init__(self, file):
super(CadenceSignOffSum, self).__init__(file)
@staticmethod
def match_line(regex1, line):
import re
line_variables = '.*(%s)[^\|]*\|[^\|]*\|[\s]*([\d.]*).*' % regex1
result = r... | self.metrics.append((max_trans_m | etric_name, self.format_metric_values(found_max_trans.group(2)))) |
coin-or/GrUMPy | src/grumpy/examples/Dippy.py | Python | epl-1.0 | 630 | 0.01746 | from __future__ import print_function
DEBUGGING = False
import sys
#sys.path.append("C:\\CO | IN\\GIMPy\\GrUMPy\\trunk")
#sys.path.append("C:\\COIN\\GIMPy\\trunk")
from pulp import *
from coinor.dippy import DipProblem, Solve
prob = DipProb | lem("Dippy Example", display_mode = 'matplotlib',
display_interval = 1)
x1 = LpVariable("x_1", 0, None, LpInteger)
x2 = LpVariable("x_2", 0, cat=LpInteger)
prob += -x1 - x2, "min"
prob += -2 * x1 + 2 * x2 >= 1
prob += -8 * x1 + 10 * x2 <= 13
Solve(prob, {
'CutCGL': 0,
})
for var in prob.var... |
MarauderXtreme/sipa | sipa/model/pycroft/__init__.py | Python | mit | 3,323 | 0 | # -*- coding: utf-8 -*-
from ipaddress import IPv4Network
from sipa.backends import DataSource, Dormitory
from sipa.backends.exceptions import InvalidConfiguration
from . import user, api, userdb
def init_pycroft_api(app):
try:
app.extensions['pycroft_api'] = api.PycroftApi(
endpoint=app.con... | lidConfiguration(*exception.args)
def init_userdb(app):
userdb.register_userdb_extension(app)
def init_context(app):
init_pycroft_api(app)
init_userdb(app)
datasource = DataSource(
name='pycroft',
user_class=user.User,
mail_server="agdsn.me",
support_mail="[email protected]",
webmai... | ame=dorm[0], display_name=dorm[1], datasource=datasource,
subnets=dorm[2])
for dorm in [
('wu', "Wundtstraße", [
IPv4Network('141.30.216.0/24'), # Wu11
IPv4Network('141.30.222.0/24'), # Wu1
IPv4Network('141.30.223.0/24'), # Wu3
IPv4Network('14... |
lino-framework/book | docs/admin/mypy/prj1/settings.py | Python | bsd-2-clause | 724 | 0.008287 | # -*- coding: UTF-8 -*-
from lino.projects.std.settings import *
import logging
logging.getLogger('weasyprint').setLevel("ERROR") # see #1462
class Site(Site):
title = "Lino@prj1"
# server_url = "https://prj1.mydomain.com"
SITE = Site(globals())
# locally override attributes of | individual plugins
# SITE.plugins.finan.suggest_future_vouchers = True
# MySQL
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mysite', #database name
'USER': 'django',
'PASSWORD': 'my cool password',
'HOST': 'localhost', |
'PORT': 3306,
'OPTIONS': {
"init_command": "SET storage_engine=MyISAM",
}
}
}
|
EricZaporzan/evention | evention/events/migrations/0010_ignoredevent.py | Python | mit | 1,007 | 0.002979 | # -*- coding: utf-8 -*-
# Generated by Djan | go 1.9.4 on 2016-04-11 11:22
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 = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('events', '0009_event_title'),
]
operations = [
migrations.CreateModel(
name='IgnoredEvent',
fields=[
... |
dustlab/noisemapper | scripts/nmcollector.py | Python | mit | 259 | 0.015444 | #!/usr/bin/python
| from noisemapper.mapper import *
#from collectors.lib import utils
### Define the object mapper and start mapping
def main():
# utils.drop_privileges()
mapper = NoiseMapper( | )
mapper.run()
if __name__ == "__main__":
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.