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 |
|---|---|---|---|---|---|---|---|---|
pramasoul/pyboard-fun | tone.py | Python | mit | 1,739 | 0.008626 | import math
from pyb import DAC, micros, elapsed_micros
def tone1(freq):
t0 = micros()
dac = DAC(1)
w | hile True:
theta = 2*math.pi*float(elapsed_micros(t0))*freq/1e6
fv = math.sin(theta)
v = int(126.0 * fv) + 127
#print("Theta %f, sin %f, scaled %d" % (theta, fv, v))
#delay(100)
dac.write(v)
def tone2(freq):
t0 = micros()
dac = DAC(1)
omega = 2 * math.pi * fr... | theta = omega*float(elapsed_micros(t0))
fv = math.sin(theta)
v = int(126.0 * fv) + 127
#print("Theta %f, sin %f, scaled %d" % (theta, fv, v))
#delay(100)
dac.write(v)
def tone3(freq, l_buf=256):
dac = DAC(1)
dtheta = 2 * math.pi / l_buf
scale = lambda fv: int(1... |
Kulmerov/Cinnamon | files/usr/share/cinnamon/cinnamon-settings-users/cinnamon-settings-users.py | Python | gpl-2.0 | 37,177 | 0.00382 | #!/usr/bin/env python2
import sys, os
import pwd, grp
from gi.repository import Gtk, GObject, Gio, GdkPixbuf, AccountsService
import gettext
import shutil
import PIL
from PIL import Image
from random import randint
import re
import subprocess
gettext.install("cinnamon", "/usr/share/locale")
(INDEX_USER_OBJECT, INDEX... | __()
try:
self.set_modal(True)
self.set_skip_taskbar_hint(True)
self.set_skip_p | ager_hint(True)
self.set_title("")
table = DimmedTable()
table.add_labels([label])
self.entry = Gtk.Entry()
self.entry.set_text(value)
self.entry.connect("changed", self._on_entry_changed)
table.add_controls([self.entry])
... |
googleapis/python-documentai | samples/snippets/process_document_splitter_sample.py | Python | apache-2.0 | 3,497 | 0.001716 | # Copyright 2020 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | t from the document splitter processor:
# https://cloud.google.com/document-ai/docs/processors-list#processor_doc-splitter
# This processor only provides text for the document and information on how
# to split the document on logical boundaries. To identify and ext | ract text,
# form elements, and entities please see other processors like the OCR, form,
# and specalized processors.
document = result.document
print(f"Found {len(document.entities)} subdocuments:")
for entity in document.entities:
conf_percent = "{:.1%}".format(entity.confidence)
p... |
openstack/glance | glance/version.py | Python | apache-2.0 | 731 | 0 | # Copyright 2 | 012 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... | tributed 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 pbr.version
version_info = pbr.version.VersionInfo('glance')
version_string = version_info.ve... |
cswaroop/airflow | airflow/contrib/hooks/__init__.py | Python | apache-2.0 | 264 | 0 | '''
Imports the hooks dynamically while keeping the package API clean,
abstracting the underlying modules
'''
from airflow.utils import import_module_attrs as _import_mod | ule_attrs
_hooks = {
'ftp_hook': | ['FTPHook'],
}
_import_module_attrs(globals(), _hooks)
|
stharrold/demo | demo/app_template/template.py | Python | mit | 1,935 | 0.001034 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
r"""Application template.
"""
# Import standard packages.
import inspect
import logging
# Import installed packages.
import matplotlib.pyplot as plt
import seaborn as sns
# Import local packages.
from .. import utils
# Define module exports:
__all__ =... | arguments passed.
here = inspect.stack()[0].function
frame = inspect.currentframe()
(args, *_, values) = inspect.getargvalues(frame)
logger.info(here+": Argument values: {args_values}".format(
args_values=[(arg, values[arg]) for arg in sorted(args)]))
# Log the code version from util.... | |
PatrickCmd/django_local_library | catalog/forms.py | Python | apache-2.0 | 776 | 0.016753 | from django import f | orms
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
import datetime # for checking renewal date range
clas | s RenewBookForm(forms.Form):
renewal_date = forms.DateField(help_text="Enter a date between now and 4 weeks (default 3). ")
def clean_renewal_date(self):
data = self.cleaned_data['renewal_date']
# check date is not in past
if data < datetime.date.today():
raise ValidationError(_('Invalid date - renewal in... |
iocanto/bug-python-libraries | ButtonEvent.py | Python | gpl-3.0 | 2,246 | 0.026269 | '''
*******************************************************************************
* ButtonEvent.py 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 o... | 257 : "BUTTON_SELECT" ,
258 : "BUTTON_HOTKEY_1",
259 : "BUTTON_HOTKEY_2",
260 : "BUTTON_HOTKEY_3",
261 : "BUTTON_HOTKEY_4",
262 : "BUTTON_RIGHT" ,
263 : "BUTTON_LEFT" ,
264 ... | 265 : "BUTTON_DOWN" ,
}[self.__button]
def setAction(self, action):
self.__action = action
def setButton(self, button):
self.__button = button
... |
derrickyoo/python-jumpstart | apps/09_real_estate_data_miner/concept_dicts.py | Python | mit | 933 | 0.005359 | lookup = {}
lookup = dict()
lookup = {'age': 42, 'loc': 'Italy'}
lookup = dict(age=42, loc='Italy')
print(lookup)
print(lookup['loc'])
lookup['cat'] = 'cat'
if 'cat' in lookup:
print(lookup['cat'])
class Wizard:
# This actually creates a key value dictionary
def __init__(self, name, level... | structures
# Here is another example
import collections
User = collections.namedtuple('User', 'id, name, email')
users = [
User(1, 'user1', 'user1@test.com'),
User(2, 'user2', 'user2@test.com'),
User(3, | 'user3', 'user3@test.com'),
]
lookup = dict()
for u in users:
lookup[u.email] = u
print(lookup['user2@test.com']) |
nirenzang/Serpent-Pyethereum-Tutorial | pyethereum/ethereum/slogging.py | Python | gpl-3.0 | 10,541 | 0.001613 | import logging
import json
import textwrap
from json.encoder import JSONEncoder
from logging import StreamHandler, Formatter, FileHandler
from ethereum.utils import bcolors, is_numeric
DEFAULT_LOGLEVEL = 'INFO'
JSON_FORMAT = '%(message)s'
PRINT_FORMAT = '%(levelname)s:%(name)s\t%(message)s'
FILE_PREFIX = '%(asctime... | _other_handlers:
self._saved_handlers = rootLogger.handlers[:]
rootLogger.handlers = []
def pop_records(self):
# onl | y returns records on the first call
r = self._records[:]
self._records = []
try:
log_listeners.remove(self._add_log_record)
except ValueError:
pass
if self._saved_config:
configure(**self._saved_config)
self._saved_config = None
... |
my-zhang/nand2tetris | ch10-frontend/jcompiler/cli.py | Python | mit | 709 | 0.026798 |
import re
import os
import sys
from jcompiler.token import tokenize
from jcompiler.parse import Parser
import jcompiler.xmlutil as xmlutil
def remove_comments(s):
return re.sub(r'(\s*//.*)|(\s*/\*(.|\n)*?\*/\s*)', '', s)
if __name__ == '__ma | in__':
if len(sys.argv) < 2:
print 'a input file is needed'
sys.exit(1)
fname = sys.argv[1]
if not os.path.isfile(fname):
print 'not a valid file path: %s' % fname
sys.exit(1)
with open(fname, 'r') as f:
source = remove_comments(f.read())
par... | tree()
# print tree
print xmlutil.dump_parse_tree(tree)
|
rootio/rootio_web | alembic/versions/4d0be367f095_station_timezone.py | Python | agpl-3.0 | 644 | 0.01087 | """add timezone to each station
Revision ID: 4d0be367f09 | 5
Revises: 6722b0ef4e1
Create Date: 2014-03-19 16:43:00.326820
"""
# revision identifiers, used by Alembic.
revision = '4d0be367f09 | 5'
down_revision = '6722b0ef4e1'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('radio_station', sa.Column('timezone', sa.String(length=32), nullable=True))
### end Alembic commands ###
def downgrade():
### com... |
ipanova/pulp_ostree | common/setup.py | Python | gpl-2.0 | 321 | 0 | from setuptools import setup, find_packages
setup(
name='pulp_ostree_common',
version='1.0.0a2',
packages=find_packages(),
url='http://www.pulpproject.or | g',
license='GPLv2+',
author='Pulp Team',
author_email='pulp-list@redhat.com',
description='common code for | pulp\'s ostree support',
)
|
9and3r/RPi-InfoScreen-Kivy | screens/mythtv/screen.py | Python | gpl-3.0 | 6,297 | 0.000476 | import os
import sys
import datetime as dt
import json
from itertools import groupby
from kivy.properties import (StringProperty,
DictProperty,
ListProperty,
BooleanProperty)
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.sc... | g = False
self.rec_timer = None
self.status_timer = None
self.be = None
self.recs = None
def on_enter(self):
# We only update when we enter the screen. No need for regular updates.
self.getRecordings()
self.drawScreen()
self.checkRecordingStatus()
... | def on_leave(self):
pass
def cacheRecs(self, recs):
"""Method to save local copy of recordings. Backend may not be online
all the time so a cache enables us to display recordings if if we
can't poll the server for an update.
"""
with open(self.cacheFile, 'w') a... |
sevas/sublime_cmake_snippets | compiler_completions.py | Python | mit | 1,676 | 0.001193 | import sublime_plugin
from cmakehelpers.compilerflags import clang, gcc
from cmakehelpers.compilerflags import find_completions
COMPLETION_DATABASES = dict(
clang=dict(loader=clang, database=None),
gcc=dict(loader=gcc, database=None))
def log_message | (s):
print("CMakeSnippets: {0}".format(s))
def load_completion_data | bases():
global COMPLETION_DATABASES
for compiler_name, database_info in COMPLETION_DATABASES.iteritems():
loader = database_info['loader']
completion_database = loader.load_compiler_options_database()
log_message("Loading {0} options database: {1} entries".format(compiler_name, len(comp... |
mvaled/sentry | src/sentry/models/projectownership.py | Python | bsd-3-clause | 5,206 | 0.000768 | from __future__ import absolute_import
import operator
from django.db import models
from django.db.models import Q
from djan | go.utils import timezone
from sentry.db.models import Model, sane_repr
from sentry.db.models.fields import FlexibleForeignKey, JSONField
from sentry.ownership.grammar import load_schema
from functools import reduce
class ProjectOwnership(Model):
__core__ = True
project = FlexibleForeignKey("sentry.Project",... | ue=True)
raw = models.TextField(null=True)
schema = JSONField(null=True)
fallthrough = models.BooleanField(default=True)
auto_assignment = models.BooleanField(default=False)
date_created = models.DateTimeField(default=timezone.now)
last_updated = models.DateTimeField(default=timezone.now)
is... |
Amechi101/concepteur-market-app | venv/lib/python2.7/site-packages/PIL/ImageEnhance.py | Python | mit | 2,760 | 0 | #
# The Python Imaging Library.
# $Id$
#
# image enhancement classes
#
# For a background, see "Image Processing By Interpolation and
# Extrapolation", Paul Haeberli and Douglas Voorhies. Available
# at http://www.sgi.com/grafica/interp/index.html
#
# History:
# 1996-03-23 fl Created
# 2009-06-16 fl Fixed mean calcu... | s an enhanced image.
:param factor: A floating point value controlling the enhancement. |
Factor 1.0 always returns a copy of the original image,
lower factors mean less color (brightness, contrast,
etc), and higher values more. There are no restrictions
on this value.
:rtype: :py:class:`~PIL.Image.Image`
... |
clara-labs/spherecluster | examples/document_clustering.py | Python | mit | 8,298 | 0.00229 | from __future__ import print_function
from sklearn.datasets import fetch_20newsgroups
from sklearn.decomposition import TruncatedSVD
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import Normalizer
from sklearn import metrics
import nu... | #############
# Mixture of von Mises Fisher clustering (soft)
vmf_soft = VonMisesFisherMixture(n_clusters=true_k, posterior_type='soft',
init='random-class', n_init=20, force_weights=np.ones((true_k,))/true_k)
print("Clustering with %s" % vmf_soft)
vmf_soft.fit(X)
print()
print('weights: {}'.format(vmf_soft.weight... | etrics.completeness_score(labels, vmf_soft.labels_))
print("V-measure: %0.3f" % metrics.v_measure_score(labels, vmf_soft.labels_))
print("Adjusted Rand-Index: %.3f"
% metrics.adjusted_rand_score(labels, vmf_soft.labels_))
print("Adjusted Mututal Information: %.3f"
% metrics.adjusted_mutual_info_score(labels... |
jpfairbanks/streaming | server.py | Python | bsd-3-clause | 286 | 0.01049 | import msgpackrpc
import time
class SumServer(object):
def sum(self, x, y | ):
return x + y
def sleepy_sum(self, x, y):
time.sleep(1)
return x + y
server = msgpackrpc.Server(SumServer())
server.listen(msgpackrpc.Add | ress("localhost", 18800))
server.start()
|
Bradfield/algorithms-and-data-structures | book/deques/palindromes_test.py | Python | cc0-1.0 | 328 | 0 | import unittest
| from palindromes import is_palindrome
cases = (
('lsdkjfskf', False),
('radar', True),
('racecar', True),
)
class TestCorrectness(unittest.TestCase):
def test_identifies_palindromes(self):
for word, expectation in cases:
self.assertEqual(is_palindrome(word), expectati | on)
|
melvin0008/pythoncodestrial | first.py | Python | apache-2.0 | 1,107 | 0.01897 | import ply.lex as lex
import re
tokens = (
'LANGLE', # <
'LANGLESLASH', # </
'RANGLE', # >
'EQUAL', # =
'STRING', # "hello"
'WORD') # Welcome!
state = (
("htmlcomment", "exclusive"),
)
t_ignore = ' '
def t_htmlcomment(token):
r'<!--'
token.lexer.begin('htmlcomment')
def t_htmlcommen... | f t_LANGLE(token):
r'<'
return token
def t_RANGLE(token):
r'>'
return token
def t_EQUAL(token):
r'='
return token
def t_STRING(token):
r'"[^"]*"'
token.value = token.value[1:-1] # dropping off the double quotes
return token
def t_WORD(token):
| r'[^ <>\n]+'
return token
webpage = "This is <!-- <b>my --> woag</b> webpage"
htmllexer = lex.lex()
htmllexer.input(webpage)
while True:
tok = htmllexer.token()
if not tok: break
print(tok) |
owlabs/incubator-airflow | tests/contrib/operators/test_gcp_bigtable_operator.py | Python | apache-2.0 | 31,128 | 0.001542 | # -*- 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
#... | odes=None,
cluster_storage_type=None,
instance_display_name=None,
instance_id=INSTANCE_ID,
instance_labels=None,
instance_type=None,
main_cluster_id=CLUSTER_ID,
main_cluster_zone=CLUSTER_ZONE,
| project_id=PROJECT_ID,
replica_cluster_id=None,
replica_cluster_zone=None,
timeout=None
)
class BigtableClusterUpdateTest(unittest.TestCase):
@parameterized.expand([
('instance_id', PROJECT_ID, '', CLUSTER_ID, NODES),
('cluster_id', PROJECT_ID, INSTAN... |
coddingtonbear/django-mailbox | django_mailbox/south_migrations/0009_remove_references_table.py | Python | mit | 2,520 | 0.007143 | import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Removing M2M table for field references on 'Message'
db.delete_table('django_mailbox_message_references')
def backwards(self... | s.related.ForeignKey', [], {'blank': 'True', 'related_name': "'replies'", 'null': 'True', 'to': "orm['django_mailbox.Message']"}),
'mailbox': ('django.db | .models.fields.related.ForeignKey', [], {'related_name': "'messages'", 'to': "orm['django_mailbox.Mailbox']"}),
'message_id': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'outgoing': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'processed':... |
flaviogrossi/sockjs-cyclone | sockjs/cyclone/transports/jsonp.py | Python | mit | 3,786 | 0.003698 | import urllib
from cyclone.web import asynchronous
from twisted.python import log
from sockjs.cyclone import proto
from sockjs.cyclone.transports import pollingbase
class JSONPTransport(pollingbase.PollingTransportBase):
name = 'jsonp'
@asynchronous
def get(self, session_id): ... | self.request.body.decode('utf-8')
data = self.request.body
ctype = self.reque | st.headers.get('Content-Type', '').lower()
if ctype == 'application/x-www-form-urlencoded':
if not data.startswith('d='):
log.msg('jsonp_send: Invalid payload.')
self.write("Payload expected.")
self.set_status(500)
return
... |
darioizzo/piranha | tools/benchmark.py | Python | gpl-3.0 | 911 | 0.023052 | import sys
import numpy as np
from scipy import stats
import subprocess as sp
import datetime
import socket
import os
exec_name = sys.argv[1]
max_t = int(sys.argv[2])
ntries = 5
tot_timings = []
for t_idx in r | ange(1,max_t + 1):
cur_timings = []
for _ in range(ntries):
# Run the process.
p = sp.Popen([exec_name,str(t | _idx)],stdout=sp.PIPE,stderr=sp.STDOUT)
# Wait for it to finish and get stdout.
out = p.communicate()[0]
# Parse the stderr in order to find the time.
out = out.split(bytes('\n','ascii'))[1].split()[0][0:-1]
cur_timings.append(float(out))
tot_timings.append(cur_timings)
tot_timings = np.array(tot_timings)
... |
hanlind/nova | nova/tests/functional/api/client.py | Python | apache-2.0 | 15,004 | 0.000267 | # Copyright (c) 2011 Justin Santa Barbara
#
# 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 applicab... | , response=None, message=None):
if not message:
message = "Authentication error"
super(OpenStackApiAuthenticationException, self).__init__(message,
response)
class OpenStackApiAuthori | zationException(OpenStackApiException):
def __init__(self, response=None, message=None):
if not message:
message = "Authorization error"
super(OpenStackApiAuthorizationException, self).__init__(message,
response)
class O... |
peterstace/project-euler | OLD_PY_CODE/project_euler_old_old/134/134.py | Python | unlicense | 858 | 0.006993 | from number_theory import int_pow, prime_sieve, prime, mod_exp
from itertools import count
from math import ceil, sqrt
def find_n(p1, p2):
"""
Finds n such that for consecutive primes p1 and p2 (p2 > p1), n is
divisible by p2 and the last digits of n are formed by p1.
"""
len_p1 = len(str(p1))
... | mes[-1] + 2
while not prime(p):
p += 2
primes += [p]
primes = primes[2:]
summation = 0
for p_i in range(len(primes) - 1):
n = find_n(primes[p_i], primes[p_i + 1])
summation += n
print(summation) | |
haxwithaxe/qutebrowser | tests/unit/browser/test_webelem.py | Python | gpl-3.0 | 30,783 | 0 | # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2014-2016 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
#
# This file is part of qutebrowser.
#
# qutebrowser 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 S... | ."""
if strategy != QWebElement.ComputedStyle:
raise ValueError("styleProperty called with strategy != "
| "ComputedStyle ({})!".format(strategy))
return style_dict[name]
elem.styleProperty.side_effect = _style_property
wrapped = webelem.WebElementWrapper(elem)
return wrapped
class SelectionAndFilterTests:
"""Generator for tests for TestSelectionsAndFilters."""
# A mapping... |
mmottahedi/neuralnilm_prototype | scripts/e362.py | Python | mit | 5,901 | 0.009659 | from __future__ import print_function, division
import matplotlib
import lo | gging
from sys import stdout
matplotlib.use('Agg') # Must be before | importing matplotlib.pyplot or pylab!
from neuralnilm import (Net, RealApplianceSource,
BLSTMLayer, DimshuffleLayer,
BidirectionalRecurrentLayer)
from neuralnilm.source import standardise, discretize, fdiff, power_and_fdiff
from neuralnilm.experiment import run_experim... |
wevote/WeVoteServer | position/views_admin.py | Python | mit | 50,531 | 0.004552 | # position/views_admin.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from .controllers import generate_position_sorting_dates_for_election, positions_import_from_master_server, \
refresh_cached_position_info_for_election, \
refresh_positions_with_candidate_details_for_election, \
refresh... | 'date_entered',
'date_last_changed', 'organization_we_vote_id', 'voter_we_vote_id',
'public_figure_we_vote_id', 'google_civic_election_id', 'state_code',
'vote_smart_rating_id', 'vote_smart_time_span', 'vote_smart_rating',
'vote_smart_rating_name', 'contest_office_we_vot... | ,
'politician_we_vote_id', 'contest_measure_we_vote_id', 'speaker_type', 'stance',
'position_ultimate_election_date', 'position_year',
'statement_text', 'statement_html', 'twitter_followers_count', 'more_info_url', 'from_scraper',
'organization_certified', 'volunteer_cert... |
tbeadle/django | tests/migrations/test_auto_now_add/0001_initial.py | Python | bsd-3-clause | 474 | 0.00211 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
operations = [
migrations.CreateModel(
name='Entry',
| fields=[
('id', models.Au | toField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=255)),
],
),
]
|
memex-explorer/memex-explorer | source/memex/rest.py | Python | bsd-2-clause | 8,218 | 0.003407 | import shutil
import json
from rest_framework import routers, serializers, viewsets, parsers, filters
from rest_framework.views import APIView
from rest_framework.exceptions import APIException
from rest_framework.response import Response
from django.core.exceptions import ValidationError
from django.core.files.uploa... | seeds"] = json.dumps(map(str.strip, seeds_list.readlines()))
elif textseeds:
if type(textseeds) == unicode:
request.data["seeds"] = json.dumps(map(unicode.strip, | textseeds.split("\n")))
# Get rid of carriage return character.
elif type(textseeds) == str:
request.data["seeds"] = json.dumps(map(str.strip, textseeds.split("\n")))
return super(SeedsListViewSet, self).create(request)
def destroy(self, request, pk=None):
se... |
PolyJIT/buildbot | polyjit/buildbot/slaves.py | Python | mit | 2,304 | 0.003038 | from buildbot.plugins import worker
infosun = {
"polyjit-ci": {
"host": "polyjit-ci",
"password": None,
"properties": {
"uchroot_image_path": "/data/polyjit/xenial-image/",
"uchroot_binary": "/data/polyjit/erlent/build/uchroot",
"can_build_llvm_debug": Fa... | redicate = None):
if not predicate:
predicate = lambda x : True
hosts = []
for k in slave_dict:
if predicate(slave_dict[k]):
hosts.append(slave_dict[k]["host"])
return hosts
def configure(c) | :
for k in infosun:
slave = infosun[k]
props = {}
if "properties" in slave:
props = slave["properties"]
c['workers'].append(worker.Worker(slave["host"], slave[
"password"], properties = props))
|
glenux/contrib-mypaint | gui/viewmanip.py | Python | gpl-2.0 | 3,703 | 0.00135 | # This file is part of MyPaint.
# Copyright (C) 2014 by Andrew Chadwick <a.t.chadwick@gmail.com>
#
# 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
"""Modes ... | b(tdw, event, dx, dy)
class RotateViewMode (gui.mode.OneshotDragMode):
"""A oneshot mode for rotat | ing the viewport by dragging."""
ACTION_NAME = 'RotateViewMode'
pointer_behavior = gui.mode.Behavior.CHANGE_VIEW
scroll_behavior = gui.mode.Behavior.NONE # XXX grabs ptr, so no CHANGE_VIEW
supports_button_switching = False
@classmethod
def get_name(cls):
return _(u"Rotate View")
... |
univ-of-utah-marriott-library-apple/management_tools | management_tools/__init__.py | Python | mit | 376 | 0.00266 | impo | rt app_info
import loggers
import plist_editor
__version__ = '1.9.1'
__all__ = ['app_info', 'fs_analysis', 'loggers', 'plist_editor', 'slack']
# This provides the ability to get the version from the command line.
# Do something like:
# $ python -m management_tools.__init__
if __name__ == "__main__":
print("... | |
henryneu/Python | sample/dict.py | Python | apache-2.0 | 415 | 0.007229 | #!/usr/bi | n/env python3
# -*- coding: utf-8 -*-
d = {'Michael':95, 'Henry':96, 'Emily':97}
d['Lucy'] = 94
d['Lucy'] = 91
key = (1, 2, 3)
d[key] = 98
print(d['Michael'])
d.pop('Michael')
print(d)
print('Tom' in d)
print(d.get('Tom'))
print(d.get('Tom'), -1)
s1 = set([1, 2, 2, 3, 3])
s2 = set([2, 3, 4])
s3 = set((1, 2))
s1.add(... | (s1 & s2)
print(s1 | s2)
print(s3)
|
xala3pa/my-way-to-algorithms | graphs/hash/python/median.py | Python | mit | 489 | 0.05317 | import heapq
import sys
| filename = "Median.txt"
lst = [int(l) for l in open(filename)]
H_low = []
H_high = []
sum = 0
for num in lst:
if len(H_low) > 0:
if num > -H_low[0]:
heapq.heappush(H_high, num)
else:
heapq.heappush(H_low, -num)
else:
heapq.heappush(H_low, -num)
if len(H_low) > len(H_high) + 1:
heapq.heappush(H_high, -... | nt sum % 10000 |
barmalei/scalpel | lib/gravity/common/db.py | Python | lgpl-3.0 | 10,270 | 0.013048 | #!/usr/bin/env python
#
# Copyright 2010 Andrei <vish@gravitysoft.org>
#
# 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... | return self._cursor.arraysize
def setinputsizes(self, sizes):
return self._cursor.setinputsizes(sizes)
def setoutputsize(self, size, column=None):
return self._cursor.setoutputsize(size, column)
def _orig_cursor(self):
return self._... | nit__(self, connection, owner):
assert connection and owner
self._connection = connection
self._creation_time = datetime.datetime.now()
self._owner = owner
self._cursors = []
def creationTime(self): return self._creation_time
def clo... |
salilab/saliweb | test/backend/run-all-tests.py | Python | lgpl-2.1 | 3,023 | 0 | from __future__ import print_function
import unittest
import sys
import os
import re
import tempfile
import shutil
import glob
import warnings
warnings.simplefilter("default")
# Only use coverage if it's new enough and is requested
try:
import coverage
if not hasattr(coverage.coverage, 'combine'):
cov... | erage report"""
| def __init__(self, *args, **keys):
if coverage:
# Start coverage testing now before we import any modules
self.topdir = 'python'
self.mods = (glob.glob("%s/saliweb/*.py" % self.topdir)
+ glob.glob("%s/saliweb/backend/*.py" % self.topdir))
... |
jmgilman/Neolib | neolib/inventory/ShopWizardResult.py | Python | mit | 3,097 | 0.009041 | """:mod:`ShopWizardResult` -- Provides an interface for shop wizard results
.. module:: ShopWizardResult
:synopsis: Provides an interface for shop wizard results
.. moduleauthor:: Joshua Gilman <joshuagilman@gmail.com>
"""
from neolib.exceptions import parseException
from neolib.inventory.Inventory import Inventor... | try:
items = pg.find | ("td", "contentModuleHeaderAlt").parent.parent.find_all("tr")
items.pop(0)
self.items = []
for item in items:
tmpItem = Item(item.find_all("td")[1].text)
tmpItem.owner = item.td.a.text
tmpItem.location = it... |
dssg/babies-public | babysaver/evaluation.py | Python | mit | 5,646 | 0.007793 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import markdown
from sklearn import metrics
from sklearn.externals import joblib
import re
def plot_precision_recall_n(y_true, y_prob, model_name=None):
# thanks rayid
from sklearn.metrics import precision_recall_curve
y_score = y_prob
... | t_index = metric_df.index.str.contains(r'test_percent')
prec = metric_df.iloc[prec_index,:].reset_index()
test = metric_df.iloc[test_index,:].reset_index()
mdf = pd.DataFrame({'Precision': prec.iloc[:,1],
'Predicted % Eligible': test.iloc[:,1]
})
mdf.inde... | at)
if rnd:
fmat = lambda x: str(np.round(x,1))+'%'
mdf = (mdf*100).applymap(fmat)
scores = sorted(scores)[::-1]
mes = 'Minimum Eligibility Score'
if scale:
mdf[mes] = [np.round(scores[int(each_k*len(scores))]*100,2)
for each_k in k]
else: mdf[mes] = [s... |
elyezer/robottelo | tests/foreman/api/test_organization.py | Python | gpl-3.0 | 17,745 | 0 | """Unit tests for the ``organizations`` paths.
Each ``APITestCase`` subclass tests a single URL. A full list of URLs to be
tested can be found here:
http://theforeman.org/api/apidoc/v2/organizations.html
:Requirement: Organization
:CaseAutomation: Automated
:CaseLevel: Acceptance
:CaseComponent: API
:TestType: F... | ttributes.
:CaseImportance: Critical
"""
# A label has a more restrictive allowable charset than a name, so we
# use it for populating both name and label.
org = entities.Organization()
name_label = org.get_fields()['label'].gen_value()
org.name = org.label = nam... | elf):
"""Create an organization and provide a name and label.
:id: 2bdd9aa8-a36a-4009-ac29-5c3d6416a2b7
:expectedresults: The organization has the provided attributes.
:CaseImportance: Critical
"""
org = entities.Organization()
org.name = name = org.get_fields(... |
teamfx/openjfx-8u-dev-rt | modules/web/src/main/native/Source/JavaScriptCore/Scripts/builtins/builtins_generate_internals_wrapper_implementation.py | Python | gpl-2.0 | 7,074 | 0.003534 | #!/usr/bin/env python
#
# Copyright (c) 2016 Apple Inc. 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
# notice, this list o... | ().framework.setting('namespace'),
}
sections = []
sections.append(self.generate_license())
sections.append(Template(Templates.DoNotEditWarning).substitute(args))
sections.append(self.generate_primary_header_includes())
sections.append(self.generate_secondary_header_incl... | e(Templates.NamespaceTop).substitute(args))
sections.append(self.generate_section_for_object())
sections.append(Template(Templates.NamespaceBottom).substitute(args))
return "\n\n".join(sections)
def generate_secondary_header_includes(self):
header_includes = [
(["WebCor... |
rafafigueroa/cws | build/quad/cmake/quad-genmsg-context.py | Python | apache-2.0 | 928 | 0.002155 | # generated from genmsg/cmake/pkg-genmsg.context.in
messages_str = ""
services_str = ""
pkg_name = "quad"
dependencies_str = "std_msgs;geometry_msgs;kobuki_msgs;hector_uav_msgs;nav_msgs;sensor_msgs;gazebo_msgs;tf"
langs = "gencpp;genlisp;genpy"
dep_include_paths_str = "std_msgs;/opt/ros/hydro/sh | are/std_msgs/cmake/../msg;geometry_msgs;/opt/ros/hydro/share/geometry_msgs/cmake/../msg;kobuki_msgs;/opt/ros/hydro/share/kobuki_msgs/cmake/../msg;hector_uav_msgs;/opt/ros/hydro/share/hector_ua | v_msgs/cmake/../msg;nav_msgs;/opt/ros/hydro/share/nav_msgs/cmake/../msg;sensor_msgs;/opt/ros/hydro/share/sensor_msgs/cmake/../msg;gazebo_msgs;/opt/ros/hydro/share/gazebo_msgs/cmake/../msg;tf;/opt/ros/hydro/share/tf/cmake/../msg;actionlib_msgs;/opt/ros/hydro/share/actionlib_msgs/cmake/../msg;trajectory_msgs;/opt/ros/hyd... |
carrdelling/project_euler | problem6.py | Python | gpl-2.0 | 996 | 0.002008 | #!/usr/bin/env python
################################################################################
#
# Project Euler - Problem 6
#
# The sum of the squares of the first ten natural numbers is,
#
# 1^2 + 2^2 + ... + 10^2 = 385
# The square of the sum of the firs | t ten natural numbers is,
#
# (1 + 2 + ... + 10)^2 = 552 = 3025
# Hence the difference between the sum of the squares of the first ten natural
# numbers and the square of the sum is 3025 - 385 = 2640
#
# Find the difference between the sum of the squares of the first one hundred
# natural numbers and the square of the ... | ###########################################################################
if __name__ == "__main__":
sum_one_hundred = sum([x for x in range(1, 101)])
sum_one_hundred_squared = sum_one_hundred * sum_one_hundred
sum_squared = sum([x ** 2 for x in range(1, 101)])
solution = sum_one_hundred_squared ... |
eayunstack/neutron | neutron/tests/unit/extensions/test_subnet_service_types.py | Python | apache-2.0 | 14,519 | 0 | # 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 appli | cable 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. S | ee the
# License for the specific language governing permissions and limitations
# under the License.
import webob.exc
from neutron.db import db_base_plugin_v2
from neutron.db import subnet_service_type_db_models
from neutron.extensions import subnet_service_types
from neutron.tests.unit.db import test_db_base_... |
beheh/fireplace | fireplace/cards/tgt/warlock.py | Python | agpl-3.0 | 950 | 0.024211 | from ..utils import *
##
# Minions
class AT_019:
"Dreadsteed"
deathrattle = Summon(CONTROLLER, "AT_019" | )
class AT_021:
"Tiny Knight of Evil"
events = Discard(FRIENDLY).on(Buff(SELF, "AT_021e"))
AT_021e = buff(+1, +1)
class AT_023:
"Void Crusher"
inspire = Destroy(RANDOM_ENEMY_MINION | RANDOM_FRIENDLY_MINION)
class AT_026:
"Wrathguard"
events = Damage(SELF).on(Hit(FRIENDLY_HERO, Damage.AMOUNT))
class AT_02... | lass AT_027e:
cost = SET(0)
##
# Spells
class AT_022:
"Fist of Jaraxxus"
play = Hit(RANDOM_ENEMY_CHARACTER, 4)
class Hand:
events = Discard(SELF).on(Hit(RANDOM_ENEMY_CHARACTER, 4))
class AT_024:
"Demonfuse"
play = Buff(TARGET, "AT_024e"), GainMana(OPPONENT, 1)
AT_024e = buff(+3, +3)
class AT_025:
"Dar... |
junmin-zhu/chromium-rivertrail | build/android/adb_install_apk.py | Python | bsd-3-clause | 1,365 | 0.011722 | #!/usr/bin/env python
#
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import multiprocessing
import optparse
import os
import sys
from pylib import android_commands
from pylib import test_options_pa... | nstall(
apk_path, False, options.apk_package)
print '----- Installed on %s -----' % device
print result
def main(argv):
parser = optparse.OptionParser()
test_options_parser.AddBuildTypeOption(par | ser)
test_options_parser.AddInstallAPKOption(parser)
options, args = parser.parse_args(argv)
if len(args) > 1:
raise Exception('Error: Unknown argument:', args[1:])
devices = android_commands.GetAttachedDevices()
if not devices:
raise Exception('Error: no connected devices')
pool = multiprocessin... |
materialsproject/MPContribs | mpcontribs-api/mpcontribs/api/config.py | Python | mit | 5,326 | 0.003567 | # -*- coding: utf-8 -*-
"""configuration module for MPContribs Flask API"""
import os
import datetime
import json
import gzip
formulae_path = os.path.join(
os.path.dirname(__file__), "contributions", "formulae.json.gz"
)
with gzip.open(formulae_path) as f:
FORMULAE = json.load(f)
VERSION = datetime.datetime... | te": "/apispec.json",
"rule_filter": lambda rule: True, # all in
"model_filter": lambda tag: True, # all in
}
],
"specs_route": "/",
}
TEMPLATE = {
"swagger": "2.0",
"info": {
"title": "MPContribs API",
"description": "Operations to contribute, update a... | "contact": {
"name": "MPContribs",
"email": "contribs@materialsproject.org",
"url": "https://mpcontribs.org",
},
"license": {
"name": "Creative Commons Attribution 4.0 International License",
"url": "https://creativecommons.org/licenses/b... |
cancerregulome/gidget | commands/feature_matrix_construction/main/filterPWPV.py | Python | mit | 4,776 | 0.002094 | # -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#
# these are system modules
import math
import numpy
import random
import sys
import urllib
# these are my local modules
import miscIO
import path
import tsvIO
# -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-... | = int(tokenList[4])
endPos = int(tokenList[5])
except:
doNothing = 1
return (chrName, startPos, endPos)
# -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#
def filterPWPV(pwpvOutFilename):
print " "
print " reading PWPV outputs from <%s> " % pwpvOutFile... | mapped"
fh0 = file(out0, 'w')
fh1 = file(out1, 'w')
n0 = 0
n1 = 0
# why didn't I put GNAB in this list ???
# --> adding it to the list on 06sep12
typeList = ["CNVR", "GEXP", "GNAB", "METH", "MIRN", "RPPA"]
# --> taking it back out on 20sep12 ;-)
typeList = ["CNVR", "GEXP", "METH",... |
delMar43/wcmodtoolsources | WC1_clone/room_engine/win_init.py | Python | mit | 424 | 0.023585 | import os, pygame
#create window of correct size (320x200, with some multiple)
x = 320
y = 200
size_mult = 4
bright_mult = 4
pygame.init()
os.environ['SDL_VIDEO_WINDOW_POS'] = str( | 0) + "," + str(40) #put window in consistent location
os.environ['SDL_VIDEO_WINDOW_POS'] = str(0) + "," + str(40) #put window in consistent location
screen = pygame.display.set_mode((x*size_mult, y*size_mult))
screen2 = pygame.Surface((x,y)) | |
choderalab/openpathsampling | openpathsampling/tests/test_range_logic.py | Python | lgpl-2.1 | 4,127 | 0.000969 |
from builtins import object
from nose.tools import assert_equal, assert_not_equal, raises
from nose.plugins.skip import Skip, SkipTest
from openpathsampling.range_logic import *
class TestRangeLogic(object):
def test_range_and(self):
assert_equal(range_and(1, 3, 2, 4), [(2, 3)])
assert_equal(range... | (0.2, 0.4, 0.1, 0.3), [(0.1, 0.4)])
assert_equal(periodic_range_or(1, 2, 3, 4), [(1, 2), (3, 4)])
assert_equal(periodic_ | range_or(3, 4, 1, 2), [(3, 4), (1, 2)])
assert_equal(periodic_range_or(1, 4, 2, 3), [(1, 4)])
assert_equal(periodic_range_or(2, 3, 1, 4), [(1, 4)])
assert_equal(periodic_range_or(1, 2, 1, 2), 1)
assert_equal(periodic_range_or(1, 2, 2, 1), -1)
assert_equal(periodic_range_or(0.1, 0... |
timeyyy/PyUpdater | pyupdater/hooks/hook-cryptography.py | Python | bsd-2-clause | 1,600 | 0 | # -----------------------------------------------------------------------------
# Copyright (c) 2014, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License with exception
# for distributing bootloader.
#
# The full license is in the file COPYING.txt, distributed with this softw... | ypto_dir = os.path.dirname(get_module_file_attribute('cryptography'))
for ext in PY_EXTENSION_SUFFIXES:
ffimods = glob.glob(os.path.join(crypto_dir,
'*_cffi_*%s*' % ext))
for f in ffimods:
name = os.path.join('cryptography', os.path.basename(f))
# ... | NARY'))
return mod
|
zhmcclient/python-zhmcclient | tests/unit/zhmcclient/test_activation_profile.py | Python | apache-2.0 | 11,882 | 0 | # Copyright 2016-2021 IBM Corp. 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... | ked_cpc.reset_activation_profiles.add({
# element-uri is set up automatically
'name': 'rap_2',
'parent': self.faked_cpc.uri,
'class': 'reset-activation-profile',
'descripti | on': 'RAP #2',
})
self.faked_image_ap_1 = self.faked_cpc.image_activation_profiles.add({
# element-uri is set up automatically
'name': 'iap_1',
'parent': self.faked_cpc.uri,
'class': 'image-activation-profile',
'description': 'IAP #1',
... |
wberrier/meson | mesonbuild/dependencies/misc.py | Python | apache-2.0 | 14,951 | 0.001271 | # Copyright 2013-2017 The Meson development team
# 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 agre... | else:
include_dir = os.path.join(self.boost_root, 'include')
else:
include_dir = self.incdir
# Use "-isystem" when including boost h | eaders instead of "-I"
# to avoid compiler warnings/failures when "-Werror" is used
# Careful not to use "-isystem" on default include dirs as it
# breaks some of the headers for certain gcc versions
# For example, doing g++ -isystem /usr/include on a simple
# "int main()" sour... |
matrumz/RPi_Custom_Files | Printing/hplip-3.15.2/ui4/printdialog_base.py | Python | gpl-2.0 | 5,718 | 0.002973 | # -*- coding: utf-8 -*-
# Form implementation generated from rea | ding ui file 'ui4/printdialog | _base.ui'
#
# Created: Mon May 4 14:30:35 2009
# by: PyQt4 UI code generator 4.4.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.setWindowModality(QtCore.Qt.Ap... |
lbel/Maastricht-Masterclass-2015 | scripts/MassFit.py | Python | mit | 2,260 | 0.031858 | def MassFit(particle) :
if raw_input("Do %s mass fit? [y/N] " % (particle)) not in ["y", "Y"]:
return
print "************************************"
print "* Doing mass fit *"
print "************************************"
f = TFile.Open("workspace.root")
w = f.Get("w")
asse... | t.LineStyle(2), RooFit.Components("bkgModel"), RooFit.Name("bkg") )
frame.Draw()
leg = TLegend(0.64, 0.77, 0.89, 0.89)
leg.AddEntry(frame.findObject("sig"), "Signal ("+particle+")", "l")
leg.AddEntry(frame.findObject("bkg"), "Background", "l")
leg.Draw("same")
cMass.Update()
cMass.SaveAs("plots/... | print " > Background events: %d +- %d" % (Nbkg.getVal(), Nbkg.getError())
raw_input("Press enter to continue.")
f.Close()
|
aspera1631/hs_logreader | logreader.py | Python | mit | 4,183 | 0.005738 | __author__ = 'bdeutsch'
import re
import numpy as np
import pandas as pd
# List cards drawn by me and played by opponent
def get_cards(filename):
# Open the file
with open(filename) as f:
mycards = []
oppcards = []
for line in f:
# Generate my revealed card list
... | 2))
name = m.group(1)
df.ix[ent_id, 'Name'] = name
#print m.group(2), m.group | (1)
return df
idlist = []
with open('test_game') as f:
# For each line
for line in f:
# Find the entity ids
m = re.search('[\[ ]id=(\d+) ', line)
# if one is found
if m:
# Check that we haven't found it yet, convert to an integer
id = int(m.group(1... |
biocore/pyqi | pyqi/core/interfaces/html/input_handler.py | Python | bsd-3-clause | 1,074 | 0.005587 | #!/usr/bin/env python
#-----------------------------------------------------------------------------
# Copyright (c) 2013, The BiPy Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-------------------------... | n a list of strings, one per line in the file.
Each line will have leading and trailing whitespace stripped from it.
"""
if not hasattr(option_value, 'read'):
raise IncompetentDeveloperError("Input type must be a file object.")
ret | urn [line.strip() for line in option_value]
def load_file_contents(option_value):
"""Return the contents of a file as a single string."""
if not hasattr(option_value, 'read'):
raise IncompetentDeveloperError("Input type must be a file object.")
return option_value.read()
|
SymbiFlow/prjuray | fuzzers/004-tileinfo/cleanup_site_pins.py | Python | isc | 4,765 | 0.000839 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2020-2022 F4PGA Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the L | icense 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 ... |
# SPDX-License-Identifier: Apache-2.0
""" Tool to cleanup site pins JSON dumps.
This tool has two behaviors. This first is to rename site names from global
coordinates to site local coordinates. The second is remove the tile prefix
from node names.
For example CLBLM_L_X8Y149 contains two sites named SLICE_X10Y149 ... |
googleapis/python-translate | samples/generated_samples/translate_generated_translate_v3_translation_service_create_glossary_async.py | Python | apache-2.0 | 1,703 | 0.001762 | # -*- coding: utf-8 -*-
# Copyright 2020 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | modifications to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-cloud-translate
# [START tra | nslate_generated_translate_v3_TranslationService_CreateGlossary_async]
from google.cloud import translate_v3
async def sample_create_glossary():
# Create a client
client = translate_v3.TranslationServiceAsyncClient()
# Initialize request argument(s)
glossary = translate_v3.Glossary()
glossary.nam... |
PyFilesystem/pyfilesystem | fs/commands/fsrm.py | Python | bsd-3-clause | 1,775 | 0.003944 | #!/usr/bin/env python
from fs.errors import ResourceNotFoundError
from fs.opener import opener
from fs.commands.runner import Command
import sys
class FSrm(Command):
usage = """fsrm [OPTION]... [PATH]
Remove a file or directory at PATH"""
def get_optparse(self):
optparse = super(FSrm, self).get_optp... | if not options.force:
raise
else:
if verbose:
self.output("removed '%s'\n" % path)
def run():
return FSrm() | .run()
if __name__ == "__main__":
sys.exit(run())
|
edx/edx-platform | openedx/core/djangoapps/user_api/accounts/tests/test_views.py | Python | agpl-3.0 | 53,614 | 0.003117 | """
Test cases to cover Accounts-related behaviors of the User API application
"""
import datetime
import hashlib
import json
from copy import deepcopy
from unittest import mock
import ddt
import pytz
from django.conf import settings
from django.test.testcases import TransactionTestCase
from django.test.utils import ... | iedNameStatus.APPROVED)
def create_user_registration( | self, user):
"""
Helper method that creates a registration object for the specified user
"""
RegistrationFactory(user=user)
def _verify_profile_image_data(self, data, has_profile_image):
"""
Verify the profile image data in a GET response for self.user
corres... |
caiges/populous | populous/thumbnail/defaults.py | Python | bsd-3-clause | 324 | 0 | D | EBUG = False
BASEDIR = ''
SUBDIR = ''
PREFIX = ''
QUALITY = 85
CONVERT = '/usr/bin/convert'
WVPS = '/usr/bin/wvPS'
PROCESSORS = (
'populous.thumbnail.processors.colorspace',
'populous.thumbnail.processors.autocrop',
'populous.thumbnail.processors.scale_and_crop',
'populous.thumbnail. | processors.filters',
)
|
amidoimidazol/bio_info | Rosalind.info Problems/Mortal Fibonacci Rabbits.py | Python | mit | 1,178 | 0.005111 | '''
Author: Peter Chip (furamail001@gmail.com)
Date: 2015 03 25
Given: Positive integers n≤100 and m≤20.
Return: The total number of pairs of rabbits that will remain after the n-th month if all rabbits live for m months.
Theory: The standard fibonacci series : 1 1 2 3 5 8 13
fn = fn-1 + fn-2
In re... | of pairs in the first six month
m = 3 : 1 1 2 2 3 4
m = 4 : 1 1 2 3 4 6
m = 5 : 1 1 2 3 5 7
After the first death the number of rabbits:
fn = fn-2 + fn-3 ... fn-m
'''
def new_value(i):
value = 0
change = 2
# Repeat it m - 1 times
for y in range(1, m):
... | ber of months
n = 94
# months a rabbit lives
m = 20
L = [1, 1, 2]
i = 3
while i < n:
# If the first death occurs
if i >= m:
L.append(new_value(i))
i += 1
# If before the first death
else:
L.append(L[i-1]+ (L[i-2]))
i += 1
print(L[len(L)-1])
|
SuperElastix/elastix | Testing/elx_get_checksum_list.py | Python | apache-2.0 | 2,114 | 0.028382 | import sys
import os
import os.path
import glob
from optparse import OptionParser
#-------------------------------------------------------------------------------
# the main function
# cd bin_VS2010
# ctest -C Release
# cd Testing
# python ../../elastix/Testing/elx_get_checksum_list.py -l elastix_run*
# cd ..
# cmake ... | oryList == None :
parser.error( "The option directory list (-l) should be given" )
# Use glob, this works not only on Linux
dirList = glob.glob( options.directoryList );
# Add everything not processed
dirList.extend( args );
print( "directory checksum" )
for directory in dirList:
#... | try:
f = open( fileName )
except IOError as e:
print( directory + " No elastix.log found" )
continue
checksumFound = False;
for line in f:
if "Registration result checksum:" in line:
checksumline = line;
checksumFound = True;
# Extract chec... |
alexanderfefelov/nav | python/nav/eventengine/plugins/modulestate.py | Python | gpl-2.0 | 2,481 | 0 | #
# Copyright (C) 2012, 2014 UNINETT
#
# This file is part of Network Administration Visualized (NAV).
#
# NAV is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License version 2 as published by
# the Free Software Foundation.
#
# This program is distributed in the h... | alert = AlertGenerator(self.event)
target = self.get_target()
if target:
alert['module'] = target
return | alert
def _post_down_warning(self):
"""Posts the actual warning alert"""
alert = self._get_alert()
alert.alert_type = "moduleDownWarning"
alert.state = self.event.STATE_STATELESS
self._logger.info("%s: Posting %s alert",
self.get_target(), alert.ale... |
amolenaar/gaphor | gaphor/RAAML/fta/conditionalevent.py | Python | lgpl-2.1 | 1,442 | 0.000693 | """Conditional Event item definition."""
from gaphor.diagram.presentation import (
Classified,
ElementPresentation,
from_package_str,
)
from gaphor.diagram.shapes im | port Box, IconBox, Text
from gaphor.diagram.support import represents
from gap | hor.diagram.text import FontStyle, FontWeight
from gaphor.RAAML import raaml
from gaphor.RAAML.fta.basicevent import draw_basic_event
from gaphor.UML.modelfactory import stereotypes_str
@represents(raaml.ConditionalEvent)
class ConditionalEventItem(ElementPresentation, Classified):
def __init__(self, diagram, id=... |
andreadean5/python-hpOneView | hpOneView/resources/servers/logical_enclosures.py | Python | mit | 9,117 | 0.002962 | # -*- coding: utf-8 -*-
###
# (C) Copyright (2012-2016) Hewlett Packard Enterprise Development LP
#
# 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 limi... | _uri) + "/script"
return self._client.update(information, uri=uri, timeout=timeout)
def generate_support_dump(self, information, id_or_uri, timeout=-1):
"""
Generates a support dump for the logical enclosure with the specified ID. A logical enclosure support dump
includes content fo... | e support dump content.
Args:
id_or_uri: Could be either the resource id or the resource uri
information (dict): information to generate support dump
timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
|
systers/vms | vms/pom/locators/eventSearchPageLocators.py | Python | gpl-2.0 | 481 | 0.002079 | class EventSear | chPageLocators(object):
NAME_FIELD = ".form-control[name='name']"
START_DATE_FIELD = ".form-control[name='start_date']"
END_DATE_FIELD = ".form-control[name='end_date']"
CITY_FIELD = ".form-control[name='city']"
STATE_FIELD = ".form-control[name='state']"
COUNTRY_FIELD = ".form-control[name='co... | lp-block'
SUBMIT_PATH = 'submit'
|
calum-chamberlain/EQcorrscan | eqcorrscan/utils/pre_processing.py | Python | gpl-3.0 | 39,205 | 0 | """
Utilities module whose functions are designed to do the basic processing of
the data using obspy modules (which also rely on scipy and numpy).
:copyright:
EQcorrscan developers.
:license:
GNU Lesser General Public License, Version 3
(https://www.gnu.org/copyleft/lesser.html)
"""
import numpy as np
imp... | results = [pool.apply_async(process, (tr,), {
| 'lowcut': lowcut, 'highcut': highcut, 'filt_order': filt_order,
'samp_rate': samp_rate, 'starttime': starttime,
'clip': clip, 'seisan_chan_names': seisan_chan_names,
'fill_gaps': fill_gaps, 'length': length,
'ignore_length': ignore_length, 'fft_threads': fft_threads,
... |
kelle/astropy | astropy/convolution/tests/test_convolve_nddata.py | Python | bsd-3-clause | 1,827 | 0.002737 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import pytest
import numpy as np
from ..convolve import convolve, convolve_fft
from ..kernels import Gaussian2DKernel
from ...nddata import NDDat... | Gaussian2DKernel(1)
result_base = convfunc(ndd_base, test_kernel)
result_nan = convfunc(ndd_nan, test_kernel)
result_mask = conv | func(ndd_mask, test_kernel)
assert np.allclose(result_nan, result_mask)
assert not np.allclose(result_base, result_mask)
assert not np.allclose(result_base, result_nan)
# check to make sure the mask run doesn't talk back to the initial array
assert np.sum(np.isnan(ndd_base.data)) != np.sum(np.isna... |
ME-ICA/me-ica | meica.libs/nibabel/nicom/tests/test_dicomwrappers.py | Python | lgpl-2.1 | 6,163 | 0.004543 | """ Testing DICOM wrappers
"""
from os.path import join as pjoin, dirname
import gzip
import numpy as np
try:
import dicom
except ImportError:
have_dicom = False
else:
have_dicom = True
dicom_test = np.testing.dec.skipif(not have_dicom,
'could not import pydicom')
from... | item')
assert_true(dw.is_mosaic)
| assert_array_almost_equal(
np.dot(didr.DPCS_TO_TAL, dw.get_affine()),
EXPECTED_AFFINE)
@dicom_test
def test_dwi_params():
dw = didw.wrapper_from_data(DATA)
b_matrix = dw.b_matrix
assert_equal(b_matrix.shape, (3,3))
q = dw.q_vector
b = np.sqrt(np.sum(q * q)) # vector... |
storyhe/playWithBot | plugins/rpgbot.py | Python | mit | 3,282 | 0.014009 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""!가입; 봇 게임센터에 가입합니다.\n!내정보; 내 등록된 정보를 봅니다."""
import re
import json
from botlib import BotLib
from rpg import RPG
from util.util import enum
CmdType = enum(
Register = 1,
MyInfo = 2,
WeaponInfo = 3,
AddWeapon = 4,
UpgradeWeapon = 5,
)
# 입력으로부터 명령어 ... | text): return CmdType.AddWeapon
if re.findall(u"^!무기강화 ", text): return CmdType.UpgradeWeapon
return None
# 입력으로부터 인자를 가져오는 함수
# 일단은 모든 인자가 오직 한개뿐이라 가정하고 만들었다....
# 인자가 없을 때 예외처리는 on_message()에서 try-except에서 처리
def get_argument(cmdType | , text):
match = None
if cmdType == CmdType.WeaponInfo :
match = re.findall(ur"^!무기정보 (.*)", text)
if not match: raise ValueError
if cmdType == CmdType.AddWeapon :
match = re.findall(ur"^!무기추가 (.*)", text)
if not match: raise ValueError
if cmdType == CmdType.UpgradeWeapo... |
lach76/scancode-toolkit | src/commoncode/functional.py | Python | apache-2.0 | 5,818 | 0.001203 | #
# Copyright (c) 2015 nexB Inc. and others. All rights reserved.
# http://nexb.com and https://github.com/nexB/scancode-toolkit/
# The ScanCode software is licensed under the Apache License version 2.0.
# Data generated with ScanCode require an acknowledgment.
# ScanCode is a trademark of nexB Inc.
#
# You may not use... | must contain an even number of elements or it will truncated.
For example::
>>> list(pair_chunks([1, 2, 3, 4, 5, 6]))
[(1, 2), (3, 4), (5, 6)]
>>> list(pair_chunks([1, 2, | 3, 4, 5, 6, 7]))
[(1, 2), (3, 4), (5, 6)]
"""
return izip(*[iter(iterable)] * 2)
def memoize(fun):
"""
Decorate fun function and cache return values. Arguments must be
hashable. kwargs are not handled. Used to speed up some often executed
functions.
Usage example::
>>> @memoize
... |
sshrdp/mclab | lib/antlr-3.0.1/runtime/Python/tests/testbase.py | Python | apache-2.0 | 9,623 | 0.004053 | import unittest
import imp
import os
import errno
import sys
import glob
import re
from distutils.errors import *
def unlink(path):
try:
os.unlink(path)
except OSError, exc:
if exc.errno != errno.ENOENT:
raise
class BrokenTest(unittest.TestCase.failureException):
def __repr__... | put += line
if line.startswith('error('):
failed = True
rc = fp.close()
if rc is not None:
failed = True
if failed:
raise RuntimeError(
"Failed to compile grammar '%s':\n\n" % file
+ output
)
... | '.g'
# don't try to rebuild grammar, if it already failed
if grammarName in compileErrorCache:
return
try:
testDir = os.path.dirname(os.path.abspath(__file__))
# get dependencies from antlr
if grammarName in dependencyCache:
dep... |
hohe/scikit-rf | skrf/network.py | Python | bsd-3-clause | 141,218 | 0.00973 | '''
.. module:: skrf.network
========================================
network (:mod:`skrf.network`)
========================================
Provides a n-port network class and associated functions.
Most of the functionality in this module is provided as methods and
properties of the :class:`Network` Class.
Networ... | tributes) are given below
References
------------
.. [#] http://en.wikipedia.org/wiki/Two-port_network
'''
global PRIMARY_PROPERTIES
PRIMARY_PROPERTIES = [ 's','z','y','a']
global COMPONENT_FUNC_DICT
COMPONENT_FUNC_DICT | = {
're' : npy.real,
'im' : npy.imag,
'mag' : npy.abs,
'db' : mf.complex_2_db,
'db10' : mf.complex_2_db10,
'rad' : npy.angle,
'deg' : lambda x: npy.angle(x, deg=True),
'arcl' : lambda x: npy.angle(x) * npy.abs(x),
'rad_unwrap' ... |
Azure/azure-sdk-for-python | sdk/devtestlabs/azure-mgmt-devtestlabs/azure/mgmt/devtestlabs/operations/_provider_operations_operations.py | Python | mit | 4,782 | 0.004391 | # 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 ... | , stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
... | next, extract_data
)
list.metadata = {'url': '/providers/Microsoft.DevTestLab/operations'} # type: ignore
|
imh/gnss-analysis | gnss_analysis/agg_run.py | Python | lgpl-3.0 | 2,348 | 0.013203 | #!/usr/bin/env python
# Copyright (C) 2015 Swift Navigation Inc.
# Contact: Ian Horn <ian@swiftnav.com>
#
# This source is subject to the license found in the file 'LICENSE' which must
# be be distributed together with this source. All other rights reserved.
#
# THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WAR... | single_run
import pandas as pd
import numpy as np
def main():
import argparse
parser = argparse.ArgumentParser(description='RTK Filter SITL t | ests.')
parser.add_argument('infile', help='Specify the HDF5 file to use for input.')
parser.add_argument('outfile', help='Specify the HDF5 file to output into.')
parser.add_argument('baselineX', help='The baseline north component.')
parser.add_argument('baselineY', help='The baseline east component.')
parse... |
hrayr-artunyan/shuup | shuup/utils/filer.py | Python | agpl-3.0 | 5,631 | 0.003374 | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import absolute_import
import hashlib
import six
from djan... | th: Pathname string (see `filer_folder_from_path`) or a Filer Folder.
:type path: basestring|filer.models.Folder
:param file_name: File name
:t | ype file_data: basestring
:param file_data: Upload data
:type file_data: bytes
:param sha1: SHA-1 checksum of the data, if available, to do deduplication.
May also be `True` to calculate the SHA-1 first.
:type sha1: basestring|bool
:rtype: filer.models.imagemodels.Image
"""
... |
laats/dpdq | src/qp/frontend.py | Python | gpl-3.0 | 3,696 | 0.005952 | # -*-Python-*-
################################################################################
#
# File: frontend.py
# RCS: $Header: $
# Description: frontend:
# responsibility:
# init backend
# init processors
# handle two query types:
# ... | erved.
#
# frontend.py 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 Li | cense, or
# (at your option) any later version.
#
# frontend.py 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 ... |
Wonfee/pymobiledevice | util/ccl_bplist.py | Python | gpl-3.0 | 15,606 | 0.005318 | """
Copyright (c) 2012, CCL Forensics
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the fo... | L, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING | NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
import sys
import os
import struct
import datetime
__version__ = "0.11"
__description__ = "Converts Apple binary PList files into a native Python data structure"
__contact__ = "Alex Cait... |
plotly/python-api | packages/python/plotly/plotly/validators/histogram/stream/_maxpoints.py | Python | mit | 550 | 0 | import _plotly_utils.basevalidators
class MaxpointsValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self, plotly_name="maxpoints", parent_name="histogram.stream", **kwargs
):
super(MaxpointsValidator, self).__init__(
plotly_name=plotly_name,
parent... | alc"),
max=k | wargs.pop("max", 10000),
min=kwargs.pop("min", 0),
role=kwargs.pop("role", "info"),
**kwargs
)
|
TeamLovely/Saliere | saliere/templatizer.py | Python | mit | 6,214 | 0.001609 | import os
import shutil
import jinja2
from saliere.core import UsageError
class Templatizer:
"""Template manager.
Handles all the template related operations.
"""
def __init__(self, template_path_list=None, template_type=None):
"""Initializer.
:param template_path_list: the list o... | er_base.replace("template", project_name)
formula_folder_path = os.path.join(output_folder_root, formula_folder_name)
Templatizer.create_folder(formula_folder_path)
# List the files.
for file in files:
dst = os.path.join(formula_folder_path, file)
... | If there is no variables to replace, simply copy the file.
if not template_vars:
src = os.path.join(root, file)
shutil.copyfile(src, dst)
continue
# Otherwise jinjanize it.
jinjanized_content = Jinjanizer.jinjan... |
jsatt/django-db-email-backend | test_app/storage.py | Python | mit | 1,353 | 0.001478 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from io import BytesIO
from django.core.files.storage import Storage
class TestStorage(Storage):
def __init__(self, *args, **kwargs):
self.reset()
def _open(self, name, mode='rb'):
if not self.exists(name):
if 'w' i... | return self._file_system[name]
else:
raise IOError("[Errno 2] No such file or directory: '{}'".format(name))
return self._file_system[name]
def _save(self, name, content):
f = BytesIO()
file_content = content.read()
if isinstance(file_content, bytes):
... | .exists(name):
name = self.get_available_name(name)
self._file_system[name] = f
return name
def delete(self, name):
"""
Deletes the specified file from the storage system.
"""
if self.exists(name):
del self._file_system['name']
else:
... |
wsricardo/mcestudos | treinamento-webScraping/Abraji/p08.py | Python | gpl-3.0 | 342 | 0.01194 | import urllib.request
pagina = urllib.request.urlopen(
'http://beans.itcarlow.ie/prices-loyalty.html')
texto = pagina.read().decode('utf8')
onde = texto.find('>$')
início = onde + 2
fim = início + 4
preço = texto[início:fim]
if preço < 4.74:
print ('Co | mprar pois est | á barato:', preço)
else:
print ('Esperar')
|
itucsProject2/Proje1 | restaurant/models.py | Python | unlicense | 639 | 0.00626 | from django.db import models
from _datetime import date
class Restaurant(models.Model):
name = models.CharField(max_length=200)
| transportation = models.BooleanField(default=False)
weatherSensetion = models.BooleanField(default=False)
status = models.BooleanField(default=True)
totalDay = models.IntegerField(default=0)
counter = models.IntegerField(default=0)
def __str__(self):
return self.name
def deleteRest(s... | (id=updateId).update(status = newStatus)
|
jithinbp/pslab-desktop-apps | psl_res/GUI/B_ELECTRONICS/B_Opamps/L_Summing.py | Python | gpl-3.0 | 4,802 | 0.05935 | #!/usr/bin/python
"""
::
This experiment is used to study Half wave rectifiers
"""
from __future__ import print_function
from PSL_Apps.utilitiesClass import utilitiesClass
from PSL_Apps.templates import ui_template_graph_nofft as template_graph_nofft
from PyQt4 import QtGui,QtCore
import sys,time
params = ... | lerValue)
self.I.capture_traces(3,self.samples,self.tg)
if self.running:self.timer.singleShot(self.samples*self.I.timebase*1e-3+10,self.plotData)
except Exception as e:
print (e)
def plotData(self):
if not self.running: return
try:
n=0
while(not self.I.oscilloscope_progre | ss()[0]):
time.sleep(0.1)
n+=1
if n>10:
self.timer.singleShot(100,self.run)
return
self.I.__fetch_channel__(1)
self.I.__fetch_channel__(2)
self.I.__fetch_channel__(3)
self.curve1.setData(self.I.achans[1].get_xaxis()*1e-6,self.I.achans[1].get_yaxis(),connect='finite')
self.curve2.set... |
leofnch/kc | tests/testnet/roles/Bob.py | Python | gpl-3.0 | 526 | 0 | """
Bob is a honest user. Bob creates transactions and smart contracts, like Alice.
Thread for sync must be started separately, wallet must be already created.
"""
from hodl import block
import logging as log
def main(wallet, keys=None):
log.info("Bob's main started")
log.debug("Bob's money: " + str(w | allet.bch.money(keys['Bob'][1])))
# start blockchain checking thread
# create transaction
# create smart contract
# messages to smart contract
# decentralized internet request
pass # t | odo
|
snibug/gyp_example | build/package_application.py | Python | apache-2.0 | 3,909 | 0.008186 | #!/usr/bin/python
# Copyright 2014 Google Inc. All Rights Reserved.
"""Package application for the given platform and build configs.
Depending on platform, this will create a package suitable for distribution.
If the buildbot is running the script, it will be uploaded to the
buildbot staging area.
Usage varies depend... |
import sys
import textwrap
import package_utils
def _ParseCommandLine(args):
"""Parse command line and return options."""
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description=textwrap.dedent(__doc__))
if platform.system() == 'Linux':
valid_platfo... | cific Packager class in a dict.
for plat in valid_platforms:
packagers[plat] = importlib.import_module(
'%s.packager' % plat.lower()).Packager
valid_configs = (
'Debug',
'Devel',
'QA',
'Gold',
)
subparsers = parser.add_subparsers(dest='platform', help='Platform name')
# ... |
Panos512/invenio | modules/miscutil/lib/upgrades/invenio_2012_11_04_circulation_and_linkback_updates.py | Python | gpl-2.0 | 4,682 | 0.006621 | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Co | pyright (C) 2012 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your option) any later version.
##
## Invenio is distributed in the hope that i... | T 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
## along with Invenio; if not, write to the Free Software Foundation, Inc.,
## 59 ... |
SMSSecure/SMSSecure | scripts/emoji-extractor/remove-emoji-margins.py | Python | gpl-3.0 | 738 | 0.001355 | #!/usr/bin/env python3
import argparse
from pathlib import Path
from PIL imp | ort Image
parser = argparse.ArgumentParser(
| prog='emoji-extractor',
description="""Resize extracted emojis to 128x128.""")
parser.add_argument(
'-e', '--emojis',
help='folder where emojis are stored',
default='output/',
required=False)
args = parser.parse_args()
path = Path(args.emojis)
for image_path in path.iterdir():
try:
p... |
kawamon/hue | desktop/core/ext-py/celery-4.2.1/celery/apps/multi.py | Python | apache-2.0 | 15,740 | 0 | """Start/stop/manage workers."""
from __future__ import absolute_import, unicode_literals
import errno
import os
import shlex
import signal
import sys
from collections import OrderedDict, defaultdict
from functools import partial
from subprocess import Popen
from time import sleep
from kombu.utils.encoding import fro... | args)
class MultiParser(object):
Node = Node
def __init__(self, cmd='celery worker',
append='', prefix='', suffix='', |
range_prefix='celery'):
self.cmd = cmd
self.append = append
self.prefix = prefix
self.suffix = suffix
self.range_prefix = range_prefix
def parse(self, p):
names = p.values
options = dict(p.options)
ranges = len(names) == 1
pr... |
tboyce1/home-assistant | homeassistant/components/tile/__init__.py | Python | apache-2.0 | 3,733 | 0.000536 | """The Tile component."""
import asyncio
from datetime import timedelta
from pytile import async_login
from pytile.errors import SessionExpiredError, TileError
from homeassistant.const import ATTR_ATTRIBUTION, CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import callback
from homeassistant.helpers import aioht... | E_INTERVAL,
update_method=async_update_data,
)
await coordinator.async_refresh()
hass.data[DOMAIN][DATA_COORDINATOR][config_entry.entry_id] = coordinator
for component in PLATFORMS:
hass.async_create_task(
hass.config_entries.async_forward_entry_setup(config_entry, componen... | .gather(
*[
hass.config_entries.async_forward_entry_unload(config_entry, component)
for component in PLATFORMS
]
)
)
if unload_ok:
hass.data[DOMAIN][DATA_COORDINATOR].pop(config_entry.entry_id)
return unload_ok
class TileEntity(Coord... |
jonfoster/pyxb-upstream-mirror | examples/ndfd/forecast.py | Python | apache-2.0 | 2,426 | 0.005359 | from __future__ import print_function
import xml.dom.minidom
import DWML
import datetime
import pyxb.binding.datatypes as xsd
import urllib2
import time
import collections
import sys
# Get the next seven days forecast for two locations
zip = [ 85711, 55108 ]
if 1 < len(sys.argv):
zip = sys.argv[1:]
begin = xsd.dat... | ne
for tl in data.time_layout:
if tl.layout_key == mint.time_layout:
mint_time_layout = tl
if tl.layout_key == maxt.time_layout:
maxt_time_layout = tl
for ti in range(min(len(mint_time_l | ayout.start_valid_time), len(maxt_time_layout.start_valid_time))):
start = mint_time_layout.start_valid_time[ti].value()
end = mint_time_layout.end_valid_time[ti]
print('%s: min %s, max %s' % (time.strftime('%A, %B %d %Y', start.timetuple()),
... |
kfcpaladin/sze-the-game | renpy/editor.py | Python | mit | 5,015 | 0.002792 | # Copyright 2004-2017 Tom Rothamel <pytom@bishoujo.us>
#
# 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, m... | f begin(self, new_window=False, **kwargs):
"""
Begins an editor transaction.
`new_window`
If True, a new editor window will be created and presented to the
| user. Otherwise, and existing editor window will be used.
"""
def end(self, **kwargs):
"""
Ends an editor transaction.
"""
def open(self, filename, line=None, **kwargs): # @ReservedAssignment
"""
Ensures `path` is open in the editor. This may be called mu... |
vmagamedov/grpclib | tests/dummy_pb2.py | Python | bsd-3-clause | 5,139 | 0.003308 | # -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: dummy.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf ... | DUMMYSERVICE = _descriptor.ServiceDescriptor(
name='DummyService',
full_name='dummy.DummyService',
file=DESCRIPTOR,
index=0,
serialized_options=None,
create_key=_descriptor._internal_create_key,
seri | alized_start=83,
serialized_end=333,
methods=[
_descriptor.MethodDescriptor(
name='UnaryUnary',
full_name='dummy.DummyService.UnaryUnary',
index=0,
containing_service=None,
input_type=_DUMMYREQUEST,
output_type=_DUMMYREPLY,
serialized_options=None,
create_key=_descriptor._internal_... |
CHrycyna/LandscapeTracker | app/controllers/__init__.py | Python | mit | 49 | 0.020408 | __all__ = ["user_controller", "pl | ant_cont | roller"] |
jasonehines/mycroft-core | mycroft/skills/container.py | Python | gpl-3.0 | 3,372 | 0 | # Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core 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 versio... | op()
def stop(self):
if self.skill:
self.skill.shutdown()
def main():
container = SkillContainer(sys.argv[1:])
try:
container.run()
except KeyboardInterrupt:
| container.stop()
finally:
sys.exit()
if __name__ == "__main__":
main()
|
JoseTomasTocino/image-metadata-viewer | main.py | Python | lgpl-3.0 | 3,693 | 0.002709 | #!/usr/bin/env python
# coding: utf-8
import datetime
import subprocess
import logging
import json
import os
import sys
from io import BytesIO
import requests
from bottle import route, run, request
from bottle import jinja2_view as view, jinja2_template as template
logging.basicConfig(level=logging.INFO)
logger = lo... | s() if isinstance(v, dict)}
if 'ExifTool' in metadata:
del metadata['ExifTool']
# Try to build a summary of information
basic_info = {}
try:
basic_info['Dimensions'] = u"{} × {} {}".format(
metadata['File']['ImageWidth'],
metadata['File']['ImageHeight'],
... | :
basic_info['Artist'] = metadata['EXIF']['Artist']
if 'Copyright' in metadata['EXIF']:
basic_info['Copyright'] = metadata['EXIF']['Copyright']
if 'Model' in metadata['EXIF']:
basic_info['Camera'] = metadata['EXIF']['Model']
if 'LensModel' in metadata['EXIF... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.