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 |
|---|---|---|---|---|---|---|---|---|
spektom/incubator-airflow | tests/test_core.py | Python | apache-2.0 | 18,421 | 0.000869 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | str(ctx.exception))
def test_bash_operator(self):
| op = BashOperator(
task_id='test_bash_operator',
bash_command="echo success",
dag=self.dag)
op.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True)
def test_bash_operator_multi_byte_output(self):
op = BashOperator(
task_id='tes... |
AndrewPeelMV/Blender2.78c | 2.78/scripts/addons/blender_cloud/texture_browser.py | Python | gpl-2.0 | 38,526 | 0.001609 | # ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distrib... | e type in node: %s', node)
raise TypeError('Node of type %r not supported; supported are %r.' % (
node['node_type'], self.SUPPORTED_NODE_TYPES))
assert isinstance(node, pillarsdk.Node), 'wrong type for node: %r' % type(node)
assert isinstance(node['_id'], str), 'wrong type f... | e_desc # pillarsdk.File object, or None if a 'folder' node.
self.label_text = label_text
self._thumb_path = ''
self.icon = None
self._is_folder = node['node_type'] in self.FOLDER_NODE_TYPES
self._is_spinning = False
# Determine sorting order.
# by default, sort ... |
jrversteegh/softsailor | deps/swig-2.0.4/Examples/python/smartptr/runme.py | Python | gpl-3.0 | 1,069 | 0.01029 | # file: runme. | py
# This file illustrates | the proxy class C++ interface generated
# by SWIG.
import example
# ----- Object creation -----
print "Creating some objects:"
cc = example.Circle(10)
c = example.ShapePtr(cc)
print " Created circle", c
ss = example.Square(10)
s = example.ShapePtr(ss)
print " Created square", s
# ----- Access a static membe... |
mariusvniekerk/impyla | impala/dbapi/beeswax.py | Python | apache-2.0 | 9,904 | 0 | # Copyright 2014 Cloudera Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | None:
size = self.arraysize
local_buffer = []
i = 0
while i < size:
try:
local_buffer.append(next(self))
i += 1
| except StopIteration:
break
return local_buffer
def fetchall(self):
# PEP 249
try:
return list(self)
except StopIteration:
return []
def setinputsizes(self, sizes):
# PEP 249
pass
def setoutputsize(self, size, ... |
MarxMustermann/OfMiceAndMechs | src/itemFolder/obsolete/commandBook.py | Python | gpl-3.0 | 689 | 0.001451 | import src
class CommandBook(src.items.Item):
type = "CommandBook"
"""
call superclass constructor with modified parameters
"""
def __init__(self):
super().__init__(display="cb")
self.name = "command book"
self.bolted = False
self.walkable = True
totalCo... | eturn state
sr | c.items.addType(CommandBook)
|
Gaia3D/QGIS | python/plugins/processing/algs/gdal/ogr2ogrclipextent.py | Python | gpl-2.0 | 3,489 | 0.001433 | # -*- coding: utf-8 -*-
"""
***************************************************************************
ogr2ogrclipextent.py
---------------------
Date : November 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
*******************... | Vector.VECTOR_TYPE_ANY], False))
self.addParameter(ParameterExtent(self.CLIP_EXTENT,
self.tr('Clip extent')))
self.addParameter(ParameterString(self.OPTIONS,
self.tr('Additional creation options'), '', optional=True))
self.addOutput(OutputVector(self.OUTPUT_LAYER, self.t... | def getConsoleCommands(self):
inLayer = self.getParameterValue(self.INPUT_LAYER)
ogrLayer = self.ogrConnectionString(inLayer)[1:-1]
clipExtent = self.getParameterValue(self.CLIP_EXTENT)
ogrclipExtent = self.ogrConnectionString(clipExtent)
output = self.getOutputFromName(self.O... |
onoga/toolib | toolib/wx/grid/test/testDeleteSelection.py | Python | gpl-2.0 | 604 | 0.023179 | i | mport wx
from toolib.wx.TestApp import TestApp
from toolib.wx.grid.Grid import Grid
from toolib.wx.grid.table.List2dTable import List2dTable
from toolib.wx.grid.MDeleteSelection import MDeleteSelection
class MyGrid(Grid, MDeleteSelection):
def __init__(self, *args, **kwargs):
Grid.__init__(self, *args, **kwargs)
... |
g = None
def oninit(self):
self.grid = MyGrid(self, -1)
self.grid.SetTable(List2dTable())
self.grid.AppendRows(4)
self.grid.AppendCols(4)
def ondestroy(self):
pass
TestApp(oninit, ondestroy).MainLoop()
|
smlacombe/sageo | app/controllers/side.py | Python | gpl-3.0 | 1,232 | 0.012175 | #
# Copyright (C) 2013 Savoir-Faire Linux Inc.
#
# This file is part of Sageo
#
# Sageo 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 optio... | pin impo | rt SnapinBase
sageo = current_app
def side():
snapin_objects = {}
for snapin in snapins.__all__:
#import ipdb;ipdb.set_trace()
__import__('app.snapins.' + snapin + '.' + snapin)
snapin_objects[snapin] = getattr(getattr(getattr(snapins, snapin), snapin),snapin)()
return snapin_objec... |
stlemme/python-dokuwiki-export | create-thumbnail.py | Python | mit | 575 | 0.034783 |
import logging
from catalog import ThumbnailGenerator
from wiki import DokuWikiRemote
if __name__ == '__main__':
import sys
import wikiconfig
filename = 'thumb.png'
if len(sys.argv) < 2:
sys.exit('Usage: | %s :wiki:thumbnail.png [ thumb.png ]' % sys.argv[0])
thumbname = sys.argv[1]
logging.info("Connecting to remote DokuWiki at %s" % wikiconfig.url)
dw = DokuWikiR | emote(wikiconfig.url, wikiconfig.user, wikiconfig.passwd)
thumbGen = ThumbnailGenerator(dw)
if len(sys.argv) > 2:
filename = sys.argv[2]
thumbGen.generate_thumb(thumbname, filename)
|
tdruez/django-registration | registration/models.py | Python | bsd-3-clause | 10,792 | 0 | """
Model and manager used by the two-step (sign up, then activate)
workflow. If you're not using that workflow, you don't need to have
'registration' in your INSTALLED_APPS.
This is provided primarily for backwards-compatibility with existing
installations; new installs of django-registration should look into
the HMA... | hash, generated from a combination of the ``User``'s
username and a random salt.
"""
User = get_user_model()
username = str(getattr(user, User.USERNAME_FIELD))
| hash_input = (get_random_string(5) + username).encode('utf-8')
activation_key = hashlib.sha1(hash_input).hexdigest()
return self.create(user=user,
activation_key=activation_key)
@transaction.atomic
def delete_expired_users(self):
"""
Remove expired ins... |
AdrianGaudebert/socorro-crashstats | vendor-local/lib/python/raven/handlers/logbook.py | Python | mpl-2.0 | 2,760 | 0.003261 | """
raven.handlers.logbook
~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import logbook
import sys
import traceback
from raven.base import Client
from raven.utils.encoding imp... | ys.stderr, to_string(traceback.format_exc())
try:
self.client.captureException()
except Exception:
pass
def _emit(self, record):
data = {
'level': logbook.get_level_name(record.level).lower(),
'logger': record.channel,
... | record.args}
# If there's no exception being processed, exc_info may be a 3-tuple of None
# http://docs.python.org/library/sys.html#sys.exc_info
if record.exc_info is True or (record.exc_info and all(record.exc_info)):
handler = self.client.get_handler(event_type)
data.u... |
NoctuaNivalis/qutebrowser | tests/unit/config/test_configexc.py | Python | gpl-3.0 | 3,233 | 0 | # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2015-2017 Florian Bruhin (The Compiler) <[email protected]>
# 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 Sof... | with_text( | "additional text")
assert str(new) == 'Error text (additional text): Exception text'
@pytest.fixture
def errors():
"""Get a ConfigFileErrors object."""
err1 = configexc.ConfigErrorDesc("Error text 1", Exception("Exception 1"))
err2 = configexc.ConfigErrorDesc("Error text 2", Exception("Exception 2"),
... |
CodigoSur/cyclope | cyclope/migrations/0026_auto__chg_field_sitesettings_font_size.py | Python | gpl-3.0 | 13,275 | 0.007684 | # -*- 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 'SiteSettings.font_size'
db.alter_column('cyclope_sitesettings', 'font_size', self.gf('dja... | dex': 'True'}),
| 'site_home': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'slug': ('autoslug.fields.AutoSlugField', [], {'unique_with': '()', 'max_length': '50', 'populate_from': 'None', 'blank': 'True'}),
'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_ind... |
ischleifer/smile | docs/examples/oddball.py | Python | gpl-3.0 | 8,307 | 0.008908 | #emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
#ex: set sts=4 ts=4 sw=4 et:
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See the COPYING file distributed along with the smile package for the
# copyright and license terms.
#
### ### ### ### ### ### ### ... |
CONDS = ['common']*NUM_COMMON + ['rare']*NUM_RARE
# timing
AUDIO_DUR = .5
AUDIO_ISI = 1.5
VISUAL_DUR = 1.0
VISUAL_ISI | = 1.0
JITTER = .5
MIN_RT = .100
RESP_DUR = 1.25
# Each stim as rare
# Each response mapped to each stimulus
blocks = []
for mode in MODES:
for reverse_stim in [True, False]:
# pick the proper stim set
stims = STIMS[mode]
# reverse if required
if reverse_stim:
stims = st... |
zstackorg/zstack-woodpecker | integrationtest/vm/virtualrouter/lb/test_create_lb.py | Python | apache-2.0 | 2,080 | 0.004808 | '''
Test load balance.
Test step:
1. Create 2 VM with load balance l3 network service.
2. Create a LB with 2 VMs' nic
3. Check the LB
4. Destroy VMs
@author: Youyk
'''
import os
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_lib as test_lib
import zstac... | heck()
test_lib.lib_robot_cleanup(test_obj_dict)
test_util.test_pass('Create Load Balancer Test Success')
#Will be called only if exception happens in test().
def error_cleanup():
test_ | lib.lib_error_cleanup(test_obj_dict)
|
jonparrott/google-cloud-python | bigquery/tests/unit/test_job.py | Python | apache-2.0 | 189,727 | 0 | # Copyright 2015 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... | def test_from_api_repr(self):
api_repr = {
'jobId': self.JOB_ID,
'projectId': self.PROJECT,
'location': self.LOCATION,
}
job_ref = self._get_target_class()._from_api_repr(api_repr)
self.assertEqual(job_ref.job_id, self.JOB_ID)
self.assertEqua... | assertEqual(job_ref.location, self.LOCATION)
class Test_AsyncJob(unittest.TestCase):
JOB_ID = 'job-id'
PROJECT = 'test-project-123'
LOCATION = 'us-central'
@staticmethod
def _get_target_class():
from google.cloud.bigquery import job
return job._AsyncJob
def _make_one(self, j... |
GoogleCloudPlatform/cloud-opensource-python | badge_server/test_badge_server.py | Python | apache-2.0 | 18,516 | 0.0027 | # Copyright 2018 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... | sult(
packages=[package.Package(name) fo | r name in package_names],
python_major_version=2,
status=compatibility_store.Status.SUCCESS)]
details = main._get_missing_details(package_names, results)
expected_details = ("Missing data for packages=['compatibility-lib', "
"'opencensus'], versions=[3... |
robertjacobs/zuros | zuros_test/src/timed_out-and-back.py | Python | mit | 3,599 | 0.006669 | #!/usr/bin/env python
""" timed_out_and_back.py - Version 1.1 2013-12-20
A basic demo of the using odometry data to move the robot along
and out-and-back trajectory.
Created for the Pi Robot Project: http://www.pirobot.org
Copyright (c) 2012 Patrick Goebel. All rights reserved.
This program is free software; you ca... | when shutting down the node.
rospy.loginfo("Stopping the robot...")
self.cmd_vel.publish(Twist())
rospy.sleep(1)
if __name__ == '__main__':
try:
OutAndBack()
except:
rospy.loginfo("Out-and-Back node terminated.")
| |
dbarbier/privot | python/test/t_NatafIndependentCopulaEvaluation_std.py | Python | lgpl-3.0 | 685 | 0.007299 | #! /usr/bin/env python
from openturns import *
from math import *
TESTPREAMBLE()
RandomGenerator().SetSeed(0)
try :
dim = 2
transformation = NatafIndependentCopulaEvaluatio | n(dim)
print "transformation=", repr(transformation)
point = NumericalPoint(dim, 0.75)
print "transformation(", point, ")=", repr(transformation(point))
print "transformation parameters gradient=", repr(transformation.parametersGradient(point))
print "input dimension=", transformation.getInputDimens... | ormation.getOutputDimension()
except :
import sys
print "t_NatafIndependentCopulaEvaluation_std.py", sys.exc_type, sys.exc_value
|
statwonk/thinkbayes | monty.py | Python | mit | 596 | 0.008389 | """Thi | s file contains code for use with "Think Bayes",
by Allen B. Downey, available from greenteapress.com
Copyright 2012 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""
tb = imp.load_source('thinkbayes', '/home/chris/installations/python/ThinkB | ayes/thinkbayes.py')
from thinkbayes import Pmf
from thinkbayes import Suite
class Monty(Suite):
def Likelihood(self, data, hypo):
if hypo == data:
return 0
elif hypo == 'A':
return 0.5
else:
return 1
suite = Monty('ABC')
suite.Update('A')
suite.Print()
|
hiroki8080/Kokemomo | kokemomo/plugins/engine/controller/km_engine.py | Python | mit | 1,820 | 0.002747 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from .km_backend.km_plugin_manager import KMBaseController
from .km_exception import log
__author__ = 'hiroki'
class KMEngine(KMBaseController):
def get_name(self):
return 'engine'
def get_route_list(self):
list = (
{'rule': '/engi... | tic(self, | filename):
"""
set css files.
:param filename: css file name.
:return: static path.
"""
file_path = 'kokemomo/plugins/engine/view/resource/css'
return self.load_static_file(filename, root=file_path)
@log
def engine_img_static(self, filename):
"""
... |
MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-3.5.0/Lib/asyncio/unix_events.py | Python | mit | 34,324 | 0.000146 | """Selector event loop for Unix with signal handling."""
import errno
import os
import signal
import socket
import stat
import subprocess
import sys
import threading
import warnings
from . import base_events
from . import base_subprocess
from . import compat
from . import constants
from . import coroutines
from . im... | _signal(sig)
self._check_closed()
try:
# set_wakeup_fd() raises ValueError if this is not the
# main thread. By callin | g it early we ensure that an
# event loop running in another thread cannot add a signal
# handler.
signal.set_wakeup_fd(self._csock.fileno())
except (ValueError, OSError) as exc:
raise RuntimeError(str(exc))
handle = events.Handle(callback, args, self)
... |
Sticklyman1936/workload-automation | wlauto/modules/__init__.py | Python | apache-2.0 | 585 | 0 | # Copyright 2014-2015 ARM Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the | License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT W | ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
|
sittizen/django_dropimages | django_dropimages/models.py | Python | mit | 859 | 0.002328 | from django.conf import settings
from django.db import models
from django_dropimages import settings as di_settings
# if no custom image models is present I load my own
if not di_settings.CONFIG['DROPIMAGEGALLERY_MODEL']:
class DropimagesGallery(models.Model):
gallery_identifier = models.CharField(max_le... | class DropimagesImage(models.Model): |
dropimages_gallery = models.ForeignKey('django_dropimages.DropimagesGallery', related_name='images')
dropimages_original_filename = models.CharField(max_length=256)
image = models.ImageField(upload_to='%y/%m/%d')
|
tyll/bodhi | bodhi/tests/server/services/test_updates.py | Python | gpl-2.0 | 193,782 | 0.001099 | # -*- coding: utf-8 -*-
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope tha... | otron_results',
'return_value': [],
}
class TestNewUpdate(base.BaseTestCase):
"""
This class contains tests for the new_update() function.
"""
@mock.patch(**mock_valid_requirements)
def test_invalid_build_name(self, *args):
res = self.app.post_json('/up | dates/', self.get_update(u'bodhi-2.0-1.fc17,invalidbuild-1.0'),
status=400)
assert 'Build not in name-version-release format' in res, res
@mock.patch(**mock_valid_requirements)
def test_empty_build_name(self, *args):
res = self.app.post_json('/updates/', self.ge... |
0xc0170/project_generator | tests/test_tools/test_uvision5.py | Python | apache-2.0 | 3,726 | 0.00161 | # Copyright 2015 0xc0170
#
# 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, soft... | ect_1'):
result = project.generate('uvision5', False)
assert | result == 0
assert os.path.isdir('create_this_folder')
shutil.rmtree('create_this_folder')
def test_build_project(self):
result_export = self.project.generate('uvision5', False)
result_build = self.project.build('uvision5')
assert result_export == 0
# nonvalid proj... |
exord/bayev | pastislib.py | Python | mit | 7,786 | 0 | """
Module containing useful functions to link PASTIS MCMC posterior samples with
the bayev package.
"""
im | port os
import pickle
import importlib
import numpy as np
import PASTIS_NM
import PASTIS | _NM.MCMC as MCMC
from PASTIS_NM import resultpath, configpath
def read_pastis_file(target, simul, pastisfile=None):
"""Read configuration dictionary."""
if pastisfile is None:
# Get input_dict
configname = os.path.join(configpath, target,
target + '_' + simul ... |
blowmage/gcloud-python | regression/pubsub.py | Python | apache-2.0 | 4,859 | 0 | # Copyright 2015 Google Inc. 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 a... | d' % (1000 * time.time(),),
'newest%d' % (1000 * time.time(),),
]
for subscription_name in subscriptions_to_create:
subscription = Subscription(subscription_name, topic)
subscription.create()
self.to_delete.append(subscription)
# Retrieve the subs... | = pubsub.list_subscriptions()
created = [subscription for subscription in all_subscriptions
if subscription.name in subscriptions_to_create and
subscription.topic.name == TOPIC_NAME]
self.assertEqual(len(created), len(subscriptions_to_create))
def test_message_... |
cnwalter/screenly-ose | lib/assets_helper.py | Python | gpl-2.0 | 4,416 | 0.001359 | import db
import queries
import datetime
FIELDS = ["asset_id", "name", "uri", "start_date",
"end_date", "duration", "mimetype", "is_enabled", "nocache", "play_order"]
create_assets_table = 'CREATE TABLE assets(asset_id text primary key, name text, uri text, md5 text, start_date timestamp, end_date timestamp... | tetime. | datetime(2013, 1, 16, 0, 0)};
>>> is_active(asset, datetime.datetime(2013, 1, 16, 12, 00))
True
>>> is_active(asset, datetime.datetime(2014, 1, 1))
False
>>> asset['is_enabled'] = False
>>> is_active(asset, datetime.datetime(2013, 1, 16, 12, 00))
False
"""
if asset['is_enabled'] a... |
oblique-labs/pyVM | rpython/jit/backend/ppc/test/test_dict.py | Python | mit | 258 | 0 |
from rpython.jit.backend.ppc.test.support import JitPPCMixi | n
from rpython.jit.metainterp.test.test_dict im | port DictTests
class TestDict(JitPPCMixin, DictTests):
# for the individual tests see
# ====> ../../../metainterp/test/test_dict.py
pass
|
hellhovnd/dentexchange | dentexchange/apps/employer/tests/test_job_posting.py | Python | bsd-3-clause | 398 | 0 | # -*- coding:utf-8 -*-
im | port unittest
import mock
from ..models import JobPosting
class JobPostingTestCase(unittest.TestCase):
def test_unicode_should_return_position_name(self):
# setup
model = JobPosting()
model.position_name = 'Position Name'
# action
email = unicode(model)
# assert
... | position_name, email)
|
Jianlong-Peng/rp | python/evaluate_smartcyp_v2.py | Python | gpl-2.0 | 5,047 | 0.015257 | '''
#=============================================================================
# FileName: evaluate_smartcyp_v2.py
# Desc:
# Author: jlpeng
# Email: [email protected]
# HomePage:
# Version: 0.0.1
# Created: 2015-03-09 20:38:49
# LastChange: 2015-03-10 17:58:21
# Hi... | prev_name = name
inf.close()
for key,value in predict.iteritems():
value.sort(key=lambda x:x[1])
if count:
print "totally %d samples of %s a | re not in `des_file`"%(count,infile)
return predict
def evaluate(actual,predict,k):
total = 0
miss = 0
right = 0
for name in actual.iterkeys():
total += 1
if len(actual[name]) == 0:
miss += 1
continue
found = False
for item in predict[name][... |
freecoder-zrw/leetcode | data_struct.py | Python | apache-2.0 | 737 | 0.008141 | #coding:utf-8
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __unicode__(self):
return u'val:%s'%(self.val,)
def __str__(self):
return self.__unicode__().encode('utf-8')
@staticmethod |
def array2list(a):
head, tail = None, None
for i in a:
if not head:
head = ListNode(i)
tail = head
else:
node = ListNode(i)
tail.next = node
tail = node
return head
def trace(self):
... | ode = self
while node:
print node.val,'->',
node = node.next
print 'end' |
GenericMappingTools/gmt-python | examples/gallery/lines/vector_heads_tails.py | Python | bsd-3-clause | 3,149 | 0.002223 | """
Vector heads and ta | ils
----------------------
Many modules in PyGMT allow plotting vectors with individual
heads and tails. For this purpose, several modifiers may be appended to
the corresponding vector-producing parameters for specifying the placement
of vector heads | and tails, their shapes, and the justification of the vector.
To place a vector head at the beginning of the vector path
simply append **+b** to the vector-producing option (use **+e** to place
one at the end). Optionally, append **t** for a terminal line, **c** for a
circle, **a** for arrow (default), **i** for tail... |
UdK-VPT/Open_eQuarter | mole3/stat_corr/window_wall_ratio_south_AVG_by_building_age_lookup.py | Python | gpl-2.0 | 2,492 | 0.140506 | # coding: utf8
# OeQ autogenerated lookup function for 'Window/Wall Ratio South in correlation to year of construction, based on the source data of the survey for the "German Building Typology developed by the "Institut für Wohnen und Umwelt", Darmstadt/Germany, 2011-2013'
import math
import numpy as np
from . import ... | .055,
1853,0.056,
1854,0.056,
1855,0.055,
1856,0.053,
1857,0.051,
1858,0.048,
1859,0.046,
1860,0.043,
1861,0.04,
1862,0.03 | 8,
1863,0.036,
1864,0.035,
1865,0.035,
1866,0.036,
1867,0.036,
1868,0.036,
1869,0.036,
1870,0.036,
1871,0.036,
1872,0.036,
1873,0.036,
1874,0.036,
1875,0.036,
1876,0.036,
1877,0.036,
1878,0.036,
1879,0.036,
1880,0.036,
1881,0.036,
1882,0.036,
1883,0.036,
1884,0.036,
1885,0.036,
1886,0.036,
1887,0.036,
1888,0.036,
1889,... |
xin3liang/platform_external_chromium_org | native_client_sdk/src/build_tools/build_projects.py | Python | bsd-3-clause | 11,275 | 0.012594 | #!/usr/bin/env python
# Copyright (c) 2013 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 posixpath
import sys
import urllib2
import buildbot_common
import build_ve... | on the command line, then VALID_TOOLCHAINS
# will not contain a bionic target.
make_cmd.append('ENABLE_BIONIC=1')
if not deps:
make_cmd.append('IGNORE_DEPS=1')
if verbose:
make_c | md.append('V=1')
if args:
make_cmd += args
else:
make_cmd.append('TOOLCHAIN=all')
buildbot_common.Run(make_cmd, cwd=make_dir, env=env)
if clean:
# Clean to remove temporary files but keep the built
buildbot_common.Run(make_cmd + ['clean'], cwd=make_dir, env=env)
def BuildProjects(pepperdir, ... |
jthurst3/MemeCaptcha | MemeScrapers/MemeScrapers/items.py | Python | mit | 291 | 0 | # -*- coding: utf-8 -*-
# Define here the models | for your scraped ite | ms
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class MemescrapersItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
pass
|
mallconnectionorg/openerp | rrhh/l10n_cl_banks/__openerp__.py | Python | agpl-3.0 | 1,624 | 0.005552 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2010-Today OpenERP S.A. (<http://www.openerp.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the term... | received a copy of the GNU Affero General Public License
# along with this p | rogram. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Instituciones Financieras Chile',
'version': '1.0',
'category': 'Localization/Chile',
"description": """
Fichas de Bancos y Cooperativas, establecido... |
PersianWikipedia/fawikibot | laupdate.py | Python | mit | 3,731 | 0.001971 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Distributed under the terms of MIT License (MIT)
import pywikibot
import time
from pywikibot.data.api import Request
import re
site = pywikibot.Site('fa', fam='wikipedia')
print "Fetching admins list"
data = Request(site=site, action="query", list="allusers", augroup="sysop",... | شصضطظعغفقکگلمنوهیآ]", admin[0]):
adminsac.append(u"!!!!!!!!!!!!!!!!!!!!!!!!!!!" + admin)
else:
adminsac.append(admin)
else:
acaction.sort()
dcaction.sort()
if re.search(ur"[ابپتثجچحخدذرزژسشصضطظعغفقکگلمنوهیآ]", admin[0]):
admin = u"!!!!!!!!!!!!!!!!!... | -1]
pywikibot.output(admin)
adminsac.sort()
activetext = u"\n{{ویکیپدیا:فهرست مدیران/سطرف|" + \
u"}}\n{{ویکیپدیا:فهرست مدیران/سطرف|".join(adminsac) + u"}}"
deactivetext = u"\n"
activetext = activetext.replace(u"!!!!!!!!!!!!!!!!!!!!!!!!!!!", u"")
ak = adminsdiac.keys()
ak.sort()
for admin in ak:
deactivete... |
silenci/neutron | neutron/tests/unit/plugins/ml2/drivers/mech_sriov/agent/extension_drivers/test_qos_driver.py | Python | apache-2.0 | 3,786 | 0.001321 | # Copyright 2015 Mellanox Technologies, Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may | not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITI... | mport mock
from oslo_utils import uuidutils
from neutron import context
from neutron.objects.qos import policy
from neutron.objects.qos import rule
from neutron.plugins.ml2.drivers.mech_sriov.agent.common import exceptions
from neutron.plugins.ml2.drivers.mech_sriov.agent.extension_drivers import (
qos_driver)
fro... |
OCA/l10n-switzerland | l10n_ch_account_tags/__manifest__.py | Python | agpl-3.0 | 561 | 0 | # Copy | right 2019 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
{
"name": "Switz | erland Account Tags",
"category": "Localisation",
"summary": "",
"version": "14.0.1.0.0",
"author": "Camptocamp SA, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/l10n-switzerland",
"license": "AGPL-3",
"depends": ["l10n_ch"],
"data": [
"data/new/account.ac... |
mjwtom/swift | test/dedupe/bin/download-debug.py | Python | apache-2.0 | 283 | 0.003534 | #!/home/mjwtom/install/ | python/bin/python
# -*- coding: utf-8 -*-
'''
Created on Jan 12, 2015
@author: mjwtom
'''
import os
if __name__ == '__main__':
os.system('/home/mjwtom/bin/swift -A http://127.0.0.1:8080/auth/v1.0 -U test:tester -K testing download mjw home/mjwtom/ | file')
|
Zerknechterer/pyload | module/plugins/hoster/ZeveraCom.py | Python | gpl-3.0 | 883 | 0.011325 | # -*- coding: utf-8 -*-
import re
import urlparse
from module.plugins.internal.MultiHoster import MultiHoster, create_getInfo
class ZeveraCom(MultiHoster):
__name__ = "ZeveraCom"
__type__ = "hoster"
__version__ = "0.31"
__pattern__ = r'https?://(?:www\.)zevera\.com/(getFiles\.ashx|Members/dow... | True)]
__description__ = """Zevera.com multi-hoster plugin"""
__license__ = "GPLv3"
__authors__ = [("zoidberg", "[email protected]"),
("Walter Purcaro", "[email protected]")]
FILE_ERRORS = [("Error", r'action="ErrorDownload.aspx')]
def handlePremium(self, pyfile... | self.link = "https://%s/getFiles.ashx?ourl=%s" % (self.account.HOSTER_DOMAIN, pyfile.url)
getInfo = create_getInfo(ZeveraCom)
|
yephper/django | tests/timezones/tests.py | Python | bsd-3-clause | 59,648 | 0.001794 | from __future__ import unicode_literals
import datetime
import re
import sys
import warnings
from contextlib import contextmanager
from unittest import SkipTest, skipIf
from xml.dom. | minidom import parseString
from django.contrib.auth.models import | User
from django.core import serializers
from django.core.exceptions import ImproperlyConfigured
from django.db import connection, connections
from django.db.models import Max, Min
from django.http import HttpRequest
from django.template import (
Context, RequestContext, Template, TemplateSyntaxError, conte... |
jstitch/gift_circle | GiftCircle/GiftCircle/wsgi.py | Python | gpl-3.0 | 397 | 0 | """
WSGI config for GiftCircle project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information o | n this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'GiftCircle.se | ttings')
application = get_wsgi_application()
|
joshchea/python-tdm | scripts/CalcLogitChoice.py | Python | mit | 12,741 | 0.015462 | #----------------------------------------------------------------------------------------------------------------------------------------------------------------------#
# Name: CalcLogitChoice
# Purpose: Utilities for various calculations of different types of choice models.
# a) CalcMultino... | d delta utility matrices in a dictionary i.e delta of Uk (k = mode)
ex. Utils = {'auto':mat1, 'transit':mat2, 'bike':mat3, 'walk':mat4}
Po = Base probabilities in a dictionary
ex. Po = {'auto':mat1, 'transit':mat2, 'bike':mat3, 'walk':mat4}
'''
Probs = {}
PeU = {}
... | s(Utils[Utils.keys()[0]].shape)
for key in Utils.keys():
PeU[key] = Po[key]*numpy.exp(Utils[key])
PeU_total+=PeU[key]
PeU_total[PeU_total == 0] = 0.0001
for key in PeU.keys():
Probs[key] = PeU[key]/PeU_total
del PeU, PeU_total, Utils
return Probs
#@profile
def... |
Micronaet/micronaet-migration | accounting_statistic_base/etl/__MOVED_SCHEDULED__/posta.py | Python | agpl-3.0 | 2,279 | 0.011847 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
#
# I find this on site: http://snippets.dzone.com/posts/show/2038
# sorry but, as the publisher, I don't know the origin and the owner of this code
# Let me tell him thank you, very useful code ;)
#
# The procedure send an E-mail to recipient list with recipient attachm... | matdate(localtime=True)
msg['Subject'] = subject
msg.attach( MIMEText(text) )
for f in files:
part = MIMEBase('application', "octet-stream")
part.set_payload(open(f,"rb").read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"'... |
# --------------
# - Invio mail -
# --------------
if not username: # invio senza autenticazione:
smtp = smtplib.SMTP(server)
#smtp.login(user, password)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.close()
elif TLS: # invio con autenticazione TLS
... |
Puyb/inscriptions_roller | inscriptions/migrations/0051_auto_20190131_2038.py | Python | gpl-3.0 | 978 | 0.002047 | # Generated by Django 2.0 on 2019-01-31 19:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('inscriptions', '0050_mer | ge_20190131_0016'),
]
operations = [
migrations.AlterField(
model_name='equipier',
name='cerfa_valide',
field=models.BooleanField(verbose_name='Cerfa QS-SPORT'),
),
migrations.AlterField(
model_name='equipier',
name='piece_join... | load_to='certificats', verbose_name='Certificat ou licence'),
),
migrations.AlterField(
model_name='templatemail',
name='destinataire',
field=models.CharField(choices=[('Equipe', "Gerant d'équipe"), ('Equipier', 'Equipier'), ('Organisateur', 'Organisateur'), ('Paiemen... |
sani-coop/tinjaca | addons/solicitudes/models/requisitos_garantia.py | Python | gpl-2.0 | 648 | 0.006182 | # -*- coding: utf-8 -*-
from openerp import models, fields, api
class RequisitosGarantia(models.Model):
_name = 'solicitudes.requisitos_garantia'
solicitudes_id = fields.Many2one('solicitudes.solicitudes', string="Número de expediente")
documentos_garantia_id = fields.Many2one('politicas.documentos_garan... | aciones = fields.Char(string='Observaciones')
valido = fields.Boolean(string='Valido')
solicitudes_tipos_garantia_id = fields.Many2one(string='Garantia', related='solicitudes_id.propuestas | _tipos_garantia_id', readonly=True)
|
SUNET/eduid-common | src/eduid_common/api/decorators.py | Python | bsd-3-clause | 7,549 | 0.002119 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import inspect
import warnings
from functools import wraps
from flask import abort, jsonify, request
from marshmallow.exceptions import ValidationError
from six import string_types
from werkzeug.wrappers import Response as WerkzeugResponse
from eduid_co... | eprecationWarning)
return func2(*args, **kwargs)
return new_func2
else:
raise TypeError(repr(type(reason)))
@deprecated('Use eduid_common.api.decorators.deprecated instead')
class Deprecated(object):
"""
| Mark deprecated functions with this decorator.
Attention! Use it as the closest one to the function you decorate.
:param message: The deprecation message
:type message: str | unicode
"""
def __init__(self, message=None):
self.message = message
def __call__(self, func):
if s... |
ProfessorX/Config | .PyCharm30/system/python_stubs/-1247972723/gtk/_gtk/TextWindowType.py | Python | gpl-2.0 | 767 | 0.007823 | # encoding: utf-8
# module gtk._gtk
# from /usr/lib/python2.7/dist-packages/gtk-2.0/gtk/_gtk.so
# by generator 1.135
# no doc
# imports
import atk as __atk
import gio as __gio
im | port gobject as __gobject
import gobject._gobject as __gobject__gobject
class TextWindowType(__gobject.GEnum):
# no doc
def __init__(self, *args, **kwargs): # real signature unknown
pass
__weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""list ... | 5: 5,
6: 6,
}
__gtype__ = None # (!) real value is ''
|
ctk3b/mdtraj | mdtraj/formats/amberrst.py | Python | lgpl-2.1 | 33,272 | 0.002495 | ##############################################################################
# MDTraj: A Python Library for Loading, Saving, and Manipulating
# Molecular Dynamics Trajectories.
# Copyright 2012-2014 Stanford University and the Authors
#
# Authors: Jason Swails
# Contributors:
#
# This code for reading Amber r... | needed.
"""
from __future__ import print_function, division
from distutils.version import StrictVersion
from math import ceil
import os
import warnings
import numpy as np
from mdtraj import version
from mdtraj.formats.registry import FormatRegistry
from mdtraj.utils import ensure_type, import_, in_units_of, cast_ind... | restrt', 'AmberNetCDFRestartFile',
'load_ncrestrt']
range = six.moves.range
@FormatRegistry.register_loader('.rst7')
@FormatRegistry.register_loader('.restrt')
@FormatRegistry.register_loader('.inpcrd')
def load_restrt(filename, top=None, atom_indices=None):
"""Load an AMBER ASCII restart/inpcrd file. ... |
edx-solutions/edx-platform | lms/djangoapps/learner_dashboard/tests/test_utils.py | Python | agpl-3.0 | 602 | 0.001661 | """
Unit test module covering utils module
"""
| import ddt
import six
from django.test import TestCase
from lms.djangoapps.learner_dashboard import utils
@ddt.ddt
class TestUtils(TestCase):
"""
The test case class covering the all the utils functions
"""
@ddt.data('path1/', '/path1/path2/', '/', '')
def test_strip_course_id(self, path):
... | """
actual = utils.strip_course_id(path + six.text_type(utils.FAKE_COURSE_KEY))
self.assertEqual(actual, path)
|
xorpaul/check_mk | web/htdocs/default_permissions.py | Python | gpl-2.0 | 7,863 | 0.010556 | #!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# | ____ _ _ __ __ _ __ |
# | / ___| |__ ___ ___| | __ | \/ | |/ / |
# | | | | '_ \ / _ \/ __| |/ /... | e Foundation, Inc., 51 Franklin St, Fifth Floor,
# Boston, MA 02110-1301 USA.
import config
loaded_with_language = False
# .----------------------------------------------------------------------.
# | ____ _ _ | |
# | | _ \ ___ _ __ _ __ ___ (_)___ ___(_) ___ _ __ ___ |
# | | |_) / _ \ '__| '_ ` _ \| / __/ __| |/ _ \| '_ \/ __| |
# | | __/ __/ | | | | | | | \__ \__ \ | (_) | | | \__ \ |
# | |_| \___|_| |_| |_| |_|_|___/___/_|\___/|_| |_|___... |
inducer/synoptic | synoptic/schema_ver_repo/versions/001_Rename_tagset_column.py | Python | mit | 467 | 0.006424 | from __future__ import absolute_import
from sqlalchemy import *
from migrate import *
meta = MetaData()
vieworderings = Table('vieworderings', meta,
Column('id', Integer, primary_key=True),
Column('tagset', Text()),
Column('timestamp', Float, index=True),
)
def upgrade(migrate_engine)... | engine):
| raise NotImplementedError
|
ericlyf/screenly-tools-schedulespreadsheet | src/model/Asset.py | Python | gpl-3.0 | 1,601 | 0.009369 | '''
Created on 11May,2016
@author: linyufeng
'''
from utils.TimeZoneConverter import TimeZoneConverter
class Asset(object):
'''
contain the values will be insert into table Asset
'''
convert = TimeZoneConverter();
def __init__(self, startTime, endTime, directory, fileName, fileType, duration... |
def getEndTime(self):
return self.endTime
def getDire | ctory(self):
return self.directory
def getFileName(self):
return self.fileName
def getFileType(self):
return self.fileType
def getDuration(self):
return self.duration
def getSequence(self):
return self.sequence
def __eq__(self,other):
... |
duramato/SickRage | sickbeard/providers/hdtorrents.py | Python | gpl-3.0 | 10,280 | 0.00428 | # Author: Idan Gutman
# Modified by jkaberg, https://github.com/jkaberg for SceneAccess
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of SickRage.
#
# SickRage 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 So... | log(u"Unable to connect to provider", logger.WARNING)
return False
if re.search('You need cookies enabled to log in.', response):
logger.log(u"Invalid username or password. Check your settings", logger.WARNING)
return False
return True
def _doSearch(self, searc... | ': [], 'Episode': [], 'RSS': []}
if not self._doLogin():
return results
for mode in search_strings.keys():
logger.log(u"Search Mode: %s" % mode, logger.DEBUG)
for search_string in search_strings[mode]:
if mode != 'RSS':
searchURL... |
annarev/tensorflow | tensorflow/python/keras/optimizer_v2/nadam.py | Python | apache-2.0 | 9,337 | 0.002356 | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | ype))
m = self.get_slot(var, 'm')
v = self.get_slot(var, 'v')
g_prime = grad / coefficients['one_minus_m_schedule_new']
# m_t = beta1 * m + (1 - beta1) * g_t
m_scaled_g_values = grad * coefficients['one_minus_beta_1_t']
m_t = state_ops.assign(m, m * coefficients['beta_1_t'],
... | _ops.gather(m_t, indices)
m_t_prime = m_t_slice / coefficients['one_minus_m_schedule_next']
m_t_bar = (coefficients['one_minus_m_t'] * g_prime +
coefficie |
mbedmicro/pyOCD | test/unit/test_notification.py | Python | apache-2.0 | 4,008 | 0.002745 | # pyOCD debugger
# Copyright (c) 2019 Arm Limited
# SPDX-License-Identifier: Apache-2.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
#
# ... | ENT_A)
notifier.unsubscribe(subscriber.cb)
notifier.notify(EVENT_A, self)
assert not subscriber.was_called
def test_unsub2(self, notifier, subscriber):
notifier.subscribe(subscriber.cb, EVENT_A)
notifier.unsubscribe(subscriber.cb, events=[EVENT_B])
notifier.notify(EV... | be(subscriber.cb, (EVENT_A, EVENT_B))
notifier.notify(EVENT_A, self)
assert subscriber.was_called
assert subscriber.last_note.event == EVENT_A
assert subscriber.last_note.source == self
assert subscriber.last_note.data == None
notifier.notify(EVENT_B, self)
assert... |
dataplumber/nexus | analysis/tests/algorithms/longitudelatitudemap_test.py | Python | apache-2.0 | 3,692 | 0.003792 | """
Copyright (c) 2016 Jet Propulsion Laboratory,
California Institute of Technology. All rights reserved
"""
import json
import time
import unittest
import urllib
from multiprocessing.pool import ThreadPool
from unittest import skip
from mock import MagicMock
from nexustiles.nexustiles import NexusTileService
from s... | ool))],
default_host=bind_unused_port()
)
# @skip("Integration test only. Works only if you have Solr and Cassandra running locally with data ingested")
def test_integration_all_in_tile(self):
def get_argument(*args, **kwarg | s):
params = {
"ds": "MXLDEPTH_ECCO_version4_release1",
"minLon": "-45",
"minLat": "0",
"maxLon": "0",
"maxLat": "45",
"startTime": "1992-01-01T00:00:00Z",
"endTime": "2016-12-01T00:00:00Z"
... |
goirijo/thermoplotting | old/testing/dataset/rough_cooling_nuke_0/cool.py | Python | mit | 472 | 0.027542 | import glob
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
#plt.style.use('ggplot')
dirlist=glob.glob("./mu-*.*")
fig=plt.figure()
ax=fig.add_subplot(111)
for run in dirlist:
rundata=np.loadtxt(run+"/debugout/tabula | ted_averages.txt")
x=rundata[:,4]/(rundata[:,3]+rundata[:,4])
y=rundata[:,6]
ax.scatter(x,y)
ax.set_xlabel(r"\textbf{x$_{\mathrm{Al}}$}")
ax.set | _ylabel(r"\textbf{T [K]}")
plt.show()
|
olafhauk/mne-python | mne/preprocessing/_csd.py | Python | bsd-3-clause | 6,319 | 0 | # Copyright 2003-2010 Jürgen Kayser <[email protected]>
# Copyright 2017 Federico Raimondo <[email protected]> and
# Denis A. Engemann <[email protected]>
#
#
# The original CSD Toolbox can be find at
# http://psychophysiology.cpmc.columbia.edu/Software/CSDtoolbox/
# Authors: Denis A. Engeman <d... | annels found.')
_validate_type(lambda2, 'numeric', 'lambda2')
if not 0 <= lambda2 < 1:
raise ValueError('lambda2 must be between 0 and 1, got %s' % lambda2)
_validate_type(stiffness, 'numeric', 'stiffness')
if stiffness < 0:
raise ValueError('stiffness must be non-negative got %s' % st... | n_legendre_terms = _ensure_int(n_legendre_terms, 'n_legendre_terms')
if n_legendre_terms < 1:
raise ValueError('n_legendre_terms must be greater than 0, '
'got %s' % n_legendre_terms)
if isinstance(sphere, str) and sphere == 'auto':
radius, origin_head, origin_device... |
jboes/jasp | jasp/volumetric_data.py | Python | gpl-2.0 | 5,279 | 0.001137 | """Module for reading volumetric data from VASP calculations.
Charge density and dipole moment
Local potential
Electron localization function
"""
import os
import numpy as np
from ase.calculators.vasp import Vasp, VaspChargeDensity
from POTCAR import get_ZVAL
def get_volumetric_data(self, filename='CHG', **kwargs):
... | ntials code returns a path
# with a / in the beginning.
fullpath = ppp + ppath
| z = get_ZVAL(fullpath)
zval[sym] = z
ion_charge_center = np.array([0.0, 0.0, 0.0])
total_ion_charge = 0.0
for atom in atoms:
Z = zval[atom.symbol]
total_ion_charge += Z
pos = atom.position
ion_charge_center += Z*pos
ion_charge_center /= total_ion_charge
... |
coderbone/SickRage-alt | sickchill/views/config/anime.py | Python | gpl-3.0 | 2,470 | 0.001619 | # coding=utf-8
# Author: Nic Wolfe <[email protected]>
# URL: https://sickchill.github.io
#
# This file is part of SickChill.
#
# SickChill 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... | See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with SickChill. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, print_function, unicode_literals
# Stdlib Imports
import os
# Third Party Imports
fr... | irst Party Imports
import sickbeard
from sickbeard import config, filters, ui
from sickchill.helper.encoding import ek
from sickchill.views.common import PageTemplate
from sickchill.views.routes import Route
# Local Folder Imports
from .index import Config
@Route('/config/anime(/?.*)', name='config:anime')
class Con... |
icoxfog417/pyfbi | tests/demo.py | Python | mit | 404 | 0.007426 | import | os
import sys
import time
sys.path.append(os.path.join(os.path.dirname(__file__), "../"))
import pyfbi
@pyfbi.target
def func1():
time.sleep(1)
def func2():
time.sleep(2)
@pyfbi.target
def func3():
time.sleep(3)
with pyfbi.watch():
[f() for f in (func1, func2, func3)]
pyfbi.show()
with pyfbi.wat... | (global_watch=True):
[f() for f in (func1, func2, func3)]
pyfbi.show()
|
illfelder/compute-image-packages | packages/python-google-compute-engine/setup.py | Python | apache-2.0 | 3,041 | 0.002302 | #!/usr/bin/python
# Copyright 2016 Google Inc. 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 appli... | ue,
install_requires=install_requires,
l | icense='Apache Software License',
long_description='Google Compute Engine guest environment.',
name='google-compute-engine',
packages=setuptools.find_packages(),
url='https://github.com/GoogleCloudPlatform/compute-image-packages',
version='20191112.0',
# Entry points create scripts in /usr/bin t... |
utmi-2014/utmi-soft3 | beginner_tutorials/scripts/simple_action_client.py | Python | mit | 582 | 0.024055 | #!/usr/bin/env python
import roslib; roslib.load_manifest('beginner_tutorials')
import rospy
import actionlib
from beginner_tutorials.msg import * |
if __name__ == '__main__':
rospy.init_node('do_dishes_client')
client = actionlib.SimpleActionClient('do_dishes', DoDishesAction)
client.wait_for_server()
goal = DoDishesGoal()
goal.dishwasher_id = 1
print "Requesting dishwasher %d"%(goal.dishwasher_id)
client.send_goal(goal)
client.wait_for_result(rospy.Du... | ient.get_result()
print "Resulting dishwasher %d"%(result.total_dishes_cleaned) |
rbuffat/pyidf | tests/test_setpointmanagermultizonecoolingaverage.py | Python | apache-2.0 | 2,146 | 0.003728 | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.setpoint_managers import SetpointManagerMultiZoneCoolingAverage
log = logging.getLogger(__name__)
class TestSetpointManagerMultiZoneCoolingAverage(unittest.TestCase):
def s... | = IDF(self.path)
self.assertEqual(idf2.setpointmanagermultizonecoolingaverages[0].name, var_name)
self.assertEqual(idf2.setpointmanagermultizonecoolingaverages[0].hvac_air_loop_name, var_hvac_air_loop_name)
self.assertAlmostEqual(idf2.setpointmanagermultizonecoolingaverages[0].minimum_setpoint_t... | 0].maximum_setpoint_temperature, var_maximum_setpoint_temperature)
self.assertEqual(idf2.setpointmanagermultizonecoolingaverages[0].setpoint_node_or_nodelist_name, var_setpoint_node_or_nodelist_name) |
badbytes/pymeg | pdf2py/el.py | Python | gpl-3.0 | 2,695 | 0.017811 |
try:from scipy.io.numpyio import *
except ImportError: from extra.numpyio import *
import os
from time import strftime
import shutil
class getpoints:
def __init__(self, elfile):
datetime = strftime("%Y-%m-%d %H:%M:%S").replace(' ', '_')
self.elfile = elfile
if os.path.isfile(elfile) == Tru... | 3, self.lpa, 'd', 1)
filewrite.seek(64, os.SEEK_SET) #24bytes
fwrite(filewrite, 3, self.rpa, 'd', 1)
filewrite.seek(128, os.SEEK_SET) #24bytes
fwrite(filewrite, 3, self.nas, 'd', 1)
filewrite.seek(192, os.SEEK_SET) #24bytes
fwrite(filewrite, 3, self.cz, 'd', 1)
fi... | 3, self.coil1, 'd', 1)
filewrite.seek(384, os.SEEK_SET) #24bytes
fwrite(filewrite, 3, self.coil2, 'd', 1)
filewrite.seek(448, os.SEEK_SET) #24bytes
fwrite(filewrite, 3, self.coil3, 'd', 1)
filewrite.seek(512, os.SEEK_SET) #24bytes
fwrite(filewrite, 3, self.coil4, 'd', 1)... |
scorphus/thefuck | thefuck/rules/tsuru_not_command.py | Python | mit | 527 | 0 | import re
from thefuck.utils import get_all_matched_commands, replace_command, for_app
@for_app('tsuru')
def match | (command):
return (' is not a tsuru command. See "tsuru help".' in command.output
and '\nDid you mean?\n\t' in command.output)
def get_new_command(command):
broken_cmd = re.fin | dall(r'tsuru: "([^"]*)" is not a tsuru command',
command.output)[0]
return replace_command(command, broken_cmd,
get_all_matched_commands(command.output))
|
beppec56/core | wizards/com/sun/star/wizards/agenda/AgendaWizardDialogResources.py | Python | gpl-3.0 | 14,293 | 0.004128 | #
# This file is part of the LibreOffice project.
#
# 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/.
#
# This file incorporates work covered by the following license noti... | gendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 8)
self.reslblTitle4_value = oWizardResource.getResText(
AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 9)
self.reslblTitle5_value = oWizardResource.getResText(
Agend | aWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 10)
self.reslblTitle6_value = oWizardResource.getResText(
AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 11)
self.reschkMinutes_value = oWizardResource.getResText(
AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG... |
TomWerner/AlumniMentoring | mentoring/migrations/0012_auto_20161027_1700.py | Python | mit | 5,231 | 0.001529 | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-10-27 22:00
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mentoring', '0011_auto_20161027_1653'),
]
operations = [
migrations.AlterField... | try'), ('3', 'Resume/CV Critique'), ('4', 'Parenting vs Career'), ('5', 'Work life balance'), ('6', 'Life after Iowa'), ('7', 'Study Abroad'), ('8', 'International Experience'), ('9', 'Fellowships'), ('10', 'Goals'), ('11', 'Shadowing Opportunities'), ('12', 'Grad school applications'), ('13', 'Med school applications'... | ', 'Gender specific')], max_length=1, null=True),
),
]
|
stevarino/cmsc495 | mac_app/migrations/0001_initial.py | Python | mit | 4,401 | 0.004317 | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-04-13 18:29
from __future__ import unicode_literals
import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import mac_app.models
class Migration(migrations.Migration):
initial = True
... | models.deletion.CASCADE, to='mac_app.Ticket')),
],
),
migrations.CreateModel(
name='TicketType',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name | ='ID')),
('name', models.CharField(max_length=16)),
('dsk_seq', models.IntegerField(default=0, verbose_name='Desktop Sequence')),
('dsk_msg', models.TextField(verbose_name='Desktop Message')),
('net_seq', models.IntegerField(default=0, verbose_name='Networ... |
merriam/dectools | dectools/test/test_make_call_if.py | Python | mit | 5,089 | 0.005699 | import dectools.dectools as dectools
from print_buffer import print_buffer
p = print_buffer()
prnt = p.rint
printed = p.rinted
prnt("Testing the @dectools.make_call_if decorator")
prnt("==================")
prnt("*No additonal parameters...")
@dectools.make_call_if
def check_security(function, args, kwargs):
prn... | :
global features
prnt("checking feature", feature)
if feature in features:
features.remove(feature)
return True
else:
return False
@is_feature_installed()
def general_stuff():
prnt("general stuff")
general_stuff()
printed("checking feature general", -2)
printed("genera... | st_to_facebook("me", "password")
printed("checking feature facebook")
prnt("Now update the global")
features = ["general", "print", "email", "twitter", "facebook"]
post_to_facebook("you", "123")
printed("checking feature facebook", -2)
printed("posting now")
prnt("==================")
prnt("Fun with bad usage")
@is_fe... |
petersilva/metpx-sarracenia | sarra/plugins/root_chown.py | Python | gpl-2.0 | 4,501 | 0.037325 | #!/usr/bin/python3
"""
This plugin can be use to add ownership and group of a file in a post message (on_post)
and change the owner/group of products at destination (on_file)
Sample usage:
plugin root_chown.py
Options
-------
If a users/groups differs from the source to the destination, the user can supply a mapp... | ownership in msg_headers")
return True
# it does, check for mapping
ug = msg.headers['ownership']
if ug in self | .mapping :
logger.debug("received ownership %s mapped to %s" % (ug,self.mapping[ug]))
ug = self.mapping[ug]
# try getting/setting ownership info to local_file
local_file = parent.new_dir + os.sep + parent.new_file
try :
parts = ug.split(':')
... |
tessercat/ddj | modules/poems.py | Python | mit | 7,006 | 0.003283 | import logging
from gluon import A
from gluon import DIV
from gluon import H3
from gluon import H4
from gluon import H5
from gluon import I
from gluon import IS_IN_SET
from gluon import LI
from gluon import P
from gluon import MARKMIN
from gluon import SQLFORM
from gluon import SPAN
from gluon import TAG
from gluon imp... | m.chapter)
if prev:
current.cache.ram('links-%d' % prev.first().chapter, None)
# Decache the page containing the poem.
page = (chapter + 8) / 9
current.cache.ram('poems-%d' % page, None)
def grid(db, deletable=F | alse):
""" Return an SQLFORM.grid to manage poems. """
createargs = editargs = viewargs = {
'fields': [
'chapter', 'published', 'intro_hanzi', 'intro_en']}
fields = [
db.poem.chapter,
db.poem.published,
db.poem.intro_hanzi,
db.poem.intro_en]
maxtextle... |
volker-kempert/python-tools | src/find_duplicates/cli_find_dups.py | Python | mit | 2,168 | 0.001384 | #!/usr/bin/env python
# -*- UTF8 -*-
import sys
import argparse
from .biz_func import *
from .io import format_duplicates
from utils.verbose import Verboser
try:
from _version import __version__
except ImportError:
__version__ = '--development-instance--'
def find_duplicates(root_dir):
"""
find_dupl... | containi | ng '--'
""")
parser.add_argument('scandir', action='store', default='.',
help='Name of the directory to scan')
parser.add_argument('--version',
help='Print the package version to stdout',
action='version', version='%(prog)s ' + __version__)
... |
zunaid321/Lenovo_A820_kernel_kk | bionic/libc/kernel/tools/update_all.py | Python | gpl-2.0 | 2,397 | 0.01627 | #!/usr/bin/env python
#
import sys, cpp, kernel, | glob, os, re, getopt, clean_header
from defaults import *
from utils import *
def usage():
print """\
usage: %(progname)s [kernel-original-path]
this program is used to update all the auto-generated clean h | eaders
used by the Bionic C library. it assumes the following:
- a set of source kernel headers is located in '../original',
relative to the program's directory
- the clean headers will be placed in '../arch-<arch>/asm',
'../common/linux', '../common/asm-generic', etc..
""" % { "progna... |
mdneuzerling/AtomicAlgebra | AtomicAlgebra.py | Python | gpl-3.0 | 23,406 | 0.007007 | from functools import reduce
from itertools import chain, combinations, product, permutations
# This class is used to represent and examine algebras on atom tables.
# It is intended to be used for nonassociative algebras, but this is not assumed.
class AtomicAlgebra:
# Create an algebra from a table of... | # methods convert between the two.
@staticmethod
def converse_pairs_to_dict(converse_pairs):
converse_dict = dict()
for converse_pair in converse_pairs:
if convers | e_pair[0] == converse_pair[1]: # symmetric atom
converse_dict[converse_pair[0]] = converse_pair[0]
else: # non-symmetric atoms
converse_dict[converse_pair[0]] = converse_pair[1]
converse_dict[converse_pair[1]] = converse_pair[0]
return converse_di... |
SUSE/azure-sdk-for-python | azure-mgmt-compute/azure/mgmt/compute/compute/v2016_04_30_preview/models/virtual_machine_scale_set_extension_profile.py | Python | mit | 1,089 | 0.000918 | # 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 g | enerated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization | import Model
class VirtualMachineScaleSetExtensionProfile(Model):
"""Describes a virtual machine scale set extension profile.
:param extensions: The virtual machine scale set child extension
resources.
:type extensions: list of :class:`VirtualMachineScaleSetExtension
<azure.mgmt.compute.comput... |
GoogleCloudPlatform/PerfKitBenchmarker | tests/scripts/gcp_pubsub_client_test.py | Python | apache-2.0 | 1,810 | 0.003315 | """Tests for data/messaging_service/gcp_pubsub_client.py."""
import unittest
from unittest import mock
from perfkitbenchmarker.scripts.messaging_service_scripts.gcp import gcp_pubsub_client
NUMBER_OF_MESSAGES = 1
MESSAGE_SIZE = 10
PROJECT = 'pkb_test_project'
TOPIC = 'pkb_test_topic'
SUBSCRIPTION = 'pkb_test_subscrip... | terface.pull_message()
# assert pull was called
subscriber_mock.return_value.pull.assert_called()
def testAcknowledgeReceivedMessage(self, subscriber_mock, _):
response_mock = mock.MagicMock()
response_mock.return_value.received_messages[
0].message.data = 'mocked_message'
gcp_interface... | SUBSCRIPTION)
gcp_interface.acknowledge_received_message(response_mock)
# assert acknowledge was called
subscriber_mock.return_value.acknowledge.assert_called()
if __name__ == '__main__':
unittest.main()
|
CKPalk/MachineLearning | Assignment1/id3.py | Python | mit | 4,116 | 0.082119 |
import sys
import math
import CSVReader
import DecisionTree
# GLOBALS
attributes = list()
data = list(list())
pre_prune_tree = True
# MATH FUNCTIONS
def Entropy( yesNo ):
yes = yesNo[0]; no = yesNo[1]
if no == 0 or yes == 0: return 0
total = no + yes
return ( -( yes / total ) * math.log( yes / total, 2 )
... | ( lambda row: row[ indexOfAttribute( Attr ) ] == Label, S ) )
def resultsOfSet( S ):
no = len( list( filter( lambda row: row[-1] is False, S ) ) )
return ( len( S ) - no, no )
def convertRowToDict( row ):
return { attributes[ i ] : row[ i ] for i in range( len( row ) ) }
def extractDecisions( S ):
return [ row[-... | / min( len( D1 ), len( D2 ) )
def findBestAttribute( S, attrs ):
bestAttributeAndGain = ( None, -1 ) if not pre_prune_tree else ( None, 0 )
#print( "+-- Gain ---" )
for attr in attrs:
attrGain = Gain( S, attr )
#print( "|", attr, "%0.7f" % ( attrGain ) )
if attrGain > bestAttributeAndGain[ 1 ]:
bestAttri... |
jardiacaj/finem_imperii | world/migrations/0004_tileevent_create_timestamp.py | Python | agpl-3.0 | 501 | 0.001996 | # Generated by Django 2.1 on 2018-08-19 13:12
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
| dependencies = [
('world', '0003_auto_20180819_0036'),
]
operations = [
migrations.AddField(
| model_name='tileevent',
name='create_timestamp',
field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now),
preserve_default=False,
),
]
|
mxOBS/deb-pkg_trusty_chromium-browser | third_party/WebKit/Source/bindings/scripts/v8_union.py | Python | bsd-3-clause | 6,305 | 0.000952 | # Copyright 2014 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 v8_utilities
UNION_H_INCLUDES = frozenset([
'bindings/core/v8/Dictionary.h',
'bindings/core/v8/ExceptionState.h',
'bindings/core/v8/V8Bi... | e_members > 1:
raise Exception('%s contains more than one nullable members' % union_type.name)
if dictionary_type and nullable_members == 1:
raise Exception('%s has a dictionary and a nullable member' % union_type.name)
return {
'array_buffer_type': array_buffer_type,
'array_buf... | _or_sequence_type,
'boolean_type': boolean_type,
'cpp_class': union_type.cpp_type,
'dictionary_type': dictionary_type,
'type_string': str(union_type),
'includes_nullable_type': union_type.includes_nullable_type,
'interface_types': interface_types,
'members': membe... |
yasir1brahim/OLiMS | lims/browser/reports/qualitycontrol_analysesrepeated.py | Python | agpl-3.0 | 5,554 | 0.00162 | from dependencies.dependency import getToolByName
from lims.browser import BrowserView
from dependencies.dependency import ViewPageTemplateFile
from lims import bikaMessageFactory as _
from lims.utils import t
from lims.utils import formatDateQuery, formatDateParms
from dependencies.dependency import IViewView
from dep... | iew_state}
dataline.append(dataitem)
datalines.append(dataline)
count_all += 1
# table footer data
footlines = []
footline = []
footitem = {'value': _('Number of analyses retested for period'),
'colspan': 7,
'... | ppend(footitem)
footitem = {'value': count_all}
footline.append(footitem)
footlines.append(footline)
self.report_content = {
'headings': headings,
'parms': parms,
'formats': formats,
'datalines': datalines,
'footings': footline... |
LogicalDash/kivy | kivy/uix/gridlayout.py | Python | mit | 19,254 | 0 | '''
Grid Layout
===========
.. only:: html
.. image:: images/gridlayout.gif
:align: right
.. only:: latex
.. image:: images/gridlayout.png
:align: right
.. versionadded:: 1.0.4
The :class:`GridLayout` arranges children in a matrix. It takes the available
space and divides it into columns a... | =0, allownone=True)
| '''Number of rows in the grid.
.. versionchanged:: 1.0.8
Changed from a NumericProperty to a BoundedNumericProperty. You can no
longer set this to a negative value.
:attr:`rows` is a :class:`~kivy.properties.NumericProperty` and defaults to
0.
'''
col_default_width = NumericProper... |
zeit/now-cli | packages/now-cli/test/dev/fixtures/python-flask/api/user.py | Python | apache-2.0 | 247 | 0.004049 | from flask import Flask, Response, request
app = Flask(__name__ | )
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def user(path):
name = request.args.g | et('name')
return Response("Hello %s" % (name), mimetype='text/html')
|
qris/mailer-dye | dye/fablib.py | Python | gpl-3.0 | 29,664 | 0.001584 | import os
from os import path
from datetime import datetime
import getpass
import re
import time
from fabric.context_managers import cd, hide, settings
from fabric.operations import require, prompt, get, run, sudo, local
from fabric.state import env
from fabric.contrib import files
from fabric import utils
def _setu... | ir', path.join(env.vcs_root_dir, 'deploy'))
env.setdefault('settings', '%(project_name)s.settings' % env)
if env.project_type == "django":
env.setdefault('relative_django_dir', env.project_name)
env.setdefault('relative_django_settings_dir', env['relative_django_dir'])
env.setdefau | lt('relative_ve_dir', path.join(env['relative_django_dir'], '.ve'))
# now create the absolute paths of everything else
env.setdefault('django_dir',
path.join(env['vcs_root_dir'], env['relative_django_dir']))
env.setdefault('django_settings_dir',
path.join... |
AlpacaDB/chainer | cupy/creation/from_data.py | Python | mit | 3,203 | 0 | import cupy
from cupy import core
def array(obj, dtype=None, copy=True, ndmin=0):
"""Creates an array on the current device.
This function currently does not support the ``order`` and ``subok``
options.
Args:
obj: :class:`cupy.ndarray` object or any other object that can be
passe... | shape if needed.
Returns:
cupy.ndarray: An array on the current device.
.. seealso:: :func:`numpy.array`
"""
# TODO(beam2d): Support order and subok options
return core.array(obj, dtype, copy, ndmin)
def asarray(a, dtype=None):
| """Converts an object to array.
This is equivalent to ``array(a, dtype, copy=False)``.
This function currently does not support the ``order`` option.
Args:
a: The source object.
dtype: Data type specifier. It is inferred from the input by default.
Returns:
cupy.ndarray: An ... |
chanhou/refine-client-py | parse_paper.py | Python | gpl-3.0 | 289 | 0.020761 |
with open('/tmp2/MicrosoftAcademicGraph/Papers.txt', | 'r') as f, open('/tmp2/MicrosoftAcademicGraph_refine/papers_1_column.txt','w') as b:
for line in f:
a = line.split('\t')
# | a = a[1].split('\r')
#b.write(a[0]+a[1])
b.write(a[2]+'\n')
#break
|
asifmadnan/DIGITS | digits/model/tasks/caffe_train.py | Python | bsd-3-clause | 54,494 | 0.004 | # Copyright (c) 2014-2015, NVIDIA CORPORATION. All rights reserved.
import os
import re
import time
import math
import subprocess
import numpy as np
from google.protobuf import text_format
import caffe
try:
import caffe_pb2
except ImportError:
# See issue #32
from caffe.proto import caffe_pb2
from train... | ame in tops:
if name not in bottoms:
network_outputs.append(name)
assert len(network_outputs), 'network must have an output'
# Update num_output for any output InnerProduct layers automatically
for layer in hidden_layers.layer:
if layer.type == 'InnerProd... | ls())
break
### Write train_val file
train_val_network = caffe_pb2.NetParameter()
# data layers
if train_data_layer is not None:
if train_data_layer.HasField('data_param'):
assert not train_data_layer.data_param.HasField('source'), "... |
daveinnyc/various | project_euler/036.double_palindromes.py | Python | mit | 761 | 0.005256 | '''
Problem 036
The decimal number, 585 = 10010010012 (binary), is palindromic in both bases.
Find the sum of all numbers, less than one million, which are palindromi | c in
base 10 and base 2.
(Please note that the palindromic number, in either base, may not include
leading zeros.)
Solution: Copyright 2017 Dave Cuthbert, MIT License
'''
def is_palindrome(number):
if str(number) == str(number)[::-1]:
return True
return False
def solve_problem(limit):
... | , 'b')):
palindromes.append(n)
return(sum(palindromes))
if __name__ == "__main__":
limit = 1000000
print(solve_problem(limit))
|
ngoduykhanh/PowerDNS-Admin | run.py | Python | mit | 224 | 0.013393 | #!/usr | /bin/env python3
from powerdnsadmin import create_app
if __name__ == '__main__':
app = create_app()
app.run(debug = True, host=app.config.get('BIND_ADDRESS', '127.0.0.1'), port=app.config.get('PORT', ' | 9191'))
|
fengbohello/practice | python/dict/fromkeys.py | Python | lgpl-3.0 | 648 | 0.016975 | dc = {'a' : 'a-ele', 'b' : 'b-ele', 'c' : 'c-ele'}
print "id(dc) = ["+ str(id(dc)) +"] dict is : " + str(dc)
print " | ========================"
x = dc.fromkeys(dc, 'x-ele')
print "type of dc.fromkeys(dc, 'x-ele') = [" + str(type(x)) + "]"
print x
print "========================"
x = dict.fromkeys(dc, 'dict-ele')
print "type of dict.fromkeys(dc, 'x-ele') = [" + str(type(x)) + "]"
print "id(x) = ["+ str(id(x)) +"], x = ["+ str(x) +"]"
... | str(type(x)) + "]"
print x
print "========================"
print "id(dc) = ["+ str(id(dc)) +"] dict is : " + str(dc)
|
uclouvain/osis | base/tests/factories/entity_version.py | Python | agpl-3.0 | 2,480 | 0.001614 | ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core bus... | class Meta:
model = 'base.EntityVersion'
entity = factory.SubFactory(EntityFactory)
title = factory.Faker('company')
acrony | m = factory.Iterator(generate_acronyms())
entity_type = factory.Iterator(entity_type.ENTITY_TYPES, getter=lambda c: c[0])
parent = factory.SubFactory(EntityFactory)
start_date = datetime.date(2015, 1, 1).isoformat()
end_date = None
class Params:
sector = factory.Trait(entity_type=entity_typ... |
jdp/urp | urp.py | Python | mit | 7,836 | 0.004977 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import itertools
import os
import sys
try:
from urllib import quote_plus, urlencode
from urlparse import parse_qsl, urlparse, urlunparse
except ImportError:
from urllib.parse import parse_qsl, quote_plus, urlencode, urlparse, urlunparse
ERR_INV... | query_value and not args.no_query_params:
suppress_default = True
# Would be nice to make `qu | ery_map` a defaultdict, but that would
# restrict this program to newer Python versions.
query_map = {}
for q, v in query:
if q not in query_map:
query_map[q] = []
query_map[q].append(v)
for q in args.query_value:
for v in query_map.get... |
skycucumber/Messaging-Gateway | webapp/venv/lib/python2.7/site-packages/twisted/test/test_threadable.py | Python | gpl-2.0 | 3,760 | 0.002926 | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for L{twisted.python.threadable}.
"""
from __future__ import division, absolute_import
import sys, pickle
try:
import threading
except ImportError:
threadingSkip = "Platform lacks thread support"
else:
threadingSkip = None... | ]
def callMethodLots():
try:
for i in range(1000):
o.aMethod()
except AssertionError as e:
errors.append(str(e))
threads = []
for x in range(5):
| t = threading.Thread(target=callMethodLots)
threads.append(t)
t.start()
for t in threads:
t.join()
if errors:
raise unittest.FailTest(errors)
if threadingSkip is not None:
testThreadedSynchronization.skip = threadingSkip
test_i... |
gantzgraf/vape | test/test_sample_filters.py | Python | gpl-3.0 | 6,155 | 0.0013 | from .utils import *
vep_and_snpeff_inputs = [(input_prefix + '.vcf.gz', False),
(input_prefix + '.snpeff.vcf.gz', True)]
def test_case_control():
for vcf, snpeff in vep_and_snpeff_inputs:
output = get_tmp_out()
test_args = dict(
input=vcf,
snpeff=... | sys._getframe().f_code.co_name)
asser | t_equal(results, expected)
os.remove(output)
if __name__ == '__main__':
import nose
nose.run(defaultTest=__name__)
|
LibreHealthIO/community-infra | ansible/files/monitoring/ssl_check_expire_days.py | Python | mpl-2.0 | 735 | 0.005442 | import time
import datetime
from OpenSSL import crypto as c
from checks import AgentCheck
class SSLCheckExpireDays(AgentCheck):
def check(self, instance):
metric = "ssl.expire_in_days"
certfile = instance['cert']
cert_tag = 'cert:%s' % (certfile.split('/')[-1:],)
date_format = "%Y%m... | today()
d1 = datetime.datetime(*(time.strptime(output, date_format)[0:3]))
delta = d1 - d0
self.gauge(metric, int(delta.days), tags=[cert | _tag])
else:
self.gauge(metric, -1, tags=[cert_tag])
|
legaultmarc/grstools | grstools/scripts/mendelian_randomization.py | Python | mit | 3,401 | 0 | """
Compute the GRS from genotypes and a GRS file.
"""
# This file is part of grstools.
#
# The MIT License (MIT)
#
# Copyright (c) 2017 Marc-Andre Legault
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# ... | args.phenotypes_filename,
args.phenotypes_sample_column, args.phenotypes_separator
)
if args.outcome_type == "continuous":
y_g_test = "linear"
elif args.outcome_type == "discrete":
y_g_test = "logistic"
else:
raise ValueError(
"Expected outcome type to be 'd... | linear"
elif args.exposure_type == "discrete":
x_g_test = "logistic"
else:
raise ValueError(
"Expected exposure type to be 'discrete' or 'continuous'."
)
n_iter = 1000
logger.info(
"Computing MR estimates using the ratio method. Bootstrapping "
"stand... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.