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 |
|---|---|---|---|---|---|---|---|---|
lem8r/cofair-addons | l10n_ch_payment_slip/__manifest__.py | Python | lgpl-3.0 | 847 | 0 | # -*- coding: utf-8 -*-
# © 2012-2016 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{'name': 'Switzerland - Payment Slip (BVR/ESR)',
'summary': 'Print ESR/BVR payment slip with your invoices',
'version': '10.0.2.1.1',
'author': "Camptocamp,Odoo Community Association (OCA)",
'category... | ends': [
'base',
'account',
'report',
'l10n_ch_base_bank',
'base_transaction_id', # OCA/bank-statement-reconcile
],
'data': [
"views/company.xml",
"views/bank.xml",
"views/account_invoice.xml",
"wizard/bvr_import_view.xml",
"report/report_declaration.xml",
"secu... | |
leVirve/NTHU-Library | nthu_library/static_urls.py | Python | gpl-2.0 | 363 | 0.002755 | info_system = 'http://webpac.lib.nthu.edu.tw/F/'
top_circulations = 'http://www.lib. | nthu.edu.tw/guide/topcirculations/index.htm'
top_circulations_bc2007 = 'http://www.lib. | nthu.edu.tw/guide/topcirculations/bc2007.htm'
rss_recent_books = 'http://webpac.lib.nthu.edu.tw:8080/nbr/reader/rbn_rss.jsp'
lost_found_url = 'http://adage.lib.nthu.edu.tw/find/search_it.php'
|
davidam/python-examples | pyglet/keyboard.py | Python | gpl-3.0 | 446 | 0.006726 |
import pyglet
from pyglet.window import key |
window = pyglet.window.Window()
@window.event
def on_key_press(symbol, modifiers):
print('A key was pressed')
if symbol == key.A:
print('The "A" key was pressed.')
elif symbol == key.LEFT:
print('The left arrow key was pressed.')
elif symbol == key.ENTER:
print('The enter key ... | ()
pyglet.app.run()
|
zoidbergwill/lint-review | tests/test_review.py | Python | mit | 15,108 | 0 | from . import load_fixture
from lintreview.config import load_config
from lintreview.diff import DiffCollection
from lintreview.review import Review, Problems, Comment
from lintreview.repo import GithubRepository, GithubPullRequest
from mock import Mock, call
from nose.tools import eq_
from github3.issues.comment impor... | self.repo.create_status.assert_called_with(
self.pr.head,
'failure',
'Lint errors found, see pull request comments.')
assert not self. | pr.create_comment.called, 'Comment not created'
assert not self.pr.add_label.called, 'Label added created'
def test_publish_problems_remove_ok_label(self):
problems = Problems()
filename_1 = 'Console/Command/Task/AssetBuildTask.php'
errors = (
(filename_1, 117, 'Somethi... |
allotria/intellij-community | python/testData/inspections/PyTypeCheckerInspection/UnresolvedReceiverGeneric.py | Python | apache-2.0 | 165 | 0.006061 | from typing import TypeVar, Dict, Iterable, Any
T = TypeVar("T")
def foo(values: Dict[T, Iterable[Any]]):
for e in []:
| values.setdefault(e, undefined | ) |
mhogg/bonemapy | setup.py | Python | mit | 2,237 | 0.021904 | # -*- coding: utf-8 -*-
# Copyright (C) 2013 Michael Hogg
# | This file is part of bonemapy - See LICEN | SE.txt for information on usage and redistribution
import bonemapy
from distutils.core import setup
setup(
name = 'bonemapy',
version = bonemapy.__version__,
description = 'An ABAQUS plug-in to map bone properties from CT scans to 3D finite element bone/implant models',
license = 'MIT license',
... |
mikeckennedy/cookiecutter-course | src/ch8_sharing_your_template/show_off_web_app/show_off_web_app/controllers/base_controller.py | Python | gpl-2.0 | 1,456 | 0.000687 | import logbook
import show_off_web_app.infrastructure.static_cache as static_cache
import pyramid.httpexceptions as exc
from show_off_web_app.infrastructure.supressor import suppress
import show_off_web_app.infrastructure.cookie_auth as cookie_auth
from show_off_web_app.services.account_service import AccountService
... | , "")
self.log = logbook.Logger(log_name)
@property
def is_logged_in(self):
return cookie_auth.get_user_id_via_auth_cookie(self.request) is not None
# noinspection PyMethodMayBeStatic
@suppress()
def redirect(self, to_url, | permanent=False):
if permanent:
raise exc.HTTPMovedPermanently(to_url)
raise exc.HTTPFound(to_url)
@property
def merged_dicts(self):
data = dict()
data.update(self.request.GET)
data.update(self.request.POST)
data.update(self.request.matchdict)
... |
Obijuan/protocoder-apps | servos/python-client/Servo.py | Python | gpl-2.0 | 1,675 | 0.027463 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#-----------------------------------------------------------------
#-- Servo | class
#-- Juan Gonzalez-Gomez (obijuan). May-2013
#-----------------------------------------------------------------
#-- Controlling the position of servos from the PC
#-- The Arduino / skymega or anoth | er arduino compatible board
#-- should have the firmware FingerServer uploaded
#-----------------------------------------------------------------
import time
class IncorrectAngle():
pass
class Servo(object):
"""Servo class. For accessing to all the Servos"""
def __init__(self, sp, dir = 0):
"""Argumen... |
rosarior/rua | rua/apps/common/compressed_files.py | Python | gpl-3.0 | 2,263 | 0.001326 | import zipfile
try:
import zlib
COMPRESSION = zipfile.ZIP_DEFLATED
except:
COMPRESSION = zipfile.ZIP_STORED
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from django.core.files.uploadedfile import SimpleUploadedFile
class NotACompressedFile(Exception):
... | File(self.descriptor, mode='r')
except zipfile.BadZipfile:
raise NotACompressedFile
else:
test.close()
self.descriptor.seek(0)
self.zf = zipfile.ZipFile(s | elf.descriptor, mode='a')
def add_file(self, file_input, arcname=None):
try:
# Is it a file like object?
file_input.seek(0)
except AttributeError:
# If not, keep it
self.zf.write(file_input, arcname=arcname, compress_type=COMPRESSION)
else:
... |
geo-poland/frappe | frappe/patches/v4_0/set_todo_checked_as_closed.py | Python | mit | 191 | 0.041885 | import frappe
def execute(): |
frappe.reload_doc("core", "doctype", "todo")
try:
frappe.db.sql("""update tabToDo set status = if(ifn | ull(checked,0)=0, 'Open', 'Closed')""")
except:
pass
|
sbidoul/pip | tests/data/src/simplewheel-2.0/simplewheel/__init__.py | Python | mit | 20 | 0 | __ | version__ = "2.0"
| |
WPI-ARC/deformable_planners | deformable_astar/src/deformable_astar/robot_marker_debug_pub.py | Python | bsd-2-clause | 2,259 | 0.001771 | #!/usr/bin/env python
# Calder Phillips-Grafflin - WPI/ARC Lab
import rospy
import math
import tf
from tf.transformations import *
from visualization_msgs.msg import *
from geometry_msgs.msg import *
class RobotMarkerPublisher:
def __init__(self, root_frame, rate):
self.root_frame = root_frame
... |
p3 = Point()
p3.x = p1.x - 0.04
p3.y = p1.y
p3.z = p1.z
marker_msg.points = [p1, p2, p3]
marker_msg.colors = [marker_msg.color, marker_msg.color, marker_msg.color]
self.marker_pub.publish(marker_msg)
if __name__ == "__main__":
rospy.init_node("robot_marker_d... | marker broadcaster...")
#Get the parameters from the server
root_frame = rospy.get_param("~root_frame", "test_robot_frame")
rate = rospy.get_param("~rate", 10.0)
RobotMarkerPublisher(root_frame, rate)
|
CLVsol/clvsol_odoo_addons | clv_summary/__manifest__.py | Python | agpl-3.0 | 940 | 0 | # -*- coding: utf-8 -*-
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLV | sol
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
'name': 'Summary',
| 'summary': 'Summary Module used by CLVsol Solutions.',
'version': '12.0.4.0',
'author': 'Carlos Eduardo Vercelino - CLVsol',
'category': 'CLVsol Solutions',
'license': 'AGPL-3',
'website': 'https://github.com/CLVsol',
'images': [],
'depends': [
'clv_base',
'clv_global_log',
... |
tensorflow/model-remediation | tensorflow_model_remediation/min_diff/keras/utils/input_utils.py | Python | apache-2.0 | 18,202 | 0.003846 | # coding=utf-8
# Copyright 2022 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... | guments:
original_dataset: `tf.data.Dataset` that was used before applying min
diff. The output should conform to the format used in
`tf.keras.Model.fit`.
sensitive_group_dataset: `tf.data.Dataset` or valid MinDiff structure
(unnested dict) of `tf.data.Dataset`s containing only examples that
... | component for every batch should have the same
structure as that of the `original_dataset` batches' `x` components.
nonsensitive_group_dataset: `tf.data.Dataset` or valid MinDiff structure
(unnested dict) of `tf.data.Dataset`s containing only examples that do
**not** belong to the sensitive group... |
Ikaguia/LWBR-WarForge | module_scene_props.py | Python | unlicense | 133,561 | 0.056558 | # -*- coding: cp1252 -*-
from compiler import *
####################################################################################################################
# Each scene prop record contains the following fields:
# 1) Scene prop id: used for referencing scene props in other files. The prefix spr_ is automati... | ene_prop_animation_finished,
[
(store_trigger_param_1, ":instance_id"),
(prop_instance_enable_physics, ":instance_id", 1),
])
scene_props = [
("invalid_object",0,"question_mark","0", []),
("inventory",sokf_type_container|sokf_place_at_origin,"package","bobaggage", []),
("empty", 0, "0", "0", []),
("chest... | othic", []),
("container_small_chest",sokf_type_container,"package","bobaggage", []),
("container_chest_b",sokf_type_container,"chest_b","bo_chest_b", []),
("container_chest_c",sokf_type_container,"chest_c","bo_chest_c", []),
("player_chest",sokf_type_container,"player_chest","bo_player_chest", []),
("locked_playe... |
kjniemi/scylla | tools/scyllatop/userinput.py | Python | agpl-3.0 | 648 | 0 | import urwid
import logging
class UserInput(object):
def __init__(self):
self._viewMap = None
self._mainLoop = None
def setMap(self, ** viewMap):
self._viewMap = viewMap
def setLoop(self, loop):
self._mainLoop = loop
def __call__(self, keypress):
logging.debu... | Loop()
if type(keypress) is not str:
return
if keypress.upper() not in self._viewMap:
| return
view = self._viewMap[keypress.upper()]
self._mainLoop.widget = view.widget()
|
becxer/pytrain | pytrain/SVM/SVC.py | Python | mit | 1,018 | 0.007859 | #
# SVC (SVM Multi classifier)
#
# @ author becxer
# @ e-mail becxer87@gmail.com
#
import numpy as np
from pytrain.SVM import SVM
from pytrain.lib import convert
from pytrain.lib import ptmath
class SVC:
def __init__(self, mat_data, label_data):
self.x = np.mat(convert.list2npfloat(mat_data))
sel... | np.mat(np.sign(convert.list2npfloat(label_data) - 0.5))
self.outbit = self.ys.shape[1]
self | .svm4bit = []
for i in range(self.outbit):
self.svm4bit.append(SVM(self.x, self.ys[:,i]))
def fit(self, C, toler, epoch, kernel = 'Linear', kernel_params = {}):
for i in range(self.outbit):
self.svm4bit[i].fit(C, toler, epoch, kernel, kernel_params)
def ... |
lensacom/sparkit-learn | splearn/preprocessing/label.py | Python | apache-2.0 | 3,089 | 0 | import numpy as np
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing.label import _check_numpy_unicode_bug
from sklearn.utils import column_or_1d
from ..base import SparkBroadcasterMixin, SparkTransformerMixin
class SparkLabelEncoder(LabelEncoder, SparkTransformerMixin,
... | )
_check_numpy_unicode_bug(y)
return np.unique(y)
def reducer(a, b):
return np.unique(np.concatenate((a, b)))
self.classes_ = y.map(mapper).reduce(reducer)
return self
def fit_transform(self, y):
"""Fit label encoder and return encoded labels
... | ples]
Target values.
Returns
-------
y : ArrayRDD [n_samples]
"""
return self.fit(y).transform(y)
def transform(self, y):
"""Transform labels to normalized encoding.
Parameters
----------
y : ArrayRDD [n_samples]
Target... |
huangtao-sh/grace | grace/alembic/versions/3d30c324ed4_grace.py | Python | gpl-2.0 | 531 | 0.011299 | """grace
Revision ID: 3d30c324ed4
Revises: 8c78a916f1
Create Date: 2015-09-07 08:51:46.375707
"""
# revision identifiers, use | d by Alembic.
revision = '3d30c324ed4'
down_revision = '8c78a916f1'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
pass
### end Alembic commands ###
def downgrade():
### commands auto g... | Alembic commands ###
|
aniketpuranik/pynet_test | day2/ex15_exception.py | Python | apache-2.0 | 445 | 0.024719 | #!/ | usr/bin/env python
network_device = {
'ip_addr' : '81.1.1.3',
'username' : 'user1',
'passwd' : 'pass123',
'vendor' : 'cisco',
'model' : '3940',
}
for k,v in network_device.items():
print k,v
network_device['passwd']='newpass'
network_device['secret']='enable'
for k,v in network_device.it... | |
cydenix/OpenGLCffi | OpenGLCffi/GLES2/EXT/EXT/occlusion_query_boolean.py | Python | mit | 616 | 0.01461 | from OpenGLCffi.GLES2 import params
@params(api='gles2', prms=['n', 'ids'])
def glGenQueriesEXT(n, ids) | :
pass
@params(api='gles2', prms=['n', 'ids'])
def glDeleteQueriesEXT(n, ids):
pass
@params(api='gles2', prms=['id'])
def glIsQueryEXT(id):
pass
@params(api='gles2', prms=['target', 'id'])
def glBeginQueryEXT(targ | et, id):
pass
@params(api='gles2', prms=['target'])
def glEndQueryEXT(target):
pass
@params(api='gles2', prms=['target', 'pname', 'params'])
def glGetQueryivEXT(target, pname):
pass
@params(api='gles2', prms=['id', 'pname', 'params'])
def glGetQueryObjectuivEXT(id, pname):
pass
|
ARM-software/lisa | external/devlib/devlib/platform/gem5.py | Python | apache-2.0 | 12,624 | 0.00198 | # Copyright 2016-2018 ARM Limited
#
# 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 w... | eck that gem5 is ru | nning!
if self.gem5.poll():
message = "The gem5 process has crashed with error code {}!\n\tPlease see {} for details."
raise TargetStableError(message.format(self.gem5.poll(), self.stderr_file.name))
# Open the stderr file
with open(self.stderr_filena... |
fran-bravo/pylogic-module | test/test_case_operands.py | Python | mit | 666 | 0.004505 | import pytest, sys, os
sys.path.append(os.path.dirname(os.path.realpath(__file__)) + "/../")
from unittest import TestCase
from pylogic.case import Case
class TestBaseOperand(TestCase):
def test_eq_case(self):
case1 = Case("parent", "homer", "bart")
case2 = Case("parent", "homer", "bart")
... | se1 = Case("parent", "homer", "bart")
case2 = Case("parent", "homer", "lisa")
assert case1 != case2
def test_not_eq_case2(self):
case1 = Case("parent", "homer", "bart") |
case2 = Case("brother", "homer", "lisa")
assert case1 != case2
|
kevinschoon/prtgcli | test/test_cli.py | Python | apache-2.0 | 294 | 0 | import unittest
from prtgcli.cli import main
class TestQuery(un | ittest.TestCase):
def setUp(self):
pass
def test_list_devices(self):
pass
def test_list_sensors(self):
pass
| def test_status(self):
pass
def test_update(self):
pass
|
sstebbins/pppcpro | pppcemr/migrations/0123_auto_20160426_1253.py | Python | agpl-3.0 | 663 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-04-26 16:53
from __future__ import unicode_l | iterals
from django.db import migrations, mode | ls
class Migration(migrations.Migration):
dependencies = [
('pppcemr', '0122_auto_20160425_1327'),
]
operations = [
migrations.AddField(
model_name='treatment',
name='height_cm',
field=models.FloatField(blank=True, help_text='cm', null=True),
)... |
megatharun/basic-python-for-researcher | TempConv.py | Python | artistic-2.0 | 243 | 0.012346 |
# TempConv.py
# Celcius to Fahrein | heit
def Fahreinheit(temp):
temp = float(temp)
temp = (temp*9/5)+32
return temp
# Fahreinhe | it to Celcius
def Celcius(temp):
temp = float(temp)
temp = (temp-32)*5/9
return temp
|
zhouhan0126/SCREENTEST1 | tests/rtmplite/multitask.py | Python | gpl-2.0 | 41,396 | 0.002053 | ################################################################################
#
# Copyright (c) 2007 Christopher J. Stawarz
#
# 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 restri... | tice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHO... | 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 DEALINGS IN THE
# SOFTWARE.
#
################################################################################
"""
Cooperative multitasking... |
nickmckay/LiPD-utilities | Python/lipd/__init__.py | Python | gpl-2.0 | 38,558 | 0.002542 | from lipd.lipd_io import lipd_read, lipd_write
from lipd.timeseries import extract, collapse, mode_ts, translate_expression, get_matches
from lipd.doi_main import doi_main
from lipd.csvs import get_csv_from_metadata
from lipd.excel import excel_main
from lipd.noaa import noaa_prompt, noaa_to_lpd, lpd_to_noaa, noaa_prom... | lled from
logger_start = create_logger("start")
files = {".txt": [], ".lpd": [], ".xls": []}
return
def readLipd(usr_path="", remote_file_save=False):
"""
Read LiPD file(s).
Enter a file path, directory path, or leave args blank to trigger gui.
:param str usr_path: Path to file / directo... | settings["verbose"]:
__disclaimer(opt="update")
files[".lpd"] = []
__read(usr_path, ".lpd")
_d = __read_lipd_contents(usr_path, remote_file_save)
# Clear out the lipd files metadata. We're done loading, we dont need it anymore.
files[".lpd"] = []
except Exception... |
jakubroztocil/httpie | docs/packaging/spack/package.py | Python | bsd-3-clause | 1,904 | 0.003151 | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Httpie(PythonPackage):
"""Modern, user-friendly command-line HTTP client for the API era."... | epends_on('python@3.6:', when='@2.5:', type=('build', 'run'))
depends_on('py-setuptools', type=('build', 'run'))
depends_on('py-charset-normalizer@2:', when='@2.6:', type=('build', 'run'))
depends_on('py-defusedxml@0.6:', when='@2.5:', type=('build', 'run'))
depends_on('py-pygments@2.1.3:', type=('build... | e=('build', 'run'))
depends_on('py-requests@2.11:', type=('build', 'run'))
depends_on('py-requests@2.22:+socks', when='@2.5:', type=('build', 'run'))
depends_on('py-requests-toolbelt@0.9.1:', when='@2.5:', type=('build', 'run'))
# TODO: Remove completely py-argparse for HTTPie 2.7.0.
# Concretizatio... |
colinleefish/theotherbarn | vmware/serializers.py | Python | mit | 786 | 0.003817 | from vmware.models import VM, VMwareHost
from rest_framework import serializers
class VMSerializer(serializers.ModelSerializer):
class Meta:
model = VM
fields = ('name',
'moid',
'vcenter',
'host',
'instance_uuid',
... | 'state')
class VMWareHostSerializer(serializers.ModelSerializer):
baremetal = serializers.HyperlinkedRelatedField(many=False, | view_name='baremetal-detail', read_only=True)
class Meta:
model = VMwareHost
fields = ('name',
'ip_address',
'vcenter',
'baremetal',
'state') |
eliran-stratoscale/inaugurator | inaugurator/targetdevice.py | Python | apache-2.0 | 1,263 | 0.001584 | import os
import stat
import time
from inaugurator import sh
class TargetDevice:
_found = None
@classmethod
def device(cls, candidates):
if cls._found is None:
cls._found = cls._find(candidates)
return cls._found
pass
@classmethod
def _find(cls, candidates):
... | cannot continue: its likely the "
"the HD driver was not loaded correctly")
except:
pass
print "Found target device %s" % device
return device
print "didn't find target device, sleeping before retry %d" % retry
... | os.system("/usr/sbin/busybox mdev -s")
raise Exception("Failed finding target device")
|
jerynmathew/AssetManager | AssetManager/core/baseobject/models.py | Python | mit | 1,839 | 0.001631 | from django.db import models
from jsonfield import JSONField
from collections import OrderedDict
class BaseObject(models.Model):
"""
The base model from which all apps inherit
"""
# Type represents the app that uses it. Assets, Persons, Orgs, etc
type = models.CharField(max_length=256)
# Rel... | ():
property_set.append(BaseProperty(baseobject=baseobject, key=attr, value=value))
self.bulk_create(property_set)
class BaseProperty(models.Model):
"""
Key-Value attributes of objects are stored here.
"""
baseobject = models.ForeignKey(BaseObject)
key = models.CharField(max... | _length=256)
objects = BasePropertyManager()
def __unicode__(self):
"""Representation of field"""
return {self.baseobject.id: {self.key: self.value}}
class ProxyObject(BaseObject):
class Meta:
proxy = True
|
orlenko/bccf | src/mezzanine/generic/defaults.py | Python | unlicense | 4,223 | 0.000947 | """
Default settings for the ``mezzanine.generic`` app. Each of these can be
overridden in your project's settings module, just like regular
Django settings. The ``editable`` argument for each controls whether
the setting is editable via Django's admin.
Thought should be given to how a setting is actually used before
... | escription=_("If ``True``, users must log in to rate content "
"such as blog posts and comments."),
editable=True,
default=False,
)
register_setting(
name="RATINGS_RANGE",
description=_("A sequence of integers that are valid ratings."),
editable=False,
| default=range(getattr(settings, "RATINGS_MIN", 1),
getattr(settings, "RATINGS_MAX", 5) + 1),
)
|
bealdav/OpenUpgrade | addons/sale/report/sale_report.py | Python | agpl-3.0 | 5,204 | 0.002882 | # -*- 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 GNU... | 'date': fields.datetime('Date Order', readonly=True),
'date_confirm': fields.date('Date Confirm', readonly=True),
'product_id': fields.many2one('product.pro | duct', 'Product', readonly=True),
'product_uom': fields.many2one('product.uom', 'Unit of Measure', readonly=True),
'product_uom_qty': fields.float('# of Qty', readonly=True),
'partner_id': fields.many2one('res.partner', 'Partner', readonly=True),
'company_id': fields.many2one('res.compa... |
fbradyirl/home-assistant | script/lazytox.py | Python | apache-2.0 | 7,111 | 0.000422 | #!/usr/bin/env python3
"""
Lazy 'tox' to quickly check if branch is up to PR standards.
This is NOT a tox replacement, only a quick check during development.
"""
import os
import asyncio
import sys
import re
import shlex
from collections import namedtuple
try:
from colorlog.escape_codes import escape_codes
except... | line = await stream.readline()
if not line:
break
output.append(line)
display(line.decode()) # assume it doesn't block
return b"".join(output)
async def as | ync_exec(*args, display=False):
"""Execute, return code & log."""
argsp = []
for arg in args:
if os.path.isfile(arg):
argsp.append("\\\n {}".format(shlex.quote(arg)))
else:
argsp.append(shlex.quote(arg))
printc("cyan", *argsp)
try:
kwargs = {
... |
matthew-Ng/sol | exp_sol/sol_shuffle.py | Python | gpl-3.0 | 626 | 0.003195 | #!/usr/bin/env python
"""shuffle a dataset"""
import random
import sys
def sol_shuffle(filename, out_filename):
try:
file = open(filena | me, 'rb')
lines = file.readlines()
if len(lines) == 0:
| print 'empty file'
file.close()
sys.exit()
if lines[-1][-1] != '\n':
lines[-1]+='\n'
random.shuffle(lines)
wfile = open(out_filename, 'wb')
wfile.writelines(lines)
wfile.close()
except IOError as e:
print "I/O error ({0}): {1}... |
cmdunkers/DeeperMind | RuleLearner/RuleLearner.py | Python | bsd-3-clause | 974 | 0.002053 | import abc
class RuleLearner:
"""2D 2-person board game rule learner base class
TODO
"""
def __ | init__(self, board_height, board_width):
"""Initialize the rule learner
Subclasses should call this constructor.
:type board_height: positive integer
:param board_height: the height (number of rows) of the board
:type board_width: positive integer
:param board_width: t... | thod
def get_valid_moves(self, board):
"""Get the valid moves for the board.
:type board: Boards.Board
:param board: the board for which to determine the valid moves
:returns: a 2D Numpy array with the same dimensions as the board contains, the cells where moves are valid set
... |
kdart/pycopia | core/pycopia/OS/Linux/proc/devices.py | Python | apache-2.0 | 1,668 | 0.002398 | #!/usr/bin/python2.7
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
... | self._charmap = {}
self._blockmap = {}
for line in fo.readlines():
if line.startswith("Character"):
curmap = self._charmap
continue
elif line.startswith("Block"):
curmap = self._blockmap
continue
elif l... | devices:"]
for num, fmt in self._charmap.items():
s.append("%3d %s" % (num, fmt))
s.append("\nBlock devices:")
for num, fmt in self._blockmap.items():
s.append("%3d %s" % (num, fmt))
return "\n".join(s)
def get_device(self, dtype, major, minor):
pas... |
osuripple/ripple | c.ppy.sh/matchReadyEvent.py | Python | mit | 370 | 0.035135 | imp | ort glob
def handle(userToken, _):
# Get usertoken data
userID = userToken.userID
# Make sure the match exists
matchID = userToken.matchID
if matchID not in glob.matches.matches:
| return
match = glob.matches.matches[matchID]
# Get our slotID and change ready status
slotID = match.getUserSlotID(userID)
if slotID != None:
match.toggleSlotReady(slotID)
|
ActiveState/code | recipes/Python/528949_Copying_Generators/recipe-528949.py | Python | mit | 3,934 | 0.008897 | ###
#
# W A R N I N G
#
# This recipe is obsolete!
#
# When you are looking for copying and pickling functionality for generators
# implemented in pure Python download the
#
# generator_tools
#
# package at the cheeseshop or at www.fiber-space.de
#
###
import new
import copy
imp... | running generator object f provides following important
information about the state of the generator:
- the values of bound locals inside the generator object
- the last bytecode being executed
This state information of f is restored in a new function g | enerator g in the following way:
- the signature of g is defined by the locals of f ( co_varnames of f ). So we can pass the
locals to g inspected from the current frame of running f. Yet unbound locals are assigned
to None.
All locals will be deepcopied. If one of th... |
weirdgiraffe/plugin.video.giraffe.seasonvar | resources/site-packages/kodi/__init__.py | Python | mit | 3,703 | 0 | # coding: utf-8
#
# Copyright © 2017 weirdgiraffe <giraffe@cyberzoo.xyz>
#
# Distributed under terms of the MIT lic | ense.
#
import sys
try: # real kodi
import xbmc
import xbmcaddon
import xbmcgui
import xbmcplugin
except ImportError: # mocked kodi
from mock_kodi import xbmc
from mock_kodi import xbmcaddon
from mock_kodi import xbmcgui
| from mock_kodi import xbmcplugin
try: # python2
from urllib import urlencode
from urlparse import urlparse, parse_qs
except ImportError: # python3
from urllib.parse import urlparse, parse_qs, urlencode
class logger:
@staticmethod
def debug(s):
xbmc.log(s, xbmc.LOGDEBUG)
@static... |
ashang/calibre | src/calibre/web/feeds/recipes/model.py | Python | gpl-3.0 | 14,130 | 0.002052 | #!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import with_statement
__license__ = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import copy, zipfile
from PyQt5.Qt import QAbstractItemModel, Qt, QColor, QFont, QI... | cipe_collection,
self.custom_recipe_collection, self.scheduler_config,
parent]
return cls(*args)
def ok(urn):
if restrict_to_urns is None:
| return False
return not restrict_to_urns or urn in restrict_to_urns
new_root = factory(NewsTreeItem, None)
scheduled = factory(NewsCategory, new_root, _('Scheduled'))
custom = factory(NewsCategory, new_root, _('Custom'))
lang_map = {}
self.all_urns = set([])
... |
lercloud/shipping_api_usps | stock_packages.py | Python | gpl-3.0 | 3,338 | 0.004494 | ##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2011 NovaPoint Group LLC (<http://www.novapointgroup.com>)
# Copyright (C) 2004-2010 OpenERP SA (<http://www.openerp.com>)
#
# This program is free software: you can re... | URPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License |
# along with this program. If not, see <http://www.gnu.org/licenses/>
#
##############################################################################
from openerp.osv import fields, osv
from openerp.tools.translate import _
from . import api
class stock_packages(osv.osv):
_inherit = "stock.packages"
de... |
bmcculley/splinter | splinter/meta.py | Python | bsd-3-clause | 954 | 0.001048 | # -*- coding: utf-8 -*-
# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
class InheritedDocs(type):
def __new__(mcs, class_name, bases, dict):
items_to_patch = [
(k, v) for k, v in dic... | obj.fget.__doc__ = doc
dict[name] = property(fget=obj.fget)
el | se:
obj.__doc__ = doc
break
return type.__new__(mcs, class_name, bases, dict)
|
bhupennewalkar1337/erpnext | erpnext/hr/doctype/leave_control_panel/leave_control_panel.py | Python | gpl-3.0 | 1,939 | 0.025271 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils import cint, cstr, flt, nowdate, comma_and, date_diff
from frappe import msgprint, _
from frappe.model.document import ... | yee found"))
for d in self.get | _employees():
try:
la = frappe.new_doc('Leave Allocation')
la.set("__islocal", 1)
la.employee = cstr(d[0])
la.employee_name = frappe.db.get_value('Employee',cstr(d[0]),'employee_name')
la.leave_type = self.leave_type
la.from_date = self.from_date
la.to_date = self.to_date
la.carry_for... |
naoyat/latin | latin/latindic.py | Python | mit | 1,985 | 0.010106 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import latin_noun
import latin_pronoun
import latin_adj
import latin_conj
import latin_prep
import latin_verb_reg
import latin_verb_irreg
import util
class LatinDic:
dic = {}
auto_macron_mode = False
def flatten(text):
return text.replace(u'ā',u'a').replac... | u'i').replace(u'ō',u'o').replace(u'ū',u'u').replace(u'ȳ',u'y').lower()
def register(surface, info):
if not info.has_key('pos'): return
if LatinDic.auto_macron_mode:
surface = flatten(surface)
if LatinDic.dic.has_key(surface):
LatinDic.dic[surface].append(info)
else:
LatinDic.... | )
def lookup(word):
return LatinDic.dic.get(word, None)
def dump():
for k, v in LatinDic.dic.items():
print util.render2(k, v)
def load_def(file, tags={}):
items = []
with open(file, 'r') as fp:
for line in fp:
if len(line) == 0: continue
if line[0] == '#':... |
elweezy/django-skeleton | app/blog/views.py | Python | gpl-3.0 | 4,187 | 0.002627 | from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
from django.db import IntegrityError
from django.shortcuts import render, redirect
from django.contrib import messages
from django import forms as django_forms
from django.views.decorators.cache import cache_page
from django... | user/blog/search.html', context={}):
blog_logic = logic.BlogLogic(request)
term = blog_logic.get_param("term")
| search_result = blog_logic.search(term)
context['term'] = term
context['pages'] = search_result.pages
context['posts'] = search_result.posts
return render(request, template, context)
@log
def subscribe(request):
blog_logic = logic.BlogLogic(request)
name = blog_logic.get_param("name")
... |
calidae/python-aeat_sii | src/pyAEATsii/callback_utils.py | Python | apache-2.0 | 918 | 0 |
__all__ = [
'fixed_value',
'coalesce',
]
try:
from itertools import ifilter as filter
except ImportError:
pass
class _FixedValue(object):
def __init__(self | , value):
self._value = value
def __call__(self, *args, **kwargs):
return self._value
def fixed_value(value):
return _FixedValue(value)
class _Coalesce(object):
def _filter(self, x):
return x is not None
def __init__(self, callbac | ks, else_=None):
self._callbacks = callbacks
self._else = else_
def __call__(self, invoice):
results = (
callback(invoice)
for callback in self._callbacks
)
try:
return next(filter(
self._filter, results
))
... |
schriftgestalt/Mekka-Scripts | Font Info/Set Preferred Names (Name IDs 16 and 17).py | Python | apache-2.0 | 1,956 | 0.027607 | #MenuTitle: Set Preferred Names (Name IDs 16 and 17) for Width Variants
# -*- coding: utf-8 -*-
__doc__="""
Sets Preferred Names custom parameters (Name IDs 16 and 17) for all instances, so that width variants will appear in separate menus in Adobe apps.
"""
thisFont = Glyphs.font # frontmost font
widths = (
"Narrow"... | sed", "Ultra Compressed",
"Extended", "Semiextended", "Semi Extended", "Extraextended", "Extra Extended", "Ultraextended", "Ultra Extended",
"Expanded", "Semiexpanded", "Semi Expanded", "Extraexpanded", "Extra Expanded", "Ultraexpanded", "Ultra Expanded",
"Wide", "Semiwide", "Semi Wide", "Extrawide", "Extra Wide"... | a Wide",
)
for thisInstance in thisFont.instances:
print "Processing Instance:", thisInstance.name
familyName = thisFont.familyName
if thisInstance.customParameters["familyName"]:
familyName = thisInstance.customParameters["familyName"]
widthVariant = None
for width in widths:
if width in thisInstance.name... |
smtpinc/sendapi-python | lib/smtpcom/config.py | Python | mit | 1,148 | 0.003484 | import os
import yaml
DEFAULT_DIR = '../etc/'
class BaseConfig(object):
__config = {}
__default_dir = None
@classmethod
def load(cls, filename, default_path=DEFAULT_DIR):
"""
Setup configuration
"""
path = "%s/%s.yaml" % (default_path, filename)
cls.__default_... | ef get(cls, key, value=None):
if key in cls.__config:
return cls.__config.get(key, value)
return cls.__config.get(key.upper(), value)
@classmethod
def get_url(cls, method):
url = cls.__config.get('urls', {}).get(method)
if not url:
raise ValueError("C | ould not find url for method: %s" % method)
return Config.get('api_host') + url
Config = BaseConfig()
|
jajberni/pcse_web | main/pcse/crop/partitioning.py | Python | apache-2.0 | 12,949 | 0.005638 | # -*- coding: utf-8 -*-
# Copyright (c) 2004-2014 Alterra, Wageningen-UR
# Allard de Wit (allard.dewit@wur.nl), April 2014
from collections import namedtuple
from math import exp
from ..traitlets import Float, Int, Instance, AfgenTrait
from ..decorators import prepare_rates, prepare_states
from ..base_classes import P... | ()
def calc_rates(self, day, drv):
""" Return partitioning factors based on current DVS.
"""
# rate calculation does nothing for partioning as it is a de | rived
# state
return self.states.PF
class DVS_Partitioning_NPK(SimulationObject):
"""Class for assimilate partitioning based on development stage (`DVS`)
with influence of NPK stress.
`DVS_Partitioning_NPK` calculates the partitioning of the assimilates to roots,
stems, leaves and sto... |
jordanemedlock/psychtruths | temboo/core/Library/Amazon/SNS/__init__.py | Python | apache-2.0 | 2,012 | 0.006461 | from temboo.Library.Amazon.SNS.AddPermission import AddPermission, AddPermissionInputSet, AddPermissionResultSet, AddPermissionChoreographyExecution
from temboo.Library.Amazon.SNS.ConfirmSubscription import ConfirmSubscription, ConfirmSubscriptionInputSet, ConfirmSubscriptionResultSet, ConfirmSubscriptionChoreographyEx... | InputSet, CreateTopicResultSet, CreateTopicChoreographyExecution
from temboo.Library.Amazon.SNS.DeleteTopic import DeleteTopic, DeleteTopicInputSet, DeleteTopicResultSet, DeleteTop | icChoreographyExecution
from temboo.Library.Amazon.SNS.GetTopicAttributes import GetTopicAttributes, GetTopicAttributesInputSet, GetTopicAttributesResultSet, GetTopicAttributesChoreographyExecution
from temboo.Library.Amazon.SNS.ListSubscriptions import ListSubscriptions, ListSubscriptionsInputSet, ListSubscriptionsRes... |
anthropo-lab/XP | EPHEMER/EDHEC_Project/both_change_group_en/consumers.py | Python | gpl-3.0 | 13,913 | 0.004313 | from channels import Group as channelsGroup
from channels.sessions import channel_session
import random
from .models import Group as OtreeGroup, Subsession as OtreeSubsession, Constants
import json
import channels
import logging
from otree import constants_internal
import django.test
from otree.common_internal import ... | & (p.participant._round_number == round_nb)):
p.participant.vars['active_flag'] = 'inactive'
| p.participant.save()
elif order == "reactivate_all |
peterhinch/micropython-async | v2/i2c/i2c_esp.py | Python | mit | 2,245 | 0.001336 | # i2c_esp.py Test program for asi2c.py
# Tests Responder on ESP8266
# The MIT License (MIT)
#
# Copyright (c) 2018 Peter Hinch
#
# 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 restr... | WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDIN | G BUT NOT LIMITED TO THE WARRANTIES 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 TH... |
steeve/plugin.video.pulsar | resources/site-packages/pulsar/logger.py | Python | bsd-3-clause | 680 | 0.002941 | # Borrowed and modified from xbmcswift
import log | ging
import xbmc
from pulsar.addon import ADDON_ID
class XBMCHandler(logging.StreamHandler):
xbmc_levels = {
'DEBUG': 0,
'INFO': 2,
'WARNING': 3,
'ERROR': 4,
'LOGCRITICAL': 5,
}
def emit(self, record):
xbmc_level = self.xbmc_levels.get(record.levelname)
... | ndler.setFormatter(logging.Formatter('[%(name)s] %(message)s'))
logger.addHandler(handler)
return logger
log = _get_logger()
|
blueboxgroup/ansible | lib/ansible/executor/playbook_executor.py | Python | gpl-3.0 | 11,134 | 0.004581 | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible 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) an... | f any errors are fatal. If either of those
# conditions are met, we break out, otherwise we only break out if the entire
# batch failed
failed_hosts_count = len(self._tqm._failed_hosts) + len(self._tqm._unreachable_hosts)
... | _hosts_count) / len(batch) * 100.0):
break
elif len(batch) == failed_hosts_count:
break
# clear the failed hosts dictionaires in the TQM for the next batch
self._unreachab... |
richard-fisher/repository | desktop/util/tint2/actions.py | Python | gpl-2.0 | 263 | 0.019011 |
#!/ | usr/bin/python
from pisi.actionsapi import shelltools, get, cmaketools, pisitools
def setup():
cmaketools.configure()
def build | ():
cmaketools.make()
def install():
cmaketools.install()
pisitools.dodoc ("AUTHORS", "ChangeLog", "COPYING")
|
Shopzilla-Ops/python-coding-challenge | cost-of-tile/mjones/tilecost/setup.py | Python | mit | 998 | 0 | import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
READ | ME = open(os.path.join(here, 'README.txt')).read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()
requires = [
'pyramid',
'pyramid_debugtoolbar',
'waitress',
]
setup(name='tilecost',
version='0.0',
description='tilecost',
long_description=README + '\n\n' + CHANGES,
cl... | Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
],
author='',
author_email='',
url='',
keywords='web pyramid pylons',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=requires,
tests_require=requires,
test_su... |
allspatial/vertex-tools | controller/VertexDialog.py | Python | mit | 550 | 0.001818 | __author__ = 'mwagner'
from PyQt4.Qt import Qt
from PyQt4.QtGui import QDialog | , QIcon
from ..view.Ui_VertexDialog import Ui_VertexDialog
from ..model.VertexToolsError import *
class VertexDialog(QDialog, Ui_VertexDialog):
def __init__(self, plugin, parent=None):
super(VertexDialog, self).__init__(parent)
self.setAttribute(Qt.WA_DeleteOnClose)
self.plugin = plugi... | self.setWindowIcon(QIcon(":beninCad/info.png")) |
kanghtta/zerorpc-python | tests/test_client.py | Python | mit | 1,919 | 0.002606 | # -*- coding: utf-8 -*-
# Open Source Initiative OSI - The MIT License (MIT):Licensing
#
# The MIT License (MIT)
# Copyright (c) 2012 DotCloud Inc (opensource@dotcloud.com)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Softwa... | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import gevent
import zerorpc
from testutils import teardown, random_ipc_endpoint
def test_client_connect():
endpoint = random_ipc_endpoint()
class MySrv(zerorpc.Server):
d | ef lolita(self):
return 42
srv = MySrv()
srv.bind(endpoint)
gevent.spawn(srv.run)
client = zerorpc.Client()
client.connect(endpoint)
assert client.lolita() == 42
def test_client_quick_connect():
endpoint = random_ipc_endpoint()
class MySrv(zerorpc.Server):
def l... |
dzhang55/riftwatch | static_images.py | Python | mit | 1,397 | 0.027917 | import json
import requests
import key
API_key = key.getAPIkey()
#load all champion pictures
def load_champion_pictures(champion_json):
print len(champion_json['data'])
version = champion_json['version']
print "version: " + version
for champion in champion_json['data']:
print champion
r = requests.get('http:... | and json.dump() for error checking
def load_champion_json():
try:
r = requests.get('https://global.api.pvp.net/api/lol/static-data/na/v1.2/champion?&api_key=' | + API_key)
champion_json = r.json()
if 'status' in champion_json:
print champion_json['status']['message']
return
load_champion_pictures(champion_json)
# quick fix to change MonkeyKing to Wukong so that sort_keys sorts it properly
champion_json['data']['Wukong'] = champion_json['data']['MonkeyKing']
... |
ferdinandvwyk/gs2_analysis | structure_analysis.py | Python | gpl-2.0 | 4,637 | 0.009273 | # Standard
import os
import sys
# Third Party
import numpy as np
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import seaborn as sns
import pyfilm as pf
from skimage.measure import label
from skimage import filters
plt.rcParams.update({'figure.autolayout': True})
mpl.rcParams['axes.unicode_mi... | ()
plt.plot(no_structures)
plt.xlabel('Time index')
plt.ylabel('Number of structures')
plt.ylim(0)
plt.savefig(run.run_dir + 'analysis/structures_' + str(perc_thresh) +
'/nblobs.pdf')
def save_results(run, no_structures, perc_thresh):
"""
Save the number of structures as a f... | 'analysis/structures_' + str(perc_thresh) +
'/nblobs.csv', np.transpose((range(run.nt), no_structures)),
delimiter=',', fmt='%d', header='t_index,nblobs')
def make_film(run, no_structures, labelled_image, perc_thresh):
titles = []
for it in range(run.nt):
titles.append('N... |
ciudadanointeligente/popit-django | runtests.py | Python | agpl-3.0 | 621 | 0.008052 | #!/usr/bin/env python
# This file mainly exists to allow python setup.py test to work.
#
# You can test all the variations of tests by running:
#
# ./manage.py test && python runtests.py && ./setup.py test && echo OK
#
import os, sys
os | .environ['DJANGO_SETTINGS_MODULE'] = 'test_settings'
from django.core.management import call_command
def runtests():
# use the call_command approach so that we are as similar to running
# './manage.py test' as possible. Notably we need the South migrations to be
# run.
call_command('test', v | erbosity=2)
sys.exit(0)
if __name__ == '__main__':
runtests()
|
pombredanne/invenio-old | modules/bibclassify/lib/bibclassify_webinterface.py | Python | gpl-2.0 | 14,432 | 0.004088 | # This file is part of CDS Invenio.
# Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008 CERN.
#
# CDS Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your... | keyword = subfield[1]
keywords[bor.KeywordToken(keyword, type=type)] = [[(0,0)]]
break
return found, | keywords, rec
def generate_keywords(req, recid, argd):
"""Extracts keywords from the fulltexts (if found) for the
given recid. It first checks whether the keywords are not already
stored in the temp file (maybe from the previous run).
@var req: req object
@var recid: record id
@var argd: argume... |
gmr/mredis | tests/general.py | Python | bsd-3-clause | 795 | 0.003774 | #!/usr/bin/env python
import mredis
import time
ports = [6379, 6380]
servers = []
for port in ports:
servers.append({'host': 'localhost', 'port': port, 'db': 0})
mr = mredis.MRedis(servers)
# Destructive test of the d | atabase
#print mr.flushall()
#print mr. | flushdb()
print mr.ping()
# Build a set of keys for operations
keys = set()
for x in xrange(0, 100):
key = 'key:%.8f' % time.time()
keys.add(key)
for key in keys:
mr.set(key, time.time())
fetched = mr.keys('key:*')
results = []
for server in fetched:
for key in fetched[server]:
results.append... |
ercas/scripts | weather.py | Python | apache-2.0 | 3,411 | 0.017014 | #!/usr/bin/python3
import argparse, random, textwrap
from datetime import datetime
from urllib import request
from xml.etree import ElementTree
labels = {
"clouds": "%",
"humidity": "%",
"precipitation": "%",
"temp": "°F",
"wind-direction": "°",
"wind-speed": " mph",
}
parser = argparse.Argume... | ,
type = float)
parser.add_argument("longitude",
help = "longitude of location",
type = float)
args = parser.parse_args()
def print_weather(latitude, longitude):
# weather.gov provides two xml files: digitalDWML and dwml.
# digitalDWML includes detailed, 24-hour forecast data for the n... | ludes simple data for the current day as well as text and icons.
# in this script, digitalDWML is referred to as "detailed" and dwml is
# referred to as "simple".
weather_detailed_xml = request.urlopen("http://forecast.weather.gov/MapClick.php?lat="
+ str(latitude) + "&lon=" + str(longitude)
... |
pmeier82/spike_gnode | base/storage.py | Python | bsd-3-clause | 2,381 | 0.00126 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import errno
import hashlib
import os
from django.conf import settings
from django.core.files import File
from django.core.files.storage import Fil | eSystemStorage
from django.utils.encoding import force_unicode
__all__ = ["HashedFileSystemStorage"]
__author__ = "pmeier82"
class ContentExists(Exception):
pass
class HashedFileSystemStorage(FileSystemStorage):
"""`FileSystemStorage` subcla | ss that manages file names by content hashes"""
def get_available_name(self, name):
raise ContentExists()
def _get_content_name(self, name, content, chunk_size=None):
dir_name = os.path.split(name)[0]
file_name = self._generate_hash(content=content, chunk_size=chunk_size)
retur... |
kevinconway/rpmvenv | rpmvenv/extensions/blocks/__init__.py | Python | mit | 199 | 0 | """Extensions w | hich provide a block segments."""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unic | ode_literals
|
nalabelle/druid-django | frontend/views.py | Python | mit | 1,868 | 0.002677 | from django.shortcuts import render, get_object_or_404
from django.views import generic
from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader
from rest_framework import reverse
from druidapi.query.models import QueryModel
from models import Result
from forms import SearchForm
imp... | of cheating, ideally the html would handle this
# | but, I felt like building the webapp in django...
# alternatively, I could just reach over and build this.
start = form.cleaned_data['start'].isoformat()
end = form.cleaned_data['end'].isoformat()
# POST the query and return the pk, so we can look it up later
... |
catapult-project/catapult | third_party/ijson/tests.py | Python | bsd-3-clause | 8,608 | 0.002679 | # -*- coding:utf-8 -*-
from __future__ import unicode_literals
import unittest
from io import BytesIO, StringIO
from decimal import Decimal
import threading
from importlib import import_module
from ijson import common
from ijson.backends.python import basic_parse, Lexer
from ijson.compat import IS_PY2
JSON = b'''
{
... | d.join()
def test_scalar(self):
events = list(self.backend.basic_parse(BytesIO(SCALAR_JSON)))
self.assertEqual(events, [('number', 0)])
def test_strings(self):
events = list(self.backend.basic_parse(BytesIO(STRINGS_JSON)))
strings = [value for event, value in events if event ==... | lf):
event = next(self.backend.basic_parse(BytesIO(SURROGATE_PAIRS_JSON)))
parsed_string = event[1]
self.assertEqual(parsed_string, '💩')
def test_numbers(self):
events = list(self.backend.basic_parse(BytesIO(NUMBERS_JSON)))
types = [type(value) for event, value in events if... |
shoaibali/kodi.background.rotator | randombackground.py | Python | gpl-3.0 | 713 | 0.026648 | import os, random
rfilename=random.choice(os.listdir("/storage/pictures" | ))
rextension=os.path.splitext(rfilename)[1]
picturespath='/storage/pictures/'
#TODO Probably dont need a forloop can possibly do random*
#TODO What if the directory is empty?
for filename in os.listdir(p | icturespath):
if filename.startswith("random"):
extension=os.path.splitext(filename)[1]
newname=picturespath + str(random.random()).rsplit('.',1)[1] + extension
# rename the existing random wallpaper to something random
filename=picturespath+filename
os.rename(filename, newname)
# now rename the newly randoml... |
RyanNoelk/OpenEats | api/v1/recipe/migrations/0011_auto_20171114_1543.py | Python | mit | 466 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2017-11-14 21:43
from __future__ import unicode_litera | ls
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('recipe', '0010_auto_20171114_1443'),
]
operations = [
migrations.RemoveField(
| model_name='direction',
name='recipe',
),
migrations.DeleteModel(
name='Direction',
),
]
|
rahlk/CSC579__Computer_Performance_Modeling | simulation/proj1/tasks/task5.py | Python | mit | 2,063 | 0.010664 | from __future__ import division
from __future__ import print_function
import os
import sys
import functools
# Update path
root = os.path.join(os.getcwd().split('proj1')[0], 'proj1')
if root not in sys.path:
sys.path.append(root)
import numpy as np
import pandas as pd
import multiprocessing
from pdb import set_tra... | l=r"$\rho$", y_label=r"Run Times", the_title=r"$\mathrm{Run\ Times\ in\ }\mu\mathrm{s\ vs.\ }\rho$")
def plot_runtime_vs_avg | (x, y, y_1):
line2(x, y, x, y_1, label_1="Actual Runtimes", label_2="Expected value of $\rho$", x_label=r"$\rho$", y_label=r"Run Times", the_title=r"$\mathrm{Run\ Times\ in\ }\mu\mathrm{s\ vs.\ }\rho$")
def task_5():
rho_list = np.arange(0.05, 1, 0.1)
C = 1e5
elapsed = []
for rho in rho_list:
... |
schleichdi2/OPENNFR-6.1-CORE | opennfr-openembedded-core/meta/lib/oeqa/core/decorator/data.py | Python | gpl-2.0 | 2,959 | 0.004055 | # Copyright (C) 2016 Intel Corporation
# Released under the MIT license (see COPYING.MIT)
from oeqa.core.exception import OEQAMissingVariable
from . im | port OETestDecorator, registerDecorator
def has_feature(td, feature):
"""
Checks for featur | e in DISTRO_FEATURES or IMAGE_FEATURES.
"""
if (feature in td.get('DISTRO_FEATURES', '') or
feature in td.get('IMAGE_FEATURES', '')):
return True
return False
@registerDecorator
class skipIfDataVar(OETestDecorator):
"""
Skip test based on value of a data store's variable.
... |
vlegoff/tsunami | src/secondaires/navigation/equipage/signaux/__init__.py | Python | bsd-3-clause | 2,386 | 0 | # -*-coding:Utf-8 -*
# Copyright (c) 2010-2017 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# ... | y 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 EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE F... |
ruyang/ironic | ironic/tests/unit/drivers/modules/network/test_neutron.py | Python | apache-2.0 | 19,670 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | self.interface.port_changed(task, port)
mock_p_changed.assert_called_once_with(task, port)
def test_init_incorrect_provisioning_net(self):
self.config(provisioning_network=None, group='neutron')
self.assertRaises(exception.DriverLoadError, neutron.NeutronNetwork)
self.config(p... | n')
self.assertRaises(exception.DriverLoadError, neutron.NeutronNetwork)
@mock.patch.object(neutron_common, 'validate_network', autospec=True)
def test_validate(self, validate_mock):
with task_manager.acquire(self.context, self.node.id) as task:
self.interface.validate(task)
... |
Athrun29/horizon | openstack_dashboard/dashboards/project/firewalls/tables.py | Python | apache-2.0 | 15,142 | 0 | # Copyright 2013, Big Switch Networks, 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 applic... | d. See the
# License for the specific language governing permissions and limitations
# under the License.
import logging
from django.core.urlresolvers import reverse
from django.template import defa | ultfilters as filters
from django.utils.translation import pgettext_lazy
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ungettext_lazy
from horizon import exceptions
from horizon import tables
from openstack_dashboard import api
from openstack_dashboard import policy
LOG ... |
e-koch/canfar_scripts | img_pipe/casanfar_image.py | Python | mit | 7,517 | 0.000133 | import os
import numpy as np
from scipy.optimize import curve_fit
def gauss(x, A, mu, sigma):
return A * np.exp(-(x - mu)**2 / (2. * sigma**2))
scriptmode = True
SDM_name = 'test' # The prefix to use for all output files
# SDM_name = '13A-213.sb20685305.eb20706999.56398.113012800924'
# Set up some useful var... | 0:
pnum = pnum / 3
while pnum % 5 == 0:
pnum = pnum / 5
print "Image size:", sel_imsize
print "Cell | size:", sel_cell
# First generate a 0-iterations
# image to estimate the noise level
# (threshold)
default('clean')
vis = vos_proc + contsubms
imagename = vos_proc + rawcleanms
cell = [sel_cell, sel_cell]
imsize = [sel_imsize, sel_imsize]
imagermode = imagermode
mode = "channel"
nchan = 4
start = chan1 - 5
width = 1... |
incuna/authentic | authentic2/saml/migrations/0010_auto__add_field_spoptionsidppolicy_enabled.py | Python | agpl-3.0 | 22,083 | 0.007472 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'SPOptionsIdPPolicy.enabled'
db.add_column('saml_spoptionsidppolicy', 'enabled', self.gf('d... | Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
| },
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ... |
tjcsl/ion | intranet/apps/dataimport/apps.py | Python | gpl-2.0 | 109 | 0 | from django.apps impor | t AppConfig
class DataimportConfig(AppConfig):
name | = "intranet.apps.dataimport"
|
eustislab/horton | data/examples/hamiltonian/even_tempered_li.py | Python | gpl-3.0 | 725 | 0 | #!/usr/bin/env python
import numpy as np
from horton import *
# specify the even tempered basis set
alpha_low = 5e-3
alpha_high = 5e2 |
nbasis = 30
lnratio = (np.log(alpha_high) - np.log(alpha_low))/(nbasis-1)
# build a list of "contra | ctions". These aren't real contractions as every
# contraction only contains one basis function.
bcs = []
for ibasis in xrange(nbasis):
alpha = alpha_low**lnratio
# arguments of GOBasisContraction:
# shell_type, list of exponents, list of contraction coefficients
bcs.append(GOBasisContraction(0, np.... |
engineer0x47/SCONS | engine/SCons/Variables/PathVariable.py | Python | mit | 5,616 | 0.00089 | """SCons.Variables.PathVariable
This file defines an option type for SCons implementing path settings.
To be used whenever a a user-specified path override should be allowed.
Arguments to PathVariable are:
option-name = name of this option on the command line (e.g. "prefix")
option-help = help string for optio... | m = 'File path for option %s is a directory: %s'
else:
m = 'File path for option %s d | oes not exist: %s'
raise SCons.Errors.UserError(m % (key, val))
def PathExists(self, key, val, env):
"""validator to check if Path exists"""
if not os.path.exists(val):
m = 'Path for option %s does not exist: %s'
raise SCons.Errors.UserError(m % (key, val))
... |
bitcraft/pyglet | contrib/experimental/input/xinput.py | Python | bsd-3-clause | 9,260 | 0 | # ----------------------------------------------------------------------------
# Copyright (c) 2008 Andrew D. Straw and Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistr... | stance.dispatch_event(*args)
@pyglet.window.xlib.XlibEventHandler(0)
def _event_xinput_key_press(self, ev):
raise NotImplementedError('TODO')
@pyglet.window.xlib.XlibEventHandler(0)
def _event_xinput_key_release(self, ev):
raise NotImplementedError('TODO')
@pyglet.window.xlib.Xlib... | vent_xinput_button_press(self, ev):
e = ctypes.cast(ctypes.byref(ev),
ctypes.POINTER(xi.XDeviceButtonEvent)).contents
self.dispatch_instance_event(e, 'on_button_press', e.button)
@pyglet.window.xlib.XlibEventHandler(0)
def _event_xinput_button_release(self, ev):
... |
clemsos/mitras | tests/examples/kmeans.py | Python | mit | 2,846 | 0.001054 | # Author: Peter Prettenhofer <peter.prettenhofer@gmail.com>
# Lars Buitinck <L.J.Buitinck@uva.nl>
# License: Simplified BSD
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn import metrics
from sklearn.cluster import KMeans, MiniBatchKMean... | orizer.fit_transform(dataset.data)
print "done in %fs" % (time() - t0)
print "n_samples: %d, n_features: %d" % X.shape
print
###############################################################################
# Do the actual clustering
if opts.minibatch:
km = MiniBatchKMeans(n_clusters=true_k, init='k-means++', n_i... | init_size=1000,
batch_size=1000, verbose=1)
else:
km = KMeans(n_clusters=true_k, init='random', max_iter=100, n_init=1, verbose=1)
print "Clustering sparse data with %s" % km
t0 = time()
km.fit(X)
print "done in %0.3fs" % (time() - t0)
print
print "Homogeneity: %0.3f" % metri... |
apache/incubator-superset | tests/unit_tests/fixtures/datasets.py | Python | apache-2.0 | 6,514 | 0 | # 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... | "id": 510,
"column_name": "num_girls",
| "verbose_name": None,
"description": None,
"expression": "",
"filterable": False,
"groupby": False,
"is_dttm": False,
"type": "BIGINT(20)",
}
),
get_column_mock(
{
... |
Stracksapp/stracks_api | stracks_api/tasks.py | Python | bsd-2-clause | 152 | 0.013158 | from celery.task import Task
import requests
class Stra | cksFlushTask(Task):
def run(self, url, data):
requests.post(ur | l + "/", data=data)
|
creyesp/RF_Estimation | Clustering/clustering/spaceClustering.py | Python | gpl-2.0 | 4,653 | 0.041694 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# spaceClustering.py
#
# Copyright 2014 Carlos "casep" Sepulveda <carlos.sepulveda@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 Found... | Id,:]
dataGrilla = np.append(dataGrilla,datos, axis=0)
## remove the first row of zeroes
dataGrilla = dataGrilla[1:,:]
rfe.graficaGrilla(dataGrilla, outputFolder+'Grilla_'+str(clusterId)+'.png', 0, clustersColours[clusterId], xSize, ySize)
return 0
if | __name__ == '__main__':
main()
|
jimi-c/ansible | lib/ansible/modules/files/lineinfile.py | Python | gpl-3.0 | 18,737 | 0.001868 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2012, Daniel Hokka Zakrisson <daniel@hozac.com>
# Copyright: (c) 2014, Ahti Kitsik <ak@ahtik.com>
# Copyright: (c) 2017, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolu... | ort, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'core'}
DOCUMENTATION = """
---
module: lineinfile
author:
- Daniel Hokka Zakrissoni (@dhozac)
- Ahti Kitsik (@ahtik)
extends_docume... | e an
existing line using a back-referenced regular expression.
- This is primarily useful when you want to change a single line in
a file only. See the M(replace) module if you want to change
multiple, similar lines or check M(blockinfile) if you want to insert/update/remove a block of lines in a file.
... |
hzlf/openbroadcast.org | website/tools/spurl/templatetags/spurl.py | Python | gpl-3.0 | 12,763 | 0.00047 | import re
from django.conf import settings
from django.utils.html import escape
from django.utils.encoding import smart_str
from urlobject import URLObject
from urlobject.query_string import QueryString
from django.template import StringOrigin
from django.template.base import Lexer, Parser
from django.template.defaultt... | for key, value in query_to_trigger.items():
# exact match of query -> unset it
if key in current_query and query_to_trigger[key] == current_query[key]:
active = True
# check if current query has multiple items
try:
ext = current_query... | en(ext) > 1:
if key in current_query and value in ext:
active = True
self.url = active
def handle_scheme(self, value):
self.url = self.url.with_scheme(value)
def handle_scheme_from(self, value):
url = URLObject(value)
self.url = self.url.wi... |
drufat/sympy | sympy/functions/elementary/tests/test_integers.py | Python | bsd-3-clause | 6,826 | 0.001025 | from sympy import AccumBounds, Symbol, floor, nan, oo, E, symbols, ceiling, pi, \
Rational, Float, I, sin, exp, log, factorial, frac
from sympy.utilities.pytest import XFAIL
x = Symbol('x')
i = Symbol('i', imaginary=True)
y = Symbol('y', real=True)
k, n = symbols('k,n', integer=True)
def test_floor():
a... | ceiling(y) < y) == False
assert (ceiling(x) >= x).is_Relational # x could be non-real
assert (ceiling(x) < x).is_Relational
assert (ceiling(x) >= y).is_Relational # arg is not same as rhs
assert (ceiling(x) < y).is_Relational
def test_frac():
assert isinstance(frac(x), frac)
assert frac(oo) ... | al(1, 3)
assert frac(-Rational(4, 3)) == Rational(2, 3)
r = Symbol('r', real=True)
assert frac(I*r) == I*frac(r)
assert frac(1 + I*r) == I*frac(r)
assert frac(0.5 + I*r) == 0.5 + I*frac(r)
assert frac(n + I*r) == I*frac(r)
assert frac(n + I*k) == 0
assert frac(x + I*x) == frac(x + I*x)
... |
angelblue05/Embytest.Kodi | resources/lib/kodimonitor.py | Python | gpl-2.0 | 8,856 | 0.0035 | # -*- coding: utf-8 -*-
#################################################################################################
import json
import xbmc
import xbmcgui
import clientinfo
import downloadutils
import embydb_functions as embydb
import playbackutils as pbutils
import utils
####################################... | ="POST")
self.logMsg("Mark as watched for itemid: %s" % itemid, 1)
else:
doUtils.downloadUrl(url, type="DELETE")
self.logMsg("Mark as | unwatched for itemid: %s" % itemid, 1)
finally:
embycursor.close()
elif method == "VideoLibrary.OnRemove":
# Removed function, because with plugin paths + clean library, it will wipe
# entire library if user has permissions. Instead, use the emby con... |
Mattie432/deluge-rbb | browsebutton/core.py | Python | gpl-2.0 | 5,012 | 0.003591 | #
# core.py
#
# Copyright (C) 2014 dredkin <dmitry.redkin@gmail.com>
#
# Basic plugin template created by:
# Copyright (C) 2008 Martijn Voncken <mvoncken@gmail.com>
# Copyright (C) 2007-2009 Andrew Resch <andrewresch@gmail.com>
# Copyright (C) 2009 Damien Churchill <damoxc@gmail.com>
#
# Deluge is free software.
#
# Yo... | = os.listdir(absolutepath)
except:
list = []
for f in list:
if os.path.isdir(os.path.join(absolutepath,f)):
f2 = f.decode(CURRENT_LOCALE).encode(UTF8)
subfolders.append(f2)
return subfolders
def is_root_folder(self, folder... | _config(self):
"""Saves the config"""
self.config.save()
log.debug("RBB: config saved")
@export
def set_config(self, config):
"""Sets the config dictionary"""
log.debug("RBB: set_config")
for key in config.keys():
self.config[key] = config[key]
... |
osuripple/pep.py | events/changeMatchSettingsEvent.py | Python | agpl-3.0 | 2,905 | 0.027893 | import random
from common import generalUtils
from common.log import logUtils as log
from constants import clientPackets
from constants import matchModModes
from constants import matchTeamTypes
from constants import matchTeams
from constants import slotStatuses
from objects import glob
def handle(userToken, packetDa... | itles = [
"RWC 2020",
"Fokabot is a duck",
"Dank memes",
"1337ms Ping",
"Iscriviti a Xenotoze",
"...e i marò?",
"Superman dies",
"The brace is on fire",
"print_foot()",
| "#FREEZEBARKEZ",
"Ripple devs are actually cats",
"Thank Mr Shaural",
"NEVER GIVE UP",
"T I E D W I T H U N I T E D",
"HIGHEST HDHR LOBBY OF ALL TIME",
"This is gasoline and I set myself on fire",
"Everyone is cheating apparently",
"Kurwa mac",
"TATOE",
"This is not your drama landfil... |
jackuess/pirateplay.se | lib/pirateplay/lib/services/ur.py | Python | gpl-3.0 | 1,161 | 0.046512 | from ..rerequest import TemplateRequest
init_req = TemplateRequest(
re = r'(http://)?(www\.)?(?P<domain>ur(play)?)\.se/(?P<req_url>.+)',
encode_vars = lambda v: { 'req_url': 'http://%(domain)s.se/%(req_url)s' % v } )
hls = { 'title': 'UR-play', 'url': 'http://urplay.se/', 'feed_url': 'http://urplay. | se/rss',
'items': [init_req,
TemplateRequest(
re = r'file_html5":\s?"(?P<final_url>[^"]+)".*?"subtitles":\s?"(?P<subtitles>[^",]*)',
encode_vars = lambda v: { 'final_url': ('http://130.242.59.75/%(final_url)s/playlist.m3u8' % v).replace('\\', ''),
'suffix-hint': 'mp4',
'subtitles':... | ubtitles', '').replace('\\', '') % v } )] }
rtmp = { 'items': [init_req,
TemplateRequest(
re = r'file_flash":\s?"(?P<final_url>[^"]+\.(?P<ext>mp[34]))".*?"subtitles":\s?"(?P<subtitles>[^",]*)',
encode_vars = lambda v: { 'final_url': ('rtmp://130.242.59.75/ondemand playpath=%(ext)s:/%(final_url)s app=onde... |
OSSystems/lava-server | dashboard_app/tests/models/attachment.py | Python | agpl-3.0 | 3,410 | 0 | # Copyright (C) 2010 Linaro Limited
#
# Author: Zygmunt Krynicki <zygmunt.krynicki@linaro.org>
#
# This file is part of Launch Control.
#
# Launch Control is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License version 3
# as published by the Free Software F... | we started using south, synchronization is no longer occurring
# for the 'dashboard_app' application. This caused some test failures
# such as any tests that depended on the e | xistence of this model.
# As a workaround we artificially "stick" this model into the only
# application that we can count on to exist _and_ not use south as well
# -- that is south itself.
# This way the test model gets synchronized when south is synchronized
# and all the tes... |
mmb90/dftintegrate | tests/fourier/extractvaspdata/test_extractvaspdata.py | Python | mit | 1,597 | 0 | #!/usr/bin/env python3
import unittest
from tests import testfunctions
from dftintegrate.fourier import vaspdata
class TestExtractingVASPDataToDatFiles(unittest.TestCase,
testfunctions.TestFunctions):
def setUp(self):
print('Testing extracting VASP data to .dat fi... | 'symops_trans')
self.assertEqual(symops_trans_ans, symops_trans_tocheck,
msg='symops_trans case '+case)
kmax_ans = self.readfile(case, 'answer', 'kmax')
kmax_tocheck = self.readfile(case, 'tocheck', 'kmax')
... | ax_ans, kmax_tocheck, msg='kmax case '+case)
|
2Cubed/ProjectEuler | euler/__init__.py | Python | mit | 584 | 0 | """Solve the Project Euler problems using functional Python.
https://projecteuler.net/archives
"""
from imp | ortlib import import_module
from os import listdir
from os.path import abspath, dirname
from re import match
SOLVED = set(
int(m.group(1))
for f in listdir(abspath(dirname(__file__)))
for m in (match(r"^p(\d{3})\.py$", f),) if m
)
def compute(problem: int):
"""Compute the answer to problem `problem... | ler.p{:03d}".format(problem))
return module.compute()
|
kinetifex/maya-impress | examples/options_example.py | Python | bsd-3-clause | 2,324 | 0.027539 | import random
import pymel.core as pm
from impress import models, register
def randomTransform( translate=False, translateAmount=1.0, translateAxis=(False,False,False),
rotate=False, rotateAmount=1.0, rotateAxis=(False,False,False),
scale=False, scaleAmount=1.0, ... | offset = map(lambda axis: random.uniform( -rotateAmount, rotateAmount )*float(axis), rotateAxis)
object.setRotation( offset, relative=True )
if scale:
| offset = map(lambda axis: 1 + ( random.uniform( -scaleAmount, scaleAmount )*float(axis) ), scaleAxis)
object.setScale( offset )
print '# Results: %i object randomized. #' % len(objects)
class RandomTransformOptions( models.OptionModel ):
translate = models.CheckBox( default=1, ann='about the ch... |
viraptor/cryptography | cryptography/hazmat/primitives/asymmetric/dsa.py | Python | apache-2.0 | 3,615 | 0 | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License a | 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 language governing permissions ... |
neishm/EC-CAS-diags | eccas_diags/diagnostics/movie_zonal.py | Python | lgpl-3.0 | 2,094 | 0.009551 | ###############################################################################
# Copyright 2016 - Climate Research Division
# Environment and Climate Change Canada
#
# This file is part of the "EC-CAS diags" package.
#
# "EC-CAS diags" is free software: you can redistribute it and/or modify
# it under... | he 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 later version.
#
# "EC-CAS diags" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABI... | Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with "EC-CAS diags". If not, see <http://www.gnu.org/licenses/>.
###############################################################################
from .zonalmean import ZonalMean as Z... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.