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 |
|---|---|---|---|---|---|---|---|---|
dNG-git/pas_http_user | src/dNG/module/controller/user/module.py | Python | mpl-2.0 | 2,059 | 0.005828 | # -*- coding: utf-8 -*-
"""
direct PAS
Python Application Services
----------------------------------------------------------------------------
(C) direct Netware Group - All rights reserved
https://www.direct-netware.de/redirect?pas;http;user
This Source Code Form is subject to the terms of the Mozilla Public Licens... | licenses;mpl2
----------------------------------------------------------------------------
#echo(pasHttpUserVersion)#
#echo(__FILEPATH__)#
"""
from dNG.data.settings import Settings
from dNG.data.translatable_exception import TranslatableException
from dNG.database.connection import Connection
from dNG.module.controll... | actHttpController
class Module(AbstractHttpController):
"""
Module for "user"
:author: direct Netware Group et al.
:copyright: (C) direct Netware Group - All rights reserved
:package: pas.http
:subpackage: user
:since: v0.2.00
:license: https://www.direct-netware.de/redirect?licenses;mpl2
... |
sadanandb/pmt | src/tactic/triggers/data_trigger.py | Python | epl-1.0 | 2,434 | 0.002465 | ###########################################################
#
# Copyright (c) 2005, Southpaw Technology
# All Rights Reserved
#
# PROPRIETARY INFORMATION. This software is proprietary to
# Southpaw Technology, and is not to be reproduced, transmitted,
# or disclosed in any way without written permi... | eTrigger"]
from pyasm.command import Trigger
from tactic.command import PythonCmd
class DataValidationTrigger(Trigger):
def execute(my):
sobject = my.get_current_sobject()
class DataUpdateTrigger(Trigger):
def | get_args_keys(my):
return {
}
def execute(my):
input = my.get_input()
if input.get("mode") == 'delete':
return
print "input: ", input
sobject = input.get("sobject")
trigger_sobj = my.get_trigger_sobj()
data = my.get_trigger_data()
... |
ActiveCoders/platformerSkel | pyGamePlatformerSkeletonV1.py | Python | gpl-3.0 | 250 | 0.008 | # Title
# Author
# ActiveCoders.club
# import external modules
import pygame
# setup global constants
# setup global variables
# se | tup classes
class PlayerSprite(pygame.sprite.Sprite):
pass
class Pla | yerControl():
pass
# main game loop
|
NvanAdrichem/networkx | networkx/readwrite/gexf.py | Python | bsd-3-clause | 36,773 | 0.001713 | # Copyright (C) 2013-2016 by
#
# Authors: Aric Hagberg <[email protected]>
# Dan Schult <[email protected]>
# Pieter Swart <[email protected]>
# All rights reserved.
# BSD license.
# Based on GraphML NetworkX GraphML reader
"""Read and write graphs in GEXF format.
GEXF (Graph Exchange XML Format) is a ... | ks structures, | their associated data and dynamics" [1]_.
Parameters
----------
path : file or string
File or file name to write.
File names ending in .gz or .bz2 will be compressed.
node_type: Python type (default: None)
Convert node ids to this type if not None.
relabel : bool (default: Fa... |
sn-amber/mylpp | scripts/dview.py | Python | gpl-2.0 | 382 | 0.005236 | #!/usr/bin/python
# Script: dview.py
# Purpose: launch vcr tool on LAMMPS dump files
# Syntax: dview.py dump.1 dump.2 ...
# files = one or more | dump files
# Example: dview.py dump.*
# Author: Steve Plimpton (Sandia)
# main s | cript
if len(argv) < 2:
raise StandardError, "Syntax: dview.py dump.1 ..."
files = ' '.join(argv[1:])
d = dump(files)
g = gl(d)
v = vcr(g)
|
rakeshmi/tempest | tempest/services/telemetry/json/telemetry_client.py | Python | apache-2.0 | 5,632 | 0 | # Copyright 2014 OpenStack Foundation
# 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 requ... | cess(200, resp.status)
body = self.deserialize(body)
return service_client.ResponseBody(resp, body)
def show_alarm(self, alarm_id):
uri = '%s/alarms/%s' % (self.uri_prefix, alarm_id)
resp, body = self.get(uri)
self.expected_success(200, resp.status)
body = self.deser... | uri = "%s/alarms/%s" % (self.uri_prefix, alarm_id)
resp, body = self.delete(uri)
self.expected_success(204, resp.status)
if body:
body = self.deserialize(body)
return service_client.ResponseBody(resp, body)
def create_alarm(self, **kwargs):
uri = "%s/alarms" % se... |
jdubs/cloud-custodian | tests/test_asg.py | Python | apache-2.0 | 14,780 | 0.000135 | # Copyright 2016-2017 Capital One Services, 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 ... | self.load_policy({
'name': 'unused-cfg',
'resource': 'launch-config',
'filters': [{'type': 'unused'}]}, session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0]['LaunchConfigurationName'],
... | tory = self.replay_flight_data('test_launch_config_delete')
p = self.load_policy({
'name': 'delete-cfg',
'resource': 'launch-config',
'filters': [{
'LaunchConfigurationName': 'CloudClusterCopy'}],
'actions': ['delete']},
session_factory... |
reinforceio/tensorforce | tensorforce/core/parameters/__init__.py | Python | apache-2.0 | 1,826 | 0.001643 | # Copyright 2020 Tensorforce Team. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a | copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES O | R CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
from functools import partial
from tensorforce.core.parameters.parameter import P... |
evonove/evonove.it | django-website/home/migrations/0005_auto_20160512_0713.py | Python | bsd-3-clause | 518 | 0.001931 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-05-12 07:13
from __future__ import unicode_literals
from django.db impor | t migrations
import wagtail.core.fields
class Migration(migrations.Migration):
dependencies = [
('home', '0004_auto_20160511_0845'),
]
operations = [
migrations.AlterField(
model_name='teammember',
name='bio',
f | ield=wagtail.core.fields.RichTextField(help_text='The team member bio', max_length=360),
),
]
|
eflee/blobapy | blobapy/aws.py | Python | mit | 69 | 0 | import boto3
session = boto3.session.Session(profile_n | ame="blobapy")
| |
OpenGuide/Python-Guide-for-Beginners | SimpleAddition/Sum_2_numbers.py | Python | mit | 661 | 0.001513 |
# first lets get 2 numbers to add
print "enter 2 number to add"
py
# getting the first number
| number1 = raw_input("Ok enter the first number ")
# and now the second number
number2 = raw_input("and now the second number ") |
# finally calculating the addidition of the numbers
# sum = number1 + number2
# seems to be right
# but as the inputs are taken as string we need to type cast them
# that is convert number1 and number2 to integer from string
# so lets do that
number1 = int(number1)
number2 = int(number2)
# and now lets calculate the... |
warnes/irrigatorpro | irrigator_pro/farms/migrations/0025_default_rain_irrigation_to_null.py | Python | mit | 2,383 | 0.002518 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from decimal import Decimal
import | django.core.validators
class Migration(migrations.Migration):
dependencies = [
('farms', '0024_rain_and_irrigation_allow_null'),
]
operations = [
| migrations.AlterField(
model_name='probereading',
name='irrigation',
field=models.DecimalField(decimal_places=2, validators=[django.core.validators.MinValueValidator(Decimal('0'))], max_digits=4, blank=True, null=True, verbose_name=b'Irrigation in inches'),
preserve_defa... |
MozillaSecurity/FuzzManager | server/covmanager/tests/conftest.py | Python | mpl-2.0 | 6,179 | 0.001618 | # coding: utf-8
'''Common test fixtures
@author: Jesse Schwartzentruber (:truber)
@license:
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/.
'''
import logging
import os... | ):
try:
proc = subprocess.Popen(["git"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = proc.communicate()
if output and proc.wait() == 1:
return True
except OSError: # FileNotFoundError
pass
return False
def _check_hg():
try:
proc = sub... | ubprocess.STDOUT)
output = proc.communicate()
if output and proc.wait() == 0:
return True
except OSError: # FileNotFoundError
pass
return False
HAVE_GIT = _check_git()
HAVE_HG = _check_hg()
@pytest.fixture
def covmanager_test(db): # pylint: disable=invalid-name,unused-a... |
mariuszlitwin/frets | frets.py | Python | apache-2.0 | 4,690 | 0.011301 | #!/usr/bin/python3
from colorama import Fore, Back
class frets:
tuning = list()
max_string_name_len = 0;
frets_count = 0;
strings = dict()
NOTES = ('E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B', 'C', 'C#', 'D', 'D#')
def __init__(self,
tuning=('E', 'A', 'D', 'G'),
... | upper_found_position))
print(Back.RED + ' ' + Back.BLACK + \
' Found note {} on: {}'.format(seek_note,
found_position))
print(Fore.WHITE + \
Back.MAGENTA + ' ' + Back.BLACK + \
' Found octave-lower ... | lower_found_position))
|
devonjones/PSRD-Parser | src/json_loader.py | Python | gpl-3.0 | 414 | 0.019324 | #!/usr/bin/env python
import sys
import os
import re
import json
import sqlite3
from psrd.options import load_option_parser, exec_load_main
from psrd.loader import load_documents
def main():
usage = "usage: %pro | g [options] [filenames]\nImports sections into psr | d db from feat json files."
parser = load_option_parser(usage)
exec_load_main(parser, load_documents)
if __name__ == "__main__":
sys.exit(main())
|
motord/Motorcycle-Diaries | lib/apiclient/oauth.py | Python | bsd-3-clause | 9,765 | 0.005735 | # Copyright 2010 Google Inc. All Rights Reserved.
"""Utilities for OAuth.
Utilities for making it easier to work with OAuth.
"""
__author__ = '[email protected] (Joe Gregorio)'
import copy
import httplib2
import logging
import oauth2 as oauth
import urllib
import urlparse
from anyjson import simplejson
try:
... | ments are all optional and required
parameters for the OAuth c | alls.
"""
self.discovery = discovery
self.consumer_key = consumer_key
self.consumer_secret = consumer_secret
self.user_agent = user_agent
self.params = kwargs
self.request_token = {}
required = {}
for uriinfo in discovery.itervalues():
for name, value in uriinfo['parameters'].i... |
domovilam/pimucha | piHAcontrollers/ctrlfcts/tsduofct.py | Python | gpl-3.0 | 2,304 | 0.013455 | # ----------------------------------------------------------------------------
# Copyright (C) 2013-2014 Huynh Vi Lam <[email protected]>
#
# This file is part of pimucha.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as pu... | logger.debug("Request %s to controller...",msg)
bytes = [ord(i) for i in seq]
for byte in bytes:
| dev.write(byte)
time.sleep(0.3)
res = dev.read(100)
if len(res) == 0:
return None
if res[0:2] == b"+W":
logger.debug("Event incoming from controller : %s",repr(res))
r = res
else:
r = res[0:lenresp]
logger.debug("Respons... |
mlflow/mlflow | mlflow/projects/backend/loader.py | Python | apache-2.0 | 1,079 | 0.00278 | import entrypoints
import logging
from ml | flow.projects.backend.local import LocalBackend
ENTRYPOINT_GROUP_NAME = "mlflow.project_backend"
__logger__ = logging.getLogger(__name__)
# Statically register backend defined in mlflow
MLFLOW_BACKENDS = {
"local": LocalBackend,
}
def load_backend(backend_name):
# Static backends
if backend_name in M... | lugin
try:
backend_builder = entrypoints.get_single(ENTRYPOINT_GROUP_NAME, backend_name).load()
return backend_builder()
except entrypoints.NoSuchEntryPoint:
# TODO Should be a error when all backends are migrated here
available_entrypoints = entrypoints.get_group_all(ENTRYPOINT_... |
Andr3iC/juriscraper | opinions/united_states/state/nmctapp_slip.py | Python | bsd-2-clause | 435 | 0 | import nm_p
class Site(nm_p.Site):
| def __init__(self, *args, **kwargs):
super(Site, self).__init__(*args, **kwargs)
self.url = 'http://www.nmcompcomm.us/nmcases/NMCASlip.aspx'
self.court_id = self.__module__
def _get_docket_numbers(self):
path = '//table[@id="GridView1"]/tr/td[3]//text()'
return list(self.... | (path))
def _get_neutral_citations(self):
return None
|
jwhui/openthread | tests/scripts/thread-cert/pktverify/layer_fields.py | Python | bsd-3-clause | 26,646 | 0.0006 | #!/usr/bin/env python3
#
# Copyright (c) 2019, The OpenThread Authors.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright
# ... | (v.get_default_value())
def _ipv6_addr(v: Union[LayerFieldsContainer, LayerField]) -> Ipv6Addr:
"""parse the layer field as an IPv6 address"""
assert not isinstance(v, LayerFieldsContainer) or len(v.fields) == 1
return Ipv6Addr(v.get_default_value())
def _eth_addr(v: Union[LayerFields | Container, LayerField]) -> EthAddr:
"""parse the layer field as an Ethernet MAC address"""
assert not isinstance(v, LayerFieldsContainer) or len(v.fields) == 1, v.fields
return EthAddr(v.get_default_value())
def _routerid_set(v: Union[LayerFieldsContainer, LayerField]) -> set:
"""parse the layer field... |
yibitcoin/yibitcoin | qa/rpc-tests/txn_doublespend.py | Python | apache-2.0 | 4,971 | 0.003018 | #!/usr/bin/env python2
# Copyright (c) 2014 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test proper accounting with malleable transactions
#
from test_framework.test_framework import BitcoinTes... | on from node[0] to node[1]; the
# second must spend change from the first because the first
# spends all mature inputs:
txid1 = self.nodes[0].sendfrom("foo", node1_address, 7499960, 0)
txid2 = self.nodes[0].sendfrom("bar", node1_address, 20, 0)
# Have node0 mine a block:... | 0].gettransaction(txid1)
tx2 = self.nodes[0].gettransaction(txid2)
# Node0's balance should be starting balance, plus 500,000 DOGE for another
# matured block, minus 7499960, minus 20, and minus transaction fees:
expected = starting_balance
if self.options.mine_block: expected +... |
tkzeng/molecular-design-toolkit | moldesign/_tests/test_mm.py | Python | apache-2.0 | 4,019 | 0.002737 | import random
import pytest
import numpy as np
import moldesign as mdt
from moldesign import units as u
from . import helpers
registered_types = {}
def typedfixture(*types, **kwargs):
"""This is a decorator that lets us associate fixtures with one or more arbitrary types.
We'll later use this type to dete... | tom.index for atom in atoms]
anagrad = -mo | l.calculate_forces()[atom_indices]
numgrad = helpers.num_grad(mol,
mol.calculate_potential_energy,
atoms=atoms,
step=0.005*u.angstrom)
assert (anagrad-numgrad).norm()/(3.0*len(atoms)) <= 5.0e-4 * u.eV / u.angstrom
@py... |
spencervillars/AutoSchema | tests/test_tabulate.py | Python | mit | 360 | 0 | from myc | li.packages.tabulate import tabulate
from textwrap import dedent
def test_dont_strip_leading_whitespace():
data = [[' abc']]
headers = ['xyz']
tbl, _ = tabulate(data, headers, tablefmt='psql')
assert tbl == dedent('''
+---------+
| xyz |
|---------|
| | abc |
+---------+ ''').strip()
|
Qalthos/remysmoke | remysmoke/websetup/bootstrap.py | Python | agpl-3.0 | 246 | 0.004065 | # -*- coding: utf-8 -*-
"""Setup the remysmoke application"""
import logging
from tg import config
from remysmoke i | mport mod | el
import transaction
def bootstrap(command, conf, vars):
"""Place any commands to setup remysmoke here"""
pass
|
sinnwerkstatt/django-indisposable-email-field | indisposable_email_field/data.py | Python | apache-2.0 | 9,940 | 0.008853 |
domain_names = ['0clickemail.com', 'noclickemail.com', '10minutemail.com', 'bofthew.com', 'drdrb.com', 'drdrb.net',
'jnxjn.com', 'klzlk.com', 'nepwk.com', 'nwldx.com', 'owlpic.com', 'pjjkp.com', 'prtnx.com', 'rmqkr.net',
'rppkn.com', 'rtrtr.com', 'trbvm.com', 'tyldd.com', 'uggsrock.com... | 'emailtemporanea.com', 'emailtemporanea.net', 'empiremail.de', 'eyepaste.com', 'fakeinbox.com',
'fakemail.fr', 'adresseemailtemporaire.com', 'armyspy.com', 'cuvox.de', 'dayrep.com', 'einrot.com',
'fakemailgenerator.com', 'fleckens.hu', 'gustr.com', 'jourrapide.com', 'rhyta.... | litafir.de', 'frapmail.com',
'garbagemail.org', 'garliclife.com', '7tags.com', 'broadbandninja.com', 'cellurl.com', 'dealja.com',
'getairmail.com', 'moburl.com', 'tagyourself.com', 'vidchart.com', 'getmails.eu', 'consumerriot.com',
'getonemail.com', 'gishpuppy.com', 'nurf... |
scavarda/mysql-dbcompare | mysql-utilities-1.6.0/scripts/mysqlrplsync.py | Python | apache-2.0 | 11,414 | 0.000789 | #!/usr/bin/env python
#
# Copyright (c) 2014, Oracle and/or its affiliates. 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; version 2 of the License.
#
# This program is d... | included in the comparison. To check specific
databases or tables, list each element as a separated argument for the
utility using full qualified names as shown in the following examples.
# Check the data consistency of a replication topology, explicitly
# specifying the master and slaves.
$ mysqlrplsync --mas... | es=rpl:pass@host2:3306,rpl:pass@host3:3306
# Check the data consistency of a replication topology, specifying the
# master and using the slaves discovery feature.
$ mysqlrplsync --master=root:pass@host1:3306 \\
--discover-slaves-login=rpl:pass
# Check the data consistency only between specif... |
maxvonhippel/q2-diversity | q2_diversity/_alpha/_visualizer.py | Python | bsd-3-clause | 8,213 | 0.000244 | # ----------------------------------------------------------------------------
# Copyright (c) 2016-2017, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... | kw_H_pairwise.to_csv(pairwise_path)
with open(os.path.join(output_dir, filename), 'w') as fh:
df = pd.Series(groups, index=names)
fh.write("load_data('%s'," % category)
df.to_json(fh, orient='split')
fh.write(",")
json.dump(... | 'filtered': filtered_data_length}, fh)
fh.write(",")
json.dump({'H': kw_H_all, 'p': kw_p_all}, fh)
fh.write(",'")
table = kw_H_pairwise.to_html(classes="table table-striped "
"table-h... |
south-coast-science/scs_core | tests/sys/tail_test.py | Python | mit | 547 | 0 | #!/usr/bin/env python3
"""
Created on 20 Jan 2020
@author: Bruno Beloff ([email protected])
"""
import os
from scs_core.sys.tail import Tail
# --------------------------------------------------------------------------------------------------------------------
path = os.path.expanduser('~/SCS/scs... | il_test.json')
tail = Tail.const | ruct(path)
print(tail)
try:
tail.open()
for message in tail.readlines():
print("got: %s" % message)
except RuntimeError:
pass
finally:
tail.close()
|
jackrzhang/zulip | zerver/webhooks/airbrake/view.py | Python | apache-2.0 | 1,393 | 0.005743 | # Webhooks for external integrations.
from typing import Any, Dict
from django.http import HttpRequest, HttpResponse
from django.utils.translation import ugettext as _
from zerver.decorator import api_key_only_webhook_view
from zerver.lib.web | hooks.common import check_send_webhook_message
from zerver.lib.request import REQ, has_request_variables
from zerver.lib.response import json_error, json_success
from zerver.models import UserProfile
AIRBRAKE_TOPIC_TEMPLATE = '{project_name}'
AIRBRAKE_MESSAGE_TEMPLATE = '[{error_class}]({error_url}): "{error_message}"... | payload: Dict[str, Any]=REQ(argument_type='body')) -> HttpResponse:
subject = get_subject(payload)
body = get_body(payload)
check_send_webhook_message(request, user_profile, subject, body)
return json_success()
def get_subject(payload: Dict[str, Any]) -> str:
return AIRBRAKE_TOPIC_TEMPLATE.fo... |
CroceRossaItaliana/jorvik | anagrafica/validators.py | Python | gpl-3.0 | 3,974 | 0.003531 | import stdnum
import re
from datetime import datetime, date
from django.utils import timezone
from django.core.exceptions import ValidationError
from django.utils.deconstruct import deconstructible
from stdnum.it import codicefiscale
def _valida_codice_fiscale(codice_fiscale):
"""
Validatore esteso che ver... | ise ValidationError("IBAN non valido.")
def valida_dimensione_file_5mb(fieldfile_obj):
filesize = fieldfile_obj.file.size
megabyte_limit = 5
if filesize > megabyte_limit*1024*1024:
raise ValidationError("Seleziona un file più piccolo di %sMB" % str(megabyte_limit))
def valida_dimensione_file_10m... | ù piccolo di %sMB" % str(megabyte_limit))
def valida_dimensione_file_8mb(fieldfile_obj):
filesize = fieldfile_obj.file.size
megabyte_limit = 8
if filesize > megabyte_limit*1024*1024:
raise ValidationError("Seleziona un file più piccolo di %sMB" % str(megabyte_limit))
def valida_almeno_14_anni(da... |
mlperf/training_results_v0.5 | v0.5.0/nvidia/submission/code/object_detection/pytorch/maskrcnn_benchmark/utils/logging.py | Python | apache-2.0 | 727 | 0.001376 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import logging
import os
import sys
def setup_logger(name, save_dir, local_rank):
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
# don't log results for the non-mas | ter process
if local_rank > 0:
return
| ch = logging.StreamHandler(stream=sys.stdout)
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s %(name)s %(levelname)s: %(message)s")
ch.setFormatter(formatter)
logger.addHandler(ch)
if save_dir:
fh = logging.FileHandler(os.path.join(save_dir, "log.txt"))
fh.set... |
emmanuelle/scikits.image | skimage/morphology/tests/test_convex_hull.py | Python | bsd-3-clause | 2,035 | 0.000491 | import numpy as np
from numpy.testing import assert_array_equal
from numpy.testing.decorators import skipif
from skimage.morphology import convex_hull_image
from skimage.morphology._convex_hull import possible_hull
try:
import scipy.spatial
scipy_spatial = True
except ImportError:
scipy_spatial = False
@... | 1, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 0, 0, 0],
[0, 0, 1, 1, 1, 1, 1, 0, 0],
[0, 1, 1, 1, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
assert_array_equal(convex_hull_image(image), expected)
@skipif(not scipy_spatial)
def test_possible_hull():
image = np.array(
... | [0, 0, 1, 1, 1, 1, 1, 0, 0],
[0, 1, 1, 1, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=np.uint8)
expected = np.array([[1, 4],
[2, 3],
[3, 2],
[4, 1],
[4, 1],
[3,... |
divio/django-cms-demo | src/wsgi.py | Python | bsd-3-clause | 382 | 0 | """
WSGI config for this project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on t | his file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ | .setdefault("DJANGO_SETTINGS_MODULE", "src.settings")
application = get_wsgi_application()
|
zooniverse/aggregation | experimental/algorithms/clustering_dict.py | Python | apache-2.0 | 244 | 0.028689 | __author__ = 'greg'
import agglomerative
clustering_dict = {}
# maps each sahpe to a clustering algorithm and any key word par | am
clustering_dict["seasons"] = {"point":(agglomerative.Agglomerative,{}),"ellipse":(agglomerative.Agglomerative,{})} | |
JQ-K/OMOOC2py | _src/om2py4w/4wex0/server/jserver.py | Python | mit | 531 | 0.028249 | #/usr/bin/env python
# -*- coding: utf-8 -*-
from bottle import get, post, request, run, jinja2_view
#import sae.kvdb
from datetime import datetime
import jnote
@g | et('/note')
@jinja2_view('jnote.html')
def ShowPage():
notes = jnote.GetNotes()
return {'notes':notes}
@post('/note')
@jinja2_view('jnote.html')
def CreatNote():
note = unicode(request.forms.get('newnote'),'utf-8')
if note:
jnote.NewNote(note)
notes = jnote.GetNotes()
return {'notes': notes}
run (host='127.... | der=True)
|
nv8h/PyRattus | base/modules/rat/application/abstract.py | Python | mit | 1,309 | 0.022918 | import sys
#from OpenGL.GLUT import *
#from OpenGL.GLU import *
#from OpenGL.GL import *
class abstract:
| params = {}
windowId = None
terminated = False
def initParams(self):
return self
def __init__(self):
self.initParams().init()
return
def init(self):
return
def mouse(self, button, state, x, y):
return
def mouseMotion(self, x,... | keyboard(self, asciiCode, x, y):
return
def keyboardSpecial(self, key, x, y):
return
def idle(self):
return
def timer(self, value):
return
def render(self):
return
def reshape(self, width, height):
return
def run(self)... |
Jgarcia-IAS/SAT | openerp/addons-extra/odoo-pruebas/odoo-server/addons-extra/account_transfer_advance/sale.py | Python | agpl-3.0 | 1,249 | 0.004804 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2013 Cubic ERP - Teradata SAC (<http://cubicerp.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the ... | ass sale_order(osv.osv):
| _inherit = 'sale.order'
_columns = {
'transfer_ids': fields.one2many('account.transfer','sale_id',string='Payment Advanced Transfered',readonly=True),
}
|
LittleRichard/luxalert | luxweb/luxweb/spiders/ParklaneSpider.py | Python | gpl-3.0 | 4,429 | 0.002032 | import datetime
import logging
import re
import scrapy
from nest.storage.luxalert.entity.Apartment import Apartment
from nest.storage.luxalert.entity.ApartmentSnapshot import ApartmentSnapshot
from luxweb.luxweb import HMTL_SPIDER_DATA_TUPLE_KEY
from luxweb.luxweb.ScrapeErrorHandler import ScrapeErrorHandler
from lux... | ield scrapy.Request(url=url, callback=self.parse)
@ScrapeErrorHandler.wrap_to_raise
def parse(self, response):
buildings_by_name = self.get_building | s_by_name(ParklaneSpider.BUILDING_NAMES)
table_index = 0
titles = []
# get apartment titles
for title in response.xpath('//h3'):
titles.append(title.xpath('text()').extract_first())
# loops through all tables
for plan in response.xpath(
'//... |
airelil/pywinauto | pywinauto/handleprops.py | Python | bsd-3-clause | 14,685 | 0.002315 | # GUI Application automation and testing library
# Copyright (C) 2006-2018 Mark Mc Mahon and Contributors
# https://github.com/pywinauto/pywinauto/graphs/contributors
# http://pywinauto.readthedocs.io/en/latest/credits.html
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or with... | ==============================
def isvisible(handle):
"""Return True if the window is visible"""
return False if handle is None else bool(win32functions.IsWindowVisible(handle))
#=========================================================================
def isunicode(handle):
"""Return True if the ... | ==================================================
def isenabled(handle):
"""Return True if the window is enabled"""
return False if handle is None else bool(win32functions.IsWindowEnabled(handle))
#=========================================================================
def is64bitprocess(process_id)... |
jessicalucci/NovaOrc | nova/tests/api/openstack/test_xmlutil.py | Python | apache-2.0 | 28,151 | 0.000107 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack Foundation
# 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.apach... | bj_for_test = {
'test': {
'name': 'test',
'values': [1, 2, 3],
'attrs': {
'foo': 1,
'bar': 2,
'baz': 3,
},
},
}
def test_empty_selector(self):
sel = xmlutil.Selector()
sel... | sel = xmlutil.Selector('test')
self.assertEqual(len(sel.chain), 1)
self.assertEqual(sel.chain[0], 'test')
self.assertEqual(sel(self.obj_for_test),
self.obj_for_test['test'])
def test_datum_selector(self):
sel = xmlutil.Selector('test', 'name')
... |
skarphed/skarphed | core/lib/operation.py | Python | agpl-3.0 | 16,724 | 0.00891 | #!/usr/bin/python
#-*- coding: utf-8 -*-
###########################################################
# © 2011 Daniel 'grindhold' Brendle and Team
#
# This file is part of Skarphed.
#
# Skarphed is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General Public License
# as ... | rops an Operation, identified by it's Operation Id and
it's children recursively
Drop deletes the Operations from Database
"""
db = Database()
stmnt | = "SELECT OPE_ID FROM OPERATIONS WHERE OPE_OPE_PARENT = ? AND OPE_STATUS IN (0, 2) ;"
cur = db.query(stmnt,(operation_id,))
for row in cur.fetchallmap():
cls.drop_operation(row["OPE_ID"])
stmnt = "DELETE FROM OPERATIONS WHERE OPE_ID = ? AND OPE_STATUS IN (0, 2) ;"
db.query(s... |
GoogleCloudPlatform/python-repo-tools | setup.py | Python | apache-2.0 | 1,458 | 0 | # 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, 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.
import io
import set... |
Shopify/shopify_python | shopify_python/packaging.py | Python | mit | 2,108 | 0.003795 | import os.path
import subprocess
import pkg_resources
import setuptools # pylint: disable=unused-import
def get_package_revision(package_name):
# type: (str) -> str
"""Determine the Git commit hash for the Shopify package.
If the package is installed in "develop" mode the SHA is retrieved using Git. Ot... | egg_info.has_metadata('git_sha.txt'):
return egg_info.get_metadata('git_sha.txt')
return ''
def write_package_revision(cmd, _, filename):
# type: (setuptools.Command, str, str) -> None
"""Write the Git commit hash for the package th | at is currently being built.
If the build is not occurring from a Git checkout the current revision must be stored in a text file named
"REVISION".
This function should not be called except via setuptools, by specifying an 'egg_info.writers' entrypoint as follows:
setuptools.setup(
na... |
plotly/plotly.py | packages/python/plotly/plotly/validators/barpolar/_opacity.py | Python | mit | 474 | 0.00211 | import _plotly_utils.basevalidators
class OpacityValidator(_plot | ly_utils.basevalidators.NumberValidator):
def __init__(self, plotly_name="opacity", parent_name="barpolar", **kwargs):
super(OpacityValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", " | style"),
max=kwargs.pop("max", 1),
min=kwargs.pop("min", 0),
**kwargs
)
|
xbash/LabUNAB | 03_condiciones/Ejercicio8_saltos.py | Python | gpl-3.0 | 1,849 | 0.018388 | """
En las competencias de clavados, cada salto es evaluado por un panel de siete jueces. Cada juez entrega una
puntuacion en una escala de 1 a 10, con incrementos de 0:5 . La puntuacion mas alta y la mas baja son
eliminadas. La suma de los cinco puntajes restantes es multiplicada por 0.6 , y el resultado es multipl... | 2,8,1):
ptje=float(raw_input("Calificacion :"))
if menor>ptje:
menor=ptje
if mayor<ptje:
mayor=ptje
ptjetotal =ptjetotal+ptje
# fuera del ciclo
ptjetotal=ptjeto | tal-(mayor+menor)
ptjetotal=ptjetotal*0.6
ptjetotal=ptjetotal*gradodif
print"\n\n\t\t Puntaje Total del Salto :", ptjetotal
"""
Resultado ejecucion:
Calificacion de Saltos Clavados
Ingrese Grado de Dificultad del Salto
Grado :3
Ingrese 7 calificaciones
Calificacion :5
Calificacion :5.5
... |
vikalpindia/vikalp | vikalp/compressor/filters.py | Python | apache-2.0 | 695 | 0.011511 | from compressor.conf import settings
from compressor.filters import CompilerFilter
class YUglifyFilter(CompilerFilter):
command = "{binary} { | args}"
def __init__(self, *args, **kwargs):
super(YUglifyFilter, self).__init__(*args, **kwargs)
self.command += ' --type=%s' | % self.type
class YUglifyCSSFilter(YUglifyFilter):
type = 'css'
options = (
("binary", settings.COMPRESS_YUGLIFY_BINARY),
("args", settings.COMPRESS_YUGLIFY_CSS_ARGUMENTS),
)
class YUglifyJSFilter(YUglifyFilter):
type = 'js'
options = (
("binary", settings.COMPRESS_Y... |
mxm/incubator-beam | sdks/python/apache_beam/examples/wordcount_debugging.py | Python | apache-2.0 | 6,652 | 0.006464 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | t='input',
default='gs://dataflow-samples/shakespeare/kinglear.txt',
| help='Input file to process.')
parser.add_argument('--output',
dest='output',
required=True,
help='Output file to write results to.')
known_args, pipeline_args = parser.parse_known_args(argv)
# We use the save_main_session option becaus... |
emiliom/pyoos | pyoos/parsers/ioos/describe_sensor.py | Python | lgpl-3.0 | 1,657 | 0.003018 | from pyoos.utils.etree import etree
| from owslib.namespaces import Namespaces
ns = Namespaces()
SML_NS = ns.get_versioned_namespace('sml', '1.0.1')
SWE_NS = [ns.get_versioned_namespace('swe', '1.0.1')]
class IoosDescribeSensor(object):
def __new__(cls, element):
if isinstance(element, str):
root = etree.fromstring(element)
... | ntifier/{{{0}}}Term[@definition='http://mmisw.org/ont/ioos/definition/%s']".format(SML_NS)
if hasattr(root, 'getroot'):
root = root.getroot()
# circular dependencies are bad. consider a reorganization
# find the the proper type for the DescribeSensor
from pyoos.parsers.ioos... |
therightmandev/WebShop | server/config.py | Python | mit | 257 | 0.003891 | import sys, os
EMAIL = os.environ.get('FLASK_EMAIL', '')
EMAIL_PASSWORD = os.environ.get('FLASK_EMAIL_PASSWORD', '' | )
DB_P | ATH = 'sqlite:///test.db'
if EMAIL == '' or EMAIL_PASSWORD == '':
sys.exit('Please write email and password in server/config.py')
|
jwhitlock/kuma | kuma/users/migrations/0003_user_discourse_url.py | Python | mpl-2.0 | 650 | 0.001538 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2018-08-13 15:29
from __future__ import unicode_literals
import djang | o.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0002_pytz_2018_5_and_username'),
]
operations = [
migrations.AddField(
model_name='user',
name='discourse_url',
field=models.T... | alid')], verbose_name='Discourse'),
),
]
|
rockychen-dpaw/borgcollector | borg_utils/borg_config.py | Python | bsd-3-clause | 890 | 0.020225 | import os
from django.conf import settings
class BorgConfiguration():
@staticmethod
def initialize():
setattr(BorgConfiguration,"DEBUG",getat | tr(settings,"DEBUG",False))
config = getattr(settings,"HARVEST_CONFIG")
if not config:
config = {}
for name, value in config.iteritems():
setattr(BorgConfiguration, name, value)
setattr(BorgConfiguration,"TEST_INPUT_SCHEMA",BorgConfiguration.test_schema(BorgCo | nfiguration.INPUT_SCHEMA))
setattr(BorgConfiguration,"TEST_NORMAL_SCHEMA",BorgConfiguration.test_schema(BorgConfiguration.NORMAL_SCHEMA))
setattr(BorgConfiguration,"TEST_TRANSFORM_SCHEMA",BorgConfiguration.test_schema(BorgConfiguration.TRANSFORM_SCHEMA))
@staticmethod
def test_schema(schema):
... |
dbmi-pitt/DIKB-Micropublication | scripts/mp-scripts/Bio/HMM/DynamicProgramming.py | Python | apache-2.0 | 12,658 | 0.001264 | """Dynamic Programming algorithms for general usage.
This module contains classes which implement Dynamic Programming
algorithms that can be used generally.
"""
class AbstractDPAlgorithms:
"""An abstract class to calculate forward and backward probabiliies.
This class should not be instantiated directly, but... | ence.
o previous_vars -- All of the forward or backward variables
calculated so far.
Returns:
o The calculated scaling variable for the sequence item.
"""
# all of the different letters the state can have
state_letters = self._seq.states.alphabet.letters
... | self._seq.emissions[seq_pos])]
# now sum over all of the previous vars and transitions
trans_and_var_sum = 0
for second_state in self._mm.transitions_from(main_state):
# the value of the previous f or b value
va... |
lastralab/Statistics | Specialization/Personal/Loops.py | Python | mit | 855 | 0.02924 |
''' While x is less than 10 it will print x and add 1 to that number,
then print it and so on until that condition is false, which is
when x equals 10 '''
condition = input('Enter number: ')
x = int(condition)
print (' ')
print ('While loop:')
while x <= 10:
print (x)
x += 1
# will stop adding 1 w... | run and watch:
'''
while True:
print('infinite')
'''
print (' ')
print ('For Loop: ')
exampleList = [1,6,7,3,6,9,0]
print (' ')
print ('See co | de for reference')
print (' ')
for thing in exampleList:
print (thing)
print (' ')
print ('For x in range loop:')
print (' ')
for x in range (1,11): # range is not in list, this is separate
print (x)
|
snowleung/mywunder | mywunder/myconfig.py | Python | mit | 505 | 0.00396 | #coding:utf-8
import os
import logging
logging.basicCo | nfig(level=logging.DEBUG, format='%(asctime)s %(filename)s:%(lineno)s - %(funcName)20s() - %(name)s - %(levelname)s - %(message)s')
logging.warning('load module:%s', __name__)
user_path = os.path.expanduser("~/")
dir_path = os.path.join(user_path, '.mywunder/')
try:
os.mkdir(dir_path)
except OSError:
pass
conf... | in(dir_path, "mywunder.db")
CLIENT_ID = 'ce310d4e732dc98c6a07'
|
zhongliliu/muse | muse/Similarity/Calc_Angle.py | Python | gpl-2.0 | 1,889 | 0.005294 | """
MUSE -- A Multi-algorithm-collaborative Universal Structure-prediction Environment
Copyright (C) 2010-2017 by Zhong-Li Liu
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 Founda | tion
version 2 of the License.
This program is distributed in the hope that it will be useful, but WIT | HOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.
E-mail: [email protected]
"""
import numpy as np
import math
def calc_angle(l1, l2):
v10 = l1
v12 = l2
v10 /= np.linalg.norm(v10)
v12 ... |
pyupio/dparse | tests/test_parse.py | Python | mit | 10,268 | 0.001169 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""Tests for `dparse.parser`"""
from dparse.parser import parse, Parser
from dparse import filetypes
from packaging.specifiers import SpecifierSet
def test_requirements_with_invalid_requirement():
content = "in=vali===d{}{}{"
... | .conda_yml)
assert len(dep_file.dependencies) == 1
dep_file = parse(content, file_type=filetypes.conda_yml, marker=((), "naah, marked"))
assert len(dep_file.dependencies) == 0
def test_tox_ini_marked_line():
content = "[testenv:bandit]\n" \
"commands =\n" \
"\tbandit --ini... | ed\n" \
"\n" \
"[testenv:manifest]\n" \
"commands =\n" \
"\tcheck-manifest --verbose\n"
dep_file = parse(content, "tox.ini")
assert len(dep_file.dependencies) == 1
dep_file = parse(content, "tox.ini", marker=((), "naah, marked"))
assert len(dep_f... |
CompassionCH/compassion-modules | mobile_app_connector/migrations/12.0.1.0.1/post-migration.py | Python | agpl-3.0 | 660 | 0 | ##############################################################################
#
# Copyright (C) 2020 Co | mpassion CH (http://www.compassion.ch)
# @author: Théo Nikles <[email protected]>
#
# The licence is in the file __manifest__.py
#
##############################################################################
def migrate(cr, version):
if not version:
return
cr.execute("""
INSERT IN... | DATE res_partner p
SET app_messages = (
SELECT id FROM mobile_app_messages
WHERE partner_id = p.id
);
""")
|
BCCVL/org.bccvl.tasks | src/org/bccvl/tasks/datamover/__init__.py | Python | gpl-2.0 | 359 | 0 | from __future__ import absolute_import
| from .tasks import move, update_metadata, import_multi_specie | s_csv
from .ala import pull_occurrences_from_ala
from .gbif import pull_occurrences_from_gbif
from .aekos import pull_occurrences_from_aekos, pull_traits_from_aekos
from .zoatrack import pull_traits_from_zoatrack
from .obis import pull_occurrences_from_obis
|
slosar/GMSampler | game.py | Python | gpl-2.0 | 11,404 | 0.033585 | from scipy import *
import random
import scipy.linalg as la
import cPickle
import pylab
class Sample:
def __init__ (self,pars, like, glikes):
self.pars=pars
self.like=like
self.glikes=glikes
class Gaussian:
def __init__(self,mean,cov, fastpars=None):
self.cov=cov
... | pars=slowpars
| self.Ns=Ns
def sample(self):
da=array([random.gauss(0.,1.) for x in range(self.N)])
glike = -(da**2).sum()/2.0-self.lndet/2.0
sa=dot(da,self.chol)
if (self.mean!=None):
sa+=self.mean
return sa,glike
def sample_fast(self, slowsamp):
... |
snapcore/snapcraft | snapcraft/internal/sources/__init__.py | Python | gpl-3.0 | 7,056 | 0 | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2015-2017 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Found | ation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License... | s this behaviour, a part can use these
'source' keys in its definition. They tell snapcraft where to pull source
code for that part, and how to unpack it if necessary.
- source: url-or-path
A URL or path to some source tree to build. It can be local
('./src/foo') or remote ('https://foo.org/...'), and can r... |
fabrickit/fabkit | core/db/impl_sqlalchemy/models.py | Python | mit | 2,392 | 0.000836 | # coding: utf-8
import datetime
from oslo_db.sqlalchemy import models
from sqlalchemy import (Column, Integer, String, ForeignKey, Index, DateTime,
Boolean, UniqueConstraint, BigInteger, MetaData)
from sqlalchemy.ext.declarative import declarative_base
metadata = MetaData()
class FabkitBase... | # requested, queued, complet | ed, error, canceled
status = Column(String(55), nullable=False, default='requested')
msg = Column(String(255), nullable=False, default='')
active = Column(Boolean(), nullable=False, default=True)
class Event(Base):
__tablename__ = 'event'
# check, setup
event_type = Column(String(255), nullab... |
Carreau/pip | pip/commands/list.py | Python | mit | 7,507 | 0 | from __future__ import absolute_import
import logging
import warnings
from pip.basecommand import Command
from pip.exceptions import DistributionNotFound
from pip.index import PackageFinder
from pip.req import InstallRequirement
from pip.utils import get_installed_distributions, dist_is_editable
from pip.utils.deprec... | d_option(
'-l', '--local',
action='store_true',
default=False,
help=('If in a virtualenv that has global access, do no | t list '
'globally-installed packages.'),
)
self.cmd_opts.add_option(
'--user',
dest='user',
action='store_true',
default=False,
help='Only output packages installed in user-site.')
cmd_opts.add_option(
'-... |
martinpopel/vowpal_wabbit | python/sklearn_vw.py | Python | bsd-3-clause | 15,244 | 0.002755 | # -*- coding: utf-8 -*-
# pylint: disable=line-too-long, unused-argument, invalid-name, too-many-arguments, too-many-locals
"""
Utilities to support integration of Vowpal Wabbit and scikit-learn
"""
import numpy as np
from pyvw import vw
import re
from scipy.sparse import csr_matrix
from sklearn.base import BaseEstim... | nore label inform | ation and just test
min_prediction (float): Smallest prediction to output
max_prediction (float): Largest prediction to output
sort_features (bool): turn this on to disregard order in which features have been defined. This will lead to
smaller cache sizes
lo... |
yinyanlong/iosig | src/analysis/single_trace_analysis.py | Python | bsd-3-clause | 8,008 | 0.006868 | #!/usr/bin/env python
"""
Single trace Analysis
"""
__author__ = "Yanlong Yin ([email protected])"
__version__ = "$Revision: 1.4$"
__date__ = "$Date: 02/08/2014 $"
__copyright__ = "Copyright (c) 2010-2014 SCS Lab, IIT"
__license__ = "Python"
import sys, os, string, getopt, gc, multiprocessing
from sig import *
from acc... | the first several lines
# Maybe the skipped lines are table heads
for i in range(int(sig._format_prop['skip_lines'])):
line = f.readlin | e()
# scan the file and put the access item into list
i = 0
j = 0
op_index = int(sig._format_prop['op'])
debugPrint ('op_index: ', op_index)
op = ''
# TODO: add while 1 loop here
for i in range(sig._range):
line = f.readline()
if not line:
break... |
RPGOne/Skynet | scikit-learn-0.18.1/examples/svm/plot_rbf_parameters.py | Python | bsd-3-clause | 8,016 | 0.001248 | '''
==================
RBF SVM parameters
==================
This example illustrates the effect of the parameters ``gamma`` and ``C`` of
the Radial Basis Function (RBF) kernel SVM.
Intuitively, the ``gamma`` parameter defines how far the influence of a single
training example reaches, with low values meaning 'far' a... | . The resulting model will
behave similarly to a linear model with a set of hyperplanes that separate the
centers of high density of any pair of two classes.
| For intermediate values, we can see on the second plot that good models can
be found on a diagonal of ``C`` and ``gamma``. Smooth models (lower ``gamma``
values) can be made more complex by selecting a larger number of support
vectors (larger ``C`` values) hence the diagonal of good performing models.
Finally one can ... |
taldcroft/datastack | test_pure_oo.py | Python | bsd-2-clause | 844 | 0.005924 | import sys
import sherpa.astro.ui as ui
import numpy as np
import datastack
x1 = np.arange(50)+2
y1 = x1**2
x2 = np.arange(10)
y2 = x2**1.9 * 2
x3 = np.arange(60)
y3 = x3**2.1 * 4
ds = datastack.DataStack()
ds[1].load_arrays(x1, y1) # ID required (autonumbering possible but potenti | al problems)
ds[2].load_arrays(x2, y2)
ds[3].load_arrays(x3, y3)
ds.set_source(ui.const1d.constID * ui.polynom1d.poly)
#ds.set_source('const1d.constID * polynom1d.poly')
ds.freeze('poly')
ds.thaw('poly.c0')
ds.thaw('poly.c1')
ds.thaw('poly.c2')
ds.thaw('const') |
ds[1].freeze('const')
ds[2].set_par('poly.c1', 0.45)
ds.set_par('const.c0', 1.0)
ds.set_par('const.integrate', False)
mins = ds.get_par('poly.c1.min')
vals = ds.get_par('poly.c1.val')
pars = ds.get_par('const.c0')
ds[2,3].link('poly.c0')
ds.unlink('poly.c0')
ds.fit()
ds.plot_fit_resid()
|
216software/Profiles | communityprofiles/userguides/urls.py | Python | mit | 261 | 0.007663 | from django.conf.urls import *
from userguides import views
urlpatterns = patterns('',
url(r'^$', views.about, | name="userguides-about"),
url(r'^FAQ/$', views.faq, name="userguides-FAQ"),
url(r'stay_in_touch$',views.stay, name="userguides-st | ay"),
)
|
procool/mygw | dist/brukva/demos/websockets/app.py | Python | bsd-2-clause | 1,650 | 0 | # Demo application for brukva
# In order to use:
# 1. $ python app.py
# 2. Open in your browser that supports websockets: http://localhost:8888/
# You should see text that says "Connected..."
# 3. $ curl http://localhost:8888/msg -d 'message=Hello!'
# You should see 'Hello!' in your browser
import brukva
im... | ation = tornado.web.Application([
(r'/', MainHandler),
(r'/msg', NewMessage),
(r'/track', MessagesCatcher),
])
if __name__ == '__main__':
http_server = tornado.httpserver.HTTPServer(appli | cation)
http_server.listen(8888)
tornado.ioloop.IOLoop.instance().start()
|
mirestrepo/voxels-at-lems | registration_eval/unused/compute_rigid_transform.py | Python | bsd-2-clause | 2,803 | 0.019979 | #!/usr/bin/env python
# encoding: utf-8
"""
Author: Isabel Restrepo
August 12, 2012
Compute rigid transformation between two point clounds using feature correspondances
"""
import os
import sys
import glob
import time
from optparse import OptionParser
from xml.etree.ElementTree import ElementTree
from vpcl_adaptor imp... | and output files should reside")
parser.add_option("--tgtRoot", action="store", type="string", dest="tgt_scene_root", help="root folder, this is where the .ply input and output files should reside")
parser.add_option("--basenameIn", action="store", type="string", dest="basename_in", help="basename of .ply file")
parser... | ion("-r", "--radius", action="store", type="int", dest="radius", help="radius (multiple of resolution)");
parser.add_option("-p", "--percent", action="store", type="int", dest="percentile", help="data percentile");
parser.add_option("-d", "--descriptor", action="store", type="string", dest="descriptor_type", help="name... |
trenton42/txbalanced | snippets/credit-soft-descriptor.py | Python | mit | 323 | 0.003096 | # bank_account_href is | the stored href for the BankAccount
# order_href is the stored href for the Order
bank_account = balanced.BankAccount.fetch(bank_account_href)
credit = bank_account.credit(
amount=100000,
description='Payout for order #1111',
appears_on_statement_as='GoodCo #1111',
order=order_href
) | |
Bulochkin/tensorflow_pack | tensorflow/contrib/keras/python/keras/callbacks.py | Python | apache-2.0 | 36,338 | 0.006632 | # 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... |
class TerminateOnNaN(Callback):
"""Callback that terminates training when a NaN loss is encountered."""
def __init__(self):
super(TerminateOnNaN, self).__init__()
def on_batch_end(self, batch, logs=None):
logs = logs or {}
loss = logs.get('loss')
| if loss is not None:
if np.isnan(loss) or np.isinf(loss):
print('Batch %d: Invalid loss, terminating training' % (batch))
self.model.stop_training = True
class ProgbarLogger(Callback):
"""Callback that prints metrics to stdout.
Arguments:
count_mode: One of "steps" or "samples".
... |
mjschust/conformal-blocks | experiments/non_sym_m0n.py | Python | mit | 1,075 | 0.009302 | from __future__ import division
import conformal_blocks.cbbundle as cbd
import cProfile, time, random
#First test
#----------
| #
def experiment():
"""
Computes the rank and divisor of conformal block bundles with random weights.
:return: Null
"""
rank = 5
level = 3
num_points = 10
tries = 100
| liealg = cbd.TypeALieAlgebra(rank, store_fusion=True, exact=False)
A_l = liealg.get_weights(level)
print("Weight", "Rank", "Divisor")
for i in range(tries):
weights = [random.choice(A_l) for i in range(num_points)]
if sum([sum(liealg._convert_funds_to_epsilons(wt)) for wt in weights]) % (ra... |
Byclosure/google-apis-client-generator | src/googleapis/codegen/utilities/maven_utils.py | Python | apache-2.0 | 2,224 | 0.010342 | #!/usr/bin/python2.7
"""Maven-related utilities for java packages."""
import re
def GetMavenArtifactId(api_name, package_path='', canonical_name='',
owner_domain='google.com'):
"""Returns the maven artifact id for a given api.
Args:
api_name: (str) The api name.
package_path: (st... | omain: (str) T | he owner domain.
Returns:
(str) The group id.
"""
if owner_domain == 'google.com':
return 'com.google.apis'
else:
return '.'.join(reversed(owner_domain.split('.')))
def GetMavenVersion(api, language_version):
"""Returns the maven version."""
if api.get('ownerDomain') == 'google.com':
retur... |
amaas-fintech/amaas-core-sdk-python | amaascore/core/reference.py | Python | apache-2.0 | 800 | 0.00375 | from __future__ import absolute_import, division, print_function, unicode_literals
from amaascore.core.amaas_model import AMaaSModel
class Reference(AMaaSModel):
def __init__(self, reference_value, reference_primary=False, *args, **kwargs):
self.reference_value = reference_value
self.reference_p... | self).__init__(*args, **kwargs)
@property
def reference_prim | ary(self):
if hasattr(self, '_reference_primary'):
return self._reference_primary
@reference_primary.setter
def reference_primary(self, value):
"""
Always convert to bool if the service/database returns 0 or 1
"""
if value is not None:
self._refer... |
smcoll/django-rules | rules/contrib/admin.py | Python | mit | 1,879 | 0.002129 | from django.contrib import admin
try:
from django.contrib.auth import get_permission_codename
except ImportError: # pragma: no cover
# Django < 1.6
def get_permission_codename(action, opts):
return '%s_%s' % (action, opts.object_name.lower())
class ObjectPermissionsModelAdminMixin(object):
d... | pts
codename = get_permission_codename('change', opts)
return request.user.has_perm('%s.%s' % (op | ts.app_label, codename), obj)
def has_delete_permission(self, request, obj=None):
opts = self.opts
codename = get_permission_codename('delete', opts)
return request.user.has_perm('%s.%s' % (opts.app_label, codename), obj)
class ObjectPermissionsInlineModelAdminMixin(ObjectPermissionsModel... |
kennedyshead/home-assistant | homeassistant/components/config/entity_registry.py | Python | apache-2.0 | 6,293 | 0.001748 | """HTTP views to interact with the entity registry."""
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.components import websocket_api
from homeassistant.components.websocket_api.const import ERR_NOT_FOUND
from homeassistant.components.websocket_api.decorators import (
async_re... | pi.websocket_command({vol.Required("type"): "config/entity_registry/list"})
async def websocket_list_entities(hass, connection, msg):
"""H | andle list registry entries command.
Async friendly.
"""
registry = await async_get_registry(hass)
connection.send_message(
websocket_api.result_message(
msg["id"], [_entry_dict(entry) for entry in registry.entities.values()]
)
)
@async_response
@websocket_api.websocke... |
austinhartzheim/gravel-api-python | src/gravel/__init__.py | Python | gpl-3.0 | 873 | 0 | import hmac
import hashlib
import requests
class GravelApi():
def __init__(self, address, shared_s | ecret):
self.address = address
self.shared_secret = shared_secret
self.tokens = []
def get_problem(self, problemid):
pass
def get_user(self, userid):
pass
def get_tokens(self, number=1):
pass
def _call_api_with_token(self):
pass
def _call... | = api
self.id = id
def get_replies(self):
pass
def post_reply(self):
pass
class GravelReply():
def __init__(self, api, id, data={}):
self.api = api
self.id = id
class GravelUser():
def __init__(self, api, id, data={}):
self.api = api
self.id... |
RedwoodAdmin/RedwoodFramework | expecon/tests.py | Python | bsd-2-clause | 1,415 | 0.028269 | from django.test import TestCase
from django.contrib.auth.models import User
from models import *
import random
import datetime
from decimal import *
alphabet = [chr(i) for i in range(97,123)]
def random_name():
return ''.join([random.choice(alphabet) for i in range (10)])
def random_date():
random_second = rando... | te.today(),
gender=random.choice(GENDER_CHOICES)[0],
field=random.choice(FIELD_CHOICES)[0])
for i in range(2):
experimenter = random.choice(User.objects.all())
Experiment.objects.create(
public_name=random_name(),
private_name=random_name(),
experimenter=experimenter)
for i in range(5):
... | ndom.random()).quantize(Decimal('0.1')),
required_subjects=random.randint(6, 12),
extra_subjects=random.randint(1, 5),
experiment=random.choice(Experiment.objects.all()))
def test_all(self):
self.assertEqual(len(Subject.objects.all()), 20)
|
tleonhardt/Python_Interface_Cpp | cython/wrap_c/setup.py | Python | mit | 193 | 0.005181 | # coding=utf-8
from setuptools import setup |
from Cython.Build import cythonize
setup(
name="cyfib",
ext_module | s=cythonize('cyfib.pyx', compiler_directives={'embedsignature': True}),
)
|
thonkify/thonkify | src/lib/future/backports/urllib/request.py | Python | mit | 96,679 | 0.00061 | """
Ported using Python-Future from the Python 3.3 standard library.
An extensible library for opening URLs using a variety of protocols
The simplest way to use this module is to call the urlopen function,
which accepts a string containing a URL or a Request object (described
below). It opens the URL and returns the... | nd 307 redirect errors, and the HTTPDigestAuthHandler
deals with digest authentication.
u | rlopen(url, data=None) -- Basic usage is the same as original
urllib. pass the url and optionally data to post to an HTTP URL, and
get a file-like object back. One difference is that you can also pass
a Request instance instead of URL. Raises a URLError (subclass of
IOError); for HTTP errors, raises an HTTPError, wh... |
soylentdeen/BlurryApple | Tools/VLTTools.py | Python | gpl-2.0 | 12,298 | 0.00309 | import os
import paramiko
import numpy
import pyfits
import warnings
import select
class VLTConnection( object ):
"""
VLTConnection: This object allows python to log into a computer
running the VLT SPARTA Light software and do the following:
- Send a new flat pattern to the DM
- Retrieve d... | ndCommand(command)
if not(self.sim):
self.ftp.get(self.remotepath+name, self.localpath+name)
return pyfits.getdat | a(self.localpath+name)
def set_gain(self, gain):
termA = numpy.array([-1], dtype='float32')
termB = gain*(numpy.array([-1.0, 0.0], dtype='float32'))
self.CDMS.maps["HOCtr.TERM_A"].replace(termA)
self.CDMS.maps["HOCtr.TERM_B"].replace(termB)
self.CDMS.maps["HOCtr.TERM_A"].wri... |
rizumu/pinax-invitations | pinax/invitations/migrations/0001_initial.py | Python | mit | 1,824 | 0.003289 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.timezone
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('account', '0001_initial'),
migrations.swappable_dependency(settings.AUT... | tegerField(default=0)),
('user', models.OneToOneField(to=settings.AUTH_USER_MODEL)),
],
options={
},
bases | =(models.Model,),
),
migrations.CreateModel(
name='JoinInvitation',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('message', models.TextField(null=True)),
('sent', model... |
uclouvain/osis_louvain | base/tests/views/group_element_years/test_detach.py | Python | agpl-3.0 | 5,223 | 0.002681 | ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as u | niversities, faculties, institutes and professional schools.
# The core business involves the administration of students, teachers,
# courses, programs and so on.
#
# Copyright (C) 2015-2017 Université catholique de Louvain (http://ww | w.uclouvain.be)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the ... |
ddico/odoo | addons/base_vat/models/res_partner.py | Python | agpl-3.0 | 19,705 | 0.0034 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import datetime
import string
import re
import stdnum
from odoo import api, models, tools, _
from odoo.tools.misc import ustr
from odoo.exceptions import ValidationError
_eu_country_vat = {
'GR': 'EL'
}
_eu_co | untry_vat_inverse = {v: k for k, v in _eu_country_vat.items()}
_ref_vat = {
'al': 'ALJ91402501L',
'ar': 'AR200-5536168-2 or 20055361682',
'at': 'ATU12345675',
'au': '83 914 571 673',
'be': 'BE0477472701',
'bg': 'BG1234567892',
'ch': 'CHE-123.456.788 TVA or CH TVA 123456', # Swiss by Yannic... | 3432-1 or CO213.123.432-1',
'cy': 'CY10259033P',
'cz': 'CZ12345679',
'de': 'DE123456788',
'dk': 'DK12345674',
'do': 'DO1-01-85004-3 or 101850043',
'ec': 'EC1792060346-001',
'ee': 'EE123456780',
'el': 'EL12345670',
'es': 'ESA12345674',
'fi': 'FI12345671',
'fr': 'FR23334175221'... |
subodhchhabra/airflow | tests/contrib/operators/test_dataflow_operator.py | Python | apache-2.0 | 7,353 | 0.000544 | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... |
expected_options = {
'project': 'test',
'staging_location': 'gs://test/staging',
'output': 'gs://test/output',
'labels': {'foo': 'bar', 'airflow-version': TEST_VERSION}
}
gcs_download_hook.assert_called_once_with(PY_FILE)
start_python_hook... | mock.ANY, PY_OPTIONS)
self.assertTrue(self.dataflow.py_file.startswith('/tmp/dataflow'))
class DataFlowJavaOperatorTest(unittest.TestCase):
def setUp(self):
self.dataflow = DataFlowJavaOperator(
task_id=TASK_ID,
jar=JAR_FILE,
... |
furlow/QifSwap | QifSwap.py | Python | unlicense | 1,496 | 0.010027 | import sys
import os
from PySide.QtCore import *
from PySide.QtGui import *
__appname__ = "Qifswap"
def swap_outflows_and_inflows(qif_filename):
qif = open(qif_filename, 'r+')
data = qif.read()
data = data.replace('\nT','\nTemp')
data = data.replace('\nTemp-','\nT')
data = data.replace('\nTemp', '... | parent = None):
super(Program, self).__init__(parent)
self.setWindowTitle(__appname__)
#Create button for opening credit card file
self.open_fi | le_button = QPushButton("Open File")
#Align the widget in the container
layout = QVBoxLayout()
layout.addWidget(self.open_file_button)
self.setLayout(layout)
#connect to functions for saving
self.open_file_button.clicked.connect(self.openQifFile)
def openQifFile(s... |
coddingtonbear/django-measurement | tests/forms.py | Python | mit | 556 | 0 | from django import forms
from django_measu | rement.forms import MeasurementField
from tests.custom_measure_base import DegreePerTime, Temperature, Time
from tests.models import MeasurementTestModel
class MeasurementTestForm(forms.ModelForm):
class Meta:
model = MeasurementTestModel
exclude = []
class LabelTestForm(forms.Form):
simple ... | simple = MeasurementField(Time)
class BiDimensionalLabelTestForm(forms.Form):
simple = MeasurementField(DegreePerTime)
|
joopert/home-assistant | homeassistant/components/familyhub/camera.py | Python | apache-2.0 | 1,553 | 0.000644 | """Family Hub camera for Samsung Refrigerators."""
import logging
import voluptuous as vol
from homeassistant.components.camera import Camera, PLATFORM_SCHEMA
from homeassistant.const import CONF_IP_ADDRESS, CONF_NAME
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helper... | ubCam(address, hass.loop, session)
async_add_entities([FamilyHubCamera(name, family_hub_cam)], True)
class FamilyHubCamera(Camera):
"""The representation of a Family Hub camera.""" |
def __init__(self, name, family_hub_cam):
"""Initialize camera component."""
super().__init__()
self._name = name
self.family_hub_cam = family_hub_cam
async def async_camera_image(self):
"""Return a still image response."""
return await self.family_hub_cam.asyn... |
rgayon/plaso | tests/parsers/sqlite_plugins/gdrive.py | Python | apache-2.0 | 2,876 | 0.00209 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the Google Drive database plugin."""
from __future__ import unicode_literals
import unittest
from plaso.formatters import gdrive as _ # pylint: disable=unused-import
from plaso.lib import definitions
from plaso.parsers.sqlite_plugins import gdrive
from te... | # 10 files mount | ing to:
# 20 Cloud Entries (two timestamps per entry).
# 10 Local Entries (one timestamp per entry).
local_entries = []
cloud_entries = []
for event in storage_writer.GetEvents():
event_data = self._GetEventDataOfEvent(storage_writer, event)
if event_data.data_type == 'gdrive:sna... |
bartnijssen/RVIC | rvic/core/convolution_wrapper.py | Python | gpl-3.0 | 1,407 | 0 | """
convolution_wrapper.py
ctypes wrapper for rvic_convolution.c
gcc -shared -o rvic_convolution.so rvic_convolution.c
"""
import os
import numpy as np
import ctypes
SHAREDOBJECT = 'rvic_convolution.so'
LIBPATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../'))
try:
_convolution = np.ctypesli... | t,
ctypes.c_int,
ctypes.c_int,
np.ctypeslib.ndpointer(np.int32),
np.ctypeslib.ndpointer(np.int32),
np.ctypeslib.ndpointer(np.int32),
np.ctypeslib.ndpointer(np.int32),
np.ctypeslib.ndpointer(np.float64),
np.ctypeslib.ndpointer(np.float64),
... | t64)]
_convolution.convolve.argtypes = _args
_convolution.convolve.restype = None
def rvic_convolve(*args):
"""args:
nsources,
noutlets,
subset_length,
xsize,
source2outlet_ind,
source_y_ind,
source_x_ind,
source_time_offset,
unit_hydrograph,
... |
HaebinShin/tensorflow | tensorflow/python/ops/nn_batchnorm_test.py | Python | apache-2.0 | 24,393 | 0.006559 | # 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... | on=False, we only
# test for scale_after_normalization=True.
for scale_after_normalization in [True, False]:
for v in [1, 2]:
self._testBatchNormGradient(3, "beta", s | cale_after_normalization, True,
v)
def testBatchNormGammaGradient(self):
# If scale_after_normalization is False, backprop for gamma in v1
# will be 0. In versi |
bhrzslm/uncertainty-reasoning | my_engine/others/GrMPy/lib/GrMPy/Examples/Discrete/BNET/Inference/Exact/Tut_BNET_maxsum.py | Python | mit | 3,090 | 0.00356 | # Author: Almero Gouws <[email protected]>
"""
This is a tutorial on how to create a Bayesian network, and perform
exact MAX-SUM inference on it.
"""
"""Import the required numerical modules"""
import numpy as np
"""Import the GrMPy modules"""
import models
import inference
import cpds
if __name__ == '_... | [W] = cpds.TabularCPD(CPT)
"""Create the Bayesian network"""
net = models.bnet(dag, node_sizes, node_cpds=node_cpds)
"""
Intialize the BNET's inference engine to use EXACT inference
by setting exact=True.
"""
net.init_inferenc | e_engine(exact=True)
"""Define observed evidence ([] means that node is unobserved)"""
evidence = [None, 0, None, None]
"""Execute the sum-product algorithm"""
# net.enter_evidence(evidence)
mlc = net.max_sum(evidence)
"""
mlc contains the most likely configuaration for all the n... |
sharad/calibre | src/calibre/gui2/tweak_book/undo.py | Python | gpl-3.0 | 8,104 | 0.002098 | #!/usr/bin/env python
# vim:fileencoding=utf-8
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
import shutil
from PyQt5.Qt import (
QAbstractListModel, Qt, QModelIndex... | merate(self.states):
if state.container is container:
return self.label_for_row(i)
@property
def current_container(self) | :
return self.states[self.pos].container
@property
def previous_container(self):
return self.states[self.pos - 1].container
def open_book(self, container):
self.beginResetModel()
self.states = [State(container)]
self.pos = 0
self.endResetModel()
def tru... |
microelly2/Animation | mathplotlibNode.py | Python | gpl-2.0 | 10,507 | 0.052441 | # -*- coding: utf-8 -*-
#-------------------------------------------------
#-- animation workbench
#--
#-- microelly 2016 v 0.1
#--
#-- GNU Lesser General Public License (LGPL)
#-------------------------------------------------
from __future__ import unicode_literals
__vers__="08.04.2016 0.4"
import sys
import os
im... | lot(x,y1,label=label)
# exec("self.obj.source"+nr+"Values=y1")
say("DDone")
if self.obj.useNumpy:
self.obj.outTime=self.obj.sour | ceNumpy.outTime
FreeCAD.activeDocument().recompute()
for i in range(10):
if eval("self.obj.useOut"+str(i)):
try:
y=self.obj.sourceNumpy.getPropertyByName('out'+str(i))
label=self.obj.sourceNumpy.getPropertyByName('label'+str(i))
if label=='':
label="numpy " + str(i)
# if x ... |
wwright2/dcim3-angstrom1 | sources/bitbake/lib/bb/ui/crumbs/hoblistmodel.py | Python | mit | 35,789 | 0.002515 | #
# BitBake Graphical GTK User Interface
#
# Copyright (C) 2011 Intel Corporation
#
# Authored by Joshua Lock <[email protected]>
# Authored by Dongxiao Xu <[email protected]>
# Authored by Shane Wang <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it unde... | COL_RCP, COL_BINB, COL_INC, COL_FADE_INC, COL_FONT, COL_FLIST) = range(15)
__gsignals__ = {
"package-selection-changed" : (gobject.SIGNAL_RUN | _LAST,
gobject.TYPE_NONE,
()),
}
__toolchain_required_packages__ = ["packagegroup-core-standalone-sdk-target", "packagegroup-core-standalone-sdk-target-dbg"]
def __init__(self):
self.rprov_pkg = {}
gtk.ListStore.__init__ (self... |
blynn/spelltapper | app/spelltapper.py | Python | gpl-3.0 | 15,729 | 0.047428 | import urllib
import logging
import random
from datetime import datetime
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.ext.db import Key
class Move(db.Model):
move = d... | key_name = "g:" + duelid,
level = level,
now_turn = 0,
received_count = 0)
duel.put()
self.response.out.write(duelid)
| logging.info("Response: " + duelid)
return
gamename = self.request.get("g")
if "f" == cmd:
logging.info("Game " + gamename + " finished.")
nonce = self.request.get("i")
def restate_user():
user = db.get(Key.from_path("User", "n:" + nonce))
if not user:
return None
user.atime = d... |
krisys/SpojBot | src/spojbot/bot/management/commands/migrate_suggestions.py | Python | mit | 707 | 0.005658 | from django.core.management.base import BaseCommand
from bot.models import *
from datetime import datetime, timedelta, date
class Command(BaseCommand):
args = 'No args'
help = 'Move problems from SuggestedProblem to ProblemSuggestion'
def handl | e(self, *args, **options):
for spojuser in SpojUser.objects.all():
user_belongs_to = [x.group for x in GroupMember.objects.filter(user=spojuser.user)]
for problem in SuggestedProblem.objects.filter(group__in=user_belongs_to).order_by('timestamp'):
try:
| ProblemSuggestion.objects.create(user=spojuser.user, problem=problem.problem)
except:
pass
|
ML-KULeuven/socceraction | tests/data/test_load_opta.py | Python | mit | 8,173 | 0.000856 | import os
import pytest
from py.path import local
from socceraction.data import opta as opta
from socceraction.data.opta import (
OptaCompetitionSchema,
OptaEventSchema,
OptaGameSchema,
OptaPlayerSchema,
OptaTeamSchema,
)
def test_create_opta_json_loader(tmpdir: local) -> None:
"""It should ... | d}.json",
"f24": "match-{season_id}-{competition_id}-{game_id}.json",
},
)
def test_competitions(self) -> None:
df_competitions = self.loader.competitions()
assert len(df_competitions) > 0
OptaCompetitionSchema.validate(df_competitions)
| def test_games(self) -> None:
df_games = self.loader.games(8, 2017)
assert len(df_games) == 1
OptaGameSchema.validate(df_games)
def test_teams(self) -> None:
df_teams = self.loader.teams(918893)
assert len(df_teams) == 2
OptaTeamSchema.validate(df_teams)
def... |
mais4719/PyLuxafor | pyluxafor/cli.py | Python | gpl-3.0 | 9,126 | 0.00263 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Simple command line interface to pyluxafor.
"""
from __future__ import division, print_function, absolute_import
import argparse
import sys
import logging
from pyluxafor import Devices
from pyluxafor import Wave, Pattern, Leds
from pyluxafor import __version__
__auth... | help='Repeats [1-255].')
def wave(args):
args.pattern = args.wave.lower()
if args.pattern not in Wave._fields:
return 'Error: {} is not a valid wave type.'.format(args.pattern)
if args.speed < 0 or args.speed > 255:
return 'Error: Speed needs to be an integer between 0 and 255.'
if ... | e a integer between 1 and 255.'
with Devices().first as d:
d.wave(color=args.color, wave_type=getattr(Wave, args.wave), speed=args.speed, repeats=args.repeats)
return 'Running a {} wave with color {} and speed {}, {} times.'.format(args.wave, args.color,
... |
SauloAislan/ironic | ironic/tests/unit/drivers/test_generic.py | Python | apache-2.0 | 4,019 | 0 | # Copyright 2016 Red Hat, Inc.
| #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in complianc | e 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 ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.