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 |
|---|---|---|---|---|---|---|---|---|
arteria/django-userproperty | userproperty/utils.py | Python | bsd-2-clause | 7,025 | 0.001993 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from userproperty.models import UserProperty, GlobalProperty
def setIntegerProperty(request, name="", value=0, anUser=None):
"""
The user must not be an anonymous user!
"""
try:
if anUser is None:
theUser = request.user
else... | alse
def getGlobalProperty(name="", value=0):
"""Returns True if this Property is set.
"""
try:
prop = GlobalProperty.objects.get(name=name)
return bool(prop.value)
except GlobalProperty.DoesNotExist:
pass
return False
def getIntegerGlobalProperty(name=""):
"""Returns... | prop = GlobalProperty.objects.get(name=name)
return prop.value
except GlobalProperty.DoesNotExist:
pass
return 0
def incGlobalProperty(name="", incrementBy=1):
"""Increments value Field by given value, creates Property if DoesNotExist
"""
try:
try:
un = Glob... |
salimfadhley/jenkinsapi | jenkinsapi_tests/systests/test_invocation.py | Python | mit | 3,914 | 0 | """
System tests for `jenkinsapi.jenkins` module.
"""
import time
import logging
import pytest
from jenkinsapi.build import Build
from jenkinsapi.queue import QueueItem
from jenkinsapi_tests.test_utils.random_strings import random_string
from jenkinsapi_tests.systests.job_configs import LONG_RUNNING_JOB
from jenkinsapi... | b.invoke()
assert isinstance(qq, QueueItem)
# Let Jenkins catchup
qq.block_until_building()
assert qq.get_build_number() == 1
def test_get_block_until_build_running(jenkins):
job_name = 'Bcreate_%s' % random_string()
job = jenkins.create_job(job_name, LONG_RUNNING_JOB)
qq = job.invoke()
... | time.sleep(3)
bn = qq.block_until_building(delay=3).get_number()
assert isinstance(bn, int)
build = qq.get_build()
assert isinstance(build, Build)
assert build.is_running()
build.stop()
# if we call next line right away - Jenkins have no time to stop job
# so we wait a bit
time.slee... |
seece/modrip | lib/modtag/format.py | Python | mit | 4,161 | 0.033902 | from lib.modtag import *
from lib.modtag.tracker import *
from struct import unpack
class ModuleFormat():
"""Interface for different module formats."""
@property
def name(self):
raise NotImplementedError("module format must have a name")
@classmethod
def identify(cls, bytes):
"""Checks if the given bytes... | .append([])
for r in range(0, 63):
for c in range(song.num_channels-1):
ofs = r*song.num_channels*4 + c*4
#pattern.rows[c][i] = cls.parse_note(patternbytes[ofs:ofs+4])
pattern.rows[c].append(cls.parse_note(patternbytes[ofs:ofs+4]))
return pattern
# TODO add proper channel checks here
@classmetho... | if not options:
options = {'verbose': False}
#if modformat != TrackerSong.PROTRACKER:
# return None
song = TrackerSong()
#song.fmt = modformat
#song.name = str(unpack('20s', songbytes[0:20]), 'ascii')
song.num_channels = cls.get_num_channels(songbytes)
song.name = str(songbytes[0:20], 'ascii').rstr... |
DroneMapp/powerlibs-aws-sqs-dequeue_to_api | powerlibs/aws/sqs/dequeue_to_api/transformations.py | Python | mit | 1,829 | 0.000547 | import os
def url_get(dequeuer, url):
response = dequeuer.get(url)
response_data = response.json()
if 'results' in response_data:
return response_data['results']
else:
return [response_data]
def accumulate(dequeuer, payload, accumulators, url_getter=None):
last_level = [{'payloa... | mapped[key] = data_ | map[map_key]
else:
mapped[key] = value
return mapped
|
xueguangl23/brownClustering | twoGramModel.py | Python | mit | 2,028 | 0.011834 | from collections import Counter
from itertools import chain
from parser import getAllWords
DEBUG = True
class TwoGramModel(object):
def __init__(self,wordlist):
if DEBUG: print("building bi-gram model.")
WBAG = set(wordlist)
self.N = len(WBAG)
def replaceLoFreq(sentence):
... | if w2 not in (x1,x2):
continue
| if x1 == w2 and x2 == w2:
self.TwoGramCounter[(w1,w1)] += count
elif x1 == w2:
self.TwoGramCounter[(w1,x2)] += count
elif x2 == w2:
self.TwoGramCounter[(x1,w1)] += count
del self.TwoGramCounter[(x1,x2)]
if __name__ == '__main__':... |
vathpela/anaconda | pyanaconda/modules/boss/boss_interface.py | Python | gpl-2.0 | 3,496 | 0.000286 | # boss_interface.py
# Anaconda main DBUS module & module manager.
#
# Copyright (C) 2017 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later v... | me)
class BossInterface(InterfaceTemplate):
"""DBus interface for the Boss."""
def InstallSystemWithTask(self) -> ObjPath:
"""Install the system.
:retur | n: a DBus path of the main installation task
"""
return self.implementation.install_system_with_task()
def Quit(self):
"""Stop all modules and then stop the boss."""
self.implementation.stop()
@dbus_interface(BOSS_ANACONDA.interface_name)
class AnacondaBossInterface(BossInterface)... |
digling/cddb | datasets/Allen2007/__init__.py | Python | gpl-3.0 | 1,690 | 0.005329 | from pycddb.dataset import Dataset
from lingpy import Wordlist, csv2list
from lingpy.compare.partial import _get_slices
def prepare(ds):
errs = 0
wl = Wordlist(ds.raw('bds.tsv'))
W = {}
for k in wl:
value = wl[k, 'value']
tokens = wl[k, 'tokens']
doc = wl[k, 'docul | ect']
| if value:
morphemes = []
for a, b in _get_slices(wl[k, 'tokens']):
ipa = ''.join(tokens[a:b])
morphemes += [ipa]
ipa = ' '.join(morphemes)
clpa = ds.transform(ipa, 'CLPA')
struc = ds.transform(ipa, 'Structur... |
NicoVarg99/daf-recipes | ckan/ckan/ckan/ckan/tests/legacy/models/test_follower.py | Python | gpl-3.0 | 4,502 | 0 | # encoding: utf-8
import ckan.model as model
import ckan.lib.create_test_data as ctd
CreateTestData = ctd.CreateTestData
class FollowerClassesTests(object):
@classmethod
def teardown_class(cls):
model.repo.rebuild_db()
def test_get(self):
following = self.FOLLOWER_CLASS.get(self.followe... | ER_CLASS = model.UserFollowingGroup
@classmethod
def setup_class(cls):
model.repo.rebuild_db()
model.repo.new_revision()
cls.follower = CreateTestData.create_user('follower')
cls.followee = cls._create_group('followee')
cls.FOLLOWER_CLASS(cls.follower.id, cls.followee.id... |
@classmethod
def _create_deleted_models(cls):
deleted_user = CreateTestData.create_user('deleted_user')
cls.FOLLOWER_CLASS(deleted_user.id, cls.followee.id).save()
deleted_user.delete()
deleted_user.save()
deleted_group = cls._create_group('deleted_group')
cls.F... |
olety/FBD | fbd/storage.py | Python | mit | 19,799 | 0.000253 | #!/usr/local/bin/python3
# STL imports
import datetime
import json
import logging
import pprint
# Package imports
import dateutil.parser
import sqlalchemy
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (relationship, scoped_session, sessionmaker,
validate... | alchemy.String,
sqlalchemy.ForeignKey('Topic.id')),
)
class Topic(Base):
__tablename__ = 'Topic'
@classmethod
def from_dict(cls, topic_dict):
return cls(id=topic_dict.get('id'), name=topic_dict.get('name'))
def to_json(self):
return json.dumps(
self.... | id = sqlalchemy.Column(sqlalchemy.String(200), primary_key=True)
name = sqlalchemy.Column(sqlalchemy.String(100))
places = relationship('Place', secondary=place_topic)
@validates('name')
def validate_trunc(self, key, value):
max_len = getattr(self.__class__, key).prop.columns[0].type.length... |
jianwei1216/my-scripts | python_script/fast.py | Python | gpl-2.0 | 3,500 | 0.008 | #!/usr/bin/python
# new
import argparse
import sys
import os
import ssh
import time
sys.path.append('./')
from log import fastlog
def get_ssh_client(host):
global args
try:
client = ssh.SSHClient()
client.set_missing_host_key_policy(ssh.AutoAddPolicy())
client.connect(host, port=int(a... | cept Exception, e:
print host, e
fastlog.error ("%s:%s" % (host, e))
return None
return client
def __despatch_cmd(host, cmd):
client = get_ssh_client(host)
if client == None:
return None
stdin, stdout, stderr = client.exec_command(cmd)
err = stderr.read()
out = ... | :
print host, out,
out = out[0:-1]
fastlog.info ("%s: %s" % (host, out))
if len(err) > 0:
print host, err,
err = err[0:-1]
fastlog.error ("%s: %s" % (host, err))
client.close()
def multi_fork(nodes, cmd):
pids = []
for host in nodes:
try:
... |
nodakai/watchman | tests/integration/test_site_spawn.py | Python | apache-2.0 | 2,338 | 0.001283 | # vim:ts=4:sw=4:et:
# Copyright 2016-present Facebook, Inc.
# Licensed under the Apache License, Version 2.0
# no unicode literals
from __future__ import absolute_import, division, print_function
import json
import os
import pywatchman
import WatchmanInstance
try:
import unittest2 as unittest
except ImportErro... | "stderr", stderr)
stderr = stderr.decode("ascii")
self.assertEqual(b"", stdout)
self.assertRegex(stderr, "failed to start\n")
self.assertRegex(stderr, "site_spawn_fail.py: exited with status 1")
def test_no_site_spawner(self):
"""With a site spawner configured to otherwise f... | ce": os.path.join(THIS_DIR, "site_spawn_fail.py")
}
inst = WatchmanInstance.Instance(config=config)
stdout, stderr = inst.commandViaCLI(["version", "--no-site-spawner"])
print(stdout, stderr.decode("ascii"))
parsed = json.loads(stdout.decode("ascii"))
self.assertTrue("v... |
mchrzanowski/ProjectEuler | src/python/Problem030.py | Python | mit | 579 | 0.008636 | '''
Created on Jan 11, 2012
@author: mchrzanowski
'''
__LIMIT = 999999 # as 999999 > 6 * 9 ^ 5 , this is our ceiling.
__POWER = 5
def main():
winners = set([])
for number in xrange(2, __LIMIT): # exclude 1 as it's not a sum (but would qua | lify)
numberString = str(number)
addedValue = 0
for numeral in numberString:
addedValue = addedValue + int(numeral) ** __POWER
if addedValue == number:
winners.add(number)
print "Numbers: ", winners
prin | t "Sum: ", sum(winners)
if __name__ == '__main__':
main() |
martbhell/wasthereannhlgamelastnight | src/lib/google/oauth2/service_account.py | Python | mit | 25,866 | 0.000464 | # Copyright 2016 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, ... | d
def _from_signer_and_info(cls, signer, | info, **kwargs):
"""Creates a Credentials instance from a signer and service account
info.
Args:
signer (google.auth.crypt.Signer): The signer used to sign JWTs.
info (Mapping[str, str]): The service account info.
kwargs: Additional arguments to pass to the c... |
theju/dtwt | accounts/models.py | Python | mit | 160 | 0 | from django.db import models
from django.con | trib.auth.models import AbstractUser
class Us | er(AbstractUser):
phone_number = models.CharField(max_length=15)
|
MrMasterBaiter/entropy-ai | entropy server/server/server.py | Python | gpl-2.0 | 3,332 | 0.032713 | # main.py: Provides the server client infra for gaming
# python2 server.py <port> <max_clients>
# YES YOU CAN ONLY USE PYTHON "2" and NOT "3".
import os, sys, socket, signal, game, json, humanSocket
if (os.path.realpath('../utils') not in sys.path):
sys.path.insert(0, os.path.realpath('../utils'))
from log import *
... | Some keys are REQUIRED. maybe check that they are present.
print ('Server config:', config)
def letClientsJoin():
global connections, sock
port = int(config.get('port'))
hostname = '0.0.0.0'
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((hostname, port))
sock.listen(1)
print ('Listening o... | for 20s' % (hostname, port))
signal.signal(signal.SIGALRM, lambda x: (_ for _ in ()).throw(Exception('TimeOut')) )
signal.alarm(20)
try:
while True:
# Wait for connections
print 'Waiting'
conn, addr = sock.accept()
botname = conn.recv(100) # a client must return information...
# conn.setblocking(1)
... |
vlegoff/tsunami | src/secondaires/navigation/equipage/postes/voilier.py | Python | bsd-3-clause | 1,769 | 0.000566 | # -*-coding:Utf-8 -*
# Copyright (c) 2010-2017 LE GOFF Vincent
# 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
# ... | R 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 TH | E
# POSSIBILITY OF SUCH DAMAGE.
"""Fichier contenant le poste voilier."""
from . import Poste
class Voilier(Poste):
"""Classe définissant le poste voilier."""
nom = "voilier"
autorite = 15
nom_parent = "officier"
|
google/google-ctf | 2021/quals/kctf/challenge-templates/pwn/healthcheck/healthcheck.py | Python | apache-2.0 | 1,160 | 0.001724 | #!/usr/bin/env python3
# -*- 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | )
print(r.recvuntil(b' solve '))
challenge = r.recvline().decode('ascii').strip()
p = pwnlib.tubes.process.process(['kctf_bypass_pow', challenge])
solution = p.readall().strip()
| r.sendline(solution)
print(r.recvuntil(b'Correct\n'))
r = pwnlib.tubes.remote.remote('127.0.0.1', 1337)
print(r.recvuntil('== proof-of-work: '))
if r.recvline().startswith(b'enabled'):
handle_pow(r)
print(r.recvuntil(b'CTF{'))
print(r.recvuntil(b'}'))
exit(0)
|
alexryndin/ambari | ambari-server/src/test/python/stacks/2.0.6/HIVE/test_hive_service_check.py | Python | apache-2.0 | 16,060 | 0.03655 | #!/usr/bin/env python
'''
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License")... | ecute', ' /tmp/hcatSmok | e.sh hcatsmoke cleanup false',
logoutput = True,
path = ['/usr/sbin',
'/usr/local/bin',
'/bin',
'/usr/bin',
'/bin:/usr/hdp/current/hive-server2/bin:/usr/bin'],
tries = 3,
user = 'ambari-qa',
try_sleep = 5,
)
self.assertResourceC... |
SolusOS-discontinued/RepoHub | profiles/views.py | Python | mit | 785 | 0.03949 | # Create your views here.
from django.http import HttpRe | sponse
from django.shortcuts import render, get_object_or_404
from django.contrib.auth.models import User
from repository.models import PisiPackage
def show_user (request, name=None):
user = get_object_or_404 (User, username=name)
context = { 'user' : user }
packages = None
try:
packages = PisiPackage.object... | pdated")
count = len(packages)
total_packages = len(PisiPackage.objects.all())
pct = float (float(count) / (total_packages)) * 100
packages = packages[:7]
context = { 'user': user, 'package_count': count, 'package_ratio': pct, 'packages': packages}
except Exception, e:
print e
pass
return rende... |
gnu-sandhi/sandhi | modules/gr36/grc/examples/xmlrpc/xmlrpc_client_script.py | Python | gpl-3.0 | 463 | 0.034557 | # | !/usr/bin/env python
import time
import random
import xmlrpclib
#create server object
s = xmlrpclib.Server("http://localhost:1234")
#randomly change parameters of the sinusoid
for i in range(10):
#generate random values
new_freq = random.uniform(0, 5000)
new_ampl = random.uniform(0, 2)
new_offset = random.unifor... | _ampl(new_ampl)
time.sleep(1)
s.set_offset(new_offset)
|
CCI-MOC/GUI-Backend | core/migrations/0041_user_ssh_keys.py | Python | apache-2.0 | 1,036 | 0.001931 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
import uuid
class Migration(migrations.Migration):
dependencies = [
('cor | e', '0040_auto_add_status_types'),
]
operations = [
migrations.CreateModel(
name='SSHKey',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary | _key=True)),
('name', models.CharField(max_length=256)),
('uuid', models.CharField(default=uuid.uuid4, unique=True, max_length=36)),
('pub_key', models.TextField()),
('atmo_user', models.ForeignKey(to=settings.AUTH_USER_MODEL)),
],
... |
archivsozialebewegungen/AlexandriaBase | alexandriabase/tools.py | Python | gpl-3.0 | 5,581 | 0.008067 | '''
Created on 15.11.2021
@author: michael
'''
from alexandriabase.daos import DocumentDao, DaoModule, DOCUMENT_TABLE,\
DocumentFileInfoDao
from injector import Injector, inject
from alexandriabase import AlexBaseModule
from alexandriabase.services import ServiceModule, DocumentFileManager,\
DocumentFileNotFou... | file_provider: | FileProvider,
reference_service: ReferenceService):
self.dao = dao
self.file_info_dao = file_info_dao
self.file_manager = file_manager
self.file_provider = file_provider
self.reference_service = reference_service
self.titel = "Plakate i... |
Greymerk/python-rpg | src/player/__init__.py | Python | gpl-3.0 | 26 | 0 | from | player import Player
| |
Johnetordoff/osf.io | addons/zotero/views.py | Python | apache-2.0 | 2,789 | 0.001076 | # -*- coding: utf-8 -*-
from flask import request
from .provider import ZoteroCitationsProvider
from website.citations.views import GenericCitationViews
from website.project.decorators import (
must_have_addon, must_be_addon_authorizer,
must_have_permission, must_not_be_registration,
must_be_contributor_or... | _addon,
user_settings=auth.user.get_addon(addon_short_name),
).serialized_node_settings
}
_set | _config.__name__ = '{0}_set_config'.format(addon_short_name)
return _set_config
def library_list(self):
addon_short_name = self.addon_short_name
@must_be_contributor_or_public
@must_have_addon(addon_short_name, 'node')
def _library_list(auth, node_addon, **kwargs):
... |
etingof/pyasn1-modules | tests/test_rfc6402.py | Python | bsd-2-clause | 6,395 | 0.001095 | #
# This file is part of pyasn1-modules software.
#
# Created by Russ Housley
# Copyright (c) 2019, Vigil Security, LLC
# License: http://snmplabs.com/pyasn1/license.html
#
import sys
import unittest
from pyasn1.codec.der.decoder import decode as der_decoder
from pyasn1.codec.der.encoder import encode as der_encoder
f... | r[next_layer](asn1Object)
def testOpenTypes(self):
class ClientInformation(univ.Sequence):
pass
ClientInformation.componentType = namedtype.NamedTypes(
namedtype.NamedType('clientId', univ.Integer()),
namedtype.NamedType('MachineName', char.UTF8String()),
... | univ.Sequence):
pass
EnrollmentCSP.componentType = namedtype.NamedTypes(
namedtype.NamedType('KeySpec', univ.Integer()),
namedtype.NamedType('Name', char.BMPString()),
namedtype.NamedType('Signature', univ.BitString())
)
openTypeMap = {
... |
PythonCharmers/orange3 | Orange/widgets/gui.py | Python | gpl-3.0 | 126,299 | 0.000515 | import math
import os
import re
import itertools
from types import LambdaType
import pkg_resources
import numpy
from PyQt4 import QtGui, QtCore, QtWebKit
from PyQt4.QtCore import Qt, pyqtSignal as Signal
from PyQt4.QtGui import QCursor, QApplication
import Orange.data
from Orange.widgets.utils import getdeepattr
fro... | col_count = max(len(items), self.columnCount())
if col_coun | t != self.columnCount():
self.setColumnCount(col_count)
for col, item_data in enumerate(items):
if isinstance(item_data, str):
name = item_data
elif hasattr(item_data, '__iter__') and len(item_data) == 2:
name, item_data = item_data
... |
naresh21/synergetics-edx-platform | cms/djangoapps/contentstore/courseware_index.py | Python | agpl-3.0 | 27,600 | 0.003043 | """ Code to allow module store to interface with courseware index """
from __future__ import absolute_import
from abc import ABCMeta, abstractmethod
from datetime import timedelta
import logging
import re
from six import add_metaclass
from django.conf import settings
from django.utils.translation import ugettext_lazy,... | self.error_list = error_list
@add_metaclass(ABCMeta)
class SearchIndexerBase(object):
"""
Base class to perform indexin | g for courseware or library search from different modulestores
"""
__metaclass__ = ABCMeta
INDEX_NAME = None
DOCUMENT_TYPE = None
ENABLE_INDEXING_KEY = None
INDEX_EVENT = {
'name': None,
'category': None
}
@classmethod
def indexing_is_enabled(cls):
"""
... |
openstack/neutron-lib | neutron_lib/api/definitions/tag_ports_during_bulk_creation.py | Python | apache-2.0 | 1,024 | 0 | # Copyright (c) 2019 Verizon Media
# 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 require... | xpress or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
ALIAS = 'tag-ports-during-bulk-creation'
IS_SHIM_EXTENSION = True
IS_STANDARD_ATTR_EXTENSION = False
NAME = 'Tag Ports During Bulk Creation'
DESCRIPTION = 'Allow to tag ports during bulk cre... | STATUS = {}
|
AxisPhilly/lobbying.ph-django | lobbyingph/migrations/0030_auto__add_field_agency_alias.py | Python | mit | 14,317 | 0.007753 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Agency.alias'
db.add_column('lobbyingph_agency', 'alias',
self.gf('dja... |
'issue': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['lobbyingph.Issue']", 'null': 'True', 'blank': 'True'}),
'methods': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['lobbyingph.Communication_Method']", 'null': 'True', 'blank': '... | k': 'True'}),
'other_desc': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'position': ('django.db.models.fields.SmallIntegerField', [], {})
},
'lobbyingph.exp_other': {
'Meta': {'object_name': 'Exp_Other'},
... |
osbd/osbd-2016 | slides/crist/get_data.py | Python | mit | 1,419 | 0 | import os
import urllib
from glob import glob
import dask.bag as db
import numpy as np
import zarr
from dask.diagnostics import ProgressBar
from netCDF4 import Dataset
def download(url):
opener = urllib.URLopener()
filename = os.path.basename(url)
path = os.path.join('data', filename)
opener.retrieve... | -------")
with ProgressBar():
b.map(download).compute(n_workers=8)
def transform_weather():
if os.path.exists('sst.day.mean.v2.zarr'):
return
datasets = [Dataset(path)['sst'] for path in sorted(glob('data/*.nc'))]
n = sum(d.shape[0] for d in datasets)
shape = (n, 720, 1440)
chu... | zarr.open_array('sst.day.mean.v2.zarr', shape=shape, chunks=chunks,
dtype='f4')
i = 0
for d in datasets:
m = d.shape[0]
f[i:i + m] = d[:].filled(np.nan)
i += m
if __name__ == '__main__':
download_weather()
transform_weather()
|
CommitAnalyzingService/CAS_Analyzer | githubissuetracker.py | Python | gpl-2.0 | 3,106 | 0.03123 | """
file: gitissuetracker.py
author: Christoffer Rosen <cbr4830@rit.edu>
date: December, 2013
description: Represents a Github Issue tracker object used
for getting the dates issues were opened.
12/12/13: Doesn't currently support private repos
"""
import requests, json, dateutil.parser, time
from caslogging impor... | err | or("ISSUE TRACKER FAILURE: Could not get created_at from github issues API")
return None
|
bregman-arie/ansible | lib/ansible/modules/packaging/os/redhat_subscription.py | Python | gpl-3.0 | 28,269 | 0.002299 | #!/usr/bin/python
# James Laska (jlaska@redhat.com)
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['prev... | pool_ids) instead if
| possible, as it is much faster. Mutually exclusive with I(pool_ids).
default: '^$'
pool_ids:
description:
- |
Specify subscription pool IDs to consume. Prefer over I(pool) when possible as it is much faster.
A pool ID may be specified as a C(string) - j... |
gagoncal/Selenium | setuptools-21.2.2/setuptools/tests/test_test.py | Python | lgpl-2.1 | 2,373 | 0 | # -*- coding: UTF-8 -*-
from __future__ import unicode_literals
import os
import site
from distutils.errors import DistutilsError
import pytest
from setuptools.command.test import test
from setuptools.dist import Distribution
from .textwrap import DALS
from . import contexts
SETUP_PY = DALS("""
from setuptool... | S("""
import unittest
class TestTest(unittest.TestCase):
def test_test(self):
print "Foo" # Should fail under Python 3 unless 2to3 is used
test_suite = unittest.makeSuite | (TestTest)
""")
@pytest.fixture
def sample_test(tmpdir_cwd):
os.makedirs('name/space/tests')
# setup.py
with open('setup.py', 'wt') as f:
f.write(SETUP_PY)
# name/__init__.py
with open('name/__init__.py', 'wb') as f:
f.write(NS_INIT.encode('Latin-1'))
# name/space/__init... |
uber/pyro | pyro/contrib/oed/util.py | Python | apache-2.0 | 1,232 | 0.002435 | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import math
import torch
from pyro.contrib.oed.glmm import analytic_posterior_cov
f | rom pyro.contrib.util import get_indices
from pyro.infer.autoguide.utils import mean_field_entropy
def linear_model_ground_truth(
model, design, observation_labels, target_labels, eig=True
):
if isinstance(target_labels, str):
target_labels = [target_labels]
w_sd = torch.cat(list(model.w_sds.valu... | analytic_posterior_cov(prior_cov, x, model.obs_sd)
for x in torch.unbind(design.reshape(-1, design_shape[-2], design_shape[-1]))
]
target_indices = get_indices(target_labels, tensors=model.w_sds)
target_posterior_covs = [
S[target_indices, :][:, target_indices] for S in posterior_covs
]
... |
cernanalysispreservation/analysis-preservation.cern.ch | cap/modules/repos/models.py | Python | gpl-2.0 | 6,089 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of CERN Analysis Preservation Framework.
# Copyright (C) 2016 CERN.
#
# CERN Analysis Preservation Framework is free software; you can redistribute
# it and/or modify it under the terms of the GNU Genera | l Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# CERN Analysis Preservation Framework is distributed in the hope that it will
# be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHA | NTABILITY 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 CERN Analysis Preservation Framework; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA ... |
daodaoliang/python-phonenumbers | python/phonenumbers/geodata/data9.py | Python | apache-2.0 | 912,681 | 0.021683 | """Per-prefix data, mapping each prefix to a dict of locale:name.
Auto-generated file, do not edit by hand.
"""
from ..util import u
# Copyright (C) 2011-2015 The Libphonenumber Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Licens... | \u5c71\u5e02')},
'861365227':{'en': 'Foshan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701 | \u4f5b\u5c71\u5e02')},
'861365224':{'en': 'Zhuhai, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u73e0\u6d77\u5e02')},
'861365225':{'en': 'Zhuhai, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u73e0\u6d77\u5e02')},
'861365222':{'en': 'Zhongshan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4e2d\u5c71\u5e02')},
'861365223':{'en': '... |
Aigrefin/py3learn | learn/tests/tests_views/tests_exercise_wrong_answer.py | Python | mit | 943 | 0.002121 | from unittest import TestCase
from unittest.mock import patch, call, MagicMock
from django.test import RequestFactory
from learn.infrastructure.database import Database
from learn.views.wrong_answer import exercise_wrong_answer
class ExerciseWrongAnswerTests(TestCase):
@patch("learn.views.wrong_answer.render")
... | ictionary | _pk': 23,
'translation_pk': 42,
'translation': database.get_translation()
})
self.assertEqual(render_mock.call_args_list[0], expected_args)
|
shagi/guifiadmin | quotas/management/commands/quotaInvoices.py | Python | agpl-3.0 | 870 | 0.001149 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
from django.core.management import BaseCommand
from django.utils.translation import ugettext_lazy as _
from django.utils.timezone import now, make_aware, utc
from quotas import models
DATE_FORMAT = "%Y-%m-%d"
class Command(BaseCommand... | arser.add_argument('-d', '--date', metavar="YYYY-MM-DD", help=_('Create quotas for the month of th | e given date.'))
def handle(self, *args, **options):
date = options['date']
if date is None:
date = now()
else:
date = make_aware(
datetime.datetime.strptime(date, DATE_FORMAT),
utc,
)
print date
models.Quo... |
nvbn/thefuck | tests/output_readers/test_rerun.py | Python | mit | 2,942 | 0.00068 | # -*- encoding: utf-8 -*-
from mock import Mock, patch
from psutil import AccessDenied, TimeoutExpired
from thefuck.output_readers import rerun
class TestRerun(object):
def setup_method(self, test_method):
self.patcher = patch('thefuck.output_readers.rerun.Process')
process_mock = self.patcher.s... | assert rerun.get_output('', '') is None
wait_output_mock.assert_called_once()
@patch('thefuck.output_readers.rerun.Popen')
| def test_get_output_invalid_continuation_byte(self, popen_mock):
output = b'ls: illegal option -- \xc3\nusage: ls [-@ABC...] [file ...]\n'
expected = u'ls: illegal option -- \ufffd\nusage: ls [-@ABC...] [file ...]\n'
popen_mock.return_value.stdout.read.return_value = output
actual = ... |
rplevka/robottelo | tests/foreman/cli/test_katello_agent.py | Python | gpl-3.0 | 11,288 | 0.001329 | """CLI tests for ``katello-agent``.
:Requirement: Host
:CaseAutomation: Automated
:CaseLevel: Component
:CaseComponent: Katello-agent
:Assignee: gtalreja
:TestType: Functional
:CaseImportance: High
:Upstream: No
"""
import time
import pytest
from broker import VMBroker
from robottelo.api.utils import wait_for... | """
client = katello_agent_client['client']
host_info = katello_agent_client['host_info']
client.download_install_rpm(settings.repos.yum_1.url, FAKE_2_CUSTOM_PACKAGE)
# Check the system is up to date
result = client.run('yum update --security | grep "No packages needed for security"')
assert res... | me())
# Downgrade walrus package
client.run(f'yum downgrade -y {FAKE_2_CUSTOM_PACKAGE_NAME}')
# Wait for errata applicability cache is counted
wait_for_errata_applicability_task(int(host_info['id']), before_downgrade)
# Check that host has applicable errata
host_errata = Host.errata_list({'host-... |
eegroopm/pyLATTICE | resources/common.py | Python | gpl-2.0 | 2,942 | 0.027872 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 21 10:34:18 2014
@author: eegroopm
"""
import os, sys
import pandas as pd
import numpy as np
class common:
def __init__(self):
self.path = os.path.expanduser('~')
#\u0305 is unicode overline character
#self._overline_strings = [u'1\u0305', u'2... | erently. GAH!!
self.sg = pd.read_hdf('resources/SpaceGroups.h5','table')
self.sghex = pd.read_hdf('resources/SpaceGroupsHex.h5','table') #for trigonal crystals with rhombohedral or hexagonal centering
self.mineraldb = pd.read_hdf('resources/MineralDatabase.h5','table')
elif s... | ex_py2.h5','table')
self.mineraldb = pd.read_hdf('resources/MineralDatabase_py2.h5','table')
self.manualConds = [] #empty list of strings for manual conditions
def Wavelength(self,E):
hbar = 6.626E-34 #m^2 kg/s
me = 9.109E-31 #kg
c = 3E8 #m/s
... |
codingjoe/django-vies | tests/__init__.py | Python | mit | 157 | 0 | VA | LID_VIES = "LU26375245"
VALID_VIES_COUNTRY_CODE = "LU"
VALID_VIES_NUMBER = "26375245"
VALID_VIES_IE = [
"1234567X",
"1X23456X",
" | 1234567XX",
]
|
Vinay26k/python | SourceForge/Website_to_pdf/Website2PdfCore.py | Python | mit | 643 | 0.018663 | import urllib.request as ul
from bs4 import B | eautifulSoup as bs
from time import sleep
import pdfkit
import os.path
from datetime import datetime
url = None
def converter(url,direc=None):
path = r'./wkhtmltopdf.exe'
if not direc:
direc = "./Website2Pdf"
else:
direc = direc + "/Website2Pdf"
if not os.path | .exists(direc):
os.makedirs(direc)
config = pdfkit.configuration(wkhtmltopdf = path)
name = url.split('/')[-2]+".pdf"
fname = direc+'/'+url.split('/')[-2]+".pdf"
#print(fname)
pdf = pdfkit.from_url(url,fname,configuration = config)
#print("Done")
return True,name
|
namili/blueman | blueman/plugins/applet/StatusIcon.py | Python | gpl-3.0 | 3,189 | 0.039511 | # Copyright (C) 2008 Valmantas Paliksa <walmis at balticum-tv dot lt>
# Copyright (C) 2008 Tadas Dailyda <tadas at dailyda dot com>
#
# Licensed under the GNU General Public License Version 3
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License ... | FORCE_HIDE = 0
def on_load(self, applet):
gtk.StatusIcon.__init__(self)
self.lines = {}
self.pixbuf = None
| self.connect("size-changed", self.on_status_icon_resized)
self.SetTextLine(0, _("Bluetooth Enabled"))
AppletPlugin.add_method(self.on_query_status_icon_visibility)
AppletPlugin.add_method(self.on_status_icon_pixbuf_ready)
def on_bluetooth_power_state_changed(self, state):
if state:
self.SetText... |
KunihikoKido/sublime-elasticsearch-client | commands/indices_get_warmer.py | Python | mit | 460 | 0 | from .base import BaseCommand
class IndicesGetWarmerCommand(BaseCommand | ):
command_name = "elasticsearch:indices-get-warmer"
def is_enabled(self):
return True
def run_request(self, name=None):
if not name:
self.show_warmer_list_panel(self.run)
return
options = dict(
index=self.sett | ings.index,
name=name
)
return self.client.indices.get_warmer(**options)
|
jiadaizhao/LeetCode | 1501-1600/1502-Can Make Arithmetic Progression From Sequence/1502-Can Make Arithmetic Progression From Sequence.py | Python | mit | 264 | 0 | class Solution:
def canMakeArithmeticProgression(self, arr: List[int]) -> bool:
arr.sort()
diff = arr[1] - arr[0]
for i in range(2, len(arr)):
if arr[i] - arr[i - | 1] != diff:
return False
| return True
|
ironfroggy/django-better-cache | bettercache/tests/test_views.py | Python | mit | 1,632 | 0.001225 | from unittest import TestCase
try:
from unittest import mock
except ImportError:
import mock
from bettercache.view | s import BetterView
class TestView(TestCase):
def | setUp(self):
self.view = BetterView()
self.view.should_bypass_cache = lambda x: False
self.view.get_cache = lambda x: (None, None, )
self.view.set_cache = lambda x, y: True
self.request = mock.Mock()
self.request.build_absolute_uri = lambda : '_'
@mock.patch('betterc... |
simras/CLAP | scripts/mk_ErrorModel.py | Python | mit | 1,940 | 0.028351 | #!/usr/bin/python
# mk_ErrorModel.py -m 0.125
# Example
# By Simon H. Rasmussen
# Bioinformatics Centre
# University of Copenhagen
#
def wLines(mutP):
# range of qualities 0...41
for qual in range(42):
for base in ["A","C","G","T"]:
# quality base P(a|base) P(c|base) P(g|base... | turn 1 - p
elif f == to:
# No mutation
return 1
else:
# No mutation and f and to are different that's impossible
return 0
if __name__ == "__main__":
from optparse impor | t OptionParser
parser = OptionParser()
parser.add_option("-m", action="store", type="float", dest="mutP", default=0.125, help="P(\"t\"|\"c\"): t to c mutation probability")
(options, args) = parser.parse_args()
wLines(options.mutP)
|
datakid/tvet | tafe/migrations/0058_auto__chg_field_timetable_year.py | Python | gpl-3.0 | 25,222 | 0.007692 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'Timetable.year'
db.alter_column('tafe_timetable', 'year', self.gf('django.db.models.field... | ission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
| 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailF... |
chocoelho/twitter-activities-monitor | users/models.py | Python | mit | 1,296 | 0 | from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from django.db import models
from django.db.models.signals import post_save
from django.utils.translation import ugettext_lazy as _
from common.models import IndexedTimeStampedModel
from tweets.models import Timeline
from .managers import UserMa... | ('Designates whether the user can log into this admin '
'site.'))
is_active = models.Boole | anField(
default=True,
help_text=_('Designates whether this user should be treated as '
'active. Unselect this instead of deleting accounts.'))
objects = UserManager()
USERNAME_FIELD = 'username'
def get_full_name(self):
return self.email
def get_short_nam... |
orlenko/plei | pleiapp/admin.py | Python | bsd-2-clause | 5,888 | 0.005944 | from copy import deepcopy
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from mezzanine.conf import settings
from mezzanine.core.admin import DisplayableAdmin, OwnableAdmin
from pleiapp.models import (FrontPageItem,
Type,
... | list_display =['__str__', | 'visible']
list_filter = ['visible',]
class FrontPageItemAdmin(admin.ModelAdmin):
list_display = ['__str__', 'admin_thumb', 'visible']
list_filter = ['visible',]
admin.site.register(Resource, ResourceAdmin)
admin.site.register(Faq, FaqAdmin)
admin.site.register(Dictionary, DictionaryAdmin)
admin.site.r... |
sridevikoushik31/nova | nova/db/sqlalchemy/utils.py | Python | apache-2.0 | 10,646 | 0.000376 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2013 Boris Pavlovic (boris@pavlovic.me).
# 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
#
# ... | ific language governing permissions and limitatio | ns
# under the License.
from migrate.changeset import UniqueConstraint
from sqlalchemy.engine import reflection
from sqlalchemy.ext.compiler import compiles
from sqlalchemy import func
from sqlalchemy import MetaData, Table, Column, Index
from sqlalchemy.sql.expression import UpdateBase, literal_column
from sqlalch... |
chipx86/reviewboard | reviewboard/diffviewer/models/legacy_file_diff_data.py | Python | mit | 837 | 0 | """LegacyFileDiffData model defitnition."""
from __future__ import unicode_literals
from django.db import models
from d | jango.utils.translation import ugettext_lazy as _
from djblets.db.fields import Base64Field, JSONField
class LegacyFileDiffData(models.Model):
"""Deprecated, legacy class for base64-encoded diff data.
This is no longer populated, and e | xists solely to store legacy data
that has not been migrated to :py:class:`RawFileDiffData`.
"""
binary_hash = models.CharField(_('hash'), max_length=40, primary_key=True)
binary = Base64Field(_('base64'))
extra_data = JSONField(null=True)
class Meta:
app_label = 'diffviewer'
... |
benkuhn/benkuhn.net | bknet/wsgi.py | Python | mit | 1,132 | 0.000883 | """
WSGI config for bknet project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` se... | ually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
f | ramework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bknet.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
app... |
vdemir/pisi_package | LXQT/addon/qterminal/actions.py | Python | gpl-3.0 | 607 | 0.00659 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Licensed under the GNU General Public License, version 3.
# See the file http://www.gnu.org/copyleft/gpl.txt
from pisi.actionsapi import cmaketools |
from pisi.actionsapi import get
from pisi.actionsapi import pisitools
def setup():
cmaketools.configure("-DCMAKE_BUI | LD_TYPE:STRING=Release \
-DCMAKE_INSTALL_PREFIX=/usr \
-DCMAKE_INSTALL_LIBDIR=/usr/lib")
def build():
cmaketools.make()
def install():
cmaketools.rawInstall("DESTDIR=%s" % get.installDIR())
pisitools.dodoc("AUTHORS", "COPYING") |
ianfelzer1/ifelzer-advprog | ianfelzer/calculator.py | Python | gpl-3.0 | 167 | 0.041916 | def add(a,b):
| c = a + b
return c
def sub(a,b):
c = a - b
return c
def mul(a,b):
c = a * b |
return c
def div(a,b):
c = a / b
return c
|
jpush/jbox | Server/jbox/plugins/discourse.py | Python | mit | 3,219 | 0.00466 | import time
from flask import abort, Flask, jsonify, request
from . import plugins
from ..models import Developer, Integration
import jpush
from jpush import common
from .github import baseurl
@plugins.route('/discourse/<string:integration_id>/<string:token>/webhook', methods=['POST'])
def send_discourse_msg(integrat... | equest.json:
message_url = request.json['url']
print("the message url " + message_url)
android_msg = jpush.android(alert=request.json['title'], extras={'title': request.json['title'],
'message': request.json['message']})
ios_msg =... | )
# ios_msg = jpush.ios(alert=request.json['title'], extras={'title': request.json['title']})
print(integration.icon)
if integration.icon is None or len(integration.icon) == 0:
url = ''
else:
url = baseurl + '/static/images/' + integration.icon
push.notification = jpush.notification(... |
Azure/azure-sdk-for-python | sdk/compute/azure-mgmt-compute/azure/mgmt/compute/v2020_10_01_preview/aio/operations/_cloud_service_roles_operations.py | Python | mit | 7,860 | 0.004198 | # 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 ... | oup_name=re | source_group_name,
cloud_service_name=cloud_service_name,
subscription_id=self._config.subscription_id,
template_url=self.list.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.for... |
tallus/pos-scale-emulator | swrapper.py | Python | gpl-3.0 | 20,895 | 0.009476 | #!/usr/bin/env python
'''Module that provides functionality to emulate pos scales with
serial interfaces'''
# Copyright Paul Munday 2013
# 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 Fou... | raise SignalException('expected: ' + self.weight_request
+ 'got: ' + str(ord(self.signal)))
# def get_weight(self,signal):
# self.signal = signal
# read_weight = read_weight(self.signal)
# # insert conversion here
# weight = read_weight
# return | weight
def pos_test(self, dummy_weight):
'''Tests to ensure we can receive the correct command from the pos,
and that it correctly receives the weight. Used for debugging.
You will need to manually initiate a weight request on the pos by
adding a product (marked scale in properties... |
data-driven-science/ddsm-cloud | common/__init__.py | Python | mit | 101 | 0 | # The c | ommon module
# from common import models
# from common import tools
# from common i | mport core
|
hyiltiz/cloudmusicbox | scripts/listdir.py | Python | gpl-3.0 | 213 | 0.093897 | import os
def recurdir():
cwd=os.getcwd();
dirlist=os.listdir(cwd)
for i in | dirlist:
if(os.path.isdir(i)):
os.chdir(cwd+'/'+i);
recurdir()
os.chdir(cwd);
else:
| print(cwd+'/'+i)
recurdir() |
tekton/DocuCanvas | accounts/migrations/0010_auto__add_usertemplates__add_unique_usertemplates_user_viewName.py | Python | gpl-3.0 | 8,389 | 0.008225 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'UserTemplates'
db.create_table(u'accounts_usertemplates', (
(u'id', self.gf('dja... | db.create_unique(u'accounts_usertemplates', ['user_id', 'viewName'])
def backwards(self, orm):
# Removing unique constraint on 'UserTemplates', fields ['user', 'viewName']
db.delete_unique(u'accounts_usertemplates', ['user_id', 'viewName'])
# Deleting model 'UserTemplates'
db.de... | 'assignable': ('django.db.models.fields.NullBooleanField', [], {'null': 'True', 'blank': 'True'}),
'avatar': ('django.db.models.fields.CharField', [], {'default': "'/static/img/pony.png'", 'max_length': '255', 'null': 'True', 'blank': 'True'}),
'facebook': ('django.db.models.fields.CharField',... |
brianzi/quantumsim | quantumsim/pauli_vectors/pauli_vector.py | Python | gpl-3.0 | 3,533 | 0 | import abc
import pytools
from quantumsim.algebra.algebra import dm_to_pv, pv_to_dm
class PauliVectorBase(metaclass=abc.ABCMeta):
"""A metaclass, that defines standard interface for Quantumsim density
matrix backend.
Every instance, that implements the interface of this class, should call
`super().__... | actmethod
def renormalize(self):
pass
@abc.abstractmethod
def copy(self):
pass
def _validate_qubit(self, number, name):
if number < 0 or number >= self.n_qubits:
raise ValueError(
"`{name}` number {n} does not exist in the system, "
"... | .format(name=name, n=number, n_qubits=self.n_qubits))
# noinspection PyMethodMayBeStatic
def _validate_ptm_shape(self, ptm, target_shape, name):
if ptm.shape != target_shape:
raise ValueError(
"`{name}` shape must be {target_shape}, got {real_shape}"
.format(... |
RobAltena/deeplearning4j | libnd4j/include/graph/generated/nd4j/graph/UIHistogramType.py | Python | apache-2.0 | 176 | 0.005682 | # aut | omatically generated by the FlatBuffers compiler, do not modify
# namespace: graph
class UIHistogramType(object):
DISCRETE = 0
EQUAL_SPAC | ING = 1
CUSTOM = 2
|
razzius/PyClassLessons | instructors/projects/decoding_fun/examples/rot13.py | Python | mit | 2,202 | 0.008174 | """
A sample encryption library using rot13.
"""
# File encoding PEP, see: http://legacy.python.org/dev/peps/pep-0263/
# -*- coding: utf-8 -*-
import re
alphabet = 'abcdefghijklmnopqrstuvwxyz'
def assign_and_return_positions(alphabet, rotation):
""" Build and return a dictionary for substitution.
"""
... | return rotation_dict
def apply_substitution(subst_dict, cleaned_string):
""" Apply a substitution dictionary to a string.
"""
encoded_string = ''
# Slightly confusing, t | he get function will get the value of the
# key named letter or will return letter.
for letter in cleaned_string:
letter = letter.lower()
if letter in subst_dict:
encoded_string += subst_dict.get(letter, letter)
else:
encoded_string += letter
return encod... |
omwomotieno/tunza_v3 | call/callback.py | Python | mit | 2,707 | 0.001108 | #!/usr/bin/python2.7
from django.http import HttpResponse
from AfricasTalkingGateway import AfricasTalkingGateway, AfricasTalkingGatewayException
from reminder.models import Reminder
import sys
import os
import django
sys.path.append("/home/foxtrot/Dropbox/tunza_v2/")
os.environ["DJANGO_SETTINGS_MODULE"] = "config.set... | alues.get('currencyCode', None)
amount = request.values.get('amount', None)
# update session info to Redis
print duration, currency_code, amount
respond = '<?xml version="1.0" encoding="UTF-8"?>'
respond += '<Response>'
respond += '<Say playBeep=... | reminder system</Say>'
respond += '</Response>'
resp = HttpResponse(respond, 200, content_type='application/xml')
resp['Cache-Control'] = 'no-cache'
return resp
if is_active == str(1):
# Compose the response
respond = '<?xml version="1.0... |
maxive/erp | addons/fleet/models/fleet_vehicle.py | Python | agpl-3.0 | 17,170 | 0.004601 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models, _
from odoo.osv import expression
class FleetVehicle(models.Model):
_inherit = ['mail.thread', 'mail.activity.mixin']
_nam... | fuel_logs_count = fields.Integer(compute="_compute_count_all", string='Fuel Log Count')
odometer_count = fields.Integer(compute="_compute_count_all", string='Odometer')
acquisition_date = fields.Date('Immatriculation Date', required=False,
default=fields.Date.today, help='Date when the vehicle has been ... | t_date = fields.Date(string="First Contract Date", default=fields.Date.today)
color = fields.Char(help='Color of the vehicle')
state_id = fields.Many2one('fleet.vehicle.state', 'State',
default=_get_default_state, group_expand='_read_group_stage_ids',
track_visibility="onchange",
help='C... |
ameihm0912/MozDef | cron/healthToMongo.py | Python | mpl-2.0 | 5,358 | 0.00224 | #!/usr/bin/env python
# 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/.
# Copyright (c) 2014 Mozilla Corporation
#
# Contributors:
# Anthony Verez averez@mozilla.com
imp... | s'][nodeid]['f | s']['total']['total_in_bytes'] / (1024 * 1024 * 1024),
'mem_heap_per': jsonobj['nodes'][nodeid]['jvm']['mem']['heap_used_percent'],
'cpu_usage': jsonobj['nodes'][nodeid]['os']['cpu_percent'],
'load': jsonobj['nodes'][nodeid]['os']['load_average']
})
return results
def w... |
miguel7penteado/python-qt4 | 6/6.py | Python | gpl-3.0 | 1,622 | 0.011097 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Miguel Suez Xve
"""
import sys
from PyQt4 import QtGui
"""=================================================================="""
""" CLASSE QUE DESENHA A JANELA """
"""===============================================================... | eu defino um objeto janela atraves de uma classe"""
class MinhaClasse(QtGui.QWidget):
""" Aqui estou chamando o construtor da classe pai"""
def __init__(self):
super(MinhaClasse, self).__init__()
self.initUI()
"""Desenhando a janela Principal"""
def initUI(self): ... | a Janela Principal"""
def center(self):
retangulo_janela = self.frameGeometry()
resolucao_tela = QtGui.QDesktopWidget().availableGeometry().center()
retangulo_janela.moveCenter(resolucao_tela)
self.move(retangulo_janela.topLeft())
"""===========================... |
halober/ovirt-engine | packaging/setup/plugins/ovirt-engine-setup/ovirt-engine/upgrade/asynctasks.py | Python | apache-2.0 | 14,855 | 0.00074 | #
# ovirt-engine-setup -- ovirt engine setup
# Copyright (C) 2013-2014 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unl... | me=entry['relname'],
)
for entry in command_entities
]
)
def _getRunningCommands(self, dbstatement):
if n | ot self._getCommandEntitiesTableExists(dbstatement):
return None
commands = dbstatement.execute(
statement="""
select
command_entities.command_type,
command_entities.command_id,
command_entities.created_at,
... |
atmark-techno/atmark-dist | user/python/Lib/test/test_strop.py | Python | gpl-2.0 | 3,659 | 0.002733 | from test_support import verbose
import strop, sys
def test(name, input, output, *args):
if verbose:
print 'string.%s%s =? %s... ' % (name, (input,) + args, output),
f = getattr(strop, name)
try:
value = apply(f, (input,) + args)
except:
value = sys.exc_type
if value != out... | return len(self.seq)
def __getitem__(self, i): return self.seq[i]
test('join', ['a', 'b', 'c', 'd'], 'a b c d')
test('join', ('a', 'b', 'c', 'd'), 'abcd', '')
test('join', Sequence(), 'w x y z')
# try a few long ones
print strop.join(['x' * 100] * 100, ':')
print strop.join(('x' * 100,) * 100, ':')
test('strip'... | ('rstrip', ' hello ', ' hello')
test('swapcase', 'HeLLo cOmpUteRs', 'hEllO CoMPuTErS')
test('translate', 'xyzabcdef', 'xyzxyz', transtable, 'def')
test('replace', 'one!two!three!', 'one@two!three!', '!', '@', 1)
test('replace', 'one!two!three!', 'one@two@three!', '!', '@', 2)
test('replace', 'one!two!three!', '... |
yuhangwang/Sigil | src/Resource_Files/plugin_launchers/python/inputcontainer.py | Python | gpl-3.0 | 2,521 | 0.008727 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
# Copyright (c) 2014 Kevin B. Hendricks, John Schember, and Doug Massay
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following ... | pell=HunspellChecker(wrapper.get_hunspell_path())
self.dictionary_dirs=wrapper.get_dictionary_dirs()
self._prefs_store = JSONPrefs(wrapper | .plugin_dir, wrapper.plugin_name)
def getPrefs(self):
return self._prefs_store
def savePrefs(self, user_copy):
self._prefs_store = user_copy
self._prefs_store._commit()
def launcher_version(self):
return self._w.getversion()
def addotherfile(self, book_href, data):
... |
avtomato/HackerRank | Python/_16_Numpy/_14_Polynomials/solution.py | Python | mit | 130 | 0 | import numpy
a | rr = numpy.array(list(map(float, input().split())))
x = float(input())
value = numpy.polyval(arr, x)
print(value)
| |
Fastcode/NUClearExample | nuclear/message/generator/OneOfField.py | Python | mit | 936 | 0 | #!/usr/bin/env python3
import stringcase
from generator.Field import Field
class OneOfField:
def __init__(self, oneof_name, oneof_fields, context):
self.name = oneof_name
# Some booleans to describe the type
self.one_of = True
self.type = 'OneOf{}'.format(stringcase.pascalcase(... | '{}()'.format(self.type)
self.map_type = False
self.repeated = False
self.pointer = False
self.array_size = 0
self.bytes_type = False
self.basic = False
self.oneof_fields = [Field(f, context) for | f in oneof_fields]
# Since our cpp_type is used a lot, precalculate it
self.cpp_type = self.fqn.replace('.', '::')
self.special_cpp_type = False
def generate_cpp_header(self):
return '{} {};'.format(self.cpp_type, self.name)
|
Adam01/Cylinder-server | tests/test_file_content_procedures.py | Python | mit | 4,718 | 0 | import difflib
import shutil
__author__ = 'Adam'
import unittest
import os
import useful
class TestFileContentProcedures(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.test_dir = "./tests/data/"
cls.text_file_name = "TextFile_UTF16_CRLF.txt"
cls.text_file_path = os.path.j... | e_ending(self):
from fsentity import FileSystemFile
f = FileSystemFile(self.text_file_path)
self.assertEqual(self.text_file_eol, f.get_line_ending()[0])
f = FileSystemFile(self.script_file_path)
self.assertEqual(self.script_file_eol, f.get_line_ending()[0])
''' ... code st... | port FileSystemFile
lang = FileSystemFile(self.script_file_path).get_programming_language()
self.assertEqual("Python", lang)
|
onyb/mooca | MongoDB_University/M101P_MongoDB_for_Developers/Chapter_2_CRUD/pymongo_removing_data/remove_student_data.py | Python | mit | 1,002 | 0.011976 |
# Andrew Erlichson
# MongoDB, Inc.
# M101P - Copyright 2015, All Rights Reserved
import pymongo
import datetime
import sys
# establish a connection to the database
connection = pymongo.MongoClient("mongodb://localhost")
# removes one | student
def remove_student(student_id):
# get a handle to the school database
db=connection.school
scores = db.scores
try:
result = scores.delete_many({'student_id':student_id})
print "num removed: ", result.deleted_count
except Exception as e:
print "Exception: ", type... | find_student_data(student_id):
# get a handle to the school database
db=connection.school
scores = db.scores
print "Searching for student data for student with id = ", student_id
try:
docs = scores.find({'student_id':student_id})
for doc in docs:
print doc
exc... |
NicovincX2/Python-3.5 | Algorithmique/Algorithme/Algorithme de la théorie des graphes/graph_functions.py | Python | gpl-3.0 | 746 | 0.002681 | # -*- coding: utf-8 -*-
import os
import random
# pour melanger les graphes...
def shuffle(G):
rand | om.shuffle(G[0])
for c in G[1].items():
random.shuffle(c[1])
# pour completer les graphes NON orientes...
def completer_graphe_no(G):
for x in G[0]:
f | or y in G[0][x]:
if not x in G[0][y]:
G[0][y].append(x)
# pour completer les graphes NON orientes VALUES...
def completer_graphe_nov(G):
for x in G[0]:
for (y, d) in G[1][x]:
if not (x, d) in G[1][y]:
G[1][y].append((x, d))
# pour calculer le poids ... |
apyrgio/ganeti | lib/client/gnt_node.py | Python | bsd-2-clause | 40,549 | 0.00804 | #
#
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Google 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 copyri... | S_OPT = cli_option("--ignore-status", default=False,
action="store_true", dest="ignore_status",
help=("Ignore the Node(s) offline status"
" (potentially DANGEROUS)"))
def ConvertStorageType(user_storage_type):
"""Conv... | ts a user storage type to its internal name.
"""
try:
return _USER_STORAGE_TYPE[user_storage_type]
except KeyError:
raise errors.OpPrereqError("Unknown storage type: %s" % user_storage_type,
errors.ECODE_INVAL)
def _TryReadFile(path):
"""Tries to read a file.
If the ... |
BeenzSyed/tempest | tempest/api/volume/test_volumes_get.py | Python | apache-2.0 | 6,033 | 0.000166 | # Copyright 2012 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... | ).setUpClass()
cls.client = cls.volumes_client
def _delete_volume(self, volume_id):
resp, _ = self.client.delete_volume(volume_id)
self.assertEqual(202, resp.status)
self.client.wait_for_resource_deletion(volume_id)
def _is_true(self, val):
# NOTE(jdg): Temporary conver... | false"
if val in ['true', 'True', True]:
return True
else:
return False
def _volume_create_get_update_delete(self, **kwargs):
# Create a volume, Get it's details and Delete the volume
volume = {}
v_name = data_utils.rand_name('Volume')
metadat... |
vismartltd/edx-platform | cms/envs/devstack.py | Python | agpl-3.0 | 3,429 | 0.004374 | """
Specific overrides to the base prod settings to make development easier.
"""
from .aws import * # pylint: disable=wildcard-import, unused-wildcard-import
# Don't use S3 in devstack, fall back to filesystem
del DEFAULT_FILE_STORAGE
MEDIA_ROOT = "/edx/var/edxapp/uploads"
DEBUG = True
USE_I18N = True
TEMPLATE_DEBU... | ." + LMS_BASE
############################# ADVANCED COMPONENTS #############################
# Make it easier to test advanced components in local dev
FEATURES['ALLOW_ALL_ADVANCED_COMPONENTS'] = True
### | ############################## CELERY ######################################
# By default don't use a worker, execute tasks as if they were local functions
CELERY_ALWAYS_EAGER = True
################################ DEBUG TOOLBAR ################################
INSTALLED_APPS += ('debug_toolbar', 'debug_toolbar_mong... |
pankajp/pyface | pyface/workbench/perspective_item.py | Python | bsd-3-clause | 2,021 | 0.000495 | """ An item in a Perspective contents list. """
# Enthought library imports.
from traits.api import Enum, Float, HasTraits, provides, Str
# Local imports.
from i_perspective_item import IPerspectiveItem
@provides(IPerspectiveItem)
class PerspectiveItem(HasTraits):
""" An item in a Perspective contents list. ""... | e 'relative_to' item.
# 'right' puts the view to the right of the 'relative_to' item.
# 'with' puts the view in the same region as the 'relative_to' item.
#
# If the position is sp | ecified as 'with' you must specify a 'relative_to'
# item other than the editor area (i.e., you cannot position a view 'with'
# the editor area).
position = Enum('left', 'top', 'bottom', 'right', 'with')
# The Id of the view to position relative to. If this is not specified
# (or if no view exists ... |
dbrgn/django-filer | filer/templatetags/filer_admin_tags.py | Python | bsd-3-clause | 1,240 | 0.004839 | import django
from django.conf import settings
from django.template import Library
from distutils.version import LooseVersion
register = Library()
def filer_actions(context):
"""
Track the number of times the action field has been rendered on the page,
so we know which value to use.
"""
context['a... | SS_BASE = "%sadmin/css/admin/" % settings.STATIC_URL |
ADMIN_JS_BASE = "%sadmin/js/admin/" % settings.STATIC_URL
else:
ADMIN_ICON_BASE = "%sadmin/img/" % settings.STATIC_URL
ADMIN_CSS_BASE = "%sadmin/css/" % settings.STATIC_URL
ADMIN_JS_BASE = "%sadmin/js/" % settings.STATIC_URL
@register.simple_tag
def admin_icon_base():
return ADMIN_ICON_BASE
@regi... |
alirizakeles/memopol-core | memopol/votes/admin.py | Python | gpl-3.0 | 286 | 0 | # -*- coding: utf-8 -*-
from django.cont | rib import admin
from memopol.votes import models
admin.site.register(models.Proposal)
admin.site.register(models.Recommendation)
admin.site.register(models.RecommendationData)
admin.site.register(models.Vote)
admi | n.site.register(models.Score)
|
raphaelm/django-i18nfield | demoproject/demoproject/wsgi.py | Python | apache-2.0 | 399 | 0 | """
WSGI config for demoproject project.
It exposes the WSGI callable as a module-level variable named | ``application``.
For more information on this | file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demoproject.settings")
application = get_wsgi_application()
|
crisely09/horton | doc/update_lib_doc.py | Python | gpl-3.0 | 4,657 | 0.001718 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# HORTON: Helpful Open-source Research TOol for N-fermion systems.
# Copyright (C) 2011-2016 The HORTON Development Team
#
# This file is part of HORTON.
#
# HORTON is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public Licens... | if the contents have changed
rst_name = 'mod_%s_%s' % (package.replace('.', '_'), module.replace('.', '_'))
fn2_rst = 'lib/%s.rst' % rst_name
fns_rst.append(fn2_rst | )
write_if_changed(fn2_rst, f2.getvalue())
print >> f1, ' %s' % rst_name
# write if the contents have changed
fn1_rst = 'lib/pck_%s.rst' % package.replace('.', '_')
fns_rst.append(fn1_rst)
write_if_changed(fn1_rst, f1.getvalue())
# Remove other rst files... |
zhangtuoparis13/Vintageous | xsupport.py | Python | mit | 6,043 | 0.000993 | """Assorted commands.
"""
import os
import threading
import sublime
import sublime_plugin
from Vintageous.state import _init_vintageous
from Vintageous.state import State
from Vintageous.vi import settings
from Vintageous.vi import cmd_defs
from Vintageous.vi.dot_file import DotFile
from Vintageous.vi.utils import m... | # more are we in?
v.settings().set('command_mode', False)
v.s | ettings().set('inverse_caret_state', False)
print("Vintageous: Exiting from command mode.")
sublime.status_message("Vintageous: Exiting from command mode.")
class VintageousToggleCtrlKeys(sublime_plugin.WindowCommand):
def run(self):
prefs = sublime.load_settings('Preferences.sublime-set... |
VeryCB/flask-slack | docs/conf.py | Python | bsd-3-clause | 8,287 | 0.005792 | # -*- coding: utf-8 -*-
#
# flask_slack documentation build configuration file, created by
# sphinx-quickstart on Sun Oct 19 16:31:35 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#... | er_doc = 'index'
# General information about the project.
project = u'flask_slack'
copyright = u'2014, VeryCB'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
versio... | /rc tags.
release = '0.1.5'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the for... |
samphippen/london | render.py | Python | mit | 232 | 0.025862 | import Image
import json
south = 51.416;
north = 51.623;
west = | -0.415;
east = 0.179;
if __name__ == "__main__":
x = Image.fromstring("RGBA", (2668 | ,1494), open("output_pixel_data").read())
x.save("lit-map.png", "PNG")
|
tensor-tang/Paddle | python/paddle/fluid/tests/unittests/test_unique_with_counts.py | Python | apache-2.0 | 2,925 | 0 | # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | self.outputs = {
'Out': np.array(
[2, 3, 1, 5], dtype='int64'),
'Index': np.array(
[0, 1, 1, 2, 3, 1], dtype='int32'),
'Count': np.array(
[1, 3, 1, 1], dtype='int32')
}
class TestOne(TestUniqueWithCountsOp):
def init_confi... | 'dtype': int(core.VarDesc.VarType.INT32)}
self.outputs = {
'Out': np.array(
[2], dtype='int64'),
'Index': np.array(
[0], dtype='int32'),
'Count': np.array(
[1], dtype='int32')
}
class TestRandom(TestUniqueWithCountsOp)... |
markosa/hydromon-client | net/hydromon/client/serverclient.py | Python | gpl-2.0 | 2,086 | 0.009108 | '''
Created on May 8, 2015
@author: markos
'''
import json
import logging
import requests
from net.hydromon.config import ConfigurationUtil
import os
from requests.exceptions import ConnectionError, RequestException
import sys
import traceback
from | time import strftime
import datetime
log = logging.getLogger(__name__)
def send(valuedto):
payload = json.dumps(valuedto, default=serialize_valuedto, indent=2)
endpointUrl = ConfigurationUtil.getAddVa | lueEndpointUrl(valuedto.sensorId)
log.debug("Sending data: " + payload + " to " + endpointUrl)
response = None
try:
response = requests.post(endpointUrl, payload, timeout=20)
except RequestException as re:
log.fatal(re)
except:
log.fatal("Unknown error occurred!")
... |
abo-abo/edx-platform | lms/djangoapps/courseware/courses.py | Python | agpl-3.0 | 11,362 | 0.001672 | from collections import defaultdict
from fs.errors import ResourceNotFoundError
import logging
import inspect
import re
from path import path
from django.http import Http404
from django.conf import settings
from .module_render import get_module
from xmodule.course_module import CourseDescriptor
from xmodule.modulestor... | ror):
raise ValueError("Course not found: {}".format(course_id))
except InvalidLocationError:
raise Va | lueError("Invalid location: {}".format(course_id))
def get_course_by_id(course_id, depth=0):
"""
Given a course id, return the corresponding course descriptor.
If course_id is not valid, raises a 404.
depth: The number of levels of children for the modulestore to cache. None means infinite depth
... |
ymichael/cprofilev | example_for_profiling.py | Python | mit | 354 | 0 | """This is just a simple example for testing cprofilev. To see cprofilev in
action, run
python -m cprofilev example_for_profiling.py
"""
import random
import time
def product(x, y):
retur | n x * y
def main():
x = 1.
while True:
x = product(x, 0.5 + random.random())
time.sleep(0.1) |
if __name__ == '__main__':
main()
|
larsbergstrom/servo | tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/executors/executorwebdriver.py | Python | mpl-2.0 | 18,381 | 0.001959 | import json
import os
import socket
import sys
import threading
import time
import traceback
import urlparse
import uuid
from .base import (CallbackHandler,
RefTestExecutor,
RefTestImplementation,
TestharnessExecutor,
extra_timeout,
... | = win_obj["window-fcc6-11e5-b4f8-330a88ab9d7f"]
except Exception:
pass
if test_window is None:
after = self.webdriver.handles
if len(after) == 2:
test_window = next(iter(set(after) - {parent}))
elif after[0] ==... | ere is the test window
test_window = after[1]
if test_window is not None:
assert test_window != parent
return test_window
time.sleep(0.1)
raise Exception("unable to find test window")
class WebDriverSelectorProtocolPart(SelectorPro... |
dongjoon-hyun/tools | telegram-shell/telegram-shell.py | Python | apache-2.0 | 1,508 | 0.002653 | #!/usr/bin/env python
# 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... | icators("api.telegram.org")
token = password
bot = telebot.TeleBot(token)
def run(cmd, message):
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
print out, err
bot.send_mess | age(message.chat.id, '```\n' + out + '```',
disable_web_page_preview=True,
disable_notification=True,
parse_mode='Markdown')
@bot.message_handler(func=lambda m: True)
def shell(message):
try:
if message.from_user.username == getpass.getuser():
... |
richm/389-perf-test | nconns.py | Python | gpl-3.0 | 504 | 0 | import sys
import time
import ldap
url, binddn, bindpw, basedn, nconns, niters = sys.arg | v[1:]
conns = []
for ii in xrange(0, int(nconns)):
conn = ldap.initialize(url)
conns.append(conn)
for conn in conns:
conn.simple_bind(binddn, bindpw)
for ii in xrange(0, int(niters)):
for conn | in conns:
ents = conn.search_s(basedn, ldap.SCOPE_SUBTREE, "uid=scarter")
assert(len(ents) == 1)
assert(ents[0][1]['uid'][0] == 'scarter')
for conn in conns:
conn.unbind_s()
|
monuszko/django-ratings | ratings/forms.py | Python | gpl-2.0 | 1,958 | 0.001532 | from django import forms
f | rom django.core.exceptions import ValidationError
from ratings.models import Choice, Score
class ScoreForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user', None)
self.criteria = kwargs.pop('criteria', None)
self.obj_id = kwargs.pop('obj_id', None)
... | es(
please_select='Please select:'))
def _get_choices(self, please_select=None):
choices = Choice.objects.values_list('value', 'label')
if please_select is not None:
choices = tuple([(666, please_select)] + list(choices))
return choices
def _get_choice_values(se... |
sasmita/upm | examples/python/mpu9150.py | Python | mit | 2,714 | 0.001842 | #!/usr/bin/python
# Author: Jon Trulson <jtrulson@ics.com>
# Copyright (c) 2015 Intel Corporation.
#
# 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 l... | rint(" AY: ", sen | sorObj.floatp_value(y), end=' ')
print(" AZ: ", sensorObj.floatp_value(z))
sensor.getGyroscope(x, y, z)
print("Gyroscope: GX: ", sensorObj.floatp_value(x), end=' ')
print(" GY: ", sensorObj.floatp_value(y), end=' ')
print(" GZ: ", sensorObj.floatp_value(z))
sensor.g... |
heytrav/drs-project | domain_api/migrations/0042_remove_registereddomain_domain.py | Python | mit | 406 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-06-16 10:38
from __future__ import | unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('domain_api', '0041_auto_20170616_1037'),
]
operations = [
migrations.RemoveField(
model_name='registereddomain',
name='domain',
| ),
]
|
roalddevries/django-dynamicforms | dynamicforms/admin.py | Python | apache-2.0 | 3,276 | 0.002137 | from datetime import date
from django import forms
from django.http import HttpResponse
from django.contrib import admin
from models import DynamicFieldValue, DynamicField, DynamicFormFieldRelation, DynamicForm, DynamicFormData
from StringIO import StringIO
from zipfile import ZipFile
import csv
class DynamicFieldVal... | ynamicField, DynamicFieldAdmin)
admin.site.register(DynamicForm, DynamicFormAdmin)
admin.site.register(DynamicFormData, Dyn | amicFormDataAdmin)
|
eruffaldi/pyoni | src/onitool/oni2depth.py | Python | mit | 1,555 | 0.01672 | # Extracts a singla RAW depth file of contiguous data
#
# Requires to build xndec
import struct
from onifile import *
from xndec import *
if __name__ == "__main__":
import sys,os
if len(sys.argv) == 0:
print "Required: ONIfilename"
sys.exit(-1)
docolor = len(sys.argv) > 3
filesize = ... | s input",len(z),"output",len(ob)
o = open("x.depth","wb")
o.write(ob)
o.close()
break
if h["rt"] | == RECORD_END:
continue
a.seek(h["nextheader"],0) #h["fs"]-HEADER_SIZE+h["ps"],1)
a.close()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.