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 |
|---|---|---|---|---|---|---|---|---|
carquois/blobon | blobon/books/migrations/0004_auto__add_item__add_time.py | Python | mit | 9,603 | 0.008435 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Item'
db.create_table('books_item', (
('id', self.gf('django.db.models.fields.Au... | 'state': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'street_adress': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'})
},
'books.expense': {
'Meta': {'object_name': 'Expense'},
| 'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
'books.invoice': {
'Meta': {'object_name': 'Invoice'},
'author': ('django.db.models.fields.related.... |
MSeifert04/numpy | numpy/core/tests/test_scalarmath.py | Python | bsd-3-clause | 28,365 | 0.002503 | from __future__ import division, absolute_import, print_function
import sys
import warnings
import itertools
import operator
import platform
import pytest
import numpy as np
from numpy.testing import (
assert_, assert_equal, assert_raises, assert_almost_equal,
assert_array_equal, IS_PYPY, suppress_warnings, _... | erator.pow, np.array(t(a)), b, c)
def floordiv_and_mod(x, y):
return (x // y, x % y)
def _signs(dt):
if dt in np.typecodes['UnsignedInteger']:
return (+1,)
else:
return (+1, -1)
class TestModulus(object):
def test_modulus_basic(self):
dt = np.typecodes['AllInteger'] + np.t... | div_and_mod, divmod]:
for dt1, dt2 in itertools.product(dt, dt):
for sg |
Ayi-/flask_HRmanager | flaskcode.py | Python | mit | 2,988 | 0.005716 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# ****************************************************************#
# ScriptName:
# Author: Eli
# Create Date:
# Modify Author:
# Modify Date:
# Function:
# ****************************************************************#
import random
import ImageDraw
from PIL import Imag... | font_type="FreeMono.ttf",
length=4,
draw_points=True,
point_chance = 2):
'''''
size: 图片的大小,格式(宽,高),默认为(120, 30)
chars: 允许的字符集合,格式字符串
mode: 图片模式,默认为RGB
bg_color: 背景颜色,默认为白色
fg_color: 前景色,验证码字符颜色
font... | img = Image.new(mode, size, bg_color) # 创建图形
draw = ImageDraw.Draw(img) # 创建画笔
def get_chars():
'''''生成给定长度的字符串,返回列表格式'''
return random.sample(chars, length)
def create_points():
'''''绘制干扰点'''
chance = min(50, max(0, int(point_chance))) # 大小限制在[0, 50]
for w in xr... |
purpleidea/gedit-plugins | plugins/commander/modules/goto.py | Python | gpl-2.0 | 1,938 | 0.001032 | # -*- coding: utf-8 -*-
#
# goto.py - goto commander module
#
# Copyright (C) 2010 - Jesse van den Kieboom
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License,... | USA.
import os
import commander.commands as commands
import commander.commands.completion
import commander.commands.result
import commander.commands.exceptions
__commander_module__ = True
def __default__(view, line, column=1):
"""Goto line number"""
buf = view.get_buffer()
ins = buf.get_insert()
ci... | er_at_mark(ins)
try:
if line.startswith('+'):
linnum = citer.get_line() + int(line[1:])
elif line.startswith('-'):
linnum = citer.get_line() - int(line[1:])
else:
linnum = int(line) - 1
column = int(column) - 1
except ValueError:
rais... |
HarryR/ffff-dnsp2p | libbenc/make.py | Python | gpl-2.0 | 1,298 | 0.008475 | #!/usr/bin/env python
import subprocess
import os
class MakeException(Exception):
pass
def swapExt(path, current, replacement):
path, ext = os.path.splitext(path)
if ext == current:
path += replacement
return path
else:
raise MakeException(
"swapExt: expected file ... | if isinstance(arg, list):
args += arg
elif isinstance(arg, tuple):
args += list(arg)
else:
args.append(arg)
subprocess.check_call(['gcc'] + args)
def compile(codeFile, cflags=[]):
objectFile = swapExt(codeFile, '.c', '.o')
gcc(cflags, '-c', ('-o',... | ectFile
def link(programFile, objectFiles, cflags=[]):
gcc(cflags, ('-o', programFile), objectFiles)
if __name__ == '__main__':
objectFiles = [compile(codeFile, cflags) for codeFile in codeFiles]
link(programFile, objectFiles, cflags)
|
Azure/azure-sdk-for-python | sdk/compute/azure-mgmt-compute/azure/mgmt/compute/v2015_06_15/aio/operations/_virtual_machine_extension_images_operations.py | Python | mit | 9,333 | 0.004822 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | map.update(kwargs.pop('error_map', {}))
| request = build_list_types_request(
location=location,
publisher_name=publisher_name,
subscription_id=self._config.subscription_id,
template_url=self.list_types.metadata['url'],
)
request = _convert_request(request)
request.url = self._clie... |
rokj/django_basketball | urls.py | Python | mit | 1,670 | 0.011976 | from django.conf.urls.defaults import *
from django.views.generic.list_detail import object_detail
from django.conf import settings
from django.contrib.auth.views import login, logout
from django.views.generic.simple import redirect_to
from django.views.decorators.cache import cache_page
from common import views as co... | name='games_view_2010-2011'),
url(r'^game/2011-2012/$', cache_page(basketball_views.games_view, settings.CACHE_SECONDS), { 'slug': '1-league-2011-2012-west' }, name='games_view_2011-2012'),
(r'^games/$', redirect_to, {'url': '/games/2011-2012/'}),
url(r'^(?P<url>games/\d{4}-\d{4}/(?P<slug>[\w-]+)/(?P<date_... | (r'^player/(?P<slug>[\w-]+)/$', basketball_views.player_view),
)
if settings.DEBUG:
urlpatterns += patterns('',
(r'^static/(?P<path>.*)$', 'django.views.static.serve', { 'document_root': settings.MEDIA_ROOT , 'show_indexes': True }),
)
|
anythingrandom/eclcli | eclcli/network/networkclient/common/utils.py | Python | apache-2.0 | 10,377 | 0.000096 | import argparse
import logging
import netaddr
import os
from oslo_utils import encodeutils
from oslo_utils import importutils
import six
from . import exceptions
from ..i18n import _
ON_STATE = "ON"
OFF_STATE = "OFF"
def env(*vars, **kwargs):
for v in vars:
value = os.environ.get(v)
if value:
... | string_parts.append(" -d '%s'" % (kwargs['body']))
req = encodeutils.safe_encode("".join(string_parts))
_logger.debug("\nREQ: %s\n", req)
def http_log_resp(_logger, resp, body):
if not _logger.isEnabledFor(logging.DEBUG):
return
_logger.debug("RESP:%(code)s %(headers)s %(bo | dy)s\n",
{'code': resp.status_code,
'headers': resp.headers,
'body': body})
def _safe_encode_without_obj(data):
if isinstance(data, six.string_types):
return encodeutils.safe_encode(data)
return data
def safe_encode_list(data):
return list(... |
hagabbar/pycbc_copy | pycbc/events/events.py | Python | gpl-3.0 | 32,066 | 0.00368 | # Copyright (C) 2012 Alex Nitz
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 3 of the License, or (at your
# self.option) any later version.
#
# This program is distributed in ... | rformance = False
@classmethod
def from_multi_ifo_interface(cls, opt, ifo, column, column_types, **kwds):
"""
| To use this for a single ifo from the multi ifo interface requires
some small fixing of the |
janpipek/hlava | hlava/items/formats/json_item.py | Python | mit | 860 | 0.005814 | from json import loads as json_loads
import collections
from .text_item import AbstractTextItem
from .tree_item import AbstractTreeItem
from .. import register
@register
class JsonItem(AbstractTextItem, Abstrac | tTreeItem):
extensions = ("json",)
mime_type = "text/x-json"
new_item_order_preference = 1.62
type_description = lambda: "JSON (JavaScript Object Notation)"
new_item_content = lambda name: "{\n \"_title\" : \"" + name + "\"\n}\n"
@property
def json(self):
if not "_json" in dir(... | ):
try:
json = self.json
return self._tree_to_html(json)
except:
return "<b>Invalid JSON:</b><pre>{0}</pre>".format(self.text)
|
norayr/unisubs | utils/breadcrumbs.py | Python | agpl-3.0 | 1,063 | 0.000941 | # Amara, universalsubtitles.org
#
# Copyright (C) 2015 Participatory Culture Foundation
#
# This program 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 op... | e 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not... |
self.label = unicode(label)
if view_name:
self.url = reverse(view_name, args=args, kwargs=kwargs)
else:
self.url = None
|
google-research/google-research | correct_batch_effects_wdn/forgetting_nuisance.py | Python | apache-2.0 | 55,433 | 0.006061 | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | vert to a tuple if not hashable.
Args:
x (list, tuple, string, or None): input to convert to a key
Returns:
Hashable object
"""
if isinstance(x, list) an | d len(x) == 1:
x = x[0]
if not isinstance(x, collections.Hashable):
return tuple(x)
else:
return x
def split_df(df, columns_split):
"""Split a dataframe into two by column.
Args:
df (pandas dataframe): input dataframe to split.
columns_split (int): Column at which to split the dataframes.... |
GNOME/gnome-python | examples/gconf/simple-controller.py | Python | lgpl-2.1 | 683 | 0.021962 | #!/usr/bin/env python
#
# A very simple program that sets a single key value when you type
# it in an entry and press return
#
import gtk
import gconf
def entry_activated_callback(entry, client):
s = entry.get_chars (0, -1)
client.set_string ("/testing/ | directory/key", s)
window = gtk.Window()
entry = gtk.Entry ()
window.add (entry)
client = gconf.client_get_default ()
client.add_dir ("/testing/directory",
gconf.CLIENT_PRELOAD_NONE)
entry.connect ('activate', entry_activated_callback, client)
# If key isn't writable, then set insensitive
entry.set_... | ()
|
SUSE/ceph-deploy-to-be-deleted | ceph_deploy/cli.py | Python | mit | 5,580 | 0.000896 | import pkg_resources
import argparse
import logging
import textwrap
import os
import sys
from string import join
import ceph_deploy
from ceph_deploy import exc, validate
from ceph_deploy.util import log
from ceph_deploy.util.decorators import catches
LOG = logging.getLogger(__name__)
__header__ = textwrap.dedent(""... | ='ceph',
)
return parser
@catches((KeyboardInterrupt, RuntimeError, exc.DeployError,), handle_all=True)
def _main(args=None, namespace=None):
# Set console logging first with some defaults, to prevent hav | ing exceptions
# before hitting logging configuration. The defaults can/will get overridden
# later.
# Console Logger
sh = logging.StreamHandler()
sh.setFormatter(log.color_format())
sh.setLevel(logging.WARNING)
# because we're in a module already, __name__ is not the ancestor of
# the... |
brainstorm/bcbio-nextgen | bcbio/structural/shared.py | Python | mit | 13,904 | 0.004387 | """Shared functionality useful across multiple structural variant callers.
Handles exclusion regions and preparing discordant regions.
"""
import collections
import os
import numpy
import pybedtools
import pysam
import toolz as tz
import yaml
from bcbio import bam, utils
from bcbio.distributed.transaction import fil... | work_dir):
"""Retrieve set of target regions for CNV analysis.
Subsets to extended transcript regions for WGS experiments to avoid
long runtimes.
"""
cov_interval = dd.get_coverage_interval(data)
base_regions = regions.get_sv_bed(data)
# if we don't have a configured BED or region | s to use for SV caling
if not base_regions:
# For genome calls, subset to regions within 10kb of genes
if cov_interval == "genome":
base_regions = regions.get_sv_bed(data, "transcripts1e4", work_dir)
if base_regions:
base_regions = remove_exclude_regions(base_... |
akranga/mafia-serverless | solutions/day.py | Python | apache-2.0 | 1,580 | 0.01519 | import os, sys
# to read dependencies from ./lib direcroty
script_dir = os.path.dirname( os.path.realpath(__file__) )
sys.path.insert(0, script_dir + os.sep + "lib")
import logging, boto3, json, random
# for dynamodb filter queries
from boto3.dynamodb.conditions import Key, Attr
# setup log level to DEBUG
log = loggi... | 'bod | y': json.dumps(body, indent=4, separators=(',', ':'))
}
return body |
douville/qcri | qcri/application/gui.py | Python | bsd-2-clause | 27,582 | 0.000145 | """
The GUI to QCRI.
"""
# pylint: disable=I0011, no-member, missing-docstring
import threading
import logging
from sys import version_info
import pythoncom
from qcri.application import importer
from qcri.application import qualitycenter
# pylint: disable=I0011, import-error
if version_info.major == 2:
import Tki... |
self.runresultsview.rowconfigure(0, weight=1)
self.runresultsview.columnconfigure(0, weight=1)
local_pane.rowconfigure(2, weight=1)
local_pane.columnconfigure(1, weight=1)
local_pane.confi | g(padx=10)
return local_pane
def _on_qc_conn_status_changed(self, *_):
if self.qc_conn_status.get():
self.qc_connected_frm.tkraise()
self.upload_button.config(state=tk.NORMAL)
else:
self.qc_disconnected_frm.tkraise()
self.upload_button.config(... |
jms/potential-bassoon | srl/tests.py | Python | bsd-3-clause | 1,507 | 0.001327 | from django.test import TestCase
from srl.services.parse import numtosxg, sxgtonum
from srl.management.commands.create_fake_users import create_fake_users
from srl.views import get_random_user
from django.contrib.auth.models import User
class TestBaseConversion(TestCase):
def test_check0(self):
assert num... | def test_check1(self):
assert sxgtonum('1') == 1
def test_check60(self):
assert sxgtonum('10') == 60
def test_check1337(self):
assert sxgtonum('NH') == 1337
def test_checkl(self):
assert sxgtonum('l') == 1
def test_checkI(self):
assert sxgtonum('I') == 1
... | == 0
def test_checkpipe(self):
assert sxgtonum('|') == 0
def test_checkcomma(self):
assert sxgtonum(',') == 0
class TestRoundtripCheck(TestCase):
def test_roundtrip(self):
# sxgtonum(numtosxg(n))==n for all n
for integer in range(0, 6000):
sxg = numtosxg(int... |
LordDarkula/polypy | polypy/product.py | Python | mit | 2,416 | 0.002897 | from .commutative import Commutative
class Product(Commutative):
def __init__(self, *args):
super(Product, self).__init__(*self.simplified(*args))
def simplified(self, *args):
"""
Returns a sequence containing expressions that make a simplified Product.
Used when ``Product`` is... | = 0
for expr in self._exprs:
de | g += self._calc_degree(expr)
return deg
def order(self, ascending=True):
"""
Converts ''frozenset'' exprs into ''list'' ordered by degree.
:rtype: list
"""
return super(Product, self).order(ascending=True)
def same_base(self, other):
return isinstance(o... |
sdague/home-assistant | homeassistant/components/gios/__init__.py | Python | apache-2.0 | 2,334 | 0.001714 | """The GIOS component."""
import logging
from aiohttp.client_exceptions import ClientConnectorError
from async_timeout import timeout
from gios import ApiError, Gios, InvalidSensorsData, NoStationError
from homeassistant.core import Config, HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
from h... | TERVAL
_LOGGER = logging.getLogger(__name__)
async def async_setup(hass: HomeAssistant, config: Config) -> bool:
"""Set up configured GIOS."""
return True
async def async_setup_entry(hass, config_entry):
"""Set up GIO | S as config entry."""
station_id = config_entry.data[CONF_STATION_ID]
_LOGGER.debug("Using station_id: %s", station_id)
websession = async_get_clientsession(hass)
coordinator = GiosDataUpdateCoordinator(hass, websession, station_id)
await coordinator.async_refresh()
if not coordinator.last_up... |
eoss-cloud/madxxx_catalog_api | catalog/manage/__init__.py | Python | mit | 705 | 0.001418 | #-*- coding: utf-8 -*-
""" EOSS catalog system
| external catalog management package
"""
__author__ = "Thilo Wehrmann, Steffen Gebhardt"
__copyright__ = "Copyright 2016, EOSS GmbH"
__credits__ = ["Thilo Wehrmann", "Steffen Gebhardt"]
__license__ = "GPL"
__version__ = "1.0.0"
__maintainer__ = "Thilo Wehrmann"
__email__ = "[email protected]"
__status__ = "Productio... | abc import ABCMeta, abstractmethod
from utilities import with_metaclass
@with_metaclass(ABCMeta)
class ICatalog(object):
"""
Simple catalog interface class
"""
def __init__(self):
pass
@abstractmethod
def find(self):
pass
@abstractmethod
def register(self, ds):
... |
leakim/GameOfLifeKata | python/resources.py | Python | mit | 1,181 | 0.004237 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Resources to make it easier and faster to implement and test game | of life
#
# @author Mikael Wikström
# https://github.com/leakim/GameOfLifeKata
#
import pygame
class GameOfLife:
# still
BLOCK_0 = set([(0, 0), (0, 1), (1, 0), (1, 1)])
BLOCK_1 = BLOCK_0
| # oscillators
THREE_0 = set([(0, 1), (0, 0), (0, 2)])
THREE_1 = set([(0, 1), (-1, 1), (1, 1)])
# spaceships (moves)
GLIDER_0 = set([(0, 1), (1, 2), (0, 0), (0, 2), (2, 1)])
GLIDER_1 = set([(0, 1), (1, 2), (-1, 1), (1, 0), (0, 2)])
def move(state, (x, y)):
newstate = set()
for (u, v) in... |
PanDAWMS/panda-bigmon-atlas | setup.py | Python | apache-2.0 | 36 | 0 | #!/ | usr/bin/env python
#
# Setup
#
# | |
iulian787/spack | var/spack/repos/builtin/packages/iwyu/package.py | Python | lgpl-2.1 | 1,882 | 0.003188 | # Copyright 2013-2020 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 Iwyu(CMakePackage):
"""include-what-you-use: A tool for use with clang to analyze #include... | a256='2d2877726c4aed9518cbb37673ffbc2b7da9c239bf8fe29432da35c1c0ec367a')
patch('iwyu-013-cmake.patch', when='@0.13:0.14')
depends_on('[email protected]:10.999', when='@0.14')
depends_on('[email protected]:9.999', when='@0.13')
| depends_on('[email protected]:8.999', when='@0.12')
depends_on('[email protected]:7.999', when='@0.11')
# Non-X86 CPU use all_targets variants because iwyu use X86AsmParser
depends_on('llvm+all_targets', when='target=aarch64:')
depends_on('llvm+all_targets', when='target=arm:')
depends_on('llvm+all_t... |
acdh-oeaw/vhioe | entities/views.py | Python | mit | 5,608 | 0.000178 | from django.views.generic.detail import DetailView
from django.core.urlresolvers import reverse_lazy
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from django.views import generic
from django.views.generic.edit import DeleteView, CreateView, UpdateView
fr... | iter
class BearbeiterListView(generic.ListView):
model = Bearbeiter
template_name = 'entities/bearbeiter_list.html'
context_object_name = 'object_list'
class BearbeiterDetailView(DetailView):
model = Bearbeiter
class BearbeiterCreate(CreateView):
model = Bearbeiter
template_name_suffix =... | **kwargs)
class BearbeiterUpdate(UpdateView):
model = Bearbeiter
template_name_suffix = '_create'
form_class = BearbeiterForm
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(BearbeiterUpdate, self).dispatch(*args, **kwargs)
class BearbeiterDelete(De... |
hiei171/lendingbotpoloniex | modules/WebServer.py | Python | mit | 3,367 | 0.002376 | # coding=utf-8
import threading
server = None
web_server_ip = "0.0.0.0"
web_server_port = "8000"
web_server_template = "www"
def initialize_web_server(config):
'''
Setup the web server, retrieving the configuration parameters
and starting the web server thread
'''
global web_server_ip, web_server... | rver = SocketServer.TCPServer((host, port), QuietHandler)
if host == "0.0. | 0.0":
# Get all addresses that we could listen on the port specified
addresses = [i[4][0] for i in socket.getaddrinfo(socket.gethostname().split('.')[0], port)]
addresses = [i for i in addresses if ':' not in i] # Filter out all IPv6 addresses
addresses.append('127.0.0.1... |
egroeper/exscript | tests/Exscript/util/startTest.py | Python | gpl-2.0 | 2,091 | 0.013391 | import sys, unittest, re, os.path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', '..', 'src'))
import Exscript
import Exscript.util.start
from multiprocessing import Value
def count_calls(job, host, conn, data, **kwargs):
# Warning: Assertions raised in this function happen in a subprocess... | self.callback,
max_threads = 2,
| verbose = 0)
self.assertEqual(self.data.value, 5)
def testRun(self):
from Exscript.util.start import run
self.doTest(run)
def testQuickrun(self):
pass # can't really be tested, as it is user interactive
def testStart(self):
from Exscript.util.start import sta... |
vinthony/racpider | src/redistool/clientinfo.py | Python | mit | 280 | 0.078571 | from redis import Redis
from basic import conn
def reflashState(client,count=None,network=None):
prefix = "client:"
if not client:
return False
x = dict()
if count:
conn().hset(prefix+client,"count",count)
if network:
conn | ().hset( | prefix+client,"network",network)
|
payal97/portal | systers_portal/meetup/permissions.py | Python | gpl-2.0 | 880 | 0 | from meetup.constants import *
groups_templates = {"community_member": COMMUNITY_MEMBER,
"community_moderator": COMMUNITY_MODERATOR,
"community_leader": COMMUNITY | _LEADER}
community_member_permissions = [
"add_meetup_rsvp",
"add_support_request"
]
community_moderator_permissions = community_member_permissions + [
"add_meetups",
"change_meetups",
"delete_meetups",
"approve_meetup_request",
"reject_meetup_request",
"view_meetup_request",
"appr... | ve_support_request",
"reject_support_request",
"add_resource"
]
community_leader_permissions = community_moderator_permissions
group_permissions = {"community_member": community_member_permissions,
"community_moderator": community_moderator_permissions,
"community_lea... |
Mirantis/vmware-firewall-driver | setup.py | Python | apache-2.0 | 738 | 0 | # Copyright | 2015 Mirantis, Inc.
# Copyright 2012-2013 IBM Corp.
# 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
#
# ... | "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import setuptools
setuptools.setup(
setup_requires=['pbr'],
pbr=True)
|
algorithmiaio/algorithmia-python | Algorithmia/insights.py | Python | mit | 534 | 0.007491 | import requests
import json
import os
class Insights:
# Example of correct insights:
# {"aKey":"aValue","aKey2":"a | Value2"}
def __init__(self, insights):
headers = {}
headers['Content-Type'] = 'application/json'
AQR_URL = os.getenv('ALGORITHMIA_API') or "http://localhost:9000"
insight_payload=[{"insight_key": key, "insight_value": insights[key]} for key in insights.keys()]
requests.post(... | data=json.dumps(insight_payload).encode('utf-8'), headers=headers)
|
thisisshi/cloud-custodian | tools/c7n_azure/c7n_azure/resources/container_registry.py | Python | apache-2.0 | 1,144 | 0 | # Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
from c7n_azure.provider import resources
from c7n_azure.resources.arm import ArmResourceManager
@resources.register('container-registry', aliases=['containerregistry'])
class ContainerRegistry(ArmResourceManager):
"""Container Registr... | s:
- type: value
key: name
op: eq
value: my-test-container-registry
"""
class resource_type(ArmResourceManager.resource_type):
doc_groups = ['Containers']
service = 'azure.mgmt.containerregistry'
client = 'ContainerRegistryManageme... | es', 'list', None)
default_report_fields = (
'name',
'location',
'resourceGroup',
'sku.name'
)
resource_type = 'Microsoft.ContainerRegistry/registries'
|
alejo8591/angular-labs | lab15/order/migrations/0004_product_product_likes.py | Python | mit | 467 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencie | s = [
('order', '0003_customer_customer_slug'),
]
operations = [
migrations.AddField(
model_name='product',
name='product_likes',
field=mo | dels.IntegerField(blank=True, null=True, default=0),
preserve_default=True,
),
]
|
nigelb/gRefer | gRefer/filer/startup.py | Python | gpl-3.0 | 1,643 | 0.003043 | #!/usr/bin/env python
# gRefer is a Bibliographic Management System that uses Google Docs
# as shared storage.
#
# Copyright (C) 2011 NigelB
#
# 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 Soft... | S FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <ht | tp://www.gnu.org/licenses/>.
from gRefer import log
def start_notifier():
import os
from gRefer.config_constants import dir_name, bibfiler_log_file
from gRefer.log import NotifyHandler
import logging
import logging.handlers
logger = logging.getLogger(name="Notifier")
if not os.path.exists... |
JShadowMan/package | python/LeetCode OJ/1.twoSum.py | Python | mit | 341 | 0.014663 | class So | lution(object):
def twoSum(self, nums, target):
return list([ (x, y) for x in range(len(nums)) for y in range(x, len(nums)) if nums[x] + nums[y] == target | and (x != y) ][0])
if __name__ == '__main__':
solution = Solution()
print(solution.twoSum([3, 2, 4], 6))
print(solution.twoSum([2, 7, 11, 15], 9)) |
tessercat/ddj | models/menu.py | Python | mit | 3,603 | 0.001388 | def app_logo_attr():
""" Return app logo LI attributes. """
attr = {
'_class': 'navbar-brand',
'_role': 'button'}
if request.controller == 'studies':
attr['_onclick'] = 'tocModal(event);'
attr['_title'] = 'Chapter Studies'
elif request.controller == 'poems' and request.fu... | don't have an associated English
poem, the se | cond dict contains chapters that do. """
from collections import OrderedDict
def study_link(chapter):
verse = db.verse[chapter]
url = URL('studies', 'chapter', args=[verse.chapter.number])
cls = 'studies-toc-link'
lnk = '%i %s' % (verse.chapter.number, verse.chapter.title or '')... |
ulule/python-mangopay | tests/test_users.py | Python | mit | 21,419 | 0.000794 | # -*- coding: utf-8 -*-
from datetime import date
from .resources import (User, NaturalUser, Wallet,
LegalUser, Transfer, Transaction)
from .test_base import BaseTest
from mangopay.utils import Money
import responses
import requests
import time
import re
requests_session = requests.Session()
... | day": date.today(),
"legal_representative_nationality": "FR",
"legal_representative_country_of_residence": "FR",
"proof_of_registration": None,
"shareholder_declaration": None,
"legal_representative_address": None,
"statute": None,
"per... | # "creation_date": datetime.now()
}
user = LegalUser(**params)
self.assertIsNone(user.get_pk())
user.save()
self.assertIsInstance(user, LegalUser)
for key, value in params.items():
self.assertEqual(getattr(user, key), value)
self.assertIsNotN... |
klahnakoski/MySQL-to-S3 | vendor/mo_logs/log_usingThreadedStream.py | Python | mpl-2.0 | 3,886 | 0.002316 | # encoding: utf-8
#
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Author: Kyle Lahnakoski ([email protected])
#
from __future__ import absolute_import
from _... | queue - FILLED WITH LOG ENTRIES {"template":template, "params":params} TO WRITE
interval - timedelta
USE IN A THREAD TO BATCH LOGS BY TIME INTERVAL
"""
next_run = time() + interval
while not please_stop:
(Till(till=next_run) | please_stop).wait()
next_run = time() + interval
... | try:
if log is THREAD_STOP:
please_stop.go()
next_run = time()
else:
expanded = expand_template(log.get("template"), log.get("params"))
lines.append(expanded)
except Exception as e:
... |
secnot/uva-onlinejudge-solutions | 10032 - Tug of War/main.py | Python | mit | 1,768 | 0.00509 | import sys
def load_num():
return int(sys.stdin.readline().rstrip())
def load_case():
_ = sys.stdin.readline() # Empty line
npeople = load_num()
return [load_num() for _ in range(npeople)]
def find_split(weights, total_weight):
reachable = [0 for _ in range(total_weight+1)]
reachable[0] = 1
... | ht = sum(weights)
# Check limit cases
if len(weights) == 0:
return 0, 0
elif len(weights) == 1:
return 0, weights[0]
return find_split(weights, total_weight)
if __name__ == '__main__':
ncases = loa | d_num()
for c in range(ncases):
weights = load_case()
low, high = solve(weights)
print(low, high)
if c+1 < ncases:
print('')
|
Jumpers/MysoftAutoTest | Step1-PythonBasic/Practices/yuxq/16-17/ex16_2.py | Python | apache-2.0 | 107 | 0.037383 | from sys import argv
script,filename=argv
aread= | open(filename)
print aread.read()
aread.clo | se() |
cortesi/qtile | docs/sphinx_qtile.py | Python | mit | 6,730 | 0.00104 | # Copyright (c) 2015 dmpayton
#
# 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, distribute... | als = builtins
if not isinstance(globals, dict):
globals = globals.__dict__
return eval(expr, globals, mod.__dict__)
class SimpleDirectiveMixin(object):
has_content = True
required_arguments = 1
def make_rs | t(self):
raise NotImplementedError
def run(self):
node = nodes.section()
node.document = self.state.document
result = ViewList()
for line in self.make_rst():
result.append(line, '<{0}>'.format(self.__class__.__name__))
nested_parse_with_titles(self.state,... |
raphaelsoul/supermilai | account/admin.py | Python | bsd-2-clause | 918 | 0.057734 | from django.contrib import admin
from account.models import UserProfile
from django.contrib.auth.models import Permission, Group
class UserProfileAdmin(admin.ModelAdmin):
#,'qq','first_name','last_name','truename','email','groups'
fieldsets = [
(None,{'fields':['username']}),
('Profile',{'fields':['last_name','f | irst_name','truename']}),
('Contact Information',{'fields':['email','qq']}),
('Permission Type',{'fields' | :['is_superuser','is_staff','is_active','groups']}),
#('My Permission Type',{'fields':['mygroups']}),
#('Timestamp',{'fields':['date_joined','last_login']}),
]
list_display = (
'username',
'truename',
'email',
'is_superuser',
'is_staff',
'date_joined',
'last_login',
#'groups',
)
admin.site.registe... |
andersonsilvade/5semscript | tekton/gae/middleware/email_errors.py | Python | mit | 2,781 | 0.002517 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import json
import logging
import traceback
import time
from google.appengine.api import app_identity, mail, capabilities
from google.appengine.runtime import DeadlineExceededError
from tekton.gae.middleware import Middleware
from tekton... | isinstance(exception, PathNotFound):
self.handler.response.set_status(404)
send_error_to_admins(settings, exception, self.handler, self.dependencies['_render'],
settings.TEMPLATE_404_ERROR)
else:
self.han | dler.response.set_status(400)
send_error_to_admins(settings, exception, self.handler, self.dependencies['_render'],
settings.TEMPLATE_400_ERROR)
|
s20121035/rk3288_android5.1_repo | cts/suite/audio_quality/test_description/processing/recording_thd.py | Python | gpl-3.0 | 2,834 | 0.001764 | #!/usr/bin/python
# Copyright (C) 2012 The Android Open Source Project
#
# 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 require... | recording,
# matching process is required.
# 2. calculate THD of host recording and client recording
# 3. check pass/fail
def recording_thd(inputData, inputTypes):
| output = []
outputData = []
outputTypes = []
# basic sanity check
inputError = False
if (inputTypes[0] != TYPE_MONO):
inputError = True
if (inputTypes[1] != TYPE_MONO):
inputError = True
if (inputTypes[2] != TYPE_I64):
inputError = True
if (inputTypes[3] != TY... |
AnykeyNL/uArmProPython | test/release_test.py | Python | gpl-3.0 | 1,108 | 0.020758 | # uArm Swift Pro - Python Library Example
# Created by: Richard Garsthagen - [email protected]
# V0 | .3 - June 2018 - Still under development
#
# Use Python 2.x!
import uArmRobot
import time
import easycv2
points = []
coins = []
totalP = 4
speed = 80
#C | onfigure Serial Port
serialport = "com10" # for windows
#serialport = "/dev/ttyACM0" # for linux like system
# Connect to uArm
myRobot = uArmRobot.robot(serialport,1) # user 0 for firmware < v4 and use 1 for firmware v4
myRobot.debug = True # Enable / Disable debug output on screen, by default disabled
... |
pfalcon/micropython | tests/basics/int_divzero.py | Python | mit | 146 | 0 | try:
| 1 // 0
except ZeroDivisionError:
print("ZeroDivisionError")
try:
1 % 0
except ZeroDivisionError:
pri | nt("ZeroDivisionError")
|
gratefulfrog/lib | python/pymol/computing.py | Python | gpl-2.0 | 10,218 | 0.013114 | #A* -------------------------------------------------------------------
#B* This file contains source code for the PyMOL computer program
#C* Copyright (c) Schrodinger, LLC
#D* -------------------------------------------------------------------
#E* It is unlawful to modify or remove this copyright notice.
#F* ---------... | atic = 0
for bond in input_model.bond:
if bond.order == 4:
aromatic = 1
try:
open(failed_file,'wb').write(input_sdf)
print "Clean-Error: Wrote | SD file '%s' into the directory:"%failed_file
print "Clean-Error: '%s'."%os.getcwd()
print "Clean-Error: If you believe PyMOL should be able to handle this structure"
print "Clean-Error: then please email that SD file to [email protected]. Thank you!"
... |
oblique-labs/pyVM | rpython/jit/backend/zarch/test/test_float.py | Python | mit | 467 | 0.002141 | import py
from rpython.jit.backend.zarch.test.support import | JitZARCHMixin
from rpython.jit.metainterp.test.test_float import FloatTests
from rpython.jit.backend.detect_cpu import getcpuclass
CPU = getcpuclass()
class TestFloat | (JitZARCHMixin, FloatTests):
# for the individual tests see
# ====> ../../../metainterp/test/test_float.py
if not CPU.supports_singlefloats:
def test_singlefloat(self):
py.test.skip('requires singlefloats')
|
ClearcodeHQ/matchbox | src/matchbox/__init__.py | Python | lgpl-3.0 | 925 | 0 | # Copyright | (C) 2015 by Clearcode <http://clearcode.cc>
# and associates (see A | UTHORS).
# This file is part of matchbox.
# matchbox is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# matchbox is distribute... |
nmoutschen/tsurvey | src/tsurvey/__init__.py | Python | mit | 38 | 0 | """
Anonymous token-based | surve | ys
"""
|
kavyasukumar/django-calaccess-raw-data | calaccess_raw/admin/base.py | Python | mit | 203 | 0 | from django.contrib import admin
class BaseAdmin(admin.ModelAdmin):
save_on_top = True
def get_readonly_fields(self, *args, **kwargs):
| return [f.name for f in se | lf.model._meta.fields]
|
Nilpo/RPi-Samples | metronome_led.py | Python | mit | 1,233 | 0.055961 | from time import sleep
import sys
import os
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
p1 = 14
p2 = 15
GPIO.setup(p1, GPIO.OUT)
GPIO.setup(p2, GPIO.OUT)
class Quit(Exception): pass
def green(duration):
GPIO.output(p1, False)
GPIO.output(p2, True)
sl | eep(duration)
GPIO.output(p2, False)
def red(duration):
GPIO.output(p2, False)
GPIO.output(p1, True)
sleep(duration)
GPIO.output(p1, False)
def main():
while True:
# The standard Linux clear screen cmmand.
n=os.sy | stem("clear")
while True:
beats=raw_input("Enter any whole number from 30 to 400 (bpm), Q or X to quit. (100): ")
if beats.isdigit():
if beats <= 400 and beats >= 30:
break
elif beats.upper() == "Q" or beats.upper() == "X":
raise Quit
elif beats == "":
beats = 100
break
... |
andrewgleave/whim | web/whim/core/time.py | Python | mit | 354 | 0.002825 | from datetime import datetime, timezone, time
import dateparser
def zero_time_with_timezone(date, tz=timezone.utc):
return datetime.combine(date, time(tzinfo=tz))
de | f attem | pt_parse_date(val):
parsed_date = dateparser.parse(val, languages=['en'])
if parsed_date is None:
# try other strategies?
pass
return parsed_date |
harshilasu/LinkurApp | y/google-cloud-sdk/platform/gsutil/third_party/boto/boto/emr/connection.py | Python | gpl-3.0 | 28,351 | 0.000917 | # Copyright (c) 2010 Spotify AB
# Copyright (c) 2010-2011 Yelp
#
# 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, m... | me
:param created_before: Bound on job flow creation time
"""
params = {}
if states:
self.build_list_params(params, states, 'JobFlowStates.member')
if jobflow_ids:
self.build_list_params(params, jobflow_ids, 'JobFlowIds.member')
| if created_after:
params['CreatedAfter'] = created_after.strftime(
boto.utils.ISO8601)
if created_before:
params['CreatedBefore'] = created_before.strftime(
boto.utils.ISO8601)
return self.get_list('DescribeJobFlows', params, [('member', J... |
jjgomera/pychemqt | lib/EoS/Cubic/PRSV2.py | Python | gpl-3.0 | 2,556 | 0 | #!/usr/bin/python3
# -*- coding: utf-8 | -*-
r"""Pychemqt, Chemical Engineering Process simulator
Copyright (C) 2009-2017, Juan José Gómez Romera <j | [email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be use... |
johnkeepmoving/oss-ftp | python27/win32/Lib/site-packages/pyftpdlib/servers.py | Python | mit | 20,552 | 0 | # Copyright (C) 2007-2016 Giampaolo Rodola' <[email protected]>.
# Use of this source code is governed by MIT license that can be
# found in the LICENSE file.
"""
This module contains the main FTPServer class which listens on a
host:port and dispatches the incoming connections to a handler.
The concurrency is handled... | ket listening on 'address' dispatching
connections to a 'handler'.
- (tuple) address_or_socket: the (host, port) pair on which
the command channel will listen for incoming connections or
an existent socket object.
- (instance) handler: the handler class to use.
... | int) backlog: the maximum number of queued connections
passed to listen(). If a connection request arrives when
the queue is full the client may raise ECONNRESET.
Defaults to 5.
"""
Acceptor.__init__(self, ioloop=ioloop)
self.handler = handler
self.backlo... |
tobami/littlechef | tests/test_command.py | Python | apache-2.0 | 10,393 | 0.000192 | import unittest
import subprocess
import os
import platform
import shutil
from os.path import join, normpath, abspath, split
import sys
env_path = "/".join(os.path.dirname(os.path.abspath(__file__)).split('/')[:-1])
sys.path.insert(0, env_path)
import littlechef
# Set some convenience variables
test_path = split(no... |
class TestEnvironment(BaseTest):
def test_no_valid_value(self):
"""Should error out when the env value is empty or is a fabric task"""
resp, error = self.execute([fix, 'list_nodes', '--env'])
self.assertEquals(resp, "")
self.assertTrue(
"error: argument -e/--env: expect... | self.assertEquals(resp, "")
self.assertTrue("error: No value given for --env" in error, error)
cmd = [fix, '--env', 'nodes_with_role:base', 'role:base']
resp, error = self.execute(cmd)
self.assertEquals(resp, "")
self.assertTrue("error: No value given for --env" in error, err... |
IsCoolEntertainment/debpkg_libcloud | libcloud/test/storage/test_azure_blobs.py | Python | apache-2.0 | 37,730 | 0.001272 | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... | anguage governing permissions and
# limitations under the License.
from __future__ import with_statement
import os
import sys
import unittest
import tempfile
from xml.etree import ElementTree as ET
fr | om libcloud.utils.py3 import httplib
from libcloud.utils.py3 import urlparse
from libcloud.utils.py3 import parse_qs
from libcloud.common.types import InvalidCredsError
from libcloud.common.types import LibcloudError
from libcloud.storage.base import Container, Object
from libcloud.storage.types import ContainerDoesNo... |
taw/python_koans | python3/koans/about_regex.py | Python | mit | 4,842 | 0.006402 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
import re
class AboutRegex(Koan):
"""
These koans are based on the Ben's book: Regular Expressions in 10 minutes.
I found this books very useful so I decided to write a koans in order to practice everything I had learned from i... | sets of characters
A set of characters is defined using the metacharacters [ and ]. Everything between them is part of the set and
any one of the set members must mat | ch (but not all).
"""
string = "sales.xlx\n" \
+ "sales1.xls\n" \
+ "orders3.xls\n" \
+ "apac1.xls\n" \
+ "sales2.xls\n" \
+ "na1.xls\n" \
+ "na2.xls\n" \
+ "sa1.xls\n" \
... |
hackedd/gw2api | gw2api/items.py | Python | mit | 4,068 | 0 | from .util import get_cached
__all__ = ("items", "recipes", "item_details", "recipe_details")
def items():
"""This resource returns a list of items that were discovered by players
in the game. Details about a single item can be obtained using the
:func:`item_details` resource.
"""
return get_ca... |
``Unique``
restrictions (list):
Race restrictions: ``Asura``, ``Charr``, ``Human``, ``Norn`` and
``Sylvari``.
Each item type has an `additional key`_ with information specific to that
item type.
| .. _additional key: item-properties.html
"""
params = {"item_id": item_id, "lang": lang}
cache_name = "item_details.%(item_id)s.%(lang)s.json" % params
return get_cached("item_details.json", cache_name, params=params)
def recipe_details(recipe_id, lang="en"):
"""This resource returns a details ab... |
50thomatoes50/Ardulan | http_serv.py | Python | gpl-2.0 | 202 | 0.014851 | #!/usr/bin | /env python
from threading import Thread
if(__name__ == '__main__'):
import webbrowser
web = WebServer()
webbrowser.open("http://127.0.0.1:8888")
web.s | tart() |
ssebastianj/ia2013-tpi-rl | src/gui/qtgen/gwgenrndestadosdialog.py | Python | mit | 1,334 | 0.003748 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'D:\Sebastian\Mis documentos\Programacion\Proyectos\IA2013TPIRL\gui\qt\IA2013TPIRLGUI\gwgenrndestadosdialog.ui'
#
# Created: Tue Jul 09 15:27:46 2013
# by: PyQt4 UI code generator 4.10.2
#
# WARNING! All changes made in this file will be... | RndEstadosDialog(object):
def setupUi(self, GWGenRndEstadosDialog):
GWGenRndEstadosDialog.setObjectName(_fromUtf8("GWGenRndEstadosDialog"))
GWGenRndEstadosDialog.resize(400, 300)
GWGenRndEstadosDialog.setMo | dal(True)
self.retranslateUi(GWGenRndEstadosDialog)
QtCore.QMetaObject.connectSlotsByName(GWGenRndEstadosDialog)
def retranslateUi(self, GWGenRndEstadosDialog):
GWGenRndEstadosDialog.setWindowTitle(_translate("GWGenRndEstadosDialog", "Generar estados aleatorios", None))
|
yangle/HaliteIO | website/tutorials/machinelearning/TrainMatt.py | Python | mit | 4,981 | 0.003212 | from hlt import *
from networking import *
from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.optimizers import SGD, Adam, RMSprop
from os import listdir, remove
from os.path import join, isfile
def loadGame(filename):
def stringUntil(gameFile, endChar):
returnStrin... | finally:
gameFile.close()
return mattID, frames, moves
def getNNData():
inputs = []
correctOutputs = []
gamePath = "replays"
for filename in [f for f in listdir(gamePath) if isfile(join(gamePath, f))]:
print("Loading " + filename)
| mattID, frames, moves = loadGame(join(gamePath, filename))
maxProduction = 0
for y in range(frames[0].height):
for x in range(frames[0].width):
prod = frames[0].getSite(Location(x, y)).production
if prod > maxProduction:
maxProduction... |
sknepneklab/SAMoS | analysis/batch_polar/batch_analyze_J10.py | Python | gpl-3.0 | 4,528 | 0.04439 | # ################################################################
#
# Active Particles on Curved Spaces (APCS)
#
# Author: Silke Henkes
#
# ICSMB, Department of Physics
# University of Aberdeen
# Author: Rastko Sknepnek
#
# Division of Physics
# School of Engineering, Physics and Mathem... | ace as appropriate (do not go the Yaouen way and fully automatize ...)
basefolder = '/home/silke/Documents/CurrentProjects/Rastko/Runs/'
outfolder= '/home/silke/Documents/CurrentProjects/Rastko/analysis/'
#JList=['10', '1', '0.1', '0.01' | ]
vList=['0.005','0.01','0.02','0.05','0.1','0.2','0.5','1']
JList=['10']
nu_r='0.002'
phi='1'
sigma=1
nstep=10000000
nsave=10000
nsnap=int(nstep/nsave)
skip=int(nsnap/2)
nbin=180
for i in range(len(vList)):
for j in range(len(JList)):
print vList[i],JList[j]
folder=basefolder+'data_v0_'+vList[i]+'/data_j_'+JLis... |
wbtuomela/mezzanine | mezzanine/pages/urls.py | Python | bsd-2-clause | 332 | 0 | from __future__ import unicode_literals
from django.conf.urls import url
from django.conf import settings
from mezzanine.pages import page_processors, views
page_processors.autodiscover()
# Page patterns.
urlpatterns = | [
| url("^(?P<slug>.*)%s$" % ("/" if settings.APPEND_SLASH else ""),
views.page, name="page"),
]
|
winstonschroeder77/Python_KMR-1.8 | setup.py | Python | mit | 1,394 | 0.021521 | # Workaround for issue in Python 2.7.3
# See http://bugs.python.org/issue15881#msg170215
try:
import multiprocessing
except ImportError:
pass
try:
# Try | using ez_setup to install setuptools if not already installed.
from ez_setup import use_setuptools
use_setuptools()
except ImportError:
# Ignore import error and assume Python 3 which already has setuptools.
pass
from setuptools import setup, find_pa | ckages
classifiers = ['Development Status :: 4 - Beta',
'Operating System :: POSIX :: Linux',
'License :: OSI Approved :: MIT License',
'Intended Audience :: Developers',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python... |
metalwihen/udacity-full-stack-nanodegree-projects | Project1/entertainment_center.py | Python | unlicense | 1,627 | 0.004917 | import media
import fresh_tomatoes
def run():
""" Generate and open the movies listing html page """
fresh_tomatoes.open_movies_page(
get_movie_list(),
"Top Anime Movies")
def get_movie_list():
""" Retrieve a list of movies """
return [media.Movie(
"Your Name",
... | tch?v=xU47nhruN-Q"),
media.Movie(
"My Neighbor Totoro",
"https://upload.wikimedia.org/wikipedia/en/0/02/My_Neighbor_Totoro_-_Tonari_no_Totoro_%28Movie_Poster%29.jpg",
"https://www.youtube.com/watch?v=92a7Hj0ijLs"),
media.Movie(
"Spi... | w"),
media.Movie(
"Kiki's Delivery Service",
"https://upload.wikimedia.org/wikipedia/en/0/07/Kiki%27s_Delivery_Service_%28Movie%29.jpg",
"https://www.youtube.com/watch?v=4bG17OYs-GA"),
media.Movie(
"Wolf Children",
"... |
sassoftware/rmake3 | rmake/build/buildjob.py | Python | apache-2.0 | 12,119 | 0.002888 | #
# Copyright (c) SAS Institute Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | n self._hasTrovesByCheck('isBuilding')
def iterBuildableTroves(self):
return (x for x in self.iterTroves() if x.isBuildable())
def hasBuildableTroves(self):
return self._hasTrovesByCheck('isBuildable')
def _hasTrovesByCheck(self, check):
for trove in self.iterTroves():
... | f):
if '' in self.configs:
return self.configs['']
def setMainConfig(self, config):
self.configs[''] = config
for trove in self.iterTroves():
if not trove.getContext():
trove.cfg = config
def getC |
ovresko/erpnext | erpnext/patches/v9_0/remove_non_existing_warehouse_from_stock_settings.py | Python | gpl-3.0 | 322 | 0.021739 | from __future__ import unicode_literals
import frappe
def execute():
default_warehouse = frappe.db.get_value("Stock Settings", None, "default_warehouse")
if default_warehouse:
if not frappe.db.get_value("Warehouse", {"name": d | efault_warehouse}):
| frappe.db.set_value("Stock Settings", None, "default_warehouse", "") |
Yelp/paasta | paasta_tools/secret_providers/vault.py | Python | apache-2.0 | 6,460 | 0.000464 | import getpass
import os
from typing import Any
from typing import Dict
from typing import List
from typing import Mapping
from typing import Optional
try:
from vault_tools.client.jsonsecret import get_plaintext
from vault_tools.paasta_secret import get_vault_client
from vault_tools.gpg import TempGpgKeyri... | we contact the correct vault cluster to get/set secrets"
% e
)
raise
def write_secret(
self,
action: str,
secret_name: str,
plaintext: bytes,
cross_environment_motivation: Optional[str] = None,
) -> None:
with TempGpgKeyri... | tems:
client = self.clients[ecosystem]
encrypt_secret(
client=client,
action=action,
ecosystem=ecosystem,
secret_name=secret_name,
soa_dir=self.soa_dir,
plaintext=plain... |
elyak123/obeying-the-testing-goat | functional_tests/test_simple_list_creation.py | Python | mit | 3,802 | 0.005786 | from selenium import webdriver
from functional_tests.base import FunctionalTest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class NewvisitorTest(FunctionalTest):
def test_can_start_a_list_for_one_user(self):
#Edith has heard about a cool new on-line to-do app
#She... | ock feathers" into a text box
inputbox.send_keys('Buy peacock feathers')
#When she presses enter the page gets updated and now the page lists
#1. | - "Buy Peak Cock feathers" as an item in a to-do list
inputbox.send_keys(Keys.ENTER)
self.wait_for_row_in_list_table('1: Buy peacock feathers')
# There is still a text box inviting her to add another item. She
# enters "Use peacock feathers to make a fly" (Edith is very methodical) ... |
AversivePlusPlus/AversivePlusPlus | modules/thirdparty/arduino/conanfile.py | Python | bsd-3-clause | 1,882 | 0.006376 | from conans import ConanFile, CMake
class AversivePlusPlusModuleConan(ConanFile):
name = "arduino"
version = "0.1"
exports = "*"
settings = "target"
def build(self):
sources = '%s/cores/arduino/*.c %s/cores/arduino/*.cpp' % (self.conanfile_directory, self.conanfile_directory)
inc_a... | ctory)
flags = '-mmcu=atmega2560 -DF_CPU=16000000L -Os'
if self.settings.target == "arduino-uno":
inc_variant = '-I%s/variants/standard/' % (self.conanfile_dire | ctory)
flags = '-mmcu=atmega328p -DF_CPU=16000000L -Os'
elif self.settings.target == "arduino-mega2560":
inc_variant = '-I%s/variants/mega/' % (self.conanfile_directory)
flags = '-mmcu=atmega2560 -DF_CPU=16000000L -Os'
self.run('avr-gcc -c %s %s %s %s' % ... |
hbeatty/incubator-trafficcontrol | traffic_control/clients/python/to_access/__init__.py | Python | apache-2.0 | 16,838 | 0.028151 | #
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under ... | :`TO_URL`, :envvar:`TO_USER`, and
:envvar`TO_PASSWORD` environment variables to define their connection to and authentication with the
Traffic Ops server. Typically, setting these is easier than using the long options :option:`--to-url`,
:option:`--to-user`, and :option:`--to-password` on every invocation.
Exit Codes
... | ` script can sometimes be used by the caller to determine what
the result of calling the script was without needing to parse the output. The exit codes used are:
0
The command executed successfully, and the result is on STDOUT.
1
Typically this exit code means that an error was encountered when parsing positional co... |
hydroshare/hydroshare_temp | hs_core/admin.py | Python | bsd-3-clause | 527 | 0.009488 | from mezzanine.pages.admin import PageAdmin
from django.contrib.gis import admin
from .models import *
from dublincore.models import QualifiedDublinCoreElement
class InlineDublinCoreMetadata(generic.GenericTabularInline):
model = QualifiedD | ublinCoreElement
class InlineResourceFiles(ge | neric.GenericTabularInline):
model = ResourceFile
class GenericResourceAdmin(PageAdmin):
inlines = PageAdmin.inlines + [InlineDublinCoreMetadata, InlineResourceFiles]
admin.site.register(GenericResource, GenericResourceAdmin)
|
fishilico/shared | python/crypto/ed25519_tests.py | Python | mit | 49,246 | 0.001624 | #!/usr/bin/env python
# -*- coding:UTF-8 -*-
# Copyright (c) 2018 Nicolas Iooss
#
# 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
... | ARISING FROM,
# OUT OF OR IN C | ONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Perform some operations with Ed25519 algorithm
Curve25519:
* q = 2**255 - 19
= 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed
* d = (-121665 / 121666) modulo q
= 0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab... |
birlrobotics/HMM | hmm_for_baxter_using_only_success_trials/emission_log_prob_plot.py | Python | bsd-3-clause | 5,609 | 0.008736 | #!/usr/bin/env python
import os
import pandas as pd
import numpy as np
from sklearn.externals import joblib
from math import (
log,
exp
)
from matplotlib import pyplot as plt
import time
import util
import math
import ipdb
import matplotlib
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcParams['ps.font... | riangle_img = open(
os.path.join(
figure_save_path,
'check_if_viterbi_path_grow_incrementally',
"state_%s"%state_no,
"%s.png"%trial_name,
),
'rb',
)
import matplotlib.image as mpi | mg
img=mpimg.imread(vp_triangle_img)
plot_idx = 3*trial_no
ax_list[plot_idx].imshow(img)
ax_list[plot_idx].set_title('growing viterbi paths')
ax_list[plot_idx].set_ylabel('time step')
ax_list[plot_idx].set_xlabel('length of viterbi path')
plot_idx = 3*trial_no+2... |
edx/edx-e2e-tests | regression/tests/studio/test_course_outline.py | Python | agpl-3.0 | 2,675 | 0.000748 | """
End to end tests for Studio Course Outline page
"""
import os
from unittest import skip
from bok_choy.web_app_test import WebAppTest
from edxapp_acceptance.pages.common.utils import assert_side_bar_help_link
from regression.pages.studio import EDXAPP_CMS_DOC_LINK_BASE_URL
from regression.pages.studio.course_outl... | , then close it.
if self.browser.current_url.startswith('https://edx.readthedocs.io'):
# TODO wrap this i | n a try/except block or otherwise harden,
# make sure that you now have an active window (the other one)
# and it's the right one (i.e. Studio or LMS)
self.browser.close() # close only the current window
self.browser.switch_to_window(self.browser.window_handles[0])
|
ltyscu/Analysis-of-CGPs-Mechanisms | bit_behavior.py | Python | bsd-2-clause | 2,708 | 0.003693 | '''
Takes file names from the final/ folder as command line arguments
and parses the semantic information to produce the contents of Table VI.
Use this module as an executable to process each problem's results:
``python bit_behavior final/decode_*.dat.gz``
Note: Do not mix results from different problems.
'''
import... | combined[version][test] = find_median(line)
# print the information in sorte | d order based on the first key
for version in sorted(combined.keys(), key=lambda version: combined[version][interesting[0]]):
duplicate, ordering = version
duplicate = ('\emph{%s}' % pretty_name[duplicate]).rjust(18)
ordering = ('\emph{%s}' % pretty_name[ordering]).rjust(14)
# LaTeX ... |
kevinkle/semantic | superphy/src/upload/python/_sparql.py | Python | apache-2.0 | 11,605 | 0.000431 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
This module wraps often-used queries to the Blazegraph SPARQL endpoint.
"""
#from SPARQLWrapper import JSON, SPARQLWrapper
from superphy.shared.endpoint import query as _sparql_query
from superphy.shared.endpoint import update as _sparql_update
__author__ = "Stephen ... | (must be from the superphyontology)
Returns: a boolean indicating if the instance exists or not in the database
"""
results = _sparql_query(
'PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n'
'PREFIX owl: <http://www.w3.org/2002/07/owl#>\n'
'PREFIX : <https://git... | nome instances in Blazegraph that are missing a sequence and hasn't
failed sequence validation
Returns: list of SPARQL URIs for Genome instances
"""
results = _sparql_query(
'PREFIX : <https://github.com/superphy#>\n'
'PREFIX gfvo: <http://www.biointerchange.org/gfvo#>\n'
'PRE... |
saghul/aiodns | aiodns/__init__.py | Python | mit | 5,081 | 0.005511 |
import asyncio
import functools
import pycares
import socket
from typing import (
Any,
List,
Optional,
Set
)
from . import error
__version__ = '3.0.0'
__all__ = ('DNSResolver', 'error')
READ = 1
WRITE = 2
query_type_map = {'A' : pycares.QUERY_TYPE_A,
'AAAA' : pycares.QUER... | = None # type: Optional[asyncio.TimerHandle]
@property
def nameservers(self) -> pycares.Channel:
return self._channel.servers
@nameservers.setter
def nameservers(self, value: List[str]) -> None:
self._channel.servers = value
@staticmethod
def _callback(fut: asyncio.Future, re... | fut.set_exception(error.DNSError(errorno, pycares.errno.strerror(errorno)))
else:
fut.set_result(result)
def query(self, host: str, qtype: str, qclass: str=None) -> asyncio.Future:
try:
qtype = query_type_map[qtype]
except KeyError:
raise ValueError('inv... |
BackupTheBerlios/pyhttpd-svn | core/baseHTTPServer.py | Python | gpl-2.0 | 2,489 | 0.045802 | # -*- coding: utf-8 -*-
##################################################################
# pyHTTPd
# $Id$
# (c) 2006 by Tim Taubert
##################################################################
import socket, sys, os, threading
class pHTTPServer:
address_family = socket.AF_INET
socket_type = socket.SOCK_S... | st()
except socket.error:
return
if self.verify_request(request, client_address):
try:
self.process_request(request, client_address)
except:
self.handle_error(request, client_address)
self.close_request(request)
def verify_request(self, request, client_address):
return True
def process_... | uest(request)
except:
self.handle_error(request, client_address)
self.close_request(request)
def process_request(self, request, client_address):
t = threading.Thread(target = self.process_request_thread,
args = (request, client_address))
if self.daemon_threads:
t.setDaemon (1)
t.start()
d... |
openconfig/oc-pyang | openconfig_pyang/plugins/util/html_emitter.py | Python | apache-2.0 | 14,661 | 0.017871 | """
Copyright 2015 Google, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
di... | ort Environment, FileSystemLoader
from .doc_emitter import DocEmitter
from .yangdoc_defs import YangDocDefs
from . import html_helper
fro | m . import yangpath
class HTMLEmitter(DocEmitter):
def genModuleDoc(self, mod, ctx):
"""HTML emitter for top-level module documentation given a
ModuleDoc object"""
ht = html_helper.HTMLHelper()
# TODO: this is far too hardcoded
mod_div = ht.open_tag("div", newline=True)
# module name
... |
gtuinsaat/TRKYH_Veritabani_programi-master | Kodlar/S-r-m 1/aad_kyh_process_function.py | Python | mit | 26,051 | 0.021569 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 19 14:46:48 2017
@author: User
"""
#%% MODULE IMPORT
def aad_process(file_url):
from IPython.core.display import display, HTML; display(HTML("<style>.container { width:95% !important; }</style>"))
from time import gmtime, strftime
import datetime
import nu... | s=['N-S','E-W','U-D']) # Bu boş bir dataframe
data_raw_displacement = pd.DataFrame(columns=['N-S','E-W','U-D']) # Bu boş bir dataframe
data_filtered_acceleration = pd.DataFrame(columns=['N-S','E-W','U-D']) # Bu boş bir dataframe
data_filtered_velocity = pd.DataFrame(columns=['N-S','E-W','U-D']) # Bu boş bir... | frame
plt.rcParams.update({'font.size': 10})
duration_Arias_intensity = [] # duration değerleri
for counter , dogrultu_ismi in enumerate(['N-S','E-W','U-D']):
#= HAM ZAMAN SERİLERİNİN ÇIKARTILMASI ======================================================================
acceleration = data_raw... |
Audiveris/omr-dataset-tools | tools/addNoise/FileOperations.py | Python | agpl-3.0 | 2,085 | 0.00048 | # -*- coding: utf-8 -*-
__author__ = 'Pulimootil'
"""
This class will handle all the file related operations
"""
import os
import cv2
class FileOperatoins(object):
def __init__(self, filename, xmlFile):
self.checkFile(filename, xmlFile)
''' Set the output folder '''
def setOutput(self, outpu... | image '''
def show(self, orig):
cv2.namedWindow("Image")
cv2.imshow("Image", orig)
cv2.waitKey(0)
cv2.destroyAllWindows()
''' Check for valid files '''
def checkFile(self, | imgfilename, xmlFilename):
if os.path.isfile(imgfilename):
self.imgFilename = imgfilename
else:
raise 'Invalid image filename:' + imgfilename
if os.path.isfile(xmlFilename):
self.xmlFilename = xmlFilename
else:
raise 'Invalid xml filename:... |
tschmorleiz/amcat | amcat/models/coding/fieldcolumn.py | Python | agpl-3.0 | 1,767 | 0.010753 | from amcat.tools import toolkit
from amcat.tools.table.table3 import ObjectColumn
import logging; log = logging.getLogger(__name__)
class FieldColumn(ObjectColumn):
"""ObjectColumn based on a AnnotationSchemaField"""
def __init__(self, field, article=None, fieldname=None, label=None, fieldtype=None):
... | % | (values, fieldname, dir(values)))
raise
log.debug(">>>>>> values=%r, fieldname=%r, --> val=%s" % (values, fieldname, val))
return val
|
dwalton76/ev3dev-lang-python | utils/console_fonts.py | Python | mit | 2,278 | 0.004829 | #!/usr/bin/env micropython
from time import sleep
from sys import stderr
from os import listdir
from ev3dev2.console import Console
"""
Used to iterate over the sys | tem console fonts (in /usr/share/consolefonts) and show the max row/col.
Font names consist of three parameters - codeset, font face and font size. The codeset specifies
what characters will be supported by the | font. The font face determines the general look of the font. Each
font face is available in certain possible sizes.
For Codeset clarity, see https://www.systutorials.com/docs/linux/man/5-console-setup/#lbAP
"""
def show_fonts():
"""
Iterate through all the Latin "1 & 5" fonts, and see how many rows/columns
... |
stinbetz/nice_ride_charting | datify.py | Python | mit | 7,682 | 0.002603 | import csv
import re
import datetime
import string
import collections
def get_nr_data():
''' returns a list of lists each entry represents one row of NiceRide data
in form -- [[11/1/2015, 21:55], '4th Street & 13th Ave SE', '30009',
[11/1/2015, 22:05], 'Logan Park', '30104', '565', 'Casual'] where the
... | rt_date, start_time]
date_data = re.match('(\d+)/(\d+)/(\d+) (\d+):(\d+)', line[3])
end_date = datetime.date(int(date_data.group(3)),
int(date_data.group(1)),
int(date_data.group(2)))
end_time = datetime.time(int(date_data.group(... | int(date_data.group(5)),
0)
nr_data[index][3] = [end_date, end_time]
index += 1
return nr_data
def get_wx_data(filename):
''' returns a list of lists, each entry represents a day of weather data in
the form -- ['1', '30', '1... |
Sinar/popit_ng | popit/tests/tests_person_api.py | Python | agpl-3.0 | 50,109 | 0.003592 | __author__ = 'sweemeng'
from rest_framework import status
from popit.signals.handlers import *
from popit.models import *
from django.conf import settings
import json
import logging
from popit.tests.base_testcase import BasePopitTestCase
from popit.tests.base_testcase import BasePopitAPITestCase
from popit.serializers.... | erson_serializer = PersonSerializer(person, data=person_data, partial=True, language='en')
person_serializer.is_valid()
self.assertEqual(person_serializer.errors, {})
person_serializer.save()
person_ = Person.objects.language('en').get(id='ab1a5788e5bae955c048748fa6af0e97')
# The... | age('en').get(id='a66cb422-eec3-4861-bae1-a64ae5dbde61')
links = contact.links.language('en').filter(url="http://sinarproject.org")
self.assertEqual(links[0].url, "http://sinarproject.org")
def test_update_update_nested_links_person_serializer(self):
person_data = {
"id":"8497ba... |
ojengwa/grr | lib/flows/general/checks.py | Python | apache-2.0 | 3,088 | 0.006477 | #!/usr/bin/env python
"""A flow to run checks for a host."""
from grr.lib import aff4
from grr.lib import flow
from grr.lib import rdfvalue
from grr.lib.checks import checks
from grr.proto import flows_pb2
class CheckFlowArgs(rdfvalue.RDFProtoStruct):
protobuf = flows_pb2.CheckFlowArgs
class CheckRun | ner(flow.GRRFlow):
"""This flow runs checks on a host.
CheckRunner:
- Identifies what checks should be run for a host.
- Identifies the artifacts that need to be collected to perform those checks.
- Orchestrates collection of the host data.
- Routes host data to the | relevant checks.
- Returns check data ready for reporting.
"""
friendly_name = "Run Checks"
category = "/Checks/"
behaviours = flow.GRRFlow.behaviours + "BASIC"
@flow.StateHandler(next_state=["MapArtifactData"])
def Start(self):
"""."""
client = aff4.FACTORY.Open(self.client_id, token=self.token... |
pearsontechnology/st2contrib | packs/bitesize/actions/find_unapproved_ns.py | Python | apache-2.0 | 862 | 0.00232 | #!/usr/bin/python
import importlib
import logging
import os
import json
from datetime import datetime
from pprint import pprint
from st2actions.runners.pythonrunner import Action
class GetUnapproved(Action):
def run(self, allns):
output = []
| for ns in allns['items']:
if 'metadata' in ns and 'labels' in ns['metadata'] and ns['metadata']['labels'] is not None and 'status' in ns['metadata']['labels']:
output.append(ns['metadata']['name'])
if len(output) > 0:
print json.dumps(output)
else:
... | etime):
serial = obj.isoformat()
return serial
raise TypeError("Type not serializable")
|
caplin/qa-browsers | nodejs/node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/__init__.py | Python | unlicense | 21,827 | 0.010858 | #!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import copy
import gyp.input
import optparse
import os.path
import re
import shlex
import sys
import traceback
from gyp.common... | AppendFlag(flag, values, predicate, env_name, options):
"""Regenerate a list of command line flags, for an option of action='append'.
The |env_name|, if given, is checked in the environment and used to generate
an initial list of options, | then the options that were specified on the
command line (given in |values|) are appended. This matches the handling of
environment variables and command line flags where command line flags override
the environment, while not requiring the environment to be set when the flags
are used again.
"""
fla... |
rgtjf/Semantic-Texual-Similarity-Toolkits | stst/features/__init__.py | Python | mit | 525 | 0.001905 |
from stst.features.features_sequence import *
from stst.features.features_pos import *
from stst.features.features_ngram import *
from stst.features.features_bow import *
from stst.features.features_dependency import *
from stst.features.features_align import *
from stst.features.features_embedding import *
from stst.... | atures.features_tree_kerne | ls import *
from stst.features.features_wn import *
from stst.features.features_mt import *
from stst.features.features_nn import *
from stst.features.features_negative import * |
gnulinooks/sympy | sympy/core/function.py | Python | bsd-3-clause | 23,521 | 0.005569 | """
There are two types of functions:
1) defined function like exp or sin that has a name and body
(in the sense that function can be evaluated).
e = exp
2) undefined function with a name but no body. Undefined
functions can be defined using a Function class as follows:
f = Function('f')
(the result will... | SLATIONS[fname]
func = getattr(mpmath, | fname)
except (AttributeError, KeyError):
return
# Convert all args to mpf or mpc
try:
args = [arg._to_mpmath(prec) for arg in self.args]
except ValueError:
return
# Set mpmath precision and apply. Make sure precision is restored
# a... |
ytanay/thinglang | tests/compiler/test_inlining.py | Python | mit | 1,570 | 0.005096 | import pytest
from tests.compiler import compile_base, internal_call
from thinglang.compiler.opcodes import OpcodePushStatic, OpcodePushLocal
INLINING_TEST_PROGRAM = '''
thing Program
setup
number n1 = 0
number n2 = 1
{}
static does add with number a, number b
a + b
... | ushLocal(1),
internal_call('number.__addition__')
]
@pytest.mark.skip()
def test_inlining_binary_op_mixed():
assert compile_base(INLINING_TEST_PROGRAM.format('self.add(2, n1)'), trim=2) == [
OpcodePushLocal(1),
OpcodePushStatic(2),
internal_call('number.__addition__')
]
@... | all_simple():
assert compile_base(INLINING_TEST_PROGRAM.format('self.external_call("Hello")'), trim=2) == [
OpcodePushStatic(2),
internal_call('File.__constructor__')
]
@pytest.mark.skip()
def test_inlining_internal_call():
compile_base(INLINING_TEST_PROGRAM.format('Console.print(n1)'), tr... |
idf/FaceReader | facerec_py/facerec/serialization.py | Python | mit | 268 | 0 | import cPickle
def save_model(filename, model):
output = open(filename, 'wb')
cPickle.dump(model, output)
output.close()
def load_model(file | name):
pkl_file = open(filenam | e, 'rb')
res = cPickle.load(pkl_file)
pkl_file.close()
return res
|
elnoxgdl/destinystats | GuardianStats.py | Python | apache-2.0 | 5,360 | 0.03806 | #! /usr/bin/python
import requests, pprint, json
from collections import defaultdict
class GuardianStats:
# Bungie API KEY
api_key = '1b6d2823d9ba455db6d22c0c75ae55a2'
def __init__(self, psn_id):
self.membership_id = self.GetMembershipID(psn_id)
self.character_id = self.GetLatestUsedGuardian(self.membe... | p_id)
def GetMembershipID(self, psn_id):
membership_id = None
api_endpoint = 'https://www.bungie.net/Platform/Destiny/SearchDestinyPlayer/2/'+psn_id
headers = {'X-API-Key': self.api_key}
r = requests.get(api_endpoint, headers=headers)
if r.status_code == 200 :
data = r.json()
... | 'HTTP error: '+r.status_code
return membership_id
def GetLatestUsedGuardian(self, membership_id):
last_guardian_id = None
api_endpoint = 'https://www.bungie.net/Platform/Destiny/2/Account/'+membership_id+'/Summary/'
headers = {'X-API-Key': self.api_key}
r = requests.get(api_endp... |
linkhub-sdk/popbill.closedown.example.py | getPartnerURL.py | Python | mit | 1,149 | 0.001951 | # -*- coding: utf-8 -*-
# code for console Encoding difference. Dont' mind on it
import sys
import imp
imp.reload(sys)
try:
sys.setdefaultencoding('UTF8')
except Exception as E:
pass
import testValue
from popbill import ClosedownService, PopbillException
closedownService = ClosedownService(testValue.LinkID,... | imeYN = testValue.UseLocalTimeYN
' | ''
파트너 포인트충전 팝업 URL을 반환합니다.
- 보안정책에 따라 반환된 URL은 30초의 유효시간을 갖습니다.
- https://docs.popbill.com/closedown/python/api#GetPartnerURL
'''
try:
print("=" * 15 + " 파트너 포인트충전 URL 확인 " + "=" * 15)
# 팝빌회원 사업자번호
CorpNum = testValue.testCorpNum
# CHRG-포인트 충전 URL
TOGO = "CHRG"
url = closedownService.getPar... |
minghuascode/pyj | addons/DeferredHandler.py | Python | apache-2.0 | 927 | 0.016181 | """
A modification of pyjamas DeferredMethod
@author: Tobias Weber
@contact: [email protected]
"""
from pyjamas.Timer import Timer
global deferredHandlers
deferredHandlers = []
global timerIsActive
timerIsActive = False
def add(handler, arguments=[]):
deferredHandlers.append([handler, argumen | ts])
maybeSetDeferredHandlerTimer()
def flushDeferredHandlers():
for i in range(len(deferredHandlers)):
current = deferredHandlers[0]
del deferredHandlers[0]
if current:
handler = current[0]
args | = current[1]
handler(*args)
def maybeSetDeferredHandlerTimer():
global timerIsActive
if (not timerIsActive) and (not len(deferredHandlers)==0):
Timer(1, onTimer)
timerIsActive = True
def onTimer(t):
global timerIsActive
flushDeferredHandlers()
timerIsAc... |
ProjectSWGCore/NGECore2 | scripts/mobiles/generic/faction/rebel/rebel_commandant.py | Python | lgpl-3.0 | 1,902 | 0.027865 | import sys
from services.spawn import MobileTemplate
from services.spawn import WeaponTemplate
from resources.datatables import WeaponType
from resources.datatables import Difficulty
from resources.datatables import Options
from resources.datatables import FactionStatus
from java.util import Vector
def addTemplate(cor... | emplate.setFactionStatus(FactionStatus.Combatant)
templates = Vector()
templates.add('object/mobile/shared_dressed_rebel_brigadier_general_bith_male.iff')
templates.ad | d('object/mobile/shared_dressed_rebel_brigadier_general_human_female_01.iff')
templates.add('object/mobile/shared_dressed_rebel_brigadier_general_moncal_female.iff')
templates.add('object/mobile/shared_dressed_rebel_brigadier_general_rodian_female_01.iff')
templates.add('object/mobile/shared_dressed_rebel_brigadier_... |
colour-science/colour | colour/examples/recovery/examples_meng2015.py | Python | bsd-3-clause | 633 | 0.00158 | """Showcases reflectance recovery computations using *M | eng et al. (2015)* method."""
import numpy as np
import colour
from colour.utilities import message_box
message_box('"Meng et al. (2015)" - Reflectance Recovery Computations')
illuminant = colour.SDS_ILLUMINANTS["D65"]
XYZ = np.array([0.20654008, 0.12197225, 0.05136952])
message_box(
f'Recovering reflectanc | e using "Meng et al. (2015)" method from given '
f'"XYZ" tristimulus values:\n\n\tXYZ: {XYZ}'
)
sd = colour.XYZ_to_sd(XYZ, method="Meng 2015")
print(sd)
print(colour.recovery.XYZ_to_sd_Meng2015(XYZ))
print(colour.sd_to_XYZ(sd, illuminant=illuminant) / 100)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.