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 |
|---|---|---|---|---|---|---|---|---|
ensime/ensime-vim | ensime_shared/ticker.py | Python | mit | 956 | 0.001046 | REFRESH_TIMER = 1000
c | lass Ticker(object):
def __init__(self, _vim):
self._vim = _vim
self.has_timers = bool(int(self._vim.eval("has('timers')")))
if self.has_timers:
self._timer = None
self._start_refresh_timer()
def tick(self, client):
filename = client.editor.path()
... | ot self.has_timers:
self._repeat_cursor_hold()
def _repeat_cursor_hold(self):
self._vim.options['updatetime'] = REFRESH_TIMER
self._vim.command('call feedkeys("f\e")')
def _start_refresh_timer(self):
"""Start the Vim timer. """
if not self._timer:
self._... |
deepjets/deepjets | deepjets/testdata/__init__.py | Python | bsd-3-clause | 207 | 0 | import os
from pkg_resources import resource_filename
__all__ = [
'get_filepath',
]
def get_filepa | th(name='sherpa_wz.hepmc'):
ret | urn resource_filename('deepjets', os.path.join('testdata', name))
|
leighpauls/k2cro4 | third_party/python_26/Lib/site-packages/win32comext/axscript/client/framework.py | Python | bsd-3-clause | 36,696 | 0.030494 | "" | "AXScript Client Framework
This module provides a core framework for an ActiveX Scripting client.
Derived classes actually implement the AX Client itself, including the
scoping rules, etc.
There are classes defined for the engine itself, and for ScriptItems
"""
import sys
from win32com.axscript import axscrip... | ext):
# No longer just "RemoveCR" - should be renamed to
# FixNewlines, or something. Idea is to fix arbitary newlines into
# something Python can compile...
return re.sub('(\r\n)|\r|(\n\r)','\n',text)
SCRIPTTEXT_FORCEEXECUTION = -2147483648 # 0x80000000
SCRIPTTEXT_ISEXPRESSION = 0x00000020
SCRIPTTEXT_ISPERSISTENT... |
openrural/open-data-nc | opendata/requests/forms.py | Python | mit | 1,046 | 0 | from django import forms
from selectable.forms import AutoCompleteSelectField
from selectable.forms import AutoCompleteSelectWidget
from opendata.catalog.lookups import CityLookup, CountyLookup
from .models import Request
class SearchForm(forms.Form):
| text = forms.CharField(required=False)
class RequestForm(forms.ModelForm):
county = AutoCompleteSelectField(
lookup_class=CountyLookup,
required=False,
widget=AutoCompleteSelectWidget(
lookup_class=CountyLookup,
attrs={"class": "suggestions-hidden suggestions-county... | lookup_class=CityLookup,
required=False,
widget=AutoCompleteSelectWidget(
lookup_class=CityLookup,
attrs={"class": "suggestions-hidden suggestions-city"},
)
)
class Meta:
model = Request
exclude = ('suggested_by', 'resources', 'rating', 'stat... |
chenmoshushi/libsvm | python_old/svm.py | Python | bsd-3-clause | 8,155 | 0.045984 | import svmc
from svmc import C_SVC, NU_SVC, ONE_CLASS, EPSILON_SVR, NU_SVR
from svmc imp | ort LINEAR, POLY, RBF, SIGMOID, PRECOMPUTED
from math import exp, fabs
def _int_array(seq):
size = len(seq)
array = svmc.new_i | nt(size)
i = 0
for item in seq:
svmc.int_setitem(array,i,item)
i = i + 1
return array
def _double_array(seq):
size = len(seq)
array = svmc.new_double(size)
i = 0
for item in seq:
svmc.double_setitem(array,i,item)
i = i + 1
return array
def _free_int_array(x):
if x != 'NULL' and x != None:
svmc.dele... |
TheAnosmic/cheetahs_byte | compile/break_to_atoms.py | Python | gpl-2.0 | 980 | 0 | from node import NodeChain
from opcode_ import OPCode
def node_to_atom(node, iterator):
arg_size = node.get_arg_size()
atom = NodeChain(node)
while arg_size > 0:
try:
arg = iterator.next()
except StopIteration:
raise ValueError("Not enough arguments")
if is... | " OPCode args")
atom.append(arg)
arg_size -= arg.get_size()
if arg_size < 0:
original_arg_size = node.get_arg_size()
real_arg_size = original_arg_size + abs(arg_size)
raise ValueError("Argument size mismatch,"
"Expecting: %s, Got %s"
... | node in i:
atoms.append(node_to_atom(node, i))
return atoms
|
aeklant/scipy | scipy/stats/tests/test_kdeoth.py | Python | bsd-3-clause | 14,694 | 0.001157 | from scipy import stats
import numpy as np
from numpy.testing import (assert_almost_equal, assert_,
assert_array_almost_equal, assert_array_almost_equal_nulp, assert_allclose)
import pytest
from pytest import raises as assert_raises
def test_kde_1d():
#some basic tests comparing to normal distribution
np.... | e_box(xnmean, np.inf), prob1, decimal=13)
assert_almost_equal( | gkde.integrate_box(-np.inf, xnmean), prob2, decimal=13)
assert_almost_equal(gkde.integrate_kde(gkde),
(kdepdf**2).sum()*intervall, decimal=2)
assert_almost_equal(gkde.integrate_gaussian(xnmean, xnstd**2),
(kdepdf*normpdf).sum()*intervall, decimal=2)
@pytest.mar... |
imperodesign/paas-tools | deis/stg/controller/api/south_migrations/0024_auto__chg_field_key_fingerprint__del_unique_key_owner_id__add_unique_k.py | Python | mit | 12,806 | 0.008199 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Removing unique constraint on 'Key', fields ['owner', 'id']
db.delete_u... | ocfile': ('json_field.fields.JSONField', [], {'default': '{}', 'blank': 'True'}),
'sha': ('django.db.models.fields.CharField', [], {'max_length': '40', 'blank': 'True'}),
'updated': (' | django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'uuid': ('api.fields.UuidField', [], {'unique': 'True', 'max_length': '32', 'primary_key': 'True'})
},
u'api.certificate': {
'Meta': {'object_name': 'Certificate'},
'certificate': ('dj... |
dreamhost/ceilometer | tests/api/v2/test_max_project_volume.py | Python | apache-2.0 | 5,448 | 0 | # -*- encoding: utf-8 -*-
#
# Copyright © 2012 New Dream Network, LLC (DreamHost)
#
# Author: Steven Berler <steven.berler@dreamhost.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
#
# ... | 'value': 'project1',
},
{'field': 'timestamp',
'op': 'le',
'value': '2012-09-25T11:30 | :00',
},
])
self.assertEqual(data[0]['max'], 5)
self.assertEqual(data[0]['count'], 1)
def test_end_timestamp_before(self):
data = self.get_json(self.PATH, q=[{'field': 'project_id',
... |
apache/libcloud | libcloud/compute/drivers/gce.py | Python | apache-2.0 | 389,823 | 0.000441 | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... | more_results = True
items = []
max_results = kwargs["max_results"] if "max_results" in kwargs else 500
params = {"maxResults": max_results}
while mo | re_results:
self.gce_params = params
response = self.request(*args, **kwargs)
items.extend(response.object.get("items", []))
more_results = "pageToken" in params
return {"items": items}
def request(self, *args, **kwargs):
"""
Perform request ... |
tomevans/utils | constants.py | Python | gpl-2.0 | 370 | 0.008108 | import | scipy
# Units in SI, i.e. not cgs
RSUN = 6.955e8
MSUN = 1.9889e30
MJUP = 1.8986e27
RJUP = 7.149e7
REARTH = 6.371e6
DAY2S = 86400.0
DEG2RAD = scipy.pi/180.
AU = 1.4 | 96e11
PLANCKH = 6.626e-34
BOLTZK = 1.38065e-23
C = 2.9979e8 # peed of light in vacuum in m s^-1
G = 6.673e-11 # gravitational constant in m^3 kg^-1 s^-2
RGAS = 8.314 # gas constant in J mol^-1 K^-1
|
8u1a/my_matasano_crypto_challenges | set1/challenge7.py | Python | unlicense | 4,632 | 0.002375 | __author__ = 'christianbuia'
from Crypto.Cipher import AES
import base64
#-----------------------------------------------------------------------------------------------------------------------
def solve_challenge(b64_crypt):
ciphertext = base64.decodebytes(bytes(b64_crypt, "ascii"))
key="YELLOW SUBMARINE"
... | rXFiz9DSq8
0rR5Kfs+M+Vuq5Z6zY98/SP0A6URIr9NFu+Cs9/gf+q4TRwsOzRMjMQzJL8f
7TXPEHH2+qEcpDKz/5pE0cvrgHr63XKu4XbzLCOBz0DoFAw3vkuxGwJq4Cpx
kt+eCtxSKUzNtXMn/mbPqPl4NZNJ8yzMqTFSODS4bYTBaN/uQYcOAF3NBYFd
5x9TzIAoW6ai13a8h/s9i5FlVRJDe2cetQhArrIVBquF0L0mUXMWNPFKkaQE
BsxpMCYh7pp7YlyCNode12k5jY1/lc8jQLQJ+EJHdCdM5t3emRzkPgND4a7O
NhoI... | A7KaHm13m0v
wN/O4KYTiiY3aO3siayjNrrNBpn1OeLv9UUneLSCdxcUqjRvOrdA5NYv25Hb
4wkFCIhC/Y2ze/kNyis6FrXtStcjKC1w9Kg8O25VXB1Fmpu+4nzpbNdJ9LXa
hF7wjOPXN6dixVKpzwTYjEFDSMaMhaTOTCaqJig97624wv79URbCgsyzwaC7
YXRtbTstbFuEFBee3uW7B3xXw72mymM2BS2uPQ5NIwmacbhta8aCRQEGqIZ0
78YrrOlZIjar3lbTCo5o6nbbDq9bvilirWG/SgWINuc3pWl5CscRcgQQNp7o
LBg... |
popravich/elasticmagic | tests/test_codec.py | Python | apache-2.0 | 1,724 | 0.00174 | import unittest
from elasticmagic.types import Integer, Float, Boolean
from elasticmagic.ext.queryfilter.codec import SimpleCodec
class SimpleCodecTest(unittest.TestCase):
def test_decode(self):
codec = SimpleCodec()
self.assertEqual(
codec.decode({'country': ['ru', 'ua', 'null']}),
... | , ('price__lte', ['200'])], {'price': Float}),
{
'price': {
'gte': [[100.1], [101.0]],
'lte': [[200.0]],
}
}
)
self.assertEqual(
codec.decode({'price__lte': '123a:bc'}, {'price': [Fl | oat]}),
{}
)
self.assertRaises(TypeError, lambda: codec.decode(''))
|
ssic7i/rpi_weather_app | form_ui.py | Python | mit | 8,911 | 0.001131 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'form_ui.ui'
#
# Created: Fri Apr 01 21:42:03 2016
# by: PyQt4 UI code generator 4.11.2
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except Attrib... | temp.setFrameShape(QtGui.Q | Frame.Panel)
self.lcdNumber_temp.setLineWidth(1)
self.lcdNumber_temp.setNumDigits(7)
self.lcdNumber_temp.setSegmentStyle(QtGui.QLCDNumber.Flat)
self.lcdNumber_temp.setProperty("value", 0.0)
self.lcdNumber_temp.setObjectName(_fromUtf8("lcdNumber_temp"))
self.label_2 = QtGu... |
HybridF5/jacket | jacket/compute/image/download/file.py | Python | apache-2.0 | 7,388 | 0.000677 | # Copyright 2013 Red Hat, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | Opt('id',
help=_('A unique ID given to each file system. This is '
'value is set in Glance and agreed upon here so '
'that the operator knowns they are dealing with '
'the same file system.')),
cfg.StrOpt('mou... | for fs in CONF.image_file_url.filesystems:
group_name = 'image_file_url:' + fs
conf_group = CONF[group_name]
if conf_group.id is None:
msg = _('The group %(group_name)s must be configured with '
'an id.') % {'group_name': group_name}
... |
Wang-Sen/nqzx-backend | bootcamp/app/models.py | Python | gpl-3.0 | 1,418 | 0.009873 | # -*- encoding: utf-8 -*-
import re
from django.contrib.auth.models import User
class LoginBackend(object):
def authenticate(self, username=None, password=None):
if username:
#email
if re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", username) != None:... | user = User.objects.get(email=usern | ame)
if user.check_password(password):
return user
except User.DoesNotExist:
return None
#mobile
elif len(username)==11 and re.match("^(1[3458]\d{9})$", username) != None:
try:
use... |
msincenselee/vnpy | vnpy/gateway/tora/terminal_info.py | Python | mit | 1,108 | 0 | import wmi
import requests
import pythoncom
def get_iip():
""""""
f = requests.get("http://myip.dnsomatic.com")
iip = f.text
return iip
def get_lip():
""""""
c = wmi.WMI()
lip = ""
for interface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1):
lip = interface.IPAddress[0... | bled=1):
mac = interface.MACAddress
return mac
def get_hd():
""""""
c = wmi.WMI()
hd = "disk01"
# for disk in c.Win32_DiskDrive():
# hd = disk.SerialNumber.strip()
return hd
def get_terminal_info():
""""""
# Initialize COM | object in this thread.
pythoncom.CoInitialize()
iip = ""
iport = ""
lip = get_lip()
mac = get_mac()
hd = get_hd()
terminal_info = ";".join([
"PC",
f"IIP={iip}",
f"IPORT={iport}",
f"LIP={lip}",
f"MAC={mac}",
f"HD={hd}",
"PCN=NA;CPU=NA;... |
wkentaro/fcn | examples/apc2016/datasets/mit_benchmark.py | Python | mit | 3,797 | 0 | import itertools
import os
import os.path as osp
import chainer
import numpy as np
import scipy.misc
from sklearn.model_selection import train_test_split
from base import APC2016DatasetBase
def ids_from_scene_dir(scene_dir, empty_scene_dir):
for i_frame in itertools.count():
empt | y_file = osp.join(
empty_scene_dir, 'frame-{:06}.color.png'.format(i_frame))
rgb_file = osp.join(
scene_dir, 'frame-{:06}.color.png'.format(i_frame))
segm_file = osp.join(
scene_dir, 'segm/frame-{:06}.segm.png | '.format(i_frame))
if not (osp.exists(rgb_file) and osp.exists(segm_file)):
break
data_id = (empty_file, rgb_file, segm_file)
yield data_id
def bin_id_from_scene_dir(scene_dir):
caminfo = open(osp.join(scene_dir, 'cam.info.txt')).read()
loc = caminfo.splitlines()[0].split('... |
tpltnt/SimpleCV | SimpleCV/examples/detection/face-substition.py | Python | bsd-3-clause | 1,253 | 0.003192 | #!/usr/bin/env python
#
# Released under the BSD license. See LICENSE file for details.
"""
All this example does is find a face and replace it with another image. The
image should auto scale to match the size of the face.
"""
from __future__ import print_function
print(__doc__)
from SimpleCV | import Camera, Display, HaarCascade, Imag | e
#initialize the camera
cam = Camera()
# Create the display to show the image
display = Display()
# Load the new face image
troll_face = Image('troll_face.png', sample=True)
# Haar Cascade face detection, only faces
haarcascade = HaarCascade("face")
# Loop forever
while display.isNotDone():
# Get image, flip i... |
Insanityandme/dotfiles | vim/bundle/ultisnips/test/test_Folding.py | Python | unlicense | 1,594 | 0.001255 | from test.vim_test_case import VimTestCase as _VimTest
from test.constant import *
# Folding Interaction {{{#
class FoldingEnabled_SnippetWithFold_ExpectNoFolding(_VimTest):
def _extra_vim_config(self, vim_config):
vim_config.append('set foldlevel=0')
vim_config.append('set foldmethod=marker')
... | foldmarker").split(",")[0]`
# End: $1 `!p snip.rv = vim.eval("&foldmarker").split(",")[1]`""")
keys | = 'fold' + EX + 'hi'
wanted = '# hi {{{\n\n# End: hi }}}'
class Fold_DeleteMiddleLine_ECR(_VimTest):
snippets = ('fold',
"""# ${1:Description} `!p snip.rv = vim.eval("&foldmarker").split(",")[0]`
# End: $1 `!p snip.rv = vim.eval("&foldmarker").split(",")[1]`""")
keys = 'fold' + EX + ... |
demisto/content | Packs/Intezer/Integrations/IntezerV2/IntezerV2.py | Python | mit | 16,706 | 0.002454 | from http import HTTPStatus
from typing import Callable
from typing import Dict
from typing import List
from typing import Union
import demistomock as demisto
import requests
from CommonServerPython import *
from CommonServerUserPython import *
from intezer_sdk import consts
from intezer_sdk.analysis import Analysis
f... | ]) -> CommandResults:
file_hash = args.get('file_hash')
if not file_hash:
raise ValueError('Missing file hash')
latest_analysis = get_latest_analysis(file_hash=file_hash | , api=intezer_api)
if not latest_analysis:
return _get_missing_file_result(file_hash)
return enrich_dbot_and_display_file_analysis_results(latest_analysis.result())
def analyze_by_uploaded_file_command(intezer_api: IntezerApi, args: dict) -> CommandResults:
file_id = args.get('file_entry_id')
... |
nemesisdesign/openwisp2 | openwisp_controller/config/migrations/0023_update_context.py | Python | gpl-3.0 | 888 | 0 | # Generated by Django 3.0.3 on 2020-02-26 19:58
import collections
import jsonfield.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [('config', '0022_vpn_format_dh')]
operations = [
migrations.AlterField(
model_name='config',
na... | href="http://netjsonconfig.openwisp.org'
'/en/stable/general/basics.html#context" target="_blank">'
'context (configuration variables)</a> in JSON format'
),
load_kwargs={'objec | t_pairs_hook': collections.OrderedDict},
),
)
]
|
ph1l/halo_radio | rename.py | Python | gpl-2.0 | 1,285 | 0.044358 | #!/usr/bin/python
#
# simple hack to rename files in the db.
#
# pass it a list of song ids (seerated by commas), a search sctring and a replacement
#
#
import string,os,sys,time,getopt
def usage():
print " | %s [--ids=<songid1>,<songid2>[,...]] --search=<old_str> --replace=<new_str>" % (sys.argv[0])
sys.exit(2)
try:
opts, args = getopt.getopt( sys.argv[1:], "hi:s:r:", [ "help", "ids=", "search=", "replace=" ])
except getopt.GetoptError:
usage()
sys.exit(2)
ids = None
search = None
replace = None
... | ge()
sys.exit()
if o in ("-i", "--ids"):
ids = a.split(",")
if o in ( "-s", "--search"):
search = a
if o in ( "-r", "--replace"):
replace = a
print "%s %s %s" % (ids,search,replace)
if ( search == None ) or ( replace == None ):
usage()
import HaloRadio
if ids == None:
import HaloRadio.... |
skylian/XWorld | games/xworld/maps/XWorldDialogMap.py | Python | apache-2.0 | 3,644 | 0.006861 | import random
from xworld_env import XWorldEnv
from py_util import overrides
class XWorldDialogMap(XWorldEnv):
def __init__(self, item_path, start_level=0):
super(XWorldDialogMap, self).__init__(
item_path=item_path,
max_height=1,
max_width=1,
start_level=sta... | f.select_goal_classes()
return self.sel_classes
def within_session_reinstantiation(self):
# re-instantiate within the same session
# re-load from map config | with the same set of sampled classes
for e in self.get_goals():
# store what has been learned
self.learned_classes[e.name] = e.asset_path
if random.uniform(0,1) > self.img_var_ratio: # no var
# change name without changing the asset_path
goals... |
yacoob/blitzloop | blitzloop/util.py | Python | gpl-2.0 | 1,930 | 0.005181 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2013 Hector Martin "marcan" <hector@marcansoft.com>
#
# 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 or vers... | rser():
return configargparse.get_argument_parser()
def get_opts():
opts, unknown = get_argparser().parse_known_args()
return opts
def get_res_path(t, fp):
return os.path.join(CFG[t], fp)
def get_resfont_path(fp):
return get_res_path('fontdir', fp)
def get_resgfx_path(fp):
retur | n get_res_path('gfxdir', fp)
def get_webres_path(fp):
return get_res_path('webdir', fp)
def map_from(x, min, max):
return (x-min) / (max-min)
def map_to(x, min, max):
return min + x * (max - min)
init_argparser()
|
senthil10/scilifelab | scripts/RNA_analysis/quantify_rRNA.py | Python | mit | 1,425 | 0.032281 | import os
import sys
from string import *
import math
import string
import re
import commands
import operator
if len(sys.argv) < 2:
print "USAGE: python quantify_rRNA.py <gff file>"
sys.exit(0)
gffFile=sys.argv[1]
#rRNAgeneList=commands.getoutput("grep 'rRNA' "+gffFile+" |awk '{print $10}'").replace('"',''... | output("ls -d tophat_out_*|sed 's/tophat_out_//g'").split('\n')
outList=[]
for name in names:
DIR = str('tophat_out_'+name)
try:
countFile=commands.getoutput("ls "+DIR+"/"+name+".counts")
totNum=commands.getou | tput("awk '{SUM+=$2} END {print SUM}' "+countFile)
if totNum != '':
rRNAnum=0
Lines=open(countFile).readlines()
n=0
for line in Lines:
geneID=line.split()[0]
if geneID in rRNAgeneList:
n=n+1
num=int(line.split()[1])
rRNAnum=rRNAnum+num
percent=round((float(rRNAnum)/int(totNum))*1... |
yanheven/glance | glance/image_cache/client.py | Python | apache-2.0 | 4,184 | 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... | mages(self, **kwargs):
"""
Returns a list of images queued for caching
"""
res = self.do_request("GET", "/queued_images")
data = json.loads(res.read())['queued_images']
return data
def delete_all_cached_images | (self):
"""
Delete all cached images
"""
res = self.do_request("DELETE", "/cached_images")
data = json.loads(res.read())
num_deleted = data['num_deleted']
return num_deleted
def queue_image_for_caching(self, image_id):
"""
Queue an image for p... |
escamilla/MultipartPostHandler | MultipartPostHandler.py | Python | lgpl-3.0 | 3,692 | 0.002167 | #!/ | usr/bin/python
# Copyright 2013 Joshua Escamilla <jescamilla@hushmail.com>
#
# 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 3 of the License, or
# (at your option) any la... | 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this progr... |
gwpy/seismon | utils/version.py | Python | gpl-3.0 | 5,922 | 0.000675 | # -*- coding: utf-8 -*-
# Copyright (C) Duncan Macleod (2013)
#
# This file is part of SeisMon
#
# SeisMon 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)... | p.returncode,
' '.join(cmdargs))
return out.strip()
# ------------------------------------------------------------------------
# Git communication methods
def get_commit_info(self):
"""Determine basic info about the latest commit
"""
... | ode('utf-8').split(',')
self.id = a
self.udate = b
author = c
author_email = d
committer = e
committer_email = f
self.date = time.strftime('%Y-%m-%d %H:%M:%S +0000',
time.gmtime(float(self.udate)))
self.author = '%s <%s>' ... |
scotartt/commentarius | decommentariis/manage.py | Python | gpl-2.0 | 256 | 0.003906 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "decommentariis.setting | s")
from django.core.management import execute_from_command_line
execute_from_command | _line(sys.argv)
|
hivam/l10n_co_doctor | doctor_attentions_diseases_inherit.py | Python | agpl-3.0 | 2,526 | 0.009925 | # -*- coding: utf-8 -*-
# #############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GN... | verify duplicated disease
'''
for r in self.browse(cr, uid, ids, context=context):
diseases_ids = self.search(cr,uid,[('attentiont_id','=',r.attentiont_id.id),('diseases_id','=',r.diseases_id.id)])
if len(diseases_ids) > 1:
return False
| return True
_constraints = [
#(_check_main_disease, u'Hay más de un diagnóstico seleccionado como Principal. Por favor seleccione uno como Principal y los demás como Relacionados.', [u'\n\nTipo de Diagnóstico\n\n']),
#(_check_duplicated_disease, u'Hay uno o más diagnósticos duplicados.', [u... |
gjlawran/ckanext-bcgov | ckanext/bcgov/util/__init__.py | Python | agpl-3.0 | 965 | 0.014508 | # Copyright 2015, Province of British Columbia
# License: https://github.com/bcgov/ckanext-bcgov/blob/master/license
import ckan.plugins.toolkit as toolkit
from ckan.logic import get_action, NotFound
def get_tag_name(vocab_id, tag_id):
'''Returns the name of a tag for a given vocabulary and tag id.
Eac... | #First get the list of all tags for the given vocabulary.
tags = toolkit.get_action('tag_list')(
data_dict={'vocabulary_id': vocab_id})
#For each tag extract the 3-digit tag id and compare it with the given tag id.
for tag in tags :
if (tag[:3] == ta | g_id) :
return tag[5:]
#No tags exist with the given tag id.
return None
except toolkit.ObjectNotFound:
#No vocabulary exist with the given vocabulary id.
return None
|
xianc78/Asteroids | player.py | Python | unlicense | 2,498 | 0.03763 | import pygame, random, sys, math
import constants
from bullet import Bullet
pygame.init()
laserSound = pygame.mixer.Sound("resources/laser.wav")
class Player:
def __init__(self, x, y):
self.facing = "up"
try:
image = pygame.image.load("resources/ship.png")
image = pygame.transform.scale(image, (40, 40))
... | stants.SCREEN_HEIGHT
for asteroid in self.level.asteroid_list:
if self.rect.colliderect(asteroid.rect):
self.lives -= 1
self.jump()
| if self.lives <= 0:
pygame.quit()
sys.exit()
def change_speed(self, x, y):
self.change_x += x
self.change_y += y
def shoot(self):
if self.facing == "up":
change_x = 0
change_y = -8
elif self.facing == "down":
change_x = 0
change_y = 8
elif self.facing == "left":
change_x = -8
... |
dragondjf/cqssl | app/cqsscworker.py | Python | apache-2.0 | 3,057 | 0.001308 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from PyQt5.QtCore import *
from collections import OrderedDict
from signalmanager import signalManager
class CqsscWorker(QObject):
def __init__(self, parent=None):
super(CqsscWorker, self).__init__(parent)
self._rawDataLines = []
self._rawDat... | )
self._rawData_ballfour.update({key: value[3]})
self._rawData_ballfive.update({key: value[4]})
if sum(value) >= 23:
self._rawData_sumsize.update({key: 1})
else:
self._rawData_sumsize.update({key: 0})
if sum(value) % 2 == 0:
... | self._rawData_sumparity.update({key: 0})
if key <= "20150913-101":
print self._rawData_sumsize[key], value, sum(value)
signalManager.statusTextChanged.emit("reading data finished")
@staticmethod
def searchPattern(source, mode=0,count=4):
pattern = []
p... |
saltastro/pysalt | saltfp/saltfpringfilter.py | Python | bsd-3-clause | 7,647 | 0.0136 | ################################# LICENSE ############################## | ####
# Copyright (c) 2009, South African Astronomical Observatory (SAAO) #
# All rights reserved. # |
# #
# Redistribution and use in source and binary forms, with or without #
# modification, are permitted provided that the following conditions #
# are met: #
# ... |
Brett777/Predict-Churn | Deploy Persisted Scores.py | Python | mit | 2,784 | 0.020474 | import os
from boto.s3.connection import S3Connection
from boto.s3.key import Key
import h2o
import numpy as np
import pandas as pd
from tabulate import tabulate
from sqlalchemy import create_engine
# initialize the model scoring server
h2o.init(nthreads=1,max_mem_size=1, start_h2o=True, strict_version_check = False)... | edict_churn(State,AccountLength,AreaCode,Phone,IntlPlan,VMailPlan,VMailMessage,DayMins,DayCalls,DayCharge,EveMins,EveCalls,EveCharge,NightMins,NightCalls,NightCharge,IntlMins,IntlCalls,IntlCharge,CustServCalls):
# connect to the model scoring service
h2o.init(nthreads=1,max_mem_size=1, start_h2o=True, strict_ve... | downloaded model
ChurnPredictor = h2o.load_model(path='AutoML-leader')
# define a feature vector to evaluate with the model
newData = pd.DataFrame({'State' : State,
'Account Length' : AccountLength,
'Area Code' : AreaCode,
... |
glenmurphy/dropmocks | main.py | Python | mit | 16,653 | 0.015613 | import os, sys
from google.appengine.api.labs import taskqueue
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.ext import db
from google.appengine.api import images
from google.appengine.api import u... | + 1
if mocklist.name:
name = mocklist.name.encode('utf-8')
else:
name = ''
mocklistdata = {
'name' : name,
'id' : str(mocklist.get_id()),
'description' : str(mocklist.description),
'mocks' : mock | s,
}
# Check if current user owns it.
owner = getOwner(self, False)
if owner and mocklist.owner and mocklist.owner.key() == owner.key():
mocklistdata['key'] = mocklist.edit_key
json = simplejson.dumps(mocklistdata)
path = os.path.join(os.path.dirname(__file__), "viewer.html")
self.re... |
fishel/yarnnlm | sample.py | Python | mit | 644 | 0.041925 | #!/usr/bin/env python3
i | mport sys
import rnnlm
import txt
import pickle
from keras.models import load_model
if __name__ == "__main__":
modelInFile = sys.argv[1]
dictInFile = sys.argv[2]
try:
catSpec = sys.argv[3]
except IndexError:
catSpec = None
numToSample = 1
(mdl, params) = rnnlm.loadModels(modelInFile, dictInFile)
for ... | , params, specVec)
decoded = [str(params.i2w[i]) for i in raw]
print("".join(decoded) + " (" + str(prob) + ")")
|
dkarakats/edx-platform | lms/djangoapps/certificates/queue.py | Python | agpl-3.0 | 19,745 | 0.001722 | """Interface for adding certificate generation tasks to the XQueue. """
import json
import random
import logging
import lxml.html
from lxml.etree import XMLSyntaxError, ParserError # pylint:disable=no-name-in-module
from django.test.client import RequestFactory
from django.conf import settings
from django.core.urlres... | d_grade - a string indicating a grade parameter to pass with
the certificate request. If this is given, grading
will be skipped.
Will change the certificate status to 'generating'.
Certificate must be in the 'unavailable', 'error',
'deleted' or... | a request will be made for a new cert.
If a student has allow_certificate set to False in the
userprofile table the status will change to 'restricted'
If a student does not have a passing grade the status
will change to status.notpassing
Returns the student's status
"... |
comprobo-final-project/comprobo_final_project | comprobo_final_project/scripts/gene_alg_v1/chromosome.py | Python | mit | 3,598 | 0.003057 | #!usr/bin/env python
"""
Basic class that represents the chomosomes of our genetic algorithm.
"""
import random
import numpy as np
# The number of genes that each organism has
NUM_GENES = 4
# Boundary values for genes
GENE_MAX = 10000
GENE_MIN = -10000
class Chromosome:
"""
Holds the genes and fitness o... | .5, 2)
# Clip and round all genes
mutated_genes[index_to_mutate] = np.clip(mutated_genes[index_to_mutate],
GENE_MIN, GENE_MAX)
mutated_genes = [round(gene, 3) for gene in mutated_genes]
# Create new chromosome with genes from the mutated gen | es
return Chromosome(mutated_genes, self.supervisor)
def get_fitness(self):
"""
Calculate the fitness of a specified chromosome.
"""
# Apply current chromosome's genes to the supervisor
self.supervisor.use_genes(self.genes)
# Calculate fitness
posi... |
sammypg/youtube_downloader | setup.py | Python | mit | 470 | 0.008511 | # For building youtube_downloader on windows
from distutils.core import setup
impor | t py2exe
# Define wh | ere you want youtube_downloader to be built to below
build_dir =
data_files = [('',['settings.ini',
'LICENSE',
'README.md']),
('sessions',[])]
options = {'py2exe': {
'dist_dir': build_dir}}
setup(
windows=['youtube_downloader.py'],
... |
HewlettPackard/python-hpOneView | examples/ethernet_networks.py | Python | mit | 5,900 | 0.001525 | # -*- coding: utf-8 -*-
###
# (C) Copyright (2012-2017) Hewlett Packard Enterprise Development LP
#
# 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 limi... | OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEAL... | g = {
"ip": "<oneview_ip>",
"credentials": {
"userName": "<username>",
"password": "<password>"
}
}
options = {
"name": "OneViewSDK Test Ethernet Network",
"vlanId": 200,
"ethernetNetworkType": "Tagged",
"purpose": "General",
"smartLink": False,
"privateNetwork": Fal... |
vrsys/avangong | examples/inspector/inspector_qt.py | Python | lgpl-3.0 | 13,470 | 0.0049 | # -*- Mode:Python -*-
##########################################################################
# #
# This file is part of AVANGO. #
# ... | #
##########################################################################
import avango.osg
import avango.osg.simpleviewer
import avango.script
from elasticnodes import *
import sys
import random
from PySide import QtCore, QtGui
#from PyQt4 import Qt... | elf.itemData = data
self.childItems = []
def appendChild(self, item):
self.childItems.append(item)
def child(self, row):
return self.childItems[row]
def childCount(self):
return len(self.childItems)
def columnCount(self):
return len(self.itemData)
def dat... |
weiweihuanghuang/Glyphs-Scripts | Masters/Show next instance.py | Python | apache-2.0 | 623 | 0.035313 | #MenuTitle: Show next instance
# -*- coding: utf-8 -*-
__doc__="""
Jumps to next inst | ance shown in the preview field of the current Edit tab.
"""
import GlyphsApp
Doc = Glyphs.currentDocument
numberOfInstances = len( Glyphs.font.instances )
try:
currentInstanceNumber = Doc.windowController().activeEditViewController().selectedInstance()
if currentInstanceNumber < numberOfInstances:
Doc.windowC... | setSelectedInstance_( 1 )
except Exception, e:
print "Error:", e
|
AutorestCI/azure-sdk-for-python | azure-mgmt-compute/azure/mgmt/compute/v2016_04_30_preview/models/grant_access_data.py | Python | mit | 1,336 | 0 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license infor | mation.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class GrantAccessData(Model):
"""Data used... | _preview.models.AccessLevel
:param duration_in_seconds: Time duration in seconds until the SAS access
expires.
:type duration_in_seconds: int
"""
_validation = {
'access': {'required': True},
'duration_in_seconds': {'required': True},
}
_attribute_map = {
'access':... |
UNICT-DMI/Telegram-DMI-Bot | module/data/vars.py | Python | gpl-3.0 | 2,524 | 0.003223 | """ aulario.py """
BACK_BUTTON_TEXT = "Indietro ❌"
DAY_SELECTION = "Seleziona la data della lezione che ti interessa."
AULARIO_WARNING = "⚠️ Aulario non ancora pronto, riprova fra qualche minuto ⚠️"
LESSON_SELECTION = "Quale lezione devi seguire?"
NO_LESSON_WARNING = "Nessuna lezione programmata per questo giorno"
"... | i e contatti"
ERSU_ORARI = "🍽 ERSU orari e cont | atti"
APPUNTI_CLOUD = "☁️ Appunti & Cloud"
PROGETTI_RICONOSCIMENTI = "🏅 Progetti e Riconoscimenti"
ALL_COMMANDS = "Tutti i comandi"
CLOSE = "❌ Chiudi"
BACK_TO_MENU = "🔙 Torna al menu"
""" lezioni.py """
LE_USE_WARNING = "Questo comando è utilizzabile solo in privato"
LE_GROUP_WARNING = "Dal comando lezioni che hai... |
slozier/ironpython2 | Tests/Tools/modulediff.py | Python | apache-2.0 | 10,604 | 0.006978 | # Licensed to the .NET Foundation under one or more agreements.
# The .NET Foundation licenses this file to you under the Apache 2.0 License.
# See the LICENSE file in the project root for more information.
import logmodule
import sys
from System.IO import File, Directory
from System.Diagnostics import Process
BUG_R... | ispaceCnt:
while first_non_whitespace(self.cpytext[self.cpyindex]) > self.ispaceCnt:
add_diff('-', self.diffs , self.path, self.cpytext[self.cpyindex])
self.cpyindex += 1
else:
while first_non_whitespace(self.ipytext[self.ipyindex]) > self.cspaceCnt:
... | add_diff('+', self.diffs , self.path, self.ipytext[self.ipyindex])
self.ipyindex += 1
def diff_module(mod_name, cpy_path):
return ModuleDiffer(mod_name, cpy_path).process()
def collect_diffs(diffs, type):
res = []
collect_diffs_worker(res, '', diffs, type)
return res
... |
adewynter/Tools | Algorithms/stringOps.py | Python | mit | 4,317 | 0.046792 | # Adrian deWynter, 2017
# Implementation of various algorithms
# applied to strings
# Given a long string find the greater
# number that is also a palindrome.
def nextPalindrome(S):
def isPalindrome(x): return x == x[::-1]
while True:
S = S + 1
if isPalindrome(S): return S
# Given two words A,B find if A = r... | gramming approach:
M = [[0 for _ in s1] for _ in s2]
for i in range(1,len(s1)):
for j in range(1,len(s2)):
if s1[i] != s2[j]:
M[i][j] = max(M[i-1][j],M[i][j-1],M[i-1][j-1])
print M[-1][-1]
# Find all positions where the anagram | of a substring
# S exists in A
# Complexity: O(A + S)
def needleHaystack(S,A):
indexes = []
T = sufixTree(A)
i = 0
while i < len(S):
k = T.findSubstring(S)
if k = len(S): indexes.append(k)
S = getNextAnagram(S)
return indexes
left,right = 0,0
count = len(S)
indexes = []
dic = {}
for c in S:
if c... |
enova/pgl_ddl_deploy | generate_new_native_tests.py | Python | mit | 3,132 | 0.003831 | #!/usr/bin/env python3
from shutil import copyfile
import glob
import os
sql = './sql'
expected = './expected'
NEW_FILES = ['native_features']
for file in NEW_FILES:
filelist = glob.glob(f"{sql}/*{file}.sql")
for path in filelist:
try:
os.remove(path)
except:
print("Err... | plit_filename = filename.split("_", 1)
number = int(split_filename[0])
files[number] = split_filename[1]
max_file_num = max(files.keys())
def construct_filename(n, name):
return f"{str(n).zfill(2)}_{name}"
contents = """
SET client_min_messages = warning;
DO $$
BEGIN
IF current_setting('server_version_n... | ;
END IF;
END$$;
CREATE EXTENSION pgl_ddl_deploy;
CREATE OR REPLACE FUNCTION pgl_ddl_deploy.override() RETURNS BOOLEAN AS $BODY$
BEGIN
RETURN TRUE;
END;
$BODY$
LANGUAGE plpgsql IMMUTABLE;
INSERT INTO pgl_ddl_deploy.queue (queued_at,role,pubnames,message_type,message)
VALUES (now(),current_role,'{mock}'::TEXT[],pgl_d... |
byt3bl33d3r/mitmproxy | libmproxy/protocol/http.py | Python | mit | 56,839 | 0.000581 | from __future__ import absolute_import
import Cookie
import copy
import threading
import time
import urllib
import urlparse
from email.utils import parsedate_tz, formatdate, mktime_tz
import netlib
from netlib import http, tcp, odict, utils
from netlib.http import cookies
from .tcp import TCPHandler
from .primitives ... | est transmission started
timestamp_end: Timestamp indicating when request transmission ended
"""
def __init__(
self,
form_in,
method,
scheme,
host,
port,
path,
httpversion,
headers,
content,
timestamp_start=None,
... | tCaseless) or not headers
HTT |
axbaretto/beam | sdks/python/.tox/lint/lib/python2.7/site-packages/pylint/test/functional/abstract_class_instantiated_in_class.py | Python | apache-2.0 | 326 | 0 | """Don't warn if the class is i | nstantiated in its own body. | """
# pylint: disable=missing-docstring
import abc
import six
@six.add_metaclass(abc.ABCMeta)
class Ala(object):
@abc.abstractmethod
def bala(self):
pass
@classmethod
def portocala(cls):
instance = cls()
return instance
|
rfhk/tks-custom | account_analytic_line_sale/models/__init__.py | Python | agpl-3.0 | 181 | 0 | # -*- coding: utf-8 -* | -
# Copyright 2017 Rooms For (Hong Kong) Limited T/A OSCG
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
from . import | account_analytic_line
|
PyPlanet/PyPlanet | pyplanet/apps/core/pyplanet/views/toolbar.py | Python | gpl-3.0 | 1,256 | 0.027866 | from pyplanet.views import TemplateView
class ToolbarView(TemplateView):
template_name = 'core.pyplanet/toolbar.xml'
def __init__(s | elf, app, *args, **kwargs):
"""
Initiate Player Toolbar
:param app: App instance.
:type app: pyplanet.apps.core.pyplanet.app.PyPlanetConfig
"""
super().__init__(*args, **kwargs)
self.id = 'pyplanet__toolbar'
self.app = app
self.manager = self.app.context.ui
self.commands = {
'bar_button_list':... | on_extend': '/extend',
'bar_button_replay': '/replay',
'bar_button_players': '/players',
'bar_button_topdons': '/topdons',
'bar_button_topsums': '/topsums',
'bar_button_topactive': '/topactive',
'bar_button_mxinfo': '/{} info'.format('tmx' if self.app.instance.game.game == 'tmnext' else 'mx'),
'bar... |
MagiChau/Hearthstone-Card-Lookup | card_lookup/searcher.py | Python | mit | 4,417 | 0.029885 | """
Completes Hearthstone Card Lookup through comparing search queries to card names
"""
import copy
class Searcher:
def __init__(self, card_dict):
"""Initializes a Searcher object with a card dictionary provided
Args: card_dict(dict): Card dictionary with cards are separated
into sub dictionaries by set and... | d_match_weight
| percent_match += (percent_query_match * max_value['match'] * query_match_weight +
percent_card_match * max_value['match'] * card_match_weight)
if percent_match >= min_match:
result_list.append([card, percent_match])
return result_list
def levenshtein_distance(s1,s2):
"""Levenshtein Distance Algo... |
zero323/spark | dev/ansible-for-test-node/roles/jenkins-worker/files/util_scripts/post_github_pr_comment.py | Python | apache-2.0 | 2,930 | 0.000341 | #!/usr/bin/env python3
"""Utility program to post a comment to a github PR"""
import argparse
import json
import os
import sys
import urllib.parse
from urllib.error import HTTPError, URLError
from urllib.request import urlopen, Request
def _parse_args():
pr_link_var = "ghprbPullLink"
pr_link_option = "--pr-li... | pr_link_var, pr_link_option
)
)
if not args.github_oauth_key:
parser.error(
"Specify either environment variable {} or option {}".format(
github_oauth_key_var, github_oauth_key_option
)
)
return args
def post_message_to... |
print("Attempting to post to Github...")
ghprb_pull_id = os.environ["ghprbPullId"]
api_url = os.getenv("GITHUB_API_BASE", "https://api.github.com/repos/apache/spark")
url = api_url + "/issues/" + ghprb_pull_id + "/comments"
posted_message = json.dumps({"body": msg})
request = Request(
... |
eunchong/build | third_party/twisted_10_2/twisted/test/test_strports.py | Python | bsd-3-clause | 5,121 | 0.003515 | # Copyright (c) 2001-2010 Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for L{twisted.application.strports}.
"""
from twisted.trial.unittest import TestCase
from twisted.application import strports
from twisted.application import internet
from twisted.internet.test.test_endpoints import ParserTest... | e(svc.endpoint, UNIXServerEndpoint)
warnings = self.flushWarnings([self.test_serviceDeprecatedDefault])
self.assertEquals(warnings[0]['category'], DeprecationWarning)
self.assertEquals(
warnings[0]['message'],
"The 'default' parameter was deprecated | in Twisted 10.2.0. "
"Use qualified endpoint descriptions; for example, 'tcp:8080'.")
self.assertEquals(len(warnings), 1)
# Almost the same case, but slightly tricky - explicitly passing the old
# default value, None, also must trigger a deprecation warning.
svc = strports.... |
LMML-Team/AlexaSkills | GenerateText/Generate_text.py | Python | mit | 4,460 | 0.005605 | import time
import numpy as np
from collections import Counter
from collections import defaultdict
import matplotlib.pyplot as plt
def unzip(pairs):
"""
Splits list of pairs (tuples) into separate lists
Parameter(s)
--------------
pairs(list of tuples):
List of pairs to be split
... | "
# Initializes history and text
text = []
history_indices = np.arange(len(lm.keys()))
index = np.random.choice(history_indices | )
history = list(lm.keys())
history = history[index]
print(history)
print(type(history))
# uses generate_letter function to generate text that is nletters long
for i in range(nletters):
c = generate_letter(lm, history)
text.append(c)
history = history[1:] + c
# Join... |
getsentry/sentry-teamwork | sentry_teamwork/plugin.py | Python | apache-2.0 | 5,373 | 0.000186 | from __future__ import absolute_import
import sentry_teamwork
from django import forms
from django.utils.translation import ugettext_lazy as _
from requests.exceptions import RequestException
from sentry.plugins.base import JSONResponse
from sentry.plugins.bases.issue import IssuePlugin, NewIssueForm
from sentry.util... | ))
def get_client(self, project):
return TeamworkClient(
base_url=self.get_option(' | url', project),
token=self.get_option('token', project),
)
def get_new_issue_form(self, request, group, event, **kwargs):
"""
Return a Form for the "Create new issue" page.
"""
return self.new_issue_form(
client=self.get_client(group.project),
... |
Mu5tank05/Walter | plugins/tfc.py | Python | gpl-3.0 | 437 | 0.006865 | from | cloudbot import hook
from cloudbot.util import http
# https://raw.githubusercontent.com/AwesomePowered/CloudBot/e01b2ab41985db8dbd6f6a1501ab9353f326188f/plugins/theyfightcrime.py
@hook.command("tfc")
def plot():
bold = "\x02"
try:
soup = http.get_soup( | "http://www.theyfightcrime.org")
plot = soup.find('table').find('p').text
return bold + plot + bold
except:
return "Could not get plot." |
jevinw/rec_utilities | babel_util/scripts/ai_to_pajek.py | Python | agpl-3.0 | 918 | 0.003268 | #!/usr/bin/env python
from util.misc import open_file, Benchmark
from util.Pa | jekFactory import PajekFactory
import ujson
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Creates Pajek (.net) files from JSON")
parser.add_argument('outfile')
parser.add_argument('--temp-dir', help="Directory to store temporary files in", default=None)
p... | ('infile', nargs='+')
arguments = parser.parse_args()
b = Benchmark()
pjk = PajekFactory(temp_dir=arguments.temp_dir)
for filename in arguments.infile:
with open_file(filename) as f:
for line in f:
entry = ujson.loads(line)
for citation in entry["cit... |
LibCrowds/libcrowds-analyst | libcrowds_analyst/analysis/convert_a_card.py | Python | mit | 1,810 | 0 | # -*- coding: utf8 -*-
"""Convert-a-Card analysis module."""
import time
import enki
from libcrowds_analyst.analysis import helpers
from libcrowds_analyst import object_loader
MATCH_PERCENTAGE = 60
VALID_KEYS = ['oclc', 'shelfmark', 'comments']
def analyse(api_key, endpoint, doi, project_id, result_id, project_sho... | onvert-a-Card results."""
e = enki.Enki(api_key, endpoint, project_short_name, all=1)
result = enki.pbclient.find_results(project_id, id=result_id, limit=1,
all=1)[0]
df = helpers.get_task_run_df(e, result.task_id)
| df = df.loc[:, df.columns.isin(VALID_KEYS)]
df = helpers.drop_empty_rows(df)
n_task_runs = len(df.index)
# Initialise the result
defaults = {k: "" for k in df.keys()}
result.info = helpers.init_result_info(doi, path, defaults)
has_answers = not df.empty
has_matches = helpers.has_n_matches(... |
chawk/django-easy-avatar | easy_avatar/urls.py | Python | mit | 148 | 0.02027 | from django.conf.urls import patterns, include, url
urlpatterns = patterns('' | ,
# Examples:
url(r'^upload/$', ' | easy_avatar.views.upload'),
) |
DamienIrving/ocean-analysis | visualisation/water_cycle/plot_pe_spatial.py | Python | mit | 9,330 | 0.005681 | """Plot spatial P-E"""
import re
import sys
script_dir = sys.path[0]
import os
import pdb
import argparse
import numpy as np
import matplotlib.pyplot as plt
import iris
from iris.experimental.equalise_cubes import equalise_attributes
import cartopy.crs as ccrs
import cmdline_provenance as cmdprov
repo_dir = '/'.join... |
hatches=['\\\\'],) # # '.', '/', '\\', '\\\\', '*'
if clim:
ce = ax.contour(x, y, clim.data,
transform=inproj,
colors=['goldenrod', 'black', 'green'],
levels=np.array([-2, 0, 2]))
cba | r = plt.colorbar(cf)
cbar.set_label(cbar_label) #, fontsize=label_size)
# cbar.ax.tick_params(labelsize=number_size)
plt.gca().coastlines()
ax.set_title(title)
if agg == 'clim':
lons = np.arange(-180, 180, 0.5)
lats_sh = np.repeat(-20, len(lons))
lats_nh = np.repeat(20, len... |
BlogomaticProject/Blogomatic | opt/blog-o-matic/usr/lib/python/Bio/HMM/DynamicProgramming.py | Python | gpl-2.0 | 12,644 | 0.001107 | """Dynamic Programming algorithms for general usage.
This module contains classes which implement Dynamic Programming
algorithms that can be used generally.
"""
class AbstractDPAlgorithms:
"""An abstract class to calculate forward and backward probabiliies.
This class should not be instantiated directly, but... | in range(len(self._seq.emissions)):
| # now loop over the letters in the state path
for main_state in state_letters:
# calculate the forward value using the appropriate
# method to prevent underflow errors
forward_value = self._forward_recursion(main_state, i,
... |
gem/oq-hazardlib | openquake/hmtk/strain/regionalisation/__init__.py | Python | agpl-3.0 | 1,925 | 0.004675 | # -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# LICENSE
#
# Copyright (c) 2010-2017, GEM Foundation, G. Weatherill, M. Pagani,
# D. Monelli.
#
# The Hazard Modeller's Toolkit is free software: you can redistribute
# it and/or modify it under the terms of the GNU Affero General Public
#License a... | k and software design communities.
#
# The software is NOT distributed as part of GEM's OpenQuake suite
# (http://www.globalquakemodel.org/openquake) and must be considered as a
# separate entity. The software provided herein is designed and implemented
# by scientific staff. It is not developed to the design standards... | bution to the software is welcome, and can be
# directed to the hazard scientific staff of the GEM Model Facility
# (hazard@globalquakemodel.org).
#
# The Hazard Modeller's Toolkit (openquake.hmtk) is therefore distributed WITHOUT
#ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
#FITNESS FOR A PAR... |
supriyasawant/gstudio | gnowsys-ndf/gnowsys_ndf/ndf/urls/file.py | Python | agpl-3.0 | 1,918 | 0.009385 | from django.conf.urls import patterns, url
from django.views.generic import TemplateView
urlpatterns = patterns('gnowsys_ndf.ndf.views.file',
url(r'^[/]$', 'file', name='file'),
# url(r'^/(?P<file_id>[\w-]+)$', 'file', name='file'),
url(r'^/uploadDo... | edit'),
url(r'^/(?P<fi | letype>[\w-]+)/page-no=(?P<page_no>\d+)/$', 'paged_file_objs', name='paged_file_objs'),
)
|
shamanu4/netmiko | netmiko/hp/hp_procurve_ssh.py | Python | mit | 2,061 | 0 | from __future__ import print_function
from __future__ import unicode_literals
import re
import time
import socket
from netmiko.cisco_base_connection import CiscoSSHConnection
class HPProcurveSSH(CiscoSSHConnection):
def session_preparation(self):
"""
Prepare the session after the connection has b... | ape_codes = True
self.set_base_prompt()
self.disable_paging(command="\nno | page\n")
self.set_terminal_width(command='terminal width 511')
def enable(self, cmd='enable', pattern='password', re_flags=re.IGNORECASE,
default_username='manager'):
"""Enter enable mode"""
debug = False
output = self.send_command_timing(cmd)
if 'username' i... |
cduff4464/2016_summer_XPD | out_of_date/matplotlib_demo/Open_New_Plot_Demo.py | Python | bsd-2-clause | 646 | 0.009288 | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import RadioButtons
t = np.arange(0.0, 2.0, 0.01)
s0 = np.sin(2*np.pi*t)
s1 = np.sin(4*np.pi*t)
s2 = np.sin(8*np.pi*t)
fig = plt.figure(1)
rax = plt.subplot2grid((1,1), (0,0))
radio | = RadioButtons(rax, ('2 Hz', '4 Hz', '8 Hz', 'Clear'))
def new_plot(Event):
plt.figure(2)
if Event == '2 Hz':
plt.plot(t | , s0)
plt.show()
if Event == 'Clear':
plt.clf().figure(2)
if Event == '8 Hz':
plt.plot(t, s2)
plt.show()
if Event == '4 Hz':
plt.plot(t,s1)
plt.show()
radio.on_clicked(new_plot)
plt.show() |
pamoller/xmlformatter | xmlformatter.py | Python | mit | 30,777 | 0.000617 | """
Format and compress XML documents
"""
import getopt
import re
import sys
import xml.parsers.expat
__version__ = "0.2.4"
DEFAULT_BLANKS = False
DEFAULT_COMPRESS = False
DEFAULT_SELFCLOSE = False
DEFAULT_CORRECT = True
DEFAULT_INDENT = 2
DEFAULT_INDENT_CHAR = " "
DEFAULT_INLINE = True
DEFAULT_ENCODING_INPUT = None... | ormatter.TokenList(self)
token_list.parser.Parse(xmldoc)
return self.enc_encode(str(token_list))
def format_file(self, file):
""" Format a XML document given by path name """
fh = open(file, "rb")
token_list = Formatter.TokenList(self)
token_list.parser.ParseFile(fh)... | ding whitespace:
desc_mixed_level = None
# Lock indenting:
indent_level = None
# Reference the Formatter:
formatter = None
# Count levels:
level_counter = 0
# Lock deletion of whitespaces:
preserve_level = None
def __init__(self, formatter... |
Errantgod/azaharTEA | menubar/menus/filechoosers/__init__.py | Python | mit | 60 | 0.016667 | __all__ = ['savedialog.SaveDia | log','opendialog.OpenDialog']
| |
setaris/django-tesseract2 | deployment/fabfile.py | Python | bsd-3-clause | 2,815 | 0.003908 | import os
from fabric.api import env, run, cd, sudo, settings
from fabric.contrib.files import upload_template
def get_env_variable(var_name):
""" Get the environment variable or return exception """
try:
return os.environ[var_name]
except KeyError:
error_msg = "Variable %s is not set in ... | o("sudo initctl start djangotesseract2")
sudo('/etc/init.d/nginx reload')
def setup():
run("mkdir -p %(root)s" % env)
sudo("aptitude update")
sudo("aptitude -y install git-core python-dev python-setuptools "
"build-essential subversion mercurial nginx "
"libjpeg62 libjpeg62-dev zlib1g-... | )
sudo("easy_install virtualenv")
run("virtualenv %(virtualenv)s" % env)
run("%(virtualenv)s/bin/pip install -U pip" % env)
with cd("~/webapps/"):
run("git clone %(repo_url)s djangotesseract2" % env)
with cd("%(project)s" % env):
run('mkdir assets')
run('mkdir media')
... |
dmick/teuthology | teuthology/config.py | Python | mit | 8,592 | 0.000466 | import os
import yaml
import logging
import collections
def init_logging():
log = logging.getLogger(__name__)
return log
log = init_logging()
class YamlConfig(collections.MutableMapping):
"""
A configuration object populated by parsing a yaml file, with optional
default values.
Note that m... | __init__(self, yaml_path=None):
self.yaml_path = yaml_path
if self.yaml_path:
self.load()
else:
self._conf = dict()
def load( | self, conf=None):
if conf:
if isinstance(conf, dict):
self._conf = conf
else:
self._conf = yaml.safe_load(conf)
return
if os.path.exists(self.yaml_path):
with open(self.yaml_path) as f:
self._conf = yaml.safe... |
rveciana/BasemapTutorial | code_examples/backgrounds/shadedrelief.py | Python | cc0-1.0 | 273 | 0.032967 | from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
map = Basemap(llcrnrlon=-10.5,llcrnrlat=33,urcrnrlon=10.,urcrnrlat=46.,
resolution='i', | projection='cass', lat_0 = 39.5, lon_0 = 0.)
map.shadedrelief()
map.drawcoastlines()
plt.show() | |
fallen/Pytition | pytition/petition/tests/tests_DelSlugView.py | Python | bsd-3-clause | 1,208 | 0.004139 | from django.test import TestCase
from | django.urls import reverse
from .utils import add_default_data
from petition.models import PytitionUser, Permission, Organization, Petition
class DelSlugViewTest(TestCase):
"""Test del_slug view"""
@classmethod
def setUpTestData(cls):
add_default_data()
def login(self, name, password=None... | ionUser.objects.get(user__username=name)
return self.pu
def logout(self):
self.client.logout()
def test_DelSlugViewOk(self):
john = self.login("john")
john_perms = Permission.objects.get(organization__slugname="attac", user=john)
john_perms.can_modify_petitions = True
... |
giserh/grab | test/grab_limit_option.py | Python | mit | 719 | 0 | # coding: utf-8
from test.util import build_grab
from test.util import BaseGrabTestCase
class TestContentLimit(BaseGrabTestCase):
def setUp(self):
self.server.reset()
def test_nobody(self):
g = build_grab()
g.setup(nobody=True)
self.server.response['get.data'] = 'foo'
... | )
self.assertTrue(len(g.response.head) > 0)
def test_body_maxsize(self):
g = build_grab()
g.setup(body_maxsize=100)
self.server.response['get.data'] = 'x' * 1024 * 1024
g.go(self.server.get_url())
# Should be less 50kb
self.assertTrue(len(g.response.body) < 5... | 00)
|
dennerlager/sepibrews | sepibrews/python_utils/converters.py | Python | gpl-3.0 | 6,552 | 0.004731 | from __future__ import (absolute_import, division, print_function,
unicode_literals)
import re
import six
import math
def to_int(input_, default=0, exception=(ValueError, TypeError), regexp=None):
'''
Convert the given input to an integer or return default
When trying to convert ... | ding
:rtype: str
>>> to_str('a')
b'a'
>>> to_str(u'a')
b'a'
>>> to_str(b'a')
b'a'
>>> class Foo(object): __str__ = lambda s: u'a'
>>> to_str(Foo())
'a'
>>> to_str(Foo)
"<class 'python_utils.converters.Foo'>"
'''
if isinstance(input_, six.binary_type):
pa... | turn input_
def scale_1024(x, n_prefixes):
'''Scale a number down to a suitable size, based on powers of 1024.
Returns the scaled number and the power of 1024 used.
Use to format numbers of bytes to KiB, MiB, etc.
>>> scale_1024(310, 3)
(310.0, 0)
>>> scale_1024(2048, 3)
(2.0, 1)
>>... |
zzyyfff/doorbot | doorbot.py | Python | mit | 918 | 0.003268 | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 25 19:54:02 2017
@author: jonathan
"""
import os
from flask import Flask, | request, Response
from slackclient import SlackClient
from twilio.twiml.messaging_response import MessagingResponse
from twilio.rest import Client
TWILIO_NUMBER = os.environ.get('TWILIO_NUMBER', None)
app = Flask(__name__)
slack_client = SlackClient(os.environ.get('SLACK_TOKEN', None))
twilio_client = Client()
@app... | at.postMessage", channel="#thedoor",
text=message, username='doorbot',
icon_emoji=':robot_face:')
# message="Recieved!"
# response.message(message)
return str(response)
if __name__ == '__main__':
app.run(port=(os.environ.get('PORT', None)), debug=True)... |
cfreundl/o3d3xx-python | o3d3xx/__init__.py | Python | mit | 40 | 0.025 | from .rpc import *
from .p | cic | import *
|
tjyang/vitess | py/vttest/run_local_database.py | Python | bsd-3-clause | 3,537 | 0.007351 | #!/usr/bin/env python
"""Command-line tool for starting a local Vitess database for testing.
USAGE:
$ run_local_database --port 12345 \
--topology test_keyspace/-80:test_keyspace_0,test_keyspace/80-:test_keyspace_1 \
--schema_dir /path/to/schema/dir
It will run the tool, logging to stderr. On stdout, a sm... | ase_port = port
with local_database.LocalDatabase(shards, schema_dir, vschema, mysql_only) as local_db:
print json.dumps(local_db.config())
sys.stdout.flush()
try:
raw_input()
except EOFError:
sys.stderr.write(
'WARNING: %s: No empty line was received on stdin.'
' Inste... | mpty line instead to proactively shutdown'
' the local cluster. For example, did you forget the shutdown in'
' your test\'s tearDown()?\n' % os.path.basename(__file__))
if __name__ == '__main__':
parser = optparse.OptionParser()
parser.add_option(
'-p', '--port', type='int',
help='... |
facebookexperimental/eden | eden/hg-server/edenscm/mercurial/match.py | Python | gpl-2.0 | 53,143 | 0.000753 | # Portions 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.
# match.py - filename matching
#
# Copyright 2008, 2009 Matt Mackall <mpm@selenic.com> and others
#
# This software may be used and distribute... | , source in kindpats:
# TODO: update me?
if pat != "" or kind not in ["relpath", "glob"]:
return False
return True
def match(
root,
cwd,
patterns=None,
include=None,
exclude=Non | e,
default="glob",
exact=False,
auditor=None,
ctx=None,
warn=None,
badfn=None,
icasefs=False,
):
"""build an object to match a set of file patterns
arguments:
root - the canonical root of the tree you're matching against
cwd - the current working directory, if relevant
p... |
chrisxue815/leetcode_python | problems/test_1348.py | Python | unlicense | 1,378 | 0.000726 | import unittest
from typing import List
import sortedcontainers
import utils
class TweetCounts:
def __init__(self):
self.tweets = {}
def recordTweet(self, tweetName: str, time: int) -> None:
if tweetName in self.tweets:
times = self.tweets[tweetName]
else:
s... | int) -> List[int]:
if tweetName not in self.tweets:
return []
if freq == 'minute':
step = 60
elif freq == 'hour':
step = 3600
else:
step = 86400
times = self.tweets[tweetName]
index = times.bisect_left(startTime)
e... | count = 0
while index < len(times):
time = times[index]
if time >= end:
break
count += 1
index += 1
result.append(count)
return result
class Test(unittest.TestCase):
def test(self):
... |
axbaretto/beam | sdks/python/.tox/docs/lib/python2.7/site-packages/sphinx/pycode/nodes.py | Python | apache-2.0 | 6,392 | 0 | # -*- coding: utf-8 -*-
"""
sphinx.pycode.nodes
~~~~~~~~~~~~~~~~~~~
Parse tree node implementations.
:copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
class BaseNode(object):
"""
Node superclass for both terminal and nonterminal ... | f get_next_leaf(self):
"""Return self if leaf, otherwise the leaf node that succeeds this
node in the parse tree.
"""
node = sel | f
while not isinstance(node, Leaf):
assert node.children
node = node.children[0]
return node
def get_lineno(self):
"""Return the line number which generated the invocant node."""
return self.get_next_leaf().lineno
def get_prefix(self):
"""Return ... |
blueyed/coveragepy | tests/test_summary.py | Python | apache-2.0 | 33,253 | 0.000872 | # coding: utf-8
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt
"""Test text-based summary reporting for coverage.py"""
import glob
import os
import os.path
import py_compile
import re
import coverage
from cove... | port)
self.assertEqual(self.last_line_squeezed(report), "mybranch.py 5 0 2 1 86%")
def test_report_show_missing(self):
self.make_file("mymissing.py", """\
def missing(x, y):
if x:
print("x")
return x
if y:
... | except ZeroDivisionError:
pass
return x
missing(0, 1)
""")
out = self.run_command("coverage run mymissing.py")
self.assertEqual(out, 'y\nz\n')
report = self.report_from_command("coverage report --show-missing")
# Name ... |
acil-bwh/SlicerCIP | Scripted/attic/PicasaSnap/gdata/oauth/__init__.py | Python | bsd-3-clause | 19,714 | 0.003348 | import cgi
import urllib.request, urllib.parse, urllib.error
import time
import random
import urllib.parse
import hmac
import binascii
VERSION = '1.0' # Hi Blaine!
HTTP_METHOD = 'GET'
SIGNATURE_METHOD = 'PLAINTEXT'
# Generic exception class
class OAuthError(RuntimeError):
def __init__(self, message=... | parse OAuth parameters from Authorization header.')
# GET or POST query string
if query_string:
query_params = O | AuthRequest._split_url_string(query_string)
parameters.update(query_params)
# URL parameters
param_str = urllib.parse.urlparse(http_url)[4] # query
url_params = OAuthRequest._split_url_string(param_str)
parameters.update(url_params)
if parameters:
... |
herilalaina/scikit-learn | sklearn/metrics/tests/test_common.py | Python | bsd-3-clause | 43,823 | 0.000046 | from __future__ import division, print_function
from functools import partial
from itertools import product
import numpy as np
import scipy.sparse as sp
from sklearn.datasets import make_multilabel_classification
from sklearn.preprocessing import LabelBinarizer
from sklearn.utils.multiclass import type_of_target
fro... | oc_auc_score, average="samples"),
"micro_roc_auc": partial(roc_auc_score, average="micro"),
"macro_roc_auc": partial(roc_auc_score, average="macro"),
"average_precision_score": average_precision_score,
"weighted_average_precision_score":
partial(average_precision_score, average="weighted"),
"sa... | ge="samples"),
"micro_average_precision_score":
partial(average_precision_score, average="micro"),
"macro_average_precision_score":
partial(average_precision_score, average="macro"),
"label_ranking_average_precision_score":
label_ranking_average_precision_score,
}
ALL_METRICS = dict()
ALL_METRI... |
harishanand95/cockpit | test/avocado/seleniumlib.py | Python | lgpl-2.1 | 12,177 | 0.007062 | #!/usr/bin/python2
""" SETUP tasks
# workaround for RHEL7
# curl https://copr.fedoraproject.org/coprs/lmr/Autotest/repo/epel-7/lmr-Autotest-epel-7.repo > /etc/yum.repos.d/lmr-Autotest-epel-7.repo
# yum --nogpgcheck -y install python-pip
# pip install selenium
yum --nogpgcheck -y install avocado python-selenium
adduse... | sible = EC.visibility_of_element_located
clickable = EC.element_to_be_clickable
invisible = EC.invisibility_of_element_located
| frame = EC.frame_to_be_available_and_switch_to_it
class SeleniumTest(Test):
"""
:avocado: disable
"""
def setUp(self):
if not (os.environ.has_key("HUB") or os.environ.has_key("BROWSER")):
@Retry(attempts = 3, timeout = 30, error = Exception('Timeout: Unable to attach firefox driver'... |
CTSRD-CHERI/u-boot | tools/patman/test_checkpatch.py | Python | gpl-2.0 | 12,954 | 0.001933 | # -*- coding: utf-8 -*-
# SPDX-License-Identifier: GPL-2.0+
#
# Tests for U-Boot-specific checkpatch.pl features
#
# Copyright (c) 2011 The Chromium OS Authors.
#
import os
import tempfile
import unittest
from patman import checkpatch
from patman import gitutil
from patman import patchstream
from patman import series... | f3748d..f9e4e65 100644
--- a/README
+++ b/README
@@ -2026,6 +2026,17 @@ The following options need to be configured:
example, some LED's) on your board. At the moment,
the following checkpoints are implemented:
+- Time boot progress
+ CONFIG_BOOTSTAGE
+
+ Define this option to enable microsecond boot stage tim... | or this to work your platform
+ needs to define a function timer_get_us() which returns the
+ number of microseconds since reset. This would normally
+ be done in your SOC or board timer.c file.
+
+ You can add calls to bootstage_mark() to set time markers.
+
- Standalone program support:
CONFIG_STANDALONE_LOAD... |
whitehorse-io/encarnia | pyenv/lib/python2.7/site-packages/twisted/names/test/test_dns.py | Python | mit | 154,060 | 0.003778 | # test-case-name: twisted.names.test.test_dns
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for twisted.names.dns.
"""
from __future__ import division, absolute_import
from io import BytesIO
import struct
from zope.interface.verify import verifyClass
from twisted.python.failure... | )
m | sg = dns.Message()
msg.fromStr(wire)
self.assertEqual(msg.queries, [
dns.Query(b'foo.bar', type=0xdead, cls=0xbeef),
])
self.assertEqual(msg.answers, [
dns.RRHeader(b'foo.bar', type=0xdead, cls=0xbeef, ttl=257,
payload... |
turon/openthread | tools/harness-automation/cases/router_5_5_4.py | Python | bsd-3-clause | 1,877 | 0 | #!/usr/bin/env python
#
# Copyright (c) 2016, The OpenThread Authors.
# Al | l 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 conditions and the following disclaimer.
# 2. Redistributi... | ed with the distribution.
# 3. Neither the name of the copyright holder nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY E... |
SmingHub/Sming | Sming/Components/Storage/Tools/hwconfig/common.py | Python | lgpl-3.0 | 3,086 | 0.00324 | #
# Common functions and definitions
#
import os, sys, json, platform
from collections import OrderedDict
sys.path.insert(1, os.path.expandvars('${SMING_HOME}/../Tools/Python'))
from rjsmin import jsmin
quiet = False
def status(msg):
"""Print status message to stderr."""
if not quiet:
critical(msg)
... | on(obj):
return json.dumps(obj, indent=4)
def lookup_keyword(t, keywords):
for k, v in keywords.items():
if t == v:
return k
return "%d" % t
class InputError(RuntimeError):
def __init__(self, e):
super(InputError, self).__init__(e)
class ValidationError(InputError):
... | r(ValidationError, self).__init__("%s.%s '%s' invalid: %s" % (type(obj).__module__, type(obj).__name__, obj.name, message))
self.obj = obj
|
ASaiM/tools-iuc | tools/meme/fimo_wrapper.py | Python | mit | 6,150 | 0.003902 | #!/usr/bin/env python
import argparse
import os
import shutil
import string
import subprocess
import sys
import tempfile
BUFFSIZE = 1048576
# Translation table for reverse Complement, with ambiguity codes.
DNA_COMPLEMENT = string.maketrans("ACGTRYKMBDHVacgtrykmbdhv", "TGCAYRMKVHDBtgcayrmkvhdb")
def reverse(sequence)... | ing position specific priors')
parser.add_argument('--bgfile', dest='bgfile', default=None, help='Background file type, used only if not "default"')
parser.add_argument('--max_strand', action='store_true', help='If matches on both strands at a given position satisfy the output threshold, only report the match for the s... | add_argument('--motif', dest='motifs', action='append', default=[], help='Specify motif by id')
parser.add_argument('--motif_pseudo', dest='motif_pseudo', type=float, default=0.1, help='Pseudocount to add to counts in motif matrix')
parser.add_argument('--no_qvalue', action='store_true', help='Do not compute a q-value ... |
wakalixes/sqldataplot | plugins/pluginFitSigmoidal.py | Python | gpl-2.0 | 1,665 | 0.037838 | #--------------------------------------------------
# Revision = $Rev: 20 $
# Date = $Date: 2011-08-05 20:42:24 +0200 (Fri, 05 Aug 2011) $
# Author = $Author: stefan $
#--------------------------------------------------
from pluginInterfaces import PluginFit, Parameter,leastsqFit
import numpy as np
class PluginFit... | nitialParameters(self,data):
"""find the best initial values and return them"""
dx = np.abs(data[0,0] - data[0,-1])
mi = np.amin(data[1,:])
ma = np.amax(data[1,:])
xc = (np.amax(data[0,:])-np.amin(data[0,:]))/2+np.amin(data[0,:])
return [ma-mi,xc,dx*2,mi]
def getParameters... | elf):
"""return a string of the implemented fitting model, i.e. 'linear fit (y=A*x +B)'"""
return "Sigmoidal"
def getResultStr(self):
"""return a special result, i.e. 'Frequency = blabla'"""
return "nothing fitted"
|
damnfine/mezzanine | mezzanine/pages/managers.py | Python | bsd-2-clause | 3,992 | 0 | from __future__ import unicode_literals
from future.builtins import range
from mezzanine.conf import settings
from mezzanine.core.managers import DisplayableManager
from mezzanine.utils.urls import home_slug
class PageManager(DisplayableManager):
def published(self, for_user=None, include_login_required=False):... | /team', 'about/team/mike']
parts = slug.split("/")
slugs = ["/".join(parts[:i]) for i in range(1, len(parts) + 1)]
# Find the deepest page that matches one of our slugs.
# Sorting by "-slug" should ensure th | at the pages are in
# descendant -> ascendant order.
pages_for_user = self.published(**kwargs)
pages = list(pages_for_user.filter(slug__in=slugs).order_by("-slug"))
if not pages:
return []
# Check to see if the other pages retrieved form a valid path
# in the... |
QuLogic/iris | lib/iris/tests/unit/analysis/cartography/test_rotate_winds.py | Python | gpl-3.0 | 20,624 | 0 | # (C) British Crown Copyright 2015 - 2016, Met Office
#
# This file is part of Iris.
#
# Iris is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any l... | grid(x, y)
lat_2d = AuxCoord(y2d, 'grid_latitude', units='degrees',
coord_system=u.coord('grid_latitude').coord_system)
for cube in (u, v):
| cube.remove_coord('grid_latitude')
cube.add_aux_coord(lat_2d.copy(), (0, 1))
with self.assertRaisesRegexp(
ValueError,
'x and y coordinates must have the same number of dimensions'):
rotate_winds(u, v, iris.coord_systems.OSGB())
def test_... |
wsy1607/Data-Analysis-of-Campus-Crime-Index | website/plugins/extract_toc/extract_toc.py | Python | mit | 984 | 0.001016 | """
Extract Table of Content
=============== | =========
This plugin allows you to extract table of contents (ToC) from article.content
and place it in its own article.toc variable.
"""
from os import path
from bs4 import BeautifulSoup
from pelican import signals, readers, contents
def extract_toc(content):
if isinstance(content, contents.Static):
| return
soup = BeautifulSoup(content._content,'html.parser')
filename = content.source_path
extension = path.splitext(filename)[1][1:]
toc = ''
# if it is a Markdown file
if extension in readers.MarkdownReader.file_extensions:
toc = soup.find('div', class_='toc')
# else if it is a... |
UManPychron/pychron | pychron/furnace/firmware/server.py | Python | apache-2.0 | 5,682 | 0.001936 | # ===============================================================================
# Copyright 2016 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/licenses... | ('RotaryDumperMoving', manager.rotary_dumper_moving),
('DenergizeMagnets', manager.denergize_magnets),
('MoveAbsolute', manager.move_absolute),
('MoveRelative', manager.move_relative),
('GetPosition... | sition),
('Slew', manager.slew),
('Stalled', manager.stalled),
('SetHome', manager.set_home),
('StopDrive', manager.stop_drive),
('Moving', manager.moving),
('StartJitter... |
matt-gardner/deep_qa | deep_qa/models/multiple_choice_qa/question_answer_similarity.py | Python | apache-2.0 | 5,186 | 0.004435 | from typing import Dict
from overrides import overrides
from keras import backend a | s K
from keras.layers import Dense, Dropout, Input
from ...data.instances.multiple_choice_qa import QuestionAnswerInstance
from ...layers.wrappers import EncoderWrapper
from ...layers.attention import Attention
from ...training import TextTrainer
from ...common.params import Params
from ...train | ing.models import DeepQaModel
class QuestionAnswerSimilarity(TextTrainer):
"""
A TextTrainer that takes a question and several answer options as input, encodes the word
sequences using a sentence encoder, optionally passes the question encoding through some dense
layers, then selects the option that i... |
aaronbassett/DisposableEmailChecker | build_list.py | Python | bsd-3-clause | 141 | 0.007092 |
emails = sorted(set([line.strip() for line in open("email_do | mains.txt")]))
for email in emails:
print("'{email}',".format(emai | l=email)) |
baixuexue123/note | python/concurrency/gevent/test_pool.py | Python | bsd-2-clause | 999 | 0.002275 | # -*- coding: utf-8 -*-
"""
Greenlet具有确定性. 在相同配置相同输入的情况下, 它们总是会产生相同的输出.
下面就有例子, 我们在multiprocessing的pool之间执行一系列的任务, 与在gevent的pool之间执行作比较.
"""
import time
from multiprocessing.pool import Pool
def echo(i):
time.sleep(0.001)
return i
# Non Deterministic Process Pool
p = Pool(10)
run1 = [a for a in p.imap_uno... | )]
run4 = [a for a in p.imap_unordered(echo, xrange(1 | 0))]
print(run1 == run2 == run3 == run4)
# Deterministic Gevent Pool
from gevent.pool import Pool
p = Pool(10)
run1 = [a for a in p.imap_unordered(echo, xrange(10))]
run2 = [a for a in p.imap_unordered(echo, xrange(10))]
run3 = [a for a in p.imap_unordered(echo, xrange(10))]
run4 = [a for a in p.imap_unordered(ech... |
intel-hpdd/intel-manager-for-lustre | chroma_core/migrations/0025_createsnapshotjob_destroysnapshotjob.py | Python | mit | 2,819 | 0.003193 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.23 on 2020-09-10 14:23
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
("chroma_core", "0024_mountsnapshotjob_unmountsnapshotjob"),... |
),
(
"use_barrier",
models.BooleanField(
default=False,
help_text=b"Set write barrier before creating snapshot. The default value is False",
),
),
],
... | e.job",),
),
migrations.CreateModel(
name="DestroySnapshotJob",
fields=[
(
"job_ptr",
models.OneToOneField(
auto_created=True,
on_delete=django.db.models.deletion.CASCADE,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.