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 |
|---|---|---|---|---|---|---|---|---|
dariomangoni/chrono | src/demos/python/fea/demo_FEA_shells.py | Python | bsd-3-clause | 15,226 | 0.008669 | # =============================================================================
# PROJECT CHRONO - http:#projectchrono.org
#
# Copyright (c) 2014 projectchrono.org
# All rights reserved.
#
# Use of this source code is governed by a BSD-style license that can be found
# in the LICENSE file at the top level of the distri... | iw)],
nodearray[(il - 1) * (nels_W + 1) + (iw)])
melement.AddLayer(rect_thickness, 0 * chrono.CH_C_DEG_TO_RAD, mat)
elarray[(il - 1) * (nels_W) + (iw - 1)] = melement
nodesLoad = nodes_end
nodePlotA = nodes_end[0]
nodePlotB = nodes_end[-1]
for... | .SetFixed(True)
# applied load
# load_force = chrono.ChVectorD(200000,0, 20000)
load_force = chrono.ChVectorD(0, 4, 0)
# load_torque = chrono.ChVectorD(0, 0, 50*CH_C_PI/3.0)
# reference solution for (0, 4, 0) shear to plot
ref_Y.AddPoint(0.10, 1.309)
ref_X.AddPoint(0.40, 0.103)
ref_Y.A... |
USGS-EROS/lcmap-firebird | test/test_cli.py | Python | unlicense | 367 | 0.00545 | from ccdc import cli
from ccdc import cli
from click.testing import CliRunner
import test
@test.vcr.use_cassette(test.cassette)
def test_changed | etection():
runner = CliRunner()
result = runner.invoke(cli.entrypoint, ['changedetection', '-x 0', '-y 0', '-n 1'])
print(result.output)
assert result.exit_code == 0
def test_classification():
pass | |
SuperMass/distOS-lab3 | src/integrated/client2/client_config.py | Python | gpl-3.0 | 334 | 0.005988 | remote_s | erver_ips = ('127.0.0.1', '127.0.0.1')
remote_server_ports = (8005, 8006)
assigned_server_index = 0 # in real system, client is distributed by a load balancing server in general; here I just simulate the balancing policy.
process_id = 2
client_addr = ('127.0.0.1', 7002)
poisson_lambda = 5
simu_len = 60
get_sco | re_pb = 0.8
|
costastf/blind-Pyrsync | pytxt2pdf/pyText2Pdf.py | Python | lgpl-3.0 | 22,089 | 0.012495 | #!/usr/bin/env python
#-*- coding: UTF-8 -*-
# File: pyText2Pdf.py
#
# Derived from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/189858
__docformat__ = 'plaintext'
__date__ = '04/10/2013'
'''
pyText2Pdf - Python script to convert plain text files into Adobe
Acrobat PDF files.
Version 1.2
Author... | if 'ofile' in kwargs:
self._ofile = kwargs['ofile']
# default tab width
self._tab=4
# input file descriptor
self._ifs=None
# output file descriptor
self._ofs=None
self.buffers = False
if 'buffers' in kwargs and kwargs['buffers']:
s... | e=False
# Subject
self._subject = ''
# Author
self._author = ''
# Keywords
self._keywords = []
# Custom regexp for page breaks
self._pagebreakre = None
# marker objects
self._curobj = 5
self._pageObs = [0]
self._lo... |
ENCODE-DCC/encoded | src/encoded/tests/fixtures/schemas/genetic_modification.py | Python | mit | 19,673 | 0.000305 | import pytest
@pytest.fixture
def genetic_modification(testapp, lab, award):
item = {
'award': award['@id'],
'lab': lab['@id'],
'modified_site_by_coordinates': {
'assembly': 'GRCh38',
'chromosome': '11',
'start': 20000,
'end': 21000
}... | test.fixture
def crispr_tag(lab, award):
return {
'lab': lab['@id'],
'award': award['@id'],
'category': 'insertion',
'purpose': 'tagging',
'method': 'CRISPR'
}
@pytest.fixture
def bombardment_tag(lab, award):
return {
'lab': lab['@id'],
'award': awar... | ertion',
'purpose': 'tagging',
'nucleic_acid_delivery_method': ['bombardment']
}
@pytest.fixture
def recomb_tag(lab, award):
return {
'lab': lab['@id'],
'award': award['@id'],
'category': 'insertion',
'purpose': 'tagging',
'method': 'site-specific recomb... |
ericawright/bedrock | bedrock/newsletter/templatetags/helpers.py | Python | mpl-2.0 | 2,361 | 0.000424 | # 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 a | t http://mozilla.org/MPL/2.0/.
import logging
imp | ort jinja2
from django.template.loader import render_to_string
from django_jinja import library
from lib.l10n_utils import get_locale
from bedrock.newsletter.forms import NewsletterFooterForm
log = logging.getLogger(__name__)
@library.global_function
@jinja2.contextfunction
def email_newsletter_form(ctx, newslette... |
astrobin/astrobin | astrobin_apps_platesolving/migrations/0002_auto_20171109_2307.py | Python | agpl-3.0 | 468 | 0.002137 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.13 on 2017-11-09 23:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('astrobin_apps_platesolving', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='solu... | name='skyplot_ | zoom1',
field=models.ImageField(blank=True, null=True, upload_to=b'images/skyplots'),
),
]
|
souviik/NetSecure | vulnerability.py | Python | gpl-3.0 | 4,720 | 0.021186 | #!/usr/bin/env python
import urllib
import re
from site_fetch import * #importing everything from site_fetch module
def testUrl(url, payloads, check): # to split the url and try the append payloads in every parameter value.
opener = urllib.urlopen(url)
... | for payload in payloads:
bugs = url.replace(evry_parameter, e | vry_parameter + str(payload).strip()) #inserting payload after every parameter
request = useragent.open(bugs) #opening the URL with the insserted payload
html = request.readlines() ... |
joshuaeitan/massivedata | PS04/forensicswiki_geolocate.py | Python | cc0-1.0 | 1,874 | 0.013874 | #!/usr/bin/spark-submit
import sys
from operator import add
from pyspark import SparkContext
from pyspark import join
import socket, struct
from bisect import bisect_left
if __name__ == "__main__":
infileIp = 's3://gu-anly502/maxmind/GeoLite2-Country-Blocks-IPv4.csv'
infileCountry = 's3://gu-anly502/maxmind... | t(ipLong)
## Part D
infileFwiki = 's3: | //gu-anly502/ps03/forensicswiki.2012.txt'
linesFwiki = sc.textFile(infileFwiki)
## Part E
# Convert IPs in fwiki to long
fwiki = linesFwiki.map(lambda line: line.split(' - -'))
fwikiIpLong = fwiki.map(lambda line: (ip2long(line[0]),line[1]))
|
zjost/antsystem | functions/tau_branch.py | Python | gpl-2.0 | 184 | 0.038043 | import numpy as np
def tau_branch(tau,epp):
N = len | (tau[0,:])
branch_cnt = []
for i in range(N):
branch_cnt.append(np.sum(tau[i,:]>epp | ))
return branch_cnt |
xelphene/swaf | swaf/resp.py | Python | gpl-3.0 | 2,300 | 0.047391 |
codes = {
307: 'Temporary Redirect',
303: 'See Other',
302: 'Found',
301: 'Moved Permanently'
}
def authRequired(realm):
return {
'status': 401,
'reason': 'Authentication Required',
'headers': [
('Content-type','text/plain'),
('WWW-Authenticate', 'Basic realm="%s"' % realm)
],
'body': 'Authentic... | ype','text/plain')],
'body': '500 Internal Server Error. Error code: %s.' % str(code)
}
r['body'] += '\ | n\n-------------------------------------------\n'
r['body'] += 'Error Detail:\n\n'
r['body'] += '\n'.join(report)
return r
def error_vague(code=None):
r = {
'status': 500,
'reason': 'Internal Server Error',
'headers': [('Content-type','text/plain')],
'body': '500 Internal Server Error. Error code: %s.' %... |
molmod/zeobuilder | zeobuilder/nodes/reference.py | Python | gpl-3.0 | 6,367 | 0.002042 | # -*- coding: utf-8 -*-
# Zeobuilder is an extensible GUI-toolkit for molecular model construction.
# Copyright (C) 2007 - 2012 Toon Verstraelen <[email protected]>, Center
# for Molecular Modeling (CMM), Ghent University, Ghent, Belgium; all rights
# reserved unless otherwise stated.
#
# This file is part of Z... | ence. This should never happen. Contact the authors."
else:
return self.prefix + ": " + self.target.name
def set_model(self, model, parent, index):
Node.set_model(self, model, parent, index)
if self.target is not None:
self.target.references.append(self)
def uns... | (self)
#
# Targets
#
def define_target(self, new_target):
if self.target is not None:
raise TargetError("Reference already has a target.")
if new_target is None:
raise TargetError("Must assign a target.")
if not self.check_target(new_target):
... |
alberthdev/pyradmon | pyradmon/args.py | Python | apache-2.0 | 68,354 | 0.009144 | #!/usr/bin/env python
# PyRadmon - Python Radiance Monitoring Tool
# Copyright 2014 Albert Huang.
#
# 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 requi | red by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied. See the License for the specific language governing
# permissions and limitations under the License.
#
# Argument Pars... |
biocore/pyqi | pyqi/interfaces/optparse/input_handler.py | Python | bsd-3-clause | 561 | 0.005348 | #!/usr/bin/env python
#----------------------------- | ------------------------------------------------
# Copyright (c) 2013, The BiPy Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#--------------------------------------------------------- | --------------------
from __future__ import division
__credits__ = ["Greg Caporaso", "Daniel McDonald", "Doug Wendel",
"Jai Ram Rideout"]
## Store project/inteface specific input handlers here
|
yland/mailman3 | src/mailman/interfaces/pipeline.py | Python | gpl-2.0 | 1,138 | 0.000879 | # Copyright (C) 2008-2015 by the Free Software Foundation, Inc.
#
# This file is part of GNU Mailman.
#
# GNU Mailman 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 you... | ilman. If not, see <http://www.gnu.org/ | licenses/>.
"""Interface for describing pipelines."""
__all__ = [
'IPipeline',
]
from zope.interface import Interface, Attribute
class IPipeline(Interface):
"""A pipeline of handlers."""
name = Attribute('Pipeline name; must be unique.')
description = Attribute('A brief description of this ... |
meteorfox/PerfKitBenchmarker | perfkitbenchmarker/linux_benchmarks/oldisim_benchmark.py | Python | apache-2.0 | 8,628 | 0.008693 | # Copyright 2015 PerfKitBenchmarker 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 appli... | < (NUM_DRIVERS + NUM_ROOTS):
root_vms.append(vm)
else:
leaf_vms.append(vm)
leaf_vms = leaf_vms[:fanout]
for root_vm in root_vms:
SetupRoot(root_vm, leaf_vms)
driver_vm = driver_vms[0]
driver_binary = oldisim_dependencies.BinaryPath('DriverNode')
launch_script = oldisim_dependencies.Path... | p.
time.sleep(5)
driver_cmd = '%s -s %s:%s -t 30 -- %s %s --threads=%s --depth=16' % (
launch_script, FLAGS.oldisim_latency_metric, FLAGS.oldisim_latency_target,
driver_binary, driver_args, driver_vm.num_cpus)
logging.info('Driver cmdline: %s', driver_cmd)
stdout, _ = driver_vm.RemoteCommand(driver_... |
Swetabhsuman8/Tic-Toe-game-in-python | TicToe.py | Python | mit | 2,330 | 0.060944 | def print_board(board):
print "Tic Toe Game Developed by Swetabh Suman \n"
print "Gmail- [email protected]/Twitter- swetabhsuman8"
print "The board look like this: \n"
for i in range(3):
print " ",
for j in range(3):
if board[i*3+j] == 1:
print 'X',
elif board[i*3+j] == 0:
prin... | > 4:
winner = check_win(board)
if winner != -1:
out = "The winner is "
out += "X" if winn | er == 1 else "O"
out += " :)"
quit_game(board,out)
elif move == 9:
quit_game(board,"No winner :(")
if __name__ == "__main__":
main()
|
PetroDE/control | control/substitution.py | Python | mit | 9,525 | 0.002835 | """
While a Controlfile is being read in MetaServices allow for substitutions to be
made. All of the code is here instead of living in controlfile.py so you don't
have to scroll past the Controlfile class
"""
from enum import Enum
from random import randint
import logging
module_logger = logging.getLogger('control.su... | + [y],
(Kind.list, Kind.list, 'suffix'): lambda x, y: x + y,
(Kind.list, Kind.dict, 'suffix'): lambda x, y: {
k: _build_values_for_key(k, 'suffix', {'shared': x}, y) for k in y.keys() | {'shared'}
},
(Kind.singular, Kind.dict, 'suffix'): lambda x, y: {
k: _build_values_for_key(k, 'suffi... | in x.keys() | {'shared'}
},
(Kind.dict, Kind.list, 'suffix'): lambda x, y: {
k: _build_values_for_key(k, 'suffix', x, {'shared': y}) for k in x.keys() | {'shared'}
},
(Kind.dict, Kind.dict, 'suffix'): lambda x, y: {
k: _build_values_for_key(k, 'suffix', x, y) for k in x.keys() | y.keys()... |
openqt/algorithms | leetcode/python/lc669-trim-a-binary-search-tree.py | Python | gpl-3.0 | 1,292 | 0.017802 | # coding=utf-8
import unittest
"""669. Trim a Binary Search Tree
https://leetcode.com/problems/trim-a-binary-search-tree/description/
Given a binary search tree and the lowest and highest boundaries as `L` and
`R`, trim the tree so that all its elements lies | in `[L, R]` (R >= L). You
might need to change the root of the tree, so the result should return the new
root of the trimmed binary searc | h tree.
**Example 1:**
**Input:**
1
/ \
0 2
L = 1
R = 2
**Output:**
1
\
2
**Example 2:**
**Input:**
3
/ \
0 4
\
2
/
1
... |
daspecster/google-cloud-python | datastore/google/cloud/datastore/query.py | Python | apache-2.0 | 19,705 | 0 | # Copyright 2014 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | .
:rtype: sequence of (property_name, operator, value) tuples.
| :returns: The filters set on the query.
"""
return self._filters[:]
def add_filter(self, property_name, operator, value):
"""Filter the query based on a property name, operator and a value.
Expressions take the form of::
.add_filter('<property>', '<operator>', <va... |
eunchong/build | scripts/slave/recipes/chromium.gpu.recipe_autogen.py | Python | bsd-3-clause | 6,588 | 0.019126 | # Copyright 2016 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.
DEPS = [
'depot_tools/bot_update',
'chromium',
'depot_tools/gclient',
'recipe_engine/json',
'recipe_engine/properties',
'recipe_engine/python',
... | ustom_vars = {'webkit_trunk': 'http://src.chromium.org/blink/trunk',
'googlecode_url': 'http://%s.googlecode.com/svn',
'nacl_trunk': 'http://src.chromium.org/native_client/trunk',
'sourceforge_url': 'https://svn.code.sf.net/p/%(repo)s/code',
'llvm_url': 'http://llvm.org/svn/llvm-project'}
src_... | 'got_swarming_client_revision',
'src/v8': 'got_v8_revision'})
api.gclient.c = src_cfg
api.bot_update.ensure_checkout(force=True)
# gclient revert step
api.gclient.revert()
# cleanup_temp step
api.chromium.cleanup_temp()
# slave_steps step
api.python("slave_steps", "src/build/android/buildbot/bb_run... |
edaniszewski/pylint-quotes | tests/test_async_function.py | Python | mit | 8,816 | 0.002949 | """Tests for the string quote checker for function-level docstrings.
"""
import sys
import pytest
from pylint_quotes.checker import StringQuoteChecker
from pylint.testutils import Message, set_config
from utils import TRI_Q_DOUB, TRI_Q_SING, StringQuoteCheckerTestCase
@pytest.mark.skipif(sys.version_info < (3, 5),... | sync_function(test_str, msg)
@set_config(docstring_quote='double')
def test_single_line_double_quote_docstring_with_cfg_double_def_contents_03(self):
test_str = '''
async def fn(x): #@
"""Function level docstring on a single line."""
# define a function in a function
def local_fn(z):
| """Function within a function - incept |
ssanderson/numpy | numpy/linalg/linalg.py | Python | bsd-3-clause | 78,991 | 0.000987 | """Lite version of scipy.linalg.
Notes
-----
This module is a lite version of the linalg.py module in SciPy which
contains high-level Python interface to the LAPACK library. The lite
version only accesses the following LAPACK functions: dgesv, zgesv,
dgeev, zgeev, dgesdd, zgesdd, dgelsd, zgelsd, dsyevd, zheevd, dgetr... | == 1:
return cast_arrays[0]
else:
return cast_arrays
def _assertRank2(*arrays):
for a in arrays:
if a.ndim != 2:
raise LinAlgError('%d-dimensional array given. Array must be '
'two-dimen | sional' % a.ndim)
def _assertRankAtLeast2(*arrays):
for a in arrays:
if a.ndim < 2:
raise LinAlgError('%d-dimensional array given. Array must be '
'at least two-dimensional' % a.ndim)
def _assertSquareness(*arrays):
for a in arrays:
if max(a.shape) != min(a.shap... |
bkolada/koalocleaner | uis/__init__.py | Python | gpl-3.0 | 59 | 0 | # -*- coding: utf-8 -*-
f | rom MainWindow import Control | ler
|
nlhepler/idepi | idepi/util/__init__.py | Python | gpl-3.0 | 13,422 | 0.001416 | #
# idepi :: (IDentify EPItope) python libraries containing | some useful machine
# learning interfaces for regression and discrete analysis (including
# cross-validation, grid-search, and maximum | -relevance/mRMR feature selection)
# and utilities to help identify neutralizing antibody epitopes via machine
# learning.
#
# Copyright (C) 2011 N Lance Hepler <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publish... |
chapmanb/cwltool | tests/test_ext.py | Python | apache-2.0 | 5,706 | 0.00368 | import unittest
import tempfile
import os
import shutil
import cwltool.expression as expr
import cwltool.factory
import cwltool.pathmapper
import cwltool.process
import cwltool.workflow
from .util import get_data
from cwltool.main import main
class TestListing(unittest.TestCase):
def test_missing_enable_ext(self)... | test_li | sting_v1_1(self):
# # Default behavior in 1.1 will be no expansion
# self.assertEquals(main([get_data('tests/wf/listing_v1_1.cwl'), get_data('tests/listing-job.yml')]), 1)
class TestInplaceUpdate(unittest.TestCase):
def test_updateval(self):
try:
tmp = tempfile.mkdtemp()
... |
dropbox/changes-lxc-wrapper | changes_lxc_wrapper/snapshot_cache.py | Python | apache-2.0 | 3,494 | 0.000286 | import os.path
import shutil
from datetime import datetime
from uuid import UUID
DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%f"
def get_directory_size(path):
total_size = 0
for dirpath, dirnames, filenames in os.walk(path):
for f in filenames:
fp = os.path.join(dirpath, f)
total_s... | 'project': UUID(snapshot['project']['id']),
'date_created': convert_date(snapshot['dateCreated']),
'is_active': snapshot['isActive'],
}
# collect size information for each path
snapshot_list = []
for path in p... | id_ = UUID(path.rsplit('/', 1)[-1])
path_data = upstream_data.get(id_, {})
snapshot_list.append(SnapshotImage(
id=id_,
path=path,
is_active=path_data.get('is_active', False),
date_created=path_data.get('date_created'),
... |
pfs/CSA14 | python/csa14/QCD_80_120_MuEnriched_pythia8_cfi.py | Python | gpl-2.0 | 5,943 | 0.00875 | import FWCore.ParameterSet.Config as cms
maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) )
readFiles = cms.untracked.vstring()
secFiles = cms.untracked.vstring()
source = cms.Source ("PoolSource",fileNames = readFiles, secondaryFileNames = secFiles)
readFiles.extend( [
'/store/mc/Spring14miniao... |
'/store/mc/Spring14miniaod/QCD_Pt-80to120_MuEnrichedPt | 5_Tune4C_13TeV_pythia8/MINIAODSIM/PU20bx25_POSTLS170_V5-v1/00000/48093276-FC05-E411-9EEE-001F296564C6.root',
'/store/mc/Spring14miniaod/QCD_Pt-80to120_MuEnrichedPt5_Tune4C_13TeV_pythia8/MINIAODSIM/PU20bx25_POSTLS170_V5-v1/00000/50B66FF3-FA05-E411-A937-001F296564C6.root',
'/store/mc/Spring14miniaod/QCD_Pt-... |
calico/basenji | bin/sonnet_predict_bed.py | Python | apache-2.0 | 9,710 | 0.016478 | #!/usr/bin/env python
# Copyright 2017 Calico LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | pd
import pysam
import pyBigWig
import tensorflow as tf
if tf.__version__[0] == '1':
tf.compat.v1.enable_eager_execution()
from basenji import bed
from basenji import dna_io
from basenji import seqnn
from basenji import stream
'''
basenji_predict_bed.py
Predict sequences from a BED fi | le.
'''
################################################################################
# main
################################################################################
def main():
usage = 'usage: %prog [options] <model_file> <bed_file>'
parser = OptionParser(usage)
parser.add_option('-b', dest='bigwig_i... |
MrSenko/Nitrate | tcms/testplans/migrations/0002_add_initial_data.py | Python | gpl-2.0 | 929 | 0.001076 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
plan_types = [
'Unit',
'Integration',
'Function',
'System',
'Acceptance',
'Installation',
'Performance',
'Product',
'Interoperability',
'Smoke',
'Regression',
]
def forwards_... | tplans', 'TestPlanType')
TestPlanType.objects.filter(name__in=plan_types).delete()
class Migration(migrations.Migration):
| dependencies = [
('testplans', '0001_initial'),
]
operations = [
migrations.RunPython(forwards_add_initial_data, reverse_add_initial_data)
]
|
google/loaner | loaner/web_app/backend/handlers/cron/run_shelf_audit_events_test.py | Python | apache-2.0 | 6,937 | 0.002451 | # Copyright 2018 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... | s it more lenient.
self.shelf2.put()
# Shelf disabled for notifications
self.shelf3.audit_notification_enabled = False
self.shelf3.audit_requested = False
self.shelf3.put()
# Shelf already notified.
self.shel | f4.audit_notification_enabled = True
self.shelf4.audit_requested = True
self.shelf4.put()
self.testbed.mock_raiseevent.reset_mock()
response = self.testapp.get(r'/_cron/run_shelf_audit_events')
self.assertEqual(response.status_int, 200)
self.assertTrue(self.testbed.mock_raiseevent.called)
... |
microcom/partner-contact | partner_multi_relation/models/res_partner_relation.py | Python | agpl-3.0 | 5,718 | 0 | # Copyright 2013-2017 Therp BV <http://therp.nl>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
# pylint: disable=api-one-deprecated
"""Store relations (connections) between partners."""
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
class ResPartnerRelation(... | d in self:
if record.left_partner_id == record.right_partner_id:
if not (record.type_id and record.type_id.allow_self):
raise ValidationError(
_('Partners cannot have a relation with themselves.')
)
@api.constrains(
... | start',
'date_end',
)
def _check_relation_uniqueness(self):
"""Forbid multiple active relations of the same type between the same
partners
:raises ValidationError: When constraint is violated
"""
# pylint: disable=no-member
# pylint: disable=no-value-for-... |
sysadminmatmoz/pmis | issue_change_request/__manifest__.py | Python | agpl-3.0 | 609 | 0 | # -*- coding: utf-8 -*-
{
'name': 'Project Issue to Change Request',
'v | ersion': '8.0.1.0.3',
'summary': 'Create Change Requests from Project Issues',
'sequence': '19',
'complexity': 'ea | sy',
'author': 'Matmoz d.o.o., '
'Project Expert Team',
'contributors': [
'Matjaž Mozetič <[email protected]>',
],
'website': 'http://project.expert',
'category': 'Project Management',
'license': 'AGPL-3',
'data': [
'views/change_request_view.xml'
],
... |
Jdash99/des-inventory-simulation | psim/psim_control.py | Python | mit | 4,034 | 0.000248 | import sys
from PySide.QtGui import QPushButton, QWidget, QVBoxLayout, \
QHBoxLayout, QFormLayout, QComboBox, \
QLineEdit, QLabel, QIntValidator, QIcon
class ControlLayout(QWidget):
"""Widget that stores the controls"""
def __init__(self):
QWidget.__in... | mboBox(self)
self.policy.addItems(self.policies)
self.form_layout.addRow('Politica', self.policy)
# Connect policy button to hide 3rd parameter
self.policy.activated.connect(self.changed_policy)
# Add Parameters
self.parameters = QLabel('', self)
self.form_layou... |
self.p1_label = QLabel("Q")
self.pam1_box = QHBoxLayout()
self.pam1_box.addWidget(self.p1_label)
self.pam1_box.addStretch(1)
self.pam1_box.addWidget(self.p1)
self.form_layout.addRow(self.pam1_box)
# Parameter 2
self.p2 = QLineEdit(self, QWidget)
... |
googleinterns/contextual-adjectives | categorize_adjectives/libraries/bert_embeddings.py | Python | apache-2.0 | 5,343 | 0.003556 | """Contains function for calculating BERT embeddings"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import json
import re
import torch
from torch.utils.data import TensorDataset, DataLoader, SequentialSampler
from torch.utils.data.dis... | tokens=tokens,
| input_ids=input_ids,
input_mask=input_mask,
input_type_ids=input_type_ids))
return features
def _read_examples(self, inp):
"""Read a list of `InputExample`s from an input file."""
examples = []
unique_id = 0
for a, i... |
ESOedX/edx-platform | openedx/core/djangoapps/api_admin/widgets.py | Python | agpl-3.0 | 1,985 | 0.003526 | """ Form widget classes """
from __future__ import absolute_import
from django.conf import settings
from django.forms.utils import flatatt
from django.forms.widgets import CheckboxInput
from django.urls import reverse
from django.utils.encoding import force_text
from django.utils.html import format_html
from django.u... | add the 'value' attribute if a value is non-empty.
final_attrs['value'] = force_text(value)
# Translators: link_start and link_end are HTML tags for a link to the terms of service.
# platform_name is the name of this Open edX installation.
label = Text(_(
u'I, and my org... | he {link_start}{platform_name} API Terms of Service{link_end}.'
)).format(
platform_name=configuration_helpers.get_value('PLATFORM_NAME', settings.PLATFORM_NAME),
link_start=HTML(u'<a href="{url}" rel="noopener" target="_blank">').format(
url=reverse('api_admin:api-tos')
... |
vied12/superdesk | server/superdesk/services.py | Python | agpl-3.0 | 4,269 | 0.001405 | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import loggi... | return res
def delete_action(self, lookup=None): |
if lookup is None:
lookup = {}
if lookup:
doc = self.find_one(req=None, **lookup)
self.on_delete(doc)
res = self.delete(lookup)
if lookup and doc:
self.on_deleted(doc)
return res
def is_authorized(self, **kwargs):
""... |
1032231418/python | lesson10/apps/books/publish/__init__.py | Python | apache-2.0 | 3,345 | 0.00129 | # coding=utf8
from django.views.generic import ListView, DetailView, CreateView
from django.db.models import Q
from django.http import Jso | nResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.shortcuts import render
from pure_pagination.mixins import PaginationMixin
from django.contrib.auth.mixins import LoginRequiredMixin
from django.conf import | settings
from books.models import Publish, Author, Book
from books.forms import PublishForm
import json
import logging
logger = logging.getLogger('opsweb')
class PublishListView(LoginRequiredMixin, PaginationMixin, ListView):
'''
动作:getlist, create
'''
model = Publish
template_name = "books/pu... |
AndreySibiryakov/coding | py/check_errors_xlsx.py | Python | gpl-3.0 | 3,308 | 0.031741 | from openpyxl import load_workbook
import os
# list of text to search for
keyWordList = ['Resume', 'Label', 'Description', 'ClueText', 'Title', 'QTEtitle']
# default path for docs on my PC for sh8 game xlsx documents
#docDir = "d:/svn/ue3/SH8Game/Production/Dialogs/"
docDir = "d:/svn/ue3/SH8Game/Production/... | logVal
# collecting all .xlsxs from supplied path
genLog = ''
for path, dirs, fileNames in os.walk(docDir):
for file | Name in fileNames:
docPath = os.path.join(path, fileName)
# filtering files except .xlsx
if '.xlsx' in docPath:
# filling log
genLog += FindAndLog(docPath, keyWordList)
# writing and saving the log file
filePath = open(logFile, 'wb')
filePath.write(genLog)
filePath.close()
|
wdingx/pan-genome-analysis | panX.py | Python | gpl-3.0 | 17,982 | 0.019686 | #!/usr/bin/env python
import argparse
import os, sys, time
panX_script_dir= os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0,panX_script_dir+'/scripts/')
from pangenome_computation import pangenome
from sf_miscellaneous import times, check_dependency
'''
panX clusters genes from a set of microbial genomes... | ool (e.g.: /path/other_tool.out)' , metavar='')
parser.add_argument('-mi', '--metainfo_fpath', type = str, default = 'none',
help='the absolute path for meta_information file (e.g.: /path/meta.out)' , metavar='')
p | arser.add_argument('-dmp', '--diamond_path', type = str, default = '',
help='alternative diamond path provided by user', metavar='')
parser.add_argument('-dme', '--diamond_evalue', type = str, default = '0.001',
help='default: e-value threshold below 0.001', metavar='')
parser.add_argument('-dmt', '--diamond_ma... |
SeleniumHQ/selenium | py/test/selenium/webdriver/chrome/chrome_network_emulation_tests.py | Python | apache-2.0 | 1,447 | 0 | # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | lation():
driver = Chrome()
driver.set_network_conditions(
offline=False,
latency=56, # additional latency (ms)
throughput=789)
conditions = driver.get_network_conditions()
assert conditions['offline'] is False
assert conditions['latency'] == 56
assert conditions['downlo... | ghput'] == 789
driver.delete_network_conditions()
with pytest.raises(WebDriverException):
driver.get_network_conditions()
|
prasannav7/ggrc-core | src/ggrc/migrations/versions/20160412134448_11cee57a4149_add_assessor_reminder_notification.py | Python | apache-2.0 | 1,996 | 0.002505 | # Copyright (C) 2016 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: [email protected]
# Maintained By: [email protected]
"""
Add assessors reminder notification
Create Date: 2016-04-12 13:44:48.2651... | le = table(
'notification_types',
column('id', sa.Integer),
column('name', sa.String),
column('descripti | on', sa.Text),
column('template', sa.String),
column('instant', sa.Boolean),
column('advance_notice', sa.Integer)
)
def upgrade():
"""Inserts new notification type"""
op.bulk_insert(
notification_types_table,
[{
"name": "assessment_assessor_reminder",
"description": ("N... |
hail-is/hail | hail/python/hailtop/hailctl/dataproc/describe.py | Python | mit | 281 | 0.003559 | from .. import describe
import sys
init_parser = describe.init_parser
async def main(*args, **kwargs):
await describe.main_after_parsing(*args, **kwargs)
print('!!! `hailctl dataproc describe` is DEPRECATED. Please use `hailctl describe` instead. !!!', file=sys.stderr) | ||
CCI-MOC/GUI-Backend | core/migrations/0007_create_allocation_strategy_and_behaviors.py | Python | apache-2.0 | 5,962 | 0.004193 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def do_nothing(apps, schema_editor):
pass
def create_new_behaviors_and_strategies(apps, schema_editor):
CountingBehavior = apps.get_model("core", "CountingBehavior")
RefreshBehavior = apps.get_model... | ield(
model_name='allocationstrategy', name='refresh_behaviors', field=models.ManyToManyField(
| to='core.RefreshBehavior', null=True, blank=True), preserve_default=True, ), migrations.AddField(
model_name='allocationstrategy', name='rules_behaviors', field=models.ManyToManyFie... |
simontakite/sysadmin | pythonscripts/programmingpython/Internet/Email/PyMailGui/wraplines.py | Python | gpl-2.0 | 4,750 | 0.004842 | """
###############################################################################
split lines on fixed columns or at delimiters before a column;
see also: related but different textwrap standard library module (2.3+);
4E caveat: this assumes str; supporting bytes might help avoid some decodes;
#################... | ]
wraplines += [front]
return wraplines
###############################################################################
# common use case utilities
###############################################################################
def wrapText1(text, size=defaultsize): # better for li... | t once" # keeps original line brks struct
lines = text.split('\n') # split on newlines
lines = wrapLinesSmart(lines, size) # wrap lines on delimiters
return '\n'.join(lines) # put back together
def wrapText2(text, size=defaultsize): # m... |
chrisfroe/readdy | wrappers/python/src/python/readdy/examples/chain_decay.py | Python | lgpl-3.0 | 4,956 | 0.002422 | # coding=utf-8
# Copyright © 2016 Computational Molecular Biology Group,
# Freie Universität Berlin (GER)
#
# This file is part of ReaDDy.
#
# ReaDDy is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Softwar... | as f:
traj_handle.enable_write_to_file(f, u"", 50)
sim.run_scheme_readdy(True)\
.evaluate_topology_reactions()\
.write_config_to_file(f)\
.configure_and_run(time_steps, sel | f.time_step)
print("currently %s topologies" % len(sim.current_topologies()))
if __name__ == '__main__':
sim = ChainDecay("SingleCPU", .001)
sim.run(10000, "out.h5") |
axinging/chromium-crosswalk | third_party/WebKit/LayoutTests/http/tests/websocket/duplicated-headers_wsh.py | Python | bsd-3-clause | 754 | 0.001326 | from mod_pywebsocket import handshake
from mod_pywebsocket.handshake.hybi import compute_accept
def web | _socket_do_extra_handshake(request):
message = 'HTTP/1.1 101 Switching Protocols\r\n'
message += 'Upgrade: websocket\r\n'
message += 'Connection: Upgrade\r\n'
message += 'Sec-WebSocket-Accept: %s\r\n' % compute_accept(request.headers_in['Sec-WebSocket-Key'])[0]
message += 'foo: bar, baz\r\n'
mes... | yy\r\n'
message += '\r\n'
request.connection.write(message)
# Prevents pywebsocket from sending its own handshake message.
raise handshake.AbortedByUserException('Abort the connection')
def web_socket_transfer_data(request):
pass
|
steakwipe/ytdl-namer | mp3gen.py | Python | gpl-3.0 | 1,558 | 0.005777 | #!/usr/bin/python
# -*- coding: utf-8 -*- #
# This would be a lot easier with a she | llscript.
# Will probably just do this in bash, once I make this work.
# In this case we're doing it for educational purposes.
# Expect future revisions to be faster and more efficient.
# Started with working code, broke it to fit my needs.
# Makes me very sa | d, and way more work to figure out than ls *.mp3
# but at least it's not full on regex? :p
# by steakwipe with way too much help from beatsteak
#importing old soup for good luck
import os
#yt variable needed later
yt=https://youtu.be/
mp3list = '/home/steakwipe/git/ytdl-namer' #i'd like this to be a runtime option l... |
manthey/girder | girder/utility/config.py | Python | apache-2.0 | 2,764 | 0.000724 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright 2013 Kitware 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 cop... | .constants import PACKAGE_DIR
def _mergeConfig(filename):
"""
Load `filename` into the cherrypy config.
Also, handle global options by putting them in the root.
"""
cherrypy._cpconfig.merge(cherrypy.config, filename)
# When in Sphinx, cherrypy may be mocked and returning None
global_config... | ypy.config[option] = value
def _loadConfigsByPrecedent():
"""
Load configuration in reverse order of precedent.
"""
configPaths = [os.path.join(PACKAGE_DIR, 'conf', 'girder.dist.cfg')]
if 'GIRDER_TEST_DB' not in os.environ:
# we don't want to load the local config file if we are running t... |
t-brandt/acorns-adi | centroid/finecenter.py | Python | bsd-2-clause | 4,176 | 0.00431 | #!/usr/bin/env python
#
# Original filename: finecenter.py
#
# Author: Tim Brandt
# Email: tbra | [email protected]
# Date: May 2012
#
# Summary: Interactively refine the centroid of an image sequence
#
#from speckle_centroid import speckle_centroid
from easygui import *
from pylab import *
import pyfits as pyf
def finecenter(flux, objname, output_dir):
"""
function finecenter interactively re... | mes, plots the
central 80x80 pixels (0.8x0.8 arcseconds for HiCIAO) and labels
the center. The user then inputs the offset, and, when satisfied,
clicks 'OK'. The final image is saved in the output directory.
The function takes three inputs:
1. A 3D flux array; the first index should run over... |
ichuang/sympy | sympy/printing/pretty/stringpict.py | Python | bsd-3-clause | 17,143 | 0.003733 | """Prettyprinter by Jurjen Bos.
(I hate spammers: mail me at pietjepuk314 at the reverse of ku.oc.oohay).
All objects have a method that create a "stringPict",
that can be used in the str method for pretty printing.
Updates by Jason gedge (email <my last name> at cs mun ca)
- terminal_string() method
- minor f... | ject by a slash of the proper size.
"""
# XXX not used anywhere ?
height = max(
self.baseline,
self.height()-1-self.baseline)*2 + 1
slash = '\n'.join(
' '*(height-i-1)+xobj('/',1)+' '*i
for i in range(height)
)
return se... | "
# XXX not used anywhere
# XXX duplicate of root drawing in pretty.py
#put line over expression
result = self.above('_'*self.width())
#construct right half of root symbol
height = self.height()
slash = '\n'.join(
' ' * (height-i-1) + '/' + ' ' * i
... |
QRAAT/QRAAT | node/python/qa_rmg.py | Python | gpl-3.0 | 1,878 | 0.019702 | #!/usr/bin/env python2
#
# Copyright 2004 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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, or (at your option)... | (gr.sizeof_gr_complex, test_data)
#src_file = gr.file_source(gr.sizeof_gr_complex, "data_backup | 20070423/20070208164806.tdat")
#src_file = gr.file_source(gr.sizeof_gr_complex, "20080911161545.tdat")
di = gr.deinterleave(gr.sizeof_gr_complex)
self.fg.connect(src_file, di)
pd = rmg.detect(4,8000,160,480,1.1,"results", tx_name, 1.1,1.5)
pd.enable()
self.fg.con... |
kgilmo/penning_artiq | artiq/master/worker_db.py | Python | gpl-3.0 | 6,331 | 0.004265 | from collections import OrderedDict
import importlib
import logging
import os
import time
import re
import numpy as np
import h5py
from artiq.protocols.sync_struct import Notifier
from artiq.protocols.pc_rpc import AutoTarget, Client, BestEffortClient
logger = logging.getLogger(__name__)
def _create_device(desc, ... | # Automatic target can be specified either by the absence of
# the target_name parameter, or a None value.
target_name = desc.get("target_name", None)
if target_name is None:
target_name = AutoTarget
return cls | (desc["host"], desc["port"], target_name)
else:
raise ValueError("Unsupported type in device DB: " + ty)
class DeviceManager:
"""Handles creation and destruction of local device drivers and controller
RPC clients."""
def __init__(self, ddb, virtual_devices=dict()):
self.ddb = ddb
... |
wildchildyn/autism-website | yanni_env/lib/python3.6/site-packages/click/formatting.py | Python | gpl-3.0 | 8,889 | 0 | from contextlib import contextmanager
from .termui import get_terminal_size
from .parser import split_opt
from ._compat import term_len
# Can force a width. This is used by the test system
FORCED_WIDTH = None
def measure_table(rows):
widths = {}
for row in rows:
for idx, col in enumerate(row):
... | eases the indentation."""
self.current_indent -= self.indent_increment
def write_usage(self, prog, args='', prefix='Usage: '):
"""Writes a usage line into the buffer.
:param prog: the program name.
:param args: whitespace separated list of arguments.
:param prefix: the pref... | e_prefix = '%*s%s ' % (self.current_indent, prefix, prog)
text_width = self.width - self.current_indent
if text_width >= (term_len(usage_prefix) + 20):
# The arguments will fit to the right of the prefix.
indent = ' ' * term_len(usage_prefix)
self.write(wrap_text(arg... |
hellais/nemesys-qos | nemesys/timeNtp.py | Python | gpl-3.0 | 1,035 | 0.007729 | # timeNtp.py
# -*- coding: utf-8 -*-
# Copyright (c) 2010 Fondazione Ugo Bordoni.
#
# This program is free software: you can redistribute it and/or mod | ify
# it under the terms of the GNU General | Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PUR... |
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractNotsogoodtranslatorWordpressCom.py | Python | bsd-3-clause | 578 | 0.032872 |
def extra | ctNotsogoodtranslatorWordpressCom(item):
'''
Parser for 'notsogoodtranslator.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in it | em['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, ... |
chumsley/gambit | contrib/scripts/enumpoly/setup.py | Python | gpl-2.0 | 241 | 0.008299 | # Th | is is a distutils/py2exe script to build the Windows binary version
# of gambit-enumphc
from distutils.core import setup
import py2exe
setup(console=["enumphc.py"],
data_files=[(".",
[ | "phc.exe", "README" ])])
|
0/SpanishAcquisition | spacq/interface/pulse/tool/box.py | Python | bsd-2-clause | 1,290 | 0.031783 | import csv
from spacq.tool.box import flatten
"""
Pulse program helpers.
"""
def find_location(s, loc):
"""
Find where loc (linear index) in s.
Returns:
line number
column number
line itself
Note: Tabs are not handled specially.
"""
if loc < 0 or loc > len(s):
raise ValueError('Location given ({0})... | h_end) in enumerate(zip(lines, with_ends), 1):
if count + len(line) < loc:
count += len(with_end)
else:
col = loc - count + 1
return i, col, line
def format_error(msg, row=None, col=None, line=None):
"""
Format the error for human consumption.
"""
if row is None or col is None or line is No | ne:
return 'error: {0}'.format(msg)
else:
return 'error: {0} at column {1} on line {2}:\n{3}{4}\n{5}^'.format(msg,
col, row, ' ' * 2, line, ' ' * (col + 1))
def load_values(f):
"""
Load data points from a file.
The values in the file must either be comma separated, line-wise, or a combination of the two.... |
googleads/google-ads-python | google/ads/googleads/v9/enums/types/click_type.py | Python | apache-2.0 | 2,994 | 0.000334 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | on of Google Ads click types.
"""
class ClickType(proto.Enum):
r"""Enumerates Google Ads click types."""
UNSPECIFIED = 0
UNKNOWN = 1
APP_DEEPLINK = 2
BREADCRUMBS = 3
BROADBAND_PLAN = 4
CALL_TRACKING = 5
CALLS = 6
| CLICK_ON_ENGAGEMENT_AD = 7
GET_DIRECTIONS = 8
LOCATION_EXPANSION = 9
LOCATION_FORMAT_CALL = 10
LOCATION_FORMAT_DIRECTIONS = 11
LOCATION_FORMAT_IMAGE = 12
LOCATION_FORMAT_LANDING_PAGE = 13
LOCATION_FORMAT_MAP = 14
LOCATION_FORMAT_STORE_INFO = 15
... |
egbertbouman/tribler-g | Tribler/Test/test_channelcast.py | Python | lgpl-2.1 | 15,423 | 0.015496 | # Written by Arno Bakker
# see LICENSE.txt for license information
# TODO: let one hit to SIMPLE+METADATA be P2PURL
import unittest
import os
import sys
import time
import tempfile
import shutil
from Tribler.Core.Utilities.Crypto import sha
from types import StringType, DictType, IntType
from M2Crypto impo... | ecast_db.getVote(bin2str(self.mypermid),bin2str(self.hispermid)),None)
#print >> sys.stderr, self.votecast_db.getAll()
self.votecast_db.spam(bin2str(self.mypermid))
self.assertEqual(self.votecast_db.getVote(bin2str(self.mypermid),bin2str(self.hispermid)),-1)
#print >> sys.stderr, s... | ast_db.getAll()
self.votecast_db.subscribe(bin2str(self.mypermid))
self.assertEqual(self.votecast_db.getVote(bin2str(self.mypermid),bin2str(self.hispermid)),2)
#print >> sys.stderr, self.votecast_db.getAll()
self.votecast_db.unsubscribe(bin2str(self.myperm... |
shaded-enmity/dnf | dnf/base.py | Python | gpl-2.0 | 72,096 | 0.000222 | # Copyright 2005 Duke University
# Copyright (C) 2012-2015 Red Hat, Inc.
#
# 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 versi... | self._add_repo_to_sack(r.id)
conf = self.conf
self._sack.configure(conf.installonlypkgs, conf | .installonly_limit)
self._setup_excludes_includes()
timer()
self._goal = dnf.goal.Goal(self._sack)
return self._sack
@property
@dnf.util.lazyattr("_yumdb")
def yumdb(self):
db_path = os.path.normpath(self.conf.persistdir + '/yumdb')
return rpmsack.AdditionalP... |
ntt-sic/neutron | neutron/openstack/common/rpc/amqp.py | Python | apache-2.0 | 22,783 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# Copyright 2011 - 2012, Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
... | kombu and impl_qpid. impl_carrot also uses
AMQP, but is deprecated and predates this code.
"""
import collections
import inspect
import sys
import uuid
from eventlet import greenpool
from eventlet import pools
from eventlet import queue
from eventlet import semaphore
from oslo.config import cfg
from neutron.opensta... | rt excutils
from neutron.openstack.common.gettextutils import _
from neutron.openstack.common import local
from neutron.openstack.common import log as logging
from neutron.openstack.common.rpc import common as rpc_common
amqp_opts = [
cfg.BoolOpt('amqp_durable_queues',
default=False,
... |
moocowmoo/pycoin | tests/tools_test.py | Python | mit | 4,283 | 0.004203 | #!/usr/bin/env python
import unittest
from pycoin.serialize import h2b
from pycoin.intbytes import int_to_bytes, bytes_from_ints
from pycoin.tx.script.tools import bin_script, compile, disassemble, int_to_script_bytes, int_from_script_bytes
from pycoin.tx.script.opcodes import OPCODE_LIST
from pycoin.tx.script.vm imp... | (as_bytes):
script = bin_script([as_bytes])
stack = []
eval_script(script, None, | lock_time=0, stack=stack, disallow_long_scripts=False)
assert len(stack) == 1
assert stack[0] == as_bytes
def test_val(n):
as_bytes = int_to_bytes(n)
test_bytes(as_bytes)
for i in range(100):
test_val(100)
for i in range(0xfff0, 0x10... |
Prasad9/incubator-mxnet | python/mxnet/ndarray/ndarray.py | Python | apache-2.0 | 98,461 | 0.001219 | # 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 u... | 1,
'add': 3
}
# pylint: enable= no-member
def _new_empty_handle():
"""Returns a new empty handle.
Empty handle can be used to hold a result.
Returns
-------
handle
A | new empty `NDArray` handle.
"""
hdl = NDArrayHandle()
check_call(_LIB.MXNDArrayCreateNone(ctypes.byref(hdl)))
return hdl
def _new_alloc_handle(shape, ctx, delay_alloc, dtype=mx_real_t):
"""Return a new handle with specified shape and context.
Empty handle is only used to hold results.
R... |
jirivrany/riskflow123d-prep | app/helpers/solver_utils.py | Python | gpl-2.0 | 2,691 | 0.002601 | '''
Created on 20.12.2012
@author: Jiri Vrany
'''
import os
import shutil
import glob
PROBLEMS = {
'basic': 'basicProblem',
'monte': 'MonteCarlo',
'sens': 'Sensitivity'
}
def __normalize_result_stora_poro(value):
'''
this function should not be called from out... |
files = glob.iglob(os.path.join(original_dir, "*.bct_*"))
for fil | e_name in files:
if os.path.isfile(file_name):
shutil.copy2(file_name, output_dir)
if __name__ == '__main__':
print round_porosity('0')
print round_porosity('0.0001')
print round_porosity('0.00001')
print round_porosity('')
|
TaliesinSkye/evennia | src/utils/test_utils.py | Python | bsd-3-clause | 952 | 0.008403 | """
Test runner for Evennia test suite. Run with "game/manage.py test".
"""
from django.conf import settings
from django.test.simple import DjangoTestSuiteRunner
class EvenniaTestSuiteRunner(DjangoTestSuiteRunner):
"""
This test runner only runs tests on the apps specified i | n src/ and game/ to
avoid running the large number of tests defined by Django
"""
def build_suite(self, test_labels, extra_tests=None, **kwargs):
"""
Build a test suite for Evennia. test_labels is a list of apps to test.
If not given, a subset of settings.INSTALLED_APPS will be use... | in settings.INSTALLED_APPS
if (applabel.startswith('src.') or applabel.startswith('game.'))]
return super(EvenniaTestSuiteRunner, self).build_suite(test_labels, extra_tests=extra_tests, **kwargs)
|
arnehilmann/netkraken | src/unittest/python/netkraken_tests.py | Python | apache-2.0 | 1,468 | 0.004768 | from __future__ import print_function
from datetime import datetime
import unittest
from mock import patch
import netkraken
from testhelper import myAssertDictEqual
class NetKrakenTests(unittest.TestCase):
def test_get_timestamp(self):
self.assertEquals(("minute", "2042-12-12T12:12"),
... | stamp("///foo///2042-12-12T12:12"))
self.assertEquals(("day", "2042-12-12"),
| netkraken.get_higher_timestamp("///foo///2042-12-12T12"))
@patch("netkraken.get_current_datetime")
def test_get_current_timestrings(self, now_mock):
now_mock.return_value = datetime(2042, 12, 12, 12, 12)
# self.assertDictEqual({'day': '2042-12-12', 'hour': '2042-12-12T12', 'minute': '20... |
remysaissy/paris-immo-finder | app/scrapers/base_scraper.py | Python | gpl-3.0 | 6,157 | 0.003086 | import logging
import sys
import time
import traceback
from weakref import WeakValueDictionary
import bs4
from selenium import webdriver
from app.services import slack
from app.utils import db
class BaseScraper(object):
""" Abstract class for implementing a datasource. """
_instances = WeakValueDictionary... | if o is None:
continue
if self._is_valid_offer(o, r_offer):
payload = self._prepare_offer_filling(o, r_offer)
o.fill_object(self, r_offer, payload)
self._clean_offer_filling(o, r_offer, payload)
offers.append(o)
els... | id offer detected. Skipping...")
return offers
def _get_offer_object(self, r_offer):
"""
Returns a valid offer object for the offer to parse.
:return A BaseOffer object subclass instance
"""
NotImplementedError("Class {} doesn't implement aMethod()".format(self.__c... |
arunhotra/tensorflow | tensorflow/python/ops/gradients_test.py | Python | apache-2.0 | 12,673 | 0.011521 | """Tests for tensorflow.ops.gradients."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import warnings
import tensorflow.python.platform
import numpy as np
from tensorflow.python.framework import ops
from tensorflow.python.framework import test_util
fr... | self):
with self.test_session():
x = constant( | 1.0)
y = x * 2.0
z = y + y + y + y + y + y + y + y + y + y
grads = gradients.gradients(
z,
[x, y],
aggregation_method=gradients.AggregationMethod.EXPERIMENTAL_TREE)
self.assertTrue(all([x for x in grads]))
self.assertEqual(20.0, grads[0].eval())
self.ass... |
jnmclarty/rrsm | rrsm/__init__.py | Python | mit | 50 | 0.02 | from r | rsm.core import StateMachine, StateT | ypeError |
kmike/port-for | src/port_for/__init__.py | Python | mit | 548 | 0 | # -*- coding: utf-8 -*-
__version__ = "0.6.2"
from ._ranges import UNASSIGNED_RANGES
from .api import (
available_good_ports,
available_ports,
is_available,
good_port_ranges,
port_is_used,
select_random,
get_port,
| )
from .store import PortStore
from .exceptions import PortForException
__all__ = (
"UNASSIGNED_RANGES",
"available_good_p | orts",
"available_ports",
"is_available",
"good_port_ranges",
"port_is_used",
"select_random",
"get_port",
"PortStore",
"PortForException",
)
|
jmbeuken/abinit | scripts/post_processing/ElectronPhononCoupling/ElectronPhononCoupling/interface/__init__.py | Python | gpl-3.0 | 23 | 0 | from | .comput | e import *
|
tedlaz/pyted | pykoin17/numtable.py | Python | gpl-3.0 | 4,379 | 0.000235 | # -*- coding: utf-8 -*-
import decimal
def isNum(value): # Einai to value arithmos, i den einai ?
"""
use: Returns False if value is not a number , True otherwise
input parameters :
1.value : the value to check against.
output: True or False
"""
try:
float(value)
... | ce to fix round problem
if dif == 0:
pass
else:
# Max value Element gets the difference
tmpArr[tmpArr.index(max(tmpArr))] += dif
return tmpArr
def dist_d(val, dist_dic, decimals=2):
dist = {}
sorted_keys = sorted(dist_dic)
tmpdist_list = []
# Create a l... | nd(dist_dic[el])
if sum(tmpdist_list) != 1000:
print("Distribution total is not 1000")
dist_list = distribute(val, tmpdist_list, decimals)
for i, el in enumerate(sorted_keys):
dist[el] = dist_list[i]
return dist
class ntable():
def __init__(self):
self.title = ... |
zwChan/VATEC | ~/eb-virt/Lib/site-packages/werkzeug/useragents.py | Python | apache-2.0 | 5,418 | 0 | # -*- coding: utf-8 -*-
"""
werkzeug.useragents
~~~~~~~~~~~~~~~~~~~
This module provides a helper to inspect user agent strings. This module
is far from complete but should work for most of the currently available
browsers.
:copyright: (c) 2014 by the Werkzeug Team, see AUTHORS for more deta... | self.platforms:
match = regex.search(user_agent)
if match is not None:
break
else:
platform = None
for browser, regex in self.browsers:
match = regex.search(user_agent)
if match is not None:
version = match.group... | break
else:
browser = version = None
match = self._language_re.search(user_agent)
if match is not None:
language = match.group(1) or match.group(2)
else:
language = None
return platform, browser, version, language
class UserAgent(... |
google/jax | tests/lax_autodiff_test.py | Python | apache-2.0 | 51,968 | 0.003964 | # 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 required by applicable law or agreed to in writing, ... | ust, enable second-order
# grad_test_spec(lax.max, nargs=2, order=1, rng_factory=jtu.rand_some_equal,
# dtypes=grad_float_dtypes, name="MaxSomeEqual"),
# grad_test_spec(lax.min, nargs=2, order=1, rng_factory=jtu.rand_some_equal,
# dtypes=grad_float_dtypes, name="MinSomeEqua... | dSpecialValuesTestSpec(op, values, tol)
LAX_GRAD_SPECIAL_VALUE_TESTS = [
grad_special_values_test_spec(
lax.sinh, [0.],
tol={np.float32: 1e-2} if jtu.device_under_test() == "tpu" else None),
grad_special_values_test_spec(
lax.cosh, [0.],
tol={np.float32: 1e-2} if jtu.device_under_test()... |
nylas/sync-engine | inbox/scheduling/queue.py | Python | agpl-3.0 | 6,779 | 0 | """This module contains code for managing Redis-backed account sync allocation.
Structurally, that works like this:
Redis list Redis hash
(acct ids to be (acct ids -> proc ids)
synced) +------... | nager
from inbox.models | .session import session_scope_by_shard_id
from inbox.models import Account
from inbox.util.concurrency import retry_with_logging
from inbox.util.stats import statsd_client
from nylas.logging import get_logger
from redis import StrictRedis
log = get_logger()
SOCKET_CONNECT_TIMEOUT = 5
SOCKET_TIMEOUT = 5
class QueueCl... |
Zsailer/latticeproteins | latticeproteins/sequences.py | Python | gpl-3.0 | 4,953 | 0.002827 | #!/usr/bin/python
# Begin sequences.py
#---------------------------------------------------------------------------
"""
Originally written by Jesse Bloom, 2004.
Updated by Zach Sailer, 2017."""
#---------------------------------------------------------------------------
import random, shelve, os
#---------------------... | mutated = False
for ires in range(len(seq)):
if random.random() < mutrate:
if not mutated:
mutated = True
newseq = list(seq)
newres = random.choice(_residues)
while newres == seq[ires]:
newres = random.choice(_residues)
... | :
return seq
def n_mutants(seq, nmutations, nsequences):
"""Returns sequences with a specified number of mutations.
Parameters
----------
seq :
is a string or list specifying the protein we wish to mutate.
nmutations :
is the number of mutations each mutant of 'seq' should
... |
tysonholub/twilio-python | tests/integration/taskrouter/v1/workspace/worker/test_reservation.py | Python | mit | 9,315 | 0.003972 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class ReservationTestCase(Integ... | {
"task": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaa | aaaaaaaaaaa/Tasks/WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"worker": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"workspace": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaa... |
by46/geek | basic/yield_t.py | Python | mit | 205 | 0.009756 | class Demo(object):
@property
def names(self):
for i in range(10): |
yield i
if __name__ == '__main__':
demo = Demo()
for name | in demo.names:
print(name) |
mlperf/training_results_v0.6 | Google/benchmarks/transformer/implementations/tpu-v3-512-transformer/transformer/layers/modalities_test.py | Python | apache-2.0 | 1,941 | 0.002061 | """Tests for Modalities."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
from layers import common_hparams
from layers import modalities
class ModalityTest(tf.test.TestCase):
def testSymbolModalityInputs(s... | height, 1, vocab_size))
self.assertEqual(res2.shape, ())
if __name__ == "__main__":
tf. | test.main()
|
lizaifang/yubico-yubiserve | yubiserve.py | Python | gpl-3.0 | 18,768 | 0.029039 | #!/usr/bin/env python
import re, os, time, socket, sys, signal
import urlparse, SocketServer, urllib, BaseHTTPServer
from Crypto.Cipher import AES
from OpenSSL import SSL
import hmac, hashlib
from threading import Thread
isThereDatabaseSupport = False
try:
import MySQLdb
isThereDatabaseSupport = True
except ImportEr... | aseSupport = True
except ImportErro | r:
pass
if isThereDatabaseSupport == False:
print "Cannot continue without any database support.\nPlease read README.\n\n"
sys.exit(1)
def parseConfigFile(): # Originally I wrote this function to parse PHP configuration files!
config = open(os.path.dirname(os.path.realpath(__file__)) + '/yubiserve.cfg', 'r').read... |
corywalker/selenium-crawler | seleniumcrawler/filesystem.py | Python | mit | 846 | 0.001182 | # Global modules
import os
# Local modules
from seleniumcrawler.config import sites_dict
THIS_DIR = os.path.dirname(os.path.realpath(__file__))
SITES_DIR = os.path.join(THIS_DIR, 'sites')
def locate_sites():
location_list = []
for site, re | gex in sites_dict.items():
this_site_dir = os.path.join(SITES_DIR, site)
# This is only the EXPECTED script name.
# All scripts should follow this convention.
script_name = site + '_raw.py'
script_path = os.path.join(this_site_dir, script_name)
config_path = os.path.join(... | 'site_dir': this_site_dir
}
location_list.append(location_dict)
return location_list
|
suttond/MODOI | ase/ga/population.py | Python | lgpl-3.0 | 15,749 | 0.001016 | """ Implementaiton of a population for maintaining a GA population and
proposing structures to pair. """
from random import randrange, random
from math import tanh, sqrt, exp
from operator import itemgetter
import numpy as np
from ase.db.core import now
def count_looks_like(a, all_cand, comp):
"""Utility method ... | e
abovementioned paper due to maximizing raw_score instead of
minimizing energy. (Set raw_score=-energy to optimize the energy)
"""
scores = [x.get_raw_score() for x in self.pop]
min_s = | min(scores)
max_s = max(scores)
T = min_s - max_s
if isinstance(indecies, int):
indecies = [indecies]
f = [0.5 * (1. - tanh(2. * (scores[i] - max_s) / T - 1.))
for i in indecies]
if with_history:
M = [float(self.pop[i].info['n_paired']) for ... |
saleemjaveds/https-github.com-openstack-nova | nova/tests/api/openstack/compute/contrib/test_admin_actions.py | Python | apache-2.0 | 25,222 | 0.000079 | # Copyright 2011 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | te_api, method)(self.context, instance)
self.mox.ReplayAll()
res = self._make_request('/servers/%s/action' % instance['uuid'],
| {action: None})
self.assertEqual(202, res.status_int)
# Do these here instead of tearDown because this method is called
# more than once for the same test case
self.mox.VerifyAll()
self.mox.UnsetStubs()
def _test_invalid_state(self, action, method=None, body_map=Non... |
bigbangdev/cityhelpdeskdjango | cityhelpdesk/utility/serializers.py | Python | gpl-3.0 | 333 | 0 | # coding=utf-8
"""
Utility Serializers
"""
from rest_framework.serializer | s import HyperlinkedModelSerializer
class HybridModelSerializer(HyperlinkedModelSerializer):
"""
ModelSerializer which provides both a `url` and `id` field
"""
def get_pk_field(self, model_field) | :
return self.get_field(model_field)
|
daniel-noland/config | root/home/dnoland/.bin/gdb.py | Python | mit | 214 | 0 | #!/ | usr/bin/gdb --eval-command=python
# vim: set filetype=python:
import sys
import gdb
gdb.execute("file " + sys.argv[1])
t = gdb.Type(sys.argv[0])
print("sizeof " + str(sys.argv[0]) + " = " + str(t.sizeof()) | )
end
|
fbradyirl/home-assistant | tests/components/demo/test_calendar.py | Python | apache-2.0 | 49 | 0 | """The | tests for the demo | calendar component."""
|
absoludity/django-financial-transactions | financial_transactions/tests/test_models.py | Python | bsd-3-clause | 664 | 0 | import datetime
from decimal import Decimal
from django_factory import TestCase
from financial_transactions.models import (
Transaction,
)
class TransactionTestCase(TestCase):
def tes | t_unicode(self):
trans = self.factory.make_one(
Transaction, memo=u'S | ublime purchase',
date=datetime.date(2013, 2, 5), amount=Decimal('59.95'),
currency=u'EUR')
self.assertEqual(u'2013-02-05 59.95 EUR - Sublime purchase',
unicode(trans))
def test_factory_makes_category(self):
transaction = self.factory.make_one(Trans... |
bally12345/enigma2 | lib/python/Plugins/SystemPlugins/Videomode/VideoWizard.py | Python | gpl-2.0 | 5,933 | 0.034384 | from Screens.Wizard import WizardSummary
from Screens.WizardLanguage import WizardLanguage
from Screens.Rc import Rc
from VideoHardware import video_hw
from Components.Pixmap import Pixmap, MovingPixmap, MultiPixmap
from Components.config import config, ConfigBoolean, configfile
from Tools.Directories import resolveF... | = self.port, mode = mode, rate = ratesList[0][0])
def listRates(self, querymode = None):
if querymode is None:
querymode = self.mode
list = []
print "modes for port", self.port, "and mode", querymode
for mode in self.hw.getModeList(self.port):
print mode
if mode[0] == querymode:
for rate in mode[... | te, rate))
continue
list.append((rate, rate))
return list
def rateSelectionMade(self, index):
print "rateSelectionMade:", index
self.rate = index
self.rateSelect(index)
def rateSelectionMoved(self):
print "rate selection moved:", self.selection
self.rateSelect(self.selection)
def rateSelec... |
linostar/timeline-clone | test/specs/plugin/PluginFactory.py | Python | gpl-3.0 | 1,487 | 0.002017 | # Copyright (C) 2009, 2010, 2011 Rickard Lindberg, Roger Lindberg
#
# This file is part of Timeline.
#
# Timeline 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... | ER, "Gradient Event box drawer")
self.assertEquals(_("Gradient Event box drawer"), plugin.display_name())
def test_returns_none_when_named_plugin_cant_be_foun | d(self):
plugin = factory.get_plugin(EVENTBOX_DRAWER, "xyz drawer")
self.assertEquals(None, plugin)
|
Samuel-Phillips/pv-viability-map | import_tool.py | Python | gpl-3.0 | 4,857 | 0.001235 | import tempfile
import traceback
import shutil
import os.path
import os
from zipfile import ZipFile
from contextlib import contextmanager
import shapefile
import interface
import pyproj
from osgeo import osr
import log
## Web Mercator (Not used for interaction)
#leaflet_proj = pyproj.Proj(
# '+proj=merc +lon_0=0 +k... | ve a .save method) into the interface.Rooftops object db. Raises
import_tool.error with messages relating to the error encountered."""
log.note("Importing a shapefile")
with tempdir() as root:
zip_name = os.path.join(root, "map.zip")
sf_dir = os.path.join(root, "shapes")
saveable.sa... | raise error("Error while opening the uploaded file. Make sure "
"it is in zip format.")
sf_names = set(
name[:-4] for name in os.listdir(sf_dir) if name.endswith(
'.shp') or name.endswith('.shx') or name.endswith('.dbf'))
if len(sf_names) == 0:
... |
glassalle/Rad4Snps | RAD4SNPs_Main.py | Python | gpl-3.0 | 12,997 | 0.015465 | #!/usr/bin/python
########################################################################## RAD4SNPs:##############################################################################
# A set of Python scripts to select and validate independent SNPs markers from a list of read files #
#################################... |
else :
print "Please insert path for working directory [-i]. End of program."
sys.exit()
############################## | ################################################
if results.database:
db = MySQLdb.connect(host="", # your host, usually localhost
user="", # your username
passwd="", # your password
db=results.database) ... |
devs1991/test_edx_docmode | venv/lib/python2.7/site-packages/sympy/core/assumptions.py | Python | agpl-3.0 | 12,183 | 0.003119 | from facts import FactRules
from sympy.core.compatibility import cmp
class CycleDetected(Exception):
"""(internal) used to detect cycles when evaluating assumptions
through prerequisites
"""
pass
class AssumeMeths(object):
""" Define default assumption methods.
AssumeMeths should be used... | from the set
of integers
- bounded - object absolute value is bounded
- positive - object can have only positive values
- negative - object can have only negative values
- nonpositive - object can have only nonpositive values
- nonn... | ect.
- irrational - object value cannot be represented exactly by Rational
- unbounded - object value is arbitrarily large
- infinitesimal - object value is infinitesimal
Example rules:
positive=T -> nonpositive=F, real=T
real=T & positive=F -> nonpositiv... |
sshuttle/sshuttle | sshuttle/ssyslog.py | Python | lgpl-2.1 | 588 | 0 | import sys
im | port os
import subprocess as ssubprocess
_p = None
def start_syslog():
global _p
with open(os.devnull, 'w') as devnull:
_p = ssubprocess.Popen(
['logger', '-p', 'daemon.notice', '-t', 'sshuttle'],
stdin=ssubprocess.PIPE,
| stdout=devnull,
stderr=devnull
)
def close_stdin():
sys.stdin.close()
def stdout_to_syslog():
sys.stdout.flush()
os.dup2(_p.stdin.fileno(), sys.stdout.fileno())
def stderr_to_syslog():
sys.stderr.flush()
os.dup2(_p.stdin.fileno(), sys.stderr.fileno())
|
ratilicus/sdtd | dev/sdtd-eac.py | Python | apache-2.0 | 2,696 | 0.002967 | #!/usr/bin/python
import time
import telnetlib
import re
line_pat = re.compile(r'\d+\. (?P<username>[^,]*), id=(?P<id>\d+), steamid=(?P<steamid>\d+), online=(?P<online>True|False), ip=[\d.]*, playtime=(?P<playtime>\d+).*')
slot_pat = re.compile(r'Slot \d+: (\d{3}) * (.*)')
ban_pat = re.compile(r'^ \d{2}/\d{2}/... | . skipping' % p['steamid']
continue
print | 'scanning', p
suspect = False
items = []
telnet.write('si %s\n' % p['steamid'])
ct = 0
while ct < 3:
line = telnet.read_until('\n', 0.25)
if not line:
time.sleep(0.1)
ct+=1
else:
result = slot_pa... |
vertigo235/Sick-Beard-XEM | sickbeard/providers/generic.py | Python | gpl-3.0 | 15,171 | 0.004482 | # Author: Nic Wolfe <[email protected]>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of Sick Beard.
#
# Sick Beard 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 t... | e saved file to see if it was actually valid, if not then consider the download a failure.
"""
# primitive verification of torrents, just make sure we didn't get a text file or something
if self.providerType == GenericProvider.TORR | ENT:
parser = createParser(file_name)
if parser:
mime_type = parser._getMimeType()
try:
parser.stream._input.close()
except:
pass
if mime_type != 'application/x-bittorrent':
... |
flexo/evolutron | evolutron/food.py | Python | mit | 1,376 | 0.00218 |
import pygame
from pygame.locals import *
class Food(pygame.sprite.Sprite):
def __init__(self, tile, x, y):
super(Food, self).__init__()
self.tile = tile
self.energy = 1000
w = self.w = 9
h = self.h = 5
self.image = pygame.Surface((w, h), SRCALPHA).convert_alpha()... | ect(3, 2, 3, 3), 0)
pygame.draw.ellipse(self.image, (128, 128, 0), Rect(0, 0, 9, 5), 0)
if self.tile.world.active_item is self:
pygame.draw.lines(self.image, (0, 0, 255), 1, [
| (0, 0), (self.w - 1, 0), (self.w - 1, self.h - 1), (0, self.h - 1)
], 3)
self.redraw = False
def __str__(self):
return "Food at {},{}".format(self.rect.x, self.rect.y)
def __repr__(self):
return "<Food at {},{}>".format(self.rect.x, self.rect.y)
|
richm/designate | designate/api/v2/__init__.py | Python | apache-2.0 | 1,327 | 0 | # Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# Author: Kiall Mac Innes <[email protected]>
#
# 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/L... | the specific language governing permissions and limitations
# under the License.
from designate.api.v2 import patches # flake8: noqa
import pecan.deploy
from oslo.config import cfg
from designate.openstack.common import log as logging
LOG = logging.getLogger(__name__)
def factory(global_config, | **local_conf):
if not cfg.CONF['service:api'].enable_api_v2:
def disabled_app(environ, start_response):
status = '404 Not Found'
start_response(status, [])
return []
return disabled_app
conf = {
'app': {
'root': 'designate.api.v2.control... |
sidharta/hansel-app | main/auth/google.py | Python | mit | 1,359 | 0 | # coding: utf-8
# pylint: disable=missing-docstring, invalid-name
from __future__ import absolute_import
from google.appengine.api import users
import flask
import auth
import model
import util
from main import app
@app.route('/signin/google/')
def signin_google():
auth.save_request_params()
google_url = ... | )
user_db = retrieve_user_from_google(google_user)
return auth.signin_via_social(user_db)
def retrieve_user_from_google(google_user):
auth_id = 'federated_%s' % google_user.user_id()
user_db = model.User.get_by('auth_ids', auth_id)
if user_db:
if not user_db.admin | and users.is_current_user_admin():
user_db.admin = True
user_db.put()
return user_db
return auth.create_or_get_user_db(
auth_id=auth_id,
name=util.create_name_from_email(google_user.email()),
username=google_user.email(),
email=google_user.email(),
... |
JioCloud/oslo-incubator | openstack/common/lockutils.py | Python | apache-2.0 | 9,378 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack Foundation.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apac... | tomatically if the process crashes, even if __exit__ is not executed.
There are no guarantees regarding usage by multiple green threads in a
single process here. This lock works only between processes. Exclusive
access between local threads should be achieved using the semaphores
in the @synchronized d... | eased when the descriptor is closed, so it's not
safe to close the file descriptor while another green thread holds the
lock. Just opening and closing the lock file can break synchronisation,
so lock files must be accessed only using this abstraction.
"""
def __init__(self, name):
self.lock... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.