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 |
|---|---|---|---|---|---|---|---|---|
eliethesaiyan/ObliviousDecisionTree | ObliviousTree.py | Python | mit | 3,395 | 0.032401 | import numpy as np
class ObliviousTree:
'This is an implementation of Oblvious Tree'
def __init__(self,data=[],func="C4.5",autoload=False):
self.data=data
self.split_funct=func
self.autoload=autoload
self.feature_names=self.data.columns.tolist()
self.feature_name_doma... | lf):
is_root=True
for feature_name in self.feature_name_domains:
level_list_nodes=[]
if fea | ture_name=="label":
continue
if is_root:
root_edge_list=[]
print(feature_name)
root_domain=self.feature_name_domains[feature_name]
root=Node(feature_name,self.data,100.0,root_domain)
for domain in root_domain: ... |
cryptickp/python-neutronclient | neutronclient/tests/unit/test_cli20.py | Python | apache-2.0 | 31,625 | 0 | # Copyright 2012 OpenStack Foundation.
# All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | self.content.append(text)
def make_string(self):
result = ''
for line in self.content:
result = result + line
return result
class MyResp(object):
def __init__(self, status_code, headers=None, reason=None):
self.status_code = status_code
| self.headers = headers or {}
self.reason = reason
class MyApp(object):
def __init__(self, _stdout):
self.stdout = _stdout
def end_url(path, query=None, format=FORMAT):
_url_str = ENDURL + "/v" + API_VERSION + path + "." + format
return query and _url_str + "?" + query or _url_str
cla... |
CaliOpen/CaliOpen | src/backend/components/py.pi/caliopen_pi/features/mail.py | Python | gpl-3.0 | 8,082 | 0 | # -*- coding: utf-8 -*-
"""Caliopen mail message privacy features extraction methods."""
from __future__ import absolute_import, print_function, unicode_literals
import logging
import pgpy
from caliopen_main.pi.parameters import PIParameter
from .helpers.spam import SpamScorer
from .helpers.ingress_path import get_i... | if not whitelistes:
return False
if mx in whitelistes:
return True
return False
@property
def internal_domains(self):
"""Get internal hosts from configuration."""
domains = self.config | .get('internal_domains')
return domains if domains else []
def emitter_reputation(self, mx):
"""Return features about emitter."""
if self.is_blacklist_mx(mx):
return 'blacklisted'
if self.is_whitelist_mx(mx):
return 'whitelisted'
return 'unknown'
... |
google/fhir | py/google/fhir/stu3/json_format_test.py | Python | apache-2.0 | 70,708 | 0.003974 | #
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | ChoiceType_succeeds(
self, file_name: str):
"""Tests parsing/printing with a primitive ext | ension nested choice field."""
self.assert_parse_and_print_spec_equals_golden(file_name,
resources_pb2.CodeSystem)
@parameterized.named_parameters(
('_withAccountExample', 'Account-example'),
('_withAccountEwg', 'Account-ewg'),
)
def testJsonForm... |
fstagni/DIRAC | FrameworkSystem/DB/UserProfileDB.py | Python | gpl-3.0 | 26,525 | 0.009425 | """ UserProfileDB class is a front-end to the User Profile Database
"""
from __future__ import print_function
__RCSID__ = "$Id$"
import os
import sys
import hashlib
from DIRAC import S_OK, S_ERROR, gLogger, gConfig
from DIRAC.Core.Utilities import Time
from DIRAC.ConfigurationSystem.Client.Helpers import Registry
fr... | PrimaryKey': ['UserId', 'GroupId', 'TagName'],
'Indexes': {'HashKey': ['UserId', 'HashTag']},
'Engine': 'InnoDB',
| },
}
def __init__(self):
""" Constructor
"""
self.__permValues = ['USER', 'GROUP', 'VO', 'ALL']
self.__permAttrs = ['ReadAccess', 'PublishAccess']
DB.__init__(self, 'UserProfileDB', 'Framework/UserProfileDB')
retVal = self.__initializeDB()
if not... |
nicocardiel/xmegara | check_wlcalib_rss.py | Python | gpl-3.0 | 6,805 | 0 | from __future__ import division
from __future__ import print_function
import argparse
import astropy.io.fits as fits
import numpy as np
import os
from numina.array.display.ximplot import ximplot
from numina.array.display.ximshow import ximshow
from numina.array.wavecalib.check_wlcalib import check_wlcalib_sp
from nu... | image.
crpix1: float
CRPIX1 keyword.
crval1: float
CRVAL1 keyword.
cdelt1: float
CDELT1 keyword.
"""
# read the 2d image
with fits.open(fitsfile) as hdulist:
image2d_header = hdulist[0].header
image2d = hdulist[0].data
naxis2, naxis1 = image2d.shape... | 1)
print('>>> NAXIS2:', naxis2)
print('>>> CRPIX1:', crpix1)
print('>>> CRVAL1:', crval1)
print('>>> CDELT1:', cdelt1)
if abs(debugplot) in (21, 22):
ximshow(image2d, show=True,
title='Wavelength calibrated RSS image', debugplot=debugplot)
# set to zero a few pixels at ... |
bsmedberg/socorro | webapp-django/crashstats/supersearch/form_fields.py | Python | mpl-2.0 | 4,545 | 0 | from django import forms
OPERATORS = (
'__true__', '__null__', '$', '~', '^', '=', '<=', '>=', '<', '>',
'!__true__', '!__null__', '!$', '!~', '!^', '!=', '!'
)
def split_on_operator(value):
for operator in sorted(OPERATORS, key=len, reverse=True):
if value.startswith(operator):
valu... | rField):
pass
class DateTimeField(MultiplePrefixedValueField, forms.DateTimeField):
def value_to_string(self, value):
try:
return value.i | soformat()
except AttributeError: # when value is None
return value
class StringField(MultipleValueField):
"""A CharField with a different name, to be considered as a string
by the dynamic_form.js library. This basically enables string operators
on that field ("contains", "starts with... |
MSMBA/msmba-workflow | msmba-workflow/srclib/wax/examples/simplebuttons4.py | Python | gpl-2.0 | 368 | 0.008152 | # simplebuttons4.py
# Button with a | border...
import sys
sys.path.append("../..")
from wax import *
WaxConfig.default_font = ("Verdana", 9)
class MainFrame(Frame):
def Body(self):
b = Button(self, "one")
b.SetSize((80, 80))
self.AddComponent(b, expand='both', border=15)
self.Pack()
app = Application(MainFrame)
app... | nLoop()
|
knightjdr/screenhits | api/app/scripts/CRISPR/MAGeCK/v0.01/lib/python2.7/site-packages/mageck/mleclassdef.py | Python | mit | 4,322 | 0.048126 | '''
Class definition
'''
from __future__ import print_function
# from IPython.core.debugger import Tracer
class SimCaseSimple:
prefix='sample1'
# the beta parameters; beta0 is the base value (a list of double, size nsgRNA)
beta0=[]
# beta1 (a nsample*r) is the beta values of different conditions
beta1=[0]
... | te_pval_pos']
fdr_label_list=[x+'_fdr' for x in pvaluelabel_list]
for ii in range(len(pvaluelabel_list)):
pvaluemat_list=[]
var_fdr_list=[]
#whichp='beta_pval'
#writep='beta_pval_fdr'
whichp=pvaluelabel_list[ii]
writep=fdr_label_list[ii]
for (gene,ginst) in allgenedict.iteritems():
... | =getattr(ginst,whichp)
pvaluemat_list+=[tlist]
#
import numpy as np
from mageck.fdr_calculation import pFDR
pvaluemat=np.matrix(pvaluemat_list)
pvaluemat_t=pvaluemat.getT()
# row by row
for cid in range(pvaluemat_t.shape[0]):
p_vec=pvaluemat_t[cid,:].getA1().tolist()
fdr_v... |
silvau/Addons_Odoo | compute_sheet_oisa/hr_payroll.py | Python | gpl-2.0 | 631 | 0.025357 | # -*- encoding: utf-8 -*-
from openerp.osv import osv,fields
class hr_payslip_run(osv.Model):
_inherit = 'hr.payslip.run'
| def compute_sheet_all(self, cr, uid, ids, context=None):
|
payslip_obj=self.pool.get('hr.payslip')
payslip_run_obj=self.pool.get('hr.payslip.run')
my_slip_ids=payslip_run_obj.read(cr,uid,ids,['slip_ids'])
for slip in my_slip_ids[0]['slip_ids']:
child_slip=payslip_obj.browse(cr,uid,slip)
child_slip.compute_sheet(... |
spapageo0x01/dioskrS | layer_block.py | Python | gpl-3.0 | 1,354 | 0.011078 | import os
import inspect
import sys
class BlockStore:
def __init__(self, input_file, block_size, output_dir):
self.input_file = input_file
self.block_size = block_size
file_size = os.stat(input_file).st_size
print | 'file_size: %d' % file_size
#Should handle this later on.
if (file_size < block_size):
print 'File provided is smaller than the deduplication block size.'
sys.exit(0)
if not (os.path.isdir(output_dir)):
print 'Output directory "%s" does not exist. Will creat... | :
self.file_fp = os.open(self.input_file, os.O_DIRECT | os.O_RDONLY)
except Exception as e:
frame = inspect.currentframe()
info = inspect.getframeinfo(frame)
print '\t[fopen: an %s exception occured | line: %d]' % (type(e).__name__, info.lineno)
sys.exit(0)
... |
scharron/elasticsearch-river-mysql | http_stream/http_stream.py | Python | apache-2.0 | 1,681 | 0.009518 | #!/usr/bin/env python
#
# Update a redis server cache when an evenement is trigger
# in MySQL replication log
#
from pymysqlreplication import BinLogStreamReader
from pymysqlreplication.row_event import *
mysql_settings = {'host': '127.0.0.1', 'port': 3306, 'user': 'root', 'passwd': ''}
import json
import cherrypy
c... | (binlogevent, UpdateRowsEvent):
yield json.dumps | ({
"action": "update",
"id": row["after_values"]["id"],
"doc": row["after_values"]}) + "\n"
elif isinstance(binlogevent, WriteRowsEvent):
yield json.dumps({
"action": "inse... |
PaulFlorea/Orbis2014 | lib/tronclient/SocketChannel.py | Python | mit | 2,095 | 0.015752 | import socket
import struct
import sys
from time import sleep
import logging
class SocketChannelFactory():
'''
Provides method to create channel connection.
'''
def openChannel(self, host, port):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))... | hile attempting to read")
raise Exception("socket broken or connection closed")
buf += data
n -= len(data)
return | buf
def close(self):
print("closing connection")
self.sock.close()
self.connected = False
|
yland/mailman3 | src/mailman/interfaces/runner.py | Python | gpl-2.0 | 4,700 | 0.000426 | # Copyright (C) 2007-2015 by the Free Software Foundation, Inc.
#
# This file is part of GNU Mailman.
#
# GNU Mailman is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at you... | Can be overridden by subclasses.
:return: The number of files still left to process.
:rtype: int
"""
def _process_one_file(msg, msgdata):
"""Process one queue file.
:param msg: The message object.
:type msg: `email.message.Message`
:param msgdata: The messa... | ed, this should perform any
necessary resource deallocation.
"""
def _dispose(mlist, msg, msgdata):
"""Dispose of a single message destined for a mailing list.
Called for each message that the runner is responsible for, this is
the primary overridable method for processing ... |
wschuell/experiment_manager | experiment_manager/job_queue/plafrim.py | Python | agpl-3.0 | 1,067 | 0.035614 |
from .slurm import SlurmJo | bQueue,OldSlurmJobQueue
class PlafrimJobQueue(SlurmJobQueue):
def __init__(self, username=None,hostname='plafrim-ext', basedir=None, local_basedir='', base_work_dir=None, max_jobs=100, key_file='plafrim', password=None, install_as_job=False, modules = [], **kwargs):
if username is None:
username = self.get_usern... | ostname):
raise ValueError('Hostname '+hostname+' not in your .ssh/config\n')
if basedir is None:
basedir = '/lustre/'+username
if base_work_dir is None:
base_work_dir = '/tmp/'+username
if not [_ for _ in modules if 'slurm' in _]:
modules.append('slurm')
SlurmJobQueue.__init__(self,ssh_cfg=ssh_cfg,... |
seanfisk/buzzword-bingo-server | buzzwordbingo/forms.py | Python | bsd-3-clause | 955 | 0.002094 | """:mod:`buzzwordbingo.form` --- Forms for the HTML REST interface
"""
from django import forms
from buzzwordbingo.models import Buzzword, Board, WinCondition
class BoardForm(forms.ModelForm):
"""Form assisting in the submission of a board that is able to stored in a
non-relational database."""
class Meta... | .word) for word in Buzzword.objects.all()])
"""Re-define words to be a custom field on the form rather than a field
straight from the model.
"""
win_conditions = forms.TypedMultipleChoiceField(
coerce=int,
choices=[(win_condition.pk, win_condition.name)
for win_conditio... | he model.
"""
|
PWr-Projects-For-Courses/SystemyWizyjne | toolbox/example/poly.py | Python | gpl-2.0 | 1,791 | 0.027359 | #!/usr/bin/env python
from sys import path
import os.path
t | hisrep = os.path.dirname(os.path.abspath(__file__))
path.append(os.path.dirname(thisrep))
from random import randint
from pygame import *
from pygame import gfxdraw
from EasyGame import pathgetter,confirm
controls = """hold the left mouse button to draw
d = undo
s = save"""
scr = display.set_mode((800,800))
co | nfirm(controls,fontsize=14,mode=1)
a = []
c = []
color = [randint(0,255) for i in (1,2,3)]+[50]
while 1:
ev = event.wait()
if ev.type == MOUSEBUTTONDOWN and ev.button == 1:
a.append([ev.pos])
c.append(color)
if ev.type == MOUSEMOTION and ev.buttons[0]:
a[-1].append(ev.pos)
i... |
google-research/deeplab2 | model/builder_test.py | Python | apache-2.0 | 3,005 | 0.002662 | # coding=utf-8
# Copyright 2022 The Deeplab2 Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | with tf.io.gfile.GFile(filename, 'r') as proto_file:
return text_format.ParseLines(proto_f | ile, proto)
class BuilderTest(tf.test.TestCase, parameterized.TestCase):
def test_resnet50_encoder_creation(self):
backbone_options = config_pb2.ModelOptions.BackboneOptions(
name='resnet50', output_stride=32)
encoder = builder.create_encoder(
backbone_options,
tf.keras.layers.exper... |
CantemoInternal/pyxb | pyxb/bundles/opengis/tml.py | Python | apache-2.0 | 43 | 0 | f | rom | pyxb.bundles.opengis.raw.tml import *
|
GridProtectionAlliance/ARMORE | source/webServer/armoreServer.py | Python | mit | 6,634 | 0.007386 | # # # # #
# armoreServer.py
#
# This file is used to serve up
# RESTful links that can be
# consumed by a frontend system
#
# University of Illinois/NCSA Open Source License
# Copyright (c) 2015 Information Trust Institute
# All rights reserved.
#
# Developed by:
#
# Information Trust Institute
# University of Illinois... | ames of its contributors may be used to endorse or promote products derived
# from this Software without specific prior written permission.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR... | HERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE SOFTWARE.
#
# # # # #
# Import python Flask server
# and add backend files to sys.path
import sys
import re
import domains.support.config as confLib
import domains.support.network as netLib
import domains.support.... |
cliffpanos/True-Pass-iOS | CheckIn/pages/urls.py | Python | apache-2.0 | 403 | 0.019851 | fro | m django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^index$', views.index, name='index'),
url(r'^signup/$', views.signup, name = 'signup'),
url(r'^map/$', views.map, name = 'map'),
url(r'^qrtest/$', views.qrtest, name = 'qrtest'),
url(... | ]
|
chrislit/abydos | tests/distance/test_distance__token_distance.py | Python | gpl-3.0 | 15,537 | 0 | # Copyright 2019-2020 by Christopher C. Little.
# This file is part of Abydos.
#
# Abydos 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 versio... | nit tests for abydos.distance._TokenDistance
"""
import unittest
from collections import Counter
from abydos.distance import (
AverageLinkage,
DamerauLevenshtein,
Jaccard,
JaroWinkler,
SokalMichener,
)
from abydos.stats import ConfusionTable
from abydos.tokenizer import (
CharacterTokenizer,
... | Distance functions.
abydos.distance._TokenDistance
"""
cmp_j_crisp = Jaccard(intersection_type='crisp')
cmp_j_soft = Jaccard(intersection_type='soft')
cmp_j_fuzzy = Jaccard(
intersection_type='fuzzy', metric=DamerauLevenshtein(), threshold=0.4
)
cmp_j_linkage = Jaccard(intersection... |
asgordon/EtcAbductionPy | etcabductionpy/abduction.py | Python | bsd-2-clause | 3,656 | 0.01395 | '''abduction.py
Base functionality for logical abduction using a knowledge base of definite clauses
Andrew S. Gordon
'''
import itertools
from . import parse
from . import unify
def abduction(obs, kb, maxdepth, skolemize = True):
'''Logical abduction: returns a list of all sets of assumptions that entail the obs... | s with substitutions
unify.subst(theta, assumptions)]) # new assumptions with substitutions
return itertools.chain(*[and_or_leaflists(*rev) for rev in revisions]) # list of lists (if any)
def crunch(conjunction):
'''Returns all possible ways that literals in a conj... | uld be unified'''
return [k for k,v in itertools.groupby(sorted(cruncher(conjunction, 0)))] # dedupe solutions
def cruncher(conjunction, idx = 0):
if idx >= len(conjunction) - 1: # last one
return [[k for k,v in itertools.groupby(sorted(conjunction))]] # dedupe literals in solution
else:
re... |
orvi2014/kitsune | kitsune/wiki/tests/test_parser.py | Python | bsd-3-clause | 39,480 | 0 | import re
from django.conf import settings
from nose.tools import eq_
from pyquery import PyQuery as pq
import kitsune.sumo.tests.test_parser
from kitsune.gallery.models import Video
from kitsune.gallery.tests import image, video
from kitsune.sumo.tests import TestCase
from kitsune.wiki.models import Document
from k... | doc_rev_parser(*args, **kwargs):
return kitsune.sumo.tests.test_parser.doc_rev_parser(
*args, parser_cls=WikiParser, **kwargs)
def doc_parse_markup(content, markup, title='Template:test'):
"""Create a doc with given con | tent and parse given markup."""
_, _, p = doc_rev_parser(content, title)
doc = pq(p.parse(markup))
return (doc, p)
class SimpleSyntaxTestCase(TestCase):
"""Simple syntax regexing, like {note}...{/note}, {key Ctrl+K}"""
def test_note_simple(self):
"""Simple note syntax"""
p = WikiPa... |
lnls-fac/sirius | pymodels/BO_V06_01/accelerator.py | Python | mit | 915 | 0.002186 |
import numpy as _np
import lnls as _lnls
import pyaccel as _pyaccel
from . import lattice as _lattice
default_cavity_on = False
default_radiation_on = False
default_vchamber_on = False
def create_accelerator(optics_mode=_lattice.defaul | t_optics_mode, energy=_lattice.energy):
lattice = _lattice.create_lattice(optics_mode=optics_mode, energy=energy)
accelerator = _pyaccel.accelerator.Accelerator(
lattice=lattice,
energy=energy,
harmonic_number=_lattice.harmonic_number,
cavity_on=default_cavity_on,
radiati... | lerator_data['global_coupling'] = 0.0002 # expected corrected value
accelerator_data['pressure_profile'] = _np.array([[0, 496.8], [1.5e-8]*2]) # [s [m], p [mbar]]o
496.78745
|
kubeflow/pipelines | sdk/python/tests/compiler/testdata/add_pod_env.py | Python | apache-2.0 | 1,058 | 0.000945 | # Copyright 2019 The Kubeflow Authors
#
# Licensed under the Apache Licens | e, 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 writi | ng, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import kfp.deprecated as kfp
@kfp.dsl.pipeline(name='Test ... |
jmwenda/osmxapi | osmxapi/__init__.py | Python | gpl-3.0 | 4,014 | 0.008975 | # -*- coding: utf-8 -*-
#
# This file is part of the osmxapi Python module.
#
# osmxapi 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 ver... | relationlist = []
for r in data:
relationlist.append(dom.parseRelation(r))
#.
return relationlist
#.
def anyGet(self, query=None, raw=None):
"""Return any data for query"""
uri = self.base+"?*"+repr(query)
data = self.http.get(uri)
if raw: ret... | = data.getElementsByTagName("osm")[0].getElementsByTagName(e)
anylist = []
for a in d:
if e == "node":
anylist.append(dom.parseNode(a))
#.
if e == "way":
anylist.append(dom.parseWay(a))
#.
... |
ololobster/cvidone | cvidone/util/validator.py | Python | mit | 11,249 | 0.012801 | # Released under the MIT license. See the LICENSE file for more information.
# https://github.com/ololobster/cvidone
from flask import request
import datetime
from calendar import monthrange
import json
import re
class ValidationError(Exception):
def __init__(self, name):
self.name = name
def __str_... | , min_length=None
, max_length=None
, mask=None
# Information about how to validate a date.
, null_date_permitted=False
# Information about how to validate a list.
, separator=","
, make_unique=False
, skip_empty_elements=False
, sort_required=False
# ... | , permitted_values=None
):
if (rule is not None):
return Validator.validate(
input_str
, name=name
, type=rule.type
, min_value=rule.min_value
, max_value=rule.max_value
, strip_required=rule.strip_required
... |
tempbottle/pykafka | tests/pykafka/test_balancedconsumer.py | Python | apache-2.0 | 4,755 | 0.001052 | import math
import time
import mock
import unittest2
from pykafka import KafkaClient
from pykafka.balancedconsumer import BalancedConsumer
from pykafka.test.utils import get_cluster, stop_cluster
def buildMockConsumer(num_partitions=10, num_participants=1, timeout=2000):
consumer_group = 'testgroup'
topic =... | # override consumer id
# Decide partitions then validate
partitions = cns._decide_partitions(participants)
assigned_parts.extend(partitions)
remainder_ppc = num_partitions % num_participants
| idx = participants.index(cns._consumer_id)
parts_per_consumer = num_partitions / num_participants
parts_per_consumer = math.floor(parts_per_consumer)
num_parts = parts_per_consumer + (0 if (idx + 1 > remainder_ppc) else 1)
self.assertEqual(le... |
frappe/frappe | frappe/desk/doctype/todo/todo.py | Python | mit | 4,119 | 0.025977 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: MIT. See LICENSE
import frappe
import json
from frappe.model.document import Document
from frappe.utils import get_fullname, parse_addr
exclude_from_linked_with = True
class ToDo(Document):
DocType = 'ToDo'
def validate(self):
self... | elf.reference_name,
"status": ("!=", "Cancelled")
}, pluck="allocated_to")
assignments.reverse()
frappe.db.set_value(self.reference_type, self.reference_name | ,
"_assign", json.dumps(assignments), update_modified=False)
except Exception as e:
if frappe.db.is_table_missing(e) and frappe.flags.in_install:
# no table
return
elif frappe.db.is_column_missing(e):
from frappe.database.schema import add_column
add_column(self.reference_type, "_assign", ... |
HiTechIronMan/openfda | openfda/parallel/sharded_db.py | Python | cc0-1.0 | 1,844 | 0.009761 | import cPickle
import glob
import logging
import os
import leveldb
class ShardedDB(object):
'''
Manages a number of leveldb "shards" (partitions).
LevelDB does not support concurrent writers, so we create a separate output
shard for each reducer. `ShardedDB` provides a unified interface to
multiple shards.... | if_missing=create_if_missing))
logging.info('Opened DB with %s files', num_shards)
@staticmethod
def create(filebase, num_shards):
'Create a new ShardedDB with the given number of output shards.'
return ShardedDB(filebase, num_shards, True)
@static | method
def open(filebase):
'Open an existing ShardedDB.'
files = glob.glob('%s/*.db' % filebase)
return ShardedDB(filebase, len(files), False)
def _shard_for(self, key):
return self._shards[hash(key) % self.num_shards]
def put(self, key, value):
self._shard_for(key).Put(key, cPickle.dumps(va... |
nave91/rebot | scripts/hdfs_to_spark_to_hdfs.py | Python | gpl-2.0 | 2,273 | 0.008799 | from pyspark import SparkContext, SparkConf
folder_name = "input/"
out_folder_name = "json/"
#file_name = "stackexchange-posts-sample.xml"
file_name = "Posts.xml"
hdfs = "ec2-52-8-214-93.us-west-1.compute.amazonaws.com:9000"
def jsoner(dic):
import json
return json.dumps(dic)
def dicte | r(row):
header = ['id','posttypeid','score','answer','body','snippets']
header_map = ['Id','PostTypeId','Score','AcceptedAnswerId','Body','snippets']
out = {}
for ind, h in enumerate(header_map):
if h == 'AcceptedAnswerId':
if h in row.keys():
out[header[ind]] = row[h... | ader[ind]] = 'NULL'
continue
out[header[ind]] = row[h]
return out
def load_row(row):
from HTMLParser import HTMLParser
class PostsBodyParser(HTMLParser):
def __init__(self, *args, **kwargs):
HTMLParser.__init__(self, *args, **kwargs)
self.recording = 0
... |
niftynei/zulip | zerver/lib/html_diff.py | Python | apache-2.0 | 4,261 | 0.003051 | from __future__ import absolute_import
from typing import Callable, Tuple, Text
from django.conf import settings
from diff_match_patch import diff_match_patch
import platform
import logging
# TODO: handle changes in link hrefs
def highlight_with_class(klass, text):
# type: (Text, Text) -> Text
return '<spa... | return highlight_with_class('highlight_text_deleted', text)
def highlight_replaced(text):
# type: (Text) -> | Text
return highlight_with_class('highlight_text_replaced', text)
def chunkize(text, in_tag):
# type: (Text, bool) -> Tuple[List[Tuple[Text, Text]], bool]
start = 0
idx = 0
chunks = [] # type: List[Tuple[Text, Text]]
for c in text:
if c == '<':
in_tag = True
if s... |
chhans/tor-automation | patternexperiment.py | Python | mit | 8,474 | 0.02903 | from classifier import Classifier
from itertools import combinations
from datetime import datetime
import sys
import os
open_path = "PatternDumps/open"
closed_path = "PatternDumps/closed"
monitored_sites = ["cbsnews.com", "google.com", "nrk.no", "vimeo.com", "wikipedia.org", "youtube.com"]
per_burst_weight = 1
total_... | stanceVotes(vector, w):
G = indexOfSortedValues(vector)
l = float(len(vector))
votes = []
for i in range(len(vector)):
j = i
while True:
try:
r = G.index(j)
br | eak
except:
j -= 1
v = 2*w - 2*r/l*w
if v == 2.0:
v += 2.0
votes.append(v)
return votes
def createTrainingSets(n):
l = []
for i in range(n):
l.append(range(0, i)+range(i+1, n)+range(i, i+1))
return l
def matchAgainstClassifiers(clf, fp):
pred = []
pbd = []
td = []
for c in clf:
pred.appen... |
xbmc/atv2 | xbmc/lib/libPython/Python/Demo/curses/xmas.py | Python | gpl-2.0 | 25,498 | 0.000824 | # asciixmas
# December 1989 Larry Bartz Indianapolis, IN
#
# $Id: xmas.py 36559 2004-07-18 05:56:09Z tim_one $
#
# I'm dreaming of an ascii character-based monochrome Christmas,
# Just like the one's I used to know!
# Via a full duplex communications channel,
# At 9600 bits per second,
# Even thou... | used a couple of `try...except curses.error' to get around some functions
# returning ERR. The errors come from using wrapping functions to fill
# windows to the last character cell. The C version doesn't have this problem,
# it simply ignores any return values.
#
import curses
import sys
FROMWHO = "Thomas Gellekum <... | es.A_COLOR)
win.attron(curses.color_pair(n))
def unset_color(win):
if curses.has_colors():
win.attrset(curses.color_pair(0))
def look_out(msecs):
curses.napms(msecs)
if stdscr.getch() != -1:
curses.beep()
sys.exit(0)
def boxit():
for y in range(0, 20):
stdscr.a... |
marcellodesales/svnedge-console | ext/windows/pkg-toolkit/pkg/vendor-packages/pkg/client/progress.py | Python | agpl-3.0 | 30,842 | 0.009857 | #!/usr/bin/python2.4
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://w... | hase, nitems):
self.ind_phase = phase
self.ind_goal_nitems = ni | tems
self.ind_cur_nitems = 0
def index_add_progress(self):
self.ind_cur_nitems += 1
if self.ind_goal_nitems > 0:
self.ind_output()
def index_done(self):
if self.ind_goal_nitems > 0:
|
Distrotech/iksemel | python/test/runtests.py | Python | lgpl-2.1 | 423 | 0.004728 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import subprocess
def runtests() | :
fail = 0
for test in os.listdir("."):
if test.startswith("tst_") and test.endswith(".py"):
if 0 != subprocess.call(["./" + test]):
fail += 1
print test, "failed!"
if not fail:
return 0
return 1
if __nam | e__ == "__main__":
sys.exit(runtests())
|
troycomi/microMS | ImageUtilities/blob.py | Python | mit | 2,709 | 0.009598 | from GUICanvases import GUIConstants
import matplotlib as mpl
class blob(object):
"""
Representation of a target point
"""
def __init__(self, x = float(0), y = float(0),
radius = float(GUIConstants.DEFAULT_BLOB_RADIUS),
circularity = float(1), group = None):
... | Parses xy location from string to make a new blob
instring: string of the form "x_{}y_{}"
returns a new blob with the indicated x,y
'''
result = blob()
if instring is None:
return result
toks = instring.split('_')
result.X = float(toks[1][:-1... | the blob
'''
return "{0:.3f}\t{1:.3f}\t{2:.3f}\t{3:.3f}".format(self.X, self.Y,
self.radius, self.circularity)
|
who-emro/meerkat_api | meerkat_api/util/__init__.py | Python | mit | 4,531 | 0.002869 | """
meerkat_api util functions
"""
from datetime import datetime
from dateutil import parser
import meerkat_abacus.util as abacus_util
import numpy as np
import meerkat_abacus.util.epi_week
def series_to_json_dict(series):
"""
Takes pandas series and turns into a dict with string keys
Args:
seri... | w in rows:
data_dicts.append(row_to_dict(row))
return data_dicts
def find_level(location, sublevel, locations):
"""
Returns | the isntance of level that location is a child of
Args:
location: location
sublevel: the sublevel we are interested in
locations: all locations in dict
Returns:
location_id(int): id of the mathcing location
"""
location = int(location)
for loc in locations:
... |
atheendra/access_keys | keystone/tests/test_url_middleware.py | Python | apache-2.0 | 2,020 | 0 | # Copyright 2012 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | ebob
from keystone import middleware
from keystone import tests
class FakeApp(object):
"""Fakes a WSGI app URL normalized."""
def __call__(self, env, start_response):
resp = webob.Response()
resp.body = 'SUCCESS'
return resp(env, start_response)
class UrlMiddlewareTest(tests.TestCas... | self.middleware = middleware.NormalizingFilter(FakeApp())
self.response_status = None
self.response_headers = None
super(UrlMiddlewareTest, self).setUp()
def start_fake_response(self, status, headers):
self.response_status = int(status.split(' ', 1)[0])
self.response_... |
constantx/dotfiles | sublime3/Packages/SideBarEnhancements-st3/desktop/dialog.py | Python | mit | 17,225 | 0.007431 | #!/usr/bin/env python
"""
Simple desktop dialogue box support for Python.
Copyright (C) 2007, 2009 Paul Boddie <[email protected]>
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; either ver... | f.factor)]
class Boolean(String):
"A boolean parameter."
values = {
"kdialog" : ["off", "on"],
"zenity" : ["FALSE", "TRUE"],
"Xdialog" : ["off", "on"]
}
def convert(self, value, program):
values = self.values[program]
| if value:
return [values[1]]
else:
return [values[0]]
class MenuItemList(String):
"A menu item list parameter."
def convert(self, value, program):
l = []
for v in value:
l.append(v.value)
l.append(v.text)
return l
class List... |
RowleyGroup/pbs-generator | pyqueue/enums.py | Python | gpl-3.0 | 1,317 | 0.001519 | """
Enums.
"""
try:
from enum import Enum
except ImportError:
Enum = object
class MailTypes(Enum):
"""
MailTypes enum
"""
ALL = 0
BEGIN = 1
END = 2
FAIL = 3
REQUEUE = 4
class DependencyTypes(Enum):
"""
DependencyTypes enum
"""
# This job can begin execution... | on with an exit code of zero).
# SUPPORT: Slurm
AFTER_CORR = 2
# This job can begin execution after the specified jobs have successfully executed
# (ran to completion with an exit code of zero).
# SUPPORT: Slurm, PBS
AFTER_OK = 3
# This job can begin execution after the specified jobs have... | on after any previously launched jobs
# sharing the same job name and user have terminated.
# SUPPORT: Slurm
SINGLETON = 4
|
XuezheMax/LasagneNLP | bi_lstm_cnn_crf.py | Python | apache-2.0 | 15,909 | 0.005091 | __author__ = 'max'
import time
import sys
import argparse
from lasagne_nlp.utils import utils
import lasagne_nlp.utils.data_processor as data_processor
from lasagne_nlp.utils.objectives import crf_loss, crf_accuracy
import lasagne
import theano
import theano.tensor as T
from lasagne_nlp.networks.networks import build_... | y(energies_eval, target_var)
corr_eval = (corr_eval * mask_var).sum(dtype=theano.config.floatX)
# Create update expressions for training.
# hyper parameters to tune: learning rate, momentum, regularization.
batch_size = args.batch_size
learning_rate = 1.0 if update_algo == 'adadelta' else args.lear... | s.get_all_params(bi_lstm_cnn_crf, trainable=True)
updates = utils.create_updates(loss_train, params, update_algo, learning_rate, momentum=momentum)
|
erseco/ugr_desarrollo_aplicaciones_internet | Practica_01/ejercicio_01.py | Python | gpl-3.0 | 1,395 | 0.017204 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
#-------------------------------------------------------------------------------
#
# DAI - Desarrollo de Aplicaciones para Internet
#
# 2014 Ernesto Serrano <[email protected]>
#
#-------------------------------------------------------------------------------
Progra... | umero (con su correspondiente mensaje de felicitacion)
o bien cuando el usuario haya realizado 10 intentos incorrectos de adivinacion.
#-------------------------------------------------------------------------------
'''
from random import randint
rnd = randint(1,100)
encontrado = False
for x in xrange(1,10):
va... | encontrado")
break # Salimos de la ejecucin del programa
elif valor > 100 or valor < 1:
print "El numero tiene que estar entre el rango [1-100]"
elif valor > rnd:
print("El numero es menor que el introducido")
elif valor < rnd:
print("El numero es mayor que el introducido")
if not encontrado:
print("El val... |
cloudysunny14/lakshmi | test/testlib/mox.py | Python | apache-2.0 | 60,051 | 0.006461 | #!/usr/bin/env python
#
# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | ng mock objects."""
# A list of types that should be | stubbed out with MockObjects (as
# opposed to MockAnythings).
_USE_MOCK_OBJECT = [types.ClassType, types.FunctionType, types.InstanceType,
types.ModuleType, types.ObjectType, types.TypeType,
types.MethodType, types.UnboundMethodType,
]
# A list of... |
irvs/ros_tms | tms_ts/tms_ts_smach/setup.py | Python | bsd-3-clause | 309 | 0 | # ! DO NOT MANUALLY INVOKE THI | S setup.py, USE CATKIN INSTEAD
from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup
# fetch values from package.xml
setup_args = generate_distutils_setup(
packages=['tms_ts_smach'],
packa | ge_dir={'': 'src'})
setup(**setup_args)
|
andrewyoung1991/supriya | supriya/tools/ugentools/IFFT.py | Python | mit | 4,524 | 0.001768 | # -*- encoding: utf-8 -*-
from supriya.tools.ugentools.WidthFirstUGen import WidthFirstUGen
class IFFT(WidthFirstUGen):
r'''An inverse fast Fourier transform.
::
>>> pv_chain = ugentools.LocalBuf(2048)
>>> ifft = ugentools.IFFT.ar(
... pv_chain=pv_chain,
... window_si... | ze=window_size,
window_type=window_type,
)
### PUBLIC METHODS ###
@classmethod
def ar(
cls,
pv_chain=None,
window_size=0,
window_type=0,
):
r'''Constructs an audio-rate IFFT.
::
>>> pv_chain = ugentools.LocalBuf(... | FFT.ar(
... pv_chain=pv_chain,
... window_size=0,
... window_type=0,
... )
>>> ifft
IFFT.ar()
Returns ugen graph.
'''
from supriya.tools import synthdeftools
calculation_rate = synthdeftools.Calculat... |
anatol/namcap | Namcap/tests/package/test_infodirectory.py | Python | gpl-2.0 | 2,400 | 0.018341 | # -*- coding: utf-8 -*-
#
# namcap tests - infodirectory
# Copyright (C) 2011 Rémy Oudompheng <[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 th... | ef test_info_dir_updated(self):
pkgfile = "__namcap_test_infodirectory-1.0-1-%(arch)s.pkg.tar" % { "arch": self.arch }
with open(os.path.join(self.tmpdir, "PKGBUILD"), "w") as f:
f.write(self.pkgbuild)
self.run_makepkg()
pkg, r = self.run_rule_on_tarball(
os.path.join(self.tmpdir, pkgfile),
Namcap.ru... | sw=4 noet:
|
pombredanne/kunai-1 | kunai/dnsquery.py | Python | mit | 3,161 | 0.006643 | import re
import socket
pattern = r"((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)([ (\[]?(\.|dot)[ )\]]?(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3})"
ipv4pattern = re.compile(pattern)
class DNSQuery:
def __init__(self, data):
self.data = data
self.domain = ''
t = (ord(data[2]) >> 3) & 15 # O... | except socket.gaierror: # not found
print 'DNS cannot find the hotname ip', addr
# skip this node
print "DNS R:", r
return r
def response(self, r):
packet = ''
print "DNS DOM", self.domain
nb = len(r)
... | Counts
packet += self.data[12:] # Original Domain Name Question
for ip in r:
packet += '\xc0\x0c' # Pointer to domain name
packet += '\x00\x01\x00\x01\x00\x00\x00\x3c\x00\x04' # Response ty... |
datafiniti/Diamond | src/collectors/snmpraw/snmpraw.py | Python | mit | 6,082 | 0.000658 | # coding=utf-8
"""
The SNMPRawCollector is designed for collecting data from SNMP-enables devices,
using a set of specified OIDs
#### Configuration
Below is an example configuration for the SNMPRawCollector. The collector
can collect data any number of devices by adding configuration sections
under the *devices* hea... | def _get_value_walk(self, device, oid, host, port, community):
| data = self.walk(oid, host, port, community)
if data is None:
self._skip(device, oid, 'device down (#2)')
return
self.log.debug('Data received from WALK \'{0}\': [{1}]'.format(
device, data))
if len(data) != 1:
self._skip(device, oid,
... |
r3alityc0d3r/pyisac-core | src/Pyisac/infrastructure/profile.py | Python | gpl-2.0 | 83 | 0.012048 | class Profile(object):
| def __init__(self, name):
| self.name = name
|
onfido/dependencies-resolver | tests/utils/test_md5_checksum.py | Python | mit | 1,242 | 0.000805 | import re
import tempfile
from dependencies_resolver.config.configuration import \
REGEX_MULTIPART_UPLOAD_PATTERN
from dependencies_resolver.utils.md5_checksum import get_aws_like_md5_checksum
from tests.utils.test_s3_utils import MOCKED_MD5_CHECKSUM
def test_get_md5_checksum_no_multipart_upload():
"""A test... | orking as we expected.
"""
with tempfile.NamedTemporaryFile() as f:
md5_checksum = ge | t_aws_like_md5_checksum(f.name, None)
assert md5_checksum == MOCKED_MD5_CHECKSUM[1:-1].split('-')[0]
def test_get_md5_checksum_multipart_upload():
"""A test to check we get the desired md5 checksum for a file that has
uploaded using multipart upload.
:return: True, unless the function is not work... |
GlobalFishingWatch/vessel-classification | classification/metadata.py | Python | apache-2.0 | 16,174 | 0.001608 | # Copyright 2017 Google Inc. and Skytruth 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 agr... | return self.metadata_by_id[id_][1]
def vessel_label(self, label_name, id_):
return self.metadata_by_id[id_][0][label_name]
def ids_for_split(self, split):
assert split in (TRAINING_SPLIT, TEST_SPLIT)
# Check to make sure we don't have leakage
if (set(self.metadata_by_split[TRA... | logging.warning('id in both training and test split')
return self.metadata_by_split[split].keys()
def weighted_training_list(self,
random_state,
split,
max_replication_factor,
... |
codeinthehole/django-async-messages | tests/urls.py | Python | mit | 119 | 0.008403 | from | django.conf.urls.defaults import patterns, url
urlpatterns = patterns('',
url(r'^$', 'tests.view | s.index'),
)
|
F5Networks/f5-common-python | f5/bigip/tm/gtm/test/unit/test_server.py | Python | apache-2.0 | 2,388 | 0 | # Copyright 2014-2017 F5 Networks Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in co | mpliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either expres... | f5.bigip import ManagementRoot
from f5.bigip.tm.gtm.server import Server
from f5.bigip.tm.gtm.server import Virtual_Server
from f5.sdk_exception import MissingRequiredCreationParameter
from six import iterkeys
@pytest.fixture
def FakeServer():
fake_servers = mock.MagicMock()
fake_server = Server(fake_servers... |
ubaumgar/OKR | docs/conf.py | Python | bsd-2-clause | 7,670 | 0.007562 | # -*- coding: utf-8 -*-
#
# sample documentation build configuration file, created by
# sphinx-quickstart on Mon Apr 16 21:22:43 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All ... | = 'sampledoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional | stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'okr.tex', u'okr Documentation',
u'siroop', 'manual'),
]
# The name of an image file (relat... |
mojaves/convirt | convirt/events.py | Python | lgpl-2.1 | 3,067 | 0 | #
# Copyright 2015-2016 Red Hat, Inc.
#
# 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; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distr... | for cb in self.get_callbacks(event_id):
arguments = list(args)
if cb.opaque is not None:
arguments.append(cb.opaque) |
domain = cb.dom
if dom is not None:
domain = dom
self._log.debug('firing: %s(%s, %s, %s)',
cb.body, cb.conn, domain, arguments)
return cb.body(cb.conn, domain, *arguments)
def get_callbacks(self, event_id):
with se... |
PierreBdR/point_tracker | point_tracker/normcross.py | Python | gpl-2.0 | 3,343 | 0.010769 | from __future__ import print_function, division, absolute_import
__author__ = "Pierre Barbier de Reuille <[email protected]>"
__docformat__ = "restructuredtext"
import scipy
from scipy import rot90, zeros, cumsum, sqrt, maximum, std, absolute, array, real
from scipy.signal.signaltools import correlate2d, fftc... | rn s[:,n:-1]-s[:,:-n-1]
def fftconvolve2d(in1, in2):
"""
Convolve two 2-dimensional arrays using FFT.
I took the code of fftconvolve and specialized it for fft2d ...
"""
s1 = array(in1.shape)
s2 = array(in2.shape)
if (s1.dtype.char in ['D','F']) or (s2.dtype.char in ['D', 'F']):
... | lx=1
else: cmplx=0
size = s1+s2-1
IN1 = fft2(in1,size)
IN1 *= fft2(in2,size)
ret = ifft2(IN1)
del IN1
if not cmplx:
ret = real(ret)
return ret
def fftcorrelate2d(template, A):
"""
Perform a 2D fft correlation using fftconvolve2d.
"""
return fftconvolve2d(rot9... |
ulikoehler/UliEngineering | tests/Electronics/TestLED.py | Python | apache-2.0 | 1,086 | 0.004604 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from numpy.testing import assert_approx_equal, assert_allclose
from UliEngineering.Electronics.LED import *
from UliEngineering.Exceptions import OperationImpossibleException
from UliEngineering.EngineerIO import auto_format
import unittest
class TestLEDSeriesResistors(un... | st.TestCase):
def test_led_series_resistor(self):
# Example verified at http://www.elektronik-kompendium.de/sites/bau/1109111.htm
# Also verified at https://www.digikey.com/en/resources/conversion-calculators/conversion-calculator-led-series-resistor
assert_approx_equal(led_series_resi | stor(12.0, 20e-3, 1.6), 520.)
assert_approx_equal(led_series_resistor("12V", "20 mA", "1.6V"), 520.)
assert_approx_equal(led_series_resistor(12.0, 20e-3, LEDForwardVoltages.Red), 520.)
def test_led_series_resistor_invalid(self):
# Forward voltage too high for supply voltage
with sel... |
bpsinc-native/src_third_party_chromite | scripts/cros_check_patches.py | Python | bsd-3-clause | 8,385 | 0.009064 | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Command to list patches applies to a repository."""
import functools
import json
import os
import parallel_emerge
import por... | irst run? Try this for a starter config:
{
"ignored_packages": ["chromeos-base/chromeos-chrome"],
"upstreamed": [],
"needs_upstreaming": [],
"not_for_upstream": [],
"uncategorized": []
}
"""
def main(argv):
if len(argv) < 4:
Usage()
sys.exit(1)
# Avoid parsing most of argv because most of | it is destined for
# DepGraphGenerator/emerge rather than us. Extract what we need
# without disturbing the rest.
config_path = argv.pop()
config = json.loads(osutils.ReadFile(config_path))
overlay_dir = argv.pop()
board = [x.split('=')[1] for x in argv if x.find('--board=') != -1]
if board:
ebuild_c... |
adobe-type-tools/python-scripts | vintage/copyCFFCharstrings.py | Python | mit | 5,593 | 0.030753 | """
Copies the CFF charstrings and subrs from src to dst fonts.
"""
__help__ = """python copyCFFCharstrings.py -src <file1> -dst <file2>[,file3,...filen_n]
Copies the CFF charstrings and subrs from src to dst.
v1.002 Aug 27 2014
"""
import os
import sys
import traceback
from fontTools.ttLib import TTFont, getTableMo... | ror parsing font file <%s>." % filePath)
return ttFont
def getTTFontCFF(filePath):
isOTF = True
try:
ttFont = TTFont(filePath)
except (IOError, OSError):
raise LocalError("Error opening or reading from font file <%s>." % filePath)
except TTLibError:
# Maybe it is a CFF. Make a dummy TTF font for fontTools ... | s>." % filePath)
return ttFont, cffTable.cff, isOTF
def validatePD(srcPD, dstPD):
# raise LocalError if the hints differ.
for key in ["BlueScale", "BlueShift", "BlueFuzz", "BlueValues", "OtherBlues", "FamilyBlues", "FamilyOtherBlues", "StemSnapH", "StemSnapV", "StdHW", "StdVW", "ForceBold", "LanguageGroup"]:
err... |
mikeek/FIT | IPP/proj_2/Macro.py | Python | mit | 4,768 | 0.066485 | #!/usr/bin/python3
#JMP:xkozub03
import sys
import re
import Config
from Config import exit_err
macro_list = {};
def init_list(redef_opt):
def_macro = Macro("@def");
set_macro = Macro("@set");
let_macro = Macro("@let");
null_macro = Macro("@null");
_def_macro = Macro("@__def__");
_set_macro = Macro("@__set__"... | "$scnd");
_def_macro.add_arg("$thrd");
_set_macro.add_arg("$frst");
_let_macro.add_arg("$frst");
_let_macro.add_arg("$scnd");
macro_list["@def"] = def_macro;
macro_list["@set"] = set_macro;
macro_list["@let"] = let_macro;
ma | cro_list["@null"] = null_macro;
macro_list["@__def__"] = _def_macro;
macro_list["@__set__"] = _set_macro;
macro_list["@__let__"] = _let_macro;
class Macro:
name = "";
body = "";
args = {};
args_ord_name = [];
args_cnt = 0;
args_order = 0;
is_def = False;
is_set = False;
is_let = False;
is_null = False;
r... |
jwg4/flask-restless | flask_restless/views/function.py | Python | agpl-3.0 | 2,512 | 0 | # function.py - views for evaluating SQL functions on SQLAlchemy models
#
# Copyright 2011 Lincoln de Sousa <[email protected]>.
# Copyright 2012, 2013, 2014, 2015, 2016 Jeffrey Finkelstein
# <[email protected]> and contributors.
#
# This file is part of Flask-Restless.
#
# Flask-Restless is distr... | ble to decode JSON in `functions` query parameter'
return error_response(400, cause=exception, detail=detail)
try:
result = evaluate_functions(self.session, self.model, data)
except AttributeError as exception:
detail = 'No such field "{0}"'.format(exception.field)
... | ception)
return error_response(400, cause=exception, detail=detail)
except OperationalError as exception:
detail = 'No such function "{0}"'.format(exception.function)
return error_response(400, cause=exception, detail=detail)
return dict(data=result)
|
luca76/QGIS | python/plugins/processing/algs/lidar/lastools/hugeFileNormalize.py | Python | gpl-2.0 | 5,671 | 0.002645 | # -*- coding: utf-8 -*-
"""
***************************************************************************
hugeFileNormalize.py
---------------------
Date : May 2014
Copyright : (C) 2014 by Martin Isenburg
Email : martin near rapidlasso point com
*************... | FileNormalize.TERRAINS[method])
gra | nularity = self.getParameterValue(hugeFileNormalize.GRANULARITY)
if granularity != 1:
commands.append("-" + hugeFileNormalize.GRANULARITIES[granularity])
self.addParametersTemporaryDirectoryAsOutputDirectoryCommands(commands)
commands.append("-odix")
commands.append("_g")
... |
practian-reapps/django-backend-utils | backend_utils/serializers.py | Python | bsd-3-clause | 380 | 0 | """
@co | pyright Copyright (c) 2016 Devhres Team
@author Angel Sullon (@asullom)
@package utils
Descripcion: serializers
"""
from rest_framework imp | ort serializers
class RecursiveSerializer(serializers.Serializer):
def to_representation(self, value):
serializer = self.parent.parent.__class__(value, context=self.context)
return serializer.data
|
mbaldessari/sarstats | sar_grapher.py | Python | gpl-2.0 | 10,858 | 0.001105 | import hashlib
import matplotlib
# Force matplotlib to not use any Xwindows backend.
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.colors as colors
import matplotlib.cm as cm
from matplotlib.patches import Rectangle
import os
import shutil
import tempfile
fro... | axes.annotate(extra[1], xy=(mdates.date2num(extra[0]),
sar_parser.f | ind_max(extra[0], datanames)),
xycoords='data', xytext=(30, 30),
textcoords='offset points',
arrowprops=dict(arrowstyle="->",
connectionstyle="arc3,rad=.2"))
# If we have a sosreport draw the... |
jkyeung/XlsxWriter | xlsxwriter/test/worksheet/test_date_time_01.py | Python | bsd-2-clause | 7,088 | 0 | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2016, John McNamara, [email protected]
#
import unittest
from datetime import datetime
from ...worksheet import Worksheet
class TestConvertDateTime(unittest.TestCase):
"""
Test t... | 68979),
('9256-02-13T | 22:23:51.376', 2686769.9332335186),
('9338-10-09T22:27:58.771', 2716957.9360968866),
('9421-06-05T22:43:30.392', 2747146.9468795368),
('9504-01-30T22:48:25.834', 2777334.9502990046),
('9586-09-24T22:53:51.727', 2807522.9540709145),
('9669-05-20T23:12:56.536', ... |
arturosevilla/repoze.who-x509 | tests/test_identifier.py | Python | bsd-3-clause | 6,719 | 0.000595 | # -*- coding: utf-8 -*-
# Copyright (C) 2012 Ckluster Technologies
# All Rights Reserved.
#
# This software is subject to the provision stipulated in
# http://www.ckluster.com/OPEN_LICENSE.txt.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLU... | ifier, X509Identifier)
def test_remember_without_headers(self):
identifier = X509Identifier('Test')
| assert identifier.remember({}, None) is None
def test_forget_without_headers(self):
identifier = X509Identifier('Test')
assert identifier.forget({}, None) is None
def test_match_default_classification(self):
identifier = X509Identifier('Test')
assert identifier in match_c... |
joaofrancese/heavy-destruction | Panda/src/objects/__init__.py | Python | bsd-3-clause | 17 | 0.117647 | __auth | or__ | ="Joao" |
KimBoWoon/Embeddad-System | nfc-server/nfcserver/controller/index.py | Python | mit | 1,224 | 0.000826 | # -*- coding: utf-8 -*-
from nfcserver.model.access import Access
from nfcserver.model.user import User
from flask import render_template, request, redirect, url_for
from nfcserver.db import dao
from nfcserver.blueprint import nfc
from exception import NoneUserName
import nxppy, time
@nfc.route('/access')
def accessP... | user = dao.query(User).filter(User.nfcid == nfcid).first()
if user is None:
raise NoneUserName
new_access = | Access(user.name, user.nfcid)
dao.add(new_access)
dao.commit()
print(new_access.name + " Access")
except NoneUserName as e:
print(e)
except nxppy.SelectError:
# SelectError is raised if no card is in the field.
# print('nxppy.Select... |
opencivicdata/scrapers-ca | ca_qc_brossard/__init__.py | Python | mit | 288 | 0 | from utils import CanadianJurisdiction
class Brossard(CanadianJurisdiction):
classification = 'legislature'
division_id = | 'ocd-division/country:ca/csd:2458007'
division_name = 'Brossard'
name = 'Conseil municipal de Brossard'
url | = 'http://www.ville.brossard.qc.ca'
|
dianamor8/waiter | manage.py | Python | lgpl-3.0 | 249 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == " | __main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "waiter.settings")
| from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
ddico/odoo | addons/l10n_latam_invoice_document/wizards/account_move_reversal.py | Python | agpl-3.0 | 3,941 | 0.003045 | # Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, fields, api, _
from odoo.exceptions import UserError
class AccountMoveReversal(models.TransientModel):
_inherit = "account.move.reversal"
l10n_latam_use_documents = fields.Boolean(compute='_compute_document_t... | atam_available_document_type_ids = fields.Many2many('l10n_latam.document.type', compute='_compute_document_type')
l10n_latam_document_number = fields.Char(string='Document Number')
l10n_latam_manual_document_number = fie | lds.Boolean(compute='_compute_l10n_latam_manual_document_number', string='Manual Number')
@api.depends('l10n_latam_document_type_id')
def _compute_l10n_latam_manual_document_number(self):
for rec in self.filtered('move_ids'):
move = rec.move_ids[0]
if move.journal_id and move.jo... |
cawc/sudokusolve | grabsudoku.py | Python | gpl-3.0 | 804 | 0.034826 | from bs4 import BeautifulSoup
import requests, re
n = int(input('How many sudoku\'s do you want to download (between 1 and 10)? '))
if n < 1 or n > 10:
die()
url = 'http://show.websudoku.com/?level=4'
for i in range(n):
page = requests.get(url)
page.raise_for_status()
rawPage=page.text
sudoku | id = int(re.search(r'\d+', rawPage.split('\n')[20]).group())
soup = BeautifulSoup(rawPage,'html.parser')
sudokuTable = soup.findAll(True, {'class':['s0', 'd0']})
sudoku = [ [(int(item['value']) if | item.get('class')[0] == 's0' else 0) for item in sudokuTable][i:i+9] for i in range(0, 81, 9) ]
filename = 'sudokus/sudoku_%i.txt'%sudokuid
sudokufile = open(filename, 'w')
for line in sudoku:
sudokufile.write( str(line).replace(',',' ').replace('[','').replace(']',' ') + '\n' )
input('Done!') |
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2020_04_01/aio/operations/_virtual_network_peerings_operations.py | Python | mit | 22,821 | 0.005039 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | By default, your polling method will be AsyncARMPolling.
Pass in False for this operation to not poll, or pass in yo | ur own initialized polling object for a personal polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of AsyncLROPoll... |
rcgee/oq-hazardlib | openquake/hazardlib/gsim/boore_atkinson_2011.py | Python | agpl-3.0 | 3,604 | 0.00111 | # -*- coding: | utf-8 -*-
| # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (C) 2014-2016 GEM Foundation
#
# OpenQuake is free software: 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, either version 3 of the License, or
# (at your option... |
DavidSPCrack/UEM_AccesoADatos | PythonTest/test/HolaMundoPack.py | Python | gpl-2.0 | 589 | 0.005111 | '''
Created on 20/12/2014
@author: usuario.apellido
'''
print("HOLA MUNDO" | )
print("AAAAAAAAAAAAAAAAAAAAAAAA")
mi_tupla = ("ARRAY LLAMADO TUPLA", 15, 2.8, "OTRO DATO", 25)
semaforo = "verde"
if semaforo == "verde":
print("Cruzar la calle")
else:
print("Esperar")
print("El niño busco la concha en la playa")
anio = 2001
while anio <= 2012:
print("Informes de... | terminado el while")
|
longmen21/edx-platform | cms/djangoapps/contentstore/views/course.py | Python | agpl-3.0 | 71,331 | 0.003266 | """
Views related to operations on course objects
"""
import copy
import json
import logging
import random
import string # pylint: disable=deprecated-module
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.core.u... | expect_json
from util.milestones_helpers import (
is_entrance_exams_enabled,
is_prerequisite_courses_enabled,
is_valid_course_key,
set_prerequisite_courses,
)
from util.organizations_helpers import (
| add_organization_course,
get_organization_by_short_name,
organizations_enabled,
)
from util.string_utils import _has_non_ascii_characters
from xblock_django.api import deprecated_xblocks
from xmodule.contentstore.content import StaticContent
from xmodule.course_module import CourseFields
from xmodule.course_... |
Nikea/VTTools | vttools/tests/test_utils.py | Python | bsd-3-clause | 4,142 | 0.00169 | # ######################################################################
# Copyright (c) 2014, Brookhaven Science Associates, Brookhaven #
# National Laboratory. All rights reserved. #
# #
# Redistribution and use in ... | __)
from nose.tools import assert_true
from skxray.testing.decorators import known_fail_if, skip_if
from vttools.utils impor | t make_symlink, query_yes_no
import tempfile
import os
import shutil
from subprocess import call
def destroy(path):
try:
shutil.rmtree(path)
except WindowsError as whee:
call(['rmdir', '/S', path], shell=True)
@skip_if(not os.name == 'nt', 'not on window')
def test_make_symlink():
test_l... |
bgruening/EDeN | eden/converter/molecule/obabel.py | Python | gpl-3.0 | 893 | 0 | import openbabel as ob
import pybel
import networkx as nx
def obabel_to_eden(input, file_type='sdf', **options):
"""
Takes a string list in sdf format format and yields networkx graphs.
Parameters
----------
input : string
A pointer to the data sou | rce.
"""
for mol in pybel.readfile(file_type, input):
# remove hydrogens
mol.removeh()
G = obabel_to_networkx(mol)
if len(G):
yield G
def obabel_to | _networkx(mol):
"""
Takes a pybel molecule object and converts it into a networkx graph.
"""
g = nx.Graph()
# atoms
for atom in mol:
label = str(atom.type)
g.add_node(atom.idx, label=label)
# bonds
for bond in ob.OBMolBondIter(mol.OBMol):
label = str(bond.GetBO())... |
sandrofolk/girox | girox/event/migrations/0016_subscription_team.py | Python | gpl-3.0 | 498 | 0.002008 | # -*- coding | : utf-8 -*-
# Generated by Django 1.10.6 on 2017-04-08 19:41
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('event', '0015_auto_20170408_1815'),
]
operations = [
migrations.AddField(
m... | ),
]
|
L33tCh/afj-flask | project/tests/test_auth.py | Python | mit | 9,874 | 0.000304 | # project/tests/test_auth.py
import time
import json
import unittest
from project.server import db
from project.server.models import User, BlacklistToken
from project.tests.base import BaseTestCase
def register_user(self, email, password):
return self.client.post(
'/auth/register',
data=json.du... | n['auth_token'])
self.assertTrue(resp_login.content_type == 'application/json')
| self.assertEqual(resp_login.status_code, 200)
# valid token logout
response = self.client.post(
'/auth/logout',
headers=dict(
Authorization='Bearer ' + json.loads(
resp_login.data.decode()
)['auth_tok... |
tomviner/pytest-django | tests/test_environment.py | Python | bsd-3-clause | 6,155 | 0.000162 | from __future__ import with_statement
import pytest
from django.core import mail
from django.db import connection
from pytest_django_test.app.models import Item
# It doesn't matter which order all the _again methods are run, we just need
# to check the environment remains constant.
# This is possible with some of t... | stem.Loader',
'django.template.loaders.app_directories.Loader',
)
ROOT_URLCONF = 'tpkg.app.urls'
""")
def test_invalid_template_variable(django_testdir):
django_testdir.create_app_file("""
fr | om django.conf.urls import url
from pytest_django_test.compat import patterns
from tpkg.app import views
urlpatterns = patterns(
'',
url(r'invalid_template/', views.invalid_template),
)
""", 'urls.py')
django_testdir.create_app_file("""
from ... |
OriHoch/Open-Knesset | committees/models.py | Python | bsd-3-clause | 22,034 | 0.000957 | # encoding: utf-8
import re
import logging
from datetime import datetime, timedelta, date
from django.db import models
from django.db.models.query_utils import Q
from django.utils.translation import ugettext_lazy as _, ugettext
from django.utils.text import Truncator
from django.contrib.contenttypes import generic
from... | odels.TextField(null=True, blank=True)
portal_knesset_broadcasts_url = models.URLField(max_length=1000,
blank=True)
type = models.CharField(max_length=10, default=CommitteeTypes.committee,
choices=CommitteeTypes.as_choices(),
... | dex=True)
hide = models.BooleanField(default=False)
# Deprecated? In use? does not look in use
protocol_not_published = models.BooleanField(default=False)
knesset_id = models.IntegerField(null=True, blank=True)
knesset_type_id = models.IntegerField(null=True, blank=True)
knesset_parent_id = mode... |
Vagab0nd/SiCKRAGE | sickchill/providers/torrent/TorrentProvider.py | Python | gpl-3.0 | 3,971 | 0.001511 | from datetime import datetime
import bencodepy
from feedparser import FeedParserDict
from sickchill import logger, settings
from sickchill.helper.common import try_int
from sickchill.oldbeard.classes import Proper, TorrentSearchResult
from sickchill.oldbeard.common import Quality
from sickchill.oldbeard.db import DBC... | if title.endswith('DIAMOND'):
logger.info('Skipping DIAMOND release for mass fake releases.')
download_url = title = 'FAKERELEASE'
if download_url:
download_url = down | load_url.replace('&', '&')
if title:
title = title.replace(' ', '.')
return title, download_url
def _verify_download(self, file_name):
try:
bencodepy.bread(file_name)
except bencodepy.BencodeDecodeError as e:
logger.debug('Failed to validate... |
GoogleCloudPlatform/appengine-blobstoremgmt-python | src/app/__init__.py | Python | apache-2.0 | 644 | 0 | # Copyright 2018 Google Inc. All rights reserved.
#
# Lice | nsed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Lice... | 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.
"""
Blob-management tool application code.
"""
|
Tinkerforge/brickv | src/brickv/bindings/bricklet_accelerometer_v2.py | Python | gpl-2.0 | 22,844 | 0.00416 | # -*- coding: utf-8 -*-
#############################################################
# This file was automatically generated on 2022-01-18. #
# #
# Python Bindings Version 2.1.29 #
# ... | AccelerometerV2.FUNCTION_GET_CONFIGURATION] = BrickletAccelerometerV2.RESPONSE_EXPECTED_ALWAYS_TRUE
self.response_expected[BrickletAccelerometerV2.FUNCTION_SET_ACCELERATION_CALLBACK_CONFIGURATION] = BrickletAccelerometerV2.RESPONSE_EXPECTED_TRUE
self.response_expected[BrickletAccelerometerV2.FUNCTION_GE... | = BrickletAccelerometerV2.RESPONSE_EXPECTED_FALSE
self.response_expected[BrickletAccelerometerV2.FUNCTION_GET_INFO_LED_CONFIG] = BrickletAccelerometerV2.RESPONSE_EXPECTED_ALWAYS_TRUE
self.response_expected[BrickletAccelerometerV2.FUNCTION_SET_CONTINUOUS_ACCELERATION_CONFIGURATION] = BrickletAcceleromet... |
poppogbr/genropy | packages/flib/model/item_category.py | Python | lgpl-2.1 | 781 | 0.008963 | # encoding: utf-8
class Table(object):
def config_db(self, pkg):
tbl = pkg.table('item_category', pkey='id', name_long='!!Item category',
name_plural='!!Item category')
self.s | ysFields(tbl)
tbl.column('item_id', size='22', group='_', name_long='Item id').relation('item.id', mode='foreignkey',
| onDelete='cascade')
tbl.column('category_id', size='22', group='_', name_long='Category id').relation('category.id',
mode='foreignkey',
... |
rohitranjan1991/home-assistant | homeassistant/components/sonarr/config_flow.py | Python | mit | 5,724 | 0.000349 | """Config flow for Sonarr."""
from __future__ import annotations
import logging
from typing import Any
from aiopyarr import ArrAuthenticationException, ArrException
from aiopyarr.models.host_configuration import PyArrHostConfiguration
from aiopyarr.sonarr_client import SonarrClient
import voluptuous as vol
import yar... | async def _async_reauth_update_entry(self, data: dict) -> FlowResult:
"""Update existing config entry."""
self.hass.config_entries.async_update_entry(self.entry, data=data)
await self.hass.config_entries.async_reload(self.entry.entry_id)
| return self.async_abort(reason="reauth_successful")
def _get_user_data_schema(self) -> dict[str, Any]:
"""Get the data schema to display user form."""
if self.entry:
return {vol.Required(CONF_API_KEY): str}
data_schema: dict[str, Any] = {
vol.Required(CONF_URL)... |
w1z2g3/crossbar | crossbar/router/auth/ticket.py | Python | agpl-3.0 | 5,567 | 0.003593 | #####################################################################################
#
# Copyright (C) Tavendo GmbH
#
# Unless a separate license agreement exists between you and Tavendo GmbH (e.g. you
# have purchased a commercial license), the license terms below apply.
#
# Should you enter into a separate licen... | hen the terms of such license agreement replace the terms below at
# the time at which such license agreement becomes effective.
#
# In case a separate license agreement ends, and such agreement ends without being
# replaced by another separate license agreement, the license terms below apply
# | from the time at which said agreement ends.
#
# LICENSE TERMS
#
# This program is free software: you can redistribute it and/or modify it under the
# terms of the GNU Affero General Public License, version 3, as published by the
# Free Software Foundation. This program is distributed in the hope that it will be
# ... |
adamgreig/agg-kicad | scripts/build_mod_tfml_sfml.py | Python | mit | 8,232 | 0.001701 | """
build_mod_tfml_sfml.py
Copyright 2016 Adam Greig
Licensed under the MIT licence, see LICENSE file for details.
Generate footprints for Samtec TFML and SFML connectors.
"""
from __future__ import print_function, division
# Settings ====================================================================
# Courtyard ... | ut.append(fp_line((sw[0], sw[1]-a_y), (sw[0]-a_x, sw[1]-a_y), l, w))
out.append(fp_line((sw[0]-a_x, sw[1]-a_y), (nw[0]-a_x, nw[1]+a_y), l, w))
out.append(fp_line((nw[0]-a_x, nw[1]+a_y), (nw[0], nw[1]+a_y), l, w))
out.append(fp_line((nw[0], nw[1]+a_y), nw, l, w))
return out
def ctyd(pins):
w = pins... | = grid * int(math.ceil(w / grid))
h = grid * int(math.ceil(h / grid))
_, _, _, _, sq = draw_square(w, h, (0, 0), "F.CrtYd", ctyd_width)
return sq
def refs(name):
out = []
ctyd_h = 6.35 + 2 * ctyd_gap
y = ctyd_h / 2.0 + font_halfheight
out.append(fp_text("reference", "REF**", (0, -y),
... |
saulpw/visidata | visidata/macos.py | Python | gpl-3.0 | 3,338 | 0.001557 | from visidata import BaseSheet
# for mac users to use Option+x as Alt+x without reconfiguring the terminal
# Option+X
BaseSheet.bindkey('å', 'Alt+a')
BaseSheet.bindkey('∫', 'Alt+b')
BaseSheet.bindkey('ç', 'Alt+c') |
BaseSheet.bindkey('∂', 'Alt+d')
BaseSheet.bindkey('´', 'Alt+e')
BaseSheet.bindkey('ƒ', 'Alt+f')
BaseSheet.bindkey('©', 'Alt+g')
BaseSheet.bindkey('˙', 'Alt+h')
BaseSheet.bindkey('ˆ', 'Alt+i')
BaseSheet.bindkey('∆', 'Alt+j')
BaseSheet.bindkey('˚', 'Alt+k')
BaseSheet.bindkey('¬', 'Alt+l')
BaseSheet.bindkey('µ', 'Alt+m')... | y('®', 'Alt+r')
BaseSheet.bindkey('ß', 'Alt+s')
BaseSheet.bindkey('†', 'Alt+t')
BaseSheet.bindkey('¨', 'Alt+u')
BaseSheet.bindkey('√', 'Alt+v')
BaseSheet.bindkey('∑', 'Alt+w')
BaseSheet.bindkey('≈', 'Alt+x')
BaseSheet.bindkey('¥', 'Alt+y')
BaseSheet.bindkey('Ω', 'Alt+z')
# Option+Shift+X
BaseSheet.bindkey('Å', 'Alt+A'... |
facebookexperimental/eden | eden/hg-server/edenscm/mercurial/smallcommitmetadata.py | Python | gpl-2.0 | 3,324 | 0.002708 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
# smallcommitmetadata.py - stores a small amount of metadata associated with a commit
from . import json
from .node import bin, hex
from .util import ... | ((node_, category_), data)
for ((node_, category_), data) in self.contents.items()
if node is None or node == node_
if category is None or category == category_
)
)
def finddelete(self, node=None, category=None):
"""Removes ... | data_) in self.contents.items()
if node is None or node == node_
if category is None or category == category_
]
for (key, _value) in entriestoremove:
del self.contents[key]
return altsortdict(entriestoremove)
def clear(self):
"""Removes and return... |
saintdragon2/python-3-lecture-2015 | gui_practice/file_io_civil.py | Python | mit | 347 | 0.002882 | __author__ = 'saintdragon2'
fname = 'C:/ttt/test.txt'
f = open(fname)
sum = 0
while | True:
line = f.readline()
if not line:
break
sum += | int(line)
print(sum)
f.close()
file_to_write = open('c:/ttt/abc.csv', 'w')
file_to_write.write('hahaha,kkk,1,2,3,4,5\n')
file_to_write.write('a, b, c, e, d, e')
file_to_write.close() |
gentoo/layman | layman/overlays/modules/stub/stub.py | Python | gpl-2.0 | 1,731 | 0.011554 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
#===============================================================================
#
# Dependencies
#
#-------------------------------------------------------------------------------
from layman.utils import path
from laym... | s | elf.hint = 'Did you install layman with "%(type)s" support?'\
% self.info
def add(self, base):
'''Add overlay.'''
self.output.error(self.missing_msg)
self.output.warn(self.hint)
return True
def update(self, base, src):
'''
Updates overlay src-url.
... |
Azzahid/Flow-Control | bin/fibo.py | Python | lgpl-3.0 | 153 | 0 | a, b = | 1, 1
total = 0
while a <= 4000000:
if a % 2 == 0:
total += a
a, b = b, a+b # the real formula for Fibonacci sequence
print tota | l
|
pythonLearning-bigData/Snail | run.py | Python | bsd-3-clause | 80 | 0 | from web import views
| if __name__ == "__main__":
views.a | pp.run(debug=True)
|
cc1-cloud/cc1 | src/cm/views/user/template.py | Python | apache-2.0 | 1,727 | 0.001738 | # -*- coding: utf-8 -*-
# @COPYRIGHT_begin
#
# Copyright [2010-2014] Institute of Nuclear Physics PAN, Krakow, Poland
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apac... | emplate import Template
from cm.utils.exception import CMException
from common.states import template_states
from cm.utils.decorators import user_log
@user_log(log=True)
def get_list(caller_id):
"""
Returns list of Templates.
@cmview_user
@response{list(dict)} Template.dict property of each Template
... | ects.filter(state__exact=template_states['active']).order_by('cpu', 'memory')]
except:
raise CMException("template_list")
return templates
@user_log(log=True)
def get_by_id(caller_id, template_id):
"""
@cmview_user
@param_post{template_id,int}
@response{dict} Template.dict property o... |
h2oai/h2o | py/testdir_0xdata_only/test_from_hdfs_hosts.py | Python | apache-2.0 | 2,900 | 0.005862 | import unittest, time, sys, random
sys.path.extend(['.','..','../..','py'])
import h2o, h2o_cmd, h2o_browse as h2b, h2o_import as h2i
class Basic(unittest.TestCase):
def tearDown(self):
h2o.check_sandbox_for_errors()
@classmethod
def setUpClass(cls):
h2o.init(3, use_hdfs=True, hdfs_version... | FilenameList = csvFilenameAll
# pop open a browser on the cloud
h2b.browseTheCloud()
timeoutSecs = 1000
# save the first, for all comparisions, to avoid slow drift with each iteration
firstglm = {}
for csvFilename in csvFilenameList:
# creates csvFilename.h... | s/" + csvFilename
parseResult = h2i.import_parse(path=csvPathname, schema='hdfs', header=0,
timeoutSecs=timeoutSecs, retryDelaySecs=1.0)
print csvFilename, '\nparse time (python)', time.time() - start, 'seconds'
### print h2o.dump_json(parseResult['response'])
... |
Bekt/tweetement | appengine_config.py | Python | mit | 639 | 0 | import sys
import os.path
sys.path.append(os.path.join(os.path.dirname(__file__), 'src'))
sys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))
sys.pa | th.append(os.path.join(os.path.dirname(__file__), 'lib/pip'))
# Workaround the dev-en | vironment SSL:
# http://stackoverflow.com/q/16192916/893652
if os.environ.get('SERVER_SOFTWARE', '').startswith('Development'):
import imp
import os
from google.appengine.tools.devappserver2.python import sandbox
sandbox._WHITE_LIST_C_MODULES += ['_ssl', '_socket']
imp.load_source('socket',
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.