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 |
|---|---|---|---|---|---|---|---|---|
pseudonym117/Riot-Watcher | src/riotwatcher/_apis/team_fight_tactics/urls/TftEndpoint.py | Python | mit | 307 | 0 | from ... import Endpoint, UrlConfig
class TftEndpoint:
def __init__(self, url: str, **kwargs):
self._url = f"/tft{url}"
def __call__(se | lf, **kwargs):
final_url = f"{UrlConfig.tft_url}{self._url}"
endpoint = Endpoint(final_url, **kwargs)
return endpoint(** | kwargs)
|
factorlibre/l10n-spain | l10n_es_ticketbai_api_batuz/models/lroe_operation_response.py | Python | agpl-3.0 | 16,313 | 0.001533 | # Copyright (2021) Binovo IT Human Project SL
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
import base64
from enum import | Enum
from odoo import models, fields, api, _
from ..l | roe.lroe_xml_schema import LROEXMLSchema,\
LROEXMLSchemaModeNotSupported,\
LROEOperationTypeEnum
from .lroe_operation import LROEOperationEnum, LROEModelEnum
from odoo.addons.l10n_es_ticketbai_api.models.ticketbai_response\
import TicketBaiResponseState, TicketBaiInvoiceResponseCode, \
TicketBaiCancella... |
ferrants/qball-python | setup.py | Python | mit | 547 | 0.003656 | """
(c) Copyright 2014. All Rights Reserved.
qball module setup and package.
"""
from setuptools import setup
setup(
name='qball',
author='Matt Ferrante',
author_email='mferrante3@gmail.com',
description=' | Python integration for qball',
license='(c) Copyright 2014. All Rights Reserved.',
packages=['qball'],
install_requires=['httpli | b2 >= 0.8'],
setup_requires=['httplib2'],
version='1.1.0',
url="https://github.com/ferrants/qball-python",
keywords = ['locking', 'resource locking', 'webservice'],
)
|
allancarlos123/Solfege | solfege/fpeditor.py | Python | gpl-3.0 | 34,015 | 0.003381 | # vim: set fileencoding=utf-8 :
# GNU Solfege - free ear training software
# Copyright (C) 2009, 2011 Tom Cato Amundsen
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the... | ics.DB()
import solfege
from solfege import cfg
from solfege import filesystem
from solfege import gu
from solfege import frontpage as pd
from solfege import lessonfile
from solfege import osutils
class LessonFilePreviewWidget(gtk.VBox):
def __init__(self, model):
gtk.VBox.__in | it__(self)
self.m_model = model
self.set_size_request(200, 200)
l = gtk.Label()
l.set_alignment(0.0, 0.5)
l.set_markup("<b>Title:</b>")
self.pack_start(l, False)
self.g_title = gtk.Label()
self.g_title.set_alignment(0.0, 0.5)
self.pack_start(self.g... |
johnyf/gr1experiments | examples/jcss12/amba_generator.py | Python | bsd-3-clause | 15,381 | 0.00013 | #!/usr/bin/env python
"""Generate AMBA AHB specifications for given number of masters.
Translated and adapted from Perl original distributed with Anzu.
https://www.iaik.tugraz.at/content/research/opensource/anzu/#download
"""
import argparse
import math
from omega.logic.syntax import conj
def build_state_str(sta... | i}'.format(i=i)
output_vars.append(var)
# busreq = hbusreq[hmaster]
sys_initial += (
"busreq=0 & \n"
# Assumption 1:
"stateA1_0 = 0 & \n"
"stateA1_1 = 0 & \n"
# Guarantee 2:
"stateG2 = 0 & \n"
# Guarantee 3:
| "stateG3_0 = 0 & \n"
"stateG3_1 = 0 & \n"
"stateG3_2 = 0 & \n")
# Guarantee 10:
for i in xrange(1, num_masters):
sys_initial += "stateG10_{i} = 0 & \n".format(i=i)
var = 'stateG10_{i}'.format(i=i)
output_vars.append(var)
#######################################... |
cmac4603/Home-Utilities-App | wx_str_test.py | Python | gpl-2.0 | 253 | 0.003953 | import pyowm
owm = pyowm.OWM('fa7813518ed203b759f116a3bac9bcce')
observation = owm.weather_at_place('London,uk')
w = observation.get_weather()
wtemp = str(w.get_tempera | ture('celsius'))
print(wtemp. | strip('{}'))
wtemp_list = list(wtemp)
print(wtemp_list) |
mahabs/nitro | nssrc/com/citrix/netscaler/nitro/resource/config/network/bridgegroup_nsip6_binding.py | Python | apache-2.0 | 7,494 | 0.037764 | #
# Copyright (c) 2008-2015 Citrix Systems, 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 l... | resource) is not list :
updateresource = bridgegroup_nsip6_binding()
updateresource.ipaddress = resource.ipaddress
updateresource.netmask = resource.netmask
return updateresour | ce.update_resource(client)
else :
if resource and len(resource) > 0 :
updateresources = [bridgegroup_nsip6_binding() for _ in range(len(resource))]
for i in range(len(resource)) :
updateresources[i].ipaddress = resource[i].ipaddress
updateresources[i].netmask = resource[i].netmask
retur... |
kohnle-lernmodule/KITexe201based | exe/engine/config.py | Python | gpl-2.0 | 25,533 | 0.005953 | # ===========================================================================
# eXe config
# Copyright 2004-2006, University of Auckland
#
# 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; e... | /iteexe.git'
# Class attributes
optionNames = {
'system': ('webDir', 'jsDir', 'port', 'dataDir',
'configDir', 'localeDir', 'browser', 'mediaProfilePath',
| 'videoMediaConverter_ogv', 'videoMediaConverter_3gp',
'videoMediaConverter_mpg',
'videoMediaConverter_avi', 'audioMediaConverter_ogg',
'audioMediaConverter_au', 'audioMediaConverter_mp3',
'audioMediaConverter_wav', 'ffmpegPath'),
... |
kdheepak89/pypdevs | test/test_realtime.py | Python | apache-2.0 | 1,022 | 0.001957 | # Copyright 2014 Modelling, Simulation and Design Lab (MSDL) at
# McGill University and the University of Antwerp (http://msdl.cs.mcgill.ca/)
#
# Licensed under the Apache License, Vers | ion 2.0 (the "License");
# you may not use this file except in complian | ce 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 express or i... |
hoaaoh/Audio2Vec | src/trans_len.py | Python | apache-2.0 | 1,528 | 0.013089 | #!/usr/bin/env python3
import csv
import argparse
FLAG = None
def write_file(feats,lab_list, fn):
with open(fn,'w') as f:
for num, i in enumerate(feats):
for j in range(len(i)):
f.write(str(i[j]) + ',')
f.write(str([len(i)-1]) + '\n')
return
def transform(... | frame feat dimension')
parser.add_argument('ark_file',
help='the transforming ark file')
parser.add_argument('len_file',
help='meaning the length of each utterance')
parser.add_argument('out_ark',
help='the output file')
FLAG | = parser.parse_args()
main()
|
shaileshgoogler/pyglet | tools/ddsview.py | Python | bsd-3-clause | 4,680 | 0.002564 | #!/usr/bin/env python
'''Simple viewer for DDS texture files.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
from ctypes import *
import getopt
import sys
import textwrap
from SDL import *
from pyglet.gl.VERSION_1_1 import *
import p | yglet.dds
import pyglet.event
import pyglet.image
import pyglet.sprite
import pyglet.window
from OpenGL.GLU import *
def usage():
print textwrap.dedent('''
Usage: ddsview.py [--header] texture1.dds texture2.dds ...
--header Dump | the header of each file instead of displaying.
Within the program, press:
left/right keys Flip between loaded textures
up/down keys Increase/decrease mipmap level for a texture
space Toggle flat or sphere view
Click and drag with mouse to ... |
lrq3000/pyFileFixity | pyFileFixity/lib/gooey/python_bindings/argparse_to_json.py | Python | mit | 5,242 | 0.013163 | """
Converts argparse parser actions into json "Build Specs"
"""
import argparse
from argparse import (
_CountAction,
_HelpAction,
_StoreConstAction,
_StoreFalseAction,
_StoreTrueAction,
ArgumentParser, _SubParsersAction)
from collections import OrderedDict
from functools import partial
VALID_WIDGETS = (... | e 'counter' dropdown
_json['data']['choices'] = map(str, range(1, 11))
yield _json
else:
raise UnknownWidgetType(action)
def get_widget(action, widgets):
supplied_widget = widgets.get(action.dest, None)
type_arg_widget = 'FileChooser' if action.type == argparse.FileType else None
return sup... | isinstance(action, _SubParsersAction) or action.required == True
def has_required(actions):
return filter(None, filter(is_required, actions))
def is_subparser(action):
return isinstance(action,_SubParsersAction)
def has_subparsers(actions):
return filter(is_subparser, actions)
def get_subparser(actions):
... |
google/jax | jax/interpreters/ad.py | Python | apache-2.0 | 32,505 | 0.012121 | # Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | , primals, has_aux=False, reduce_axes=()):
if n | ot has_aux:
out_primals, pvals, jaxpr, consts = linearize(traceable, *primals)
else:
out_primals, pvals, jaxpr, consts, aux = linearize(traceable, *primals, has_aux=True)
def unbound_vjp(pvals, jaxpr, consts, *cts):
cts = tuple(map(ignore_consts, cts, pvals))
dummy_args = [UndefinedPrimal(v.aval) f... |
zcbenz/cefode-chromium | third_party/mesa/MesaLib/src/gallium/drivers/llvmpipe/lp_tile_shuffle_mask.py | Python | bsd-3-clause | 716 | 0.111732 |
tile = [[0,1,4,5],
[2,3,6,7],
[8,9,12,13],
[10,11,14,15]]
shift = 0
align = 1
value = 0L
holder = []
import sys
basemask = [0x
fd = sys.stdout
indent = " "*9
for c in range(4):
fd.write(indent + "*pdst++ = \n");
for l,line in enumerate(tile):
fd.write(indent + " %s_mm_shuffle_epi8(line%d, (__m128i){"... | %2 == 0:
fd.write("0x%8.0x"%(holder[0] + (holder[1] << 32)))
holder = []
if (i) %4 == 1:
fd.write( ',')
fd.write("})%s\n"%((l == 3) an | d ';' or ''))
print
shift += 8
|
aangert/PiParty | common.py | Python | mit | 5,854 | 0.01247 | import asyncio
import colorsys
import enum
import functools
import psmove
import time
import traceback
import random
SETTINGSFILE = 'joustsettings.yaml'
#Human speeds[slow, mid, fast]
#SLOW_WARNING = [0.1, 0.15, 0.28]
#SLOW_MAX = [0.25, 0.8, 1]
#FAST_WARNING = [0.5, 0.6, 0.8]
#FAST_MAX = [1, 1.4, 1.8]
SLOW_WARNING =... | ve.get_serial() != serial:
for move_num in range(psmove.count_connected()):
move = psmove.PS | Move(move_num)
if move.get_serial() == serial:
print("returning " +str(move.get_serial()))
return move
return None
else:
return move
def lerp(a, b, p):
return a*(1 - p) + b*p
class Games(enum.Enum):
JoustFFA = (0, 'Joust Free-for-All', 2)
Jou... |
ressu/SickGear | sickbeard/search.py | Python | gpl-3.0 | 30,487 | 0.004395 | # Author: Nic Wolfe <nic@wolfeden.ca>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of SickGear.
#
# SickGear 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,... | .join, sickbeard.NZB_DIR, result.name + ".nzb")
logger.log(u"Saving NZB to " + fileName)
newResult = True
# save the data to disk
try:
with ek.ek(open, fileName, 'w') as fileOut:
fileOut.write(result.extraInfo[0])
helpers.chmodAsParent(fileName... | ogger.ERROR)
newResult = False
elif resProvider.providerType == "torrent":
newResult = resProvider.downloadResult(result)
else:
logger.log(u"Invalid provider type - this is a coding error, report it please", logger.ERROR)
newResult = False
return newResult
def snatchEpi... |
rogerscristo/BotFWD | env/lib/python3.6/site-packages/telegram/ext/typehandler.py | Python | mit | 4,005 | 0.003745 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as publish... | ed 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 Public License for more details.
#
# You should have received a copy of the GNU Lesse | r Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the TypeHandler class."""
from .handler import Handler
class TypeHandler(Handler):
"""Handler class to handle updates of custom types.
Attributes:
type (:obj:`type`): The ``typ... |
noah/riddim | lib/data.py | Python | mit | 674 | 0.014837 | # -*- coding: utf-8 -*-
import sys
import time
from config import Config
from multiprocessing import managers, connection
def _new_init_timeout():
return time.time() + 0.2
sys.modules['multiprocessing'].__dict__['managers'].__dict__['connection']._init_timeout = _new_init_timeout
from multiprocessing.manage... | ed Data object
DataManager.register('get_data')
manager = DataManager(address=(Config.hostname, port + 1),
authkey=Config.authkey)
manager.connect()
data = manager.get_d | ata()
data[k] = v
|
Otterpaw/Python-Roguelike | floor_object.py | Python | mit | 920 | 0.029348 | class Floor_Object(object):
"""docstring for Floor_Object"""
def __init__(self, coordinates, icon, name, interactions, description):
super(Floor_Object, self).__init__()
self.coordinates = coordinates
self.icon = icon
self.name = name
self.interactions = interactions
self.description = description
class ... | bject):
"""A container holding items"""
def __init__(self, coordinates, icon, name, interactions, description, item_list, is_locked, key_name):
super(Chest, self).__init__(coordinates, icon, name, interactions, description)
self.item_list = item_list
self.is_locked = is_locked
self.key_name = | key_name
class Item_Pile(Floor_Object):
"""A list of items present on a tile"""
def __init__(self, coordinates, icon, name, interactions, description, item_list):
super(Item_Pile, self).__init__(coordinates, icon, name, interactions, description)
self.item_list = item_list
|
hethune/tutorials | pymongo/openweathermap.py | Python | mit | 1,579 | 0.008233 | import json
import urllib2
import time
import math
from pymongo import MongoClient
from pymongo import ASCENDING, DESCENDING
def debug(info):
print info
def log(info):
print info
def parseJson(url):
try:
data = json.load(urllib2.urlopen(url))
return data
except ValueError as e:
... | lection.ensure_index([("name", ASCENDING), ("start", ASCENDING)], unique=True, dropDups=True)
return collection
def validateData(raw):
data = [];
f | or key in raw:
value = raw[key]
if isinstance(value, basestring) and value.lower() == "error":
log("Failed retrieve latency for " + key)
else:
value["name"] = key
data.append(value)
return data
def write(collection, posts):
for post in posts:
... |
frappe/frappe | frappe/tests/test_defaults.py | Python | mit | 2,355 | 0.022505 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: MIT. See LICENSE
import frappe, unittest
from frappe.defaults import *
class TestDefaults(unittest.TestCase):
def test_global(self):
clear_user_default("key1")
set_global_default("key1", "value1")
self.assertEqual(get_global_defaul... | "key1"), ["2value1"])
set_user_default("key1", "2value2")
self.assertEqual(get_user_default("key1"), "2value2")
add_user_d | efault("key1", "3value3")
self.assertEqual(get_user_default("key1"), "2value2")
self.assertEqual(get_user_default_as_list("key1"), ["2value2", "3value3"])
def test_global_if_not_user(self):
set_global_default("key4", "value4")
self.assertEqual(get_user_default("key4"), "value4")
def test_clear(self):
set_... |
tannishk/airmozilla | airmozilla/base/tests/test_helpers.py | Python | bsd-3-clause | 3,664 | 0 | from nose.tools import eq_
from django.test.client import RequestFactory
from airmozilla.base.tests.testbase import DjangoTestCase
from airmozilla.base.helpers import abs_static, show_duration
class TestAbsStaticHelpers(DjangoTestCase):
def tearDown(self):
super(TestAbsStaticHelpers, self).tearDown()
... | atic(context, 'foo.png')
eq_(result, 'http://my.cdn.com/static/fo | o.png')
def test_abs_static_with_already_STATIC_URL(self):
context = {}
context['request'] = RequestFactory().get('/')
with self.settings(STATIC_URL='//my.cdn.com/static/'):
result = abs_static(context, '//my.cdn.com/static/foo.png')
eq_(result, 'http://my.cdn.com/s... |
youtube/cobalt | cobalt/bindings/path_generator.py | Python | bsd-3-clause | 7,751 | 0.004774 | # Copyright 2017 The Cobalt Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | "
in | terface_info = self.info_provider.enumerations[enum_name]
return ConvertPath(
interface_info['full_path'],
forward_slashes=True,
output_directory=self.generated_root,
output_extension='h',
base_directory=os.path.dirname(self.interfaces_root))
def EnumConversionImplementati... |
NUPT-Pig/python_test | tkinter_gui.py | Python | gpl-2.0 | 1,385 | 0.012274 | from Tkinter import *
root = Tk()
root.title('first test window')
#root.geometry('300x200')
frm = Frame(root)
f | rm_l = Frame(frm)
Label(frm_l, text='left_top').pack(side=TOP)
Label(frm_l, text='left_bottom').pack(side=BOTTOM)
frm_l.pack(side=LEFT)
frm_r = Frame(frm)
Label(frm_r, text='right_top').pack(side=TOP)
Label(frm | _r, text='right_bottom').pack(side=BOTTOM)
frm_r.pack(side=RIGHT)
frm.pack(side=TOP)
##########################################################
frm1 = Frame(root)
var = StringVar()
Entry(frm1, textvariable=var).pack(side=TOP)
var.set('entry text')
t = Text(frm1)
t.pack(side=TOP)
def print_entry():
t.insert(END,... |
anusornc/vitess | test/queryservice_tests/stream_tests.py | Python | bsd-3-clause | 6,435 | 0.014452 | import json
import threading
import time
import traceback
import urllib
from vtdb import cursor
from vtdb import dbexceptions
import environment
import framework
class TestStream(framework.TestCase):
def tearDown(self):
self.env.conn.begin()
self.env.execute("delete from vtocc_big")
self.env.conn.commi... | sor(self.env.conn)
cu.execute("select * from vtocc_big b1, vtocc_big b2", {})
count = 0
while True:
row = cu.fetchone()
if row is None:
break
if count == 10:
self.check_row_10(row)
count += 1
self.assertEqual(count, 10000)
... | eError):
cu = self.env.execute("select count(abcd) from vtocc_big b1",
cursorclass=cursor.StreamCursor)
def check_row_10(self, row):
# null the dates so they match
row = list(row)
row[6] = None
row[11] = None
row[20] = None
row[25] = None
self.assertEqual... |
devs1991/test_edx_docmode | venv/lib/python2.7/site-packages/django/db/migrations/questioner.py | Python | agpl-3.0 | 7,694 | 0.002339 | from __future__ import print_function, unicode_literals
import importlib
import os
import sys
from django.apps import apps
from django.db.models.fields import NOT_PROVIDED
from django.utils import datetime_safe, six, timezone
from django.utils.six.moves import input
from .loader import MIGRATIONS_MODULE_NAME
class... | want to merge these migrations?"
return self.defaults.get("ask_merge", False)
class InteractiveMigrationQuestioner(MigrationQuestioner):
def _boolean_input(self, question, default=None):
result = input("% | s " % question)
if not result and default is not None:
return default
while len(result) < 1 or result[0].lower() not in "yn":
result = input("Please answer yes or no: ")
return result[0].lower() == "y"
def _choice_input(self, question, choices):
print(questio... |
antoinecarme/sklearn2sql_heroku | tests/classification/BinaryClass_10/ws_BinaryClass_10_DecisionTreeClassifier_db2_code_gen.py | Python | bsd-3-clause | 149 | 0.013423 | from sklearn2sql_h | eroku.tests.classification import generic as class_gen
class_gen.test_model("DecisionTreeClassifier | " , "BinaryClass_10" , "db2")
|
thumbor/thumbor | tests/filters/test_watermark.py | Python | mit | 10,644 | 0.000188 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/thumbor/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com thumbor@googlegroups.com
from preggy import expect
from tornado.testing import gen_test
from... | sim(image, expected)
expect(ssim).to_be_greater_than(0.98)
@gen_test
async def test_watermark_filter_centered_x(self):
image = await self.get | _filtered(
"source.jpg",
"thumbor.filters.watermark",
"watermark(watermark.png,center,40,20)",
)
expected = self.get_fixture("watermarkCenterX.jpg")
ssim = self.get_ssim(image, expected)
expect(ssim).to_be_greater_than(0.98)
@gen_test
async de... |
Erotemic/ibeis | ibeis/gui/id_review_api.py | Python | apache-2.0 | 32,750 | 0.003908 | # -*- coding: utf-8 -*-
"""
CommandLine:
python -m ibeis.gui.inspect_gui --test-test_review_widget --show
"""
from __future__ import absolute_import, division, print_function, unicode_literals
from functools import partial
from ibeis.viz import viz_helpers as vh
import guitool_ibeis as gt
import numpy as np
import ... | unique_aids = ut.unique(ut.flatten([qaid_arr, daid_arr]))
#grouped_aids, unique_nids = ibs.group_annots_by_name(unique_aids)
invalid_nid_map = get_photobomber_map(ibs, qaid_arr)
nid2_aids = ut.group_ | items(unique_aids, ibs.get_annot_nids(unique_aids))
expanded_aid_map = ut.ddict(set)
for nid1, other_nids in invalid_nid_map.items():
for a |
breuderink/psychic | psychic/plots.py | Python | bsd-3-clause | 1,878 | 0.014377 | import matplotlib.pyplot as plt
import numpy as np
import scalpplot
from scalpplot import plot_scalp
from positions import POS_10 | _5
from scipy import signal
def plot_timeseries(frames, time=None, offset=None, color='k', linestyle='-'):
frames = np.asarray(frames)
if | offset == None:
offset = np.max(np.std(frames, axis=0)) * 3
if time == None:
time = np.arange(frames.shape[0])
plt.plot(time, frames - np.mean(frames, axis=0) +
np.arange(frames.shape[1]) * offset, color=color, ls=linestyle)
def plot_scalpgrid(scalps, sensors, locs=POS_10_5, width=None,
clim=None... |
minesense/VisTrails | vistrails/packages/spreadsheet/init.py | Python | bsd-3-clause | 8,965 | 0.004016 | ###############################################################################
##
## Copyright (C) 2014-2016, New York University.
## Copyright (C) 2011-2014, NYU-Poly.
## Copyright (C) 2006-2011, University of Utah.
## All rights reserved.
## Contact: contact@vistrails.org
##
## This file is part of VisTrails.
##
## ... | distribution and use in source and binary forms, with or without
## modification, are permitted provided that the following conditio | ns are met:
##
## - Redistributions of source code must retain the above copyright notice,
## this list of conditions and the following disclaimer.
## - Redistributions in binary form must reproduce the above copyright
## notice, this list of conditions and the following disclaimer in the
## documentation an... |
KL-WLCR/incubator-airflow | tests/operators/sensors.py | Python | apache-2.0 | 11,787 | 0.000339 | # -*- coding: utf-8 -*-
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
... | keHDFSHook
self.hook = FakeHDFSHook
def test_legacy_file_exist(self):
"""
Test the legacy behaviour
:return:
"""
# Given
logging.info("Test for existing file with the legacy behaviour")
# When
task = HdfsSens | or(task_id='Should_be_file_legacy',
filepath='/datadirectory/datafile',
timeout=1,
retry_delay=timedelta(seconds=1),
poke_interval=1,
hook=self.hook)
task.execute(None)
# Th... |
BladeSmithJohn/nixysa | nixysa/cpp_utils_unittest.py | Python | apache-2.0 | 1,879 | 0.002661 | #!/usr/bin/python2.4
#
# 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 o | f 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 express or implied.
# See the License for the specific l... | ls."""
import unittest
import cpp_utils
template = """test1
${#Test}
test2"""
template_reuse = """test1
${#Test}
test2
${#Test}
test3"""
class CppFileWriterUnitTest(unittest.TestCase):
def setUp(self):
self.writer = cpp_utils.CppFileWriter('a.cc', False)
def tearDown(self):
pass
def testSectionTemp... |
nop33/indico | indico/modules/networks/util.py | Python | gpl-3.0 | 1,020 | 0 | # This file is part of Indico.
# Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN).
#
# Indico 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 (a... | option) any later version.
#
# Indico is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General... | _ip_network_group(group):
"""Serialize group to JSON-like object"""
return {
'id': group.id,
'name': group.name,
'identifier': 'IPNetworkGroup:{}'.format(group.id),
'_type': 'IPNetworkGroup'
}
|
sxjscience/tvm | python/tvm/relay/op/contrib/arm_compute_lib.py | Python | apache-2.0 | 12,300 | 0.000976 | # 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 u... | conv2d(call.attrs, call.args)
def check_qnn_conv(extract):
"""Check qnn conv pattern is supported by ACL."""
if extract.attrs.out_dtype != "uint8":
return False
call = extract
while call.op.name != "qnn.conv2d":
call = call.args[0]
return qnn_conv2d(... | trs, call.args)
def check_dense(extract):
"""Check conv pattern is supported by ACL."""
call = extract
while call.op.name != "nn.dense":
call = call.args[0]
return dense(call.attrs, call.args)
def check_qnn_dense(extract):
"""Check qnn conv pattern is suppor... |
joe-jordan/minimalisp | setup.py | Python | mit | 377 | 0.023873 | #!/usr/bin/env python
from distu | tils.core import setup
setup(name='minimalisp',
version='1.0',
description='An implementation of a small lisp language',
author='Joe Jordan',
author_email='t | ehwalrus@h2j9k.org',
url='https://github.com/joe-jordan/minimalisp',
packages=['minimalisp'],
scripts=['scripts/minimalisp'],
include_package_data=True
)
|
unbracketed/snowbird | snowbird/analyzer.py | Python | mit | 112 | 0.017857 | def | get_related_fields(model):
pass
def get_table_size(model):
pass
def get_row_size(model):
| pass
|
xuender/test | testAdmin/itest/migrations/0006_auto__chg_field_test_content.py | Python | apache-2.0 | 1,755 | 0.006838 | # -*- 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):
# Changing field 'Test.content'
db.alter_column(u'itest_test', 'content'... | : '35'})
},
'itest.test': {
'Meta': {'object_name': 'Test'},
'content': | ('django.db.models.fields.CharField', [], {'max_length': '1850', 'null': 'True', 'blank': 'True'}),
'create_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'num': ('dj... |
jopohl/urh | src/urh/ui/views/ZoomAndDropableGraphicView.py | Python | gpl-3.0 | 2,692 | 0.000743 | from PyQt5.QtCore import pyqtSignal
from PyQt5.QtGui import QDragEnterEvent, QDropEvent
from urh.signalprocessing.IQArray import IQArray
from urh.cythonext import util
from urh.signalprocessing.ProtocolAnalyzer import ProtocolAnalyzer
from urh.signalprocessing.Signal import Signal
from urh.ui.painting.SignalSceneMana... | nalSceneManager(signal, self)
self.plot_data(self.signal.real_plot_data)
self.show_full_scene()
self.auto_fit_view()
self.signal_loaded.emit(self.proto_analyzer)
def auto_fit_view(self):
super().auto_fit_view()
plot_min, plot_max = util | .minmax(self.signal.real_plot_data)
data_min, data_max = IQArray.min_max_for_dtype(self.signal.real_plot_data.dtype)
self.scale(1, (data_max - data_min) / (plot_max-plot_min))
self.centerOn(self.view_rect().x() + self.view_rect().width() / 2, self.y_center)
def eliminate(self):
# D... |
How2Compute/SmartHome | hub/Models.py | Python | mit | 2,593 | 0.008484 | """
Database Models Library
"""
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
# Model to store information about devices
class Device(db.Model):
__tablename__ = 'clients'
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.Text)
api_key = db.Column(db.Text)
active ... |
id = db.Column(db.Integer, primary_key = True)
user_id = db.Column(db.Integer)
category = db.Column(db.Text)
title = db.Column(db.Text)
body = db.Column(db.Text)
callback_url = db.Column(db.Text)
dismissed = db.Column(db.Boolean, default=0)
timestamp = db.Column(db.DateTime)
#... | l):
self.user_id = user_id
self.category = category
self.title = title
self.body = body
self.callback_url = callback_url
# Down here to avoid issues with circular dependancies
from helpers import generate_api_token
class Preference(db.Model):
__tablename__ = 'prefe... |
prculley/gramps | gramps/gui/editors/__init__.py | Python | gpl-2.0 | 4,028 | 0.001986 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2000-2006 Donald N. Allingham
# Copyright (C) 2011 Tim G L Lyons
#
# 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; eith... | if obj:
try:
EDITORS[obj_class](dbstate, uistate, track, obj, callback=callback)
except Exception as msg:
LOG.warning(str(msg))
else:
LOG.warning("gramps://%s/%s/%s not found" %
(obj_class, p... | bject to edit '%s'; "
"should be one of %s" % (obj_class, list(EDITORS.keys())))
|
peragro/peragro-rest | manage.py | Python | bsd-3-clause | 289 | 0 | #!/usr/bin/env python
from __future__ import absolute_import
import os
import sys
if __name__ == "__main__":
os.environ.setdefa | ult("DJANGO_SETTINGS_MODULE", "service.settings")
fr | om django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
brefsdal/sherpa | sherpa/models/tests/test_basic.py | Python | gpl-2.0 | 1,765 | 0.005099 | #_PYTHON_INSERT_SAO_COPYRIGHT_HERE_(2007)_
#_PYTHON_INSERT_GPL_LICENSE_HERE_
from numpy import arange
import sherpa.models.basic as basic
from sherpa.utils import SherpaFloat, SherpaTestCase
from sherpa.models.model import ArithmeticModel
def userfunc(pars, x, *args, **kwargs):
return x
class test_basic(Sherp | aTestCase):
def test_create_and_evaluate(self):
x = arange(1.0, 5.0)
count = 0
for cls in dir(basic):
clsobj = getattr(basic, cls)
if ((not isinstance(clsobj, type)) or
(not issubclass(clsobj, ArithmeticModel)) or
(clsobj is Arithmet... | ferent interfaces than the others
if cls == 'Integrator1D' or cls == 'Integrate1D':
continue
m = clsobj()
if isinstance(m, basic.TableModel):
m.load(x,x)
if isinstance(m, basic.UserModel):
m.calc = userfunc
sel... |
phracek/devassistant | test/fixtures/files/crt/commands/a.py | Python | gpl-2.0 | 609 | 0.001642 | from devassistant.command_runners import CommandRunner
from devassistant.logger import logger
class CR1(CommandRunner):
@classmethod
def matches(cls, c):
return c.comm_type == 'barbarbar'
@classmethod
def run(cls, c):
logger.info('CR1: Doing something ...')
x = c.input_res + 'b... | unner):
@classmethod
def matches(cls, c):
return c.comm_type == 'spamspamspam'
@classmethod
def run(cls, c):
logger.info('C | R2: Doing something ...')
x = c.input_res + 'spam'
return (True, x)
|
hagberg/nx3k | test_edges.py | Python | bsd-3-clause | 4,105 | 0.031425 | #
# TESTS
#
from nose.tools import assert_true, assert_equal, assert_raises
from mixedges import Edges, EdgeKeys, EdgeData, EdgeItems
class BaseEdgeTests(object):
def setup_edges(self):
self.edlist = [{1:"one"}, {1:"two"}, {1:"three"}, {1:"four"}]
ed1, ed2, ed3, ed4 = self.edlist
Ge = se... | if Ge.directed:
ans = [(0,1), (0,0), (1,0), (2,3)]
else:
ans = [(0,1), (0,0), (2,3)]
assert_equal( sorted(Ge), sorted(ans))
if Ge.directed:
ans = [((0,1),ed1), ((0,0),ed2), ((1,0),ed3), ((2,3),ed4)]
else:
| ans = [((0,1),ed3), ((0,0),ed2), ((2,3),ed4)]
print("succ:",Ge._succ)
print("pred:",Ge._pred)
print("items",list(Ge._items()))
assert_equal( sorted(Ge._items()), sorted(ans))
def test_view_data_keys(self):
Ge = self.Ge
ed1, ed2, ed3, ed4 = self.edlist
if Ge.d... |
rapidhere/snake_game | snake_game.py | Python | gpl-3.0 | 1,496 | 0.012032 | #!/usr/bin/python
# Copyright (C) 2013 rapidhere
#
# Author: rapidhere <rapidhere@gmail.com>
# Maintainer: rapidhere <rapidhere@gmail.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, ... | 'A' or LF-Arrow left"
print "'s' or 'S' or DW-Arrow down"
print "'d' or 'D' or RG-Arrpw right"
print "'q' or 'Q' quit"
s | ys.exit(0)
else:
app = skapp.SKApp()
app.run()
|
xianghuzhao/VMDIRAC | VMDIRAC/Security/VmProperties.py | Python | gpl-3.0 | 268 | 0.011194 | # $HeadURL$
__RCS | ID__ = "$Id$"
#
#
VM_WEB_OPERATION = "VmWebOperation"
#
VM_RPC_OPERATION = "VmRpcOperation"
#...............................................................................
#E | OF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF
|
jonathan-s/happy | happy/test/test_lists.py | Python | apache-2.0 | 11,513 | 0.001042 | import unittest2
import helper
import simplejson as json
from nose.plugins.attrib import attr
PORTAL_ID = 62515
class ListsClientTest(unittest2.TestCase):
"""
Unit tests for the HubSpot List API Python wrapper (hapipy) client.
This file contains some unittest tests for the List API.
Questions, comme... |
# create a list to get
dummy_data = json.dumps(dict(
name='try_and_get_me',
dynamic=False,
portalId=PORTAL_ID
))
created_list = self.client.create_list(dummy_data)
# make sure it was created
self.asserTrue(len(created_list['lists' | ]))
# the id number of the list the test is trying to get
id_to_get = created_list['listID']
# try and get it
recieved_lists = self.client.get_list(id_to_get)
# see if the test got the right list
self.assertEqual(recieved_lists['lists'][0]['listId'], created_list['list... |
s0lst1c3/eaphammer | local/hostapd-eaphammer/tests/remote/config.py | Python | gpl-3.0 | 3,543 | 0.011572 | # Environment configuration
# Copyright (c) 2016, Tieto Corporation
#
# This software may be distributed under the terms of the BSD license.
# See README for more details.
#
# Currently static definition, in the future this could be a config file,
# or even common database with host management.
#
import logging
logge... | after modprobe mac80211_hwsim
#
devices = [{"hostname": "localhost", "ifname": "wlan0", "port": "9868", " | name": "hwsim0", "flags": "AP_VHT80 STA_VHT80"},
{"hostname": "localhost", "ifname": "wlan1", "port": "9878", "name": "hwsim1", "flags": "AP_VHT80 STA_VHT80"},
{"hostname": "localhost", "ifname": "wlan2", "port": "9888", "name": "hwsim2", "flags": "AP_VHT80 STA_VHT80"},
{"hostname": "lo... |
jboning/python-dogma | test_dogma_extra.py | Python | agpl-3.0 | 1,477 | 0.00677 | from unittest import TestCase
import dogma
from test_dogma_values import *
class TestDogmaExtra(TestCase):
def test(self):
ctx = dogma.Context()
slot = ctx.add_module(TYPE_125mmGatlingAutoCannonII)
loc = dogma.Location.module(slot)
affectors = ctx.get_affectors(loc)
ctx.... | ffectors_with_ship = ctx.get_affectors(loc)
self.assertTrue(dogma.type_has_effect(TYPE_125mmGatlingAutoCannonII, dogma.State.ONLINE, EFFECT_HiPower))
self.assertTrue(dogma.type_has_active_effects(TYPE_125mmGatlingAutoCannonII))
self.assertTrue(dogma.type_has_overload_effects(TYPE_125mmGatlingAu... | rtTrue(dogma.type_has_projectable_effects(TYPE_StasisWebifierI))
self.assertEqual(dogma.type_base_attribute(TYPE_Rifter, ATT_LauncherSlotsLeft), 2)
ctx.add_charge(slot, TYPE_BarrageS)
self.assertEqual(ctx.get_number_of_module_cycles_before_reload(slot), 200)
effect = dogma.get_nth_type... |
mysociety/polipop | polipop/popit/models/positions.py | Python | agpl-3.0 | 7,783 | 0.010022 | import datetime
from django.contrib.gis.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.core import exceptions
from django.db.models import Q
from django.conf import settings
from django_date_extensions.fields import ApproximateDa... | e, default='')
# XXX: Working with South here presumably, umm, tricky
if 'mapit' in settings.INSTALLED_APPS:
place = models.ForeignKey('Place', null=True, blank=True, help_text="use if needed to identify the position - eg add constituency for an 'MP'" )
else:
place = models.Char... | note = models.CharField(max_length=300, blank=True, default='')
start_date = ApproximateDateField(blank=True, help_text=date_help_text)
end_date = ApproximateDateField(blank=True, help_text=date_help_text, default="future")
# Two hidden fields that are only used to do sorting. Fill... |
alekseik1/python_mipt_study_1-2 | 1sem/lesson_1/1.py | Python | gpl-3.0 | 138 | 0.043478 | a = in | t(input())
s = "odd"
s1 = "even"
for i in range(1, a):
if i%2==0 :
print(str(i) + " even")
else:
pri | nt(str(i)+" odd")
|
choltz95/story-understanding-amt | simpleamt.py | Python | mit | 2,932 | 0.011596 | import argparse, json
import boto3
from boto.mturk.connection import MTurkConnection
from boto.mturk.qualification import *
from jinja2 import Environment, FileSystemLoader
"""
A bunch of free functions that we use in all scripts.
"""
def get_jinja_env(config):
"""
Get a jinja2 Environment object that we can use... | ment('--hit_ids_file')
parser.add_argument('--config', default='config.json',
type=json_file)
return parser
def get_mturk_connection_from_args(args):
"""
Utility method to get an MTurkConnection from argparse args.
"""
aws_access_key = args.config.get('aws_access_key')
aws_secret_k... | cret_key=aws_secret_key)
def get_mturk_connection(sandbox=True, aws_access_key=None,
aws_secret_key=None):
"""
Get a boto mturk connection. This is a thin wrapper over the
MTurkConnection constructor; the only difference is a boolean
flag to indicate sandbox or not.
"""
kwargs ... |
leighpauls/k2cro4 | third_party/python_26/Lib/idlelib/AutoComplete.py | Python | bsd-3-clause | 9,041 | 0.000553 | """AutoComplete.py - An IDLE extension for automatically completing names.
This extension can complete either attribute names of file names. It can pop
a window with all available names, for the user to select from.
"""
import os
import sys
import string
from configHandler import idleConf
import AutoCompleteWindow
f... | return
else:
comp_what = ""
else:
return
if complete and not comp_what and not comp_start:
return
comp_lists = self.fetch_completions(comp_what, mo | de)
if not comp_lists[0]:
return
self.autocompletewindow = self._make_autocomplete_window()
self.autocompletewindow.show_window(comp_lists,
"insert-%dc" % len(comp_start),
complete,
... |
blckshrk/Weboob | weboob/tools/application/qt/qt.py | Python | agpl-3.0 | 13,100 | 0.001221 | # -*- coding: utf-8 -*-
# Copyright(C) 2010-2011 Romain Bignon
#
# This file is part of weboob.
#
# weboob 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... | s = self.weboob.do(*args, **kwargs)
self.process.callback_thread(self.thread_c | b, self.thread_eb)
def default_eb(self, backend, error, backtrace):
if isinstance(error, MoreResultsAvailable):
# This is not an error, ignore.
return
msg = unicode(error)
if isinstance(error, BrowserIncorrectPassword):
if not msg:
msg = ... |
timj/scons | test/QT/installed.py | Python | mit | 5,726 | 0.001921 | #!/usr/bin/env python
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
... | V_PATH,
'PATHEXT':os.environ.get('PATHEXT'),
'HOME':os.getcwd(),
'SystemRoot':ENV.get('SystemRoot')},
# moc / uic want to write stuff in ~/.qt
CXXFILESUFFIX=".cpp")
conf = env.Configure()
if not conf.CheckLib(... | ()
VariantDir('bld', '.')
env.Program('bld/test_realqt', ['bld/mocFromCpp.cpp',
'bld/mocFromH.cpp',
'bld/anUiFile.ui',
'bld/main.cpp'])
""")
test.write('mocFromCpp.h', """\
void mocFromCpp();
""")
test.write('mocFromCpp.cp... |
adriansuhov/lis-test | WS2012R2/lisa/Infrastructure/lisa-parser/lisa_parser/file_parser.py | Python | apache-2.0 | 38,829 | 0.00376 | """
Linux on Hyper-V and Azure Test Code, ver. 1.0.0
Copyright (c) Microsoft Corporation
All rights reserved
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICEN... | .split(':')[1]\
.strip()
elif re.search('^logs can be found at', line):
parsed_ica['logPath'] = line.split()[-1]
elif re.search('^lis version', line):
parsed_ica['lisVersion'] = line.split(':')[1].strip()
return parsed_ica
def parse_from... | nd read csv file into a dict data type.
:param csv_path: csv file path
:return: <list of dict> e.g. [{'t_col1': 'val1',
't_col2': 'val2',
...
},
...]
None - on ... |
GoogleCloudPlatform/healthcare | fhir/immunizations_demo/inference/main.py | Python | apache-2.0 | 10,155 | 0.008075 | #!/usr/bin/python3
#
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | res/my-store
/fhir/Patient' for create requests and 'projects/my-project
/locations/us-central1/datasets/my-dataset/fhirStores/my-store
/fhir/Patient/patient-id' for update requests.
payload (str): resource to be written to | the FHIR Store.
Returns:
Object: the resource from the server, usually this is an
OperationOutcome resource if there is anything wrong.
"""
# Determine which HTTP method we need to use: POST for create, and PUT for
# update. The path of update requests have one more component than create
# req... |
eile/ITK | Modules/ThirdParty/pygccxml/src/pygccxml/declarations/type_traits.py | Python | apache-2.0 | 44,926 | 0.02838 | # Copyright 2004-2008 Roman Yakovenko.
# Distributed under the Boost Software License, Version 1.0. (See
# accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
"""
defines few algorithms, that deals with different properties of C++ types
Do you aware of boost::type_traits library? pygc... | ype represents pointer to free/member function, False otherwise"""
if not is_pointer(type):
return False
nake_type = remove_alias( type )
nake_type = remove_const( nake_type )
nake_type = remove_volatile( nake_type )
return isinstance( nake_type, cpptypes.compound_t ) \
and isinst... | """removes pointer from the type definition
If type is not pointer type, it will be returned as is.
"""
nake_type = remove_alias( type )
if not is_pointer( nake_type ):
return type
elif isinstance( nake_type, cpptypes.volatile_t ) and isinstance( nake_type.base, cpptypes.pointer_t ):
... |
erc7as/cs3240-labdemo | check.py | Python | mit | 94 | 0.06383 | def check(msg):
if msg == 'hello':
print( | hello)
| else:
print(goodbye)
check('greetings') |
mcmcplotlib/mcmcplotlib | api/generated/arviz-plot_dist-5.py | Python | apache-2.0 | 69 | 0 | az. | plot_dist(b, rug=True, quantil | es=[.25, .5, .75], cumulative=True)
|
gurunars/state_machine_crawler | setup.py | Python | apache-2.0 | 812 | 0 | #!/usr/bin/python
import os
from setuptools import setup, find_packages
SRC_DIR = os.path.dirname(__file__)
CHANGES_FILE = os.path.join(SRC_DIR, "CHANGES")
with open(CHANGES_FILE) as fil:
version = fil.readline().split()[0]
setup(
name="state-machine-crawler",
description="A library for following autom... | k==1.0.1", "coverage"],
install_requires=["werkzeug", "pydot2", "pyparsing==1.5.2"],
test_suite='nose.collector',
author="Anton Berezin",
author_email="gurunars@gmail.com",
entry_points={
"console_scripts": [
'state-machine-crawler = state_machine_crawler:entry_point'
]
... | lude_package_data=True
)
|
jpeddicord/jobservice | JobService/policy.py | Python | gpl-3.0 | 2,319 | 0.004743 | # This file is part of jobservice.
# Copyright 2010 Jacob Peddicord <jpeddicord@ubuntu.com>
#
# jobservice 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)... | force=True):
self.enforce = enforce
self.bus = SystemBus()
self.dbus_iface = None
self.pk = Interface( | self.bus.get_object('org.freedesktop.PolicyKit1',
'/org/freedesktop/PolicyKit1/Authority'),
'org.freedesktop.PolicyKit1.Authority')
if not enforce:
log.warn('Not enforcing PolicyKit privileges!')
def check(self, sender, conn, priv='com.ubuntu.jobserv... |
IrinaZI/Python_training | model/contact.py | Python | apache-2.0 | 1,808 | 0.005531 | from sys import maxsize
class Contact:
def __init__(self, Firstname=None, Middlename=None, Lastname=None, Nickname=None, Title=None, Company=None, Address=None, Home=None, Mobile=None, Work=None,
Fax=None, Email=None, Email2=None, Email3=None, Homepage=None, Bday=N | one, Bmonth=None, Byear=None, Aday=None, Amonth=None, Ayear=None, Address2=None, Phone2=None,
Notes=None, id=None, all_phones_from_home_p | age=None, all_address_from_home_page=None, all_emails=None):
self.Firstname = Firstname
self.Middlename = Middlename
self.Lastname = Lastname
self.Nickname = Nickname
self.Title = Title
self.Company = Company
self.Address = Address
self.Home = Home
... |
eusoubrasileiro/fatiando | fatiando/gravmag/magdir.py | Python | bsd-3-clause | 7,336 | 0 | """
Estimation of the total magnetization vector of homogeneous bodies.
It estimates parameters related to the magnetization vector of homogeneous
bodies.
**Algorithms**
* :class:`~fatiando.gravmag.magdir.DipoleMagDir`: This class estimates
the Cartesian components of the magnetization vector of homogeneous
dipo... | t of dipoles, the
estimation of the Cartesian components | of the magnetization vectors is
formulated as linear inverse problem. After estimating the magnetization
vectors, they are converted to dipole moment, inclination (positive down)
and declination (with respect to x, North).
Reference
Blakely, R. (1996), Potential theory in gravity and magnetic app... |
weinrank/wireshark | tools/asn2wrs.py | Python | gpl-2.0 | 308,942 | 0.01106 | #!/usr/bin/env python
#
# asn2wrs.py
# ASN.1 to Wireshark dissector compiler
# Copyright 2004 Tomas Kukosa
#
# 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
# ... | be used in advertising or otherwise to promote the sale, use
# or other dealings in this Software without prior written authorization
# of the copyright holder.
"""ASN.1 to Wir | eshark dissector compiler"""
#
# Compiler from ASN.1 specification to the Wireshark dissector
#
# Based on ASN.1 to Python compiler from Aaron S. Lav's PyZ3950 package licensed under the X Consortium license
# http://www.pobox.com/~asl2/software/PyZ3950/
# (ASN.1 to Python compiler functionality is broken but not remo... |
keelerm84/powerline | setup.py | Python | mit | 931 | 0.026853 | #!/usr/bin/env python
# vim:fileencoding=utf-8:noet
from __future__ import unicode_literals
import os
import sys
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.rst'), 'rb').read().decode('utf-8')
except IOError:
README = ''... | ywords='',
packages=find_packages(exclude=('tests', 'tests.*')),
include_package_data=True,
zip_safe=False,
install_req | uires=[],
extras_require={
'docs': [
'Sphinx',
],
},
test_suite='tests' if not old_python else None,
)
|
uclouvain/osis_louvain | base/migrations/0208_create_role_executive.py | Python | agpl-3.0 | 935 | 0.003209 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-11-22 07:11
from __future__ import unicode_literals
from django.core.management.sql import emit_post_migrate_signal
from django.db import migrations
def add_executive_group(apps, schema_editor):
# create group
db_alias = schema_editor.connection.al... | it
can_access_learningunit = Permission.objects.get(codename='can_access_learningunit')
executive_group.permissions.add(can_ac | cess_learningunit)
class Migration(migrations.Migration):
dependencies = [
('base', '0207_auto_20171220_1035'),
]
operations = [
migrations.RunPython(add_executive_group),
] |
mhielscher/wasabiscripts | twitterpic.py | Python | bsd-2-clause | 1,695 | 0.020649 | # Twitter profile image updater
# http | ://twitter.com/account/update_profile_image.json
# image = [imagefile]
import sys
import os
import random
import re
import urllib
import json
import urllib2
import oauth2 as oauth
import time
import wcommon
def encode_file_data(image):
boundary = hex(int(time.time()))[2:]
headers = {}
headers['Content-Type'] = '... | r\n")
data.append('Content-Disposition: form-data; name="image"; filename="%s"\r\n' % image.name)
if image.name.endswith("jpg") or image.name.endswith("jpeg"):
data.append("Content-Type: image/jpeg\r\n\r\n")
elif image.name.endswith("png"):
data.append("Content-Type: image/png\r\n\r\n")
elif image.name.endswith... |
gentooza/Freedom-Fighters-of-Might-Magic | src/gamelib/gummworld2/pygametext.py | Python | gpl-3.0 | 21,402 | 0.00271 | # ptext module: place this in your import directory.
# ptext.draw(text, pos=None, **options)
# Please see README.md for explanation of options.
# https://github.com/cosmologicon/pygame-text
from __future__ import division
from math import ceil, sin, cos, radians, exp
import pygame
DEFAULT_FONT_SIZE = 2... | paras = text.replace("\t", " ").split("\n")
lines = []
for jpara, para in enumerate(paras):
if strip:
para = para.rstrip(" ")
if width is None:
lines.append((para, jpara))
continue
if not para:
lines.append(("", jpara))
... | me, a is the rightmost known index you can legally split a line. I.e. it's legal
# to add para[:a] to lines, and line is what will be added to lines if para is split at a.
a = para.index(" ", a) if " " in para else len(para)
line = para[:a]
while a + 1 < len(para):
# b i... |
neuroo/equip | equip/analysis/flow.py | Python | apache-2.0 | 18,228 | 0.012783 | # -*- coding: utf-8 -*-
"""
equip.analysis.flow
~~~~~~~~~~~~~~~~~~~
Extract the control flow graphs from the bytecode.
:copyright: (c) 2014 by Romain Gaucher (@rgaucher)
:license: Apache 2, see LICENSE for more details.
"""
import opcode
from operator import itemgetter, attrgetter
from itertools import tee,... | d.
"""
if self._conds is None:
self.compute_conditions()
return self._conds
@property
def frames(self):
return self._frames
@property
def graph(self):
"""
Returns the underlying graph that holds the CFG.
"""
return self._graph
@property
def dominators(self):
""... | CFG node -> set CFG nodes)
This is lazily computed.
"""
if self._dom is None:
self._dom = DominatorTree(self)
return self._dom
@property
def control_dependence(self):
"""
Returns the ``ControlDependence`` graph. This is lazily computed.
"""
if self._cdg is None:
self... |
Tribler/decentralized-mortgage-market | market/community/blockchain/community.py | Python | gpl-3.0 | 30,409 | 0.00342 | import os
import time
import hashlib
import logging
from base64 import b64encode
from collections import OrderedDict, defaultdict
from twisted.internet.task import LoopingCall
from twisted.internet.defer import Deferred
from dispersy.authentication import MemberAuthentication
from dispersy.candidate import Candidate
... | 6052b81040027038192000407bacf5ae4d3fe94d49a7f94b7239e9c2d878b29' + \
'f0fbdb7374d5b6a09d9d6fba80d3807affd0ba45ba1ac1c278ca59bec422d8a44b5fefaabcdd62c2778414c01da4' + \
'578b304b104b00eec74de98dcda803b79fd1783d76cc1bd7aab75cfd8fff9827a9647ae3c59423c2a9a984700e7c' + \
... | 'b43b881a6455574032cc11dba806dba9699f54f2d30b10eed5c7c0381a0915a5'
master = dispersy.get_member(public_key=master_key.decode('hex'))
return [master]
def initiate_meta_messages(self):
meta_messages = super(BlockchainCommunity, self).initiate_meta_messages()
return meta_messages ... |
windreamer/dpark | dpark/conf.py | Python | bsd-3-clause | 991 | 0.001009 | from __future | __ import absolute_import
import os.path
from dpark.util import get_logger
logger = get_logger(__name__)
# workdir used in slaves for internal files
#
DPARK_WORK_DIR = '/tmp/dpark'
if os.path.exists('/dev/shm'):
DPARK_WORK_DIR = '/dev/shm,/tmp/dpark'
# uri of mesos master, host[:5050] or or zk://...
MESOS_MASTE... | t dir cache in client, need patched mfsmaster
MOOSEFS_DIR_CACHE = False
# memory used per task, like -M (--m) option in context.
MEM_PER_TASK = 200.0
def load_conf(path):
if not os.path.exists(path):
logger.error("conf %s do not exists", path)
raise Exception("conf %s do not exists" % path)
t... |
Impavidity/SearchEngine | WebSite/engine/query.py | Python | mit | 3,939 | 0.001269 | import cPickle as pickle
import numpy as np
import re
from math import log
from dic import Info
from | config.config import config
from tools import tokenlize, comp_tuple, weights
class query_voc(object):
def __init__(self, tokens, dic):
self.tokens = tokens
self.dic = dic
class query_entry(object):
def __init__(self, doc_id, tokens, voc):
self.docID = doc_id
self.tokens = to... | or token in self.tokens:
if config.WEIGHT_TYPE == 'wf-idf':
self.vector[0, voc.dic[token]['index']] = (1 + log(self.tokens[token])) * voc.dic[token]['idf']
elif config.WEIGHT_TYPE == 'tf-idf':
self.vector[0, voc.dic[token]['index']] = self.tokens[token] * voc.dic[... |
javert/tftpudGui | src/tftpudgui/qt4/TftpudSettings.py | Python | mit | 2,975 | 0.005714 | '''
Created on 21 Dec 2013
@author: huw
'''
from ConfigParser import ConfigParser
class TftpudSettings:
'''
A class to hold the settings for the TftpudServerGui application.
'''
def __init__(self):
'''
Constructor
'''
self.saveLastUsed = False
self.defaultDir... | erSection = 'Server'
if cfg.has_section(serverSection):
if cfg.has_option(serverSection, 'defaultDirectory'):
self.defaultDirectory = cfg.get(serverSection, 'defaultDirectory')
if cfg.has_option(serverSection, 'saveLastUsed'):
self.saveLastUsed = cfg.getbo... | |
centaurialpha/edis | src/ui/editor/lexer.py | Python | gpl-3.0 | 2,435 | 0.000411 | # -*- coding: utf-8 -*-
# EDIS - a simple cross-platform IDE for C
#
# This file is part of Edis
# Copyright 2014-2015 - Gabriel Acosta <acostadariogabriel at gmail>
# License: GPLv3 (see http://www.gnu.org/licenses/gpl.html)
from PyQt4.Qsci import QsciLexerCPP
from PyQt4.QtGui import QColor
from src import editor_sc... | r/scheme'))
self.setDefaultPaper(QColor(scheme['BackgroundEditor']))
self.setPaper(self.defaultPaper(0))
self.setColor(QColor(scheme['Color']))
types = dir(self)
for _type in types:
if _type in scheme:
atr = getattr(self, _type)
self.s... | _type]), atr)
def keywords(self, kset):
super(Lexer, self).keywords(kset)
if kset == 1:
# Palabras reservadas
return ('auto break case const continue default do else enum '
'extern for goto if register return short sizeof static '
'str... |
ZoranPavlovic/kombu | t/unit/utils/test_amq_manager.py | Python | bsd-3-clause | 1,196 | 0 | import pytest
from unittest.mock import patch
from case import mock
from kombu import Connection
class test_get_manager:
@mock.mask_modules('pyrabbit')
def test_without_pyrabbit(self):
with pytest.raises(ImportError):
Connection('amqp://').get_manager()
@mock.module_exists(' | pyrabbit')
def test_with_pyrabbit(self):
with patch('pyrabbit.Client', create=True) as Client:
manager = Connection('amqp://').get_manager()
assert manager i | s not None
Client.assert_called_with(
'localhost:15672', 'guest', 'guest',
)
@mock.module_exists('pyrabbit')
def test_transport_options(self):
with patch('pyrabbit.Client', create=True) as Client:
manager = Connection('amqp://', transport_options={
... |
teheavy/AMA3D | Nh3D/1_AMA3D_start.py | Python | gpl-2.0 | 1,285 | 0.035798 | # Script Version: 1.0
# Author: Te Chen
# Project: AMA3D
# Task Step: 1
import sys
import urllib2
import time
VERSION = '4.0.0'
def prepare_cath():
ver = VERSION.replace('.', '_')
download_file(ver, 'CathDomainList')
download_file(ver, 'CathNames')
download_file(ver, 'CathDomainDescriptionFile')
def download_fil... | ath/v%s/%s" % (ver, file_name)
file_name = url.split('/')[-1]
u = urllib2.urlopen(url)
f = open('C:/AMA3D/Nh3D/' + file_name, 'wb')
meta = u.in | fo()
file_size = int(meta.getheaders("Content-Length")[0])
print "Downloading: %s Bytes: %s" % (file_name, file_size)
file_size_dl = 0
block_sz = 8192
while True:
buffer = u.read(block_sz)
if not buffer:
break
file_size_dl += len(buffer)
f.write(buffer)
f.close()
print "Downl... |
Michael-Tu/tools | stock_scraping/stock_price_scraping_to_local.py | Python | mit | 2,169 | 0.003688 | '''
This script helps you scrap stock data avaliable on Bloomberg Finance
and store them locally.
Please obey applicable local and federal laws and applicable API term of use
when using this scripts. I, the creater of this script, will not be responsible
for any legal issues resulting from the use of this script.
@au... | s Initialization
# Feel free to modify the file source to contain stock symbols you plan to scrap fro
stocks = open("nas | daq_symbols.txt", "r").read().split("\n")
# URL Initialization
urlPrefix = "http://www.bloomberg.com/markets/api/bulk-time-series/price/"
urlAffix = "%3AUS?timeFrame="
# Only four of these are valid options for now
# 1_Day will scrap minute by minute data for one day, while others will be daily close price
# Feel fre... |
mauimuc/gptt | src/animation.py | Python | gpl-3.0 | 2,920 | 0.012671 | #!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = "Stefan Mauerberger"
__copyright__ = "Copyright (C) 2017 Stefan Mauerberger"
__license__ = "GPLv3"
import numpy as np
from sys import stdout
from matplotlib import pyplot as plt
from matplotlib import animation
from plotting import prepare_map, lllat, lllon,... | max_sd = np.max(sd_C).round().astype(np.integer)
cbar.set_ticks(range(vmin_sd, vmax_sd, 5))
#cbar.set_label('standard deviation')
m.scatter(stations['lon'], stations['lat'], latlon= | True, lw=0, color='g')
# First frame; Necessary for LaTeX beamer
plt.savefig('../animation_pri.png', dpi=dpi)
def animate(i):
global mu_C, cov_CC
tpc_mu.set_array(mu_C[i,:])
tpc_sd.set_array(sd_C[i,:])
# Screen output; a very basic progress bar
p = int(100.*(i+1)/mu_C.shape[0]) # Progress
std... |
daicang/Leetcode-solutions | 064-minimum-path-sum.py | Python | mit | 877 | 0.002281 | class Solution(object):
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
if not grid or not grid[0]:
| return 0
m = len(grid)
n = len(grid[0])
dp = []
for _ in range(m):
dp.append([None] * (n))
dp[m-1][n-1] = grid[m-1][n-1]
def solve(row, col):
if dp[row][col] is not None:
return dp[row][col]
if row == m-1:
... | [col] + solve(row+1, col)
else:
cost = grid[row][col] + min(solve(row, col+1), solve(row+1, col))
dp[row][col] = cost
# print 'dp(%s,%s) is %s' % (row, col, ans)
return cost
return solve(0, 0) |
dryobates/testing_django | todo/tasks/tests/test_models.py | Python | mit | 601 | 0 | from django.test import TestCase
from morelia.decorators import tags
from smarttest.decorators import no_db_testcase
from task | s.factories import TaskFactory, UserFactory
@no_db_testcase
@tags(['unit'])
class TaskGetAbsoluteUrlTest(TestCase):
''' :py:meth:`tasks.models.Task.get_absolute_url` '''
def test_should_return_task_absolute_url(self):
# Arrange
owner = UserFactory.build(pk=1)
task = TaskFactory.build(... | solute_url()
# Assert
self.assertEqual(url, '/%s/' % owner.username)
|
gnowgi/gnowsys-studio | gstudio/xmlrpc/dispatcher.py | Python | agpl-3.0 | 3,078 | 0.00065 | """Offers a simple XML-RPC dispatcher for django_xmlrpc
Author::
| Graham Binns
Credit must go to Brendan W. McAdams <brendan.mcadams@thewi | ntergrp.com>, who
posted the original SimpleXMLRPCDispatcher to the Django wiki:
http://code.djangoproject.com/wiki/XML-RPC
New BSD License
===============
Copyright (c) 2007, Graham Binns http://launchpad.net/~codedragon
All rights reserved.
Redistribution and use in source and binary forms, with or without
modific... |
tmerrick1/spack | var/spack/repos/builtin/packages/gmp/package.py | Python | lgpl-2.1 | 2,575 | 0.000388 | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | 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) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF... | tails.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
... |
openstack/python-tripleoclient | tripleoclient/tests/workflows/test_baremetal.py | Python | apache-2.0 | 19,069 | 0 | # -*- coding: utf-8 -*-
# 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, softw... | self.existing_nodes = [
{'uuid': '1', 'driver': 'ipmi',
'driver_info': {'ipmi_address': '10.0.0.1'}},
{'uuid': '2', 'driver': 'pxe | _ipmitool',
'driver_info': {'ipmi_address': '10.0.0.1', 'ipmi_port': 6235}},
{'uuid': '3', 'driver': 'foobar', 'driver_info': {}},
{'uuid': '4', 'driver': 'fake',
'driver_info': {'fake_address': 42}},
{'uuid': '5', 'driver': 'ipmi', 'driver_info': {}},
... |
daobilige-su/SSM_LinearArray | ROS/SSM_LinearArray/scripts/ps3_driver.py | Python | gpl-3.0 | 1,741 | 0.013211 | #!/usr/bin/env python
#
# This file is part of the SSM_LinearArray (Sound Sources Mapping
# using a Linear Microphone Array)
# developed by Daobilige Su <daobilige DOT su AT student DOT uts DOT edu DOT au>
#
# This file is under the GPLv3 licence.
#
import rospy
from std_msgs.msg import String
from std_msgs.msg impo... | ize=1)
def callback(in_data, frame_count, time_info, status):
global np,pub_mic_array
numpydata = np.fromstring(in_data, dtype=np.int16)
print('sending...')
numpydata_msg = Int32MultiArray()
numpydata_msg.data = numpydata
pub_mic_array.publish(numpydata_msg)
return (in_data, pyaudio.paConti... | input=True,
frames_per_buffer=CHUNK,
input_device_index=DEV_IDX,
stream_callback=callback)
def signal_handler(signal, frame):
print('---stopping---')
stream.close()
p.terminate()
sys.exit()
signal.signal(signal.SIGINT, signal_handler)
def talker():
... |
AASHE/hub | hub/apps/api/views.py | Python | mit | 3,271 | 0 | from __future__ import unicode_literals
from logging import getLogger
from django.conf import settings
from django.core.cache import cache
from django.views.generic import View
from django.http import JsonResponse, HttpResponseBadRequest
from django.template.defaultfilters import sl | ugify
from ratelimit.mixins import RatelimitMixin
from ..metadata.models import Organization
from ..content.models import ContentType
logger = getLogger(__name__)
class BaseApiView(RatelimitMixin, View):
cache = False
cache_timeout = 60 * 60
# Rate-limiting
ratelimit_key = 'ip'
ratelimit_rate =... | , request, *args, **kwargs):
"""
Respond the content of `self.get_data` as JSON. Cache it, if enabled.
"""
if self.cache:
data = cache.get(self.get_cache_key())
if data:
logger.debug('API response: cache hit :: {}'.format(
self.... |
rbtcollins/lmirror | l_mirror/tests/test_logging_support.py | Python | gpl-3.0 | 2,180 | 0.004128 | #
# LMirror is Copyright (C) 2010 Robert Collins <robertc@robertcollins.net>
#
# LMirror 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... | sertEqual(time.gmtime, formatter.converter)
| self.assertEqual("%Y-%m-%d %H:%M:%SZ", formatter.datefmt)
self.assertEqual(logging.StreamHandler, c_log.__class__)
self.assertEqual(out, c_log.stream)
self.assertEqual(logging.FileHandler, f_log.__class__)
self.assertEqual(os.path.expanduser("~/.cache/lmirror/log"), f_log.baseFilen... |
laurentb/weboob | modules/cragr/netfinca_browser.py | Python | lgpl-3.0 | 251 | 0 | # -*- coding: utf-8 -*-
# Copyrig | ht(C) 2012-2019 Budget Insight
# yapf-compatible
from weboob.browser import AbstractBrowser
class NetfincaBrowser(A | bstractBrowser):
PARENT = 'netfinca'
BASEURL = 'https://www.cabourse.credit-agricole.fr'
|
itskewpie/tempest | tempest/api/identity/base.py | Python | apache-2.0 | 6,216 | 0.000161 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# 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.apach... | resp, self.project = self.client.create_project(
name=self.test_project,
description=self.test_description)
self.projects.append(self.project)
def setup_test_v3_role(self):
"""Set up a test v3 role. | """
self.test_role = rand_name('role')
resp, self.v3_role = self.client.create_role(self.test_role)
self.v3_roles.append(self.v3_role)
def teardown_all(self):
for user in self.users:
self.client.delete_user(user['id'])
for tenant in se... |
tylertian/Openstack | openstack F/cinder/cinder/tests/test_skip_examples.py | Python | apache-2.0 | 1,837 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop= | 4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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
# ... | t
#
# 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 express or implied. See the
# License for the specific l... |
spoqa/flask-s3 | flask_s3.py | Python | mit | 12,801 | 0.002734 | from concurrent.futures import ThreadPoolExecutor
import os
import re
import gzip
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
import logging
import mimetypes
from collections import defaultdict
from flask import url_for as flask_url_for
from flask import current_app, r... | t be under %s static folder" %
(static_asset, static_folder))
rel_asset = static_asset[len(sta | tic_folder):]
# Now bolt the static url path and the relative asset location together
key = u'%s/%s' % (static_url.rstrip('/'), rel_asset.lstrip('/'))
if prefix:
key = u'%s/%s' % (prefix, key)
return key
def _write_files(app, static_url_loc, static_folder, files, bucket,
ex_ke... |
parksandwildlife/ibms | ibms_project/ibms/migrations/0007_auto_20180813_1604.py | Python | apache-2.0 | 391 | 0 | # Generated by Django 2.1 on 2018-08-13 08:04
from django.db import migrations
class Migration(migrations.Migration):
dependen | cies = [
('ibms', '0006_auto_20180813_1603'),
]
operations = [
migrations.RenameField(
model_name='serviceprioritymappings',
old_name='costcentreName',
n | ew_name='costCentreName',
),
]
|
eblur/newdust | newdust/graindist/composition/cmsilicate.py | Python | bsd-2-clause | 3,341 | 0.00419 | import numpy as np
from scipy.interpolate import interp1d
from astropy.io import ascii
from astropy import units as u
from newdust import constants as c
from newdust.graindist.composition import _find_cmfile
__all__ = ['CmSilicate']
RHO_SIL = 3.8 # g cm^-3
class CmSilicate(object):
"""
| **ATTRIBUTES... | f.ip(lam, unit)
x = lam
assert unit in c.ALLOWED_LAM_UNITS
if unit == 'kev': xlabel = "Energy (keV)"
if unit == 'angs': xlabel = "Wavelength (Angstroms)"
if rppart:
ax.plot(x, rp_m1, ls='-', label='|Re(m-1)|')
if impart:
ax.plot(x,... | ax.legend()
|
supunkamburugamuve/mooc2 | controllers/lessons.py | Python | apache-2.0 | 12,062 | 0.00257 | # Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | user = self.personalize_page_and_get_user()
if not user:
self.redirect('/preview')
| return None
student = Student.get_by_email(user.email())
playlist = student.playlist
playlist_urls = student.playlist_urls
if not self.personalize_page_and_get_enrolled():
return
self.template_value['units'] = self.get_units()
self.template_value['... |
ddico/odoo | addons/l10n_in/models/res_config_settings.py | Python | agpl-3.0 | 355 | 0.002817 | # -*- coding: utf-8 -*-
# Part of Odoo. S | ee LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class ResConfigSettings(models.TransientModel):
_inherit = 'res.config.settings'
group_l10n_in_reseller = fields.Boolean(implied_group='l10n_in.group_l10n_in_reseller', string="M | anage Reseller(E-Commerce)")
|
phobson/bokeh | sphinx/docserver.py | Python | bsd-3-clause | 1,749 | 0.005146 | from __future__ import print_function
import flask
import os
import threading
import time
import webbrowser
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
_basedir = os.path.join("..", os.path.dirname(__file__))
app = flask.Flask(__name__, static... | erver to facilitate developing the docs. by
serving up static files from this server, we avoid the need to use a
symlink.
"""
@app.route('/')
def welcome():
return """
<h1>Welcome to the Bokeh documentation server</h1>
You probably want to go to <a href="/en/latest/index.html"> Index</a>
"""
@app.r... | open_browser():
# Child process
time.sleep(0.5)
webbrowser.open("http://localhost:%d/en/latest/index.html" % PORT, new="tab")
def serve_http():
http_server.listen(PORT)
IOLoop.instance().start()
def shutdown_server():
ioloop = IOLoop.instance()
ioloop.add_callback(ioloop.stop)
print("A... |
fcrozat/telepathy-haze | tests/twisted/roster/removed-from-rp-subscribe.py | Python | gpl-2.0 | 6,175 | 0.002591 | """
Regression tests for rescinding outstanding subscription requests.
"""
from twisted.words.protocols.jabber.client import IQ
from servicetest import (EventPattern, wrap_channel, assertLength,
assertEquals, call_async, sync_dbus)
from hazetest import exec_test
import constants as cs
import ns
jid = 'marco@... | EnsureChannel')
subscribe = wrap_channel(bus | .get_object(conn.bus_name, e.value[1]),
cs.CHANNEL_TYPE_CONTACT_LIST)
call_async(q, conn.Requests, 'EnsureChannel',{
cs.CHANNEL_TYPE: cs.CHANNEL_TYPE_CONTACT_LIST,
cs.TARGET_HANDLE_TYPE: cs.HT_LIST,
cs.TARGET_ID: 'stored',
})
e = q.expect('dbus-return', method='Ensur... |
tungvx/deploy | Django-0.90/django/contrib/comments/views/comments.py | Python | apache-2.0 | 16,510 | 0.006481 | from django.core import formfields, validators
from django.core.mail import mail_admins, mail_managers
from django.core.exceptions import Http404, ObjectDoesNotExist
from django.core.extensions import DjangoContext, render_to_response
from django.models.auth import users
from django.models.comments import comments, fre... | self.ratings_range, self.num_rating_choices = ratings_range, num_rating_choices
choices = [(c, c) for c in ratings_range]
def get_validator_list(rating_num):
if rating_num <= num_rating_choices:
return [validators.RequiredIfOtherFiel | dsGiven(['rating%d' % i for i in range(1, 9) if i != rating_num], "This rating is required because you've entered at least one other rating.")]
else:
return []
self.fields.extend([
formfields.LargeTextField(field_name="comment", maxlength=3000, is_required=True,
... |
Benzhaomin/TwitchCancer | twitchcancer/api/tests/test_pubsubmanager.py | Python | gpl-3.0 | 4,912 | 0.000611 | import unittest
from unittest.mock import patch, MagicMock
from twitchcancer.api.pubsubmanager import PubSubManager
# PubSubManager.instance()
class TestPubSubManagerInstance(unittest.TestCase):
# check that we only store one instance of any topic
@patch('twitchcancer.api.pubsubmanager.PubSubManager.__new__... | that a client subscribed to a topic gets data on publish()
def test_publish_subscribed(self):
# subscribe a cli | ent to a topic
client = MagicMock()
p = PubSubManager()
p.subscriptions["topic"] = {client}
# publish data for that topic
topic = MagicMock()
topic.payload = MagicMock(return_value="payload")
p.publish(topic)
# make sure the client got data
clien... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.