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 |
|---|---|---|---|---|---|---|---|---|
yxdong/ybk | zg/models.py | Python | mit | 3,701 | 0.000277 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
# from datetime import timedelta, datetime
from yamo import (
Connection,
EmbeddedDocument, Document, IDFormatter, Index,
StringField,
IntField,
FloatField,
BooleanField,
ListField,
EmbeddedField,
DateTimeField,
)
conn = ... | lass Meta:
idf = IDFormatter('{user_id}_{login_name}')
user_id = StringField(required=True)
login_name = StringField(required=True)
login_password = StringField(required=True)
class MyPosition(EmbeddedDocument):
""" 持仓汇总 """
name = StringField(required=True)
symbol = StringField(req... | quantity = IntField(required=True)
price = FloatField(required=True)
sellable = IntField()
profit = FloatField()
@property
def increase(self):
if self.price > 0:
return '{:4.2f}%'.format(
(self.price / self.average_price - 1) * 100)
else:
re... |
derrickorama/image_optim | image_optim/__init__.py | Python | mit | 52 | 0.019231 | from .c | ore impor | t ImageOptim, NoImagesOptimizedError |
nanolearning/edx-platform | lms/djangoapps/shoppingcart/views.py | Python | agpl-3.0 | 9,715 | 0.0035 | import logging
import datetime
import pytz
from django.conf import settings
from django.contrib.auth.models import Group
from django.http import (HttpResponse, HttpResponseRedirect, HttpResponseNotFound,
HttpResponseBadRequest, HttpResponseForbidden, Http404)
from django.utils.translation import ugettext as _
from ... | paratedCourseKey
from shoppingcart.reports import RefundReport, ItemizedPurchaseReport, UniversityRevenueShareR | eport, CertificateStatusReport
from student.models import CourseEnrollment
from .exceptions import ItemAlreadyInCartException, AlreadyEnrolledInCourseException, CourseDoesNotExistException, ReportTypeDoesNotExistException
from .models import Order, PaidCourseRegistration, OrderItem
from .processors import process_postp... |
zen/openstack-dashboard | django-openstack/django_openstack/tests/view_tests/dash/container_tests.py | Python | apache-2.0 | 4,367 | 0.001145 | # 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 2011 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# no... | self.assertEqual(containers[0].name, 'containerName')
self.mox.VerifyAll()
def test_delete_container(self):
formData = {'contain | er_name': 'containerName',
'method': 'DeleteContainer'}
self.mox.StubOutWithMock(api, 'swift_delete_container')
api.swift_delete_container(IsA(http.HttpRequest),
'containerName')
self.mox.ReplayAll()
res = self.client.post(reverse... |
mir-group/flare | tests/test_mgp.py | Python | mit | 12,643 | 0.000791 | import numpy as np
import os
import pickle
import pytest
import re
import time
import shutil
from copy import deepcopy
from numpy import allclose, isclose
from flare import struc, env, gp
from flare.parameters import Parameters
from flare.mgp import MappedGaussianProcess
from flare.lammps import lammps_calculator
fro... | force_block_only,
noa=5,
)
gp_model.parallel = True
gp_model.n_cpus = 2
allgp_dict[f"{bodies}{multihyps}"] = gp_model
yield allgp_dict
del | allgp_dict
@pytest.fixture(scope="module")
def all_mgp():
allmgp_dict = {}
for bodies in ["2", "3", "2+3"]:
for multihyps in [False, True]:
allmgp_dict[f"{bodies}{multihyps}"] = None
yield allmgp_dict
del allmgp_dict
@pytest.fixture(scope="module")
def all_lmp():
all_lmp_d... |
Kami/libcloud | contrib/generate_provider_logos_collage_image.py | Python | apache-2.0 | 4,224 | 0 | #!/usr/bin/env python
#
# 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 (th... | o files')
parser.add_argument('--output-path', action='store',
help='Path where the new files will be written')
args = parser.parse_args()
input_path = os.path.abspath(args.input_path)
output_path = os.path.abspath(args.output_path)
main( | input_path=input_path, output_path=output_path)
|
Azure/azure-sdk-for-python | sdk/compute/azure-mgmt-compute/azure/mgmt/compute/v2016_03_30/operations/_virtual_machine_scale_set_vms_operations.py | Python | mit | 56,685 | 0.004869 | # 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 ... | pName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'),
"vmScaleSetName": _SERIALIZER.url("vm_scale_set_name", vm_scale_set_name, 'str'),
"instanceId": _SERIALIZER.url("instance_id", instance_id, 'str'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscr | iption_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_paramet... |
ankanch/tieba-zhuaqu | DSV-user-application-plugin-dev-kit/lib/result_functions_file.py | Python | gpl-3.0 | 3,240 | 0.01997 | import os
import datetime
import lib.maglib as MSG
#这是一个对结果进行初步处理的库
#用来分离抓取结果,作者,发帖时间
#抓取结果应该储存在【用户端根目录】并以result命名
#在测试情况下,抓取结果文件为results.txt
#重要全局变量
PATH_SUFFIX = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir))
print(PATH_SUFFIX)
PATH_SUFFIX = PATH_SUFFIX[::-1]
PATH_SUFFIX = PATH_SUFFIX[... | ("\r\n")
for db in dbl:
DBSETTINGS[db[0]] = db[db.find('=')+1:].replace('\'','').replace(' ','')
return data
loadDataSource()
DBCONN = pymysql.connect(host=DBSETTINGS['H'], port=3306,user=DBSETTINGS['U'],passwd=DBSETTINGS['P'],db=DBSETTINGS['D'],charset='UTF8')
| DBCUR = DBCONN.cursor()
#从数据库查询包含指定字词的所有数据集
#返回值:包含指定字词的数据集列表
def queryWordContainPostListbyKeyword(word):
SEL = "select CONTENT from `postdata` where CONTENT like('%" + word +"%')"
DBCUR.execute("SET names 'utf8mb4'")
DBCUR.execute(SEL)
DBCONN.commit()
datalist = DBCUR.fetchall()
return d... |
mfcloud/python-zvm-sdk | zvmsdk/tests/unit/sdkwsgi/handlers/test_version.py | Python | apache-2.0 | 1,674 | 0 | # Copyright 2017,2018 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 agr... | version(self):
req = mock.Mock()
ver_str = {"rc": 0,
"overallRC": 0,
"errmsg": "",
"modID": None,
"output":
{"api_version": version.APIVERSION,
"min_version": version.APIVERSION,
... | "rs": 0}
res = version.version(req)
self.assertEqual('application/json', req.response.content_type)
# version_json = json.dumps(ver_res)
# version_str = utils.to_utf8(version_json)
ver_res = json.loads(req.response.body.decode('utf-8'))
self.assertEqual(ver_str, ver_r... |
hillst/RnaMaker | bin/daemons/testclient.py | Python | mit | 789 | 0.010139 | #!/usr/bin/python
import socket
import sys
HOST, PORT = "24.21.106.140", 8080
# Create a socket (SOCK_STREAM means a TCP socket)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
| try:
# Connect to server and send data
print "Connected to ", HOST, ":", PORT, "\n","Awaiting input\n"
data = sys.stdin.readline()
sock.connect((HOST, PORT))
print "Connected to ", HOST, ":", PORT, "\n","Awaiting input\ | n"
exit = False
while exit != True:
sock.sendall(data + "\n")
if data.strip() == 'bye':
exit = True
received = sock.recv(1024)
print "Sent: " , data
print "Received: " , received
data = sys.stdin.readline()
# Receive data from the server and sh... |
Pierre-Sassoulas/django-survey | survey/admin.py | Python | agpl-3.0 | 1,693 | 0.001772 | from django.contrib import admin
| from survey.actions import make_published
from survey.exporter.csv import Survey2Csv
from survey.exporter.tex import Survey2Tex
from survey.models import Answer, Category, Question, Response, Survey
class QuestionInline(admin.StackedInline):
model = Question
ordering = ("order", "category")
extra = 1
... | ().get_formset(request, survey_obj, *args, **kwargs)
if survey_obj:
formset.form.base_fields["category"].queryset = survey_obj.categories.all()
return formset
class CategoryInline(admin.TabularInline):
model = Category
extra = 0
class SurveyAdmin(admin.ModelAdmin):
list_displ... |
jorgegarciadev/estacaidooque | run.py | Python | mit | 166 | 0.012048 | # -*- coding: utf-8 -*-
from app import app
import os
if __name__ == "__ma | in__":
port = int(os.environ.ge | t('PORT', 33507))
app.run(port=port, debug = True)
|
candlepin/subscription-manager | test/zypper_test/test_serviceplugin.py | Python | gpl-2.0 | 2,745 | 0.0051 | import configparser
from unittest import TestCase
import os
import subprocess
import tempfile
from test import subman_marker_functional, subman_marker_needs_envvars, subman_marker_zypper
@subman_marker_functional
@subman_marker_zypper
@subman_marker_needs_envvars('RHSM_USER', 'RHSM_PASSWORD', 'RHSM_URL', 'RHSM_POOL'... | True)
subprocess.call('{sub_man} attach --pool={RHSM_POOL}'.format(sub_man=self.SUB_MAN, **os.environ), shell=True)
self.assertTrue(self.has_subman_repos())
def test_can_download_rpm(self):
subprocess.check_call('{sub_man} register --username={RHSM_USER} --password={RHSM_PASSWORD} --serveru... | iron), shell=True)
subprocess.check_call('{sub_man} repos --enable={RHSM_TEST_REPO}'.format(sub_man=self.SUB_MAN, **os.environ), shell=True)
# remove cached subman packages
subprocess.call('rm -rf /var/cache/zypp/packages/subscription-manager*', shell=True)
# remove test package if inst... |
kingsdigitallab/tvof-django | tvof/text_search/es_indexes.py | Python | mit | 12,832 | 0.000935 | from collections import deque, OrderedDict
from django.conf import settings
from elasticsearch_dsl import Document, Date, Integer, Keyword, Text, Search, Index, Boolean, Completion, \
SearchAsYouType, normalizer, analyzer
from elasticsearch_dsl.connections import connections
from tqdm import tqdm
from elasticsearc... | lemma = Keyword()
class Index:
name = 'autocomplete'
@classmethod
def new_from_token_element(cls, token_element, parsing_context):
ret = []
lemma = | normalise_lemma(token_element.attrib.get('lemma', ''))
if lemma:
form = normalise_form(token_element)
for i in [0, 2]:
autocomplete = '{} {}'.format(form or lemma, lemma)
doc = cls(
lemma=lemma,
form=form,
... |
drslump/pyshould | tests/expect.py | Python | mit | 856 | 0 | import unittest
from pyshould import *
from pyshould.expect import expect, expect_all, expect_any, expect_none
class ExpectTestCase(unittest.TestCase):
""" Simple tests for the expect based api """
def test_expect(self):
expect(1).to_equal(1)
expect(1).to_not_equal(0)
def test_expect_all... | :
expect_all([1, 2]).to_be_integer()
expect_all(1, 2).to_be_integer()
def test_expect_any(self):
expect_any([1, 2]).to_equal(2)
expect_any(1, 2).to_equal(2)
def test_expect_none(self):
expect_none([1, 2]).to_equal(0)
expect_none(1, 2).to_equal(0)
def test_e... | s(self):
expect(all_of(1, 2)).to_be_integer()
expect(any_of([1, 2])).to_eq(1)
def test_ignore_keywords(self):
it(1).should.be_an_int()
expect(1).to.equal(1)
|
IsabellKonrad/Shugou | combineFiles.py | Python | mit | 1,675 | 0.001194 | import os
import sys
import re
def read_text_from_include(line):
match = re.search("^#:include *(.*.kv)", line)
filename = match.group(1)
return open(filename, 'r').read()
def main(combine):
if combine:
if not os.path.isfile('shugou_original.kv'):
os.rename('shugou.kv', 'shugou_o... | d.")
except:
print("No backup file.\
Maybe the original file has been restored already?")
if __name__ == '__main__':
if len(sys.argv) == 1:
print("Missing necessary argument. Use \n\
'combine' to concatenate the include files into shugou.kv \n\
'clean' ... | sys.argv[1] == 'True'):
main(True)
elif (sys.argv[1] == 'Clean' or
sys.argv[1] == 'clean' or sys.argv[1] == 'False'):
main(False)
else:
print("Can not understand the argument.\
Call this file again with no arguments to see possib... |
waheedahmed/edx-platform | lms/djangoapps/email_marketing/tests/test_signals.py | Python | agpl-3.0 | 8,373 | 0.001672 | """Tests of email marketing signal handlers."""
import logging
import ddt
from django.test import TestCase
from django.test.utils import override_settings
from mock import patch
from util.json_request import JsonResponse
from email_marketing.signals import handle_unenroll_done, \
email_marketing_register_user, \
... | lue = SailthruResponse(JsonResponse({'ok': True}))
update_user.delay(self.user.username, new_user=True, activation=True)
# look for call args for 2nd call
self.assertEquals(mock_sailthru.call_args[0][0], "send")
userparms = mock_sailthru.call_args[0][1]
sel | f.assertEquals(userparms['email'], TEST_EMAIL)
self.assertEquals(userparms['template'], "Activation")
@patch('email_marketing.tasks.log.error')
@patch('email_marketing.tasks.SailthruClient.api_post')
def test_error_logging(self, mock_sailthru, mock_log_error):
"""
Ensure that error ... |
pli3/e2-openwbif | plugin/controllers/views/web/getservices.py | Python | gpl-2.0 | 5,478 | 0.011683 | #!/usr/bin/env python
##################################################
## DEPENDENCIES
import sys
import os
import os.path
try:
import builtins as builtin
except ImportError:
import __builtin__ as builtin
from os.path import getmtime, exists
import time
import types
from Cheetah.Version import MinCompatib... |
else:
_filter = self._CHEETAH__currentFilter = \
self._CHEETAH__filters[filterName] = getattr(self._CHEETAH__filtersLib, filterName)(self).filter
write(u'''<?xml version="1.0" encoding="UTF-8"?>
<e2servicelis | t>
''')
for service in VFFSL(SL,"services",True): # generated from line 4, col 2
write(u'''\t<e2service>
\t\t<e2servicereference>''')
_v = VFFSL(SL,"service.servicereference",True) # u'$service.servicereference' on line 6, col 23
if _v is not None: write(_filter(_v, rawExpr=u... |
skyostil/tracy | src/analyzer/Charting.py | Python | mit | 2,058 | 0.014091 | # Copyright (c) 2011 Nokia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribu... | ." % e)
def slicePlot(x, y, sliceLength = 100, st | yle = "line", *args, **kwargs):
assert len(x) == len(y)
if style == "line":
plotFunc = pylab.plot
elif style == "bar":
plotFunc = pylab.bar
else:
raise RuntimeError("Unknown plotting style: %s" % style)
if len(x) < sliceLength:
plotFunc(x, y, *args, **kwargs)
return
... |
rhyolight/nupic.core | bindings/py/src/nupic/bindings/regions/TestNode.py | Python | agpl-3.0 | 10,011 | 0.005894 | # ------------------------------------ | ----------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2015, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribu... | he Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero Public License for more details.
#
# You should have received a copy of the GNU Af... |
antoinecarme/pyaf | tests/artificial/transf_Logit/trend_PolyTrend/cycle_7/ar_12/test_artificial_1024_Logit_PolyTrend_7_12_20.py | Python | bsd-3-clause | 262 | 0.087786 | import pyaf.Bench.TS_datasets as tsds
| import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 1024 , FREQ = 'D', seed = 0, trendtype = "PolyTrend", cycle_length = 7, transform = "Logit", sigma = 0.0, exog_count = 20, ar_orde | r = 12); |
vhaupert/mitmproxy | examples/addons/events-websocket-specific.py | Python | mit | 1,300 | 0 | """WebSocket-specific events."""
import mitmproxy.http
import mitmproxy.websocket
class Events:
# Websocket lifecycle
def websocket_handshake(self, flow: mitmproxy.http.HTTPFlow):
"""
Called when a client wants to establish a WebSocket connection. The
WebSocket-specific headers... | s user-modifiable. Currently there are two types of
messages, corresponding to the BINARY and TEXT frame types.
"""
def websocket_error(self, flow: mitmproxy.websocket.WebSocketFlow):
"""
A websocket conne | ction has had an error.
"""
def websocket_end(self, flow: mitmproxy.websocket.WebSocketFlow):
"""
A websocket connection has ended.
"""
|
jvandijk/pla | pla/version.py | Python | mit | 23 | 0 | _ | _version__ = "master" | |
yetty/django-embed-video | example_project/example_project/wsgi.py | Python | mit | 1,447 | 0.000691 | """
WSGI config for example_project project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a | module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standa | rd Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
# We defer... |
rmarkello/pyls | pyls/matlab/io.py | Python | gpl-2.0 | 6,754 | 0 | # -*- coding: utf-8 -*-
from collections.abc import MutableMapping
import numpy as np
import scipy.io as sio
from ..structures import PLSResults
_result_mapping = (
('u', 'x_weights'),
('s', 'singvals'),
('v', 'y_weights'),
('usc', 'x_scores'),
('vsc', 'y_scores'),
('lvcorrs', 'y_loadings'),... | to be renamed
mapping : list of tuples
List of (oldkey, newkey) pairs to rename entries in `d`
Returns
-------
renamed : dict
Input dictionary `d` with keys renamed
"""
new_dict = d.copy()
for oldkey, newkey in mapping:
try:
new_dict[newkey] = new_dict.... | rt_matlab_result(fname, datamat='datamat_lst'):
"""
Imports `fname` PLS result from Matlab
Parameters
----------
fname : str
Filepath to output mat file obtained from Matlab PLS toolbox. Should
contain at least a result struct object.
datamat : str, optional
Variable nam... |
jprk/sirid | aapi/AAPI.py | Python | gpl-3.0 | 131,251 | 0.012107 | # This file was automatically generated by SWIG (http://www.swig.org).
# Version 1.3.36
#
# Don't modify this file, modify the SWIG interface instead.
# This file is compatible with both classic and new-style classes.
import _AAPI
import new
new_instancemethod = new.instancemethod
try:
_swig_property = property
ex... | set
AKIActionAddNextSubPathODAction = _AAPI.AKIActionAddNextSubPathODAction
AKIActionAddNextSubPathResultAction = _AAPI.AKIActionAddNextSubPathResultAction
AKIActionAddNextSubPathPTAction = _AAPI.AKI | ActionAddNextSubPathPTAction
AKIActionModifyNextTurningODAction = _AAPI.AKIActionModifyNextTurningODAction
AKIActionModifyNextTurningResultAction = _AAPI.AKIActionModifyNextTurningResultAction
AKIActionModifyChangeDestAction = _AAPI.AKIActionModifyChangeDestAction
AKIActionModifyNextSubPathResultAction = _AAPI.AKIActio... |
lavish205/olympia | src/olympia/devhub/tests/test_utils.py | Python | bsd-3-clause | 10,323 | 0 | import os.path
from django.conf import settings
from django.test.utils import override_settings
import mock
from celery.result import AsyncResult
from olympia import amo
from olympia.amo.tests import TestCase, addon_factory, version_factory
from olympia.devhub import tasks, utils
from olympia.files.models import Fi... | alidation(
['error', 'warning', 'notice', 'error'])
utils.limit_val | idation_results(validation)
limited = validation['messages']
assert len(limited) == 3
assert '2 messages were truncated' in limited[0]['message']
assert limited[1]['type'] == 'error'
assert limited[2]['type'] == 'error'
class TestFixAddonsLinterOutput(TestCase):
def test_f... |
ngoduykhanh/PowerDNS-Admin | powerdnsadmin/__init__.py | Python | mit | 4,275 | 0.000702 | import os
import logging
from flask import Flask
from flask_seasurf import SeaSurf
from flask_mail import Mail
from werkzeug.middleware.proxy_fix import ProxyFix
from flask_session import Session
from .lib import utils
def create_app(config=None):
from . import models, routes, services
from .assets import as... | _name'] = utils.display_record_name
app.jinja_env.filters['display_master_name'] = utils.display_master_name
app.jinja_env.filters['display_second_to_time'] = utils.display_time
app.jinja_env.filters[
'email_to_gravatar_url'] = utils.email_to_gravatar_url
app.jinja_env.filters[
'display_... | .pretty_domain_name
# Register context proccessors
from .models.setting import Setting
@app.context_processor
def inject_sitename():
setting = Setting().get('site_name')
return dict(SITE_NAME=setting)
@app.context_processor
def inject_setting():
setting = Setting()
... |
slackapi/python-slackclient | tutorial/PythOnBoardingBot/onboarding_tutorial.py | Python | mit | 2,881 | 0.003124 | class OnboardingTutorial:
"""Constructs the onboarding message and stores the state of which tasks were completed."""
WELCOME_BLOCK = {
"type": "section",
"text": {
"type": "mrkdwn",
"text": (
"Welcome to Slack! :wave: We're so glad you're here. :blush:\n... | ttps://get.slack.help/hc/en-us/articles/206870317-Emoji-reactions|"
"Learn How to Use Emoji Reactions>*"
)
return self._get_task_block(text, information)
def _get_pin_block(self):
task_checkmark = self._get_checkmark(self.pin_task_completed)
text = (
f"{task_... | sage* :round_pushpin:\n"
"Important messages and files can be pinned to the details pane in any channel or"
" direct message, including group messages, for easy reference."
)
information = (
":information_source: *<https://get.slack.help/hc/en-us/articles/205239997-Pi... |
gnuvet/gnuvet | options_ui.py | Python | gpl-3.0 | 1,879 | 0.00958 | # -*- coding: utf-8 -*-
# Copyright (c) 2015 Dipl.Tzt. Enno Deimel <ennodotvetatgmxdotnet>
#
# This file is part of gnuvet, published under the GNU General Public License
# version 3 or later (GPLv3+ in short). See the file LICENSE for information.
# Initially created: Fri Apr 23 00:02:26 2010 by: PyQt4 UI code gene... | autoHistCb = QCheckBox(Options)
self.autoHistCb.setGeometry(60,50,104,23)
self.lSympCb = QCheckBox(Options)
self.lSympCb.setGeometry(60,80,122,23)
self.retranslateUi(Options)
def retranslateUi(self, Options):
Options.setWindowTitle(tl("GnuVet: Set Options"))
self | .autoConsCb.setToolTip(tl("To automatically book consultation"))
self.autoConsCb.setText(tl("Auto-Consult"))
self.autoHistCb.setToolTip(tl("To automatically open History Window."))
self.autoHistCb.setText(tl("Auto-History"))
self.lSympCb.setToolTip(tl("To use the Lead Symptom feature."))... |
quantmind/pulsar-queue | tests/example/executable.py | Python | bsd-3-clause | 235 | 0 | """ | An example of a python script which can be executed by the task queue
"""
import sys
def execute():
"""Simply write the python executable
"""
sys.stdout.write(sy | s.executable)
if __name__ == '__main__':
execute()
|
vmlaker/pythonwildmagic | tool/parse-xml.py | Python | mit | 1,870 | 0.004278 | #!/usr/bin/env python
"""Parse GCC-XML output files and produce a list of class names."""
# import system modules.
import multiprocessing
import xml.dom.minidom
import sys
import os
# Import application modules.
import mpipe
import util
# Configure and parse the command line.
NAME = os.path.basename(sys.argv[0])
AR... |
name = entry.getAttribute('demangled')
NSPACE = 'Wm5::'
if name[:len(NSPACE)] != NSPACE:
continue
names.append(name)
return names
pipe = mpipe.Pipeline(mpipe.UnorderedStage(parseFile, num_cpus))
for fname in fnames:
pipe.put(fname)
pipe.put(None)
# Report on progres... | e_count) / len(fnames) * 100
sys.stdout.write('\r' + '%d of %d (%.1f%%)'%(done_count, len(fnames), percent))
sys.stdout.flush()
# End on a newline.
print()
print('Writing file %s'%ARGS['out_file'])
fout = open(ARGS['out_file'], 'w')
for key in sorted(total_names):
fout.write('%s\n'%key)
fout.close()
# Th... |
hclivess/Stallion | nuitka/Cryptodome/Util/__init__.py | Python | gpl-3.0 | 1,951 | 0.00205 | # -*- coding: utf-8 -*-
#
# ===================================================================
# The contents of this file are dedicated to the public domain. To
# the extent that dedication to the public domain is not available,
# everyone is granted a worldwide, perpetual, royalty-free,
# non-exclusive license to e... | emoving p | adding.
======================== =============================================
:undocumented: _galois, _number_new, cpuid, py3compat, _raw_api
"""
__all__ = ['RFC1751', 'number', 'strxor', 'asn1', 'Counter', 'Padding']
|
bokeh/bokeh | examples/app/taylor.py | Python | bsd-3-clause | 2,238 | 0.003128 | ''' A taylor series visualization graph. This example demonstrates
the ability of Bokeh for inputted expressions to reflect on a chart.
'''
import numpy as np
import sympy as sy
from bokeh.core.properties import value
from bokeh.io import curdoc
from bokeh.layouts import column
from bokeh.models import (ColumnDataSou... | , order, x_range=(0, 1), n=200):
x0, x1 = x_range
x = np.linspace(float(x0), float(x1), n)
fy = sy.lambdify(xs, fx, modules=['numpy'])(x)
tx = fx.series(xs, n=order).removeO()
if tx.is_Number:
ty = np.zeros_like(x)
ty.fill(float(tx))
else:
ty = sy.lambdify(xs, tx, modul... | =['numpy'])(x)
return x, fy, ty
source = ColumnDataSource(data=dict(x=[], fy=[], ty=[]))
p = figure(x_range=(-7,7), y_range=(-100, 200), width=800, height=400)
line_f = p.line(x="x", y="fy", line_color="navy", line_width=2, source=source)
line_t = p.line(x="x", y="ty", line_color="firebrick", line_width=2, sourc... |
ashapochka/saapy | saapy/analysis/actor.py | Python | apache-2.0 | 11,608 | 0.000258 | # coding=utf-8
from typing import List
import networkx as nx
import pyisemail
from fuzzywuzzy import fuzz
from recordclass import recordclass
import pandas as pd
import saapy.util as su
from .lexeme import cleanup_proper_name
def connect_actors(actor_frame, connectivity_sets, connectivity_column):
"""
:para... | r_email.split('@')
parsed_email.name = email_parts[0]
if len(email_parts) == 2:
parsed_email.domain = email_parts[1]
else:
parsed_email.domain = ''
parsed_email.parsed_name = self.parse_name(parsed_email.name)
return parsed_email
def parse_actor(self,... | if not name and name_from_email:
name = parsed_email.parsed_name.name
actor = Actor(name, email)
actor.parsed_name = self.parse_name(name)
actor.parsed_email = parsed_email
return actor
ACTOR_SIMILARITY_FIELDS = ['possible',
'identical',
... |
Stanford-Online/edx-platform | openedx/stanford/djangoapps/student_utils/tests/test_bulk_user_activate.py | Python | agpl-3.0 | 2,256 | 0.000887 | """
Tests for the bulk_user_activate command.
"""
from django.contrib.auth.models import User
from django.core.management import call_command
from django.test import TestCase
from openedx.stanford.djangoapps.student_utils.helpers import get_users_by_email
class BulkUserActivateTests(TestCase):
"""
Test the ... | f).setUp()
self.domain = [
"{i}.example.com".format(
| i=i,
)
for i in xrange(BulkUserActivateTests.NUMBER_DOMAINS)
]
self.users = [
User.objects.create(
username="user{i}".format(
i=i,
),
email="user{i}@{domain}".format(
... |
carpedm20/Bias | scripts/download.py | Python | bsd-3-clause | 449 | 0.004454 | """
Downloads the following:
- Korean Wikipedia texts
- Korean
"""
from sqlparse import parsestream
from sqlparse.sql impo | rt Parenthesis
for statement in parsestream(open('data/test.sql')):
texts = [str(token.tokens[1].tokens[-1]).decode('string_escape') for token in statement.tokens if isinstance(token, Parenthesis)]
print texts
texts = [text for text in texts if tex | t[0] != '#']
if texts:
print "\n===\n".join(texts)
|
google/makani | config/base_station/sim/perch_sim.py | Python | apache-2.0 | 5,391 | 0.002968 | # Copyright 2020 Makani Technologies LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | ted here:
# go/makaniwiki/perch-geometry.
'panel': {
| # For each panel, the center [m] and radius [m] describe the
# cylinder modeling it. The z_extents_p [m] specify the planes,
# parallel to the perch z-plane, at which the cylinders are
# cut.
'port': {
'center_panel': [3.122, 0.763],
'radius': 4.0... |
jburns12/stixproject.github.io | documentation/idioms/malware-hash/malware-indicator-for-file-hash_consumer.py | Python | bsd-3-clause | 1,039 | 0.001925 | #!/usr/bin/env python
# Copyright (c) 2014, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
import sys
from stix.core import STIXPackage
def parse_stix(pkg):
print("== MALWARE ==")
for fam in pkg.ttps:
print("---")
print("Title : " + fam.title)
print(... | or_types[0]))
print("ID -> : " + ind.indi | cated_ttps[0].item.idref)
for obs in ind.observables:
for digest in obs.object_.properties.hashes:
print("Hash : " + str(digest))
return 0
if __name__ == '__main__':
try:
fname = sys.argv[1]
except:
exit(1)
fd = open(fname)
stix_pkg = STIXPackag... |
JuBra/GEMEditor | GEMEditor/rw/test/test_compartment_rw.py | Python | gpl-3.0 | 2,169 | 0 | import lxml.etree as ET
from GEMEditor.model.classes.cobra import Model, Metabolite, Compartment
from GEMEditor.rw import *
from GEMEditor.rw.compartment import add_compartments, parse_compartments
from GEMEditor.rw.test.ex_compartment import valid_compartment_list
from lxml.etree import Element
def test_parse_compar... | ist is not None
compartment = compartment_list.find(sbml3_compartment)
assert compartment is not None
assert compartment.get("id") == "c"
assert compartment.get("name") == "Cytoplasm"
def test_add_compartments_defined_in_metabolite():
model = Model()
metabolite = Metabolite(id="test", compart... | ompartments(root, model)
compartment_list = root.find(sbml3_listOfCompartments)
assert compartment_list is not None
compartment = compartment_list.find(sbml3_compartment)
assert compartment is not None
assert compartment.get("id") == "c"
assert compartment.get("name") is None
def test_add_co... |
webmasterraj/FogOrNot | flask/lib/python2.7/site-packages/pandas/io/tests/test_cparser.py | Python | gpl-2.0 | 10,838 | 0.000185 | """
C/Cython ascii file parser tests
"""
from pandas.compat import StringIO, BytesIO, map
from datetime import datetime
from pandas import compat
import csv
import os
import sys
import re
import nose
from numpy import nan
import numpy as np
from pandas import DataFrame, Series, Index, isnull, MultiIndex
import pand... | from pandas.util.testing import (assert_almost_equal, | assert_frame_equal,
assert_series_equal, network)
import pandas.lib as lib
from pandas import compat
from pandas.lib import Timestamp
import pandas.util.testing as tm
from pandas.parser import TextReader
import pandas.parser as parser
class TestCParser(tm.TestCase):
def setUp(... |
coeusite/ShuffleIR | config.py | Python | gpl-2.0 | 1,373 | 0.017769 | # -*- coding: utf-8 -*-
# ShuffleIR的设置文件
#===============================================
# ShuffleMove的安装路径
pathShuffleMove | = '../../Shuffle-Move/'
# 当前关卡在ShuffleMove中的关卡ID
# 例如美梦天梯为 'SP_275', Mega超梦为'150'
# 注意要有英文单引号!
varStageID = 'SP_275'
# 支援精灵列表
# 格式为 listSupport = ('口袋妖怪的NationDex #',...)
# 注意要有英文单引号!
# 特殊的条目包括 空白'Air', 铁块'Metal', 木块'Wood', 金币'Coin'
# Mega 精灵请在Dex后加 -m, 例如Mega化石翼龙为 '142-m'
# 已支援图标列表请参考Supported_Icons.md
listSupport=[... | =True
# 铁块计数器
varMetalTimer=3
#===============================================
# 以下设置用于确定Miiverse截图选区
# 消消乐方块区域在窗口截图内部的相对坐标(x1, y1, x2, y2)
# 其中(x1, y1)为左上坐标,(x2, y2) 为右下坐标
#varBox = (46, 6, 274, 234) # Old 3DS XL
varBox = (38,376,494,832) # iPhone 6p + Airserver
#===============================================
# 以下... |
vbelakov/h2o | py/testdir_single_jvm/test_enum_multi_permission.py | Python | apache-2.0 | 6,221 | 0.009805 | import unittest, random, sys, time, os, stat, pwd, grp
sys.path.extend(['.','..','../..','py'])
import h2o, h2o_cmd, h2o_browse as h2b, h2o_import as h2i, h2o_exec as h2e
FILENUM=100
def write_syn_dataset(csvPathname, rowCount, colCount, SEED, translateList):
r1 = random.Random(SEED)
dsf = open(csvPathname, "... | # always have to re-import because source key is deleted by h2o
parseResult = h2i.import_parse(path=SYNDATASETS_DIR + '/*'+rowxcol+'*', schema='local',
exclude=None, header=1, timeoutSecs=timeoutSecs)
print "parseResult['destination_key']: " + parseResult['destination_key'... | pect(None, parseResult['destination_key'])
h2o_cmd.infoFromInspect(inspect, csvPathname)
print "write by owner, only, and parse"
os.chmod(badPathname, stat.S_IWRITE)
parseResult = h2i.import_parse(path=SYNDATASETS_DIR + '/*'+rowxcol+'*', schema='local',
e... |
mitodl/ccxcon | courses/fields_test.py | Python | agpl-3.0 | 3,535 | 0.001132 | """
Tests for Serializer Fields
"""
from django.core.exceptions import ImproperlyConfigured
from django.test import TestCase
import pytest
from rest_framework.serializers import ValidationError
from courses.factories import EdxAuthorFactory, CourseFactory
from courses.models import EdxAuthor
from courses.serializers i... | e=no-self-use
"""model-to-string returns correct strings"""
e1 = EdxAuthorFactory.create()
e2 = EdxAuthorFactory.create()
| co = CourseFactory.create()
co.instructors.add(e1)
co.instructors.add(e2)
f = SMMF(model=EdxAuthor, lookup='edx_uid')
assert sorted([str(e1), str(e2)]) == sorted(f.to_representation(co.instructors))
def test_returns_model_if_string_provided(self): # pylint: disable=no-self-use
... |
jackchi/interview-prep | sorting/bubbleSort.py | Python | mit | 738 | 0.023035 | #! /usr/bin/python
# https://github.com/jackchi/interview-prep
import random
# Bubble Sort
# randomly generate 10 integers from (-100, 100)
arr = [random.randrange(-100,100) for i in range(10)]
print('original %s' % arr)
def bubbleSort(array):
n = len(array)
# traverse thru all elements
for i in range(n):
s... | ], array[j]
swapped = True
# IF no two elements were swapped
# by in | ner loop, then break
if swapped == False:
break
return array
a = bubbleSort(arr)
print(f"sorted {a}")
|
pixmeter/enma | enma/rest/__init__.py | Python | bsd-3-clause | 131 | 0.015267 | from flask im | port Blueprint
api = Blueprint('api', __name__, url_prefix='/rest/v1.0')
from . import | authentication, errors, views |
autotest/virt-test | virttest/utils_config.py | Python | gpl-2.0 | 13,647 | 0 | import ast
import logging
import os.path
import ConfigParser
import StringIO
class ConfigError(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class ConfigNoOptionError(ConfigError):
def __init__(self, option, path):
self.option = option
... | f'] = 'test'
| ... print config
... finally:
... config.restore()
Example script using `with` statement:
>>> from virttest import utils_config
>>> with utils_config.SectionlessConfig('test.conf') as config:
... print len(config)
... print config
... print config['a']
... ... |
alephu5/Soundbyte | environment/lib/python3.3/site-packages/sympy/simplify/fu.py | Python | gpl-3.0 | 63,469 | 0.000394 | """
Implementation of the trigsimp algorithm by Fu et al.
The idea behind the ``fu`` algorithm is to use a sequence of rules, applied
in what is heuristically known to be a smart order, to select a simpler
expression that is equivalent to the input.
There are transform rules in which a single rule is applied to the
e... | implify, powsimp, ratsimp, combsimp,
_mexpand, bottom_up)
from sympy.core.sympify import sympify
from sympy.functions.elementary.trigonometric import (
cos, sin, tan, cot, sec, csc, sqrt)
from sympy.functions.elementary.hyperbolic import cosh, sinh, tanh, coth
from sympy.core.compatibility import ordered
from s... | mbol import Dummy
from sympy.core.exprtools import Factors, gcd_terms
from sympy.core.rules import Transform
from sympy.core.basic import S
from sympy.core.numbers import Integer, pi, I
from sympy.strategies.tree import greedy
from sympy.strategies.core import identity, debug
from sympy.polys.polytools import factor
fr... |
sserrot/champion_relationships | venv/Lib/site-packages/networkx/algorithms/isomorphism/isomorph.py | Python | mit | 6,757 | 0 | """
Graph isomorphism functions.
"""
import networkx as nx
from networkx.exception import NetworkXError
__author__ = """\n""".join(['Aric Hagberg ([email protected])',
'Pieter Swart ([email protected])',
'Christopher Ellison [email protected])'])
# Copyright... | ue does NOT guarantee isomorphism.
Parameters
----------
G1, G2 : graphs
The two graphs G1 and G2 must be the same type.
| Notes
-----
Checks for matching degree sequences.
"""
# Check global properties
if G1.order() != G2.order():
return False
# Check local properties
d1 = sorted(d for n, d in G1.degree())
d2 = sorted(d for n, d in G2.degree())
if d1 != d2:
return False
# OK...
... |
mainconceptx/DAS | contrib/spendfrom/spendfrom.py | Python | mit | 9,887 | 0.005664 | #!/usr/bin/env python
#
# Use the raw transactions API to spend dass received on particular addresses,
# and send any change back to that same address.
#
# Example usage:
# spendfrom.py # Lists available funds
# spendfrom.py --from=ADDRESS --to=ADDRESS --amount=11.00
#
# Assumes it will talk to a dasd or Das-Qt runn... | 1)
txdata = signed_rawtx["hex"]
return txdata
def compute_amount_in(dasd, txinfo):
result = Decimal("0.0")
for vin in txinfo['vin']:
in_info = dasd.getrawtransaction(vin['txid'], 1)
vout = in_info['vout'][vin['vout']]
result = result + vout['value']
return result
de | f compute_amount_out(txinfo):
result = Decimal("0.0")
for vout in txinfo['vout']:
result = result + vout['value']
return result
def sanity_test_fee(dasd, txdata_hex, max_fee):
class FeeError(RuntimeError):
pass
try:
txinfo = dasd.decoderawtransaction(txdata_hex)
tota... |
quattor/aquilon | lib/aquilon/worker/commands/show_resource.py | Python | apache-2.0 | 2,445 | 0 | # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2008-2015,2018 Contributor
#
# 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... | group":
resourcegroup = kwargs.pop("resourcegroup", None)
else:
resourcegroup = None
q = session.query(self.resource_class)
who = None
if not all:
if self.resource_name:
name = kwargs.get(self.resource_name)
else:
... | ame:
q = q.filter_by(name=name)
if hostname or cluster or resourcegroup or personality or \
archetype or grn or eon_id:
who = get_resource_holder(session, logger, hostname, cluster,
metacluster, resourcegroup,
... |
denkab/FrameworkBenchmarks | frameworks/PHP/hhvm/setup.py | Python | bsd-3-clause | 1,384 | 0.020954 |
import subprocess
import setup_util
import os
def start(args, logfile, errfile):
setup_util.replace_text("hhvm/once.php.inc", "host=localhost;", "host=" + args.database_host + ";")
setup_util.replace_text("hhvm/deploy/config.hdf", "SourceRoot = .*\/FrameworkBenchmarks/hhvm", "SourceRoot = " + args.troot)
setup_... | oy/config.hdf", "Path = .*\/.hhvm.hhbc", "Path = " + args.troot + "/.hhvm.bbhc")
setup_util.replace_text("hhvm/deploy/config.hdf", "PidFile = .*\/hhvm.pid", "PidFile = " + args.troot + "/hhvm.pid")
setup_util.replace_text("hhvm/deploy/config.hdf", "File = .*\/error.log", "File = " + args.troot + "/error.log")
tr... | =True, stderr=errfile, stdout=logfile)
return 0
except subprocess.CalledProcessError:
return 1
def stop(logfile, errfile):
try:
if os.name == 'nt':
# Not Supported !
return 0
p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE)
out, err = p.communicate()
for line in out.sp... |
sserkez/ocelot | demos/sr/k_diode.py | Python | gpl-3.0 | 2,071 | 0.011106 | __author__ = 'Sergey Tomin'
from ocelot.rad import *
from ocelot import *
from ocelot.gui import *
import numpy as np
import time
font = {'size' : 14}
matplotlib.rc('font', **font)
#from scipy.optimize import curve_fit
from ocelot.demos.sr.k_analysis import *
#from ocelot.lib.genera.src.python.radiation import gener... | _scan_points)
for | i in range(n_shots):
beam.E = np.random.normal(beam_energy, beam_energy*b_energy_jit, 1)
print("beam energy: ", beam.E)
screen.start_energy = eph # 8078.2 - 50 + i*100/30. #eV
screen.num_energy = 1
screen = calculate_radiation(lat, screen, beam)
flux.append(sum(screen.Tot... |
ibabushkin/Iridium | defines/util/tree.py | Python | gpl-3.0 | 1,538 | 0 | """
File: tree.py
Author: Inokentiy Babushkin
Email: [email protected]
Github: ibabushkin
Description:
A tree used to store DFS-trees for the CFG-module.
"""
class Tree(object):
"""
The tree mentioned in the module-docstring.
Probably a Gingko.
"""
def __init__(self, obj):
... | nt_node = len(self.nodes) - 1
# print self.c | urrent_node
def get_children_of(self, index):
"""
Get a node's children.
"""
ret = []
for edge in self.edges:
if edge[0] == index:
ret.append(edge[1])
return ret
def postorder(self, start=0):
"""
Get the postorder trav... |
bobbysoon/Taxi3 | Swarm.py | Python | unlicense | 1,110 | 0.062162 | from Centroid import Centroid
from Vec2 import Vec2
from random import random
from math import *
from angle import angle
from Seed import *
Seed()
class Swarm(list):
def __init__(self, count):
self.speed= 1.0/16.0
self.paused= False
def __new__(cls, count):
swarm= list.__new__(cls)
for n in range(count):... | [i].inertia+= push
self[j].inertia-= push
def move(self, step):
if self.paused: return |
self.repel(step)
step*= self.speed
for c in self:
c+= c.inertia*step
if abs(c.x)>=1:
c.inertia.x*=-1
c.x+=c.inertia.x*2*step
if abs(c.y)>=1:
c.inertia.y*=-1
c.y+=c.inertia.y*2*step
c.clear()
|
bashalex/datapot | setup.py | Python | gpl-3.0 | 1,582 | 0.001896 | #!/usr/bin/env python
import os
from setuptools import setup, find_packages
CURRENT_DIR = os.path.dirname(__file__)
setup(name='datapot',
description='Library for automatic feature extraction from JSON-datasets',
long_description=open(os.path.join(CURRENT_DIR, 'README.rst')).read(),
version='0.1.3'... | 'langdetect >= 1.0.7',
'gensim >= 2.1.0',
'nltk >= 3.2.4',
'tsfresh >= 0.7.1',
'python-dateutil >= 2.6.0',
'fastnumbers >= 2.0.1',
'pystemmer >= 1.3.0',
],
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Appr... | gramming Language :: Python :: 3',
'Programming Language :: Python :: 2',
'Intended Audience :: Science/Research',
'Intended Audience :: Developers',
'Topic :: Scientific/Engineering',
'Topic :: Software Development',
],
packages=find_packages())
|
antoinecarme/pyaf | tests/artificial/transf_Quantization/trend_PolyTrend/cycle_5/ar_12/test_artificial_1024_Quantization_PolyTrend_5_12_100.py | Python | bsd-3-clause | 270 | 0.085185 | import pyaf.Bench.TS_datasets as tsds
im | port tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 1024 , FREQ = 'D', seed = 0, trendtype = "PolyTrend", cycle_length = 5, transform = "Quantization", sigma | = 0.0, exog_count = 100, ar_order = 12); |
threefoldfoundation/app_backend | plugins/tff_backend/migrations/_009_change_token_value.py | Python | bsd-3-clause | 1,840 | 0.002174 | # -*- coding: utf-8 -*-
# Copyright 2018 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... | s.query(): # type: GlobalStats
new_value = stats_model.value / 100
currencies = _get_currency_conversions(stats_model.currencies, | new_value)
stats_model.populate(currencies=currencies, value=new_value)
stats_model.put()
coords = [2, 1, 0]
icon_name = 'fa-suitcase'
label = 'Purchase iTokens'
flow = BUY_TOKENS_FLOW_V5
api_key = get_tf_token_api_key()
roles = system.list_roles(api_key)
menu_item_roles = []... |
mbsat/gr-poes-weather | apps/FY1/gui/usrp_rx_fy1_bb_hrpt.py | Python | gpl-3.0 | 19,883 | 0.024342 | #!/usr/bin/env python
##################################################
# Gnuradio Python Flow Graph
# Title: USRP Feng Yun 1 HRPT Receiver
# Author: POES Weather Ltd
# Description: Feng Yun 1 HRPT Receiver
# Generated: Fri Jan 7 15:21:35 2011
##################################################
from gnuradio import e... | 0, 1, 1)
self._datetime_text_static_text = forms.static_text(
parent=self.displays.GetPage(1).GetWin(),
value=self.datetime_text,
callback=self.set_datetime_text,
label="Acquisition start",
converter=forms.str_converter(),
)
self.displays.GetPage(1).GridAdd(self._datetime_text_static_text, 2, 0, 1,... | )
self._clock_alpha_text_box = forms.text_box(
parent=self.GetWin(),
sizer=_clock_alpha_sizer,
value=self.clock_alpha,
callback=self.set_clock_alpha,
label="Clock alpha",
converter=forms.float_converter(),
proportion=0,
)
self._clock_alpha_slider = forms.slider(
parent=self.GetWin(),
si... |
aek/pgbouncer-ng | pgbouncerlib/__init__.py | Python | bsd-3-clause | 36 | 0 | __version__ | = (1, 0, 0, 'final | ', 0)
|
RuiNascimento/krepo | script.module.lambdascrapers/lib/lambdascrapers/sources_incursion/en_incursion-1.20(final)/ymovies.py | Python | gpl-2.0 | 11,750 | 0.007064 | # -*- coding: utf-8 -*-
'''
Covenant Add-on
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This prog... | link = json.loads(link)['src']
valid, host = source_utils.is_host_valid(link, hostDict)
sources.append({'source':host,'quality':quality,'language': 'en','url':link,'info':[],'direct':False,'debridonly':False})
... | nk % (eid[0], mid))
script = client. |
Extintor/DjangoBlog | blog/admin.py | Python | gpl-2.0 | 129 | 0 | from | django.contrib import admin
from blog.models import Blog_post
admin.site.register(Blog_post)
# Register your models | here.
|
FlipperPA/pyodbc | tests2/sqlservertests.py | Python | mit | 54,094 | 0.003605 | #!/usr/bin/python
# -*- coding: latin-1 -*-
usage = """\
usage: %prog [options] connection_string
Unit tests for SQL Server. To use, pass a connection string as the parameter.
The tests will create and drop tables t1 and t2 as necessary.
These run using the version from the 'build' directory, not the version
instal... | ue)
def test_guid(self):
| self.cursor.execute("create table t1(g1 uniqueidentifier)")
self.cursor.execute("insert into t1 values (newid())")
v = self.cursor.execute("select * from t1").fetchone()[0]
self.assertEqual(type(v), str)
self.assertEqual(len(v), 36)
def test_nextset(self):
self.cursor.exe... |
utkbansal/tardis | setup.py | Python | bsd-3-clause | 4,442 | 0.002701 | #!/usr/bin/env python
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import glob
import os
import sys
import ah_bootstrap
from setuptools import setup
#A dirty hack to get around some early import/configurations ambiguities
if sys.version_info[0] >= 3:
import builtins
else:
import __builtin_... | nds(PACKAGENAME, VERSION, RELEASE)
add_command_option('install', 'with-openmp', 'compile TARDIS without OpenMP',
is_bool=True)
add_command_option('build', 'with-openmp', 'compile TARDIS without OpenMP',
is_bool=True)
add_command_option('develop', 'with-openmp', 'compile TARDIS with... | is platform is to use a
# broken one.
adjust_compiler(PACKAGENAME)
# Freeze build information in version.py
generate_version_py(PACKAGENAME, VERSION, RELEASE,
get_debug_option(PACKAGENAME))
# Treat everything in scripts except README.rst as a script to be installed
scripts = [fname for fname in gl... |
jorisvandenbossche/DS-python-data-analysis | notebooks/python_recap/_solutions/05-numpy35.py | Python | bsd-3-clause | 14 | 0.071429 | n | p.identi | ty(3) |
kylef/swiftenv-api | versions.py | Python | bsd-2-clause | 4,108 | 0.001217 | import os
import glob
from pathlib import Path
import flask
import yaml
class VersionManager(object):
def __init__(self, versions=None):
self._versions = versions
@property
def versions(self):
if self._versions is None:
version_paths = Path('versions').glob('**/*.yaml')
... | e,
}
| else:
binaries[key] = value
if 'version' in content:
version = content['version']
return cls(version, binaries)
def __init__(self, version, binaries):
self.version = version
self.binaries = binaries
def __str__(self):
return se... |
Integral-Technology-Solutions/ConfigNOW | Lib/xml/sax/saxutils.py | Python | mit | 20,106 | 0.006864 | """
A library of useful helper classes to the saxlib classes, for the
convenience of application and driver writers.
$Id: saxutils.py,v 1.19 2001/03/20 07:19:46 loewis Exp $
"""
import types, sys, urllib, urlparse, os, string
import handler, _exceptions, xmlreader
try:
_StringTypes = [types.StringType, types.Uni... | elf._out.write('<' + name)
for (name, value) in attrs.items():
self._out.write(' %s="%s"' % (name, escape(value)))
self._out.write('>')
def endElement(self, name):
self._out.write('</%s>' % name)
def startElementNS(self, name, qname, attrs):
if name[0] is None:
... | [0]] is None:
# default namespace
name = name[1]
else:
name = self._current_context[name[0]] + ":" + name[1]
self._out.write('<' + name)
for k,v in self._undeclared_ns_maps:
if k is None:
self._out.write(' xmlns="%s"' % v)
... |
TonyThompson/fail2ban-patch | fail2ban/server/transmitter.py | Python | gpl-2.0 | 10,359 | 0.03147 | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: t -*-
# vi: set ft=python sts=4 ts=4 sw=4 noet :
# This file is part of Fail2Ban.
#
# Fail2Ban 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;... | n":
value = command[2]
self.__server.setDatePattern(name, value)
return self.__server.getDatePattern(name)
elif command[1] == "maxretry":
value = command[2]
self.__server.setMaxRetry(name, int(value))
return self.__server.getMaxRetry(name)
elif command[1] == "maxlines":
value = command[2]
se... | MaxLines(name, int(value))
return self.__server.getMaxLines(name)
# command
elif command[1] == "bantime":
value = command[2]
self.__server.setBanTime(name, int(value))
return self.__server.getBanTime(name)
elif command[1] == "banip":
value = command[2]
return self.__server.setBanIP(name,value)
... |
Taapat/enigma2-openpli-vuplus | lib/python/Components/ResourceManager.py | Python | gpl-2.0 | 529 | 0.032136 | class ResourceManager:
def __init__(self):
self.resourceList = {}
def addResource(self, name, resource):
print "adding Resource", name
self.resourceList[name] = resource
print "resources:", self.resourceList
def getResource(self, name) | :
if not self.hasResource(name):
return None
return self.resourceList[n | ame]
def hasResource(self, name):
return name in self.resourceList
def removeResource(self, name):
if self.hasResource(name):
del self.resourceList[name]
resourcemanager = ResourceManager()
|
walterbender/turtle3D | plugins/audio_sensors/ringbuffer.py | Python | mit | 4,149 | 0.000241 | # Copyright (C) 2009, Benjamin Berg, Sebastian Berg
# Copyright (C) 2010, Walter Bender
#
# 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
# ... | alues will
give the newest added information from the buffer. (in normal order)
Before the buffer | is filled once: This returns just None
"""
return np.array([])
def _read(self, number=None, step=1):
"""Read the ring Buffer. Number can be positive or negative.
Positive values will give the latest information, negative values will
give the newest added information from th... |
mldbai/mldb | testing/MLDB-2100_fetcher_timeout_test.py | Python | apache-2.0 | 1,628 | 0.003686 | #
# MLDB-2100_fetcher_timeout_test.py
# Francois-Michel L'Heureux, 2016-11-20
# This file is part of MLDB. Copyright 2016 mldb.ai inc. All rights reserved.
#
import socket
import threading
import time
class MyThread(threading.Thread):
def run(self):
try:
threading.Thread.run(self)
excep... | eption as xxx_todo_changeme:
self.err = xxx_todo_changeme
pass
else:
self.err = None
# tim | eout in case MLDB fails to connect to the socket, the test won't hang
socket.setdefaulttimeout(10)
from mldb import mldb
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('127.0.0.1', 0))
serversocket.listen(1)
port_num = serversocket.getsockname()[1]
keep_going = threading.Event()... |
lmazuel/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_08_01/models/packet_capture_result_paged.py | Python | mit | 987 | 0.001013 | # 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.
# --------------------------------------------------------------------------
from msrest.paging import Paged
class PacketCaptureResultPaged(Paged):
"""
A paging container for iterating over a list of :class:`PacketCaptureResult <azure.mgmt.network.v2017_08_01.models.Pac... |
longmazhanfeng/interface_web | interface_platform/management/interfacerunner.py | Python | mit | 2,680 | 0.000856 | # -*- coding: UTF-8 -*-
from ..model.interfacebuilder import InterfaceBuilder
from ..models import ITLog, ITStatement
import interface_pl | atform.settings as settings
import logging.config
import os
from datetime import datetime
# 运行接口
# 传入it_id和验证数据
class InterfaceRunner(object):
def __init__(self, it_id):
print "InterfaceRunner.__init__()"
self._it = ITStatement.objects.get(id=it_id)
self._log_name = str(datetime.now()) + "... | lder = InterfaceBuilder(self._it, self._logger)
@property
def interfacebuilder(self):
return self._interfacebuilder
@property
def logger(self):
return self._logger
@property
def interface(self):
return self._interface
# 执行之后返回执行结果:失败、通过、未执行
def runner(self):
... |
dwitvliet/CATMAID | django/applications/catmaid/control/exportneuroml.py | Python | gpl-3.0 | 3,874 | 0.003356 | # A file to contain exclusively dependencies of the NeuroML package.
# See:
# https://github.com/NeuralEnsemble/libNeuroML
# http://neuroml.org
from __future__ import print_function
from collections import defaultdict
try:
from neuroml import Cell, Segment, SegmentParent, Morphology, \
NeuroMLD... | segments=parent.id) if parent else None
for childID in children:
p2 = asPoint(childID)
segment_id += | 1
segment = Segment(proximal=p1, distal=p2, parent=segment_parent)
segment.id = segment_id
segment.name = "%s-%s" % (nodeID, childID)
segments.append(segment)
todo.append(childID)
# Pack the segments into a Cell
morphology = Morphology()
morpholog... |
helenst/django | django/db/models/base.py | Python | bsd-3-clause | 66,310 | 0.001508 | from __future__ import unicode_literals
import copy
import inspect
import sys
import warnings
from django.apps import apps
from django.apps.config import MODELS_MODULE_NAME
from django.conf import settings
from django.core import checks
from django.core.exceptions import (ObjectDoesNotExist,
MultipleObjectsReturn... | attached_to=new_class))
if base_meta and not base_meta.abstract:
# Non-abstract child classes inherit some attrib | utes from their
# non-abstract parent (unless an ABC comes before it in the
# method resolution order).
if not hasattr(meta, 'ordering'):
new_class._meta.ordering = base_meta.ordering
if not hasattr(meta, 'get_latest_by'):
... |
nhejazi/project-gamma | code/project_config.py | Python | bsd-3-clause | 562 | 0.007117 | """
Convenient way to expose filepaths to scripts. Also, important
constants are centralized here to avoid m | ultiple copies.
"""
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
sys.path.append(os.path.join(os.path.dirname(__file__)))
sys.path.append(os.path.join(os.path.dirname(__file__), 'utils'))
sys.path.append(os.path.join(os.path.dirname(__file__), 'utils', 'tests'))
TR = 2.5
#we choose cu... | nspecting the histogram of data values of the standard mni brain
MNI_CUTOFF = 5000
MIN_STD_SHAPE = (91, 109, 91) |
razzius/sqlalchemy-migrate | migrate/tests/versioning/test_script.py | Python | mit | 9,323 | 0.002789 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import shutil
from migrate import exceptions
from migrate.versioning import version, repository
from migrate.versioning.script import *
from migrate.versioning.util import *
from migrate.tests import fixture
from migrate.tests.fixture.models import t... | it again: it already exists
self.assertRaises(exceptions.PathFoundError,self.cls.create,path)
@fixture.usedb(supported='sqlite')
def test_run(self):
script_path = self.tmp_py()
pyscript = PythonScript.cr | eate(script_path)
pyscript.run(self.engine, 1)
pyscript.run(self.engine, -1)
self.assertRaises(exceptions.ScriptError, pyscript.run, self.engine, 0)
self.assertRaises(exceptions.ScriptError, pyscript._func, 'foobar')
# clean pyc file
os.remove(script_path + 'c')
... |
joetainment/mmmmtools | MmmmToolsMod/script_file_runner_scripts/hand_auto_rigging.py | Python | gpl-3.0 | 5,762 | 0.020305 | import maya.cmds as cmds
import pymel.all as pm
import traceback
controlCurve = pm.PyNode('control_curve')
## to make a numerical 'floating point'
## attribute, we use at='double', keyable=True
controlCurve.addAttr( 'allCurl', at='double', keyable=True )
controlCurve.addAttr( 'pointerAllCurl', at='double', keyable... | inkyBCurl >> target.input1D[num]
target = adds[ 'pinky_c' + 'Z' ]
num = target.input1D.getNumElements()
controlCurve.pinkyCCurl >> target.input1D[num]
## allCurl connections
target = adds[ 'pointer_a' + 'Z' ]
num = target.input1D.getNumElements()
controlCurve.allCurl >> target.input1D[num]
target = adds[ 'pointer_b... | arget.input1D[num]
target = adds[ 'middle_a' + 'Z' ]
num = target.input1D.getNumElements()
controlCurve.allCurl >> target.input1D[num]
target = adds[ 'middle_b' + 'Z' ]
num = target.input1D.getNumElements()
controlCurve.allCurl >> target.input1D[num]
target = adds[ 'middle_c' + 'Z' ]
num = target.input1D.getNumElements... |
ebilionis/py-best | best/inverse/_inverse_problem.py | Python | lgpl-3.0 | 4,531 | 0.002207 | """Define the InverseProblem class.
Author:
Ilias Bilionis
Date:
1/14/2013
1/21/2013
"""
__all__ = ['InverseProblem']
import numpy as np
import itertools
from ..random import StudentTLikelihoodFunction
from ..random import RandomWalkProposal
from ..random import SequentialMonteCarlo
class InversePro... | mean_function=solver,
cov=(beta / alpha))
self._smc = SequentialMonteCarlo(prior=prior, likelihood=likelihood,
verbose=verbose, num_particles=num_particles,
num_mcmc=num_mcmc, p... | mediate_samples,
mpi=mpi, comm=comm)
def solve(self):
"""Solve the inverse problem."""
r, w = self.smc.sample()
self._r = r
self._w = w
idf = lambda(x): x
self._mean = self.mean_of(idf)
self._variance = self.variance_o... |
luotao1/Paddle | python/paddle/fluid/incubate/fleet/parameter_server/ir/ps_dispatcher.py | Python | apache-2.0 | 3,500 | 0.000286 | # Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | Distribute variables to several endpoints using
RondRobin<https://en.wikipedia.org/wiki/Round-robin_scheduling> method.
Args:
pserver_endpoints (list): list of endpoint(ip:port).
Examples:
.. code-block:: python
pserver_endpoints = ["127.0.0.1:6007", "127.0.0.1:6008"]
va... | rr = RoundRobin(pserver_endpoints)
rr.dispatch(vars)
"""
def __init__(self, pserver_endpoints):
super(RoundRobin, self).__init__(pserver_endpoints)
def dispatch(self, varlist):
"""
use `RoundRobin` method to dispatch variables with each parameter server.
Args:... |
lonnen/socorro | webapp-django/crashstats/crashstats/migrations/0001_initial.py | Python | mpl-2.0 | 369 | 0 | # Generated by Django 1.11.15 on 2018-09-25 15:40
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the M | PL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from django.db import migrations
class Migration(migrations.Migration):
dependencie | s = []
operations = []
|
crast/grpc | tools/run_tests/run_interops.py | Python | bsd-3-clause | 1,163 | 0.009458 | import argparse
import xml.etree.cElementTree as ET
import jobset
argp = argparse.ArgumentParser(description='Run interop tests.')
argp.add_argument('-l', '--language',
default='c++')
args = argp.parse_args()
# build job
build_job = jobset.JobSpec(cmdline=['tools/run_tests/run_interops_build.sh', '%... | '%s' % test],
shortname=test,
timeout_seconds=15*60)
jobs.append(test_job)
jobNumber+=1
root = ET.Element('testsuites')
testsuite = ET.SubElement(root, 'testsuite', id='1', package='grpc', name='tests')
# always do the build of docker first, and then all the tests can run in parallel
jobset.run(... | s=jobNumber, xml_report=testsuite)
tree = ET.ElementTree(root)
tree.write('report.xml', encoding='UTF-8')
|
datacommonsorg/data | scripts/ourworldindata/covid19/preprocess_csv_test.py | Python | apache-2.0 | 2,497 | 0 | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | ata/expected_covid19.tmcf')
result_tmcf_file = os.path.join(tmp_dir,
'OurWorldInData_Covid19.tmcf')
create_tmcf_file(result_tmcf_file)
with open(result_tmcf_file, "r") as result_f:
| result_str: str = result_f.read()
with open(expected_tmcf_file, "r") as expect_f:
expect_str: str = expect_f.read()
self.assertEqual(result_str, expect_str)
os.remove(result_tmcf_file)
if __name__ == '__main__':
unittest.main()
|
dkamotsky/program-y | src/test/parser/test_aiml_parser.py | Python | mit | 30,276 | 0.000727 | import unittest
import os
from xml.etree.ElementTree import ParseError
from programy.parser.aiml_parser import AIMLParser
from programy.parser.exceptions import ParserException
from programy.parser.pattern.nodes.root import PatternRootNode
from programy.parser.pattern.nodes.topic import PatternTopicNode
from programy.... | rom_text(
"""<?xml version="1.0" encoding="UTF-8"?>
<aiml>
<category>
<topic></topic>
<pattern>*</pattern>
<template>RESPONSE</template>
</category>
</aiml>
... | """)
self.assertEqual(raised.exception.message, "Topic node text is empty")
def test_base_aiml_that_empty_child_node(self):
with self.assertRaises(ParserException) as raised:
|
ujvl/ray-ng | python/ray/reporter.py | Python | apache-2.0 | 6,847 | 0 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import logging
import json
import os
import traceback
import time
import datetime
from socket import AddressFamily
try:
import psutil
except ImportError:
print("The reporter requires ps... | se.ArgumentParser(
description=("Parse Redis server for the "
"reporter to connect to."))
parser.add_argument(
"--redis-address",
required=True,
type=str,
help="The address to use for Redis.")
parser.add_argument(
"--redis-password",
r... | =str,
default=None,
help="the password to use for Redis")
parser.add_argument(
"--logging-level",
required=False,
type=str,
default=ray_constants.LOGGER_LEVEL,
choices=ray_constants.LOGGER_LEVEL_CHOICES,
help=ray_constants.LOGGER_LEVEL_HELP)
parser... |
mikel-egana-aranguren/SADI-Galaxy-Docker | galaxy-dist/eggs/bx_python-0.7.2-py2.7-linux-x86_64-ucs4.egg/bx/_seqmapping.py | Python | gpl-3.0 | 281 | 0.035587 | def __bootstrap__():
global __bootstrap__, __loader__, __file__
import sys, pkg_resources, imp
__file__ = pkg_resour | ces.resource_filename(__name__,'_seqmapping.so')
__loader__ = None; del __bootstrap__, __loader__
| imp.load_dynamic(__name__,__file__)
__bootstrap__()
|
terzeron/FeedMakerApplications | study/_javabeat/capture_item_link_title.py | Python | gpl-2.0 | 791 | 0.001264 | #!/usr/bin/env python
import sys
import re
import getopt
from typing import List, Tuple
from feed_maker_util import IO
def main():
num_of_recent_feeds = 1000
optlist, _ = getopt.getopt(sys.argv[1:], " | n:")
for o, a in optlist:
if o == '-n':
num_of_recent_feeds = int(a)
line_list = IO.read_stdin_as_line_list()
result_list: List[Tuple[str, str]] = []
for line in line_list:
m = re.search(r'a href="(?P<link>[^"]+)"[^>]*title="(?P<title>[^"]+)"', line)
if m:
... | nk, title) in result_list[:num_of_recent_feeds]:
print("%s\t%s" % (link, title))
if __name__ == "__main__":
sys.exit(main())
|
kinsights/brabeion | brabeion/tests/tests.py | Python | bsd-3-clause | 2,258 | 0.001329 | from django.conf import settings
from django.contrib.auth.models import User
from django.db import connection
from django.test import TestCase
from brabeion import badges
from brabeion.base import Badge, BadgeAwarded
from brabeion.tests.models import PlayerStat
class PointsBadge(Badge):
slug = "points"
level... | "Silver",
"Gold",
]
events = [
"points_awarded",
]
multiple = False
def award(self, **state):
user = state["user"]
points = user.stats.points
if points > 10000:
return BadgeAwarded(3)
elif points > 7500:
return BadgeAwarded(2)... | :
current_debug = settings.DEBUG
settings.DEBUG = True
current = len(connection.queries)
func()
self.assertEqual(current + n, len(connection.queries), connection.queries[current:])
settings.DEBUG = current_debug
class BadgesTests(BaseTestCase):
def test_award(self):... |
petervanderdoes/wger | wger/core/tests/test_repetition_unit.py | Python | agpl-3.0 | 3,162 | 0.000316 | # This file is part of wger Workout Manager.
#
# wger Workout Manager 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 your option) any later version.
#
# wger W... | should have received a copy of the GNU Affero General Public License
# along with Workout Manager. If not, see <http://w | ww.gnu.org/licenses/>.
# wger
from wger.core.models import RepetitionUnit
from wger.core.tests import api_base_test
from wger.core.tests.base_testcase import (
WorkoutManagerAccessTestCase,
WorkoutManagerAddTestCase,
WorkoutManagerDeleteTestCase,
WorkoutManagerEditTestCase,
WorkoutManagerTestCase
)... |
ibamacsr/routes_registry_api | routes_registry_api/routes/management/commands/importstates.py | Python | agpl-3.0 | 1,055 | 0.002844 | # -*- coding: utf-8 -*-
import simplejson
from django.core.managemen | t.base import BaseCommand
from django.contrib.gis.geos import MultiPolygon, Polygon
from ...models import State
class Command(BaseCommand):
args = 'filename'
help = 'Import states from a GeoJSON file'
def handle(self, *args, **options):
for filename in args:
data_json = open(filename... | me'),
code=feature['properties'].get('code'),
)
if feature['geometry'].get('type') == 'MultiPolygon':
state.geom = MultiPolygon(
[Polygon(poly) for poly in feature['geometry'].get('coordinates')[0]]
... |
boada/desCluster | mkTargeted/legacy/targetedRealistic_async.py | Python | mit | 4,107 | 0.006331 | from multiprocessing import Pool
import h5py as hdf
import numpy as np
from calc_cluster_props import *
from data_handler import mkTruth, mkHalo
import os
import sys
class AsyncFactory:
def __init__(self, func, cb_func):
self.func = func
self.cb_func = cb_func
self.pool = Pool()
def ca... | s(data['LOSV']) < 5000
data = data[mask]
while True:
try:
if size == data.size:
break
except NameError:
pass
size = data.size
# | print 'size', data.size
#data = rejectInterlopers(data)
try:
x = shifty_gapper(data['SEP'], data['Z'], tZ, ngap=15, glimit=500)
data = data[x]
except:
break
#data = findLOSVD(data)
data = findLOSVDgmm(data)
data['LOSVD'] = data['LOSVDg... |
google/material-design-icons | update/venv/lib/python3.9/site-packages/fontTools/ttLib/tables/T_S_I_V_.py | Python | apache-2.0 | 572 | 0.026224 | from fontTools.misc.py23 import strjoin, tobytes, tostr
from . import | asciiTable
class table_T_S_I_V_(asciiTable.asciiTable):
def toXML(self | , writer, ttFont):
data = tostr(self.data)
# removing null bytes. XXX needed??
data = data.split('\0')
data = strjoin(data)
writer.begintag("source")
writer.newline()
writer.write_noindent(data.replace("\r", "\n"))
writer.newline()
writer.endtag("source")
writer.newline()
def fromXML(self, name, a... |
dims/nova | nova/objects/request_spec.py | Python | apache-2.0 | 22,987 | 0.000131 | # Copyright 2015 Red Hat, 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 a... | # NOTE(sbauza): ... but there are some cas | es where request_spec
# has an instance key as a dictionary, just because
# select_destinations() is getting a request_spec dict made by
# sched_utils.build_request_spec()
# TODO(sbauza): To be removed once all RequestSpec hydrations are
# done on the conducto... |
klen/simpletree | benchmark/main/tests.py | Python | bsd-3-clause | 3,596 | 0.000278 | from django.test import TestCase
import time
from .models import SimpleTree, MPTTTree, TBMP, TBNS
def timeit(method):
| """ Measure time of method's execution.
"""
def timed(*args, **kw):
ts = time.time()
result = method(*args, **kw)
te = time.time()
print '\n%r: %2.2f sec' % \
(method.__name__, te - ts)
return result
return timed
CYCLES = 8
class Benchmark(object)... | it
def test_deletion():
for _ in xrange(pow(2, CYCLES) / 2):
self._delete_last()
test_deletion()
def test_get(self):
self._create_tree(cycles=7)
@timeit
def test_get_tree():
root = self._get_root()
for _ in xrange(100):
... |
hellotomfan/v8-coroutine | deps/v8/tools/push-to-trunk/releases.py | Python | gpl-2.0 | 18,090 | 0.007573 | #!/usr/bin/env python
# Copyright 2014 the V8 project authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# This script retrieves the history of all V8 branches and trunk revisions and
# their corresponding Chromium revisions.
# Requires ... | leases-tempfile",
}
# Expression for retrieving the bleeding edge revision from a commit message.
PUSH_MSG_SVN_RE = re.compile(r".* \(based | on bleeding_edge revision r(\d+)\)$")
PUSH_MSG_GIT_RE = re.compile(r".* \(based on ([a-fA-F0-9]+)\)$")
# Expression for retrieving the merged patches from a merge commit message
# (old and new format).
MERGE_MESSAGE_RE = re.compile(r"^.*[M|m]erged (.+)(\)| into).*$", re.M)
CHERRY_PICK_TITLE_GIT_RE = re.compile(r"^.*... |
bmi-forum/bmi-pyre | pythia-0.8/examples/tabulator/tabulator/Quadratic.py | Python | gpl-2.0 | 1,399 | 0.005004 | #!/usr/bin/env python
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Michael A.G. Aivazis
# California Institute of Technology
# (C) 1998-2005 All Rights Reserved
#
# <LicenseText>
#
# ~~~~~~~~~~~~~~~~~~~~~~~~... | rt pyre.inventory
a = pyre.inventory.float("a", default=0.0)
b = pyre.inventory.float("b", default=0.0)
c = pyre.inventory.float("c", default=0.0)
def initialize(self):
self.a = self.inventory.a
self.b = self.inventory.b
self.c = self.inventory.c
import ta... |
def __init__(self):
Component.__init__(self, "quadratic", "functor")
self.a = 0.0
self.b = 0.0
self.c = 0.0
import tabulator._tabulator
self.handle = tabulator._tabulator.quadratic()
return
def _init(self):
Component._init(self)
... |
rtx3/saltstack-deyunio | srv/salt/modules/xmpp.py | Python | apache-2.0 | 5,646 | 0 | # -*- coding: utf-8 -*-
'''
Module for Sending Messages via XMPP (a.k.a. Jabber)
.. versionadded:: 2014.1.0
:depends: - sleekxmpp python module
:configuration: This module can be used by either passing a jid and password
directly to send_message, or by specifying the name of a configuration
profile in the m... | erybadpass'
'''
# Remove: [WARNING ] Use of send mask waiters is deprecated.
for handler in logging.root.handlers:
handler.addFilter(SleekXMPPMUC())
if profile:
creds = __salt__['config.option'](profile)
jid = creds.get('xmpp.jid')
password = creds.get('xmpp.password')... | SendMsgBot.create_multi(
jid, password, message, recipients=recipients, rooms=rooms)
if rooms:
xmpp.register_plugin('xep_0045') # MUC plugin
if xmpp.connect():
try:
xmpp.process(block=True)
return True
except XMPPError as err:
log.error("Coul... |
endlessm/chromium-browser | third_party/llvm/llvm/test/MC/COFF/bigobj.py | Python | bsd-3-clause | 935 | 0.004278 | # RUN: python %s | llvm-mc -filetype=obj -triple i686-pc-win32 - | llvm-readobj -h | FileCheck %s
from __future__ import print_function
# This test checks that the COFF object emitter can produce objects with
# more than 65279 sections.
# While we only generate 65277 sections, an implicit .text, .data and .bss will
... | -NEXT: SectionCount: 65280
# CHECK-NEXT: TimeDateStamp: {{[0-9]+}}
# CHECK-NEXT: PointerToSymbolTable: 0x{{[0-9A-F]+}}
# CHECK-NEXT: SymbolCount: 195837
# CHECK-NEXT: OptionalHeaderSize: 0
# CHECK-NEXT: Characteristics [ (0x0)
# CHECK-NEXT: ]
# CHECK-NEXT: }
for i in range(0, num_sections):
print(""" .s... | _b%d
.globl _b%d # @b%d
_b%d:
.byte 0 # 0x0
""" % (i, i, i, i))
|
poranmeloge/test-github | stm32_rtt_wifi/bsp/efm32/rtconfig.py | Python | gpl-2.0 | 2,289 | 0.009611 | import os
# toolchains options
ARCH = 'arm'
CPU = 'cortex-m3'
CROSS_TOOL = 'gcc'
if os.getenv('RTT_CC'):
CROSS_TOOL = os.getenv('RTT_CC')
if CROSS_TOOL == 'gcc':
PLATFORM = 'gcc'
EXEC_PATH = 'C:\Program Files (x86)\CodeSourcery\Sourcery G++ Lite\bin'
#EXEC_PATH = 'C:\Program Files ... | ============='
exit(0)
if os.getenv('RTT_EXEC_PATH'):
EXEC_PATH = os.getenv('RTT_EXEC_PATH')
BUILD = 'debug'
# EFM32_BOARD = 'EFM32_G8XX_STK'
# EFM32_BOARD = 'EFM32_GXXX_DK'
EFM32_BOARD = 'EFM32GG_DK3750'
if EFM32_BOARD == 'EFM32_G8XX_STK':
EFM32_FAMILY = 'Gecko'
EFM32_TYPE = 'EFM32G890F128'
E... | ':
EFM32_FAMILY = 'Giant Gecko'
EFM32_TYPE = 'EFM32GG990F1024'
# EFM32_LCD = 'LCD_MAPPED'
EFM32_LCD = 'LCD_DIRECT'
if PLATFORM == 'gcc':
# toolchains
PREFIX = 'arm-none-eabi-'
CC = PREFIX + 'gcc'
AS = PREFIX + 'gcc'
AR = PREFIX + 'ar'
LINK = PREFIX + 'gcc'
TARGET_EXT = 'axf... |
mitre/multiscanner | multiscanner/modules/MachineLearning/EndgameEmber.py | Python | mpl-2.0 | 2,656 | 0.001506 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
By default, this module uses the pre-built Ember model from
https://pubdata.endgame.com/ember/ember_dataset.tar.bz2.... | )[0], 'etc', 'ember', 'ember_model_2017.txt'),
}
LGBM_MODEL = None
try:
import ember
has_ember = True
except ImportError as e:
print("ember module not installed...")
has_ember = False
try:
import lightgbm as lgb
except ImportError as e:
print("lightgbm module needed for ember. Not installed...... | ABLED']:
return False
if not has_ember:
return False
if not Path(conf['path-to-model']).is_file():
print("'{}' does not exist. Check config.ini for model location.".format(conf['path-to-model']))
return False
try:
global LGBM_MODEL
LGBM_MODEL = lgb.Booster(m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.