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 |
|---|---|---|---|---|---|---|---|---|
frappe/erpnext | erpnext/hr/doctype/hr_settings/test_hr_settings.py | Python | gpl-3.0 | 153 | 0.006536 | # | Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
import unittest
class TestHRSettings(unittest.TestCase):
| pass
|
artish/syncsettings | sync_settings/__init__.py | Python | mit | 18 | 0.055556 | fro | m .cli | import * |
cyhmat/pythonDersleri | XOX.py | Python | mit | 8,375 | 0.010988 | from time import sleep
def menu():
try:
sleep(1.5)
print(menuStr)
sleep(0.5)
choose = int(input("For Play = 1\nFor Exit = 0\nChoose : "))
print(stars)
except:
print("There's something wrong about your input. Try again.")
menu()
if choose == 1:
... |
p2Cond.appe | nd(5)
turns(p1,p2)
if x == 2:
if y == 3:
if gamePlany2[2] != "___":
print("Its already taken. Try again...")
makeYourMove()
else:
if turn%2 == 0:
gamePlany2[2] = "X".center(3)
... |
mov-q/dumpy | discariche/model/reallocation.py | Python | gpl-3.0 | 1,137 | 0.009675 | """Person model"""
from sqlalchemy import Column, UniqueConstraint, ForeignKey
from sqlalchemy import schema as saschema
from sqlalchemy.types import Integer, String, Unicode, Float, UnicodeText, DateTime
from discariche.model.meta import Base
class Reallocation(Base):
__tablename__ = "reallocation"
id = Col... | 12), nullable=True)
modder = Column(Integer, saschema.ForeignKey('user.id', onupdate="CASCADE", ondelete | ="SET NULL"))
lastmod = Column(DateTime, nullable=False)
__table_args__ = (
{
"mysql_engine":"InnoDB",
"mysql_charset":"utf8"
}
)
def __init__(self):
pass
def __repr__(... |
jorisroovers/opencv-playground | coin_dectector/coins/detector2.py | Python | apache-2.0 | 7,609 | 0.001051 | import cv2
import cv2.cv
import numpy as np
import time
COLOR_TOLERANCE = 25
# GOLD = (207, 176, 79)
GOLD = (51, 255, 255)
GOLD_MIN = (41, 100, 100)
GOLD_MAX = (61, 255, 255)
# GOLD = (255, 215, 0)
SILVER = (0, 0, int(255 * 0.75))
SILVER_MIN = (0, 0, SILVER[2] * 0.75)
SILVER_MAX = (10, 100, SILVER[2] * 1.25)
# SILV... | cntRsilver = 0
for a in range(0, width):
for b in range(0, height):
if mask[b, a]:
output[b, a] = color_img[b, a]
if mask_gold[b, a]:
cntgold += 1
elif mask_silver[b, a]:... | if maskC[b, a]:
if mask_gold[b, a]:
cntCgold += 1
elif mask_silver[b, a]:
cntCsilver += 1
if maskR1[b, a]:
if mask_gold[b, a]:
cntRgold += 1
... |
davetcoleman/ompl | demos/RigidBodyPlanningWithODESolverAndControls.py | Python | bsd-3-clause | 4,218 | 0.003793 | #!/usr/bin/env python
######################################################################
# Software License Agreement (BSD License)
#
# Copyright (c) 2010, Rice University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that t... | ,
# 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 LIA | BILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
######################################################################
# Author: Mark Moll
from math import sin, co... |
mbokulic/bmt_parser | tests/unit_tests.py | Python | mit | 9,581 | 0 | import unittest
import bmt_parser.collaborators as collabs
import bmt_parser.name_corrections as corr
import pandas as pd
class Test_collabs(unittest.TestCase):
def test_repeat_collab(self):
testdata = {
'issue_id': [1, 1, 1, 2, 2],
'authors': ['a', 'b', 'c', 'a', 'b']
}
... |
'Dr. phil.')
self.assertEqual(corr.get_title_and_rest(
'Profesor Avgust Černigoj')[0],
| 'Prof.')
# without titles
self.assertEqual(corr.get_title_and_rest('Avgust Černigoj')[0],
'')
# testing rest
self.assertEqual(corr.get_title_and_rest('Prof. Avgust Černigoj')[1],
'Avgust Černigoj')
self.assertEqual(co... |
anhstudios/swganh | data/scripts/templates/object/ship/shared_smuggler_warlord_ship_tier5.py | Python | mit | 424 | 0.049528 | #### 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 = Ship()
result.template = "object/ship/shared_smuggler_warlord_ship_tier5.iff"
result.attribute_template_id = -1
... | ND MOD | IFICATIONS ####
return result |
mburakergenc/Malware-Detection-using-Machine-Learning | cuckoo/modules/processing/platform/linux.py | Python | mit | 4,175 | 0.005269 | # Copyright (C) 2010-2013 Claudio Guarnieri.
# Copyright (C) 2014-2016 Cuckoo Foundation.
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.
import os
import logging
import datetime
import re
import dateutil.parser
from lib.cuckoo.common.abstrac... | def __iter__(self):
for event in self.eventstream:
for k, v in self.kwfilters | .items():
if event[k] != v:
continue
del event["type"]
yield event
def __nonzero__(self):
return True
class LinuxSystemTap(BehaviorHandler):
"""Parses systemtap generated plaintext logs (see data/strace.stp)."""
key = "processes... |
byndcivilization/toy-infrastructure | flask-app/config.py | Python | gpl-3.0 | 851 | 0 | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = False
TESTING = False
CSRF_ENABLED = True
SECRET_KEY = os.getenv('APP_SECRET_KEY', '')
# db config
DB_PORT = os.getenv('DB_PORT', '')
DB_HOST = os.getenv('DB_HOST', '')
DB_ROLE = os.getenv('DB_... | DB_ROLE, DB_PASSWORD, DB_HOST, str(DB_PORT), DB_NAME)
|
class ProductionConfig(Config):
DEBUG = False
class StagingConfig(Config):
DEVELOPMENT = True
DEBUG = True
class DevelopmentConfig(Config):
DEVELOPMENT = True
DEBUG = True
class TestingConfig(Config):
TESTING = True
|
TheMutley/openpilot | selfdrive/controls/lib/longitudinal_mpc/libmpc_py.py | Python | mit | 989 | 0.002022 | import os
import subprocess
from cffi import FFI
mpc_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)))
subprocess.check_call(["make", "-j4"], cwd=mpc_dir)
def _get_libmpc(mpc_id):
libmpc_fn = os.path.join(mpc_dir, | "libcommampc%d.so" % mpc_id)
ffi = FFI()
ffi.cdef("""
typedef struct {
double x_ego, v_ego, a_ego, x_l, v_l, a_l;
} state_t;
typedef struct {
double x_ego[21];
double v_ego[21];
double a_ | ego[21];
double j_ego[21];
double x_l[21];
double v_l[21];
double a_l[21];
double cost;
} log_t;
void init(double ttcCost, double distanceCost, double accelerationCost, double jerkCost);
void init_with_simulation(double v_ego, double x_l, double v_l, double a_l, double l);
int run_m... |
DreamSourceLab/DSView | libsigrokdecode4DSL/decoders/edid/__init__.py | Python | gpl-3.0 | 1,316 | 0.009119 | ##
## This file is part of the libsigrokdecode project.
##
## Copyright (C) 2012 Bert Vermeulen <[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 2 of the Lice... | ers to
a Plug and Play ID (PNPID). The list of PNPID assignments is done by Microsoft.
The 'pnpids.txt' file included with this protocol decoder is derived from
the list of | assignments downloadable from that page. It was retrieved in
January 2012.
Details:
https://en.wikipedia.org/wiki/Extended_display_identification_data
http://msdn.microsoft.com/en-us/windows/hardware/gg463195
'''
from .pd import Decoder
|
jschaf/pylint-flask | test/input/func_noerror_flask_ext_long.py | Python | gpl-2.0 | 115 | 0 | '''Ensure | that pylint finds the exported methods from flask.ext.'''
from flask.ext.wtf import Form
MYFORM = Form | |
hagenw/ltfat | mat2doc/mat/release.py | Python | gpl-3.0 | 770 | 0.014286 | print "Creating downloadable package"
# Remove unwanted files
s=os.path.join(conf.t.dir,'testing')
rmrf(s)
os.rmdir(s)
s=os.path.join(conf.t.dir,'timing')
rmrf(s)
os.rmdir(s)
s=os.path.join(conf.t.dir,'reference')
rmrf(s)
os.rmdir(s)
# Recursively remove the .git files
for root, dirs, files in os.walk(conf.t.dir, t... | ributes','.gitignore','desktop.ini']:
os.remove(os.path.join(root, name))
# "bootstrap" the configure files
os.system("cd "+conf.t.dir+"/src; ./bootstrap")
s=os.path.join(conf.t.dir,'src','autom4te.cache')
rmrf(s)
os.rmdir(s)
# Compile the Java classes
os.system("cd "+conf.t.dir+"/blockproc/java; make")... | ava; make classclean")
|
antkillerfarm/antkillerfarm_crazy | python/ml/tensorflow/unit_test/run_list.py | Python | gpl-3.0 | 257 | 0 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import tensorflow as tf
hello | = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print(sess.run(hello))
a = tf.constant(10)
b = tf.constant(32)
c = a + b
d = a - b
run_list = | [c, d]
print(sess.run(run_list))
|
arseneyr/essentia | test/src/unittest/sfx/test_tctototal_streaming.py | Python | agpl-3.0 | 2,098 | 0.001907 | #!/usr/bin/env python
# Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra
#
# This file is part of Essentia
#
# Essentia is fr | ee so | ftware: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation (FSF), 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... |
veltri/DLV2 | tests/parser/bug.69_working.test.py | Python | apache-2.0 | 1,691 | 0.002365 | input = """
% Simplified version of a program by Michael Fink, which segfaults
% with the Jun 11 2001 Release.
object(o1,4).
object(o2,5).
object(o3,17).
bid(1,14).
bid(2,34).
bid(3,14).
contains(1,o1,2).
contains(1,o2,4).
contains(1,o3,2).
contains(2,o3,10).
contains(3,o2,5).
%#maxint=62.
selec... | signed_bidId(1).
:- assigned(B1,I), not assigned_bidId(J), J!=0. %#prec(I,J), !=(J,0), !=(J,#maxint).
%:- nselect(B),bid(B,V). [V:4]
%:- assigned(B,I), contains(B,O,N), #int(S), S=N+I. [S:1]
"""
output = """
% Simplified version of a program by Michael Fink, which segfaults
% with the Jun 11 2001 Relea | se.
object(o1,4).
object(o2,5).
object(o3,17).
bid(1,14).
bid(2,34).
bid(3,14).
contains(1,o1,2).
contains(1,o2,4).
contains(1,o3,2).
contains(2,o3,10).
contains(3,o2,5).
%#maxint=62.
select(B) | nselect(B) :- bid(B,V).
:- nselect(B).
assigned(B,I) :- bid(B,V), I!=0, not nassigned(B,I). %#int... |
danielgarm/Public-Algorithms | LeetCode/0206 - Reverse Linked List.py | Python | mit | 472 | 0.004237 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListN | ode:
current = head
previous = None
while current is no | t None:
temp = current.next
current.next = previous
previous = current
current = temp
return previous
|
tangming2010/gitRepository | we.py | Python | gpl-2.0 | 201 | 0.014925 | import | json
class Student(object):
def __init__(self, name, age, score):
self.name = name
self.age = age
self.score = score
s = Student('Bob', 20, 88)
| print(json.dumps(s)) |
ozdemircili/pycheat | pycheat/api_nmap.py | Python | gpl-3.0 | 2,549 | 0.009023 | # -*- coding: utf-8 -*-
"""
Created on Fri Sep 13 12:10:57 2013
@author: ozdemircili
"""
"""
Install :
pip install python-nmap
"""
import nmap # import nmap.py module
nm = nmap.PortScanner() # instantiate nmap.PortScanner object
nm.scan('127.0.0.1', '22-443') # scan host 127... | # get nmap scan informations {'tcp': {'services': '22-443', 'method': 'connect'}}
nm.all_hosts() # get all hosts tha | t were scanned
for host in nm.all_hosts():
print('----------------------------------------------------')
print('Host : %s (%s)' % (host, nm[host].hostname()))
print('State : %s' % nm[host].state())
for proto in nm[host].all_protocols():
print('----------')
print('Protocol : %s' % proto... |
VitalPet/addons-onestein | hr_absenteeism/__manifest__.py | Python | agpl-3.0 | 776 | 0 | # -*- coding: utf-8 -*-
# Copyright 2016 Onestein (<http://www.onestein.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
'name': "Absence Management",
'summary': """Create time based absence notifications""",
'author': 'Onestein',
'website': 'http://www.onestein.eu',
'ima... |
'aut | o_install': False,
'application': False,
}
|
datalogics/scons | test/LIBS.py | Python | mit | 7,418 | 0.002831 | #!/usr/bin/env python
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
... | 1/SConscript', 'env')
SConscript('sub2/SConscript', 'env')
""")
test.run(arguments = '.')
test.run(program=foo1_exe, stdout='sub1/bar.c\nsub1/baz.c\n')
test.write(['sub1', 'baz.c'], r"""
#include <stdio.h>
void baz()
{
printf("sub1/baz.c 2\n");
}
""")
test.run(arguments = | '.',
stderr='(%s|%s'%(sw, TestSCons.noisy_ar[1:]),
match=TestSCons.match_re_dotall)
#test.fail_test(not test.stderr() in ['', sw, TestSCons.noisy_ar])
test.run(program=foo1_exe, stdout='sub1/bar.c\nsub1/baz.c 2\n')
# Make sure we don't add $LIBPREFIX to library names that
# already have the prefix ... |
jjon/Google-Spreadsheet-python-scripts | GSheet2Python.py | Python | gpl-3.0 | 1,622 | 0.006169 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Takes Google's json encoded spreadsheet and prints a python dictionary keyed by
the values in the first column of the SS. ©2017 J. J. Crump, GNU general public
license
"""
import urllib2
from pprint import pprint
import re
import json
# This is the url of a sample googl... | t = pyDict['feed']['entry']
fields = ["name", "city", "state", "zip"]
SSdict = {}
def parsestring(rowstring, fields):
"""yields tuples of (fieldname, fieldvalue)"""
i = iter(fields[1:])
field = i.next()
start = end = 0
try:
while True:
lastfield = | field
field = i.next()
if rowstring.find(field) == -1:
field = lastfield
continue
end = rowstring.find(field)
yield lastfield, re.sub('^.*?:', '', rowstring[start:end].strip().strip(',')).strip()
start = en... |
nf-dj/cellpilot | drone/scripts/set_led.py | Python | mit | 1,239 | 0.00565 | #!/usr/bin/python
# Copyright (c) 2015 Netforce Co. Ltd.
#
# Permission is hereby granted, free of charge, | to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limita | tion the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or s... |
chienlieu2017/it_management | odoo/addons/account/models/account_move.py | Python | gpl-3.0 | 83,795 | 0.00537 | # -*- coding: utf-8 -*-
import time
from collections import OrderedDict
from odoo import api, fields, models, _
from odoo.osv import expression
from odoo.exceptions import RedirectWarning, UserError, ValidationError
from odoo.tools.misc import formatLang
from odoo.tools import float_is_zero, float_compare
from odoo.to... | Many2one('res.currency', compute='_compute_currency', store=True, string="Currency")
state = fields.Selection([('draft', 'Unposted'), ('posted', 'Posted')], stri | ng='Status',
required=True, readonly=True, copy=False, default='draft',
help='All manually created new journal entries are usually in the status \'Unposted\', '
'but you can set the option to skip that status on the related journal. '
'In that case, they will behave as journal entries ... |
lxml/lxml | src/lxml/tests/test_unicode.py | Python | bsd-3-clause | 7,379 | 0.002035 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import unittest
import sys
from .common_imports import StringIO, etree, HelperTestCase, _str, _bytes, _chr, needs_libxml
try:
unicode
except NameError:
unicode = str
ascii_uni = _bytes('a').decode('utf8')
klingon = _bytes("\\uF8D2").decode("uni... | i, el.attrib['bar'])
def test_unicode_comment(self):
el = etree.Comment(uni)
self.assertEqual(uni, el.text)
def test_unicode_repr1(self):
x = etree.Element(_str('å'))
# must not raise UnicodeEncodeError
repr(x)
def test_unicode_repr2(self):
x = etree.Commen... | tr('\u0131'))
repr(x)
def test_unicode_repr4(self):
x = etree.Entity(_str('ä'))
repr(x)
def test_unicode_text(self):
e = etree.Element('e')
def settext(text):
e.text = text
self.assertRaises(ValueError, settext, _str('ab\ufffe'))
self.asser... |
edx/edx-enterprise | integrated_channels/cornerstone/migrations/0006_auto_20191001_0742.py | Python | agpl-3.0 | 824 | 0.002427 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.23 on 2019-10-01 07:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cornerstone', '0005_auto_20190925_0730'),
]
operations = [
migrations.AddField(
model_name='cornersto... | og UUIDs to transmit.', null=True),
),
migrations.AddField(
model_name='historicalcornerstoneenterprisecustomerc | onfiguration',
name='catalogs_to_transmit',
field=models.TextField(blank=True, help_text='A comma-separated list of catalog UUIDs to transmit.', null=True),
),
]
|
edwardt/pcp | src/python/pcp/pmi.py | Python | lgpl-2.1 | 11,357 | 0.002025 | # pylint: disable=C0103
"""Wrapper module for libpcp_import - Performace Co-Pilot Log Import API
#
# Copyright (C) 2012-2015 Red Hat.
#
# This file is part of the "pcp" module, the python interfaces for the
# Performance Co-Pilot toolkit.
#
# This program is free software; you can redistribute it and/or modify it
# und... | ation; either version 2 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public | License
# for more details.
#
# Example use of this module for creating a PCP archive:
import math
import time
import pmapi
from pcp import pmi
# Create a new archive
log = pmi.pmiLogImport("loadtest")
log.pmiSetHostname("www.abc.com")
log.pmiSetTimezon... |
GanjaNoel/pym2 | wdt/chunk.py | Python | lgpl-3.0 | 2,490 | 0.069478 | #!/usr/bin/python
import struct
import array
class WChunk: #Chunk Basic Class for World Data (like adt,wmo etc.)
def __init__(self):
self.magic = 0
self.size = 0
def unpack(self,f):
self.magic, = struct.unp | ack("i",f.read(4))
self.size, = struct.unpack("i",f.read(4))
self.unpackData(f)
return self
def pack(self):
temp = self.packData()
self.size | = len(temp)
ret = struct.pack("i",self.magic)
ret += struct.pack("i",self.size)
ret += temp
return ret
def unpackData(self,f):
pass
def packData(self):
return 0
class MVER(WChunk):
def __init__(self):
self.magic = 1297499474
self.size = 4
self.version = 18
def unp... |
datacommonsorg/data | scripts/eurostat/regional_statistics_by_nuts/fertility_rate_mother_age/fertility_rate_preprocess_gen_tmcf.py | Python | apache-2.0 | 3,789 | 0.000792 | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | s=[header[0]], inplace=True)
# Remove empty rows, clean values to have all digits.
df | = df[df.value.str.contains('[0-9]')]
possible_flags = [' ', ':']
for flag in possible_flags:
df['value'] = df['value'].str.replace(flag, '')
df['value'] = pd.to_numeric(df['value'])
df = df.pivot_table(values='value',
index=['geo', 'time'],
colum... |
SafeSlingerProject/SafeSlinger-AppEngine | safeslinger-messenger/python/apns_enhanced.py | Python | mit | 28,130 | 0.00583 | # PyAPNs was developed by Simon Whitaker <[email protected]>
# Source available at https://github.com/simonwhitaker/PyAPNs
#
# PyAPNs is distributed under the terms of the MIT license.
#
# Copyright (c) 2011 Goo Software Ltd
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# thi... | except ssl.SSLError, err:
if ssl.SSL_ERROR_WANT_READ == err.args[0]:
select.select([self._ssl], [], [])
elif ssl.SSL_ERROR_WANT_WRITE == err.args[0]:
select.select([], [self._ssl], [])
| else:
raise
else:
# Fallback for 'SSLError: _ssl.c:489: The handshake operation timed out'
for i in xrange(3):
try:
self._ssl = wrap_socket(self._socket, server_side=False, keyfile=StringIO.StringIO(self.key... |
kbrose/project_euler | p120-129/p123.py | Python | unlicense | 347 | 0.023055 | import primes
# same logic as p120
# I was hoping since these were primes that
# maybe | Fermat's Little Theorem would show up
# ... but it didn't.
def check(p,n,target):
return 2*p*n > target
def main():
ps = primes.primes(250000)
| i = 0
while not check(ps[i],i+1,10**10):
i += 2
print i+1 # zero indexing, yo
main()
|
MSusik/invenio | invenio/ext/sqlalchemy/__init__.py | Python | gpl-2.0 | 7,341 | 0.003678 | # -*- coding: utf-8 -*-
#
## This file is part of Invenio.
## Copyright (C) 2011, 2012, 2013, 2014 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 (... | sting': True,
'extend_exis | ting': False,
'mysql_engine': 'MyISAM',
'mysql_charset': 'utf8'}
_include_sqlalchemy(self, engine=engine)
def __getattr__(self, name):
# This is only called when the normal mechanism fails, so in practice
... |
open-dynaMIX/experms | src/experms/restore.py | Python | gpl-3.0 | 435 | 0 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
from collect_filenames import collect
from action.prepare_files import prepare
def restore(config, debug):
"""
Restores all the ownerships and permissions on all files
| """
filenames = collect(config)
for item in filenames[0]:
prepare(item, 'RESTORE', T | rue, config, debug)
for item in filenames[1]:
prepare(item, 'RESTORE', False, config, debug)
|
hbiyik/tribler | src/tribler-core/tribler_core/modules/metadata_store/serialization.py | Python | lgpl-3.0 | 16,048 | 0.002555 | import struct
from datetime import datetime, timedelta
from ipv8.database import database_blob
from ipv8.keyvault.crypto import default_eccrypto
from ipv8.messaging.payload import Payload
from ipv8.messaging.serialization import default_serializer
from tribler_core.exceptions import InvalidSignatureException
from tri... | data_type = metadata_type
self.reserved_ | flags = reserved_flags
self.public_key = bytes(public_key)
self.signature = bytes(kwargs["signature"]) if "signature" in kwargs and kwargs["signature"] else None
# Special case: free-for-all entries are allowed to go with zero key and without sig check
if "unsigned" in kwargs and kwargs... |
myevan/flask_server | examples/websocket_server.py | Python | mit | 278 | 0.007194 | from flask import Flask
from flask_sockets import Sockets
app = Flask(__name__)
sockets = Sockets(app)
@sockets.route('/echo')
def echo_socket(ws):
while True:
message | = ws.receive()
ws.send(message)
@app.route('/' | )
def hello():
return 'Hello World!'
|
carquois/blobon | blobon/posts/migrations/0004_auto__del_blog__add_blogpost.py | Python | mit | 6,130 | 0.00783 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting model 'Blog'
db.delete_table('posts_blog')
# Adding model 'BlogPost'
db.create_t... | 'groups': ('django.db | .models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('... |
jjoaonunes/namebench | libnamebench/tk.py | Python | apache-2.0 | 13,586 | 0.007434 | # Copyright 2009 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... |
enable_button=None, debug=False):
self.message = message
self.error = error
self.count = count
self.debug = debug
| self.total = total
self.enable_button = enable_button
class WorkerThread(threading.Thread, base_ui.BaseUI):
"""Handle benchmarking and preparation in a separate UI thread."""
def __init__(self, supplied_ns, global_ns, regional_ns, options, data_source=None, master=None,
backup_notifier=None)... |
mattjmorrison/ReportLab | tests/test_rl_accel.py | Python | bsd-3-clause | 6,284 | 0.021801 | __version__=''' $Id'''
__doc__='''basic tests.'''
from reportlab.lib.testutils import setOutDir,makeSuiteForClasses, printLocation
setOutDir(__name__)
import unittest
def getrc(defns,depth=1):
from sys import getrefcount, _getframe
f = _getframe(depth)
G0 = f.f_globals
L = f.f_locals
if L is not G... | _sameFrag(b,a)==0, "_sameFrag(%s,%s)!=0" % (b,a)
delattr(b,name)
assert _sameFrag(a,b)==1, "_sameFrag(%s,%s)!=1" % (a,b)
assert _sameFrag(b,a)==1, "_sameFrag(%s,%s)!=1" % (b,a)
setattr(a,name,old)
setattr(b,name,old)
def makeSuite():
# only run the tests ... | ass(unittest.TestCase):
pass
return makeSuiteForClasses(Klass)
#noruntests
if __name__ == "__main__":
unittest.TextTestRunner().run(makeSuite())
printLocation()
|
ahcub/hokey_prediction_app | setup.py | Python | bsd-3-clause | 578 | 0.00346 | from distutils.core import setup
import py2exe
import sys
from os.path import join, dirname
setup(
windows=[{"script": "hockey_prediction_app.py", "icon_resources": [(1, join(dirname(sys.argv[0]), 'hokey.ico'))]}],
options={"py2exe": {"includes": ["sip", 'lxml.etree', 'lxml._elementpath', 'gzip', 'pandas', 'nu... | },
requires=['requests', 'lxml', 'PyQt4', 'pandas'],
data_files=[('.', [join(dirname(sys.argv[0]), 'up.png')]), |
('.', [join(dirname(sys.argv[0]), 'down.png')]),
('.', [join(dirname(sys.argv[0]), 'hokey.png')])])
|
collective/zettwerk.clickmap | zettwerk/clickmap/__init__.py | Python | gpl-2.0 | 401 | 0.004988 | from zope.i18nmessageid import MessageFactory
clickmapMessageFactor | y = MessageFactory('zettwerk.clickmap')
import ClickmapTool
from Products.CMFCore import utils
def initialize(context):
| """Initializer called when used as a Zope 2 product."""
utils.ToolInit('Zettwerk Clickmap', tools=(ClickmapTool.ClickmapTool,),
icon='z.png'
).initialize(context)
|
lesina/labs2016 | Laba05/exercise04.py | Python | gpl-3.0 | 127 | 0.007874 | k = list(map(int, input().split()))
t = int(inp | ut())
for i in range(t):
k = k[:-k[-1]-1] + k[-1:] | + k[-k[-1]-1:-1]
print(k) |
Brazelton-Lab/lab_scripts | 16S/tax_summary_edit.py | Python | gpl-2.0 | 1,875 | 0.018133 | #! /usr/bin/env python
"""
edits mothur taxonomy summary file
transfers last name that is not "unclassified" or "uncultured" to "unclassified" or "uncultured" assignment
make sure that the file has default sorting (by rankID)
Copyright:
tax_summary_edit edits mothur taxonomy summary file
Copyright (C) 2016... | TABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should hav | e received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import sys
infilename = sys.argv[1]
outfilename = infilename + '.renamed.txt'
outfile = open(outfilename,'a')
infile = open(infilename)
for line in infile:
if "unclassified" in line:
co... |
ratschlab/ASP | examples/undocumented/python_modular/features_snp_modular.py | Python | gpl-2.0 | 462 | 0.04329 | parameter_list=[['../data/snps.dat']]
def features_snp_m | odular(fname):
from shogun.Features import StringByteFeatures, SNPFeatures, SNP
sf=StringByteFeatures(SNP)
sf.load_ascii_file(fname, False, SNP, SNP)
#print(sf.get_feature | s())
snps=SNPFeatures(sf)
#print(snps.get_feature_matrix())
#print(snps.get_minor_base_string())
#print(snps.get_major_base_string())
if __name__=='__main__':
print('SNP Features')
features_snp_modular(*parameter_list[0])
|
Yangqing/caffe2 | caffe2/python/crf.py | Python | apache-2.0 | 15,115 | 0.000265 | # Copyright (c) 2016-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | to='int32')
t_range = self.model.net.LengthsRangeFill(length)
padding = self.model.net.ConstantFill([t_range], value=low_score)
padding = self.model.net.ExpandDims(padding, dims=[1])
padded_predictions, _ = self.model.net.Concat(
[predictions, padding, padding],
o... | oncat(
[b_scores, padded_predictions, e_scores],
outputs=2,
axis=0
)
return padded_predictions_concat
def _pad_labels(self, labels):
bos_i = self.num_classes
eos_i = self.num_classes + 1
bos_i_b = self.model.param_init_net.ConstantFill(
... |
mguijarr/mxcube3 | mxcube3/routes/Queue.py | Python | gpl-2.0 | 17,319 | 0.001559 | import json
import logging
import signals
import queue_model_objects_v1 as qmo
import queue_entry as qe
import QueueManager
from flask import Response, jsonify, request, session
from mxcube3 import app as mxcube
from mxcube3 import socketio
from . import qutils
qm = QueueManager.QueueManager('Mxcube3')
@mxcube.rou... | ct, status code set to:
200: On success
409: Queue could not be started
"""
logging.getLogger('HWR').info('[QUEUE] Queue going to start')
try:
mxcube.queue.queue_hwobj.set_pause(False)
mxcube.queue.queue_hwobj.execute()
except Exception as ex:
signals... | tatus=200)
@mxcube.route("/mxcube/api/v0.1/queue/stop", methods=['PUT'])
def queue_stop():
"""
Stop execution of the queue.
:returns: Response object status code set to:
200: On success
409: Queue could not be stopped
"""
mxcube.queue.queue_hwobj.stop()
return Resp... |
tjguk/networkzero | networkzero/__init__.py | Python | mit | 1,846 | 0.002709 | # -*- coding: utf-8 -*-
"""Easy network discovery & messaging
Aimed at a classrom or club situation, networkzero makes it simpler to
have several machines or several processes on one machine discovering
each other and talking across a network. Typical examples would include:
* Sending commands to a robot
* Sending sc... | ro as nw0
address = nw0.advertise("data-logger")
while True:
#
# ... do stuff
#
nw0.send_news_to(address, "data", ...)
::
[Computer 2, 3, 4...]
import networkzero as nw0
logger = nw0.discover("data-logger")
while True:
topic, data = nw0.wait_fo... | database etc.
#
"""
from .core import (
NetworkZeroError, SocketAlreadyExistsError,
SocketTimedOutError, InvalidAddressError,
SocketInterruptedError, DifferentThreadError,
address, action_and_params,
string_to_bytes, bytes_to_string
)
from .discovery import advertise, discover, discov... |
areeda/gwpy | examples/miscellaneous/range-spectrogram.py | Python | gpl-3.0 | 2,377 | 0.000421 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) Alex Urban (2019-2020)
#
# This file is part of GWpy.
#
# GWpy 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
... | et_title('LIGO-Livingston sensitivity to BNS around GW170817')
ax.set_epoch(1187008882) # <- set 0 on plot to GW170817
ax.colorbar(cmap='cividis', clim=(0, 16),
label='BNS range amplitude spectral density '
r | '[Mpc/$\sqrt{\mathrm{Hz}}$]')
plot.show()
# Note, the extreme dip in sensitivity near GW170817 is caused by a
# loud, transient noise event, see `Phys. Rev. Lett. vol. 119, p.
# 161101 <http://doi.org/10.1103/PhysRevLett.119.161101>`_ for more
# information.
|
whiteclover/solo | samples/web.py | Python | gpl-2.0 | 609 | 0.003284 | #!/usr/bin/env python
from solo.web.server import WebServer
from solo.web.app import App
class HelloRoot(object):
def index(self):
return "Hello World!"
def page(self, page):
return page
c | lass HelloApp(App):
def initialize(self):
ctl = HelloRoot()
route = self.route()
route.mapper.explicit = False
route.connect('index', '/', controller=ctl, action='index')
route.connect('page', '/page/:page', controller=ctl, action='page')
if __name__ == '__main__':
app... | WebServer(('127.0.0.1', 8080), app, log=None).start()
|
behrtam/xpython | exercises/simple-cipher/simple_cipher_test.py | Python | mit | 2,258 | 0.001771 | import re
import unittest
from simple_cipher import Cipher
# Tests adapted from `problem-specifications//canonical-data.json` @ v2.0.0
class RandomKeyCipherTest(unittest.TestCase):
def test_can_encode(self):
cipher = Cipher()
plaintext = "aaaaaaaaaa"
self.assertEqual(cipher.encode(plaint... | cipher = Cipher("abcdefghij")
plaintext = "zzzzzzzzzz"
self.assertEqual(cipher.encode(plaintext), "zabcdefghi")
def test_can_wrap_on_decode(self):
cipher = Cipher("abcdefghij")
self.assertEqual(cipher.decode("zabcdefghi"), "zzzzzzzzzz")
def te | st_can_encode_messages_longer_than_the_key(self):
cipher = Cipher("abc")
plaintext = "iamapandabear"
self.assertEqual(cipher.encode(plaintext), "iboaqcnecbfcr")
def test_can_decode_messages_longer_than_the_key(self):
cipher = Cipher("abc")
self.assertEqual(cipher.decode("ibo... |
kdart/pycopia | XML/pycopia/XML/DTD.py | Python | apache-2.0 | 8,510 | 0.00282 | #!/usr/bin/python2.7
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
# 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
... | keywordname = keyword_identifier(normalize_unicode(a_name))
fwdkwattribs[keywordname] = ident
else:
self._add_element_attlist(element, attr, ident)
def _add_element_attlist(self, element, xmlattribute, ident):
try:
attrmap = element.get_attribute("ATTRIBUTE... | bute("KWATTRIBUTES")
except KeyError:
element.add_attribute("ATTRIBUTES", AttributeMap())
element.add_attribute("KWATTRIBUTES", AttributeMap())
attrmap = element.get_attribute("ATTRIBUTES")
kwattrmap = element.get_attribute("KWATTRIBUTES")
attrmap[xmlattri... |
fadiga/mstock | tools/periods.py | Python | apache-2.0 | 8,621 | 0.001163 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Maintainer: Fad
from datetime import date, timedelta
from calendar import monthrange
def get_week_boundaries(year, week):
"""
Retoure les date du premier et du dernier jour de la semaine dont
on a le numéro.
"""
d = date(year, 1, 1)
if(... | ear()
# def next_year(self):
# current_date = date(self.year, 1, 1)
# # la date de l'année après celle qu'on affiche
# return date(current_date.year + 1, current_date.month,
# current_date.day)
# def previous_year(self):
... | te.year - 1, current_date.month,
# current_date.day)
# TODO: faire de ce mamouth un middleware ou un context processor
def get_time_pagination(year, duration, duration_number):
"""
navigation entre les dates année, mois, week
"""
todays_... |
Chuban/moose | gui/utils/YamlData.py | Python | lgpl-2.1 | 1,666 | 0.002401 | #!/usr/bin/python
import sys, os, commands, time, re, copy
try:
from PyQt4 import QtCore, QtGui
QtCore.Signal = QtCore.pyqtSignal
QtCore.Slot = QtCore.pyqtSlot
except ImportError:
try:
from PySide import QtCore, QtGui
QtCore.QString = str
except ImportError:
raise ImportErro... | syntax.GetSyntax(recache)
def recursiveYamlDataSearch(self, path, current_yaml):
if current_yaml['name'] == path:
return current_yaml
else:
if current_yaml['subblo | cks']:
for child in current_yaml['subblocks']:
yaml_data = self.recursiveYamlDataSearch(path, child)
if yaml_data: # Found it in a child!
return yaml_data
else: # No children.. stop recursion
return None
d... |
hxer/exercise | scapy/scanwifi.py | Python | gpl-2.0 | 1,014 | 0.00108 | # -*- coding: utf-8 -*-
"""
扫描周围无线网络,列出SSID and mac address
开启网卡监听模式(mon),侦听无线网络流量
开启/关闭 监听模式
>sud | o airmon-ng start/stop wlan0
找回网络管理图标
>NetworkManager start
"""
import sys
from scapy.all import *
from argparse import ArgumentParser
def packet_handler(pkt):
ap_list = []
if pkt.haslayer(Dot11):
if pkt.type == 0 and pkt.subtype == 8:
# filter mac address
if pkt.addr2 not i... | python {prog} <interface>\n".format(prog=sys.argv[0])
usage += "\te.g. python {prog} wlan0mon".format(prog=sys.argv[0])
parser = ArgumentParser(usage=usage)
parser.add_argument('interface', help="the interface needed to monitor")
args = parser.parse_args()
iface = args.interface
sniff(iface=iface, prn=packet_handler)
|
rowanv/finders_keepers | finders_keepers/settings.py | Python | apache-2.0 | 2,931 | 0 | """
Django settings for finders_keepers project.
Generated by 'django-admin startproject' using Django 1.8.4.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Bu... | iewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddlewar... | ': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages'... |
LLNL/spack | lib/spack/spack/test/llnl/util/tty/tty.py | Python | lgpl-2.1 | 3,017 | 0 | # 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)
import os
import pytest
import llnl.util.tty as tty
def test_get_timestamp(monkeypatch):
"""Ensure the results of ... | in output
])
def test_info(capfd, monkeypatch, msg, trace, wrap):
"""Ensure the output from info with options is appropriate."""
# temporarily use the parameterized settings
monkeypatch.setattr(tty, | '_stacktrace', trace)
expected = [msg if isinstance(msg, str) else 'Exception: ']
if trace:
expected.insert(0, '.py')
extra = 'This extra argument *should* make for a sufficiently long line' \
' that needs to be wrapped if the option is enabled.'
args = [msg, extra]
num_newlines ... |
LLNL/spack | var/spack/repos/builtin/packages/py-deeptools/package.py | Python | lgpl-2.1 | 1,792 | 0.002232 | # 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 PyDeeptools(PythonPackage):
"""deepTools addresses the challenge of handling the large amo... | ca307fe6ec5e156750389fdfa4324bf0dd6bf5f53d5fda109358 | ')
version('3.2.1', sha256='dbee7676951a9fdb1b88956fe4a3294c99950ef193ea1e9edfba1ca500bd6a75')
version('2.5.2', sha256='16d0cfed29af37eb3c4cedd9da89b4952591dc1a7cd8ec71fcba87c89c62bf79')
depends_on('[email protected]:', type=('build', 'run'))
depends_on('py-setuptools', type='build')
depends_on('py-numpy@... |
DavideCanton/Python3 | ping/pyng.py | Python | gpl-3.0 | 6,649 | 0.00015 | __author__ = "davide"
import struct
import socket
import argparse
import sys
from datetime import datetime
import time
from collections import defaultdict
from signal import signal, SIGINT, SIG_IGN
ICMP_ECHO_REQUEST = 8, 0
ICMP_ECHO_RESPONSE = 0, 0
__all__ = ["ICMPPacket", "Pinger",
"ICMP_ECHO_REQUEST", "... | return struct.pack("!BBH{}s".format(len(self._data)),
self._type[0], self._type[1],
self._checksum, self._data)
@staticmethod
def buildPacket(raw):
"""Builds an ICMPPacket from the string raw
( | received from a pong), returns (IP Header (raw), ICMP Packet)"""
ihl = (raw[0] & 0x0F) << 2
ip_header, raw_packet = raw[:ihl], raw[ihl:]
format_len = len(raw_packet) - 4
unpacked = struct.unpack("!BBH{}s".format(format_len), raw_packet)
packet = ICMPPacket(unpacked[:2], unpacked[... |
Aquaio/aqua-io-python | setup.py | Python | mit | 1,417 | 0 | import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name='aqua-io',
version='0.1.0',
description='Official Aqua.io API library client for Python',
author='Michael Carroll / Aqua.io',
author_email='[email protected]',
url='htt... | 'meaningful use',
'healthcare',
'health',
'EHR',
'EMR',
'medicine',
'medical'
],
license='MIT',
install_requires=[
'requests > | = 2.1.0'
],
packages=[
'aqua_io',
'aqua_io.api',
'aqua_io.error',
'aqua_io.http_client'
],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating ... |
apache/steve | pysteve/lib/voter.py | Python | apache-2.0 | 3,304 | 0.006659 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | ism found"}
def email(rcpt, subject, message):
sender = config.get("email", "sender")
signature = config.get("email", "signature")
receivers = [rcpt]
# py 2 vs 3 conversion
if type(message) is bytes:
| message = message.decode('utf-8', errors='replace')
msg = u"""From: %s
To: %s
Subject: %s
%s
With regards,
%s
--
Powered by Apache STeVe - https://steve.apache.org
""" % (sender, rcpt, subject, message, signature)
msg = msg.encode('utf-8', errors='replace')
try:
smtpObj = smtplib.SMTP(config.get("e... |
RamonAranda/ConfusionMatrix | lib/formatter/src/_formatter.py | Python | mit | 3,826 | 0.001307 | from pyrsistent import pvector
from toolz import pipe
from toolz.curried import reduce, map
from toolz.dicttoolz import iterkeys, itervalues
from lib.value_objects.src.string_value_object import StringValueObject
__WHITESPACE = StringValueObject(" ")
__VERTICAL_SEPARATOR = StringValueObject("|")
__LINE_BREAK = String... | (data, max_length_per_column)
return StringValueObject(separator + headers + separator + rows)
def __calculate_max_str_length_per_column(data):
def __calculate_max_column_length(column_key):
max_value_length = pipe(
data,
iterkeys,
map(lambda key: data[key][column_k... | max(max_value_length, len(str(column_key)))
max_values_column_length = pipe(
data,
itervalues,
__first,
iterkeys,
map(__calculate_max_column_length),
pvector
)
max_key_length = pipe(
data, iterkeys, map(str), map(len), pvector, max, lambda x: [x], pvec... |
KRHS-GameProgramming-2016/Spoonghetti-Man | Player.py | Python | mit | 4,204 | 0.009039 | import pygame, sys, math
from Meatball import *
class Player(Meatball):
def __init__(self, maxSpeed =5 , pos=[10,10]):
Meatball.__init__(self, pos, None)
size = [45,45]
self.maxSpeed = maxSpeed
self.images = [pygame.transform.scale(pygame.image.load("rsc/ball/SpoonerF.png"), si... | pygame.transform.scale(pygame.image.load("rsc/ball/SpoonerF(6).png"), size),
pygame.transform.scale(pygame.image.load("rsc/ball/SpoonerF(7).png"), size),
pygame.transform.scale(pygame.image.load("rsc/ball/SpoonerF(6).png"), size),
pygame.transform.sc... | pygame.transform.scale(pygame.image.load("rsc/ball/SpoonerF(4).png"), size),
pygame.transform.scale(pygame.image.load("rsc/ball/SpoonerF(3.1).png"), size),
pygame.transform.scale(pygame.image.load("rsc/ball/SpoonerF(2).png"), size),
... |
robertwbrandt/zarafa | zarafa-tools/plugins/movetopublic.py | Python | gpl-2.0 | 3,569 | 0.006444 | import MAPI
from MAPI.Util import *
from MAPI.Time import *
from MAPI.Struct import *
from plugintemplates import *
import zconfig
class MoveToPublic(IMapiDAgentPlugin):
prioPreDelivery = 50
configfile = '/etc/zarafa/movetopublic.cfg'
def __init__(self, logger):
self.rulelist = {}
... | )
# scan max for 100 settings
for i in range(1, 100, 1):
try:
data = config.getdict('rule'+str(i), ['recipient', 'destination_folder'])
self.rulelist[data['recipien | t'].lower()] = data['destination_folder']
except:
break
self.logger.logDebug("*--- Rule list %s" % self.rulelist)
def PreDelivery(self, session, addrbook, store, folder, message):
props = message.GetProps([PR_RECEIVED_BY_EMAIL_ADDRESS_W], 0)
if props[0].ulPropT... |
app-git-hub/SendTo | examples/save.py | Python | mit | 481 | 0.035343 | import sublime, sublime_plugin
class SaveAllExistingFilesCommand(sublime_plugin.ApplicationCommand):
| def run(self):
for w in sublime.windows():
self._save_files_in_window(w)
def _save_files_in_window(self, w):
for v in w.views():
self._save_existing_file_in_view(v)
def _save_existing_file_in_view(self, v):
if v.file_name() and v.is_dirty():
v.run_command("save")
r"""
append to file sublime plug... | stackoverflow
""" |
fenderglass/ABruijn | flye/trestle/trestle.py | Python | bsd-3-clause | 138,871 | 0.002463 | #(c) 2016-2018 by Authors
#This file is a part of Flye program.
#Released under the BSD license (see LICENSE file)
"""
Created on Wed Jan 4 03:50:31 2017
@author: jeffrey_yuan
"""
from __future__ import absolute_import
from __future__ import division
import os
import logging
from itertools import combinations, prod... | rker,
args=(func_args, log_file,
| results_queue, error_queue)))
signal.signal(signal.SIGINT, orig_sigint)
for t in threads:
t.start()
try:
for t in threads:
t.join()
if t.exitcode == -9:
logger.error("Looks l... |
mhugent/Quantum-GIS | python/plugins/processing/algs/admintools/CreateWorkspace.py | Python | gpl-2.0 | 2,079 | 0 | # -*- coding: utf-8 -*-
"""
***************************************************************************
CreateWorkspace.py
---------------------
Date : October 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
**********************... | GeoServerToolsAlgorithm
from processing.parameters.ParameterString import ParameterString
from processing.outputs.OutputString import OutputString
class CreateWorkspace(GeoServerToolsAlgorithm):
WORKSPACE = 'WORKSPACE'
WORKSPACEURI = 'WORKSPACEURI'
def processAlgorithm(self, progress):
| self.createCatalog()
workspaceName = self.getParameterValue(self.WORKSPACE)
workspaceUri = self.getParameterValue(self.WORKSPACEURI)
self.catalog.create_workspace(workspaceName, workspaceUri)
def defineCharacteristics(self):
self.addBaseParameters()
self.name = 'Create... |
jburos/survivalstan | test/test_exp_survival_model.py | Python | apache-2.0 | 1,679 | 0.032162 |
import matplotlib as mpl
mpl.use('Agg')
import survivalstan
from stancache import stancache
import numpy as np
from nose.tools import ok_
from functools import partial
num_iter = 1000
from .test_datasets import load_test_dataset
model_code = survivalstan.models.exp_survival_model
make_inits = None
def test_model():
... | _dataset()
testfit = survivalstan.fit_stan_survival_model(
model_cohort = 'test model',
model_code = model_code,
df = d,
time_col = 't',
event_co | l = 'event',
formula = 'age + sex',
iter = num_iter,
chains = 2,
seed = 9001,
make_inits = make_inits,
FIT_FUN = stancache.cached_stan_fit,
)
ok_('fit' in testfit)
ok_('coefs' in testfit)
ok_('loo' in testfit)
survivalstan.utils.plot_coefs([testfit... |
georgeyk/loafer | loafer/runners.py | Python | mit | 1,955 | 0.000512 | import asyncio
import logging
import signal
from concurrent.futures import CancelledError, ThreadPoolExecutor
from contextlib import suppress
logger = logging.getLogger(__name__)
class LoaferRunner:
def __init__(self, max_workers=None, on_stop_callback=None):
self._on_stop_callback = on_stop_callback
... | logger.debug('loop.is_running={}'.format(self.loop.is_running()))
logger.debug('loop.is_closed={}'.format(self.loop.is_closed()))
def prepare_stop(self, *args):
if self.loop.is_running():
# signals loop.run_forever to exit in the next iteration
self.loop.stop()
... | stop_callback()
logger.info('cancel schedulled operations ...')
for task in asyncio.Task.all_tasks(self.loop):
task.cancel()
if task.cancelled() or task.done():
continue
with suppress(CancelledError):
self.loop.run_until_complete(task... |
Heteroskedastic/chills-pos | chills_pos/pos/management/__init__.py | Python | mit | 1,041 | 0 | from django.db.models.signals import post_migrate
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import Permission
def add_view_permissions(sender, **kwargs):
"""
This syncdb hooks takes care of adding a view permission too all our
content types.
"""
# f... | codename=codename):
# add it
Permission.objects.create(content_type=content_type,
codename=codename,
name="Can view %s" % content_type.name)
print("Added view permission for %s" % content_typ... | |
denny820909/builder | lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_config.py | Python | mit | 43,114 | 0.00501 | # This file is part of Buildbot. Buildbot 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, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... | pen configuration | file .*: error_msg"),
lambda : config.MasterConfig.loadConfig(
self.basedir, self.filename))
@compat.usesFlushLoggedErrors
def test_loadConfig_parse_error(self):
self.install_config_file('def x:\nbar')
self.assertRaisesConfigError(
re.compile("error whil... |
hanamvu/C4E11 | SS3/clothes_shop.py | Python | gpl-3.0 | 1,117 | 0.038496 | clouthes = ["T-Shirt","Sweater"]
print("Hello, welcome to my shop\n")
while (True):
comment = input("Welcome to our shop, what do you want (C, R, U, D)? ")
if comment.upper()=="C":
new_item = input("Enter new item: ")
clouthes.append(new_item.capitalize())
elif comment.upper()=="R":
print(end='')
elif comment... | = int(input("Delete position? "))
if pos <= len(c | louthes):
clouthes.pop(pos-1)
else:
print("Sorry, your item is out of sale!")
else:
print("Allahu akbar! We're in reconstructing and can't serve you. See you again!")
# items =[", "+clouthe for clouthe in clouthes if clouthes.index(clouthe)>0]
# items.insert(0,clouthes[0])
# print("Our items: {0}".format... |
jbaiter/beets | test/test_mediafile.py | Python | mit | 9,378 | 0.001493 | # This file is part of beets.
# Copyright 2013, Adrian Sampson.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, ... | e the temporary file
def test_corrupt_mp3_raises_unreadablefileerror(self):
# Make sure we catch Mutagen reading errors appropriately.
self._exccheck('corrupt.mp3', beets.mediafile.UnreadableFileError)
def test_corrupt_mp4_raises_unreadablefileerror(self):
self._exccheck('corrupt.m4a',... | pt_flac_raises_unreadablefileerror(self):
self._exccheck('corrupt.flac', beets.mediafile.UnreadableFileError)
def test_corrupt_ogg_raises_unreadablefileerror(self):
self._exccheck('corrupt.ogg', beets.mediafile.UnreadableFileError)
def test_invalid_ogg_header_raises_unreadablefileerror(self):
... |
ychen820/microblog | y/google-cloud-sdk/platform/google_appengine/lib/django-1.3/django/contrib/staticfiles/finders.py | Python | bsd-3-clause | 9,183 | 0.000653 | import os
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.files.storage import default_storage, Storage, FileSystemStorage
from django.utils.datastructures import SortedDict
from django.utils.functional import memoize, LazyObject
from django.utils.importlib impo... | urn match
matches.append(match)
return matches
def find_in_app(self, app, path):
"""
Find a requested static file in an app's static locations.
"""
storage = self.storages.get(app, None)
if storage:
if storage.prefix:
prefi... | one
path = path[len(prefix):]
# only try to find a file if the source dir actually exists
if storage.exists(path):
matched_path = storage.path(path)
if matched_path:
return matched_path
class BaseStorageFinder(BaseFinder):
... |
maartenbreddels/vaex | .releash.py | Python | mit | 3,029 | 0.006933 | from releash import *
# these objects only tag when they are exe
gitpush = ReleaseTargetGitPush()
# core package
core = add_package("packages/vaex-core", "vaex-core")
version_core = VersionSource(core, '{path}/vaex/core/_version.py')
gittag_core = ReleaseTargetGitTagVersion(version_source=version_core, prefix='core-v'... | argets.appen | d(gitpush)
#if name in ['hdf5', 'viz']:
if name == 'meta':
package.release_targets.append(ReleaseTargetCondaForge(package, '../feedstocks/vaex' + '-feedstock'))
else:
package.release_targets.append(ReleaseTargetCondaForge(package, '../feedstocks/vaex-' + name + '-feedstock'))
|
kingvuplus/EGAMI-D | lib/python/Plugins/Extensions/PicturePlayer/ui.py | Python | gpl-2.0 | 21,962 | 0.027138 | from boxbranding import getMachineBrand
from enigma import ePicLoad, eTimer, getDesktop, gMainDC, eSize
from Screens.Screen import Screen
from Tools.Directories import resolveFilename, pathExists, SCOPE_MEDIA, SCOPE_ACTIVE_SKIN
from Components.Pixmap import Pixmap, MovingPixmap
from Components.ActionMap import Actio... | "MenuActions"],
{
"cancel": self.keyCancel,
"save": self.keySave,
"ok": self.keySave,
"menu": self.clo | seRecursive,
}, -2)
self["key_red"] = StaticText(_("Cancel"))
self["key_green"] = StaticText(_("OK"))
self.createSetup()
self.onLayoutFinish.append(self.layoutFinished)
def layoutFinished(self):
self.setTitle(self.setup_title)
def createSetup(self):
setup_list = [
getConfigListEntry(_("Slide show ... |
timj/scons | test/SConscript/Return.py | Python | mit | 2,480 | 0.000806 | #!/usr/bin/env python
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
... | onstruct', """\
SConscript('SConscript1')
x = SConscript('SConscript2')
y, z = SConscript('SConscript3')
a4, b4 = SConscript('SConscript4')
foo, bar = SConscript('SConscript5')
print ("x =", x)
print ("y =", y)
print ("z =", z)
print ("a4 =", a4)
print ("b4 =", b4)
print ("foo =", foo)
print ("bar =", bar)
""")
test.w... | t3', """\
print ("line 5")
y = 8
z = 9
Return('y z')
print ("line 6")
""")
test.write('SConscript4', """\
a4 = 'aaa'
b4 = 'bbb'
print ("line 7")
Return('a4', 'b4', stop=False)
b4 = 'b-after'
print ("line 8")
""")
test.write('SConscript5', """\
foo = 'foo'
bar = 'bar'
Return(["foo", "bar"])
print ("line 9")
""")
expe... |
FRidh/python-acoustics | acoustics/quantity.py | Python | bsd-3-clause | 2,707 | 0.008866 | """
Quantities and units
====================
The Quantity module provides two classes to work with quantities and units.
. | . inheritance-diagram:: acoustics.quantity
"""
from acoustics.standards.iso_tr_25417_2007 import REFERENCE_PRESSURE
quantities = {
'pressure' : ('Pressure', 'pascal', True, 'p', '$p$', REFERENCE_PRESSURE)
}
"""
Dictionary with quantities. Each quantity is stored as a tuple.
"""
units = {
'meter' : ('met... | }
"""
Dictionary with units. Each unit is stored as a tuple.
"""
class Unit(object):
"""
Unit of quantity.
.. note:: Perhaps inherit from tuple or :class:`collections.namedTuple`?
"""
def __init__(self, name, symbol, symbol_latex):
self.name = name
"""
Nam... |
eriknw/eqpy | eqpy/tests/test_nums.py | Python | bsd-3-clause | 747 | 0 | import eqpy
import sympy
from eqpy._utils import raises
def test_constants():
assert eqpy.nums.Catalan is sympy.Catalan
assert eqpy.nums.E is sympy.E
assert eqpy.nums.EulerGamma is sympy.EulerGamma
assert eqpy.nums.GoldenRatio is sympy.GoldenRatio
assert eqpy.nums.I is sympy.I
assert eqpy.nums... | ') == sympy.S('2/3')
assert raises(sympy.SympifyError, lambda: eqpy.nums('1.2.3'))
def test_dunders():
eqpy.nums.__mydunder__ = '1/2'
assert eqpy.nums.__mydunder__ == | '1/2'
|
CaiZhongda/psutil | psutil/_compat.py | Python | bsd-3-clause | 9,627 | 0.002077 | #!/usr/bin/env python
# Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Module which provides compatibility with older Python versions."""
__all__ = ["PY3", "int", "long", "xrange", "exec_"... | rty):
__metaclass__ = type
def __init__(self, fget, *args, **kwargs):
super(property, self).__init__(fget, *args, **kwargs)
self.__doc__ = fget.__doc__
def getter(self, method):
return property(method, self.fset, self.fdel)
def setter(self, method):... | deleter(self, method):
return property(self.fget, self.fset, method)
# py 2.5 collections.defauldict
# Taken from:
# http://code.activestate.com/recipes/523034-emulate-collectionsdefaultdict/
# credits: Jason Kirtland
try:
from collections import defaultdict
except ImportError:
class defaultdict(... |
FEniCS/ufl | demo/P5tet.py | Python | lgpl-3.0 | 852 | 0 | # Copyright (C) 2006-2007 Anders Logg
#
# This file is part of UFL.
#
# UFL is free software: you can redistribute it and/or modify
# it under the terms of th | e GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# UFL 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 PAR... | AR 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 UFL. If not, see <http://www.gnu.org/licenses/>.
#
# A fifth degree Lagrange finite element on a tetrahedron
from ufl import FiniteElement, tetrahedron
ele... |
car3oon/saleor | saleor/urls.py | Python | bsd-3-clause | 2,079 | 0 | from django.conf import settings
from django.conf.urls import url, include
from django.conf.urls.static import static
from django.contrib.sitemaps.views import sitemap
from django.contrib.staticfiles.views import serve
from django.views.i18n import javascript_catalog
from graphene_django.views import GraphQLView
from... | s product_urls
from .search.urls import urlpatterns as search_urls
from .userprofile.views import login as login_view
from .userprofile.urls import urlpatt | erns as userprofile_urls
from .data_feeds.urls import urlpatterns as feed_urls
from .dashboard.urls import urlpatterns as dashboard_urls
urlpatterns = [
url(r'^', include(core_urls)),
url(r'^account/', include('allauth.urls')),
url(r'^account/login', login_view, name="account_login"),
url(r'^cart/', i... |
NaturalEcon/RDb | RDb/models.py | Python | gpl-3.0 | 114 | 0 | from commonmodels import *
from basemodels import | *
from descriptivemodels import *
from operativemodels impo | rt *
|
stsouko/CGRtools | CGRtools/periodictable/groupIX.py | Python | lgpl-3.0 | 6,672 | 0.003447 | # -*- coding: utf-8 -*-
#
# Copyright 2019, 2020 Ramil Nugmanov <[email protected]>
# Copyright 2019 Tagir Akhmetshin <[email protected]>
# Copyright 2019 Tansu Nasyrova <[email protected]>
# This file is part of CGRtools.
#
# CGRtools is free software; you can redistribute it and/or modify
# it ... | ))), # [RhBr4]-
(-3, False, 0, ((1, 'Cl'), (1, 'Cl'), (1, 'Cl'), (1, 'Cl'), (1, 'Cl'), (1, 'Cl'))), # [RhCl6]3-
(-3, False, 0, ((1, 'O'), (1, 'O'), (1, 'O'), (1, 'O'), (1, 'O'), (1, 'O'))), # [Rh(NO2)6]3-
(0, False, 0, ((1, 'F'), (1, 'F'), (1, 'F'), (1, 'F'), (1, 'F'),... | ), (1, 'P'), (1, 'C'), (1, 'H')))) # HRh(CO)[P(Ph)3]3
@property
def atomic_radius(self):
return 1.73
class Ir(Element, PeriodVI, GroupIX):
__slots__ = ()
@property
def atomic_number(self):
return 77
@property
def isotopes_distribution(self):
return FrozenDict({1... |
pandas-dev/pandas | pandas/tests/io/sas/test_sas7bdat.py | Python | bsd-3-clause | 12,142 | 0.000659 | import contextlib
from datetime import datetime
import io
import os
from pathlib import Path
import dateutil.parser
import numpy as np
import pytest
from pandas.errors import EmptyDataError
import pandas.util._test_decorators as td
import pandas as pd
import pandas._testing as tm
@pytest.fixture
def dirpath(datapa... | in(dirpath, f"test_sas7bdat_{i}.csv")
df = pd.read_csv(fname)
epoch = datetime(19 | 60, 1, 1)
t1 = pd.to_timedelta(df["Column4"], unit="d")
df["Column4"] = epoch + t1
t2 = pd.to_timedelta(df["Column12"], unit="d")
df["Column12"] = epoch + t2
for k in range(df.shape[1]):
col = df.iloc[:, k]
if col.dtype == np.int64:
df.iloc[:, k] = df.iloc[:, k].astype(np... |
divio/django-filer | filer/__init__.py | Python | bsd-3-clause | 582 | 0.001718 | """
See PEP 386 (https://www.python.org/dev/peps/pep-0386/)
Release logic:
1. Increase version number (change | __version__ below).
2. Check that all changes have been documented in CHANGELOG.rst.
3. git add filer/__init__.py CHANGELOG.rst
4. git commit -m 'Bump to {new version}'
5. git push
6. Assure that all tests pass on https://travis-ci.org/github/divio/django-filer.
7. git tag {new version}
8. git push --tags
9. py... | ngo-filer-{new version}.tar.gz
"""
__version__ = '2.1.2'
default_app_config = 'filer.apps.FilerConfig'
|
quantcast/qfs | webui/chart.py | Python | apache-2.0 | 1,146 | 0.009599 | #
# $Id$
#
# Copyright 2011,2016 Quantcast Corporation. All rights reserved.
#
# Author: Kate Labeeva
#
# This file is part of Kosmos File System (KFS).
#
# 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 L... |
self.serverName = serverName
self.serverArray = serverArray
class ChartData:
def __init__(self):
self.headers = None
self.serverArray = []
class ChartHTML:
def __init__(self, chartData):
self.chartData = chartData
def printToHTML(self,buffer): |
print "TBD"
|
bblais/plasticity | plasticity/run.py | Python | mit | 17,982 | 0.024747 | #!/usr/bin/env python
__version__= "$Version: $"
__rcsid__="$Id: $"
import matplotlib
#matplotlib.use('WX')
from wx import MilliSleep
from wx import SplashScreen, SPLASH_CENTRE_ON_SCREEN, SPLASH_TIMEOUT
import os
import sys
import warnings
from . import zpickle
from .utils import *
from .dialogs.waxy import *
from ... | le()
fname=self.base_dir+"/images/plasticity_small_icon.ico"
self.SetIcon(fname)
self.fig = Figure(figsize=(7,5),dpi=100) |
self.canvas = FigureCanvas(self, -1, self.fig)
self.figmgr = FigureManager(self.canvas, 1, self)
self.axes = [self.fig.add_subplot(221),
self.fig.add_subplot(222),
self.fig.add_subplot(223),
self.fig.add_subplot(224)]
... |
aioworkers/aioworkers | tests/test_plugins.py | Python | apache-2.0 | 498 | 0 | import argparse
import sys
i | mport pytest
from aioworkers.core.plugin import ProxyPlugin, search_plugins
class plugin:
configs = ('a',)
@pytest.mark | .parametrize('name', [__name__, 'tests'])
def test_proxy_plugin(name, mocker):
del sys.modules[name]
assert name not in sys.modules
(p,) = search_plugins(name)
assert isinstance(p, ProxyPlugin)
assert p.get_config() == {}
p.add_arguments(mocker.Mock())
p.parse_known_args(args=[], namespace=a... |
xchen101/analysis-preservation.cern.ch | cap/modules/records/ext.py | Python | gpl-2.0 | 1,715 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of CERN Analysis Preservation Framework.
# Copyright (C) 2016 CERN.
#
# CERN Analysis Preservation Framework is free software; you can redistribute
# it and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either... | # waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Jinja utilities for Invenio."""
from __future__ import absolute_import, print_function
from invenio_indexer.signals import before_record_index
# from .indexer i... | __(self, app=None):
"""Extension initialization."""
if app:
self.init_app(app)
def init_app(self, app):
"""Flask application initialization."""
app.register_blueprint(blueprint)
# before_record_index.connect(indexer_receiver, sender=app)
app.extensions['c... |
bejar/kemlglearn | kemlglearn/datasets/__init__.py | Python | mit | 249 | 0.016064 | """
.. module:: __init__.py
__init__.py |
*************
:Description: __init__.py
:Authors: bejar
:Version:
:Created on: 21/01/2015 9:00
"""
__author__ = 'bejar'
from .samples_generator import make_blobs |
__all__ = ['make_blobs']
|
marwano/django-glaze | setup.py | Python | bsd-3-clause | 1,285 | 0 |
from s | etuptools import setup
import re
readme = open('README.rst').read()
changes = open('CHANGES.txt').read()
version_file = 'glaze/__init__.py'
version = re.findall("__version__ = '(.*)'", open(version_file).read())[0]
try:
version = __import__('utile').git_version(version)
except ImportError:
pass
setup(
nam... | go-glaze',
version=version,
description="Adding extra functionality to Django",
long_description=readme + '\n\n' + changes,
author='Marwan Alsabbagh',
author_email='[email protected]',
url='https://github.com/marwano/django-glaze',
license='BSD',
packages=[
'glaze', 'gla... |
google/llvm-propeller | llvm/utils/extract_vplan.py | Python | apache-2.0 | 1,612 | 0.003722 | #!/usr/bin/env python
# This script extracts the VPlan digraphs from the vectoriser debug messages
# and saves them in individual dot files (one for each plan). Optionally, and
# providing 'dot' is installed, it can also render the dot into a PNG file.
from __future__ import print_function
import sys
import re
impor... | ches = re.findall(pattern, sys.stdin.rea | d())
for vplan in matches:
m = re.search("graph \[.+(VF=.+,UF.+)", vplan)
if not m:
raise ValueError("Can't get the right VPlan name")
name = re.sub('[^a-zA-Z0-9]', '', m.group(1))
if args.png:
filename = 'VPlan' + name + '.png'
print("Exporting " + name + " to PNG via dot: " +... |
WatanabeYasumasa/edx-platform | lms/envs/common.py | Python | agpl-3.0 | 51,888 | 0.00258 | # -*- coding: utf-8 -*-
"""
This is the common settings file, intended to set sane defaults. If you have a
piece of configuration that's dependent on a set of feature flags being set,
then create a function that returns the calculated value based on the value of
FEATURES[...]. Modules that extend this one can change th... | handle configuration for multiple courses. This could be as
multiple sites, but we do need a way to map their data assets.
"""
# We intentionally define lots of variables that aren't used, and
# want to import all variables from base settings files
# pylint: disable=W0401, W0611, W0614, C0103
import sys
import os
... | h
from .discussionsettings import *
from lms.lib.xblock.mixin import LmsBlockMixin
################################### FEATURES ###################################
# The display name of the platform to be used in templates/emails/etc.
PLATFORM_NAME = "edX"
CC_MERCHANT_NAME = PLATFORM_NAME
COURSEWARE_ENABLED = True
... |
ypu/virt-test | virttest/lvsb_base.py | Python | gpl-2.0 | 17,087 | 0.000351 | """
Base classes supporting Libvirt Sandbox (lxc) container testing
:copyright: 2013 Red Hat Inc.
"""
import logging
import signal
import aexpect
class SandboxException(Exception):
"""
Basic exception class for problems occurring in SandboxBase or subclasses
"""
def __init__(self, message):
... | Finalize assigned opaque session object
"""
# Allow this to be called more than once w/o consequence
if self.connected:
self.session.close()
else:
if warn_if_nonexist:
logging.warning("Closing nonexisting sandbox session")
def kill_sess... | self.session.kill(sig=sig)
else:
raise SandboxException("Can't send signal to inactive sandbox "
"session")
def send(self, a_string):
"""Send a_string to session"""
if self.connected:
self.session.send(a_string)
else:... |
dimonaks/siman | siman/picture_functions.py | Python | gpl-2.0 | 47,676 | 0.022506 | # -*- coding: utf-8 -*-
from __future__ import division, unicode_literals, absolute_import
import sys, os
import copy
import numpy as np
try:
import scipy
from scipy import interpolate
# print (scipy.__version__)
# print (dir(interpolate))
except:
print('picture_functions.py: scipy is not avail'... | e+='.'
path2saved_png = dirname+'/png/'+os.path.basename(image_name)+'.png'
makedir(path2saved_png)
return path2saved, path2saved_png
def fit_and_plot(ax = None, power = None, xlabel = None, ylabel = None,
image_name = None, filename = None,
show = None, pad = None,
xlim = None, ylim = None, ... | one, markersize = None,
linewidth = None, hor = False, ver = True, fig_format = 'eps', dpi = 300,
ver_lines = None, hor_lines = None, xy_line = None, x_nbins = None,
alpha = 0.8, fill = False,
first = True, last = True,
convex = None, dashes = None,
corner_letter = None, corner_letter_pos = N... |
pombreda/django-hotclub | libs/external_libs/docutils-0.4/docutils/transforms/__init__.py | Python | mit | 6,690 | 0.000149 | # Authors: David Goodger, Ueli Schlaepfer
# Contact: [email protected]
# Revision: $Revision: 3892 $
# Date: $Date: 2005-09-20 22:04:53 +0200 (Tue, 20 Sep 2005) $
# Copyright: This module has been placed in the public domain.
"""
This package contains modules for standard tree transforms available
to Docut... | ific transforms before or after performing
these standard transforms.
"""
__d | ocformat__ = 'reStructuredText'
from docutils import languages, ApplicationError, TransformSpec
class TransformError(ApplicationError): pass
class Transform:
"""
Docutils transform component abstract base class.
"""
default_priority = None
"""Numerical priority of this transform, 0 through 9... |
ricomoss/learn-tech | python/track_1/lesson4/exercise.py | Python | gpl-3.0 | 1,793 | 0.000558 | #!/usr/bin/p | ython
from __future__ import unicode_literals
import os
def wait():
raw_input('\nPress Enter to continue. | ..\n\n')
os.system(['clear', 'cls'][os.name == 'nt'])
# Create a class to handle items in a wallet
class BaseWalletHandler(object):
def __init__(self):
self.items = {
'Driver\'s License': False,
'Credit Card': False,
'Cash': False,
'Change': False,
... |
INI-ratlab/ratlab | util/ratbot.py | Python | gpl-3.0 | 8,302 | 0.038063 | #==============================================================================
#
# Copyright (C) 2016 Fabian Schoenfeld
#
# This file is part of the ratlab software. It 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... | up.rat.path != None:
return self.followPathNodes()
# current position & velocity/direction
pos = self.__path__[len(self.__path__)-1]
pos_next = np.array([np.nan,np.nan])
if len(self.__path__) > 1: vel = pos-self.__path__[len(self.__path__)-2]
else: vel = self.__gaussianWhiteNoise2D__()
# generate ne... | ep))
step *= self.__ctrl__.setup.rat.speed
# optional movement bias
bias = self.__ctrl__.setup.rat.bias
step += bias*(np.dot(bias,step)**2)*np.sign(np.dot(bias,step))*self.__ctrl__.setup.rat.bias_s
# check for valid step
pos_next = pos + step
if self.__ctrl__.modules.world.validStep( pos, pos_next... |
chrys87/fenrir | src/fenrirscreenreader/core/settingsData.py | Python | lgpl-3.0 | 3,330 | 0.014786 | #!/bin/python
# -*- coding: utf-8 -*-
# Fenrir TTY screen reader
# By Chrys, Storm Dragon, and contributers.
from fenrirscreenreader.core import debug
settingsData = {
'sound': {
'enabled': True,
'driver': 'genericDriver',
'theme': 'default',
'volume': 1.0,
'genericPlayFileCommand': 'play -q -v fenrirVolum... | :%M%P',
'dateFormat': '%A, %B %d, %Y',
'autoSpellCheck': False,
'spellCheckLanguage': 'en_US',
'scriptPath': '/us | r/share/fenrirscreenreader/scripts',
'commandPath': '/usr/share/fenrirscreenreader/commands',
'attributeFormatString': 'Background fenrirBGColor,Foreground fenrirFGColor,fenrirUnderline,fenrirBold,fenrirBlink, Font fenrirFont,Fontsize fenrirFontSize',
'autoPresentIndent': False,
'autoPresentIndentMode': 1,
'h... |
jsha/letsencrypt | acme/acme/messages.py | Python | apache-2.0 | 14,264 | 0.00028 | """ACME protocol messages."""
import collections
import six
from acme import challenges
from acme import errors
from acme import fields
from acme import jose
from acme import util
OLD_ERROR_PREFIX = "urn:acme:error:"
ERROR_PREFIX = "urn:ietf:params:acme:error:"
ERROR_CODES = {
'badCSR': 'The CSR is unacceptable ... | :ivar unicode title:
:ivar unicode detail:
"""
typ = jose.Field('type', omitempty=True, defau | lt='about:blank')
title = jose.Field('title', omitempty=True)
detail = jose.Field('detail', omitempty=True)
@classmethod
def with_code(cls, code, **kwargs):
"""Create an Error instance with an ACME Error code.
:unicode code: An ACME error code, like 'dnssec'.
:kwargs: kwargs to... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.