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 |
|---|---|---|---|---|---|---|---|---|
yes7rose/maya_utils | python/maya_utils/singleton.py | Python | mit | 330 | 0.010274 | # -*- coding: utf-8 -*-
# 只是个模板,继承还是有问题,不用于继承
class Singleton(o | bject):
def __init__(self):
globals()[self.__class__.__name__] = sel | f
def __call__(self):
return self
# class Singleton:
# def __call__(self):
# return self
#
# Singleton = Singleton() |
henniggroup/MPInterfaces | mpinterfaces/mat2d/electronic_structure/analysis.py | Python | mit | 32,249 | 0.000868 | from __future__ import print_function, division, unicode_literals
import os
import matplotlib as mpl
mpl.us | e('Agg')
import matplotlib.pyplot as plt
from matplotlib.font_m | anager import FontProperties
import numpy as np
from scipy.spatial.distance import euclidean
from pymatgen.core.structure import Structure
from pymatgen.io.vasp.outputs import Vasprun, Locpot, VolumetricData
from pymatgen.io.vasp.inputs import Incar
from pymatgen.electronic_structure.plotter import BSPlotter, BSPlot... |
kb8u/ZenPacks.Merit.AdvaFSP3000R7 | ZenPacks/Merit/AdvaFSP3000R7/FSP3000R7NCU.py | Python | gpl-2.0 | 933 | 0.006431 | ######################################################################
#
# FSP3000R7NCU object class
#
# Copyright (C) 2011 Russe | ll Dwarshuis, Merit Network, Inc.
#
# This program can be used under the GNU General Public License version 2
# You can find full information here: http://www.zenoss.com/oss
#
######################################################################
__doc__="""FSP3000R7NCU
FSP3000R7NCU is a component of a FSP3000R7Devic... | omponent):
"""FSP3000R7NCU object"""
portal_type = meta_type = 'FSP3000R7NCU'
_relations = (("FSP3000R7Dev",
ToOne(ToManyCont,
"ZenPacks.Merit.AdvaFSP3000R7.FSP3000R7Device",
"FSP3000R7Ncu")),
)
InitializeClass(FSP3000R7NCU)
|
dangoldin/python-tools | backup.py | Python | mit | 1,007 | 0.005958 | #!/usr/bin/env python
import datetime
start = datetime.datetime.strptime("2012-11-16", "%Y-%m-%d")
end = datetime.datetime.strptime("2013-10-25", "%Y-%m-%d")
table_name = 'sql_table_name_here';
dates = []
while start < end:
s = start.strftime('%Y-%m-%d')
start += datetime.timedelta(days=1)
e = start.str... | p {}_{}_{}.csv.gz s3://{}/{}/".format(table_name, s, e, S3_FOLDER, table_name)
print "rm {}_{}_{}.cs | v.gz".format(table_name, s, e)
|
dustin/couchapp | Couchapp.py | Python | apache-2.0 | 219 | 0.004566 | #!/us | r/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of couchapp released under the Apache 2 license.
# See the NOTICE for more information.
if __name__ == "__main__":
from couchapp import dispa | tch
|
korvyashka/pykongregate | pykongregate/api.py | Python | mit | 1,946 | 0 | import requests
import simplejson
from simplejson.scanner import JSONDecodeError
from .exceptions import NullResponseException
GET_USER_ITEMS_URL = "http://www.kongregate.com/api/user_items.json"
GET_ITEMS_URL = "http://www.kongregate.com/api/items.json"
USER_INFO_URL = "http://www.kongregate.com/api/user_info.json"... | ://developers.kongregate.com/docs/rest/user-items
:param user_id:
:type user_id: int
:param api_key:
:type api_key: str
:rtype: dict
:return: loaded json from response
"""
params = {
'api_key': api_key,
| 'user_id': user_id,
}
url = GET_USER_ITEMS_URL
return _handle_request(url, params)
def get_items_api(api_key):
"""
wrapper on API method:
http://developers.kongregate.com/docs/rest/items
:param api_key:
:type api_key: str
:rtype: dict
:return: loaded json from response
... |
ahmfrz/Let-s-Catalog | Lets_Catalog/models/category.py | Python | mit | 664 | 0.003012 | """Defines category table"""
import datetime
from database_setup import Base
from user import User
from sqlalchemy import Column, String, | ForeignKey, Integer, DateTime
from sqlalchemy.orm import relationship
class Category(Base):
''' Defines category table and columns '''
__tablename__ = "category"
id = Column(Integer, primary_key=True)
name = Column(String(150), nullable=False)
created_date = Column(DateTime, default=datetime.dat... | 'name': self.name
} |
niwinz/tornado-webtools | webtools/session/backend/database.py | Python | bsd-3-clause | 1,894 | 0.00528 | # -*- coding: utf-8 -*-
from sqlalchemy import Column, Table, select
from sqlalchemy.types import Integer, PickleType, DateTime, Unicode
from webtools.database import Base
from webtools.utils import timezone
from .base import BaseSessionEngine
session = Table("webtools_session", Base.metadata,
Column("id", Inte... | = res_proxy['data']
self._modified = False
def save(self):
sql = session.update()\
.where(session.c.key == self._current_session_key)\
.values(data=self._session_data)
self.db.execute(sql)
self.db.commit()
self._modified = False
def del... | if self._current_session_key is None:
return
self.db.execute(session.delete().where(session.c.key == self._current_session_key))
self.db.commit()
self._current_session_key = None
self._session_data = None
|
ptosco/rdkit | rdkit/sping/SVG/__init__.py | Python | bsd-3-clause | 44 | 0 | # simp | le __init__.py
from .pidSVG import *
| |
danmackinlay/branching_process | branching_process/cts/background.py | Python | mit | 6,771 | 0 | """
Background kernels are *like* InfluenceKernel, but not necessarily integrable
and there is no support for differentiationg with respect to time.
"""
from .influence import InfluenceKernel
have_autograd = False
try:
import autograd.numpy as np
have_autograd = True
except ImportError as e:
import numpy ... | This is presumably for background rate modelling.
"""
# def kappa_bounds(self):
# return [(-1, None)] * self.n_bases
def f_kappa(self, **kwargs):
kappa = self.get_param('kappa', **kwargs)
mu = self.get_param('mu', 0.0, **kwargs)
return (np.maximum(kappa + 1, self.eps)) * mu... | at):
# Is this correct?
med = np.median(f_kappa_hat)
return dict(
mu=med,
kappa=f_kappa_hat/med - 1
)
class LogStepKernel(StepKernel):
"""
Piecewise-constant rate.
This is presumably for background rate modelling.
"""
def kappa_bounds(self):
... |
anant-dev/django | django/template/engine.py | Python | bsd-3-clause | 7,528 | 0 | from django.core.exceptions import ImproperlyConfigured
from django.utils import lru_cache, six
from django.utils.functional import cached_property
from django.utils.module_loading import import_string
from .base import Context, Template
from .context import _builtin_context_processors
from .exceptions import Template... | dling template inheritance recursively.
"""
template, origin = self.find_template(template_name)
if not hasattr(template, 'render'):
# template needs to be compiled
template = Template(template, origin, template_name, engine=self)
return template
def render_t... | ontext=None):
"""
Render the template specified by template_name with the given context.
For use in Django's test suite.
"""
if isinstance(template_name, (list, tuple)):
t = self.select_template(template_name)
else:
t = self.get_template(template_n... |
keshashah/GCompris | src/sudoku-activity/sudoku.py | Python | gpl-2.0 | 57,045 | 0.097607 | # gcompris - sudoku
#
# Copyright (C) 2005, 2008 Bruno Coudoin
#
# 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... | olor = 0x3366FFAAL
self.error_square_color = 0xFF3366AAL
self.lines_color = 0xFF3366ffL
self.fixed_number_color = 0x000000FFL
self.user_number_color = 0x000000FFL
self.root_sudo = None
self.sudoku = None # The current sud | oku data
self.sudo_size = 0 # the size of the current sudoku
self.sudo_region = None # the modulo region in the current sudoku
self.timer = 0 # The timer that highlights errors
self.symbolize_level_max = 8 # Last level in which we set symbols
self.symbols = [
(gcomp... |
openstack/trove | trove/tests/unittests/cluster/test_models.py | Python | apache-2.0 | 9,636 | 0 | # Copyright 2016 Tesora Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... |
test_instances = [{'flavor_id': 1, 'volume_size': 5},
{'flavor_id': 1, 'volume_size': 5},
{'flavor_id': 1, 'volume_size': 5}]
models.assert_same_instance_volumes(test_instances, required_size=5)
test_instances = [{'flavor_id': 1, 'volume_size... | tion.ClusterVolumeSizesNotEqual,
models.assert_same_instance_volumes,
test_instances)
test_instances = [{'flavor_id': 1, 'volume_size': 10},
{'flavor_id': 1, 'volume_size': 10},
{'flavor_id': 1, 'volume_size... |
mosquito/LXC-Web-Panel | lwp/lxc/__init__.py | Python | mit | 13,591 | 0.000368 | # LXC Python Library
# for compatibility with LXC 0.8 and 0.9
# on Ubuntu 12.04/12.10/13.04
# Author: Elie Deloumeau
# Contact: elie@deloumeau.fr
# The MIT License (MIT)
# Copyright (c) 2013 Elie Deloumeau
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associate... | e_exist(filename):
filename = '/etc/default/lxc'
if not file_exist(filename):
return False
config = configparser.SafeConfigParser()
cfg = {}
config.readfp(FakeSection(open(filename)))
cfg['use'] = config.get('DEFAULT', 'USE_LXC_BRIDGE | ').strip('"').strip('"')
cfg['bridge'] = config.get('DEFAULT', 'LXC_BRIDGE').strip('"').strip('"')
cfg['address'] = config.get('DEFAULT', 'LXC_ADDR').strip('"').strip('"')
cfg['netmask'] = config.get('DEFAULT', 'LXC_NETMASK').strip('"').strip('"')
cfg['network'] = config.get('DEFAULT', 'LXC_NETWORK').st... |
OCA/stock-logistics-warehouse | stock_location_empty/tests/__init__.py | Python | agpl-3.0 | 40 | 0 | from . import test_stock_locati | on_emp | ty
|
MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-2.1/Lib/encodings/cp861.py | Python | mit | 7,192 | 0.039627 | """ Python Character Mapping Codec generated from 'CP861.TXT' with gencodec.py.
Written by Marc-Andre Lemburg (mal@lemburg.com).
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
(c) Copyright 2000 Guido van Rossum.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,error... | ETTER TAU
0x00e8: 0x03a6, # GREEK CAPITAL LETTER PHI
0x00e9: 0x0398, # GREEK CAPITAL LETTER THETA
0x00ea: 0x03a9, # GREEK CAPITAL LETTER OMEGA
0x00eb: 0x03b4, # GREEK SMALL LETTER DELTA
0x00ec: 0x221e, # INFINITY
0x00ed: 0x03c6, # GREEK SMALL LETTER PHI
0x00ee: 0x03b5, # GREEK SMALL LETTER | EPSILON
0x00ef: 0x2229, # INTERSECTION
0x00f0: 0x2261, # IDENTICAL TO
0x00f1: 0x00b1, # PLUS-MINUS SIGN
0x00f2: 0x2265, # GREATER-THAN OR EQUAL TO
0x00f3: 0x2264, # LESS-THAN OR EQUAL TO
0x00f4: 0x2320, # TOP HALF INTEGRAL
0x00f5: 0x2321, # BOTTOM HALF INTEGRAL
0x00f6: 0x00f7, # DIVISION SIGN
0x00f7: 0x2248, #... |
fnp/redakcja | src/documents/management/commands/prune_audience.py | Python | agpl-3.0 | 2,111 | 0.001422 | # This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
#
import sys
from django.contrib.auth.models import User
from lxml import etree
from django.core.management import BaseCommand
from documents.models import Book
fro... | print('%s has no audience, skipping' % book.slug)
continue
for node in audience_nodes:
node.getparent().remove(node)
chunk.commit(
etree.tostring(tree, encoding='unicode'),
author=user,
description='automaty... | )
print('committed %s' % book.slug)
if not old_head.publishable:
print('Warning: %s not publishable, last head: %s, %s' % (
book.slug, old_head.author.username, old_head.description[:40].replace('\n', ' ')))
|
hoh/reloadr | examples/04_both.py | Python | lgpl-3.0 | 573 | 0 |
from time import sleep
from reloadr import reloadr
@reloadr
def move_z(target, dz):
target.z += dz
@reloadr
class Car:
x | = 0
y = 0
z = 0
def __init__(self, x=0 | , y=0, z=0):
self.x = x
self.y = y
self.z = z
def move(self, dx=0, dy=0):
self.x += dx
self.y += dy
def position(self):
return 'Car on {} {} {}'.format(self.x, self.y, self.z)
car = Car(1000, 3000)
while True:
car.move(1, 1)
move_z(car, 1)
print(ca... |
kobotoolbox/kobo_selenium_tests | kobo_selenium_tests/selenium_ide_exported/download_entered_data_test.py | Python | gpl-3.0 | 3,987 | 0.00928 | # -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
import unittest, time, re
class DownloadEnteredDataTest(unittest.TestCase):
def setUp(self)... | xt): break
except: pass
time.sleep(1)
else: self.fail("time out")
driver.find_element_by_css_selector("#forms-table a").click()
def is_element_present(self, how, what):
try: self. | driver.find_element(by=how, value=what)
except NoSuchElementException: return False
return True
def is_alert_present(self):
try: self.driver.switch_to_alert()
except NoAlertPresentException: return False
return True
def close_alert_and_get_its_text(self):
try:
... |
ipython-contrib/IPython-notebook-extensions | setup.py | Python | bsd-3-clause | 4,617 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Setup script for jupyter_contrib_nbextensions."""
# -----------------------------------------------------------------------------
# Imports
# -----------------------------------------------------------------------------
from __future__ import print_function
import os
... | noqa: E501
version='0.5.1',
author='ipython-contrib and jupyter-contrib developers',
author_email='jupytercontrib@gmail.com',
url=('https://github.com/'
'ipython-contrib/jupyter_contrib_nbextensions.git'),
download_url=('https://github.com/'
'i... | n', 'Jupyter', 'notebook'],
license='BSD',
platforms=['Any'],
packages=find_packages('src'),
package_dir={'': 'src'},
include_package_data=True,
py_modules=[
os.path.splitext(os.path.basename(path))[0]
for path in glob('src/*.py')
],
... |
cynapse/cynin | products/CMFNotification/tests/testInstallation.py | Python | gpl-3.0 | 4,873 | 0.002257 | """Tests for CMFNotification installation ad uninstallation.
$Id: testInstallation.py 65679 2008-05-25 23:45:26Z dbaty $
"""
from zope.component import getUtility
from zope.component import getMultiAdapter
from AccessControl.PermissionRole import rolesForPermissionOn
from plone.portlets.interfaces import IPortletMan... | PermissionOn(SUBSCRIBE_PERMISSION, self.portal))
se | lf.failUnlessEqual(roles, set(('Manager', 'Member')))
def testConfigletHasBeenAdded(self):
cptool = getToolByName(self.portal, 'portal_controlpanel')
configlets = [c.getId() for c in cptool.listActions()]
self.failUnless('cmfnotification_configuration' in configlets)
class TestUnInstall... |
luckielordie/conan | conans/client/tools/scm.py | Python | mit | 5,881 | 0.00204 | import os
import re
import subprocess
from six.moves.urllib.parse import urlparse, quote_plus
from subprocess import CalledProcessError, PIPE, STDOUT
from conans.client.tools.env import no_op, environment_append
from conans.client.tools.files import chdir
from conans.errors import ConanException
from conans.util.file... | with environment_append({"LC_ALL": "en_US.UTF-8"}) if self._force_eng else no_op():
if not self._runner:
return subprocess.check_output(command, shell=True).decode().strip()
else:
return self._runner(command)
def get_repo_root(self... | lf._password:
return url
if urlparse(url).password:
return url
user_enc = quote_plus(self._username)
pwd_enc = quote_plus(self._password)
url = url.replace("://", "://" + user_enc + ":" + pwd_enc + "@", 1)
return url
def _configure_ssl_verify(self):
... |
dex4er/django | tests/admin_views/urls.py | Python | bsd-3-clause | 617 | 0.001621 | from __future__ import absolute_import
from django.conf.urls import patt | erns, include
from . import views, customadmin, admin
urlpatterns = patterns('',
(r'^test_admin/admin/doc/', include('django.contrib.admindocs.urls' | )),
(r'^test_admin/admin/secure-view/$', views.secure_view),
(r'^test_admin/admin/', include(admin.site.urls)),
(r'^test_admin/admin2/', include(customadmin.site.urls)),
(r'^test_admin/admin3/', include(admin.site.urls), dict(form_url='pony')),
(r'^test_admin/admin4/', include(customadmin.simple_sit... |
pombredanne/metamorphosys-desktop | metamorphosys/META/analysis_tools/PYTHON_RICARDO/output_ingress_egress/scripts/ingress_egress.py | Python | mit | 19,842 | 0.005393 | """
Run test benches related to ingress/egress for a vehicle assembly model specified in settings.
"""
import sys
import os
import _winreg
from scipy.ndimage import measurements as meas
def query_analysis_tools():
"""
Find the location of the Ricardo Python library.
"""
analysis_tools_key... | self.desired_params['Manikin']
mani_list = [{'name': k,
'vehicle_role': manikins[k]['properties']['vehicle_role'],
datum_name: manikins[k]['datums'][datum_name]['global']}
for k in manikins]
# API returns a 4x4 matrix mark... | If vehicle role specified, filter list by role
return [m[datum_name][:-1, 3] for m in mani_list if m['vehicle_role'] == veh_role]
else:
return [m[datum_name][:-1, 3] for m in mani_list]
def get_vehicle_csys(self):
"""
Create a mock vehicle coordinate system b... |
Kaezon/allianceauth | allianceauth/services/modules/openfire/views.py | Python | gpl-2.0 | 7,676 | 0.004039 | import datetime
import logging
from django.contrib import messages
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.models import Group
from django.shortcuts import render, redirect
from allianceauth.services.forms import ServicePasswordForm
from .forms import Ja... | failed
if result != "":
logger.info("Successfully rese | t jabber password for user %s" % request.user)
messages.success(request, 'Reset jabber password.')
credentials = {
'username': request.user.openfire.username,
'password': result,
}
return render(request, 'services/service_credentials.html',... |
amremam2004/pygtk | examples/gtk/scrollable.py | Python | lgpl-2.1 | 8,475 | 0.001416 | #
# Reimplementation of gtk.Layout in python
# Example on how to implement a scrollable container in python
#
# Johan Dahlin <johan@gnome.org>, 2006
#
# Requires PyGTK 2.8.0 or later
import pygtk
pygtk.require('2.0')
import gobject
import gtk
from gtk import gdk
class Child:
widget = None
x = 0
y = 0
def... | (gobject.SIGNAL_RUN_LAST, None,
(gtk.Adjustment, gtk.Adjustment)))
def __init__(self):
self._ | children = []
self._width = 100
self._height = 100
self._hadj = None
self._vadj = None
self._bin_window = None
self._hadj_changed_id = -1
self._vadj_changed_id = -1
gtk.Container.__init__(self)
if not self._hadj or not self._vadj:
self... |
dshpet/nure_TPDS | PrefixSum/PrefixSumParallelExtraNaive.py | Python | mit | 1,237 | 0.021827 | #!/usr/bin/env python
'''
Naive parallel algorithm of prefix sum
http://people.cs.vt.edu/yongcao/teaching/cs5234/spring2013/slides/Lect | ure10.pdf
'''
import threading
# look maybe multiprocessing lib
import TestFunction
test_data = [2,6,2,3,5]
'''
Generic sum function
'''
def accumulate(in_list, amount, out_list, out_index):
sum = 0
for i in range(0, amount):
sum += in_list[i]
out_list[out_index] = sum
'''
What is prefix ... |
def prefixSum(num_list):
# create new output holder of the same size
out = [0] * len(num_list)
jobs = []
for i in range(0, len(num_list)):
thread = threading.Thread(target = accumulate(num_list, i + 1, out, i))
jobs.append(thread)
for job in jobs:
job.start()
for job in jobs:
job.join()
... |
mathemage/h2o-3 | h2o-py/tests/testdir_munging/pyunit_categories.py | Python | apache-2.0 | 456 | 0.015351 | import sys
sys.path.insert(1,"../ | ../")
import h2o
from tests import pyunit_utils
def pyunit_categories():
iris = h2o.import_file(pyunit_utils.locate("smalldata/iris/iris.csv"))
category_list = iris['C5'].categories()
print(category_list)
assert set(category_list) == set(['Iris-setosa', 'Iris-versicolor', 'Iris-virginica'])
if __... | pyunit_categories() |
google/embedding-tests | eval_word_embedding.py | Python | apache-2.0 | 2,379 | 0.004624 | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | n import MODEL_DIR
from gensim.models import Word2Vec, FastText
from utils.word_utils import load_glove_model, load_tf_embedding
flags.DEFINE_string('model', 'w2v', 'Word embedding model')
flags.DEFINE_float('noise_multiplier', 0.,
'Ratio of the standard deviation to the clipping norm')
flags.DEFINE... | 'l2_norm_clip', 0., 'Clipping norm')
flags.DEFINE_integer('epoch', 4, 'Load model trained this epoch')
flags.DEFINE_integer('microbatches', 128, 'microbatches')
flags.DEFINE_integer('exp_id', 0, 'Experiment trial number')
flags.DEFINE_string('save_dir', os.path.join(MODEL_DIR, 'w2v'),
'Model directo... |
OSURoboticsClub/Rover2015 | software/ros-packages/motor_controller/scripts/motor_queue_proc.py | Python | mit | 2,620 | 0.035496 | #!/usr/bin/env python
import itertools
import time
import rospy
from std_msgs.msg import String
class QueueProc(object):
def __init__(self):
rospy.init_node('motor_queue_proc', anonymous=True)
self.state_change = rospy.Publisher('/motor/state_change', String, queue_size=10)
rospy.Subscriber("/mot... | ight"))
tmer.start()
#
# General timer class, does nothing
#
class GeneralTimer():
def __ | init__(self, distance, callback, is_angle):
self.callback = callback
def start(self):
self.callback()
def get_time(self):
return 0
#
# A time based timer
#
class TimeTimer(GeneralTimer):
def __init__(self, distance, callback, is_angle):
self.callback = callback
#distance in ... |
Arlefreak/ApiArlefreak | portfolio/migrations/0017_auto_20170606_0238.py | Python | mit | 546 | 0.001832 | # -*- coding: utf | -8 -*-
# Generated by Django 1.11.1 on 2017-06-06 02:38
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('portfolio', '0016_auto_20170519_1725'),
]
operations = [
mi... | field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='portfolio.LinkCategory'),
),
]
|
sahat/bokeh | examples/plotting/cloud/glucose.py | Python | bsd-3-clause | 1,424 | 0.007725 |
import pandas as pd
from bokeh.sampledata.glucose import data
from bokeh.plotting import *
output_cloud("glucose")
hold()
dates = data.index.to_series()
figure(x_axis_type="datetime", tools="pan,wheel_zoom,box_zoom,reset,previewsave")
line(dates, data['glucose'], color='red', legend='glucose')
line(dates, data['... | line(day.index.to_series(), day['glucose'],
line_color="gray", line_dash="4 4", line_width=1, legend="glucose")
scatter(highs.index.to_series(), highs['glucose'] | , size=6, color='tomato', legend="high")
scatter(lows.index.to_series(), lows['glucose'], size=6, color='navy', legend="low")
curplot().title = "Glucose Range"
xgrid()[0].grid_line_color=None
ygrid()[0].grid_line_alpha=0.5
data['inrange'] = (data['glucose'] < 180) & (data['glucose'] > 80)
window = 30.5*288 #288 is av... |
madisona/django-image-helper | image_helper/tests/test_app/models.py | Python | bsd-3-clause | 216 | 0 | from django.db import models
from image_helper.fields import SizedImag | eField
class TestModel(models.Model):
image = SizedI | mageField(
upload_to='test_images', size=(220, 150), thumbnail_size=(100, 100))
|
Elico-Corp/odoo-addons | business_requirement_deliverable_project_task_mandatory/models/__init__.py | Python | agpl-3.0 | 203 | 0 | # -*- coding: utf-8 -*-
# © 2017 Elico Corp (www.elico-corp.com).
# License AGPL-3.0 or later (http://www.gnu.org/ | licenses/agpl.html).
from . import project_project_category
from . import project_ | task
|
forter/boten | test/test_botparse.py | Python | apache-2.0 | 2,177 | 0.000459 | from boten.core import BaseBot
import payloads
class TestBot(BaseBot):
def command_arg_bot(self, user_name):
yield "hello {}".format(user_name)
def command_no_arg_bot(self):
yield "hello"
def command_optional_arg_bot(self, optional="default"):
yield "hello {}".format(optional)
... | llo derp'
def test_optional_arg_bot_with_no_arg():
bot = TestBot({})
response = list(bot.run_command(payloads.optional_arg_bot_with_no_arg))
assert response[0] == 'hello default'
def test_two_message_bot():
bot = TestBo | t({})
response = list(bot.run_command(payloads.two_message_bot))
assert len(response) == 2
def test_help_subcommand():
bot = TestBot({})
response = list(bot.run_command(payloads.no_arg_bot_with_arg))
assert response[0].startswith("Got TypeError") # Help message
|
ubivar/ubivar-python | setup.py | Python | mit | 2,448 | 0.006536 | import os
import sys
import warnings
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
try:
| from distutils. | command.build_py import build_py_2to3 as build_py
except ImportError:
from distutils.command.build_py import build_py
path, script = os.path.split(sys.argv[0])
os.chdir(os.path.abspath(path))
install_requires = []
if sys.version_info < (2, 6):
warnings.warn(
'Python 2.5 is not supported by Ubivar. If... |
jdob/bonkbot | plugins/ops.py | Python | gpl-2.0 | 720 | 0 | #!/usr/bin/python
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, inc | luding the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
from bonkbot.bot.decorators import join
def init_plugin(config, irc_client):
return [giv... | n't try to op yourself
if new_op != message.config.get('bot', 'nick'):
message.irc_client.give_ops(message.channel()[1:], message.author())
|
nathangeffen/tbonline-old | tbonlineproject/gallery/admin.py | Python | mit | 1,624 | 0.009852 | '''Admin interface registers Image model with admin.site.
'''
from django.contrib import admin
from django.contrib.contenttypes import generic
from django.forms.widgets import HiddenInput
from django.db.models import PositiveIntegerField
from credit.admin import OrderedCreditInline
from gallery.models import Gallery... | setup/tinymce_setup.js',
]
admin.site.register(Image, ImageAdmi | n)
admin.site.register(Gallery, GalleryAdmin)
|
johnwiseheart/HangoutsBot | hangupsbot/plugins/image_links.py | Python | gpl-3.0 | 2,109 | 0.003793 | """
Identify images, upload them to google plus, pos | t in hangouts
"""
import aiohttp, asyncio, io, logging, os, re
import plugins
logger = logging.getLogger(__name__)
def _initialise():
plugins.register_handler(_watch_image_link, type="message")
@asyncio.coroutine
def _watch_image_link(bot, event, command):
# Don't handle events caused by the bot himself... | urn
if " " in event.text:
"""immediately reject anything with spaces, must be a link"""
return
probable_image_link = False
event_text_lower = event.text.lower()
if re.match("^(https?://)?([a-z0-9.]*?\.)?imgur.com/", event_text_lower, re.IGNORECASE):
"""imgur links can be suppl... |
auag92/n2dm | Asap-3.8.4/Test/testMonteCarloEMT.py | Python | mit | 1,391 | 0.007189 | print
print "This test runs Verlet dynamics with the MonteCarloEMT potential instead"
print "of the usual EMT potential. The result must be the same, but the"
print "performance will be slightly worse."
print
from Asap import *
from Asap.Dynamics.VelocityVerlet import VelocityVerlet
from cPickle import *
from Numer... | load(file("testVerlet.pickle"))
init_pos = array(data["initial"])
init_pos.shape = (-1,3)
init_box = array(data["box"])
init_box.shape = (3,3)
atoms = ListOfAtoms(positions=init_pos, cell=init_box)
atoms.SetAtomicNumbers(47)
atoms.SetCa | lculator(MonteCarloEMT())
dyn = VelocityVerlet(atoms, 2 * femtosecond)
for i in range(20):
dyn.Run(10)
epot = atoms.GetPotentialEnergy() / len(atoms)
ekin = atoms.GetKineticEnergy() / len(atoms)
print "E_pot = %-12.5f E_kin = %-12.5f E_tot = %-12.5f" % (epot, ekin,
... |
xcgspring/dependence_repo | manager/dependence_repo_manager/ui/resources_rc.py | Python | apache-2.0 | 443,165 | 0.000011 | # -*- coding: utf-8 -*-
# Resource object code
#
# Created: Wed Jun 17 16:47:37 2015
# by: The Resource Compiler for PyQt (Qt v4.8.6)
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore
qt_resource_data = "\
\x00\x00\x14\x89\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x... | 3\xe9\xd3\xa9\x0 | 8\x55\x58\
\xd6\x4f\x11\x5a\x0c\x0f\x61\xf9\x71\x41\x61\x99\x43\x11\x6a\xcc\
\x47\x58\xee\x2b\x30\x2c\xf3\xee\xb2\x22\xd4\x84\xc2\xb2\x5d\x8a\
\xd0\x56\x79\x09\xcb\xd5\xd6\x37\xaa\x66\x8a\xd0\x56\x28\x2c\x6d\
\x29\x42\x1b\xe5\x21\x2c\x3f\x72\x1a\x96\x39\x06\x19\xe6\xb8\xf9\
\x9d\x4e\x1d\x67\x11\xea\x25\x2c\x37\xbb\x0e\... |
MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-3.0/Lib/lib2to3/fixes/fix_urllib.py | Python | mit | 7,255 | 0.000276 | """Fix changes imports of urllib which are now incompatible.
This is rather similar to fix_imports, but because of the more
complex nature of the fixing for urllib, | it has its own fixer.
"""
# Author: Nick Edds
# Local imports
from .fix_imports import alternates, FixImport | s
from .. import fixer_base
from ..fixer_util import Name, Comma, FromImport, Newline, attr_chain
MAPPING = {'urllib': [
('urllib.request',
['URLOpener', 'FancyURLOpener', 'urlretrieve',
'_urlopener', 'urlcleanup']),
('urllib.parse',
... |
zadgroup/edx-platform | openedx/core/lib/logsettings.py | Python | agpl-3.0 | 5,765 | 0 | """Get log settings."""
import os
import platform
import sys
from logging.handlers import SysLogHandler
LOG_LEVELS = ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']
def get_logger_config(log_dir,
logging_env="no_env",
tracking_filename="tracking.log",
... | logger_config['loggers']['']['level'] = 'INFO'
logger_config['handlers'].update({
'local': {
'level': | local_loglevel,
'class': 'logging.handlers.SysLogHandler',
'address': '/dev/log',
'formatter': 'syslog_format',
'facility': SysLogHandler.LOG_LOCAL0,
},
'tracking': {
'level': 'DEBUG',
'class': 'loggi... |
motmot/wxglvideo | motmot/wxglvideo/wxglvideo.py | Python | bsd-3-clause | 4,761 | 0.008402 | import wx
import wx.glcanvas
import pyglet
import pyglet.gl as gl
import pyglet.gl
import motmot.wxvideo.wxvideo as wxvideo
# XXX TODO:
# check off-by-one error in width/coordinate settings (e.g. glOrtho call)
# allow sharing of OpenGL context between instances
NewImageReadyEvent = wx.NewEventType() # use to trigge... | pyglet.gl.current_context = self
else:
# tested on 1.0
pyglet.gl._current_context = self
self.glcanvas.SetCurrent()
class DynamicImageCanvas(wx.glcanvas.GLCanvas):
"""Display image data to OpenGL using as few resources as possible"""
def _setcurrent(self,hack_ok=Tru... | self.wxcontext.SetCurrent()
def __init__(self, *args, **kw):
attribList = kw.get('attribList',None)
if attribList is None:
attribList = [
wx.glcanvas.WX_GL_RGBA,
wx.glcanvas.WX_GL_DOUBLEBUFFER, # force double buffering
wx.glcanvas.WX_G... |
vasco-santos/CertificationService | certModule/CertAuthority.py | Python | mit | 6,803 | 0.001617 | # -*- coding: utf-8 -*-
"""
This module provides the necessary methods for a Certification Authority.
For creating the self signed Certificate for the CA, use the following command:
$ openssl req -x509 -newkey rsa:2048 -keyout ca_priv.pem -out ca_cert.pem
@author: Vasco Santos
"""
import time
from M2Crypto impo... | 4'), RSA.pkcs1_padding)
def encryptData(self, data, certificate):
""" Encrypt the intended data with the public key contained in the certificate.
Arguments:
data: data to be encrypted.
| certificate: subject certificate.
"""
cert = X509.load_cert_string(certificate.decode('hex'))
return cert.get_pubkey().get_rsa().public_encrypt(str(data), RSA.pkcs1_padding).encode('base64')
def getPublicKey(self):
""" Get the CA Public Key.
Returns:
CA Publ... |
resulto/django-celery-fulldbresult | django_celery_fulldbresult/__init__.py | Python | bsd-3-clause | 2,722 | 0 | from __future__ import absolute_import, unicode_literals
from celery import current_app
from celery.states import PENDING
from celery.app.task import Context, Task
from celery.signals import before_task_publish
from django_celery_fulldbresult.errors import SchedulingStopPublishing
from django.conf import settings
fro... | _PUBLISH", False)
ignore_result = getattr(task, "ignore_result", False) or\
getattr(settings, "CELERY_IGNORE_RESULT", False)
if schedule_eta and body.get("eta") and not body.get("chord")\
and not body.get("taskset"):
status = SCHEDULED
save = True
... | ckend = task.backend if task else current_app.backend
request = Context()
request.update(**body)
request.date_submitted = now()
request.delivery_info = {
"exchange": exchange,
"routing_key": routing_key
}
backend.sto... |
aksinghdce/aksinghdce.github.io | students/subjects/Programming/projects/knowledge-tree/server/knowledgetree/lib/python3.6/site-packages/werkzeug/datastructures.py | Python | mit | 100,480 | 0.000418 | # -*- coding: utf-8 -*-
"""
werkzeug.datastructures
~~~~~~~~~~~~~~~~~~~~~~~
This module provides mixins and classes with an immutable interface.
:copyright: 2007 Pallets
:license: BSD-3-Clause
"""
import codecs
import mimetypes
import re
from copy import deepcopy
from itertools import repeat
from... | if self.on_update is not None:
self.on_update(self)
return rv
oncall.__name__ = name
return oncall
def setdefault(self, key, | default=None):
modified = key not in self
rv = super(UpdateDictMixin, self).setdefault(key, default)
if modified and self.on_update is not None:
self.on_update(self)
return rv
def pop(self, key, default=_missing):
modified = key in self
if default is _mi... |
readw/210CT-Coursework | Basic-Py/11-TreeNodeDelete.py | Python | gpl-3.0 | 3,026 | 0.018506 | # | Week 5 - 11) Based on the Python Code or the C++ Code Provided in class as a
# starting point, implement the binary search tree node, delete
# function.
class Node(object):
def __init__(self, value):
self.val | ue=value
self.next=None
self.prev=None
class List(object):
def __init__(self):
self.head=None
self.tail=None
def insert(self,n,x):
#Not actually perfect: how do we prepend to an existing list?
if n!=None:
x.next=n.next
n.next=x
... |
penguinmenac3/GraphProgramming | cluster_server/cluster_host.py | Python | gpl-2.0 | 446 | 0.006726 | # This cluster host should listen on the ne | twork for graph execution requests.
# Such requests consist out of a language identifier string (lua, python, ...) and a graph to execute as well as optional arguments for the graph.
# The graph is executed in is_cluster_server mode, which might restrict some features for security of the cluster provider.
# Output | s of the graph will be reported back over a tcp connection. Each line will be a packet.
|
santosfamilyfoundation/SantosGUI | application/custom/videographicsitem.py | Python | mit | 7,446 | 0.005372 | #!/usr/bin/env python
#############################################################################
##
## Copyright (C) 2013 Riverbank Computing Limited.
## Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
## All rights reserved.
##
## This file is part of the examples of PyQt.
| ##
## $QT_BEGIN_LICENSE:BSD$
## You may use this file under the terms of the BSD license as follows:
##
## "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 list of conditions and the following disclaimer.
## * Redistributions in binary form must reproduce the above copyright
## notice, this list of conditions and the following disclaimer in
## the documentation and/or ... |
arcyfelix/Courses | 18-04-18-REST APIs with Flask and Python/Section 5 - Storing resources in a SQL database/2_Logging in and retrieving Users from a database/app.py | Python | apache-2.0 | 2,324 | 0.034423 | from flask import Flask, request
from flask_restplus import Resource, Api, reqparse
from flask_jwt import JWT, jwt_required
from security import authenticate, identity
app = Flask(__name__)
app.secret_key = 'Wojciech'
api = Api(app)
# JWT creates a new endpoint /auth
jwt = JWT(app, authenticate, identity)
# List fo... | name):
# Code quality improvement
# 'next' normally throws an error if there is no values in the filter function
# that can be replaced by a default value, in this case 'None'
item = next(filter(lambda x: x['name'] == name, items), None)
# If the item is not found
return {'item' : item}, 200 if item is not ... | xisting item does not exist in the list.
if next(filter(lambda x: x['name'] == name, items), None) is not None:
return {'message' : "An item with name '{} already exists!".format(name)}, 400
request_data = Item.parser.parse_args()
item = {'name' : name,
'price' : request_data['price']}
items.append(... |
UCRoboticsLab/BaxterTictactoe | src/baxter_interface/src/baxter_dataflow/__init__.py | Python | apache-2.0 | 1,613 | 0 | # Copyright (c) 2013-2015, Rethink Robotics
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditio... | GHT 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 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF ... |
ryfeus/lambda-packs | Tensorflow_Pandas_Numpy/source3.6/tensorflow/core/util/memmapped_file_system_pb2.py | Python | mit | 4,351 | 0.006665 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: tensorflow/core/util/memmapped_file_system.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.p... | name=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='offset', full_name='tensorflow.MemmappedFileSystemDirectoryElement.offset', index=0,
number=1, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_ty... | nsion=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='name', full_name='tensorflow.MemmappedFileSystemDirectoryElement.name', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None,... |
cloud4life/targetcli-fb | targetcli/ui_root.py | Python | apache-2.0 | 7,712 | 0.002464 | '''
Implements the targetcli root UI.
This file is part of targetcli.
Copyright (c) 2011-2013 by Datera, 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/LICE... | f)
self.shell.log.info("Last %d configs saved in %s." % \
| (kept_backups, backup_dir))
self.rtsroot.save_to_file(savefile)
self.shell.log.info("Configuration saved to %s" % savefile)
def ui_command_restoreconfig(self, savefile=default_save_file, clear_existing=False):
'''
Restores configuration from a file.
... |
cmelange/ansible | lib/ansible/modules/network/eos/eos_user.py | Python | gpl-3.0 | 11,890 | 0.002019 | #!/usr/bin/python
#
# 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) any later version.
#
# Ansible is distribut... | ning config, this
argument will instruct the module when to change the password. When
set to C(always), the password will always be updated in the device
and when set to C(on_create) the password will be updated only if
the username is created.
required: false
default: always
... | when logged into the system. This argument accepts integer
values in the range of 1 to 15.
required: false
default: null
role:
description:
- The C(role) argument configures the role for the username in the
device running configuration. The argument accepts a string value
d... |
pcostell/google-cloud-datastore | python/googledatastore/local_cloud_datastore.py | Python | apache-2.0 | 7,713 | 0.004278 | #
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | cd_zip: path to the gcd zip file
java: path to a java executable
Raises:
ValueError: if gcd.sh cannot be located in the gcd zip file
"""
self._working_directory = working_directory
self._remote_datastores = {}
# Extract GCD.
zipped_file = zipfile.ZipFile(g | cd_zip)
self._gcd_dir = os.path.join(self._working_directory, 'gcd')
os.mkdir(self._gcd_dir)
zipped_file.extractall(self._gcd_dir)
# Locate gcd.sh in the unzipped directory (it may be in a directory which
# contains a version string).
gcd_dirs = [d for d in os.listdir(self._gcd_dir)
... |
pyrapt/rapt | rapt/transformers/sql/sql_translator.py | Python | mit | 8,668 | 0.000923 | from rapt.treebrd.attributes import AttributeList
from ...treebrd.node import Operator
from ..base_translator import BaseTranslator
class SQLQuery:
"""
Structure defining the building blocks of a SQL query.
| """
def __init__(self, select_block, from_block, where_block=''):
self.prefix = ''
self.select_block = select_block
self.from_block = from_block
self.where_block = where_block
@property
def _basic_query(self):
if self.select_block:
return '{prefix}' \
... | return '{prefix}{relation}'
@property
def _sql_query_skeleton(self):
sql = self._basic_query
if self.where_block:
sql += ' WHERE {conditions}'
return sql
def to_sql(self):
"""
Construct a SQL query based on the stored blocks.
:return: a... |
Featuretools/featuretools | featuretools/tests/primitive_tests/test_primitive_base.py | Python | bsd-3-clause | 2,871 | 0 | from datetime import datetime
import numpy as np
import pandas as pd
from pytest import raises
from featuretools.primitives import Haversine, IsIn, IsNull, Max, TimeSinceLast
from featuretools.primitives.base import TransformPrimitive
def test_call_agg():
primitive = Max()
# the assert is run twice on purp... | 6, 7)])
answer = 86400.0
answer_h = 24.0
assert answer == primitive(datetimes, time=datetime(2015, 6, 8))
assert answer_h == primitive_h(datetimes, time=datetime(2015, 6, 8))
def test_call_multiple_arg | s():
primitive = Haversine()
data1 = [(42.4, -71.1), (40.0, -122.4)]
data2 = [(40.0, -122.4), (41.2, -96.75)]
answer = [2631.231, 1343.289]
for _ in range(2):
assert np.round(primitive(data1, data2), 3).tolist() == answer
def test_get_function_called_once():
class TestPrimitive(Transf... |
ioam/scipy-2017-holoviews-tutorial | solutions/apps/periodic_app.py | Python | bsd-3-clause | 1,047 | 0.00382 | import holoviews as hv
import geoviews as gv
import dask.dataframe as dd
from holoviews.operation.datashader import datashade, aggregate, shade
from bokeh.models import WMTSTileSource
re | nderer = hv.renderer('bokeh')
# Load data
usecols = ['tpep_pickup_datetime', 'dropoff_x', 'dropoff_y']
ddf = dd.read_csv | ('../data/nyc_taxi.csv', parse_dates=['tpep_pickup_datetime'], usecols=usecols)
ddf['hour'] = ddf.tpep_pickup_datetime.dt.hour
ddf = ddf.persist()
# Declare objects
stream = hv.streams.Counter()
points = hv.Points(ddf, kdims=['dropoff_x', 'dropoff_y'])
dmap = hv.DynamicMap(lambda counter: points.select(hour=counter%24... |
pedrofeijao/RINGO | src/ringo/LD_simulation.py | Python | mit | 5,857 | 0.005805 | #!/usr/bin/env python2
import ringo_config
cfg = ringo_config.RingoConfig()
import pyximport;pyximport.install(build_dir=cfg.pyximport_build())
import argparse
import random
import numpy as np
import model
from simulation import Simulation, SimParameters, EventType, RearrangementType
def run_L_D_simulation(self, L, ... | .events[ev] + count for ev, count in
ev_node.edge.events.iteritems()}
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description="Simulates rearrangement evolution on | a given newick tree")
parser.add_argument("-s", "--sim", type=int, help="Simulate a new birth_death with SIM species")
parser.add_argument("-n", "--num_genes", type=int, default=100, help="Number of genes in the root genome.")
parser.add_argument("-c", "--num_chr", type=int, default=5, help="Number of chro... |
allenlavoie/tensorflow | tensorflow/contrib/boosted_trees/estimator_batch/custom_export_strategy.py | Python | apache-2.0 | 11,678 | 0.007536 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | DO(nponomareva): adjus | t this id assignement when we allow multi-
# column sparse tensors.
feature_id = split.feature_column + num_dense
inequality_test |
moreati/trac-gitsvn | sample-plugins/HelloWorld.py | Python | bsd-3-clause | 2,080 | 0.003365 | """Example macro."""
revision = "$Rev$"
url = "$URL$"
#
# The following shows the code for macro, old-style.
#
# The `execute` function serves no purpose other than to illustrate
# the example, it will not be used anymore.
#
# ---- (ignore in your own macro) ----
# --
from trac.util import escape
def execute(hdf, tx... | hdf['wiki.macro.greeting'] = 'Hello World'
# args will be `None` if the macro is called without parenthesis.
args = txt or 'No arguments'
# then, as `txt` comes from the user, it's important to guard against
# the possibility to inject malicious HTML/Javascript, by using | `escape()`:
return 'Hello World, args = ' + escape(args)
# --
# ---- (ignore in your own macro) ----
#
# The following is the converted new-style macro
#
# ---- (reuse for your own macro) ----
# --
from trac.wiki.macros import WikiMacroBase
class HelloWorldMacro(WikiMacroBase):
_description = cleandoc_(
... |
brython-dev/brython | www/src/Lib/test/test_largefile.py | Python | bsd-3-clause | 10,216 | 0.000098 | """Test largefile support on system where this makes sense.
"""
import os
import stat
import sys
import unittest
import socket
import shutil
import threading
from test.support import requires, bigmemtest
from test.support import SHORT_TIMEOUT
from test.support import socket_helper
from test.support.os_helper import TE... | n(TESTFN2, 'wb') as f:
event.wait(self.timeout)
while True:
chunk = conn.recv(65536)
if not chunk:
return
f.write(chunk)
event = threading.Event()
sock.settimeout(... | thread = threading.Thread(target=run, args=(sock, ))
self.thread.start()
event.set()
# Exact required disk space would be (size * 2), but let's give it a
# bit more tolerance.
@skip_no_disk_space(TESTFN, size * 2.5)
def test_it(self):
port = socket_helper.find_unused_port()
... |
scwhitehouse/rose | lib/python/rose/config_editor/valuewidget/combobox.py | Python | gpl-3.0 | 3,038 | 0.000658 | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# (C) British Crown Copyright 2012-7 Met Office.
#
# This file is part of Rose, a framework for meteorological suites.
#
# Rose is free software: you can redistribute it and/or modify
# it under the terms of the GNU ... | later version.
#
# Rose is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the impl | ied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Rose. If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------... |
albatros69/Divers | sudoku.py | Python | gpl-3.0 | 11,551 | 0.013602 | # -*- coding: utf-8 -*-
from __future__ import (unicode_literals, absolute_import, print_function, division)
from copy import deepcopy
from itertools import combinations
class Cell:
def __init__(self):
self.value = 0
self.row = set()
self.col = set()
self.sq = set()
self.... | self.col.add(val)
self.sq.add(val)
else:
raise ValueError
def rm_value(self, val):
if isinstance(val, int):
self.rm_values.add(val)
elif | isinstance(val, set):
self.rm_values |= val
def __repr__(self):
if self.value == 0:
return ' '
else:
return repr(self.value)
def carre(i,j):
return i//3+3*(j//3)
def are_neigh(i,j,k,l):
return (i==k) + (j==l) + (carre(i,j)==carre(k,l))
def coord(dim, ... |
paulray/NICERsoft | scripts/fitharms.py | Python | mit | 11,515 | 0.022058 | #!/usr/bin/env python
from __future__ import print_function,division
from astropy.io import fits
import matplotlib.pyplot as plt
import numpy as np
import matplotlib
from pint.templates import lctemplate,lcprimitives,lcfitters
from pint.eventstats import z2m,sf_z2m, hm, sf_hm, sig2sigma
import sys
from astropy import ... | form over [0,1)
ph = np.random.random_sample(len(en))
log.info("Replaced with {0} random phases".format(len(en)))
matplotlib.rcParams['font.family'] = "serif"
matplotlib.rcParams.update({'font.size': 13})
matplotlib.rc('axes', linewidth=1.5)
if args.output:
resultsfile = ... | Filter on energy
idx = np.where(np.logical_and(en > int(args.emin*100), en < int(args.emax*100) ))[0]
ph = ph[idx]
en = en[idx]
# Hack to manually split out a segment
#q = 3 # Use 0, 1, 2, 3
#qn = len(ph)//4
#ph = ph[q*qn:(q+1)*qn]
#en = en[q*qn:(q+1)*qn]
nbins = args.num... |
mahak/neutron | neutron/db/models/provisioning_block.py | Python | apache-2.0 | 1,178 | 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
# distributed under | the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from neutron_lib.db import model_base
from neutron_lib.db import standard_attr
impor... |
crmccreary/openerp_server | openerp/addons/sale_margin/sale_margin.py | Python | agpl-3.0 | 4,000 | 0.00675 | ##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public L... | r option) any later version.
#
# This program is distributed in the hope that it will be usef | ul,
# 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, see <... |
huguesv/PTVS | Python/Product/Miniconda/Miniconda3-x64/Lib/site-packages/conda/models/dist.py | Python | apache-2.0 | 11,208 | 0.002141 | # -*- coding: utf-8 -*-
# Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import absolute_import, division, print_function, unicode_literals
from collections import namedtuple
from logging import getLogger
import re
from .channel import Channel
from .package_info import Packag... | = Dist.from_string(value)
Di | st._cache_[value] = dist
return dist
else:
return super(DistType, cls).__call__(*args, **kwargs)
def strip_extension(original_dist):
for ext in CONDA_PACKAGE_EXTENSIONS:
if original_dist.endswith(ext):
original_dist = original_dist[:-len(ext)]
return origina... |
7ws/django-setmagic | setmagic/backend.py | Python | mit | 1,189 | 0 | from setmagic.models import Setting
from .exceptions import NoSuchSettingError
class SettingsBackend(object):
'''
A structure to organize the settings scheme and provide a simple API for
easier access to all registered settings.
'''
settings = property(lambda self: self._settings)
def __ini... | objects.get(name=setting_def['name'])
except Setting.DoesNotExist:
name = setting_def['name']
setting = Setting(
name=name,
current_value=self.defs[name | ].get('default'))
setting.__dict__.update(**setting_def)
setting.save()
def get(self, name):
try:
return Setting.objects.get(name=name).current_value
except Setting.DoesNotExist:
raise NoSuchSettingError(name)
def set(self, name, value):
... |
SekoiaLab/Fastir_Collector | memory/windows2012ServerMemory.py | Python | gpl-3.0 | 662 | 0.001511 | from __future__ import unicode_literals
from memory.mem import _Memory
class Windows2012ServerMemory(_Memory):
def __init__(self, params):
super(Windows2012ServerMemory, self).__init__(params)
def csv_all_modules_dll(self):
super(Windows2012ServerMemory, self)._csv_all_modules_dll()
def ... | l_modules_opened_files()
def json_all_modules_dll(self):
super(Windows2 | 012ServerMemory, self)._json_all_modules_dll()
def json_all_modules_opened_files(self):
super(Windows2012ServerMemory, self)._json_all_modules_opened_files() |
cjaymes/expatriate | src/expatriate/xpath/NodeTest.py | Python | lgpl-3.0 | 877 | 0.00114 | # Copyright 2016 Casey Jaymes
# This file is part of Expatriate.
#
# Expatriate 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.
#
# Expatriate is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more deta | ils.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Expatriate. If not, see <http://www.gnu.org/licenses/>.
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
class NodeTest(object):
def __init__(self):
self.children = []
|
Kaggle/docker-python | tests/test_pytorch_ignite.py | Python | apache-2.0 | 245 | 0 | import unittest
|
from ignite.engine import Engine
class TestPytorchIgnite(unittest.TestCase):
def test_engine(self):
def update_fn(engine, batch):
| pass
engine = Engine(update_fn)
engine.run([0, 1, 2])
|
joowani/quadriga | quadriga/rest.py | Python | mit | 4,123 | 0 | from __future__ import absolute_import, unicode_literals, division
import hashlib
import hmac
import time
from quadriga.exceptions import RequestError
class RestClient(object):
"""REST client using HMAC SHA256 authentication.
:param url: QuadrigaCX URL.
:type url: str | unicode
:param api_key: Quad... | n self.http_success_status_codes:
raise RequestError(
response=resp,
message='[HTTP {}] {}'.format(http_code, resp.reason)
)
try:
body = resp.json()
| except ValueError:
raise RequestError(
response=resp,
message='[HTTP {}] response body: {}'.format(
http_code,
resp.text
)
)
else:
if 'error' in body:
error_code = b... |
devartis/passbook | passbook/models.py | Python | mit | 15,345 | 0.001499 | # -*- coding: utf-8 -*-
import decimal
import hashlib
import json
import zipfile
from io import BytesIO
from M2Crypto import SMIME
from M2Crypto import X509
from M2Crypto.X509 import X509_Stack
class Alignment:
LEFT = 'PKTextAlignmentLeft'
CENTER = 'PKTextAlignmentCenter'
RIGHT = 'PKTextAl... | f.altitude = 0.0
# Optional. Notification distance
self.distance = None
# Optional. Text displayed on the lock screen when
# the pass is currently near the location
self.relevantText = ''
def json_dict(self):
return self.__dict__
class IBeacon(object):
... | # IBeacon data
self.proximityUUID = proximityuuid
self.major = major
self.minor = minor
# Optional. Text message where near the ibeacon
self.relevantText = ''
def json_dict(self):
return self.__dict__
class PassInformation(object):
def __in... |
davidcox/freetype-py | freetype/__init__.py | Python | bsd-3-clause | 71,996 | 0.012584 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
#
# FreeType high-level python API - Copyright 2011 Nicolas P. Rougier
# Distributed under the terms of the new BSD license.
#
# ---------------------------------------------------------------... | if error: raise FT_Exception(error)
try | :
set_lcd_filter( FT_LCD_FILTER_DEFAULT )
except:
pass
if error: raise FT_Exception(error)
return __handle__
def version():
'''
Return the version of the FreeType library being used as a tuple of
( major version number, minor version number, patch version number ... |
nonZero/demos-python | src/examples/short/datetime/date_to_mysql.py | Python | gpl-3.0 | 511 | 0.001957 | #!/usr/bin/python3
'''
example of how to convert the output of date(1) on the command line
to mysql t | ype dates.
'''
import subprocess # for check_output
import datetime # for strptime
def date_to_mysql(output):
format = '%a %b %d %H:%M:%S %Z %Y'
d = datetime.datetime.strptime(output, format)
# print('d is [{0}]'.format(d))
return d
output = subprocess.check_output('date').decode().strip()
print('... | ql(output)
print('d is [{0}]'.format(d))
|
lbeckman314/dotfiles | i3/musicwatcher.py | Python | mit | 1,595 | 0.025078 | #!/usr/bin/env python2
import i3ipc
import subprocess
# process all windows on this workspace. hide when leaving and show when entering
# because chrome/ium doesnt c | onsider itself hidden when on an invisible workspace
# this script drops my cpu u | sage when listening to google music from ~10% to ~3%
# I'm just putting any workspaces that have chromium apps running on them
WATCHED_WORKSPACES = [5, 6]
HIDDEN = '_NET_WM_STATE_HIDDEN'
SHOWN = '_NET_WM_STATE_SHOWN'
def showWindow(windowId):
print "SHOWING"
subprocess.call(["xprop", "-id", str(windowId), "-f",... |
editorsnotes/editorsnotes | editorsnotes/main/migrations/0019_auto_20160229_0921.py | Python | agpl-3.0 | 10,543 | 0.003889 | # -*- coding: utf-8 -*-
from django.db import migrations, models
from django.conf import settings
import editorsnotes.main.fields
class Migration(migrations.Migration):
dependencies = [
('main', '0018_auto_20151019_1331'),
]
operations = [
migrations.AlterField(
model_name=... | er to update this item.'),
),
migrations.AlterField(
model_name='featureditem',
name='created',
field=models.DateTimeField(auto_now_add=True, verbose_na | me='The time this item was created.'),
),
migrations.AlterField(
model_name='featureditem',
name='creator',
field=models.ForeignKey(related_name='created_featureditem_set', editable=False, to=settings.AUTH_USER_MODEL, help_text='The user who created this item.'),
... |
mysociety/polipop | polipop/popit/migrations/0005_auto__add_codetype__chg_field_personcode_type__chg_field_organisationc.py | Python | agpl-3.0 | 13,851 | 0.007725 | # 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 model 'CodeType'
db.create_table('popit_codetype', (
('id', self.gf('django.db.models... | MarkupField', [], {'default': "''", 'no_rendered_field': 'True', 'blank': 'True'}),
'updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
},
'popit.organisationcode': {
| 'Meta': {'object_name': 'OrganisationCode'},
'code': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'organisation': ('django.db.models.fields.related.ForeignKey', [], {'related_nam... |
sarleon/HackGame | app/advancetool/views.py | Python | gpl-3.0 | 307 | 0.019544 | from . import advancetools
from flask import render_ | template,redirect,Response,url_for
@advancetools.route('/')
def index():
return redirect(url_for('auto_decode_ba | se'))
@advancetools.route('/auto_decode_base')
def auto_decode_base():
return render_template('advancetool/auto_decode_base.html')
|
emacsattic/haddoc | lib/python/haddoc/lookup.py | Python | gpl-2.0 | 885 | 0.00226 | """
Lookup some search terms in the index.
"""
import sys
import haddoc
from collections import defaultdict
def main():
import optparse
parser = optparse.OptionParser(__doc__.strip())
haddoc.add_options(parser)
opts, args = parser.parse_args()
haddoc.validate_options(opts)
if not args:
... | url, rlist in res.iteritems():
print url
for source, fullname in rlist:
print " %s: %s" % (source, fullname)
print
conn.close( | )
|
lilleswing/deepchem | contrib/pubchem_dataset/download_pubchem_ftp.py | Python | mit | 1,644 | 0.01399 | import ftplib
import os
import time
import deepchem
def main():
ftp = ftplib.FTP("ftp.ncbi.nih.gov")
ftp.login("anonymous", "anonymous")
# First download all SDF files. We need these to get smiles
ftp.cwd("/pubchem/Compound/CURRENT-Full/SDF")
data_dir = deepchem.utils.get_data_dir()
sdf_dir = os.path.joi... | filelist = ftp.nlst()
existingfiles = os.listdir(bioassay_dir)
print("Downloading: {0} Bioassay files".format(len(filelist)))
i = 0
for filename in filelist:
local_filename = os.path.join(bioassay_dir, filename)
if filename in existingfiles or "README" in filename:
i = i + 1
... | y('RETR ' + filename, file.write)
i = i + 1
print("Processed file {0} of {1}".format(i, len(filelist)))
ftp.quit()
if __name__ == "__main__" :
main()
|
SPlanzer/AIMS | ElectoralAddress/Gui/Config.py | Python | bsd-3-clause | 1,936 | 0.024793 |
# Configuration settings for electoral address GUI
from PyQt4.QtCore import *
import ElectoralAddress.Database as Database
organisationName='Land Information New Zealand'
applicationName='Electoral Address Loader'
_settings=None
def settings():
global _settings
if not _settings:
_sett... | setDatabaseConfiguration( host=None, port=None, database=None, user=None, password=None, bdeSchema=None, addressSchema=None, db | module=Database ):
if not host: host = dbmodule.host()
if not port: host = dbmodule.port()
if not database: database = dbmodule.database()
if not user: user = dbmodule.user()
if not password: password = dbmodule.password()
if not addressSchema: addressSchema = dbmodule.addressSchema()
... |
birsoyo/conan | conans/client/userio.py | Python | mit | 4,473 | 0.000894 | import os
import sys
from conans.client.output import ConanOutput
from conans.model.username import Username
from conans.errors import InvalidNameException, ConanException
import getpass
from six.moves import input as raw_input
class UserIO(object):
"""Class to interact with the user, used to show messages and as... | username=None):
"""Request u | ser to input their name and password
:param username If username is specified it only request password"""
user_input = ''
while not username:
try:
if self._interactive:
self.out.write("Remote '%s' username: " % remote_name)
user_inp... |
manz/python-mapnik | test/python_tests/feature_test.py | Python | lgpl-2.1 | 3,439 | 0.012511 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from nose.tools import eq_,raises
from .utilities import run_all
import mapnik
from binascii import unhexlify
def test_default_constructor():
f = mapnik.Feature(mapnik.Context(),1)
eq_(f is not None,True)
def test_feature_geo_interface():
ctx = mapnik.Contex... | f['name'] = 'a'
eq_(f['name'],u'a')
expr = mapnik.Expression("[name]='a'")
evaluated = expr.evaluate(f)
eq_(evaluated,True)
num_attributes = len(f)
eq_(num_attributes,1)
eq_(f.id(),1)
# https://github.com/mapnik/mapnik/issues/933
def test_feature_expression_evaluation_missing_attr():
c... | eq_(f['name'],u'a')
expr = mapnik.Expression("[fielddoesnotexist]='a'")
eq_(f.has_key('fielddoesnotexist'),False)
try:
expr.evaluate(f)
except Exception as e:
eq_("Key does not exist" in str(e),True)
num_attributes = len(f)
eq_(num_attributes,1)
eq_(f.id(),1)
# https://githu... |
makerblueprint/retrospecification | modules/host/beaglebone-black/beaglebone-black.py | Python | cc0-1.0 | 599 | 0.013356 | #
# Get the pin which correlates with a given purpose.
#
# @param char array purpos | e
# The purpose to search by.
# @return int
# A pin which can be used for the given purpose.
#
def getPin(purpose):
purpose_collection = {
"i2c-data": 20
"i2c-clock": 19
"adc": 39
"adc0": 39
"adc-0": 39
"one-wire-data": 40
"adc1": 40
"adc-1": 40
"spi-slave-select": ... | "spi-master-in-slave-out": 29
"spi-clock": 31
}
if purpose in purpose_collection:
return purpose_collection[purpose]
else
return -1
|
munificent/magpie-optionally-typed | doc/site/magpie/setup.py | Python | mit | 305 | 0.003279 | """
A Pygments lex | er for Magpie.
"""
from setuptools import setup
__author__ = 'Robert Nystrom'
setup(
name='Magpie',
version='1.0',
description=__doc__,
author=__author__,
packages=['magpie'],
entry_points='''
[pygments.lexers]
magpielexer = magpie: | MagpieLexer
'''
) |
conorkcorbin/tractometry | call_interpolate.py | Python | mit | 1,231 | 0.029245 | from bundleprocessing import interpolateMetric
import pandas as pd
import nibabel as nib
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-templateBundle', '--templateBundle', required = True)
parser.add_argument('-subjectBundle', '--subjectBundle', required = True)
parser.add_argument('-metr... | ser.add_argument('-numPoints', '--numPoints', type=int, required = True)
parser.add_argument('-flip', '--flip', type=bool, required = True)
parser.add_argument('-outTracks', '--outTracks', required = True)
parser.add_argument('-outMetrics', '--outMetrics', required = True)
args = parser.parse_args()
tracks, hdr ... | ckvis.read(args.templateBundle)
templateBundle = [trk[0] for trk in tracks]
tracks, hdr = nib.trackvis.read(args.subjectBundle)
subjectBundle = [trk[0] for trk in tracks]
image = nib.load(args.metric)
metric = image.get_data()
subjectTracks,scalars = interpolateMetric(templateBundle,
subjectBundle,
m... |
oppia/oppia | core/domain/suggestion_registry_test.py | Python | apache-2.0 | 148,457 | 0.00029 | # Copyright 2018 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | ort question_domain
from core.domain import question_services
from core.domain import skill_services
from core.domain import state_domain
from core.d | omain import suggestion_registry
from core.domain import suggestion_services
from core.platform import models
from core.tests import test_utils
(suggestion_models,) = models.Registry.import_models([models.NAMES.suggestion])
class MockInvalidSuggestion(suggestion_registry.BaseSuggestion):
def __init__(self): # ... |
mgerstner/backintime | common/test/test_restore.py | Python | gpl-2.0 | 7,692 | 0.00429 | # Back In Time
# Copyright (C) 2008-2017 Oprea Dan, Bart de Koning, Richard Bailey, Germar Reitze
#
# 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, or
# (at your... | self.assertEqual(33260, os.stat(restoreFile).st_mode)
def test_restore_file_with_spaces(self):
restoreFile = os.path.join(self.include.name, 'file with spaces')
self.prepairFileInfo(restoreFile)
self.sn.restore(self.sid, restoreFile)
self.assertIsFile(restore | File)
with open(restoreFile, 'rt') as f:
self.assertEqual(f.read(), 'asdf')
self.assertEqual(33260, os.stat(restoreFile).st_mode)
@unittest.skipIf(not generic.LOCAL_SSH, 'Skip as this test requires a local ssh server, public and private keys installed')
class TestRestoreSSH(generic.SSHSnaps... |
barisser/perceptron | btcanalysis.py | Python | mit | 2,614 | 0.034047 | import requests
import json
import math
import matplotlib.pyplot as plt
data=[]
price=[] #weighted price per day, reverse order
volume=[] #volume USD per day
onedaychange=[]
Xmovingaverage=[]
Xinterval=15
Ymovingaverage=[]
Yinterval=50
Xdifference=[] # PERCENTAGE DIFFERENCE between X moving average and todays p... | =0
r=0
while b<Xinterval:
r=r+float(price[a+b])/float(Xinterval)
b=b+1
Xmovingaverage.append(r)
a=a+1
a=0
while a<len(pric | e)-Yinterval:
c=0
r=0
while c<Yinterval:
r=r+float(price[a+c])/float(Yinterval)
c=c+1
Ymovingaverage.append(r)
a=a+1
for i in range(0,Xinterval):
Xdifference.append(1)
for i in range(0,Yinterval):
Ydifference.append(1)
g=Xinte... |
uogbuji/versa | tools/py/iriref.py | Python | apache-2.0 | 1,234 | 0.004862 | #versa.iriref
'''
Versa distinguishes declared IRI references from strings which coincidentally look like IRI references
'''
from amara3 import iri
import logging
from versa import init_localization
init_localization()
#VERSA_BASEIRI = 'http://bibfra.me/purl/versa/'
class iriref(str):
'''
IRI references ob... | ghtly decorated unicode
>>> from | versa.iriref import iriref
>>> iriref('spam')
'spam'
>>> iriref('spam eggs')
[raises ValueError]
>>> from versa import I
>>> I('spam')
'spam'
'''
def __new__(cls, value):
if not iri.matches_uri_ref_syntax(value):
raise ValueError(_('Invalid IRI reference: "{0}"'... |
comick/barduino | app/weblib/logging.py | Python | mit | 1,603 | 0.000624 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
flask.logging
~~~~~~~~~~~~~
Implements the logging support for Flask.
:copyright: (c) 2011 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import web
from logging import getLogger
from logging import getLo... | g. Furthermore
this function also removes all attached handlers in case there was a logger
with the log name before.
| """
Logger = getLoggerClass()
class DebugLogger(Logger):
def getEffectiveLevel(self):
if self.level == 0:
return DEBUG if web.config.DEBUG else INFO
return super(DebugLogger, self).getEffectiveLevel()
class DebugHandler(StreamHandler):
def emit(x,... |
cliffano/swaggy-jenkins | clients/python/generated/test/test_favorite_impllinks.py | Python | mit | 871 | 0.001148 | """
Swaggy Jenkins
Jenkins API clients generated from Swagger / Open API specification # noqa: E501
The version of the OpenAPI document: 1.1.2-pre.0
Contact: blah@cliffano.com
Generated by: https://openapi-generator.tech
"""
import sys
import unittest
import swaggyjenkins
from swaggyjenkins.mo... | ns.model.favorite_impllinks import FavoriteImpllinks
class TestFavoriteImpllinks(unittest.TestCase):
"""FavoriteImpllinks unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testFavoriteImpllinks(self):
"""Test FavoriteImpllinks"""
# FIXME: construc... | == '__main__':
unittest.main()
|
sobhe/baaz | baaz/LearningBasedInformationExtractor.py | Python | mit | 598 | 0.033445 | from hazm import IOBTagger
from nltk.t | ag import TaggerI
class LearningBasedInformationExtractor(TaggerI):
def train(self, sentences, model_file='resources/extractor.model'):
self.tagger = IOBTagger(patterns=[
'*',
'*:tl1=%X[-1,1]',
'*:t=%X[0,1]',
'*:tr1=%X[1,1]',
'*:cp=%m[0,2,"..$"]',
'*:c=%X[0,2]',
'*:c0l1=%X[-1,2]/%X[0,2]',
... | 2]',
])
self.tagger.train(sentences)
self.tagger.save_model(model_file)
def tag(self, sent):
return self.tagger.tag(sent)
|
zhangjiajie/PTP | nexus/bin/nexus_binary2multistate.py | Python | gpl-3.0 | 1,202 | 0.008319 | #!/usr/bin/env python
import sys
from nexus import NexusReader, VERSION
from nexus.tools import multistatise, combine_nexuses
__author__ = 'Simon Greenhill <simon@simon.net.nz>'
__doc__ = """nexus_binary2multistate - python-nexus tools v%(version)s
Converts binary nexuses to a multistate nexus.
""" % {'version': VERS... | ort OptionParser
parser = OptionParser(usage="usage: %prog [-o output.nex] nex1.nex nex2.nex ... nexN.nex")
parser.add_option("-o", "--output", dest="output",
action="store", default=None, type="string",
help="output nexus file")
options, nexuslist = parser.parse_args()
if ... |
print(__doc__)
parser.print_help()
sys.exit()
if options.output is not None:
outfile = options.output
else:
outfile = 'multistate.nex'
nexuslist2 = []
for nfile in nexuslist:
n = NexusReader(nfile)
n = multistatise(n)
nexusli... |
brohrer/becca | becca/preprocessor.py | Python | mit | 3,736 | 0 | import numpy as np
from becca.discretizer import Discretizer
import becca.tools as tools
import os
import logging
logging.basicConfig(filename='log/log.log', level=logging.DEBUG,
format='%(asctime)s %(levelname)s %(name)s %(message)s')
logger = logging.getLogger(os.path.basename(__file_ | _))
class Preprocessor(object):
"""
The Preprocessor takes the raw sensor signals in and creates a set of
inputs for the Brain to learn from.
"""
def __init__(self, n_sensors=None):
"""
Parameters
----------
| n_sensors: int
The number of sensors that the world will be providing. These
are the only pieces of information Becca needs about the
world to get started.
"""
if not n_sensors:
logger.error('You have to give a number for n_sensors.')
return
... |
Pexego/PXGO_00049_2013_PCG | project-addons/maintenance/maintenance_type.py | Python | agpl-3.0 | 6,303 | 0.006665 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2004-2014 Pexego Sistemas Informáticos All Rights Reserved
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public Lice... | ent_id and type_obj.department_id.id or False,
'executor_department_id': type_obj.department_id and type_obj.department_id.id or False,
}
self.pool | .get('intervention.request').create(cr, uid, args_request, context)
maintenance_type_obj.write(cr, uid, type_obj.id, {'ultima_ejecucion': ultima_creacion}, context)
return True
maintenance_type()
|
qtile/qtile | test/test_popup.py | Python | mit | 1,850 | 0 | # Copyright (c) 2020-1 Matt Colligan
#
# 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, dis... | one")
start_wins = len(manager.backend.get_all_windows())
success, msg = manager.c.eval(
textwrap.dedent(
"""
from libqtile.popup import Popup
popup = Popup(self,
x=0,
y=0,
width=self.current_screen.width,
height=self.current_s... | er.backend.get_all_windows())
assert end_wins == start_wins + 1
assert manager.c.group.info()["focus"] == "one"
assert manager.c.group.info()["windows"] == ["one"]
assert len(manager.c.windows()) == 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.