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 |
|---|---|---|---|---|---|---|---|---|
codex-bot/github | github/data_types/team.py | Python | mit | 1,793 | 0 | class Team:
"""
GitHub Team
https://developer.github.com/v3/orgs/teams/
Attributes:
id: GitHub internal id
url: "https://api.github.com/teams/1"
name: The name of the team
slug: Team name uri
description: The description of the team.
privacy: The level o... | mbers of this team.
* closed - visible to all members of this organization.
Default: secret
permission: Deprecated. The permission that new repositories will
be added to | the team with when none is specified.
Can be one of:
* pull - team members can pull, but not push
to or administer newly-added repositories.
* push - team members can pull and push, but
not administer newly-adde... |
shivkantranade/geointegration | geointegration/urls.py | Python | unlicense | 283 | 0.014134 | from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
# Examples:
| # url(r'^$', 'geointegration.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)), |
)
|
akumar21NCSU/servo | tests/wpt/harness/wptrunner/wptcommandline.py | Python | mpl-2.0 | 18,161 | 0.00446 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import argparse
import ast
import os
import sys
from collections import OrderedDict
from distutils.spawn import find_exe... | help="Path to openssl binary", default="openssl")
ssl_group.add_argument("--certutil-binary", action="store",
help="Path to certutil binary for use with Firefox + ssl")
ssl_group.add_argument("--ca-cert-path", action="store", type=abs_path,
... | )
ssl_group.add_argument("--host-key-path", action="store", type=abs_path,
help="Path to host private key when using pregenerated ssl certificates")
ssl_group.add_argument("--host-cert-path", action="store", type=abs_path,
help="Path to host certificate when using... |
dominicgs/GreatFET-experimental | host/greatfet/sensors/tsl2561.py | Python | bsd-3-clause | 4,679 | 0.004061 | #
# This file is part of GreatFET
#
from .. import errors
from ..sensor import GreatFETSensor
from ..interfaces.i2c_device import I2CDevice
class TSL256X(I2CDevice, GreatFETSensor):
"""
Represents a TSL256X Ambient Light Sensor.
"""
SHORTHAND = "tsl256x"
# Default I2C address.
DEFAULT_AD... | / self.MAX_ADC_READING
def get_reading(self, name_prefix=True):
"""
Returns an dictionary of all readings provided by the given device.
Used by the Sensor API.
"""
# Determine the name of the reading to be captured.
prefix = (self.name + ': ') if name_prefix else '... | refix + "Light Intensity"
# Return our captured reading!
reading = {}
reading[reading_name] = self.intensity_reading()
return reading
|
bhupennewalkar1337/erpnext | erpnext/controllers/selling_controller.py | Python | gpl-3.0 | 12,444 | 0.02451 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils import cint, flt, cstr, comma_or
from erpnext.setup.utils import get_company_currency
from frappe import _, throw
from e... | p.parent_detail_docname == d.name and p.parent_item == d.item_code:
# the packing details table's qty is already multiplied with parent's qty
il.append(frappe._dict({
'warehouse': p.warehouse,
'item_code': p.item_code,
'qty': flt(p.qty),
'uom': p.uom,
'batch_no': cstr(p.b... | 'name': d.name,
'target_warehouse': p.target_warehouse
}))
else:
il.append(frappe._dict({
'warehouse': d.warehouse,
'item_code': d.item_code,
'qty': d.qty,
'uom': d.stock_uom,
'stock_uom': d.stock_uom,
'batch_no': cstr(d.get("batch_no")).strip(),
'serial_no': cstr... |
oli-kester/advanced-av-examples | amp-osc-lv2/.waf-1.8.5-3556be08f33a5066528395b11fed89fa/waflib/Tools/c_aliases.py | Python | gpl-2.0 | 1,334 | 0.072714 | #! /usr/bin/env python
# encoding: utf-8
# WARNING! Do not edit! http://waf.googlecode.com/git/docs/wafbook/single.html#_obtaining_the_waf_file
import os,sys,re
from waflib import Utils,Build
from waflib.Configure import conf
def get_extensi | ons(lst):
ret=[]
for x in Utils.to_list(lst):
try:
if not isinstance(x,str):
x=x.name
ret.append(x[x.rfind('.')+1:])
except Exception:
pass
return ret
def sniff_features(**kw):
exts=get_extensions(kw['source'])
type=kw['_type']
feats=[]
if'cxx'in exts or'cpp'in exts or'c++'in exts or'cc'in exts ... |
if'd'in exts:
feats.append('d')
if'java'in exts:
feats.append('java')
if'java'in exts:
return'java'
if type in('program','shlib','stlib'):
for x in feats:
if x in('cxx','d','c'):
feats.append(x+type)
return feats
def set_features(kw,_type):
kw['_type']=_type
kw['features']=Utils.to_list(kw.get('f... |
Furzoom/learnpython | pythonCore/ch13/class_test.py | Python | mit | 2,030 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class People:
__name = 'furzoom'
__age = 22
gender = 'female'
__country = 'China'
def print_name(self):
print(self.__name)
def set_name(self, name):
print(id(self.__name))
self.__name = name
print(id(self.__name))
... | = name
self.age = age
def get_name(self):
return self.name
def get_age(self):
return self.age
class Student(UniversityMember):
def __init__(self, name, age, sno, mark):
UniversityMember.__init__(self, name, age)
self.sno = sno
self.mark = mark
def ge... | mark(self):
return self.mark
class Teacher(UniversityMember):
def __init__(self, name, age, tno, salary):
UniversityMember.__init__(self, name, age)
self.tno = tno
self.salary = salary
def get_tno(self):
return self.tno
def get_salary(self):
return self.sa... |
cowenberg/snap | snap_website/default/settings.py | Python | gpl-2.0 | 2,266 | 0 | """
Django settings for ghost_project project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, .... | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
'USER': 'ghost',
'PASSWORD': 'geekattitude',
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'us-EN'
TIME_ZONE = 'CET'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScrip... | s)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_URL = '/assets/'
# templates and files
TEMPLATE_DIRS = ('assets/tpl')
STATICFILES_DIRS = (os.path.abspath(os.path.join(BASE_DIR, 'assets')),)
# others
APPEND_SLASH = True
|
hakyimlab/MetaXcan-Postprocess | source/Gencode.py | Python | mit | 2,470 | 0.009312 | __author__ = 'heroico'
#trimmed from PredictDBAnalysis/gencode_input
import csv
import gzip
import pandas
K_NOT_GENES = ["transcript","exon","CDS","UTR","start_codon","stop_codon","Selenocysteine"];
# look at gencode http://www.gencodegenes.org/data_format.html
class GFTF:
"""gencode file table format"""
CHR... | e
K_CHROMOSOME = "chromosome"
K_START_LOCATION = "start_location"
K_GENE_ID = "gene_id"
K_TRANSCRIPT_ID = "transcript_id"
K_GENE_TYPE = "gene_type"
K_GENE_STATUS = "gene_status"
K_GENE_NAME = "gene_name"
K_TRANSCRIPT_TYPE = "transcript_t | ype"
K_TRANSCRIPT_STATUS = "transcript_status"
K_TRANSCRIPT_NAME = "transcript_name"
K_EXON_NUMBER = "exon_number"
K_EXON_ID = "exon_id"
K_LEVEL = "level"
#some are missing
K_TAG = "tag"
def key_value_pairs_to_dict(key_value_pairs):
d = {}
key, value = None, None
for i, string ... |
YuxuanLing/trunk | trunk/code/study/python/Fluent-Python-example-code/attic/concurrency/charfinder/tcp_charfinder.py | Python | gpl-3.0 | 1,730 | 0 | #!/usr/bin/env python3
import sys
import asyncio
from charfinder import UnicodeNameIndex
CRLF = b'\r\n'
PROMPT = b'?> '
index = None # a UnicodeNameIndex instance
@asyncio.coroutine
def handle_queries(reader, writer):
while True:
writer.write(PROMPT) # can't yield from!
yiel... | oop.run_forever()
except KeyboardInterrupt: # CTRL+C pressed
pass
server.close()
loop.run_until_complete(server.wait_closed())
loop.close()
if __n | ame__ == '__main__':
index = UnicodeNameIndex()
main(*sys.argv[1:])
|
tdfischer/modulation | modulation/controls.py | Python | gpl-3.0 | 2,941 | 0.00646 | # -*- coding: utf-8 -*-
# Copyright 2010 Trever Fischer <tdfischer@fedoraproject.org>
#
# This file is part of modulation.
#
# modulation 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... | ignal to a child plugin, such as "STOP", "PLAY | ", "SEARCH", "VOLUME", etc
If a plugin handles the packet according to its intent (eg stopping playback on a stop packet), then the
original packet must be forwarded with send(). If a plugin then does other actions (such as switching to
a different stream and then playing), a new packet must be sent as wel... |
Asurada2015/TFAPI_translation | NeuralNekworks_function/Activefunction/tf_nn_relu.py | Python | apache-2.0 | 769 | 0 | """tf.nn.relu(features, name = None)
解释:这个函数的作用是计算激活函数rel | u,即max(features, 0)。
所有负数都会归一化为0,所以的正值保留为原值不变
优点在于不受"梯度消失"的影响,且取值范围在[0,+oo],缺点在于使用了较大的学习速率时,易受达到饱和的神经元的影响
使用例子:"""
import tensorflow as tf
a = tf.constant([-1.0, 2.0])
with tf.Session() as sess:
b = tf.nn.relu(a)
print(sess.run(b))
# [0. 2.]
"""输入参数:
● features: 一个Tensor。数据类型必须是:float32,float64,int32,i... | 作取一个名字。
输出参数:
● 一个Tensor,数据类型和features相同。"""
|
mtermoul/fishbone | setup.py | Python | bsd-3-clause | 518 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import fishbone
version = fishbone.__version__
setup(
name='fishbone | ',
version=version,
author="Mohamed Termoul",
author_email='mtermoul@gmail.com',
packages=[
'fishbone',
],
include_package_data=True,
install_requires=[
| 'Django>=1.7.4',
],
zip_safe=False,
scripts=['fishbone/manage.py'],
)
|
emilio2601/scpy | scpy/daemon.py | Python | gpl-3.0 | 900 | 0.003333 | from collections import namedtuple
class SiaDaemon(object):
"""The daemon is responsible for starting and stopping the modules which make up the rest of Sia. It also provides endpoints for viewing build constants."""
def __init__(self, scpy):
self.scpy = scpy
def stop(self):
| """
Cleanly shuts down the Sia daemon
:return: True if action succeeded
:raises: SiaError if action was unsuccessful
"""
return self.scpy.get_api('/daemon/stop')
@property
def version(self):
"""
Version of the Sia daemon
"""
return s... | s(self):
"""
Set of constants in use
"""
constants = self.scpy.get_api('/daemon/constants')
return namedtuple("Constants",constants.keys())(*constants.values())
|
grlee77/numpy | numpy/setup.py | Python | bsd-3-clause | 983 | 0.003052 | #!/usr/bin/env python3
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('numpy', parent_package, top_path)
config.add_subpackage('compat')
config.add_subpackage('core')
config.add_subpackage('distutils')
config.add_s... | nfig.add_subpackage('polynomial')
config.add_subpackage('random')
config.add_subpackage('testing')
config.add_subpackage('typing')
config.add_data_dir('doc')
config.add_data_files('py.typed')
config.add_data_files('*.pyi')
config.add_subpackage('tests')
config.make_config_py() # installs... | g setup.py file to run')
|
b-com/watcher-metering-drivers | watcher_metering_drivers/wrappers/virt/instance/base.py | Python | apache-2.0 | 8,768 | 0 | # -*- encoding: utf-8 -*-
# Copyright (c) 2015 b<>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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | x, libvirt.libvirtError):
raise virt_inspector.InspectorException(six.text_type(ex))
error_code = ex.get_er | ror_code()
if (error_code == libvirt.VIR_ERR_SYSTEM_ERROR and
ex.get_error_domain() in (libvirt.VIR_FROM_REMOTE,
libvirt.VIR_FROM_RPC)):
raise
msg = _("Error from libvirt while looking up instance "
"<n... |
MaxPoint/cyavro | test/basic_types.py | Python | bsd-3-clause | 9,822 | 0.002545 | # Copyright (c) 2015 MaxPoint Interactive, Inc.
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
# following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of conditi... | ame)
import avro.schema
from avro.datafile import DataFileReader, DataFileWriter
from avro.io import DatumReader, DatumWriter
with open(self.filename, 'rb') as fo:
reader = DataFileReader(fo, DatumReader())
records = []
for user in reader:
... | df_reference = pd.DataFrame(records)
reader.close()
success = True
for col in avro_schema["fields"]:
colname = col['name']
assert_fn = assert_fns.get(colname, np.testing.assert_array_equal)
def print_fail_header(s):
print('#' * len(s))
... |
AlexS12/PyFME | src/pyfme/simulator.py | Python | mit | 6,523 | 0 | """
Python Flight Mechanics Engine (PyFME).
Copyright (c) AeroPython Development Team.
Distributed under the terms of the MIT License.
Simulation class
----------------
Select the simulation configuration based on a system (and its dynamic
model), environment and aircraft.
"""
import copy
import operator
import pand... | stem.time_step(dt)
self._save_time_step()
bar.update(dt)
bar.close()
results = pd.DataFrame(self.re | sults)
results.set_index('time', inplace=True)
return results
def _save_time_step(self):
"""Saves the selected variables for the current system, environment
and aircraft.
"""
for var_name, value_pointer in self._save_vars.items():
self.results[var_name].... |
areeda/gwpy | gwpy/cli/tests/test_timeseries.py | Python | gpl-3.0 | 1,323 | 0 | # -*- coding: utf-8 -*-
# Copyright (C) Duncan Macleod (2018-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
# (at your option)... | ses/>.
"""Unit tests for :mod:`gwpy.cli.timeseries`
"""
from ... import cli
from .base import (_TestTimeDomainProduct, update_namespace)
class TestCliTimeSeries(_TestTimeDomainProduct):
TEST_CLASS = cli.TimeSeries
ACTION = 'timeseries' |
def test_get_title(self, prod):
update_namespace(prod.args, highpass=10, lowpass=100)
t = 'Fs: (), duration: {0}, band pass (10.0-100.0)'.format(
prod.args.duration)
assert prod.get_title() == t
def test_get_suptitle(self, prod):
assert prod.get_suptitle() == 'Time... |
Phelimb/cbg | bigsi/matrix/bitmatrix.py | Python | mit | 2,591 | 0.002702 | from bitarray import bitarray
NUM_ROWS_KEY = "number_of_rows"
NUM_COLS_KEY = "number_of_cols"
class BitMatrix(object):
"""
Manages the gets and sets of the bitmatrix to the various storage backends.
Does not know the concept of a kmer.
"""
def __init__(self, storage):
self.storage = st... | _bits(
list(range(len(bitarray))),
[column_index] * len(bit | array),
bitarray.tolist(),
)
if column_index >= self.num_cols:
self.set_num_cols(self.num_cols + 1)
|
michele-mada/cv-eyetracking-project-2017 | py_eyetracker_v1.0/utils/screen_mapping/mappers/optimizer.py | Python | mit | 1,359 | 0.000736 | import numpy as np
from scipy.optimize import least_squares
def compute_error(screen_coordinate, eye_vector, candidate_params, mapfun):
computed_coord = mapfun(eye_vector, candidate_params)
return screen_coordinate - computed_coord
def compute_params(screen_points, eye_vectors, mapfun, num_params):
x_sc... | ,
zip(y_screen_points, eye_vectors))))
optimization_res_x = least_squares(error_function_x,
np.ones(num_params))
optimization_res_y = least_squares(error_function_y,
np.ones(num_params))
params_x... | optimization_res_y.x
return params_x, params_y
|
VitalyW/python_training | generator/group.py | Python | apache-2.0 | 1,011 | 0.004946 | from model.group import Group
import random
import string
import os.path
import jsonpickle
import getopt
import sys
try:
opts, args = getopt. | getopt(sys.argv[1:], | "n:f:", ["number of groups", "file"])
except getopt.GetoptError as err:
getopt.usage()
sys.exit(2)
n = 5
f = "data/groups.json"
for o, a in opts:
if o == "-n":
n = int(a)
elif o == "-f":
f = a
def random_string(prefix, maxlen):
symbols = string.ascii_letters + string.digits + st... |
jotterbach/ExactDiagonalization_PolarizedFermionicDipolesOnZigZagChain | DiagonalizationMethods.py | Python | gpl-2.0 | 10,568 | 0.015519 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 26 11:09:05 2013
@author: jotterbach
"""
from numpy import *
from ED_HalfFilling import EigSys_HalfFilling
from DotProduct import scalar_prod
from multiprocessing import *
from multiprocessing import Pool
import matplotlib.pyplot as plt
from ParallelizationTools import... | particles: number of particles in the problem
noEV: number of eigenvalues being calculated
gamma: opening angle of the zi | g-zag chain
hopping: hopping parameter in units of interaction V
angle: array containing the angles as a multiple of **PI**
"""
''' default values for other methods that are being called by the current
function '''
spectrum = 1 #ensures that the spectrum is calculated in EigSys_Half... |
giginet/django-contrib-comments | tests/testapp/tests/test_comment_views.py | Python | bsd-3-clause | 13,575 | 0.001179 | from __future__ import absolute_import, unicode_literals
import re
from django.conf import settings
from django.contrib.auth.models import User
from django_comments import signals
from django_comments.models import Comment
from . import CommentTestCase
from ..models import Article, Book
post_redirect_re = re.comp... | should fail when Comment.ip_address is an IPAddress instead of a GenericIPAddress,
but does not do so on SQLite or PostgreSQL, because they use the TEXT and INET types, which already
allow storing an IPv6 address internally.
"""
address = "2a02::223:6cff:fe8a:2e8a"
a = Article.ob... | self.assertEqual(self.response.status_code, 302)
self.assertEqual(Comment.objects.count(), 1)
c = Comment.objects.all()[0]
self.assertEqual(c.ip_address, address)
self.assertEqual(c.comment, "This is my comment")
def testCreateValidCommentIPv6Unpack(self):
address = "::f... |
abtreece/ansible | contrib/inventory/rackhd.py | Python | mit | 2,357 | 0.008485 | #!/usr/bin/python
import json
import requests
import os
import argparse
import types
RACKHD_URL = 'http://localhost:8080'
class RackhdInventory(object):
def __init__(self, nodeids):
self._inventory = {}
for nodeid in nodeids:
self._load_inventory_data(nodeid)
inventory = {}
... | (nodeid )
info['lookup'] = RACKHD_URL + '/api/common/lookups/?q={0}'.format(nodeid)
results = {}
for key,url in info.items():
r = requests.get( url, verify=False)
results[key] = r.text
self._inventory[nodeid] = results
def _format_output(s | elf, nodeid, info):
try:
node_info = json.loads(info['lookup'])
ipaddress = ''
if len(node_info) > 0:
ipaddress = node_info[0]['ipAddress']
output = { 'hosts':[ipaddress],'vars':{}}
for key,result in info.items():
output... |
pirsquare/chequeconvert-python | chequeconvert/base.py | Python | mit | 6,111 | 0.000327 | from decimal import Decimal
map_ones = {
0: "",
1: "One",
2: "Two",
3: "Three",
4: "Four",
5: "Five",
6: "Six",
7: "Seven",
8: "Eight",
9: "Nine",
}
map_tens = {
10: "Ten",
11: "Eleven",
12: "Twelve",
13: "Thirteen",
14: "Fourteen",
15: "Fifteen",
16... | # at least 1 billion
if len(num) > 9:
billion_num = int(num[0:(len(num)-9)])
num = str(int(num) - (billion_num*int(1e9)))
hundredth, tenth, one = extract(str(billion_num))
word += "{0} ".format(get_billion(hundredth, tenth, one))
# at least 1 million
if len(num) > 6:
... | llion_num*int(1e6)))
hundredth, tenth, one = extract(str(million_num))
word += "{0} ".format(get_million(hundredth, tenth, one))
# at least 1 thousand
if len(num) > 3:
thousand_num = int(num[0:(len(num)-3)])
num = str(int(num) - (thousand_num*int(1e3)))
hundredth, tenth,... |
SunPower/PVMismatch | pvmismatch/contrib/module_mismatch_simulator.py | Python | bsd-3-clause | 20,978 | 0.001287 | #!/usr/bin/env python
'''
Created on Mar 29, 2013
This script allows the user to dynamically investigate the IV and PV
characteristics of a single module. The user chooses the modules size--72 or 96
cells. A GUI is then generated that allows the user to change the size, location,
and irradiance level of a single "sha... | ========================================
# Importing standard libraries
# ==============================================================================
from __future__ import (
absolute_import, division, unicode_literals, print_function)
import json
from functools import partia | l
from copy import deepcopy
import os
import numpy as np
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib.widgets import Slider
from matplotlib.widgets import Button
from past.builtins import raw_input, xrange
# ==============================... |
Mlieou/oj_solutions | leetcode/python/ex_265.py | Python | mit | 782 | 0.002558 | class Solution(object):
def minCostII(self, costs):
"""
:type costs: List[List[in | t]]
:rtype: int
"""
if not costs or not costs[0]: return 0
min1 = min2 = -1
for i in range(len(costs)):
last1, last2 = min1, min2
min1 = min2 = -1
for j in range(len(costs[0])):
if j != last1:
costs[i][j] += ... | costs[i][j] += 0 if last2 < 0 else costs[i - 1][last2]
if min1 < 0 or costs[i][j] < costs[i][min1]:
min2, min1 = min1, j
elif min2 < 0 or costs[i][j] < costs[i][min2]:
min2 = j
return costs[-1][min1] |
repotvsupertuga/tvsupertuga.repository | script.module.projectx.wizard/resources/libs/downloader.py | Python | gpl-2.0 | 3,248 | 0.025246 | ################################################################################
# Copyright (C) 2015 Surfacingx #
# #
# This Program is free software; you can redistribute it and/or modify ... | #
# 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. #
# ... |
jamestwebber/scipy | scipy/io/matlab/mio5_params.py | Python | bsd-3-clause | 7,077 | 0.000848 | ''' Constants and classes for matlab 5 read and write
See also mio5_utils.pyx where these same constants arise as c enums.
If you make changes in this file, don't forget to change mio5_utils.pyx
'''
from __future__ import division, print_function, absolute_import
import numpy as np
from .miobase import convert_dtyp... | hat
# mxOBJECT_CLASS = 3, whereas matrix.h says that mxLOGICAL = 3.
# Matlab 2008a appears to save logicals as type 9, so we assume that
# the document is correct. See type 18, below.
mxOBJECT_CLASS = 3
mxCHAR_CLASS = 4
mxSPARSE_CLASS = 5
mxDOUBLE_CLASS = 6
mxSING | LE_CLASS = 7
mxINT8_CLASS = 8
mxUINT8_CLASS = 9
mxINT16_CLASS = 10
mxUINT16_CLASS = 11
mxINT32_CLASS = 12
mxUINT32_CLASS = 13
# The following are not in the March 2008 edition of "Matlab 7
# MAT-File Format," but were guessed from matrix.h.
mxINT64_CLASS = 14
mxUINT64_CLASS = 15
mxFUNCTION_CLASS = 16
# Not doing anythi... |
sadanandb/pmt | src/mako/exceptions.py | Python | epl-1.0 | 11,269 | 0.005591 | # ex | ceptions.py
# Copyright (C) 2006, 2007, 2008, 2009, 2010 Michael Bayer mike | _mp@zzzcomputing.com
#
# This module is part of Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""exception classes"""
import traceback, sys, re
from mako import util
class MakoException(Exception):
pass
class RuntimeException(MakoException):
pass
def _form... |
beetbox/beets | beets/util/__init__.py | Python | mit | 37,269 | 0 | # This file is part of beets.
# Copyright 2016, 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, ... | if not matches:
return Fal | se
return True
def prune_dirs(path, root=None, clutter=('.DS_Store', 'Thumbs.db')):
"""If p |
rustychris/stompy | stompy/grid/optimize_grid.py | Python | mit | 18,033 | 0.011923 | # Explore some possibilities for optimizing the grid.
from __future__ import print_function
from . import (paver,trigrid,orthomaker)
from ..spatial import field
import sys
import numpy as np # from numpy import *
from scipy.linalg import norm
# from pylab import *
import matplotlib.pyplot as plt
class OptimizeGui(... | ty
field of the paver (which may be a reduced Apollonius Graph field)
"""
p=self.p
|
if cell_ids is None:
cell_ids = np.arange(p.Ncells())
valid = (p.cells[cell_ids,0]>=0)
vc = p.vcenters()[cell_ids]
local_scale = np.zeros( len(cell_ids), np.float64)
if use_original_density:
local_scale[valid] = self.original_density( vc[valid,:] )
... |
Semi-global/edx-platform | openedx/core/lib/json_utils.py | Python | agpl-3.0 | 533 | 0 | """
Utilities for dealing with JSON.
"""
import simplejson
from xmodule.modulestore import EdxJSONEncoder
class EscapedEdxJSONEncoder(EdxJSONEncoder):
"""
Class for encoding edx JSON which will be printed inline into HTML
templates.
"""
| def encode(self, obj):
"""
| Encodes JSON that is safe to be embedded in HTML.
"""
return simplejson.dumps(
simplejson.loads(super(EscapedEdxJSONEncoder, self).encode(obj)),
cls=simplejson.JSONEncoderForHTML
)
|
Hexanonyme/PLD_SmartCity | Backend/api/maintenance/heatmap/process_streets.py | Python | gpl-3.0 | 3,008 | 0.001336 | #!/usr/bin/python3
# -!- encoding:utf8 -!-
# ---------------------------- IMPORTS
from subpr | ocess import call
from ...fs.fs import list_heatmap_streets
fro | m ...fs.fs import load_heatmap_streets
from ...fs.fs import dump_heatmap_grid
from ...fs.fs import dump_heatmap_psd
from ...printer.printer import print_progress
# ---------------------------- CONFIGURATION
baseurl = 'https://download.data.grandlyon.com/wfs/grandlyon'
params = {
'SERVICE': 'WFS',
'VERSION': '... |
adviti/melange | thirdparty/google_appengine/lib/django_1_2/tests/modeltests/delete/models.py | Python | apache-2.0 | 967 | 0.008273 | # coding: utf-8
"""
Tests for some corner cases with deleting.
"""
from django.db import models
class DefaultRepr(object):
def __repr__(self):
return u"<%s: %s>" % (self.__class__.__name__, self.__dict__)
class A(DefaultRepr, models.Model):
| pass
class B(DefaultRepr, models.Model):
a = models.ForeignKey(A)
class C(DefaultRepr, models.Model):
b = models.ForeignKey(B)
class D(DefaultRepr, models.Model):
c = models.ForeignKey(C)
a = models.ForeignKey(A)
# Simplified, we have:
# A
# B -> A
# C -> B
# D -> C
# D -> A
# So, we must delet... | t find Bs first (in which
# case things will be nice), or find Ds first.
# Some mutually dependent models, but nullable
class E(DefaultRepr, models.Model):
f = models.ForeignKey('F', null=True, related_name='e_rel')
class F(DefaultRepr, models.Model):
e = models.ForeignKey(E, related_name='f_rel')
|
colloquium/spacewalk | client/solaris/smartpm/smart/uncompress.py | Python | gpl-2.0 | 3,089 | 0.003237 | #
# Copyright (c) 2004 Conectiva, Inc.
#
# Written by Gustavo Niemeyer <niemeyer@conectiva.com>
# |
# This file is part of Smart Package Manager.
#
# Smart Package Manager is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as published
# by the Free Software Foundation; either version 2 of the License, or (at
# your option) any later version.
#
# Smart Pack... | Y WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Smart Package Manager; if not, write to the Free Software
# Foundation, Inc.,... |
kenorb-contrib/BitTorrent | twisted/conch/test/test_helper.py | Python | gpl-3.0 | 15,792 | 0.000507 | # -*- test-case-name: twisted.conch.test.test_helper -*-
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.
from twisted.conch.insults import helper
from twisted.conch.insults.insults import ServerProtocol, ClientProtocol
from twisted.conch.insults.insults import G0, G1, G2, G3
from twis... | self.assertEquals(self.term.reportCursorPosition(), (7, 5))
def testSingleShifts(self):
self.term.singleShift2()
self.term.write('Hi')
ch = self.term.getCharacter(0, 0)
self.assertEquals(ch[0], 'H')
self.assertEquals(ch[1].charset, G2)
ch = self.term.getCharacter... | ingleShift3()
self.term.write('!!')
ch = self.term.getCharacter(2, 0)
self.assertEquals(ch[0], '!')
self.assertEquals(ch[1].charset, G3)
ch = self.term.getCharacter(3, 0)
self.assertEquals(ch[0], '!')
self.assertEquals(ch[1].charset, G0)
def testShifting(se... |
tylertebbs20/Practice-httpie | tests/test_downloads.py | Python | bsd-3-clause | 4,859 | 0 | import os
import time
import pytest
from requests.structures import CaseInsensitiveDict
from httpie.compat import urlopen
from httpie.downloads import (
parse_content_range, filename_from_content_disposition, filename | _from_url,
get_unique_filename, ContentRangeError, Download,
)
from utils import http, TestEnvironment
class Response(object):
# noinspection PyDefaultArgument
def __ini | t__(self, url, headers={}, status_code=200):
self.url = url
self.headers = CaseInsensitiveDict(headers)
self.status_code = status_code
class TestDownloadUtils:
def test_Content_Range_parsing(self):
parse = parse_content_range
assert parse('bytes 100-199/200', 100) == 200
... |
daiyiwhale/hatch | incubator/signals.py | Python | gpl-2.0 | 842 | 0.008314 | from account.signals import user_signed_up
from django.conf import settings
from django.contrib.auth.signals import user_logged_in, user_logged_out
from django.dispatch import receiver
from incubator.models import Incubator, Egg
from sys import stderr
@receiver(user_signed_up)
def new_account_handler(sender, **kwargs... | ve()
egg = Egg(incubator=incubator, focus=True)
egg.save()
#@receiver(user_logged_in)
#def sig_user_logged_in(sender, user, request, **kwargs):
# print "################## log in"
#
#@receive | r(user_logged_out)
#def sig_user_logged_out(sender, user, request, **kwargs):
# print "################## log out"
|
magicicada-bot/magicicada-server | magicicada/wsgi.py | Python | agpl-3.0 | 395 | 0 | """
WSGI config for filesync project.
It exposes the WSGI callable | as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "magicicada.settings")
application = get_wsgi_ | application()
|
electionleaflets/electionleaflets | electionleaflets/apps/boundaries/models.py | Python | mit | 454 | 0.008811 | from django.db import models
from constituencies.models import Constituency
class Boundary(models.Model):
constituency = models.ForeignKey( Constituency )
boundary = models.TextField()
zoom = models.IntegerField()
north = models.FloatField()
sout | h = models.FloatField()
east = models.FloatField()
west = | models.FloatField()
class Meta:
db_table = u'boundaries_boundary'
verbose_name_plural = 'Boundaries'
|
pllim/ginga | ginga/rv/plugins/Pipeline.py | Python | bsd-3-clause | 14,214 | 0.00007 | # This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
"""
Simple data processing pipeline plugin for Ginga.
**Plugin Type: Local**
``Pipeline`` is a local plugin, which means it is associated with a channel.
An instance can be opened for each channel.
**Usage**
... | d_gui(xpd)
xpd.add_callback('opened', lambda w: stage.resume())
xpd.add_callback('closed', lambda w: stage.pause( | ))
stage.gui_up = True
_vbox.add_widget(xpd, stretch=0)
stage.w.gui = _vbox
return _vbox
def close(self):
chname = self.fv.get_channel_name(self.fitsimage)
self.fv.stop_local_plugin(chname, str(self))
self.gui_up = False
return True
def start(sel... |
Nagasaki45/Friends-Mapper | friends/models.py | Python | mit | 353 | 0.031161 | from django.db import models
# Create your models here.
class Friend(models.Model) | :
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
friends = models.ManyToManyField('self', blank=True)
def full_name(self):
return self.first_name + " " + self.last_name
def __ | unicode__(self):
return self.full_name() |
carlosperate/mu | mu/modes/circuitpython.py | Python | gpl-3.0 | 10,028 | 0.0001 | """
A mode for working with Circuit Python boards.
Copyright (c) 2015-2017 Nicholas H.Tollervey and others (see the AUTHORS file).
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of... | {
"name": "serial",
"display_name": _("Serial"),
| "description": _("Open a serial connection to your device."),
"handler": self.toggle_repl,
"shortcut": "CTRL+Shift+U",
}
]
if CHARTS:
buttons.append(
{
"name": "plotter",
"display_name": _("... |
selfcommit/gaedav | pyxml/dom/html/HTMLOListElement.py | Python | lgpl-2.1 | 1,873 | 0.007475 | ########################################################################
#
# File Name: HTMLOListElement
#
#
### This file is automatically generated by GenerateHtml.py.
### DO NOT EDIT!
"""
WWW: http://4suite.com/4DOM e-mail: support@4suite.com
Copyright (c) 2000 Fourthought Inc, USA. | All Rights Reserved.
See http://4suite.com/COPYRIGHT for license and copyright information
"""
import string
from pyxml.dom import Node
from pyxml.dom.html.HTMLElement import HTMLElement
class HTMLOListElement(HTMLElement):
def __init__(self, ownerDocument, nodeName="OL"):
HTMLElement.__init__(self,... | t_compact(self):
return self.hasAttribute("COMPACT")
def _set_compact(self, value):
if value:
self.setAttribute("COMPACT", "COMPACT")
else:
self.removeAttribute("COMPACT")
def _get_start(self):
value = self.getAttribute("START")
if value:
... |
SouthStar/portia | slyd/slyd/utils/download.py | Python | bsd-3-clause | 10,593 | 0 | from __future__ import absolute_import
import itertools
import json
import os
import zipfile
from collections import defaultdict
from six import StringIO
from datetime import datetime
from slyd.projecttemplates import templates
import six
REQUIRED_FILES = {'setup.py', 'scrapy.cfg', 'extractors.json', 'items.json',
... | None, added
spider_content = json.dumps(spid | er_data, sort_keys=True, indent=4)
return file_path, spider_content, added
def _spider_templates(self, spider_templates, extractors):
"""
Find all templates for a legacy spider and combine them into a single
list.
"""
templates, added = [], set()
for template... |
xiaoyanit/kivy | setup.py | Python | mit | 35,753 | 0.000112 | #
# Kivy - Crossplatform NUI toolkit
# http://kivy.org/
#
from __future__ import print_function
import sys
from copy import deepcopy
import os
from os.path import join, dirname, sep, exists, basename, isdir, abspath
from os import walk, environ, makedirs, listdir
from distutils.version import LooseVersion
from collec... | ported.
Please install the newest supported version, {1}, if possible, but
the minimum supported version is {0}.
If your platform provides a Cython package, check if you can install
a supported version. Otherwise, uninstall the platform package and
install Cython via pip:
pip install -I Cython=={1}{2}\
... | N_STRING, MAX_CYTHON_STRING,
cython_unsupported_append)
have_cython = False
if platform in ('ios', 'android'):
print('\nCython check avoided.')
else:
try:
# check for cython
from Cython.Distutils import build_ext
have_cython = True
import Cython
cy_version_str... |
tiangolo/fastapi | docs_src/additional_responses/tutorial004.py | Python | mit | 701 | 0 | from typing import Optional
from fastapi import FastAPI
from fastapi.responses import FileResponse
from pydantic import BaseModel
class Item(BaseModel):
id: str
value: str
responses = {
404: {"description": "Item not found"},
302: {"description": "The item was moved"},
403: {"description": "Not... | em_id}",
response_model=Item,
responses={**responses, 200: {"content": {"image/png": {}}}},
)
async def read_item(item_id: str, img: Optional[bool] = None):
if | img:
return FileResponse("image.png", media_type="image/png")
else:
return {"id": "foo", "value": "there goes my hero"}
|
axinging/chromium-crosswalk | third_party/WebKit/Tools/Scripts/webkitpy/common/system/systemhost.py | Python | bsd-3-clause | 2,557 | 0.000782 | # Copyright (c) 2011 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the ... | OWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import os
import platform
import sys
from webkitpy.common.system import environm... | Host(object):
def __init__(self):
self.executable = sys.executable
self.executive = executive.Executive()
self.filesystem = filesystem.FileSystem()
self.user = user.User()
self.platform = platforminfo.PlatformInfo(sys, platform, self.filesystem, self.executive)
self.... |
mohseniaref/PySAR-1 | pysar/_remove_surface.py | Python | mit | 4,681 | 0.044221 | #! /usr/bin/env python
############################################################
# Program is part of PySAR v1.0 #
# Copyright(c) 2013, Heresh Fattahi #
# Author: Heresh Fattahi #
#####################################################... | ane[1]*y1 + plane[2]
elif surf_type == 'plane_range':
zplane= plane[0]*x1 + plane[1]
elif surf_type == 'plane_azim | uth':
zplane= plane[0]*y1 + plane[1]
data_n = data - zplane
data_n[data == 0.] = 0.
data_n = np.array(data_n,np.float32)
return data_n
##################################################################
def remove_surface_timeseries(surf_type,h5file,h5flat,Mask):
# Mask=Mask.flatte... |
ldjebran/robottelo | robottelo/decorators/host.py | Python | gpl-3.0 | 2,027 | 0 | """Implements decorator regarding satellite host"""
import logging
from functools import wraps
import unittest2
from robottelo.config import settings
from robottelo.host_info import get_host_os_version
LOGGER = logging.getLogger(__name__)
def skip_if_os(*versions):
"""Decorator to skip tests based on host vers... | skipped
:returns: ``unittest2.skipIf``
"""
versions = set(map(lambda s: s | .upper(), versions))
def decorator(func):
"""Wrap test methods in order to skip them accordingly with host
version.
"""
@wraps(func)
def wrapper(*args, **kwargs):
"""Wrapper that will skip the test if one of defined versions
match host's version.
... |
horazont/aioxmpp | aioxmpp/version/xso.py | Python | lgpl-3.0 | 1,795 | 0 | ########################################################################
# File name: xso.py
# This file is part of: aioxmpp
#
# LICENSE
#
# This program 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, ... | ; 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
# Li | cense along with this program. If not, see
# <http://www.gnu.org/licenses/>.
#
########################################################################
"""
XSO Definitions
===============
.. autoclass:: Query
"""
import aioxmpp
import aioxmpp.xso as xso
from aioxmpp.utils import namespaces
namespaces.xep0092_versi... |
rmanocha/django-crowdsource | crowdsource/urls.py | Python | bsd-3-clause | 186 | 0.021505 | from django.conf.urls.def | aults import *
urlpatterns = patterns('crowdsource.views',
url(r'^post_cs_entry/$', 'post_csentry', name = 'post-cs-entry') | ,
)
|
KnowNo/reviewboard | reviewboard/ssh/utils.py | Python | mit | 3,229 | 0 | from __future__ import unicode_literals
import os
import paramiko
from django.utils import six
from reviewboard.ssh.client import SSHClient
from reviewboard.ssh.errors import (BadHostKeyError, SSHAuthenticationError,
SSHError)
from reviewboard.ssh.policy import RaiseUnknownHostKey... | , username=None, password=None, namespace=None):
"""
Checks if we can connect to a host with a known key.
This will raise an exception if we cannot connect to the host. The
exception will be | one of BadHostKeyError, UnknownHostKeyError, or
SCMError.
"""
from django.conf import settings
client = SSHClient(namespace=namespace)
client.set_missing_host_key_policy(RaiseUnknownHostKeyPolicy())
kwargs = {}
if ':' in netloc:
hostname, port = netloc.split(':')
port = in... |
victos/busuu_anki | anki/storage.py | Python | agpl-3.0 | 11,169 | 0.00009 | # -*- coding: utf-8 -*-
# Copyright: Damien Elmes <anki@ichi2.net>
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import copy
import os
import re
import json
from anki.collection import _Collection
from anki.consts import *
from anki.db import DB
from anki.lang import _
from anki.stdmo... | return ver
def _upgrade(col, ver):
if ver < 3:
# new deck properties
for d in col.decks.all():
d['dyn'] = 0
d['collapsed'] = False
col.decks.save(d)
if ver < 4:
col.modSchema(check=False)
clozes = []
for m in col.models.all():
... | :
m['type'] = MODEL_STD
col.models.save(m)
else:
clozes.append(m)
for m in clozes:
_upgradeClozeModel(col, m)
col.db.execute("update col set ver = 4")
if ver < 5:
col.db.execute("update cards set odue = 0 where queue = 2... |
dadavidson/Python_Lab | Python-w3resource/Python_Basic/ex88.py | Python | mit | 214 | 0.014019 | # https://www.w3resource.com/python | -exercises/
# 88. Given variables x=30 and y=20, write a Python program to print t "30+20=50"
def addvar(a, b):
| print "%d + %d =%d" % (a,b, a+b)
x = 30
y = 20
addvar(x, y)
|
ftrader/spec_checker | setup.py | Python | agpl-3.0 | 9,048 | 0 | # -*- coding: utf-8 -*-
from __future__ import print_function
import os
import sys
import imp
import subprocess
# Python 2.6 subprocess.check_output compatibility. Thanks Greg Hewgill!
if 'check_output' not in dir(subprocess):
def check_output(cmd_args, *args, **kwargs):
proc = subprocess.Popen(
... | _project_files():
"""Retrieve a list of all non-ignored files, including untracked files,
excluding deleted files.
:return: sorted list of git project files
:rtype: :class:`list`
"""
cached_and_untracked_files = git_ls_files(
'--cached', # All files cached in the index
'--other... | uncommitted_deleted_files = git_ls_files('--deleted')
# Since sorting of files in a set is arbitrary, return a sorted list to
# provide a well-defined order to tools like flake8, etc.
return sorted(cached_and_untracked_files - uncommitted_deleted_files)
def git_ls_files(*cmd_args):
"""Run ``git l... |
to266/hyperspy | hyperspy/_signals/dielectric_function.py | Python | gpl-3.0 | 4,892 | 0.001636 | # -*- coding: utf-8 -*-
# Copyright 2007-2016 The HyperSpy developers
#
# This file is part of HyperSpy.
#
# HyperSpy is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at... | ption) any later version.
#
# HyperSpy 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.
#
# You should have receiv | ed a copy of the GNU General Public License
# along with HyperSpy. If not, see <http://www.gnu.org/licenses/>.
import numpy as np
from scipy import constants
from scipy.integrate import simps, cumtrapz
from hyperspy._signals.spectrum import Spectrum
from hyperspy.misc.eels.tools import eels_constant
class Dielect... |
francisar/rds_manager | aliyun/api/rest/Rds20140815CheckAccountNameAvailableRequest.py | Python | mit | 408 | 0.026961 | '''
Created by auto_sdk o | n 2015.06.23
'''
from aliyun.api.base import RestApi
class Rds20140815CheckAccountNameAvailableRequest(RestApi):
def __init__(self,domain='rds.aliyuncs.com',port=80):
RestApi.__init__(self,domain, port)
self.AccountName = None
self.DBInstanceId = None
self.resourceOwnerAccount = None
def getapiname(self):
... | |
bobslee/orbeon-xml-api | orbeon_xml_api/tests/controls/test_date.py | Python | mit | 2,535 | 0.001183 | # -*- coding: utf-8 -*-
# Copyright 2017-2018 Bob Leers (http://www.novacode.nl)
# See LICENSE file for full licensing details.
from datetime import datetime
from lxml import etree
from . import CommonTestCase
from ..controls import DateControl
|
class DateTestCase(CommonTestCase):
def setUp(self):
super(DateTestCase, self).setUp()
self.control = self.builder. | controls['date']
def test_control(self):
self.assertIsInstance(self.control, DateControl)
date_obj = datetime.strptime('2009-10-16', '%Y-%m-%d').date()
el = etree.Element('test')
el.text = '2009-10-16'
self.assertEqual(self.control.encode(date_obj), '2009-10-16')
... |
PalouseRobosub/robosub | scripts/histogram.py | Python | gpl-3.0 | 4,036 | 0.001487 | #!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
import argparse
import rospy
import rostopic
class Histogram():
def __init__ | (self, arguments):
self. | args = arguments
self.data = {}
self.labels = []
for i in range(0, len(self.args.topics)):
# Get the class type of the requested topic, block until it exists
t_type = rostopic.get_topic_class(self.args.topics[i],
blocking=... |
mauerflitza/Datalogger | Webpage/cgi-bin/loading.py | Python | mit | 952 | 0.047319 | #!/usr/bin/python3
import os
import os.path
import cgi, cgitb
import re
#own packages
import dbcPattern
def dbc_main(): # NEW except for the call to processInput
contents = createHTML() # process input into a page
print(contents)
return -1
def createHTML():
file=open("Header_Saved.html")
html_string = file.... | e)
for line in savings:
match = re.match("html:(?P<html>.*)",line)
if match:
html_string+=match.group("html")
savings.close()
file = open("popula | te.txt")
html_string+=file.read()
file.close()
html_string+="</body>"
return html_string
#Muss später ins Hauptprogramm kopiert werden
try: # NEW
cgitb.enable()
print("Content-Type: text/html;charset:UTF-8") # say generating html
print("\n\n")
dbc_main()
except:
cgi.print_exception() # catch and p... |
MyRequiem/spman | src/main.py | Python | mit | 12,016 | 0.000083 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# main.py file is part of spman
#
# spman - Slackware package manager
# Home page: https://github.com/MyRequiem/spman
#
# Copyright (c) 2018 Vladimir MyRequiem Astrakhan, Russia
# <mrvladislavovich@gmail.com>
# All rights reserved
# See LICENSE for details.
"""
main.py... | oad package or source + SlackBuild script
"""
if len(self.args) < 4:
show_help_mess('error')
# Examples:
# spman --download --src sbo pkg1 pkg2 pkg3
# spman -d --pkg alienbob pkg1 pkg2 pkg3
mode = self.args[1]
repo = self.args[2]
pkglist = sel... | repo == 'sbo':
print('Only SlackBuild script with source code\n'
'can be downloaded from \'sbo\' repository')
show_help_mess('error')
if mode == '--src' and repo == 'multilib':
print('Only binary packages can be\ndownloaded '
'from \'multi... |
NoctuaNivalis/qutebrowser | tests/unit/completion/test_completer.py | Python | gpl-3.0 | 12,192 | 0 | # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2016-2017 Ryan Roden-Corrent (rcorre) <ryan@rcorre.net>
#
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software... | t| general ', 'command', 'set', []),
(':|set general ', 'command', 'set', []),
(':se | t gene|ral ignore-case', 'section', 'general', []),
(':|', 'command', '', []),
(': |', 'command', '', []),
('/|', None, '', []),
(':open -t|', None, '', []),
(':open --tab|', None, '', []),
(':open -t |', 'url', '', []),
(':open --tab |', 'url', '', []),
(':open | -t', 'url', '', []),
... |
adam-miller/h3_py | h3_py/h3.py | Python | apache-2.0 | 8,597 | 0.03001 | #!python3
import requests
import yaml
import time
import enum
import sys
import re
import logging
import ssl
from requests.auth import HTTPDigestAuth
from requests.auth import HTTPBasicAuth
from lxml import etree as ET
from requests.packages.urllib3.exceptions import InsecureRequestWarning
from requests.adapters import... | r" that allows us to use SSLv3."""
def init_poolmanager(self, connections, maxsize, block=False):
self.poolmanager = PoolManager(
num_pools=connections, maxsize=maxsize,
block=block, ssl_version=ssl.PROTOCOL_SSLv3)
session = requests.Session()
session.mount('https://wbgrp-crawl',Ss... | rawl_Status():
none = "None"
unbuilt = "Unbuilt"
ready = "Ready"
paused = "Active: PAUSED"
running = "Active: RUNNING"
finished = "Finished: ABORTED"
class Crawl_Actions():
build = "build"
launch = "launch"
unpause = "unpause"
pause = "pause"
checkpoint = "checkpoint"
terminate = "terminate"
teardown = "... |
chokribr/invenio | setup.py | Python | gpl-2.0 | 11,954 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2013, 2014, 2015 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 optio... |
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""Invenio is a framework for digit | al libraries and data repositories.
Invenio enables you to run your own digital library or document
repository on the web. Invenio covers all aspects of digital library
management, from document ingestion, through classification, indexing
and further processing, to curation, archiving, and dissemination.
The flexibil... |
ilee/projects | django/firstproject/firstproject/wsgi.py | Python | mit | 399 | 0.002506 | """
WSGI config for firstproject project.
It exposes the WSGI callable as a | module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "firstproject.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application(... | |
EmuKit/emukit | emukit/core/acquisition/acquisition.py | Python | apache-2.0 | 8,967 | 0.003792 | # Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import abc
from typing import Tuple
import numpy as np
class Acquisition(abc.ABC):
"""Acquisition base class"""
def __add__(self, other: "Acquisition") -> "Sum":
"""
Overloads se... | ion_1 = acquisition_1
self.acquisition_2 = acquisition_2
def evaluate(self, x: np.ndarray) -> np.ndarray:
"""
Evaluate product of the two acquisition functions
:param x: (n_points x n_dims) array of points at which to calculate acquisition function values
:return: (n_points... | .ndarray) -> Tuple[np.ndarray, np.ndarray]:
"""
Evaluate value and gradient of acquisition function at x
:param x: (n_points x n_dims) array of points at which to calculate acquisition function values and gradient
:return: Tuple contains an (n_points x 1) array of acquisition function v... |
coala/coala | tests/bearlib/aspects/SubTest.py | Python | agpl-3.0 | 2,585 | 0 | from coalib.bearlib.aspects import Root, aspectclass, TasteError
from coalib.bearlib.aspects.base import | aspectbase
import pytest
class SubAspectTest:
| def test_class(self, SubAspect):
assert isinstance(SubAspect, aspectclass)
assert issubclass(SubAspect, aspectbase)
def test_class_tastes_recreation(self, SubAspect):
assert SubAspect.tastes is not SubAspect.tastes
def test_class_tastes_items(self, SubAspect, SubAspect_tastes):
... |
dscorbett/pygments | pygments/lexers/nit.py | Python | bsd-2-clause | 2,719 | 0.002942 | """
pygments.lexers.nit
~~~~~~~~~~~~~~~~~~~
Lexer for the Nit language.
:copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.lexer import RegexLexer, words
from pygments.token import Text, Comment, Operator, Keyword, Name, St... | \{\{?)*""""*', String), # End long string
(r'"(\\.|([^"}{\\]))*"', String), # Simple String
(r'"(\\.|([^"}{\\]))*\{', String), # Start string
| (r'\}(\\.|([^"}{\\]))*\{', String), # Mid String
(r'\}(\\.|([^"}{\\]))*"', String), # End String
(r'(\'[^\'\\]\')|(\'\\.\')', String.Char),
(r'[0-9]+', Number.Integer),
(r'[0-9]*.[0-9]+', Number.Float),
(r'0(x|X)[0-9A-Fa-f]+', Number.Hex),
(r'... |
ychen820/microblog | y/google-cloud-sdk/platform/google_appengine/lib/django-1.5/django/contrib/formtools/tests/wizard/forms.py | Python | bsd-3-clause | 7,721 | 0.001943 | from __future__ import unicode_literals
from django import forms, http
from django.conf import settings
from django.db import models
from django.test import TestCase
from django.template.response import TemplateResponse
from django.utils.importlib import import_module
from django.contrib.auth.models import User
from... | uest = get_request()
testform = TestWizard.as_view([('start', Step1), ('step2', Step2)])
response, instance = testform(request)
instance.render_done(None)
self.assertEqual(instance.storage.current_step, 'start')
class SessionFormTests(TestCase):
def test_init(self):
reques... | ([('start', Step1)])
self.assertTrue(isinstance(testform(request), TemplateResponse))
class CookieFormTests(TestCase):
def test_init(self):
request = get_request()
testform = CookieWizardView.as_view([('start', Step1)])
self.assertTrue(isinstance(testform(request), TemplateResponse... |
wangtaoking1/found_website | 项目代码/html5lib/tests/test_tokenizer.py | Python | gpl-2.0 | 6,826 | 0.00542 | import sys
import os
import unittest
import cStringIO
import warnings
import re
try:
import json
except ImportError:
import simplejson as json
from support import html5lib_test_files
from html5lib.tokenizer import HTMLTokenizer
from html5lib import constants
class TokenizerTestParser(object):
def __init_... | n[1] = decode(token[1])
if len(token) > 2:
for key, value in token[2]:
del token[2][key]
token[2][decode(key)] = decode(value)
return test
def runTokenizerTest(test):
#XXX - move this out into the setup function
#concatenate all consecuti... | expected = concatenateCharacterTokens(test['output'])
if 'lastStartTag' not in test:
test['lastStartTag'] = None
outBuffer = cStringIO.StringIO()
stdout = sys.stdout
sys.stdout = outBuffer
parser = TokenizerTestParser(test['initialState'],
test... |
HughMcGrade/eusay | votes/tests.py | Python | gpl-2.0 | 45 | 0 | fr | om django.test import TestCase
# No t | ests
|
mtreinish/stestr | stestr/commands/failing.py | Python | apache-2.0 | 4,990 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under th... | sys.stdout.buffer.write(stream.read())
else:
sys.stdout.write(stream.read())
return 0
def _make_result(repo, list_tests=False, stdout=sys.stdout):
if list_tests:
list_result = testtools.StreamSummary()
return list_result, list_result
else:
def _get_id():
ret... | lt.get_summary()
return output_result, summary_result
def failing(repo_type='file', repo_url=None, list_tests=False, subunit=False,
stdout=sys.stdout):
"""Print the failing tests from the most recent run in the repository
This function will print to STDOUT whether there are any tests that... |
rfleschenberg/django-shop | shop/management/commands/shopcustomers.py | Python | bsd-3-clause | 1,580 | 0.003165 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import BaseCommand
from django.utils.translation import ugettext_lazy as _
class Command(BaseCommand):
help = _("Collect information about all customers which accessed this shop.")
... | data['registered'] += 1
elif customer.is_guest():
data['guests'] += 1
elif customer.is_anonymous():
data['anonymous'] += 1
if customer.is_expired():
data['expired'] += 1
if delete_expired:
custom... | stered={registered}, staff={staff}.")
self.stdout.write(msg.format(**data))
|
freyes/juju | scripts/find-bad-doc-comments.py | Python | agpl-3.0 | 3,504 | 0.004281 | #!/usr/bin/python
# Copyright 2014 Canonical Ltd.
# Licensed under the AGPLv3, see LICENCE file for details.
"""
This quick-and-dirty tool locates Go doc comments in a source tree
that don't follow the convention of the first word of the comment
matching the function name. It highlights cases where doc comments
haven... | in os.walk(root):
for filename in fnmatch.filter(files, '*.go'):
yield path.join(directory, filename)
DOC_COMMENT_PATT = '\n\n//.+\n(//.+\n)*func.+\n'
FIRST_WORD_PATT = '// *(\w+)'
FUNC_NAME_PATT = 'func(?: \([^)]+\))? (\S+)\('
def extract_doc_comments(text):
for match in re.finditer(DOC_COMME... | ments(comments):
for comment in comments:
lines = comment.splitlines()
first_word_match = re.match(FIRST_WORD_PATT, lines[0])
if first_word_match:
first_word = first_word_match.group(1)
func_name = re.match(FUNC_NAME_PATT, lines[-1]).group(1)
if first_word... |
asm-products/spawnsong | apps/spawnsong/migrations/0010_auto__add_field_order_purchaser_email__chg_field_order_purchaser.py | Python | agpl-3.0 | 9,105 | 0.008018 | # -*- 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):
# Adding field 'Order.purchaser_email'
db.add_column(u'spawnsong_order', 'purchaser_email',
... | anyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
u'auth.permission': {
'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
... | ey', [], {'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'auth.user': {
'Meta': {'object_name': 'User'},
'da... |
kcarnold/autograd | autograd/numpy/complex_array_node.py | Python | mit | 1,079 | 0.006487 | from __future__ import absolute_import
from autograd.core import Node, ComplexNode, primitive, cast, getval
from . import numpy_wrapper as anp
from .numpy_extra import ArrayNode, array_dtype_mappings, SparseArray
cla | ss ComplexArrayNode(ArrayNode):
@staticmethod
def zeros_like(value):
return anp.zeros(value.shape) + 0.0j
@staticmethod
def cast(value, example):
result = complex_arraycast(value)
| if result.shape != example.shape:
result = result.reshape(example.shape)
return result
@staticmethod
def new_sparse_array(template, idx, x):
return ComplexSparseArray(template, idx, x)
for complex_type in [anp.complex64, anp.complex128]:
array_dtype_mappings[anp.dtype(comp... |
egbertbouman/idomaar | datastreammanager/orchestrator/test/test_recommendation_manager.py | Python | apache-2.0 | 395 | 0.017722 | import logging
from recommendation_manager import RecommendationManager
def test_config_generation():
manager = RecommendationManager(name="test", executor=None, config_base_dir='../../flume-config/config')
manager.create_co | nfiguration(recommendation_target="fs:/tmp/recommendations")
if __name__ == "__main__" | :
logging.basicConfig(level = "INFO")
test_config_generation()
|
mythkiven/python | Training/untitled/05_其他知识点.py | Python | mit | 190 | 0.02809 | # coding | =utf-8
# 文件写
f = open('test.txt','a')
for i in range(10):
f.write('hello,')
f. | write('world!\n')
f.close()
#文件读
ff= open('test.txt','r')
d = ff.read(4)
print d |
beeftornado/sentry | tests/sentry/plugins/bases/notify/tests.py | Python | bsd-3-clause | 3,112 | 0.001285 | from __future__ import absolute_import
from six.moves.urllib.parse import urlparse, parse_qs
from requests.exceptions import HTTPError, SSLError
from sentry_plugins.base import CorePluginMixin
from sentry.exceptions import PluginError
from sentry.shared_integrations.exceptions import ApiError, ApiHostError, ApiUnauth... | turn True
class NotifyPlugin(TestCase):
def test_add_notification_referrer_param(self):
n = DummyNotificationPlugin()
n.slug = "slack"
url = "https://sentry.io/"
assert n.add_notification_referrer_param(url) == url + "?referrer=" + n.slug
url = "https://sentry.io/?referrer... | "https://sentry.io/?referrer=slack"
url = "https://sentry.io/?utm_source=google"
with_referrer = n.add_notification_referrer_param(url)
# XXX(py3): Handle ordering differences between py2/3
assert parse_qs(urlparse(with_referrer).query) == parse_qs(
"referrer=slack&utm_sou... |
mrakitin/sirepo | sirepo/sim_data/elegant.py | Python | apache-2.0 | 5,814 | 0.001204 | # -*- coding: utf-8 -*-
u"""simulation data operations
:copyright: Copyright (c) 2019 RadiaSoft LLC. All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from __future__ import absolute_import, division, print_function
from pykern.pkcollections import PKDict
from pykern.pkdebug import pk... | m.filename = '1'
if m.mode == 'coordinates' or m.mode == 'coord':
m.mode = 'coordinate'
cls.update_model_defaults(m, m.type)
if 'centroid' not in dm.bunch:
b = dm.bunch
for f in 'emit_x', 'emit_y', 'emit_z':
| if b[f] and not isinstance(b[f], basestring):
b[f] /= 1e9
if b.sigma_s and not isinstance(b.sigma_s, basestring):
b.sigma_s /= 1e6
c = cls.__find_first_bunch_command(data)
# first_bunch_command may not exist if the elegant sim has no bunche... |
craiglabenz/django-grapevine | tests/core/models.py | Python | mit | 1,420 | 0.000704 | from __future__ import unicode_literals
# Django
from django.conf import settings
from django.db import models
# 3rd Party
from grapevine import generics
from grapevine.models.base import GrapevineModel
from model_utils.managers import PassThroughManager
# Local Apps
from .querysets import WelcomeEmailQuerySet
cla... | r()
except AttributeError:
# This handles Django <= 1.6
objects = PassThroughManager.for_queryset_class(WelcomeEmailQuerySet)()
class Meta:
verbose_name = "Welcome Email"
verbose_name_plural = "Welcome Emails"
def as_str(self):
return "Welcome Email to {0}".format(s... | def get_template_name(self):
return "emails/welcome.html"
def get_raw_subject(self):
return "Welcome to Acme Inc, {{ sendable.user }}!"
def get_recipients(self):
return {"to": [self.user.email], "bcc": ["top@secret.com"]}
def confirm_individual_sendability(self):
"""Only s... |
CaptainDesAstres/Blender-Render-Manager | Preferences/PresetList/RenderlayerGroup/RenderlayerGroup.py | Python | mit | 7,147 | 0.065991 | #!/usr/bin/python3.4
# -*-coding:Utf-8 -*
'''module to manage Renderlayer group'''
import xml.etree.ElementTree as xmlMod
import os, re
class RLGroup:
'''class to manage Renderlayer group'''
def __init__(self, keywords = None, xml= None):
'''initialize Renderlayer group with default value or values extracted f... | len(self.keywords):
log.error('No keywords corresponding to this index number!')
continue
log.menuOut()
return choice
def search(self, key):
'''A method to check if a keyword is used by the group'''
return key in self.keywords
def add(self, log, RLGlist):
'''A | method to add a new keyword'''
log.menuIn('Add Keywords')
while True:
log.print()
print('\n\n Add Keyword :\n\n')
keys = input('Type keywords to add (separed by ";") : ').strip()
if keys.lower() in ['', 'q']:
log.menuOut()
return False
keys = keys.split(';')
for i... |
USGSDenverPychron/pychron | pychron/experiment/__init__.py | Python | apache-2.0 | 1,484 | 0 | # ===============================================================================
# Copyright 2011 Jake Ross
#
# 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/licens... | 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.
# ===============================================================================
__ver... | lf, msg):
self._msg = msg
def __str__(self):
return "{}: {} Failed".format(self.tag, self._msg)
class PreExtractionCheckException(CheckException):
tag = "PreExtraction"
class PreExecuteCheckException(CheckException):
tag = "PreExecute"
def __init__(self, msg, error=None):
s... |
okamstudio/godot | modules/mono/build_scripts/godotsharptools_build.py | Python | mit | 8,471 | 0.001062 | # Build GodotSharpT | ools solution
import os
from SCons.Script import Builder, Dir
def find_nuget_unix():
import os
if 'NUGET_PATH' in os.environ:
hint_path = os.environ['NUGET_PATH']
| if os.path.isfile(hint_path) and os.access(hint_path, os.X_OK):
return hint_path
hint_path = os.path.join(hint_path, 'nuget')
if os.path.isfile(hint_path) and os.access(hint_path, os.X_OK):
return hint_path
import os.path
import sys
hint_dirs = ['/opt/novell/... |
choderalab/perses | perses/tests/test_relative_point_mutation_setup.py | Python | mit | 1,033 | 0 | def test_PointMutationExecutor():
from pkg_resour | ces import resource_filename
from simtk import unit
from perses.app.relative_point_mutation_setup import PointMutationExecutor
pdb_filename = resource_filename("perses", "data/ala_vacuum.pdb")
PointMutationExecutor(
pdb_filename,
"1",
"2",
"ASP",
ionic_strength=... | olar,
flatten_torsions=True,
flatten_exceptions=True,
conduct_endstate_validation=False,
)
def test_PointMutationExecutor_endstate_validation():
from pkg_resources import resource_filename
from simtk import unit
from perses.app.relative_point_mutation_setup import PointMutatio... |
ProfessorX/Config | .PyCharm30/system/python_stubs/-1247972723/PyKDE4/kdeui/KXMLGUIFactory.py | Python | gpl-2.0 | 2,060 | 0.011165 | # encoding: utf-8
# module PyKDE4.kdeui
# from /usr/lib/python2.7/dist-packages/PyKDE4/kdeui.so
# by generator 1.135
# no doc
# imports
import PyKDE4.kdecore as __PyKDE4_kdecore
import PyQt4.QtCore as __PyQt4_QtCore
import PyQt4.QtGui as __PyQt4_QtGui
import PyQt4.QtSvg as __PyQt4_QtSvg
class KXMLGUIFactory(__PyQt4_... | f readConfigFile(self, *args, **kwargs): # real signature unknown
pass
def refreshActionProperties(self, *a | rgs, **kwargs): # real signature unknown
pass
def removeClient(self, *args, **kwargs): # real signature unknown
pass
def reset(self, *args, **kwargs): # real signature unknown
pass
def resetContainer(self, *args, **kwargs): # real signature unknown
pass
def saveConfig... |
RedHatInsights/insights-core | insights/tests/client/phase/test_LEGACY_post_update.py | Python | apache-2.0 | 3,188 | 0.002196 | # -*- coding: UTF-8 -*-
from insights.client.phase.v1 import post_update
from mock.mock import patch
from pytest import raises
def patch_insights_config(old_function):
patcher = patch("insights.client.phase.v1.InsightsConfig",
**{"return_value.load_all.return_value.status": False,
... | se.v1.InsightsClient")
def test_exit_ok(insights_config, insights_client):
"""
Support collection replaces the normal client run.
"""
with raises(SystemExit) as exc_info:
post_update()
assert exc_info.value.code == 0
@patch("insights.client.phase.v1.InsightsClient")
@patch_insights_config
... | s_client):
"""
No-upload short circuits this phase
"""
insights_config.return_value.load_all.return_value.no_upload = True
try:
post_update()
except SystemExit:
pass
insights_client.return_value.register.assert_not_called()
insights_client.return_value.get_machine_id.asse... |
hiliev/py-zfs-rescue | zfs/zio.py | Python | bsd-3-clause | 12,640 | 0.004272 | # Copyright (c) 2017 Hristo Iliev <github@hiliev.eu>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of c... | hild_devs, block_provider_addr, dump_dir="/tmp"):
self._devs = child_devs
self._bp = BlockProxy(block_provider_addr)
self._dump_dir = dump_dir
self._verbose = LOG_QUIET
def set_verbosity_level(self, level):
self._verbose = level
def read_block(self, bptr, dva=0, debug_d... | :
return None,False
if bptr.get_dva(dva).gang:
# TODO: Implement gang blocks
raise NotImplementedError("Gang blocks are still not supported")
offset = bptr.get_dva(dva).offset
asize = bptr.get_dva(dva)._asize
psize = bptr.psize
if offset == 0 a... |
vicky2135/lucious | oscar/lib/python2.7/site-packages/phonenumbers/data/region_BG.py | Python | bsd-3-clause | 2,961 | 0.007768 | """Auto-generated file, do not edit by hand. BG metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_BG = PhoneMetadata(id='BG', country_code=359, international_prefix='00',
general_desc=PhoneNumberDesc(national_number_pattern='[23567]\\d{5,7}|[489]\\d{6,8}', possible... | ,9}', example_number='48123456', possible_length=(8, 9)),
toll_free=PhoneNumberD | esc(national_number_pattern='800\\d{5}', possible_number_pattern='\\d{8}', example_number='80012345', possible_length=(8,)),
premium_rate=PhoneNumberDesc(national_number_pattern='90\\d{6}', possible_number_pattern='\\d{8}', example_number='90123456', possible_length=(8,)),
shared_cost=PhoneNumberDesc(),
per... |
Zephyrrus/ubb | YEAR 1/SEM1/FP/LAB/l6-l9/Domain/IModel.py | Python | mit | 1,500 | 0.004 | from copy import deepcopy
class IModel():
def __init__(self):
self.list = []
def __getitem__(self, index):
'''
Getter for the [] operator
'''
if index >= len(self.list):
raise IndexError("Index out of range.")
return self.list[index]
def __seti... | -= 1
else:
i += 1
return cpy
def _filter(list, f):
result = []
for e in list:
if f(e):
result.append(e)
return result
if __name__ == "__main__":
a = IModel()
a.extend(4)
print(a.list)
a[0] = 15
a[1] = 10
a[2] = 5
a[3] = 3
for i i... | ")
for i in gnomeSort(a):
print(i)
print("-----------")
for i in _filter(a, lambda x: x % 5):
print(i) |
aldanor/ipybind | ipybind/notebook.py | Python | mit | 661 | 0.003026 | # -*- coding: utf-8 -*-
from IPython.core.display import Javascript, HTML, display_javascript, display_html
def setup_notebook():
# assign text/x-c++src MIME type to pybind11 cells
code = """
require(['notebook/js/codecell'], function(cc) {
cc.Code | Cell.options_default.highlight_modes['magic_text/x-c++src'] =
{reg: [/^\s*%%pybind11/]};
});
"""
display_javascript(Javascript(data=code))
# assign non-black colour to C/C++ keywords
html = """
<style>
.cm-s-ipython span.cm-variable-3 {
color: #208ffb;
font-weigh... | le>
"""
display_html(HTML(data=html))
|
soupmonkey/pushcoin | PoS/payment-processor/pushcoin-payment-processor.py | Python | gpl-3.0 | 1,933 | 0.021211 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2012 Slawomir Lisznianski <sl@minta.com>
#
# GNU General Public Licence (GPL)
#
# 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; eithe... | _fields() ) )
# handle PTA from the scanner
proc.onDataArrived.connect(main.process_data)
proc.onStatus.connect(main.statusbar.showMessage)
scanner.onData.connect(proc.parse_pcos)
scanner.onStatus.connect(main.scannerStatus.setText)
# show main window
main.show()
# start the scanner
scanner.start()
# ent... | r.wait()
sys.exit(rc)
|
pavlovicr/bac | bac/contrib/sites/migrations/0003_set_site_domain_and_name.py | Python | mit | 1,071 | 0 | """
To understand why this file is here, please read:
http://cookiecutter-django.readthedocs.io/en/latest/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django
"""
from django.conf import settings
from django.db import migrations
def update_site_forward(apps, schema_editor):
"""Set site d... | perations = [
migrations.RunPython(update_site_forward, update_si | te_backward),
]
|
uname/PySockDebuger | form/CreateUdpClientDialog.py | Python | apache-2.0 | 2,370 | 0.010127 | #-*- coding: utf-8 -*-
import utils
import signals
import config
import error
from CreateDialog import CreateDialog
from ui.Ui_CreateUdpClientForm import Ui_CreateUdpClientForm
from PyQt4 import QtGui
from PyQt4 import QtCore
class CreateUdpClientDialog(CreateDialog):
def __init__(self, parent=None):
Cre... | return
localPort = int(strLocalPort)
if not utils.isPortOk(localPort):
return
if not strRemotePort.isdigit():
return
re | motePort = int(strRemotePort)
if not utils.isPortOk(remotePort):
return
self.emit(signals.SIG_CREATE_UDP_CLIENT, utils.qstr2str(self.ui.ipCmbBox.currentText()), remotePort, localPort)
self.close()
def onBroadcastBtnClicked(self):
curIp = utils.qstr2str(self.ui.... |
getsmap/smap-responsive | ws/cherrypy/libs/proxy.py | Python | gpl-3.0 | 2,703 | 0.005179 | #!/usr/bin/python
"""This is a blind proxy that we use to get around browser
restrictions that prevent the Javascript from loading pages not on the
same server as the Javascript. This has several problems: it's less
efficient, it might break some sites, and it's a security risk because
people can use this proxy to b... | urllib2.urlopen(r)
else:
y = urllib2.urlopen(url)
# out += content type header
i = y.info()
if i.has_key("Content-Type"):
outMi | meType = "%s" % (i["Content-Type"])
out += y.read()
y.close()
else:
out += ""
out += "Illegal request."
except Exception, E:
out += "Status: 500 Unexpected Error"
out += ""
out += "Some unexpected error occurred. Error text was: " # E... |
dimara/synnefo | snf-astakos-app/astakos/api/projects.py | Python | gpl-3.0 | 21,618 | 0.000093 | # Copyright (C) 2010-2015 GRNET S.A.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed i... | not, see <http://www.gnu.org/licenses/>.
import operator
from django.utils import simplejson as json
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from django.db.models import Q |
from astakos.im import transaction
from astakos.api.util import json_response
from snf_django.lib import api
from snf_django.lib.api import faults
from snf_django.lib.api import utils
from .util import user_from_token, invert_dict, check_is_dict
from astakos.im import functions
from astakos.im.models import (
A... |
diN0bot/ProcrasDonate | procrasdonate/migrations/0002_is_sponsored.py | Python | agpl-3.0 | 28,500 | 0.00814 |
from south.db import db
from django.db import models
from procrasdonate.models import *
class Migration:
def forwards(self, orm):
# Adding field 'Recipient.is_sponsored'
db.add_column('procrasdonate_recipient', 'is_sponsored', orm['procrasdonate.Recipient:is_sponsored'])
... | def backwards(self, orm):
# Deleting field 'Recipient.is_sponsored'
db.delete_column('procrasdonate_recipient', 'is_sponsored')
models = {
'auth.group': {
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': (... | 'auth.Permission']", 'blank': 'True'})
},
'auth.permission': {
'Meta': {'unique_together': "(('content_type', 'codename'),)"},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.