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 |
|---|---|---|---|---|---|---|---|---|
knappador/kivy-netcheck | src/netcheck/mockconn.py | Python | mit | 1,385 | 0.005054 | from kivy.logger import Logger
''' Mock for checking the connection. Set success to test '''
class Netcheck():
def __init__(self, prompt=None):
if prompt is None:
prompt = self._no_prompt
self._prompt = prompt
self.MOCK_RESULT=False
self.MOCK_SETTINGS_RESULT=True
... | ogger.info('in ask connect callback ' + str(try_connect))
if try_connect:
self._settings_callback()
else:
self._callback(False)
def _settings_callback(self):
#self.MOCK_RESULT=self.MOCK_SETTINGS_RESULT
self._callback(self.MOCK_SETTINGS_RESULT)
de... | lf, k, kwargs[k])
|
EduPepperPDTesting/pepper2013-testing | lms/lib/comment_client/comment_client.py | Python | agpl-3.0 | 1,852 | 0.00486 | # Import other classes here so they can be | imported from here.
# pylint: disable=W0611
from .comment import Comment
from .thread import Thread
from .user import User
from | .commentable import Commentable
from .utils import perform_request
import settings
def search_similar_threads(course_id, recursive=False, query_params={}, *args, **kwargs):
default_params = {'course_id': course_id, 'recursive': recursive}
attributes = dict(default_params.items() + query_params.items())
r... |
pymedusa/Medusa | tests/test_should_process.py | Python | gpl-3.0 | 2,950 | 0.000339 | # coding=utf-8
"""Tests for medusa/test_should_process.py."""
from __future__ import unicode_literals
from medusa.common import Quality
from medusa.post_processor import PostProcessor
import pytest
@pytest.mark.parametrize('p', [
{ # p0: New allowed quality higher than current allowed: yes
'cur_quality'... | .NA,
'new_quality': Quality.HDTV,
'allowed_qualities': [ | Quality.HDWEBDL],
'preferred_qualities': [Quality.HDTV],
'expected': True
},
])
def test_should_process(p):
"""Run the test."""
# Given
current_quality = p['cur_quality']
new_quality = p['new_quality']
allowed_qualities = p['allowed_qualities']
preferred_qualities = p['prefer... |
googleads/google-ads-python | google/ads/googleads/v9/services/services/campaign_bid_modifier_service/transports/__init__.py | Python | apache-2.0 | 1,099 | 0 | # -*- 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 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.
#
from collections import OrderedDict
from typing import Dict, Type
from .base import Campaig... |
imjonsnooow/vivisect | vivisect/qt/remote.py | Python | apache-2.0 | 7,037 | 0.005684 | from PyQt4 import Qt, QtCore, QtGui
import vqt.main as vq_main
import vqt.tree as vq_tree
import envi.threads as e_threads
import cobra.remoteapp as c_remoteapp
import vivisect.remote.server as viv_server
from vqt.basics import *
class WorkspaceListModel(vq_tree.VQTreeModel):
columns = ('Name',)
class Workspac... | =self)
self.setdef = QtGui.QCheckBox(parent=self)
self.buttons = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel)
self.buttons.accepted.connect( self.accept )
self.buttons.rejected.connect( self.reject )
serverlayout = QtGui.QHBoxLayout()
... | rlayout.addWidget(QtGui.QLabel('Make Default:'))
serverlayout.addWidget(self.setdef)
layout = QtGui.QFormLayout()
layout.addRow('Workspace Server', serverlayout)
layout.addWidget(self.buttons)
self.setLayout(layout)
def getServer(self):
if not self.exec_():
... |
zhuzhidong/StaticAnalysisforCI | script/klocwork/__init__.py | Python | mit | 74 | 0 | #!/usr/bin | /env python3
# -*- c | oding: utf-8 -*-
__author__ = "zhuzhidong"
|
Bauble/bauble.api | test/spec/test_user.py | Python | bsd-3-clause | 1,763 | 0.002269 | #import pytest
#import sys
import test.api as api
#import bauble.db as db
from bauble.model.user import User
def xtest_user_json(session):
username = 'test_user_json'
password = username
users = session.query(User).filter_by(username=username)
for user in users:
session.delete(user)
ses... | ce(first_family['ref'])
# query for families
response_json = api.query_resource('/family', q=second_family['family'])
second_family = response_json[0] # we're assuming there's only one
assert second_family['ref'] == second_ref
# delete the created resources
api.delete_resource(first_family['re... | api.delete_resource(second_family['ref'])
def test_password(session):
username = api.get_random_name()
email = username + '@bauble.io'
password = api.get_random_name()
user = User(email=email, username=username, password=password)
session.add(user)
session.commit()
# test the password... |
juniwang/open-hackathon | open-hackathon-client/src/client/config_docker.py | Python | mit | 7,716 | 0.001426 | # -*- coding: utf-8 -*-
"""
This file is covered by the LICENSING file in the root of this project.
"""
import os
# "javascript" section for javascript. see @app.route('/config.js') in app/views.py
# NOTE: all following key/secrets for test purpose.
ENDPOINT_WEB = os.getenv("ENDPOINT_WEB", "http://localhost") # host ... | t"],
"checkemail": ["get"],
"list": ["get"]
},
"profile": {
"": ["post", "put"]
},
"picture": {
"": ["put"]
},
... | "like": ["get", "post", "delete"]
},
"notice": {
"read": ["put"]
},
"show": {
"list": ["get"]
},
"file": {
"... |
5nizza/party-elli | helpers/main_helper.py | Python | mit | 2,935 | 0.007155 | import logging
import os
import sys
from typing import List
from logging import FileHandler
from synthesis.z3_via_files import Z3NonInteractiveViaFiles, FakeSolver
from synthesis.z3_via_pipe import Z3InteractiveViaPipes
from third_party.ansistrm import ColorizingStreamHandler
from interfaces.solver_interface import Sol... | r(formatter)
stdout_handler.stream = sys.stdout
if not filename:
filename = 'last.log'
file_handler = FileHandler(filename=filename, mode='w')
file_handler.setFormatter(formatter)
root = logging.getLogger()
root.addHandler(stdout_handler)
root.addHandler(file_handler)
root.set... | 3_path:str,
is_incremental:bool,
generate_queries_only:bool,
remove_files:bool):
self.smt_tmp_files_prefix = smt_tmp_files_prefix
self.z3_path = z3_path
self.is_incremental = is_incremental
self.generate_queries = generate_queries_only
... |
franklingu/leetcode-solutions | questions/partition-array-into-disjoint-intervals/Solution.py | Python | mit | 1,320 | 0.003788 | """
Given an array nums, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a part... | mx, ms = [], []
for n in A:
if not mx:
mx.append(n)
else:
mx.append(max(mx[-1], n))
for n in reve | rsed(A):
if not ms:
ms.append(n)
else:
ms.append(min(ms[-1], n))
ms = list(reversed(ms))
for i, n in enumerate(mx):
if i >= len(A) - 1:
continue
n2 = ms[i + 1]
if n2 >= n:
return i... |
haoliangyu/basic-data-structure | Heap.py | Python | mit | 3,852 | 0.001298 | class Heap(object):
def __init__(self, data=[]):
if len(data) == 0:
self.data = [None] * 100
else:
self.data = data
self.__size = sum([1 if item is not None else 0 for item in self.data])
self.__heapify()
def size(self):
return self.__size
... | ential_parent
potential_parent = self.__proper_parent(current_index)
self.data[current_index] = initial_value
return current_index
def __percolate_up(self, i):
if not self.__has_parent(i):
return | 0
initial_value = self.data[i]
parent_indexes = []
h = 1
current_index = i
while self.__has_parent(current_index):
current_index = ((i + 1) >> h) - 1
parent_indexes.append(current_index)
h += 1
lo = 0
hi = len(parent_indexes... |
GovReady/govready-q | controls/migrations/0003_auto_20200417_1418.py | Python | gpl-3.0 | 598 | 0.001672 | # Generated by Django 2.2.12 on 2020-04-17 14:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('controls', '0002_commoncontrol_common_control_provider'),
]
operations = [
migrations.RemoveField(
model_name='commoncontrol',
... | name='legacy_imp_stm',
field=models.TextField(blank=True, help_text='Legacy large implementation statement', null=True),
),
]
| |
wetneb/dissemin | deposit/osf/migrations/0001_initial.py | Python | agpl-3.0 | 1,150 | 0.003478 | # -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2017-08-28 11:43
fr | om django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial | = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('deposit', '0010_email_on_preferences'),
]
operations = [
migrations.CreateModel(
name='OSFDepositPreferences',
fields=[
('id', models.AutoField(auto_created=... |
tkupek/tkupek-elearning | tkupek_elearning/elearning/migrations/0001_initial.py | Python | gpl-3.0 | 1,728 | 0.001736 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-01-31 17:13
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration | ):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Option',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('text', models.CharField(max_length=1... | fields=[
('id', models.AutoField(primary_key=True, serialize=False)),
('title', models.CharField(max_length=100, null=True)),
('text', models.TextField(null=True)),
('explanation', models.TextField(null=True)),
],
),
migrations.... |
dcramer/logan | tests/logan/settings/tests.py | Python | apache-2.0 | 1,921 | 0.001562 | from unittest import TestCase
import mock
from logan.settings import add_settings
class Ad | dSettingsTestCase(TestCase):
def test_does_add_settings(self):
class NewSettings(object):
FOO = 'bar'
BAR = 'baz'
settings = mock.Mock()
new_settings = NewSettings()
add_settings(new_settings, settings=settings)
self.assertEquals(getattr(settings, 'FO... | ss NewSettings(object):
EXTRA_FOO = ('lulz',)
settings = mock.Mock()
settings.FOO = ('foo', 'bar')
new_settings = NewSettings()
add_settings(new_settings, settings=settings)
self.assertFalse(settings.EXTRA_FOO.called)
def test_extra_settings_work_on_tuple(self):... |
mbauskar/tele-frappe | frappe/utils/verified_command.py | Python | mit | 2,109 | 0.02276 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import hmac
import urllib
from frappe import _
import frappe
import frappe.utils
def get_signed_params(params):
"""Sign a url by appending `&_signature=xxxxx` to given params (... | not isinstance(params, basestring):
params = urllib.urlencode(params)
signature = hmac.new(params)
signature.update(get_secret())
return params + "&_signature=" + signature.hexdigest()
def get_secret():
return frappe.local.conf.get("secret") or str(frappe.db.get_value("User", "Adminis | trator", "creation"))
def verify_request():
"""Verify if the incoming signed request if it is correct."""
query_string = frappe.request.query_string if hasattr(frappe.request, "query_string") \
else frappe.local.flags.signed_query_string
params, signature = query_string.split("&_signature=")
given_signature = ... |
AmandaCMS/amanda-cms | amanda/offer/models.py | Python | mit | 325 | 0.003077 | fro | m django.db import models
class Offer(models.Model):
"""
Describes an offer/advertisement
"""
image = models.URLField()
button_text = models.CharField(max_length=32, null=True, blank=True, help_text="Call to action/Button Text")
url = models.UR | LField(help_text="Destination url for this offer")
|
veselosky/schemazoid | schemazoid/__init__.py | Python | apache-2.0 | 221 | 0 | """
schemazoid package
"""
# This file should NEVER impor | t anything (unless it is from the standard
# librar | y). It MUST remain importable by setup.py before any requirements
# have been installed.
__version__ = '0.1.0'
|
OSgroup-wwzz/DFS | sync.py | Python | mit | 2,802 | 0.00571 | import os
import subprocess
import json
from multiprocessing import Process,Lock
"""
Upload and download, API handling services provided by rclone.org
VERY IMPORTANT:
it reads config from a JSON file: config.json
drawback: no exception catching
Example:
from:**here**:/home/exampleuser/examplerfolder
to:**there**... | if status < 0:
print(f"Copy process terminated abnormally(status {status})")
return 0
else:
print(f"Copy from {copytask.frompath}/{copytask.filename} to {copytask.topath}/{copytask.filename} comple | ted successfully")
return 1
"""
Concurrently manage copy processes which run in parallel
Remove it?
"""
def batch_copy(file_list):
count = 0
count_lock = Lock()
# alive indicates if any process is alive
alive = False
proc_list = [None] * config["MAX_PROCESSES"]
while count < len(file_... |
rew4332/tensorflow | tensorflow/contrib/layers/python/layers/feature_column_ops_test.py | Python | apache-2.0 | 66,277 | 0.00433 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | 25],
indices=[[0, | 0], [1, 0], [1, 1]],
shape=[2, 2])
features = {"wire": wire_tensor}
output = feature_column_ops._Transformer(features).transform(hashed_sparse)
with self.test_session():
self.assertEqual(output.values.dtype, tf.int32)
self.assertTrue(all(x < 10 and x >= 0 for x... |
baby-factory/baby-ai | main.py | Python | mit | 3,197 | 0.034696 | # encoding: utf-8
#这里放置主程序以及IO
from numpy import *
from utils.tools import loadvoc
from keras.models import Sequential,load_model,Model
from keras.layers import Input, Embedding, LSTM, Dense, merge, RepeatVector,TimeDistributed,Masking
from keras.optimizers import SGD,Adam
from keras.utils.np_utils import to_categorica... | 定义主模型
#输入层 |
main_input = Input(shape=(SEN,), dtype='int32', name='main_input')
#文字矢量化层
x = Masking(mask_value=0)(main_input)
x = Embedding(output_dim=VOC, input_dim=VOC, input_length=SEN)(x)
#长短记忆层
lstm_out = LSTM(128)(x)
#生物钟,当前时间信息输入[hr,min]
time_input = Input(shape=(2,), name='time_input')
#生物钟激活函数
time_out = Dense(128, activ... |
minhphung171093/GreenERP_V9 | openerp/addons/base/__openerp__.py | Python | gpl-3.0 | 2,841 | 0.000352 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Base',
'version': '1.3',
'category': 'Hidden',
'description': """
The kernel of OpenERP, needed for all installation.
===================================================
""",
'author': 'Op... | a.xml',
'res/ir_property_view.xml',
'res/res_security.xml',
'security/ir.model.access.csv',
],
'demo': [
'base_demo.xml',
'res/res_currency_demo.xml',
'res/res_bank_demo.xml',
'res/res_partner_demo.xml',
'res/res_partner_demo.yml',
'res/res... | rules.
],
'installable': True,
'auto_install': True,
'post_init_hook': 'post_init',
}
|
wegamekinglc/Finance-Python | PyFin/Math/Distributions/__init__.py | Python | mit | 429 | 0.002331 | # -*- coding: utf-8 -*-
u"""
Created on 2015-7-23
@author: cheng.li
"""
from PyFin.Math.Distributions.No | rmalDistribution import NormalDistribution
from PyFin.Math.Distributions.NormalDistribution import CumulativeNormalDistribution
from PyFin.Math.Distributions.NormalDistribution import InverseCumulativeNormal
__all__ = ['NormalDistribution',
| 'CumulativeNormalDistribution',
'InverseCumulativeNormal']
|
ckuehnel/pycom | blink.py | Python | gpl-3.0 | 701 | 0.018545 | #Hello World from pycom LoPy
import machine, pycom, time, sys, uos
pycom.heartbeat(False)
|
print("")
print("Hello World from pycom LoPy")
print("Running Python %s on %s" %(sys.version, uos.uname() [4]))
print("CPU clock = %d MHz" %(int(machine.freq()[0]/1000/1000)))
print("On-board RGB LED will bl | ink 10 times")
def blink():
pycom.rgbled(0x007f00) # green
time.sleep(0.15)
pycom.rgbled(0x7f7f00) # yellow
time.sleep(0.15)
pycom.rgbled(0x7f0000) # red
time.sleep(0.15)
pycom.rgbled(0) # off
time.sleep(.55)
return
for x in range(0, 10):
print("... |
iamweilee/pylearn | pickle-example-1.py | Python | mit | 509 | 0.003929 | '''
pickle Ä£¿éͬ marshal Ä£¿éÏàͬ, ½«Êý¾ÝÁ¬Ðø»¯, ±ãÓÚ±£´æ´«Êä.
Ëü±È marshal ÒªÂýһЩ, µ«Ëü¿ÉÒÔ´¦ÀíÀàʵÀý, ¹²ÏíµÄÔªËØ, ÒÔ¼°µÝ¹éÊý¾Ý½á¹¹µÈ.
'''
imp | ort pickle
value = (
"this is a string",
[1, 2, 3, 4],
("more tuples", 1.0, 2.3, 4.5),
"this is yet another string"
)
data = pickle.dumps(value)
# intermediate format
print type(data), len(data)
print "-"*50
print data
print "-"*50
print p | ickle.loads(data)
'''
²»¹ýÁíÒ»·½Ãæ, pickle ²»ÄÜ´¦Àí code ¶ÔÏó(¿ÉÒÔ²ÎÔÄ copy_reg Ä£¿éÀ´Íê³ÉÕâ¸ö).
''' |
antoinecarme/pyaf | tests/perf/test_long_cycles_nbrows_cycle_length_1000_440.py | Python | bsd-3-clause | 88 | 0.022727 | import tests.perf.test_c | ycles_full_long_long as gen
gen. | test_nbrows_cycle(1000 , 440)
|
code-google-com/cortex-vfx | test/IECoreHoudini/ToHoudiniCurvesConverter.py | Python | bsd-3-clause | 45,988 | 0.070888 | ##########################################################################
#
# Copyright (c) 2010-2013, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redis... | tion, v3iData )
curves["stringDetail"] = IECore.PrimitiveVariable( detailInterpolation, stringData )
# a | dd all valid point attrib types
if not periodic and basis == IECore.CubicBasisf.bSpline() :
modPData = IECore.V3fVectorData()
modPData.setInterpretation( IECore.GeometricData.Interpretation.Point )
floatPointData = IECore.FloatVectorData()
v2fPointData = IECore.V2fVectorData()
v3fPointData = IECore... |
hal0x2328/neo-python | neo/Core/UInt256.py | Python | mit | 688 | 0.002907 | from neo.Core.UIntBase import UIntBase
class UInt256(UIntBase):
def __init__(self, data=None):
super(UInt256, self).__init__(num_bytes=32, data=data)
@staticmethod
def ParseString(value):
"""
Parse the input str `value` into UInt256
Raises:
ValueError: if the ... | reversed_data = bytearray.fromh | ex(value)
reversed_data.reverse()
return UInt256(data=reversed_data)
|
olivierfriard/BORIS | boris/behavior_binary_table.py | Python | gpl-3.0 | 12,397 | 0.004195 | """
BORIS
Behavioral Observation Research Interactive Software
Copyright 2012-2022 Olivier Friard
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 ... | rs=["time"] + [x[0] for x in sorted(behav_modif_set)])
if subject == NO_FOCAL_SUBJECT:
sel_subject_dict = {"": {SUBJECT_NAME: ""}}
else:
sel_subject_dict = dict([
(idx, pj[SUBJECTS][idx]) for idx in pj[SUBJECTS] if pj[SUBJECTS][idx][SUBJECT_NA... | row_idx = 0
t = start_time
while t <= end_time:
# state events
current_states = utilities.get_current_states_modifiers_by_subject_2(
state_behavior_codes, pj[OBSERVATIONS][obs_id][EVENTS], sel_subject_dict, t)
# point even... |
umutgultepe/spoff | yahoo/oauth.py | Python | gpl-3.0 | 7,530 | 0.008499 | """
Yahoo! Python SDK
* Yahoo! Query Language
* Yahoo! Social API
Find documentation and support on Yahoo! Developer Network: http://developer.yahoo.com
Hosted on GitHub: http://github.com/yahoo/yos-social-python/tree/master
@copyright: Copyrights for code authored by Yahoo! Inc. is licensed under the following t... | yahoo_guid = params['xoauth_yahoo_guid'][0]
return AccessToken(key, secret, expires_in, session_handle, authorization_expires_in, yahoo_guid)
from_string = st | aticmethod(from_string)
class Client(oauthlib.oauth.OAuthClient):
def __init__(self, server='https://api.login.yahoo.com/', port=httplib.HTTPS_PORT, request_token_url=REQUEST_TOKEN_API_URL, access_token_url=ACCESS_TOKEN_API_URL, authorization_url=AUTHORIZATION_API_URL):
urlData = urlparse.urlparse(server)
... |
000paradox000/django-dead-base | dead_base/forms/__init__.py | Python | gpl-3.0 | 62 | 0.016129 | from baseform import *
from export_json_data_to | _excel import * | |
bthirion/nistats | nistats/contrasts.py | Python | bsd-3-clause | 9,609 | 0.000208 | """
This module is for contrast computation and operation on contrast to
obtain fixed effect results.
Author: Bertrand Thirion, Martin Perez-Guevara, 2016
"""
from warnings import warn
import numpy as np
import scipy.stats as sps
from .utils import z_score
DEF_TINY = 1e-50
DEF_DOFMAX = 1e10
def compute_contrast... | st (effects, variance, p-values) |
"""
con_val = np.asarray(con_val)
dim = 1
if con_val.ndim > 1:
dim = con_val.shape[0]
if contrast_type is None:
contrast_type = 't' if dim == 1 else 'F'
acceptable_contrast_types = ['t', 'F']
if contrast_type not in acceptable_contrast_types:
raise ValueError(
... |
DK-Git/script.mdm166a | resources/lib/charset_map_hd44780_a00.py | Python | gpl-2.0 | 13,625 | 0.016 | '''
XBMC LCDproc addon
Copyright (C) 2012 Team XBMC
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 v... |
0x00a0: 0x00ff, # NO-BREAK SPACE
0x00a1: 0x0021, # INVERTED EXCLAMATION MARK
0x00a2: 0x0020, # CENT | SIGN
0x00a3: 0x0020, # POUND SIGN
0x00a4: 0x0020, # CURRENCY SIGN
0x00a5: 0x005c, # YEN SIGN
0x00a6: 0x007c, # BROKEN BAR
0x00a7: 0x0020, # SECTION SIGN
0x00a8: 0x0022, # DIAERESIS
0x00a9: 0x0020, # COPYRIGHT SIGN
0x00aa: 0x0020, # FEMININE ORDINAL INDICA... |
bioinform/somaticseq | somaticseq/utilities/dockered_pipelines/somatic_mutations/VarDict.py | Python | bsd-2-clause | 11,186 | 0.024406 | import sys, argparse, os, re
import subprocess
from datetime import datetime
import somaticseq.utilities.dockered_pipelines.container_option as container
from somaticseq._version import __version__ as VERSION
ts = re.sub(r'[:-]', '.', datetime.now().isoformat() )
DEFAULT_PARAMS = {'vardict_image' : 'lethal... | tal_bases = total_bases + int(item[2]) - int(item[1])
num_lines += 1
line_i = bed.readline().rstrip()
else:
fai_file = input_parameters[' | genome_reference'] + '.fai'
bed_file = os.path.join(input_parameters['output_directory'], 'genome.bed')
with open(fai_file) as fai, open(bed_file, 'w') as wgs_bed:
for line_i in fai:
item = line_i.split('\t')
total_ba... |
DarthMaulware/EquationGroupLeaks | Leak #5 - Lost In Translation/windows/Resources/Ops/PyScripts/lib/ops/cmd/audit.py | Python | unlicense | 3,639 | 0.001924 |
import ops
import ops.cmd
import ops.env
import ops.cmd.safetychecks
OpsCommandException = ops.cmd.OpsCommandException
VALID_OPTIONS = ['status', 'on', 'off', 'disable', 'force']
class AuditCommand(ops.cmd.DszCommand, ):
optgroups = {'main': ['status', 'on', 'off', 'disable']}
reqgroups = ['main']
reqopts... | end('Altering audit policy in a script is not safe, verify you really want to do that')
msg = ''
if (len(msgparts) > 0):
msg = msgparts[0]
for msgpart in msgparts[1:]:
msg += ('\n\t' + msgpart)
return (good, msg)
ops.cmd.command_classes['aud | it'] = AuditCommand
ops.cmd.aliasoptions['audit'] = VALID_OPTIONS
ops.cmd.safetychecks.addSafetyHandler('audit', 'ops.cmd.audit.mySafetyCheck') |
tuaminx/ping_server | send_alert.py | Python | apache-2.0 | 732 | 0 | import subprocess
from threading import Timer
def send_alert(message, log=None):
""" This function is used by ping_server.py to send alert
Do NOT change this function name.
:param message: Mess to be sent out
:param log: logger object passed from ping_server.py
:return: None
"""
try:
... | ERT ALERT: %s' % message)
except Exception:
print('ALERT ALERT ALERT: | %s' % message)
pass
palert = subprocess.Popen(["echo %s" % message],
stdout=subprocess.PIPE,
shell=True)
time = Timer(30, palert.kill)
time.start()
_, _ = palert.communicate()
if time.is_alive():
time.cancel()
|
huiyiqun/check_mk | agents/windows/it/remote.py | Python | gpl-2.0 | 6,472 | 0.000464 | #!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset: 4 -*-
import ConfigParser
import contextlib
import os
import platform
import pytest
import re
import subprocess
import sys
import telnetlib # nosec
# To use another host for running the tests, replace this IP address.
remote_ip = '10.1.2.30'
# To use anothe... | h.join(remotedir, 'check_mk_agent-64.exe')
ini_filename = os.path.join(remotedir, 'check_mk.ini')
def run_subprocess(cmd):
sys.stderr.write(' '.join(cmd) + '\n')
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
return (p.returncode, stdout, std... | te(stderr)
assert exit_code == 0, "'%s' failed" % ' '.join(cmd)
@pytest.fixture
def config():
ini = IniWriter()
ini.add_section('global')
ini.set('global', 'port', port)
return ini
@pytest.fixture
def write_config(testconfig):
if platform.system() == 'Windows':
with open(ini_filename... |
alobbs/webest | webest/obj.py | Python | mit | 2,552 | 0 | import retrying
import selenium
import selenium.webdriver.support.ui as ui
from . import exceptions as ex
@retrying.retry(wait_fixed=1000, retry_on_exception=ex.is_retry_exception)
def get(b, selector, not_found=None):
try:
obj = b.find_element_by_css_selector(selector)
except selenium.common.excepti... | nium.common.exceptions.NoSuchElementException:
return False
return obj.is_displayed()
@retrying.retry(wait_fixed=1000, retry_on_exception=ex.is_retry_exception)
def is_enabled(b, selector):
try:
obj = b.find_element_by_css_selector(selector)
except selenium.common.exceptions.NoSuchElementE... | return not_found
def obj_attr(b, selector, attr, not_found=None):
obj = get(b, selector)
if obj:
re = obj.get_attribute(attr)
if re is None:
return not_found
return re
return not_found
def wait_for_obj(b, selector, timeout=30):
wait = ui.WebDriverWait(b, timeout... |
yoseforb/lollypop | src/settings.py | Python | gpl-3.0 | 14,299 | 0.00028 | #!/usr/bin/python
# Copyright (c) 2014-2015 Cedric Bellegarde <[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 published by
# the Free Software Foundation, either version 3 of the License, or
# (at your opti... | ate'))
switch_view = builder.get_object('switch_dark')
switch_view.set_sta | te(Lp.settings.get_value('dark-ui'))
switch_background = builder.get_object('switch_background')
switch_background.set_state(Lp.settings.get_value('background-mode'))
switch_state = builder.get_object('switch_state')
switch_state.set_state(Lp.settings.get_value('save-state'))
... |
Migdalo/para | setup.py | Python | mit | 494 | 0.006073 | from setuptools import setup
import unittest
def para_test_suite():
test_loader = unittest.TestLoader()
test_suite = test_loader.discover('tests', pattern='test_*.py')
return test_suite
setup(name='para',
version='2.0.1',
author='Migdalo',
license='MIT',
packages=['para'],
te... | ]
},
zip_safe=True)
| |
thought-machine/please | test/python_rules/data_dep_test.py | Python | apache-2.0 | 577 | 0.001733 | """Test on deps, data, re | quires and provides."""
import os
import subprocess
import unittest
class DataDepTest(unittest.TestCase | ):
def test_direct_dep(self):
"""Test that we can import the module directly."""
from test.python_rules import data_dep
self.assertEqual(42, data_dep.the_answer())
def test_data_dep(self):
"""Test that we can also invoke the .pex directly as a data dependency."""
output... |
openlabs/raven | tests/contrib/tornado/tests.py | Python | bsd-3-clause | 5,739 | 0.000174 | # -*- coding: utf-8 -*-
"""
tests
Test the tornado Async Client
"""
import unittest
from mock import patch
from tornado import web, gen, testing
from raven.contrib.tornado import SentryMixin, AsyncSentryClient
class AnErrorProneHandler(SentryMixin, web.RequestHandler):
def get(self):
try:
... | self.assertTrue(('sentry.interfaces.Http' in kwargs))
| self.assertTrue(('sentry.interfaces.Exception' in kwargs))
http_data = kwargs['sentry.interfaces.Http']
self.assertEqual(http_data['cookies'], None)
self.assertEqual(http_data['url'], response.effective_url)
self.assertEqual(http_data['query_string'], 'qs=qs')
self.assertEqual(h... |
sebest/katana | katana/utils.py | Python | mpl-2.0 | 2,188 | 0 | import os
import errno
import fcntl
from contextlib import contextmanager
from time import time, sleep
@contextmanager
def wlock(filename, retry_interval=0.05):
# returns: write, exists, fd
try:
with open(filename, 'rb+') as lock:
try:
fcntl.flock(lock, fcntl.LOCK_EX | fcnt... | sleep(retry_interval)
continue
else:
raise
else:
yield False, True, lock
break
else:
ra... | e:
yield True, True, lock
except IOError as exc:
if exc.errno == errno.ENOENT:
with open(filename, 'wb') as lock:
while True:
try:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError as ex... |
LLNL/spack | var/spack/repos/builtin/packages/r-dss/package.py | Python | lgpl-2.1 | 1,309 | 0.000764 | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RDss(RPackage):
"""Dispersion shrinkage for sequencing data
DSS is an R library perfo... | .36.0', commit='841c7ed')
version('2.34.0', commit='f9819c7')
version('2.32.0', commit='ffb502d')
depends_on('[email protected]:', type=('build', 'run'))
depends_on('r-biobase', type=('build', 'run'))
depends_on('r-biocparallel', when='@2.36.0:', type=('build', 'run'))
depends_on('r-bsseq', type=('build', ... | build', 'run'))
|
pygraz/old-flask-website | migrations/versions/002_notificationflags.py | Python | bsd-3-clause | 896 | 0.001116 | from sqlalchemy import *
from migrate import *
meta = MetaData()
user_tbl = Table('user', meta)
status_col = Column('email_status', String, default='not_verified')
activation_code_col = Column('email_activation_code', String, nullable=True)
notify_new_meetup = Column('email_notify_new_meetup', Boolean, default=False... | tify_new_sessionidea = Column('email_noti | fy_new_sessionidea', Boolean, default=False)
def upgrade(migrate_engine):
meta.bind = migrate_engine
user_tbl.create_column(status_col)
user_tbl.create_column(activation_code_col)
user_tbl.create_column(notify_new_meetup)
user_tbl.create_column(notify_new_sessionidea)
def downgrade(migrate_engin... |
ashleysommer/sanic-cors | tests/decorator/test_exception_interception.py | Python | mit | 9,339 | 0.00182 | # -*- coding: utf-8 -*-
"""
test
~~~~
Sanic-CORS is a simple extension to Sanic allowing you to support cross
origin resource sharing (CORS) using a simple decorator.
:copyright: (c) 2020 by Ashley Sommer (based on flask-cors by Cory Dolphin).
:license: MIT, see LICENSE for more details.
"""
fr... | ('/test_acl_async_abort_404', origin='www.example.com')
self.assertEqual(resp.status, 404)
self.assertTrue(ACL_ORIGIN in resp.headers)
def test_no_a | cl_abort_404(self):
'''
HTTP Responses generated by calling abort are handled identically
to normal responses, and should be wrapped by CORS headers if the
path matches. This path does not match.
'''
resp = self.get('/test_no_acl_abort_404', origin='www.exampl... |
marcelogomess/glpi_api | setup.py | Python | bsd-2-clause | 344 | 0.002907 | from distutils.core import setup
setup(
name='glpi_api',
version='0.0.1',
packages=['requests'],
| url='http | s://github.com/marcelogomess/glpi_api.git',
license='BSD 2',
author='marcelogomess',
author_email='[email protected]',
description='Just a app to start with glpi api communitacion. glpi-project.org'
)
|
statsmodels/statsmodels | statsmodels/graphics/utils.py | Python | bsd-3-clause | 4,032 | 0.000496 | """Helper functions for graphics with Matplotlib."""
from statsmodels.compat.python import lrange
__all__ = ['create_mpl_ax', 'create_mpl_fig']
def _import_mpl():
"""This function is not needed outside this utils module."""
try:
import matplotlib.pyplot as plt
except:
raise ImportError("M... | ig` is None, the created figure. Otherwise the input `fig` is
returned.
See Also
--------
create_mpl_ax
"""
if fig is None:
plt = _import_mpl()
fig = plt.figure(figsize=figsi | ze)
return fig
def maybe_name_or_idx(idx, model):
"""
Give a name or an integer and return the name and integer location of the
column in a design matrix.
"""
if idx is None:
idx = lrange(model.exog.shape[1])
if isinstance(idx, int):
exog_name = model.exog_names[idx]
... |
petr-devaikin/dancee | helpers/extractor.py | Python | gpl-3.0 | 5,790 | 0.03057 | # Cut the experiment session in small fragments
# Input: ../bin/data/records/{session}/body.csv and skeletok.csv
# Output: fragments/{fragment_number}.json and fragments/log.csv
import os
import numpy
import json
DELAY = 15
LENGTH = 30
OVERLAP = 0.719999
FREQUENCY = 60
MARGIN = 5
FREQUENCY = 60
CUTOFF_FREQUENCY = 1... | [0] * buf_emg_length
# acc filtering
CUTOFF_ACC_FREQUENCY = 10
buf_acc_length = FREQUENCY / CUTOFF_ACC_FREQUENCY
kernel_acc = numpy.blackman(buf_acc_length)
kernel_acc_summ = numpy.sum(kernel_acc)
a | cc_buffer = [[0] * buf_acc_length] * 3
# clean the folder
for f in os.listdir("fragments"):
os.remove(os.path.join('fragments', f))
# cut fragments
record_counter = 0
def cut_fragment(participant, track_number):
global record_counter
global values
global values2
global buffers
global emg2_buffer
global acc_... |
dtysky/Led_Array | LED/PCB/Script/script6.py | Python | gpl-2.0 | 538 | 0.033457 | import st | ring
import struct
out=open('Led.scr','w');
w=202
h=726.8
for j in range(120):
wtf='add'+' '+'connect'+';'+'\n'+'pick'+' '+str(w)+' '+str(h)+';'+'\n'
out.write(wtf)
w=w-1.3
wtf='pick'+' '+str(w)+' '+str(h)+';'+' | \n'
out.write(wtf)
wtf='add'+' '+'connect'+';'+'\n'+'pick'+' '+str(w)+' '+str(h)+';'+'\n'
out.write(wtf)
h=h-153
wtf='pick'+' '+str(w)+' '+str(h)+';'+'\n'
out.write(wtf)
w=w+1.3
h=h+153
wtf='done'+';'+'\n'
out.write(wtf)
w=w+2
|
adamgreig/momobot | settings.py | Python | bsd-3-clause | 508 | 0.001969 | # | -*- coding: utf-8 -*-
# The IRC nickname and password to connect and identify with
NICKNAME = 'momobot_test'
PASSWORD = ''
# The IRC server and port to connect to
SERVER = 'irc.rizon.net'
PORT = 6667
# The channel to join
CHANNEL = '#momotest'
# A list of command indicators
COMMAND_INDICATORS = ['!', '.', 'momo, ']... | d', 'Xaiter'] |
team-hdnet/hdnet | tests/test_tmppath.py | Python | gpl-3.0 | 548 | 0 | # -*- coding: utf-8 -*-
# This file i | s part of the hdnet package
# Copyright 2014 the authors, see file AUTHORS.
# Licensed under the GPLv3, see file LICENSE for details
import os
import unittest
import shutil
class TestTmpPath(unittest.TestCase):
TMP_PATH = '/tmp/hdnettest'
def setUp(self):
if os.path.exists(self.TMP_PATH):
... | path.exists(self.TMP_PATH):
shutil.rmtree(self.TMP_PATH)
# end of source
|
simontakite/sysadmin | pythonscripts/learningPython/bothmethods.py | Python | gpl-2.0 | 486 | 0 | # File bothmethods.py
cl | ass Methods:
def imeth(self, x): # Normal instance method: passed a self
print([self, x])
def smeth(x): # Static: no instance passed
print([x])
def cmeth(cls, x): # Clas | s: gets class, not instance
print([cls, x])
smeth = staticmethod(smeth) # Make smeth a static method (or @: ahead)
cmeth = classmethod(cmeth) # Make cmeth a class method (or @: ahead)
|
keflavich/spectral-cube | spectral_cube/tests/test_spectral_cube.py | Python | bsd-3-clause | 96,662 | 0.005069 | from __future__ import print_function, absolute_import, division
import re
import copy
import operator
import itertools
import warnings
import mmap
from distutils.version import LooseVersion
import sys
import pytest
import astropy
from astropy import stats
from astropy.io import fits
from astropy import units as u
f... | advs, use_dask=use_dask)
| c2, d2 = cube_and_raw(data_sadv, use_dask=use_dask)
for w1, w2 in zip(c1.world[view], c2.world[view]):
assert_allclose(w1, w2)
@pytest.mark.parametrize(('filename','masktype','unit','suffix'),
|
ess-dmsc/do-ess-data-simulator | DonkiDirector/HDFWriterThread.py | Python | bsd-2-clause | 6,785 | 0.040678 | import time
import threading
import PyTango
import numpy
import h5py
THREAD_DELAY_SEC = 0.1
class HDFwriterThread(threading.Thread):
#-----------------------------------------------------------------------------------
# __init__
#-----------------------------------------------------------------------------------... | threading.Thread.__init__(self)
self._a | live = True
self.myState = PyTango.DevState.OFF
self.filename = filename_in
self.parent = parent_obj
self.trg_start = trg_start
self.trg_stop = trg_stop
self.data_queue = []
self.datasource_finished = {}
self._hdf_file = None
self.timeout_sec = 20
self.MetadataSources = {}
if "_errors" in dir(h5py):
h5py._... |
abelcarreras/aiida_extensions | setup.py | Python | mit | 2,089 | 0.00383 | from setuptools import setup, find_packages
setup(
name='aiida-phonon',
version='0.1',
description='AiiDA plugin for running phonon calculations using phonopy',
url='https://github.com/abelcarreras/aiida_extensions',
author='Abel Carreras',
author_email='[email protected]',
license='MI... | f_gruneisen_pressure:WorkflowGruneisen',
| 'wf_gruneisen_volume = workflows.wf_gruneisen_volume:WorkflowGruneisen',
'wf_qha = workflows.qha:WorkflowQHA',
'wf_quasiparticle = workflows.quasiparticle:WorkflowQuasiparticle',
'wf_quasiparticle_thermo = workflows.wf_quasiparticle_thermo:WorkflowQuasiparticle',
... |
valmynd/MediaFetcher | src/plugins/youtube_dl/youtube_dl/extractor/hearthisat.py | Python | gpl-3.0 | 4,347 | 0.027605 | # coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import compat_urlparse
from ..utils import (
HEADRequest,
KNOWN_EXTENSIONS,
sanitized_Request,
str_to_int,
urlencode_postdata,
urlhandle_detect_ext,
)
class HearThisAtIE(InfoExtractor):
_VALID_UR... |
meta_span = r'<span[^>]+class="%s".*?</i>([^<]+)</span>'
view_count = str_to_int(self._search_regex(
meta_span % 'plays_count', webpage, 'view count', fatal=False))
like_count = str_to_int(self._search_regex(
meta_span % 'likes_count', webpage, 'like count', fatal=False))
comment_count = str_to_int(self.... | (\d+)', webpage, 'duration', fatal=False))
timestamp = str_to_int(self._search_regex(
r'<span[^>]+class="calctime"[^>]+data-time="(\d+)', webpage, 'timestamp', fatal=False))
formats = []
mp3_url = self._search_regex(
r'(?s)<a class="player-link"\s+(?:[a-zA-Z0-9_:-]+="[^"]+"\s+)*?data-mp3="([^"]+)"',
web... |
saltstack/salt | tests/unit/modules/test_djangomod.py | Python | apache-2.0 | 8,081 | 0.001114 | """
:codeauthor: Jayesh Kariya <[email protected]>
"""
import sys
import pytest
import salt.modules.djangomod as djangomod
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.mock import MagicMock, patch
from tests.support.unit import TestCase
class DjangomodTestCase(TestCase, LoaderMod... | with patch.dict(djangomod.__salt__, | {"cmd.run": mock}):
djangomod.command("settings.py", "runserver")
mock.assert_called_once_with(
"django-admin.py runserver --settings=settings.py",
python_shell=False,
env=None,
runas=None,
)
def test_django_admin_c... |
TheTimmy/spack | var/spack/repos/builtin/packages/slurm/package.py | Python | lgpl-2.1 | 4,160 | 0.00024 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, [email protected], All rights reserved.
# LLNL-CODE-64... | o users for some duration of time so they can
perform work. Second, it provides a framework for starting, executing,
and monitoring work (normally a parallel job | ) on the set of allocated
nodes. Finally, it arbitrates contention for resources by managing a
queue of pending work.
"""
homepage = 'https://slurm.schedmd.com'
url = 'https://github.com/SchedMD/slurm/archive/slurm-17-02-6-1.tar.gz'
version('17-02-6-1', '8edbb9ad41819464350d9de013367020')
... |
usc-isi-i2/etk | etk/data_extractors/htiExtractors/utils.py | Python | mit | 18,615 | 0.017029 | """
This class is used to speed up general, day-to-day programming needs. It contains a variety of
very commonly used functions - anything from retrieving a custom list of dates to
retrieving Dictionaries of Backpage cities' coordinates.
"""
from copy import deepcopy
import csv
from datetime import datetime, timede... | eric value
ethn_legend = {}
ethn_list = ['white_non_hispanic', 'hispanic_latino', 'american_indian', 'asian', 'midEast_nAfrican',
'african_american', 'subsaharan_african', 'multiracial']
for e in range(len(ethn_list)):
ethn_legend[ethn_list[e]] = e+1
return ethn_legend
def ethnicities_clean():
... | n = {}
fname = pkg_resources.resource_filename(__name__, 'resources/Ethnicity_Groups.csv')
with open(fname, 'rU') as csvfile:
reader = csv.reader(csvfile, delimiter = ',')
first = []
for row in reader:
if first:
for i in range(len(first)):
if first[i] and row[i]:
eth... |
zhsso/ubunto-one | src/backends/db/schemas/txlog/patch_4.py | Python | agpl-3.0 | 1,421 | 0 | # Copyright 2008-2015 Canonical
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Ge | neral 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 PARTICULA... | ic License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# For further info, check http://launchpad.net/filesync-server
"""Add db_worker_unseen table to keep track of unseen items on the database
... |
daaoling/KBEngine-LearnNote | kbengine_demos_assets/scripts/cell/kbengine.py | Python | gpl-2.0 | 1,646 | 0.056657 | # -*- codin | g: utf-8 -*-
import KBEngine
from KBEDebug import *
import dialogmgr
import skills
def onInit(isReload):
"""
KBEngine method.
当引擎启动后初始化完所有的脚本后这个接口被调用
"""
DEBUG_MSG('onInit::isReload:%s' % isReload)
dialogmgr.onInit()
skills.onInit()
def onGlobalData(key, value):
"""
KBEngine method.
globalData改变
"""
DEB... | ta(key, value):
"""
KBEngine method.
cellAppData改变
"""
DEBUG_MSG('onCellAppData: %s' % key)
def onCellAppDataDel(key):
"""
KBEngine method.
cellAppData删除
"""
DEBUG_MSG('onCellAppDataDel: %s' % key)
def onSpaceData( spaceID, key, value ):
"""
KBEngine method.
spaceData改变
@spaceID: 数据被设置在这个spaceID的sp... |
ComputerNetworks-UFRGS/OpERA | python/algorithm/qa_test.py | Python | apache-2.0 | 3,935 | 0.00432 | """
Copyright 2013 OpERA
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, softwar... | ait() | # wait = 3
obj.wait() # wait = 4
obj.increase_time() # 2^2 = 4
self.assertEqual(True, obj.feedback()) # wait gets back to 0 # volta wait para 0
self.assertEqual(False, obj.feedback()) # wait gets back to 0 # volta wait para 0
obj.decrease_time() # Should be 2^1 = 2
... |
cangencer/hazelcast-python-client | hazelcast/protocol/codec/semaphore_init_codec.py | Python | apache-2.0 | 1,147 | 0.000872 | from hazelcast.serialization.bits import *
from hazelcast.protocol.client_message import ClientMessage
from hazelcast.protocol.custom_codec import *
from hazelcast.util import ImmutableLazyDataList
from hazelcast.protocol.codec.semaphore_message_type import *
REQUEST_TYPE = SEMAPHORE_INIT
RESPONSE_TYPE = 101
RETRYABLE... | += INT_SIZE_IN_BYTES
return data_size
def encode_request(name, permits):
""" Encode request into client_message"""
client_message = ClientMessage(payload_size=calculate_size(name, permits))
client_message.set_message_type(REQUEST_TYPE)
| client_message.set_retryable(RETRYABLE)
client_message.append_str(name)
client_message.append_int(permits)
client_message.update_frame_length()
return client_message
def decode_response(client_message, to_object=None):
""" Decode response from client message"""
parameters = dict(response=None... |
galaxyproject/pulsar | test/authorization_test.py | Python | apache-2.0 | 1,340 | 0.002239 | from pulsar.tools.authorization import get_authorizer
from .test_utils import get_test_toolbox, TestCase
def test_allow_any_authorization():
authorizer = get_authorizer(None)
authorization = authorizer.get_authorization('tool1')
authorization.authorize_setup()
authorization.authorize_tool_file('cow', ... | rize_setup()
def test_invalid_setup_fails(self):
with self.unauthorized_expectation():
self.authorizer.get_authoriza | tion('tool2').authorize_setup()
def test_valid_tool_file_passes(self):
authorization = self.authorizer.get_authorization('tool1')
authorization.authorize_tool_file('tool1_wrapper.py', 'print \'Hello World!\'\n')
def test_invalid_tool_file_fails(self):
authorization = self.authorizer.ge... |
efarres/GoIPbus | cactuscore/softipbus/scripts/ctp6_integration_patterns.py | Python | gpl-2.0 | 325 | 0.006154 | # Map the oRSC fiber indices to CTP fiber indices
FIBER_MAP = {
24: 0x5,
25: 0x4,
26: 0x8,
27 | : 0xb,
28: 0x6,
29: 0x7
}
from integration_patterns import pattern as orsc_pattern
def pattern(link):
if link in FIBER_MAP:
return orsc_pattern(FIBER_MAP[link]-1)
r | eturn orsc_pattern(link)
|
wangzitian0/BOJ-V4 | submission/views.py | Python | mit | 2,454 | 0.000407 | from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated
from .models import Submission
from .serializers import SubmissionSerializer
from django.views.generic import ListView, DetailView
from django.views.generic.edit import CreateView
from django.utils.decorators import method_deco... | ubmissionTable(self.get_queryset())
RequestConfig(self.request).configure(submissions_table)
# add filter here
context['submissions_table'] = submissions_table
return context
class SubmissionDetailView(DetailView):
model = Submission
def get_context_data(self, **kwargs):
... | **kwargs)
return context
class SubmissionCreateView(CreateView):
model = Submission
form_class = SubmissionForm
template_name_suffix = '_create_form'
@method_decorator(login_required)
def dispatch(self, request, pid=None, *args, **kwargs):
pid = self.kwargs['pid']
self.pro... |
python-poetry/poetry-core | src/poetry/core/spdx/license.py | Python | mit | 5,634 | 0.000887 | from collections import namedtuple
from typing import Optional
class License(namedtuple("License", "id name is_osi_approved is_deprecated")):
id: str
name: str
is_osi_approved: bool
is_deprecated: bool
CLASSIFIER_SUPPORTED = {
# Not OSI Approved
"Aladdin",
"CC0-1.0",
... | "GPL-3.0-or-later": "GNU General Public License v3 or later (GPLv3+)",
"LGPL-2.0": "GNU Lesser General Public License v2 (LGPLv2)",
"LGPL-2.0-only": "GNU Lesser General Public License v2 (LGPLv2)",
"LGPL-2.0+": "GNU Lesser General Public License v2 or later (LGPLv2+)",
| "LGPL-2.0-or-later": "GNU Lesser General Public License v2 or later (LGPLv2+)",
"LGPL-3.0": "GNU Lesser General Public License v3 (LGPLv3)",
"LGPL-3.0-only": "GNU Lesser General Public License v3 (LGPLv3)",
"LGPL-3.0+": "GNU Lesser General Public License v3 or later (LGPLv3+)",
"LGPL-3... |
iffy/parsefin | parsefin/error.py | Python | apache-2.0 | 59 | 0.050847 | class Error(Exception): pass
class | MissingData(Error): | pass |
PapaCharlie/WolframAlphaLookup | WolframAlphaLookup.py | Python | mit | 2,331 | 0.005148 | import sublime, sublime_plugin, requests
from xml.etree import ElementTree as ET
class WolframAlphaLookupCommand(sublime_plugin.WindowCommand):
def run(self):
settings = sublime.load_settings("Preferences.sublime-settings")
if settings.has("wolfram_api_key"):
API_KEY = setting... | ).sel():
| if not region.empty():
query = self.window.active_view().substr(region)
else:
query = self.window.active_view().substr(self.window.active_view().line(region))
query = query.strip()
r = requests.get("http://api.wolframal... |
HyperloopTeam/FullOpenMDAO | cantera-2.0.2/samples/python/flames/adiabatic_flame/adiabatic_flame.py | Python | gpl-2.0 | 2,623 | 0.020206 | #
# ADIABATIC_FLAME - A freely-propagating, premixed methane/air flat
# flame with multicomponent transport properties
#
from Cantera import *
from Cantera.OneD import *
from Cantera.OneD.FreeFlame import FreeFlame
################################################################
#
# parameter values
#
p ... |
f.set(energy = 'on')
f.setRefineCriteria(ratio = 3.0, slope = 0.1, curve = 0.2)
f.solve(loglevel, refine_grid)
f.save('ch4_adiabatic.xml','energy',
'solution with the energy equation enabled')
print 'mixture-averaged flamespeed = ',f.u()[0]
gas.switchTransportModel('Multi')
f.flame.setTransportModel(gas)
f.so... | velocity, temperature, density, and mole fractions to a CSV file
z = f.flame.grid()
T = f.T()
u = f.u()
V = f.V()
fcsv = open('adiabatic_flame.csv','w')
writeCSV(fcsv, ['z (m)', 'u (m/s)', 'V (1/s)', 'T (K)', 'rho (kg/m3)']
+ list(gas.speciesNames()))
for n in range(f.flame.nPoints()):
f.setGasState(n)
... |
crmccreary/openerp_server | openerp/addons/web_diagram/controllers/main.py | Python | agpl-3.0 | 4,665 | 0.004287 | try:
# embedded
import openerp.addons.web.common.http as openerpweb
from openerp.addons.web.controllers.main import View
except ImportError:
# standalone
import web.common.http as openerpweb
from web.controllers.main import View
class DiagramView(View):
_cp_path = "/web_diagram/diagram"
... | view_id):
fields_view = self.fields_view_get(req, model, view_id, 'diagram')
return {'fields_view': fields_view}
@openerpweb.jsonrequest
def get_diagram_info(self, req, id, model, node, connector,
src_node, des_node, label, **kw):
visible_node_fields = kw.get('... | kw.get('connector_fields',[])
connector_fields_string = kw.get('connector_fields_string',[])
bgcolors = {}
shapes = {}
bgcolor = kw.get('bgcolor','')
shape = kw.get('shape','')
if bgcolor:
for color_spec in bgcolor.split(';'):
if color_spec:... |
myangeline/pygame | itgame/itgame.py | Python | apache-2.0 | 7,541 | 0.000959 | # _*_coding:utf-8_*_
import math
import random
__author__ = 'Administrator'
import pygame
pygame.init()
width, height = 640, 480
keys = [False, False, False, False]
playerpos = [100, 240]
# 记录玩家射击精度,射击次数、命中次数
acc = [0, 0]
arrows = []
# 命中率
accuracy = 0
# 记录獾的数据
badtimer = 100
rest = 0
badguys = [[640, 100]]
healthv... | yer_w
# 判断输赢
if pygame.time.get_ticks() >= 90000:
running = 0
# win
| exitcode = 1
if healthvalue <= 0:
running = 0
# lose
exitcode = 0
if acc[1] != 0:
accuracy = round(acc[0] * 1.0 / acc[1] * 100, 2)
pygame.font.init()
# font = pygame.font.Font(None, 24)
# 为了显示中文需要设置中文字体,可以使用字体文件和系统字体
font = pygame.font.SysFont('楷体', 24)
if exitcode:
text... |
stack-of-tasks/rbdlpy | tutorial/lib/python2.7/site-packages/OpenGL/raw/GL/ARB/clear_buffer_object.py | Python | lgpl-3.0 | 845 | 0.04142 | '''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.GL import _types as _cs
# End users want this...
from OpenGL.raw.GL._types import *
from OpenGL.raw.GL import _errors
from OpenGL.constant import Constant as _C
import ctypes
_... | ( function ):
return _p.createFunction( function,_p.PLATFORM.GL,'GL_ARB_clear_buffer_object',error_checker=_errors._error_checker)
@_f
@_p.types(None,_cs.GLenum,_cs.GLenum,_cs.GLenum,_cs.GLenum,ctypes.c_void_p)
def glClearBufferData(target,internalformat,format,type,data):pass
@_f
@_p.types(None,_cs.GLenum,_cs.GLe... | ass
|
Ziqi-Li/bknqgis | bokeh/examples/howto/server_embed/tornado_embed.py | Python | gpl-2.0 | 2,322 | 0.003015 | from jinja2 import Environment, FileSystemLoader
import yaml
from tornado.ioloop import IOLoop
from tornado.web import RequestHandler
from bokeh.application import Application
from bokeh.application.handlers import FunctionHandler
from bokeh.embed import server_document
from bokeh.layouts import column
from bokeh.mod... | toolbar_location: above
height: 500
width: 800
Grid:
grid_line_dash: [6, 4]
grid_line_color: white
"""))
bokeh_app = Application(FunctionHandler(modify_doc))
io_loop = IOLoop.current()
server = Server({'/bkapp': bokeh_app}, io_loop=io... | '__main__':
from bokeh.util.browser import view
print('Opening Tornado app with embedded Bokeh application on http://localhost:5006/')
io_loop.add_callback(view, "http://localhost:5006/")
io_loop.start()
|
Juniper/ceilometer | ceilometer/alarm/notifier/test.py | Python | apache-2.0 | 1,257 | 0 | #
# Copyright 2013 eNovance
#
# 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, ... | uage governing permissions and limitations
# under the License.
"""Test alarm notifier."""
from ceilometer.alarm import notifier
class TestAlarmNotifier(notifier.AlarmNotifier):
"Test alarm notifier."""
def __init__(self):
self.notifications = []
def notify(self, action, alarm_id, alarm_name, s... | a):
self.notifications.append((action,
alarm_id,
alarm_name,
severity,
previous,
current,
reason,
... |
inovtec-solutions/OpenERP | openerp/addons/smsfee/__openerp__.py | Python | agpl-3.0 | 859 | 0.003492 | {
'name': 'SMS Fee',
'version': '1.0',
'author': 'Inovtec Solutions',
'category': 'SMS Fee Management',
'description': """This Module is used for fee management for Compas ManagmentS ystem.""",
'website': 'http://www.inovtec.com.pk',
'images': [''],
'depends' : ['sms'],
'data': ['sec... | _fee_register.xml',
'wizard/smsfee_wizard_fee_repor | ts.xml',
'wizard/smsfee_wizard_class_fee_receipt_unpaid.xml',
'wizard/smsfee_wizard_daily_fee_reports.xml',
'smsfee_report.xml',
'smsfee_view.xml',
'smsfee_menus.xml',
],
'demo': [],
'installable': True,
'application': True,
'a... |
ivanyu/rosalind | algorithmic_heights/inv/inv_logic.py | Python | mit | 2,407 | 0 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
class InversionsCoun | ter:
# Taken from mer problem and modified
@staticmethod
def _merge_with_inv_counting(a1, a2):
result = []
invs = 0
i = 0
j = 0
while i < len(a1) or j < len(a2):
if i == len(a1):
result.extend(a2[j:])
break
if j ... | result.extend(a1[i:])
break
if a1[i] <= a2[j]:
result.append(a1[i])
i += 1
else:
result.append(a2[j])
j += 1
invs += len(a1[i:])
return result, invs
def _merge_sort_with_i... |
yancharkin/games_nebula_goglib_scripts | the_temple_of_elemental_evil/settings.py | Python | gpl-3.0 | 36,924 | 0.010373 | import sys, os
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk, GLib
import gettext
import imp
nebula_dir = os.getenv('NEBULA_DIR')
modules_dir = nebula_dir + '/modules'
set_visuals = imp.load_source('set_visuals', modules_dir + '/set_visuals.py')
gettext.bindtextdomain('games_nebula', ... | 0Setup.exe"
link_ja2_portraits_std = "http://files.co8.org/mods/TFE-X%20Modules/Portrait%20Packs/Jagged%20Alliance%202%20Portrait%20Pack%208.1.0%20Standard%20Edition%20Setup.exe"
link_ja2_portraits_nc = "http://files.co8.org/mods/TFE-X%20M | odules/Portrait%20Packs/Jagged%20Alliance%202%20Portrait%20Pack%208.1.0%20New%20Content%20Edition%20Setup.exe"
link_ja2_portraits_kob = "http://files.co8.org/mods/TFE-X%20Modules/Portrait%20Packs/Jagged%20Alliance%202%20Portrait%20Pack%201.0.1%20Keep%20on%20the%20Borderlands%20Setup.exe"
link_lr_portraits_std = "http:/... |
Real-Instruments/fflib | fflib/peer.py | Python | agpl-3.0 | 26,829 | 0.003541 | #!/usr/bin/env python3
# The MIT License (MIT)
# Copyright (c) 2016 Michael Sasser <[email protected]>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the Software without restriction... | sing
self.__read_process(file_raw)
def __del_msgs(self, *args):
for err in args:
self.__error.pop(err, None)
self. | __warn.pop(err, None)
self.__debug.pop(err, None)
return 0
def __read_process(self, file_raw):
self.__del_msgs(70, 51, 52, 60, 71, 61, 72, 62, 73, 80)
line_no = 0
self.__read_done = False
cache_name = None
cache_mac = None
cache_key = None
... |
mpasternak/pyglet-fix-issue-518-522 | tests/image/PLATFORM_RGBA_LOAD.py | Python | bsd-3-clause | 963 | 0.003115 | #!/usr/bin/env python
'''Test RGBA load using the platform decoder (QuickTime, Quartz, GDI+ or Gdk).
You should see the rgba.png image on a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
import base_load
import sys
if sys.platform == 'linux2':
... | mageDecoder as dclass
class TEST_PLATFORM_RGBA_LOAD(base_load.TestLoad):
texture_file = 'rgba.png'
decoder = dcl | ass()
if __name__ == '__main__':
unittest.main()
|
yytang2012/novels-crawler | novelsCrawler/spiders/m-daomengren.py | Python | mit | 1,831 | 0.000548 | #!/usr/bin/env python
# coding=utf-8
"""
Created on April 15 2017
@author: yytang
"""
from scrapy import Selector
from libs.misc import get_spider_name_from_domain
from libs.polish import *
from novelsCrawler.spiders.novelSpider import NovelSpider
class DaomengrenMobileSpider(NovelSpider):
"""
classdocs
... | ').extract()[0]
title = polish_title(title, self.name)
return title
def parse_episodes(self, response):
sel = Selector(response)
episodes = []
subtitle_selectors = sel.xpath('//ul[@class="chapter"]/li/a')
for page_id, subtitle_selector in enumerate(subtitle_selectors... | ubtitle_selector.xpath('@href').extract()[0]
subtitle_url = response.urljoin(subtitle_url.strip())
subtitle_name = subtitle_selector.xpath('text()').extract()[0]
subtitle_name = polish_subtitle(subtitle_name)
episodes.append((page_id, subtitle_name, subtitle_url))
... |
martinohanlon/minecraft-starwars | planet.py | Python | mit | 1,268 | 0.005521 | import mcpi.minecraft as minecraft
import mcpi.block as block
import mcpi.minecraftstuff as mcstuff
from time import sleep
class Planet():
def __init__(self, pos, radius, blockType, blockData = 0):
self.mc = minecraft.Minecraft.create()
self.pos = pos
self.radi | us = radius
self.blockType = blockType
self.blockData = blockData
self._draw()
def _draw(self):
mcDraw = mcstuff.MinecraftDrawing(self.mc)
mcDraw.drawHollowSphere(self.pos.x, self.pos.y, self.pos.z,
self.radius, self.blockType, self.bl... | .drawHollowSphere(self.pos.x, self.pos.y, self.pos.z,
# self.radius, block.LAVA_STATIONARY.id)
#sleep(delayLava)
mcDraw.drawHollowSphere(self.pos.x, self.pos.y, self.pos.z,
self.radius, block.COBBLESTONE.id)
sleep(delay)
... |
shakle17/django_range_slider | test_slider/slider_app/widgets.py | Python | mit | 1,469 | 0.007488 | from django import forms
from django.utils.safestring import mark_safe
import re
class RangeSlider(forms.TextInput):
def __init__(self, minimum, maximum, step, elem_name,*args,**kwargs):
widget = super(RangeSlider,self).__init__(*args,**kwargs)
self.minimum = str(minimum)
self.maximum = str... | cript>
$('#id_"""+self.elem_id+"""').attr("readonly", true)
$( "#slider-range-"""+self.elem_id + """" ).slider({
range: true,
min: """+self.minimum+""",
max: """+self.maximum | +""",
step: """+self.step+""",
values: [ """+self.minimum+""","""+self.maximum+""" ],
slide: function( event, ui ) {
$( "#id_"""+self.elem_id+"""" ).val(" """ + self.elem_name + """ "+ ui.values[ 0 ] + " - " + ui.values[ 1 ] );
}
});
$( "#id_"""+self.elem_id+"""... |
battlemidget/taiga-ncurses | taiga_ncurses/ui/views/backlog.py | Python | apache-2.0 | 3,880 | 0.001291 | # -*- coding: utf-8 -*-
"""
taiga_ncurses.ui.views.backlog
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
import urwid
from taiga_ncurses.ui.widgets import generic, backlog
from . import base
class ProjectBacklogSubView(base.SubView):
help_popup_title = "Backlog Help Info"
help_popup_info = base.SubView.help_popup_in... | _story_form.team_requirement,
"client_requirement": self.user_story_form.client_requirement,
"project": self.project["id"],
})
return data
def open_user_stories_in_b | ulk_form(self):
self.user_stories_in_bulk_form = backlog.UserStoriesInBulkForm(self.project)
# FIXME: Calculate the form size
self.parent.show_widget_on_top(self.user_stories_in_bulk_form, 80, 24)
def close_user_stories_in_bulk_form(self):
del self.user_stories_in_bulk_form
... |
obi-two/Rebelion | data/scripts/templates/object/tangible/loot/bestine/shared_bestine_painting_schematic_ronka.py | Python | mit | 503 | 0.043738 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
|
result.template = "object/tangible/loot/bestine/shared_bestine_painting_schematic_ronka.iff"
result.attribute_template_id = -1
result.stfName("craft_furniture_ingredients_n","painting_schematic_ronka")
#### BEGIN MODIFICATIONS ####
#### END MODIFICA | TIONS ####
return result |
edgedb/edgedb | tests/test_edgeql_casts.py | Python | apache-2.0 | 82,780 | 0 | #
# This source file is part of the EdgeDB open source project.
#
# Copyright 2018-present MagicStack Inc. and the EdgeDB authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http... | ELECT
<bytes>cal::to_local_datetime('2018-05-07T20:01:22.306916');
| """)
async def test_edgeql_casts_bytes_07(self):
async with self.assertRaisesRegexTx(
edgedb.QueryError, r'cannot cast'):
await self.con.execute("""
SELECT <bytes>cal::to_local_date('2018-05-07');
""")
async def test_edgeql_casts_byte... |
amitgroup/amitgroup | examples/parts_descriptor_test.py | Python | bsd-3-clause | 608 | 0.008224 |
import amitgroup as ag
import numpy as np
ag.set_verbose(True)
# This requires you to have the MNIST data set.
data, digits = ag.io.load_mnist('training', selection=slice(0, 100))
pd = ag.features.PartsDescriptor((5, | 5), 20, patch_frame=1, edges_threshold=5, samples_per_image=10)
# | Use only 100 of the digits
pd.train_from_images(data)
# Save the model to a file.
#pd.save('parts_model.npy')
# You can then load it again by
#pd = ag.features.PartsDescriptor.load(filename)
# Then you can extract features by
#features = pd.extract_features(image)
# Visualize the parts
ag.plot.images(pd.visparts)
|
toumorokoshi/uranium | uranium/tests/lib/test_context.py | Python | mit | 1,065 | 0 | import pytest
from uranium.lib.context import Proxy, ContextStack, ContextUnavailable
@pytest.fixture
def context_stack():
return ContextStack()
@pytest.fixture
def proxy(context_stack):
return Proxy(context_stack)
def test_context_stack(context_stack | ):
obj1 = object()
obj2 = object()
with pytest.raises(ContextUnavailable):
context_stack.obj
context_stack.push(obj1)
assert context_stack.obj is obj1
context_stack.push(obj2)
assert context_stack.obj is obj2
context_stack.pop()
assert context_stack.obj is obj1
with ... | j1
with pytest.raises(ContextUnavailable):
context_stack.obj
def test_context_proxy(context_stack, proxy):
class TestObj(object):
pass
obj = TestObj()
obj.foo = 3
obj.bar = 6
with context_stack.create_context(obj):
assert proxy.foo == 3
assert proxy.bar == 6
... |
Crypt0s/Ramen | fs_libs/ftputil/sandbox/test_ticket_71.py | Python | gpl-3.0 | 411 | 0.002433 | #! /usr/bin/env python
import ftplib
import ftputil
ftp_host = ftputil.FTPHost("lo | calhost", "ftptest",
"d605581757de5eb56d568a4419f4126e")
ftp_host._session.set_debugl | evel(2)
#import pdb; pdb.set_trace()
ftp_host.listdir("/rootdir2")
print
ftp = ftplib.FTP("localhost", "ftptest", "d605581757de5eb56d568a4419f4126e")
ftp.set_debuglevel(2)
ftp.cwd("/")
ftp.cwd("/")
ftp.dir("-a")
|
ahnitz/pycbc | docs/_include/distributions-table.py | Python | gpl-3.0 | 1,274 | 0 | #!/usr/bin/env python
# Copyright (C) 2018 Duncan Macleod, Collin Capano
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 3 of the License, or (at your
# option) any later versi... | '.format,
| header=('Name', 'Class'),
val_format=format_class)
filename = 'distributions-table.rst'
with open(filename, 'w') as fp:
print(tbl, file=fp)
|
kingsamchen/Eureka | crack-data-structures-and-algorithms/leetcode/find_the_celebrity_q277.py | Python | mit | 1,367 | 0 | # The knows API is already defined for you.
# @param a, person a
# @param b, person b
# @return a boolean, whether a knows b
# def knows(a, b):
# 核心思路
# 保证O(n)时间复杂度,否则会TLE
# 第一步选取我们的候选celebrity,主要通过假定一个候选i,然后遍历j(i!=j)检查knows(i,j)返回值
# 如果返回True,则表明i认识j,则i一定不是候选者,将i替换为j,继续遍历;
# 如果返回False,则说明i有可能是候选者,继续遍历
# 第二轮是校验候选i是否是真... | ntinue
if kno | ws(candidate, i) or not knows(i, candidate):
return -1
# aha, it passes all tests.
return candidate
|
Debian/openjfx | modules/web/src/main/native/Tools/Scripts/webkitpy/port/driver.py | Python | gpl-2.0 | 32,610 | 0.003312 | # Copyright (C) 2011 Google Inc. All rights reserved.
# Copyright (c) 2015, 2016 Apple Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the... | EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUE | NTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
... |
Knewton/pettingzoo-python | pettingzoo/deleted.py | Python | apache-2.0 | 3,159 | 0.034505 | import zc.zk
import zookeeper
import threading
import sys
import traceback
import pettingzoo.testing
class Deleted(zc.zk.NodeInfo):
"""
This class is implementing the zc.zk
"""
event_type = zookeeper.DELETED_EVENT
def __init__(self, session, path, callbacks=[]):
zc.zk.ZooKeeper._ZooKeeper__zkfuncs[zookeeper.DE... | is not being exercised in tests
for watch in self.session.watches.pop(self.key):
try:
self.path = self.session.resolve(self.path)
except (zookeeper.NoNodeException, zc. | zk.LinkLoop):
zc.zk.logger.exception("%s path went away", watch)
watch._deleted()
else:
self._set_watch()
def _notify(self, data):
"""
Internal function, not intended for external calling
"""
if data == None:
for callback in list(self.callbacks):
try:
callback(self)
except Excep... |
k-okada/vcstools | setup.py | Python | bsd-3-clause | 1,330 | 0.001504 | from setuptools import setup
import imp
def get_version():
ver_file = None
try:
ver_file, pathname, description = imp.find_module('__version__', ['src/vcstools'])
vermod = imp.load_module('__version__', ver_file, pathname, description)
version = vermod.version
return version
... | vn", "hg", "bzr"],
classifiers=["Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
"License :: OSI Approved :: B | SD License"],
description="VCS/SCM source control library for svn, git, hg, and bzr",
long_description="""\
Library for managing source code trees from multiple version control systems.
Current supports svn, git, hg, and bzr.
""",
license="BSD")
|
fmin2958/POCS | panoptes/mount/ioptron.py | Python | mit | 10,044 | 0.003189 | import re
from astropy import units as u
from astropy.coordinates import SkyCoord
from astropy.time import Time
from panoptes.mount.mount import AbstractMount
from ..utils.logger import has_logger
from ..utils.config import load_config
from ..utils import error as error
@has_logger
class Mount(AbstractMount):
... | return self.is_initialized
##################################################################################################
# Private Methods
##################################################################################################
def _setup_location_for_mount(self):
"""
Sets th... | This uses mount.location (an astropy.coords.EarthLocation) to set most of the params and the rest is
read from a config file. Users should not call this directly.
Includes:
* Latitude set_long
* Longitude set_lat
* Daylight Savings disable_daylight_savings
* Universal... |
e-gob/plataforma-kioscos-autoatencion | scripts/ansible-play/.venv/lib/python2.7/site-packages/ansible/plugins/terminal/vyos.py | Python | bsd-3-clause | 1,700 | 0.000588 | #
# (c) 2016 Red Hat Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is d... | nalBase):
terminal_stdout_re | = [
re.compile(br"[\r\n]?[\w+\-\.:\/\[\]]+(?:\([^\)]+\)){,3}(?:>|#) ?$"),
re.compile(br"\@[\w\-\.]+:\S+?[>#\$] ?$")
]
terminal_stderr_re = [
re.compile(br"\n\s*Invalid command:"),
re.compile(br"\nCommit failed"),
re.compile(br"\n\s+Set failed"),
]
terminal_leng... |
akellne/simhash | setup.py | Python | mit | 639 | 0.045383 | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name = 'simhash',
version = '1.8.0',
keywords = ('simhash'),
description = 'A Python implementation of Simhash Algorithm',
license = 'MIT License',
url = 'http://leons.im/posts/a-python-implementation-of-simhash-algorith... | ',
],
| test_suite = "nose.collector",
)
|
EBI-Metagenomics/emgapi | emgapi/migrations/0007_split_run.py | Python | apache-2.0 | 7,178 | 0.002647 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-04-24 08:25
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
def populate_status(apps, schema_editor):
Status = apps.get_model("emgapi", "Status")
st = (
(1, "draft"),
... | ,
field=models.SmallIntegerField(db_column='EXPERIMENT_TYPE_ID', primary_key=True, serialize=False),
),
| migrations.RenameField(
model_name='analysisjob',
old_name='accession',
new_name='external_run_ids',
),
migrations.AlterField(
model_name='analysisjob',
name='external_run_ids',
field=models.CharField(blank=True, db_column='E... |
firesunCN/My_CTF_Challenges | bctf_2017/diary/diary_server/firecms/oauth_client/views.py | Python | gpl-3.0 | 9,288 | 0.01292 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import JsonResponse
from django.http import HttpResponseRedirect
from django.http import Http404, HttpResponse
... | = len(chars) - 1
random = Random()
for i in range(randomlength):
str+=chars[random.randint(0, length)]
return str
@require_http_methods(["GET","POST"])
def report_bugs(request):
if not request.user.is_authenticated:
raise Http404()
if request.method != 'POST':
captcha=ra... | d (request.session['captcha'] == hashlib.md5(request.POST.get('captcha', '')).hexdigest()[0:5]):
captcha=request.session['captcha']
url = request.POST.get('url', '').strip()
if not url.startswith('http://diary.bctf.xctf.org.cn/'):
return render(request, 'report.htm... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.