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 |
|---|---|---|---|---|---|---|---|---|
joestringer/libcpuid | tests/add_test.py | Python | bsd-2-clause | 1,755 | 0.024501 | #!/usr/bin/python
import os, sys, re
args = sys.argv
if not len(args) in (3, 4):
print "Usage: add_test.py <rawdata file> <report file> [tests stash file]"
print "If the last is not specified, `tests_stash.txt' is assumed"
sys.exit(1)
rawdata = []
for line in open(args[1], "rt").readlines():
lookfor = ["basic_c... | ind(":") + 2:]
repdata.append(value)
if field == "SSE units":
value = s[s.find(":") + 2:]
# the value here is something like "XX bits (authoritative)". We remove the "bits" part:
i = value.find("bits")
if i != - | 1:
value = value[:i] + value[i + 5:]
repdata.append(value)
stash = "tests_stash.txt"
if len(args) == 4:
stash = args[3]
fout = open(stash, "at")
delimiter = "-" * 80
lines = rawdata + [delimiter] + repdata + [delimiter]
fout.writelines(map(lambda s: s + "\n", lines))
fout.close()
|
bepatient-fr/itools | itools/handlers/__init__.py | Python | gpl-3.0 | 2,247 | 0.000446 | # -*- coding: UTF-8 -*-
# Copyright (C) 2004-2010 J. David Ibáñez <jdavid.ibp@gmail.com>
# Copyright (C) 2007-2008 Hervé Cauwelier <herve@oursours.net>
#
# 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 Foun... | se, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a ... | <http://www.gnu.org/licenses/>.
"""
This package provides an abstraction layer for files and directories.
There are two key concepts, resources and handlers.
A resource is anything that behaves like a file (it contains an array of
bytes), as a directory (it contains other resources) or as a link (it
contains a path ... |
oblique-labs/pyVM | rpython/flowspace/test/test_objspace.py | Python | mit | 40,883 | 0.003082 | from __future__ import with_statement
import types
import py
from contextlib import contextmanager
from rpython.flowspace.model import (
Constant, mkentrymap, const)
from rpython.translator.simplify import simplify_graph
from rpython.flowspace.objspace import build_flow
from rpython.flowspace.flowcontext import Fl... | i = i + 1
return result
def test_break_continue(self):
x = self.codetest(self.break_continue)
def test_break_from_handler(self):
def f(x):
while True:
try:
x()
except TypeError:
if x:
... | aise
break
assert f(0) is None
graph = self.codetest(f)
simplify_graph(graph)
entrymap = mkentrymap(graph)
links = entrymap[graph.returnblock]
assert len(links) == 1
#__________________________________________________________
def unpack_tuple(... |
pypowervm/pypowervm | pypowervm/tests/utils/test_validation.py | Python | apache-2.0 | 23,564 | 0.000042 | # Copyright 2015, 2017 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
#
# Unless require... | shared_proc_cfg.min_units = min_proc_units
lpar_w.proc_config.shared_proc_cfg.max_units = max_proc_units
# Mem
lpar_w.mem_config.desired = des_mem
lpar_w.mem_config.min = min_mem
lpar_w.mem_config.max = max_mem
lpar_w.mem_config.exp_factor = ex... | and rmc_state != bp.RMCState.ACTIVE):
lpar_w.can_modify_proc.return_value = (False, 'Bad RMC')
lpar_w.can_modify_mem.return_value = (False, 'Bad RMC')
else:
# Doesn't matter what the message is unless it's bad
# so always make... |
nguy/artview | docs/sphinxext/numpydoc/comment_eater.py | Python | bsd-3-clause | 5,425 | 0.001475 | from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.... | ck including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno | = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self... |
ProjectQ-Framework/ProjectQ | examples/ionq_bv.py | Python | apache-2.0 | 2,725 | 0 | # -*- coding: utf-8 -*-
# Copyright 2021 ProjectQ-Framework (www.projectq.ch)
#
# 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
#
# ... | 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 an | d
# limitations under the License.
# pylint: skip-file
"""Example of a basic Bernstein-Vazirani circuit using an IonQBackend."""
import getpass
import random
import matplotlib.pyplot as plt
import projectq.setups.ionq
from projectq import MainEngine
from projectq.backends import IonQBackend
from projectq.libs.his... |
Jellofishi/solartron | office.py | Python | lgpl-3.0 | 398 | 0.040201 | # openoffice modules
import uno
def soffice_check():
"""Check if openoffice is running.
Attempts a socket connection to a running instance.
Raises ConnectionError on error.
"""
|
def soffice_start():
"""Start an openoffice instance.
Raises StartupError on error.
"""
def soffice_connect():
"""Return a connection to an | openoffice instance.
Raises ConnectionError on error.
"""
|
KiraLT/KiraBot | src/kirabot/kirabot/communication/user.py | Python | mit | 425 | 0 | from __future__ import unicode_literals
class User(object):
def __init__(s | elf, app, id, name, adapter):
self.app = app
self.id = id
self.name | = name
self.chat = adapter.create_chat_with(self.id)
self.storage = app.get_storage('communication:{}:users:{}'.format(
adapter.name, self.id))
def __unicode__(self):
return '{} ({})'.format(self.name, self.id)
|
jccaicedo/localization-agent | detection/relations/RelationsDB.py | Python | mit | 4,781 | 0.026773 | import os,sys
import utils as cu
import MemoryUsage
import numpy as np
import scipy.io
import cPickle as pickle
import random
from utils import tic | , toc
class RelationsDB():
def __init__(self, dbDir, randomize):
self.images = [img for img in os.li | stdir(dbDir) if img.endswith('.mat')]
self.dir = dbDir
self.boxes = []
self.scores = []
self.image = ''
self.idx = 0
self.random = randomize
if randomize:
random.shuffle(self.images)
def loadNext(self):
if self.idx < len(self.images):
data = scipy.io.loadmat(self.dir + '/'... |
coder006/BinPy | BinPy/examples/ic/Series_4000/IC4002.py | Python | bsd-3-clause | 1,102 | 0.019056 | from __future__ import print_function
from BinPy import *
print ('Usage of IC 4002:\n')
ic = IC_4002()
print ('\nT | he Pin configuration is:\n | ')
input = {2: 0, 3: 0, 4: 0, 5: 0, 7: 0, 9: 1, 10: 1, 11: 1, 12: 1, 14: 1}
print (input)
print ('\nPin initinalization\n')
print ('\nPowering up the IC - using -- ic.setIC({14: 1, 7: 0}) -- \n')
ic.setIC({14: 1, 7: 0})
print ('\nDraw the IC with the current configuration\n')
ic.drawIC()
print (
'\nRun the IC with ... |
N-Parsons/exercism-python | exercises/high-scores/example.py | Python | mit | 291 | 0 | class HighScore | s(object):
def __init__(self, scores):
self.scores = scores
def latest(self):
return self.scores[-1]
def personal_best(self):
return max(self.scores)
def personal_top_three(self):
return s | orted(self.scores, reverse=True)[:3]
|
craigderington/django-code-library | jobs/urls.py | Python | gpl-3.0 | 268 | 0 | from django.conf.urls import url
from . import views, feed
urlpatterns = [
url(r'^$', views.JobIndex.as_view(), name='index'),
url(r'^(?P<pk>[0-9]+)/$', views.JobDetail.as_view(), name='detail'),
url(r'^fe | ed/$', feed.La | testJobs(), name='feed'),
]
|
dasmith/IsisWorld | agents/test_thoughts.py | Python | gpl-3.0 | 1,119 | 0.020554 | import xmlrpclib as xml
import time
# connect to environment via XML-RPC
e = xml.ServerProxy('http://localhost:8001')
def sense():
return e.do('sense', {'agent':'Ralph'})
def step(time):
e.do('meta_step', {'seconds':time})
def do(command, args = No | ne):
| if not args:
args = {}
args['agent'] = 'Ralph'
return e.do(command, args)
layer_config = {'0': {'name': 'Reactive'}, '1':{'name':'Deliberative','color':[0.9,0.8,0.3,1]}, '2': {'name':'Reflective'}}
#layer_config = {'0': {'name': 'ID'}, '1':{'name':'Ego'}}#,'color':[0.9,0.8,0.3,1]}, '2': {'nam... |
JonasT/miraclecrafter-client | src/miraclecrafterclient/gui/versionconflictwindow.py | Python | gpl-3.0 | 1,781 | 0.004492 | """
This file is part of the Miracle Crafter Client.
Miracle Crafter (C) 2014 The Miracle Crafter Team (see AUTHORS)
Miracle Crafter 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 vers... | cked(self):
print("Ignore")
def create_widgets(self):
self.greetings = tk.Label(self, justify=tk.LEFT, anchor=tk.NW,
text="Unfortionatly your client version and the server version" \
+ " may be incompatible.")
s | elf.greetings.pack(side="top", anchor=tk.W)
box = self.add_hori_box()
self.add_to_box(
self.add_button("Download", self.download_button_clicked,
parent=box),
self.add_button("Ignore", self.ignore_button_clicked, parent=box)
)
|
yayoiukai/signalserver | groups/migrations/0002_auto_20161003_1842.py | Python | mit | 633 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.dev20160107235441 on 2016-10-03 18:42
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
| dependencies = [
('groups', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='group',
name='shared',
field=models.BooleanField(default=True),
),
migrations.AddField(
model_name='group',
n | ame='user_name',
field=models.CharField(default=None, max_length=400, null=True),
),
]
|
BehavioralInsightsTeam/edx-platform | common/lib/capa/capa/tests/test_html_render.py | Python | agpl-3.0 | 11,336 | 0.00097 | """
CAPA HTML rendering tests.
"""
import textwrap
import unittest
import ddt
import mock
import os
# Changes formatting of empty elements; import here to avoid test order dependence
import xmodule.modulestore.xml # pylint: disable=unused-import
from capa.tests.helpers import test_capa_system, new_loncapa_problem
fro... | 'Test text')
def test_anonymous_student_id(self):
# make sure anonymous_student_id is rendered properly as a context variable
xml_str = textwrap.dedent("""
<problem>
<span>Welcome $anonymous_student_id</span>
</probl | em>
""")
# Create the problem
problem = new_loncapa_problem(xml_str)
# Render the HTML
rendered_html = etree.XML(problem.get_html())
# Expect that the anonymous_student_id was converted to "student"
span_element = rendered_html.find('span')
self.assertE... |
dbrattli/OSlash | tests/test_monad.py | Python | apache-2.0 | 519 | 0 | import unittest
from oslash import StringWriter, MonadWriter
from oslash.monadic import compose
class | TestMonadMonadic(unittest.TestCase):
def test_monad_monadic_compose(self):
unit, tell = StringWriter.unit, MonadWriter.tell
def half(x):
return tell("I just halved %s!" % x).bind(lambda _: unit(x//2))
quarter = compose(half, half)
value, log = quarter(8).run()
... | log)
|
freerangerouting/frr | tests/topotests/bgp_community_alias/test_bgp-community-alias.py | Python | gpl-2.0 | 4,645 | 0.002153 | #!/usr/bin/env python
# Copyright (c) 2021 by
# Donatas Abraitis <donatas.abraitis@gmail.com>
#
# Permission to use, copy, modify, and/or distribute this software
# for any purpose with or without fee is hereby granted, provided
# that the above copyright notice and this permission notice appear
# in all copies.
#
# T... | if BGP community alias is visible in CLI outputs
"""
import os
import sys
import json
import pytest
import functools
pytestmark = pytest.mark.bgpd
CWD = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(CWD, "../"))
# pylint: disable=C0413
from lib import topotest
from lib.topogen import Topo... | )
switch = tgen.add_switch("s1")
switch.add_link(tgen.gears["r1"])
switch.add_link(tgen.gears["r2"])
def setup_module(mod):
tgen = Topogen(build_topo, mod.__name__)
tgen.start_topology()
router_list = tgen.routers()
for i, (rname, router) in enumerate(router_list.items(), 1):
ro... |
jelugbo/tundex | common/djangoapps/track/views/tests/test_segmentio.py | Python | agpl-3.0 | 10,966 | 0.002371 | """Ensure we can parse events sent to us from the segment.io webhook integration"""
from datetime import datetime
import json
from ddt import ddt, data
from freezegun import freeze_time
from mock import patch, sentinel
from django.contrib.auth.models import User
from django.test import TestCase
from django.test.clie... | esponse.status_code, 200)
expected_event = {
'username': str(sentinel.username),
'ip': '',
'event_source': 'mobile',
'event_type': str(sentinel.event_type),
'name': str(sentinel.name),
'event': {'foo': 'bar'},
... | e("2014-08-27T16:33:39.215Z", "%Y-%m-%dT%H:%M:%S.%fZ"),
'host': 'testserver',
'context': {
'user_id': USER_ID,
'course_id': course_id,
'org_id': 'foo',
'path': ENDPOINT,
'client': {
... |
RosesTheN00b/BudgetButlerWeb | butler_offline/test/viewcore/configuration_provider_test.py | Python | agpl-3.0 | 1,464 | 0.004781 | import unittest
from butler_offline.viewcore import configuration_provider
from butler_offline.core import file_system
from butler_offline.test.core.file_system_stub import FileSystemStub
class TesteConverter(unittest.TestCase):
def set_up(self):
file_system.INSTANCE = FileSystemStub()
configur... | ssing(self):
self.set_up()
configuration_provider.set_configuration('test', 'bla')
assert configuration_provider.get_configuration('DATABASES') == configuration_provider.DEFAULT_CONFIG['DATABASES']
def test_configuration_provider_should_loa | d_values(self):
self.set_up()
configuration_provider.set_configuration('test', 'bla')
assert configuration_provider.get_configuration('test') == 'bla'
def test_configuration_provider_should_save_values(self):
self.set_up()
configuration_provider.set_configuration('test','bla... |
jholewinski/ics-12-overlapped-tiling | scripts/new-model-2.py | Python | mit | 5,138 | 0.026275 | #!/usr/bin/env python
import math
import sys
import yaml
log = True
def main():
handle = open(sys.argv[1])
config = yaml.load(handle)
handle.close()
phase_limit = int(config['phase_limit'])
num_load = float(config['num_load'])
num_store = float(config['num_store'])
ops_per_point = float(config['ops... | sst_time + (time_tile_size-1)*(sld_time + compute + sst_time) + gst_time
print('cycles (1 point): %f' % time)
#phase
# Account for spatial tiling
#time = time * elems_per_thread
#print('cycles (E points): %f' % | time)
time = time * stages_per_sm
print('stages_per_sm: %f' % stages_per_sm)
print('cycles (w/o launch penalty): %f' % time)
total = time + global_sync
print('Cycles/Iteration: %f' % total)
if __name__ == '__main__':
main()
|
calvarezpe/ptavi-p3 | karaoke.py | Python | gpl-2.0 | 1,492 | 0.00067 | #!/usr/bin/python
# -*- coding: iso-8859-15 -*-
from xml.sax import make_parser
from xml.sax.handler im | port ContentHandler
import smallsmilhandler
import sys
import os
class KaraokeLocal(smallsmilhandler.SmallSMILHandler):
def __init__(self, fich):
par | ser = make_parser()
sHandler = smallsmilhandler.SmallSMILHandler()
parser.setContentHandler(sHandler)
parser.parse(fich)
self.list_tags = sHandler.get_tags()
def __str__(self):
todo = ""
for diccionarios in self.list_tags:
frase = ""
for clave... |
Magicjarvis/relay-backend | relay/views/relays.py | Python | apache-2.0 | 5,107 | 0.011357 | # -*- coding: utf-8 -*-
import logging
from flask import request
from flask import render_template
from relay import app
from relay.decorators import jsonify
from relay.decorators import session_required
from relay.decorators import sanitize_user
from relay.models.relays import add_relay_model
from relay.models.rel... | m in sent_relay_items:
item_map = make_sent_relay_map(sent_relay_item)
item_map.pop('sender', None)
item_map['recipients'] = sent_relay_item.recipients
sent_relays.append(item_map)
return {'relays': sent_relays}
@app.route('/relays/to/<user_id>')
@jsonify
@sanitize_user
@session_required
def get_r... | ved = bool(int(request.args.get('archived', 0)))
return _get_relay_to_user(user_id, user, archived)
def _get_relay_to_user(user_id=None, user=None, archived=False):
offset = int(request.args.get('offset', 0))
relays = get_relays_for_recipient(user_id, offset, archived=archived)
return {
'relays' : [
... |
shawncaojob/LC | PY/272_closet_binary_search_tree_value_ii.py | Python | gpl-3.0 | 1,979 | 0.00607 | # 272. Closest Binary Search Tree Value II Add to List
# DescriptionHintsSubmissionsSolutions
# Total Accepted: 15854
# Total Submissions: 41240
# Difficulty: Hard
# Contributor: LeetCode
# Given a non-empty binary search tree and a target value, find k values in the BST that are closest to the target.
#
# Note:
# Giv... | type target: f | loat
:type k: int
:rtype: List[int]
"""
def dfs(node):
if not node: return
dfs(node.left)
heappush(hq, [abs(target - node.val), node.val])
dfs(node.right)
hq = []
dfs(root)
res = []
while k > 0:
... |
duplamatyi/python-demo | src/apps/hotel/tests/test_ajax.py | Python | mit | 1,500 | 0.002667 | import json
from django.test import TestCase, | Client
from django.core.urlresolvers import reverse
from src.apps.hotel.models import City, Hotel
class AjaxTestCase(TestCase):
def setUp(self):
setattr(self, | 'client', Client())
amsterdam = City.objects.create(code="AMS", name="Amsterdam")
Hotel.objects.create(code="CAT", name="Ibis Amsterdam Airport", city=amsterdam)
def test_hotel_city(self):
client = getattr(self, 'client')
response = client.get('%s?q=Amsterdam' % reverse('city'), HTT... |
open-machine-learning/mldata-utils | scripts/voc2006classes.py | Python | gpl-3.0 | 954 | 0.01153 | """
Parser for vox 2006-2007 images
reads ImageSet directory and gets classes of images
than writes it to arff file
"""
import os
SIZE = 5305
maxint = 0
res = {}
for subdir, dirs, files in os.walk( | '.'):
for file in files:
if file[-3:] != "txt":
continue
cls,dummy = file.split("_")
f=open(file, 'r')
lines=f.readlines()
if cls not in res:
res[cls] = list(range(0,SIZE))
for line in lines:
id,val = line.strip().replace(" "," ").spl... | (id):
maxint = int(id)
print("@relation classification\n")
print("@attribute image string")
KEYS=list(res.keys())
for key in KEYS:
print("@attribute %s numeric" % (key))
print("\n@data")
for i in range(1,SIZE):
line = "'%06d'," % (i,)
for cls in KEYS:
line += res[cls][i].__str__()... |
LargePanda/GEAR_Network | scripts/data_collection_util.py | Python | gpl-3.0 | 9,523 | 0.010186 | import requests
from bs4 import BeautifulSoup
import pyprind
import json
import collections
import os
import codecs
import mathscinet
def make_mappers(profile):
"""
return mappers for id and mathscinet id
"""
gear_mathsci_mapper = {}
mathsci_gear_mapper = {}
for person in profile['items']:
... | per['authors']
for member_id in ids:
person = get_person_by_id(gear_profile, member_id)
details = person[col_detail_key]
for mid in ids:
if mid != member_id:
# update detail
if mid in de... | details[mid].append( paper['id'] )
else:
details[mid] = [ paper['id'] ]
for key in details.keys():
person[col_size_key][key] = len(details[key])
def update_collaborators(gear_profile, gear_paper_set... |
BayesFlare/bayesflare | bayesflare/finder/find.py | Python | gpl-2.0 | 45,609 | 0.004604 | """
"""
from __future__ import print_function
from ..misc import mkdir
from ..noise import estimate_noise_ps, estimate_noise_tv
from ..models import *
from ..stats import *
from math import log
import pyfits
import numpy as np
from copy import copy, deepcopy
def contiguous_regions(condition):
"""
Fin... | det_file = open(self.results_root+'/quarter'+str(quarter)+'/'+cadence+'/flares/'+object+'.kep', 'w')
#
# det_file.write('# Start the flaring statistics' + nl)
# det_file.write('# Flaring statistics for KIC' + object + nl)
# det_file.write('# Total number of flares: ' + str(len(flares)) +nl)
# ... | MP t_g \t MP t_e \t Amp \t |
GeorgiaTechDHLab/TOME | topics/migrations/0011_auto_20170605_0507.py | Python | bsd-3-clause | 1,022 | 0.002935 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-06-05 05:07
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('topics', '0010_auto_20170531_1439'),
]
operations ... | tion.CASCADE, to='topics.Topic')),
],
options={
| 'ordering': ('year', 'score'),
},
),
migrations.AlterUniqueTogether(
name='yeartopicrank',
unique_together=set([('year', 'topic')]),
),
]
|
cytomine/Cytomine-python-client | cytomine/tests/test_pattern_matching.py | Python | apache-2.0 | 1,106 | 0.001808 | from collections import namedtuple
from cytomine.models._utilities.pattern_matching import resolve_pattern
class TestPatternM | atching:
def get_fake_type(self):
return namedtuple("fakeobj", ["lst", "atomstr", "atomfloat"])
def test_no_iterable_pattern(self):
fake = self.get_fake_type()(lst=1, atomstr="aa", atomfloat=1.5)
resolved = sorted(resolve_pattern("{lst}/{atomstr}_{atomfloat}.png", fake))
assert(... | e_iterable_pattern(self):
fake = self.get_fake_type()(lst=[1, 2, 3], atomstr="aa", atomfloat=1.5)
resolved = sorted(resolve_pattern("{lst}/{atomstr}_{atomfloat}.png", fake))
assert(len(resolved) == 3)
assert(resolved[0] == "1/aa_1.5.png")
assert(resolved[1] == "2/aa_1.5.png")
... |
HERA-Team/pyuvdata | pyuvdata/uvcal/uvcal.py | Python | bsd-2-clause | 170,532 | 0.001824 | # -*- mode: python; coding: utf-8 -*-
# Copyright (c) 2018 Radio Astronomy Software Group
# Licensed under the 2-clause BSD License
"""Primary container for radio interferometer calibration solutions."""
import copy
import numpy as np
import threading
import warnings
from ..uvbase import UVBase
from .. import paramet... | example of how to convert this to topocentric frame."
)
self._antenna_positions = uvp.UVParameter(
"antenna_positions",
description=desc,
form=("Nants_telescope", 3),
expected_type=float,
tols=1e-3, # 1 mm
required=False,
)... | d' calibration solutions with gains or delays "
"that apply over a range of frequencies rather than having distinct values "
"at each frequency. Delay type cal solutions are always 'wide-band' if "
"future_array_shapes is True. If it is True several other parameters are "
... |
kandluis/machine-learning | prac4/practical4-code/qlearner3.py | Python | mit | 2,670 | 0.026217 | from qlearner import QLearner
import numpy as np
from collections import defaultdict
class QLearner3(QLearner):
'''
Implements a more intelligent Q-Learning Mechanism. Uses Logistic function for learning learn_rate
decay. Not that the parameters have been optimized using SpearMint.
'''
def __init__(self, es... | er_num)
self.Q[s][a] += learn_rate * (r + discount*(max(self.Q[sp])) - self.Q[s][a])
self.last_action = new_action
self.last_state = ne | w_state
return new_action
|
hvelazquezs/TheIoTLearningInitiative | InternetOfThings101/MainAll01.py | Python | apache-2.0 | 5,180 | 0.036486 | #!/usr/bin/python
import pyupm_i2clcd as lcd
import psutil
import pywapi
import signal
import os
import sys
import time
import paho.mqtt.client as paho
import string
import plotly.plotly as py
import dweepy
import pyupm_grove as grove
from plotly.graph_objs import Scatter, Layout, Figure
from threading import Thread
f... | stream=dict(
token=stream_token,
maxpoints=200
)
)
layout = Layout(
title='Hello Internet of Things 101 Data'
)
fig = Figure(data=[trace1], layout=layout)
print py.plot(fig, filename='Hello Internet of Things 101 Plotly')
i = 0
stream = py.Stream(s... | _data = dataPlotly()
stream.write({'x': i, 'y': stream_data})
i += 1
time.sleep(0.25)
class Network(Resource):
def get(self):
return(data)
if __name__ == '__main__':
signal.signal(signal.SIGINT, interruptHandler)
threadx = Thread(target=dataNetworkHandler)
threadx.start()
... |
MediffRobotics/DeepRobotics | rpiRobotArm/InverseKine/robotics-toolbox-python1/trunk/robotics-toolbox-python/demo/fdyn.py | Python | gpl-3.0 | 1,911 | 0.016222 | # Copyright (C) 1993-2002, by Peter I. Corke
# $Log: rtfddemo.m,v $
# Revision 1.4 2002/04/02 12:26:48 pic
# Handle figures better, control echo at end of each script.
# Fix bug in calling ctraj.
#
# Revision 1.3 2002/04/01 11:47:17 pic
# General cleanup of code: help comments, see also, copyright, remnant dh/dyn
... | for a user written function to compute the joint torque as a function of
# manipulator state.
#
# To simulate the motion of the Puma 560 from rest in the zero angle pose
# with zero applied joint torques
tic
[t q qd] = fdyn(nofriction(p560), 0, 10);
toc
# |
# and the resulting motion can be plotted versus time
subplot(3,1,1)
plot(t,q(:,1))
xlabel('Time (s)');
ylabel('Joint 1 (rad)')
subplot(3,1,2)
plot(t,q(:,2))
xlabel('Time (s)');
ylabel('Joint 2 (rad)')
subplot(3,1,3)
plot(t,q(:,3))
xlabel('Time (s)');
ylabel('Joint 3 (ra... |
PacificBiosciences/rDnaTools | src/pbrdna/rDnaResequencer.py | Python | bsd-3-clause | 16,747 | 0.009196 | #################################################################################$$
# Copyright (c) 2011,2012, Pacific Biosciences of California, Inc.
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are... | default=DEFAULT_MIN_CLUSTER, metavar='INT',
help='Minimum number of CCS reads to resequence')
parser.add_argument('-n', '--numProc', type=int,
default=1, metavar='INT',
| help="Number of processors to use")
parser.add_argument('-o', '--outputDir', default='reseq',
help="Specify a directory for intermediate files")
args = parser.parse_args()
self.__dict__.update( vars(args) )
def initializeFromCall(self, listFile, seqFile, dista... |
zubie7a/Algorithms | Google_Code_Jam/2020/Qualifier_Round/03_Parenting_Partnering_Returns.py | Python | mit | 4,723 | 0.000635 | # 03 - Parenting Partening Returns
# Scheduling kid activities and domestic necesities is a chal | lenge for a couple
# parents of a 3 year old child. They have a list of N activities to take care
# during the day, each activity | happens during a specified interval in the day.
# Thet need to assign each activity to any of the parents, so that neither of
# them is responsible of 2 activities that overlap. An activity that ends at
# time t is not considered to overlap with an activity that starts at time t.
# The parents names are Jamie and Cam... |
diego-d5000/Estudiala | estudiala/estudiala/usuarios/migrations/0001_initial.py | Python | mit | 1,127 | 0.007098 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Usuarios',
fields=[
('id', models.AutoField(ver... | ose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(max_length=225, verbose_name='Nombre')),
('middle_name', models.CharField(max_length=225, verbose_name='Apellido Paterno')),
('last_name', models.CharField(max_length=225, nul... | ngth=225, verbose_name='Correo')),
('user_name', models.CharField(unique=True, max_length=225, verbose_name='Nombre de Usuario')),
('password', models.CharField(max_length=225, verbose_name='Contrasenia')),
('user_type', models.CharField(max_length=225, verbose_name='Tipo... |
royalwang/readthedocs.org | readthedocs/projects/urls/private.py | Python | mit | 4,653 | 0.000645 | """Project URLs for authenticated users"""
from django.conf.urls import patterns, url
from readthedocs.projects.views.private import AliasList, ProjectDashboard, ImportView
from readthedocs.projects.backends.views import ImportWizardView, ImportDemoView
urlpatterns = patterns(
# base view, flake8 complains if i... | roject_comments_moderation',
name='projects_comments_moderation'),
url(r'^(?P<project_slug>[-\w]+)/edit/$',
'readthedocs.projects.v | iews.private.project_edit',
name='projects_edit'),
url(r'^(?P<project_slug>[-\w]+)/advanced/$',
'readthedocs.projects.views.private.project_advanced',
name='projects_advanced'),
url(r'^(?P<project_slug>[-\w]+)/version/(?P<version_slug>[^/]+)/delete_html/$',
'readthedocs.project... |
greeenSY/Tstream | tstream-client/src/main/py/storm/ttypes.py | Python | apache-2.0 | 148,568 | 0.01888 | #
# Autogenerated by Thrift Compiler (0.7.0)
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
from thrift.Thrift import *
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol, TProtocol
try:
from thrift.proto | col import fastbinary
except:
fastbinary = None
class TopologyInitialStatus:
ACTIVE = 1
INACTIVE = 2
_VALUES_TO_NAMES = {
1: "ACTIVE",
2: "INACTIVE",
}
_NAMES_TO_VALUES = {
"ACTIVE": 1,
"INACTIVE": 2,
}
class JavaObjectArg:
"""
Attributes:
- int_arg
- long_arg
- string_a... | ne, # 0
(1, TType.I32, 'int_arg', None, None, ), # 1
(2, TType.I64, 'long_arg', None, None, ), # 2
(3, TType.STRING, 'string_arg', None, None, ), # 3
(4, TType.BOOL, 'bool_arg', None, None, ), # 4
(5, TType.STRING, 'binary_arg', None, None, ), # 5
(6, TType.DOUBLE, 'double_arg', None, None, ), #... |
liuwenf/moose | python/MooseDocs/tests/template/test_template.py | Python | lgpl-2.1 | 4,058 | 0.0069 | #!/usr/bin/env python
#pylint: disable=missing-docstring
####################################################################################################
# DO NOT MODIFY THIS HEADER #
# MOOSE - Multiphysics Object Oriented Simu... | #
# Prepared by Battelle Energy Alliance, LLC #
# | Under Contract No. DE-AC07-05ID14517 #
# With the U. S. Department of Energy #
# #
# See ... |
iti-luebeck/HANSE2012 | hanse_ros/hanse_behaviourctrl/nodes/behaviourctrl_pipe.py | Python | bsd-3-clause | 14,366 | 0.030906 | #!/usr/bin/env python
import roslib; roslib.load_manifest('hanse_behaviourctrl')
import rospy
import smach
import smach_ros
import signal
import os
import actionlib
from hanse_msgs.msg import sollSpeed, pressure
from std_msgs.msg import Float64, Float32, String
from geometry_msgs.msg import PoseStamped, Point, Twist, V... | e_timeout = rospy.Duration(180))
goalStatusDict = | {
GoalStatus.PENDING : "PENDING",
GoalStatus.ACTIVE : "ACTIVE",
GoalStatus.PREEMPTED : "PREEMPTED",
GoalStatus.SUCCEEDED : "SUCCEEDED",
GoalStatus.ABORTED : "ABORTED",
}
rospy.loginfo('Result: ' + goalStatusDict[state])
if state == GoalStatus... |
lucienfostier/gaffer | python/GafferImageUI/RankFilterUI.py | Python | bsd-3-clause | 3,440 | 0.020058 | ##########################################################################
#
# Copyright (c) 2017, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistrib... | ERCHANTABILITY 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, O | R 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
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY O... |
mirjalil/ml-visual-recognition | codes/classify_half5.py | Python | apache-2.0 | 4,215 | 0.017082 | import numpy as np
import pandas
import scipy, scipy.spatial
import sklearn
import sklearn.svm
import sys
import argparse
import pickle
sys.path.append('codes/')
from utilities_v2 import *
ymin = 157
ysplit = 160
ymax = 161
feat_threshold = 0.01
# C=10.0000 Gamma=0.0080
optimal_c = 10.00
optimal_gamma = 0.008
... | #print(np.unique(ysub))
n = 50000
for i in range(1):
Xsub, ysub = readRandomSample(args.train, y[0], siz | e=n, \
goodfeat=goodfeatures, acc_miny=ymin, acc_maxy=ymax)
assert(np.sum(ysub < ymin) == 0)
assert(np.sum(ysub > ymax) == 0)
ysub[np.where(ysub < ysplit)[0]] = -1
ysub[np.where(ysub >= ysplit)[0]] = 1
features_idx = np.where(np.std(Xsub, axis=0)> 0.0001)[0]
print("N... |
viktorRock/myFirstPythonAPI | pythonapi/settings.py | Python | unlicense | 5,496 | 0.002001 | """
Django settings for pythonapi project.
Generated by 'django-admin startproject' using Django 1.11.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
# Parse da... | ework.authtoken',
'corsheaders',
'pythapp',
]
MIDDLEWARE | = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddlewar... |
cancerregulome/gidget | gidget/gidget_add.py | Python | mit | 300 | 0.003333 | # vim: ta | bstop=4 expandtab shiftwidth=4 softtabstop=4
# -*- mode: python; indent-tabs-mode nil; tab-width 4; python-indent 4; -*-
"""
usage: gidget add data <filename>
gidget add reference <filename>
"""
fro | m docopt import docopt
if __name__ == '__main__':
print(docopt(__doc__))
|
crmne/jobman | jobman/sql_runner.py | Python | bsd-3-clause | 39,656 | 0.001412 | """ WRITEME """
from __future__ import with_statement
try:
import sql
from cachesync_runner import cachesync_lock
import cachesync_runner
except:
pass
import os
import tempfile
import shutil
import socket
import optparse
import time
import random
import re
from optparse import OptionParser
from tools... | le rsync_rval != 0 and keep_trying:
rsync_rval = os.system(rsync_cmd)
if rsync_rval != 0: |
attempt += 1
keep_trying = attempt < num_retries
# wait anywhere from 30s to [2,4,6] mins before retrying
if keep_trying:
r = random.randint(30, attempt * 120)
print >> os.sys.stderr, ('RSync... |
vizcacha/practicalcv | chapter3/converting_set.py | Python | mit | 214 | 0 | from SimpleCV import ImageSet
img_set = ImageSet(".")
for img in img_set:
oldname = img.fil | ename
newname = oldname[0:-3] + 'jpg'
print 'Converting ' + oldname + ' to ' + newname
img.save(n | ewname)
|
Zarokka/exaile | xlgui/preferences/plugin.py | Python | gpl-2.0 | 11,952 | 0.004016 | # Copyright (C) 2008-2010 Adam Olsen
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that... | re not obligated to
# do so. | If you do not wish to do so, delete this exception statement
# from your version.
from gi.repository import GLib
from gi.repository import Gtk
from xl import (
event,
main,
plugins,
xdg
)
import xl.common
from xlgui.widgets import common, dialogs
from xl.nls import gettext as _, ngettext
import logg... |
sweemeng/Malaysian-Bill-Watcher | billwatcher/indexer.py | Python | gpl-3.0 | 3,747 | 0.021617 | import pyes
import os
from models import *
from sqlalchemy import select
from downloader import download
import utils
import re
import time
class Search(object):
def __init__(self,host,index,map_name,mapping=None,id_key=None):
self.es = pyes.ES(host)
self.index = index
self.map_name = map_... | es':self.mapping
}
},[self.index])
self.es.refresh(self.index)
def index_item(self,item):
self.es.index(item,self.index,self.map_name)
self.es.refresh(self.index)
def convert_to_document(revision):
temp = {}
rev_key = [ i for i in dir(revision) ... | ll':
temp[key] = getattr(revision,key)
for key in bill_key:
if key != 'metadata' and key!='id' and key!='bill_revs':
temp[key] = getattr(revision.bill,key)
full_path = download(temp['url'])
if full_path:
temp['document'] = pyes.file_to_attachment(full_path)
... |
alexey4petrov/reinteract | lib/reinteract/main_menu.py | Python | bsd-2-clause | 3,049 | 0.002624 | # Copyright 2008 Owen Taylor
#
# This file is part of Reinteract and distributed under the terms
# of the BSD license. See the file COPYING in the Reinteract
# distribution for full details.
#
########################################################################
import glib
from about_dialog import AboutDialog
fro... | getattr(self | .__active_window, method_name)(None)
elif hasattr(self, method_name):
getattr(self, method_name)()
else:
print action_name
def do_action(self, action_name):
# Recursing the main loop (which we do for various messages, etc), is a bad thing
# to do out of a Qua... |
Spiderlover/Toontown | toontown/cogdominium/DistributedCogdoElevatorExt.py | Python | mit | 561 | 0.001783 | from toontown.building.DistributedElevatorExt import DistributedElevatorExt
class DistributedCogdoElevatorExt(DistributedElevatorExt):
def setupElevator(self):
DistributedElevatorExt.setupElevator(self)
self.elevatorSphereNodePath.setY(-1.0)
self.elevatorSphereNodePath.setZ(1.5)
def g... | l(self):
return self.bldg.getCogdoElevatorNodePath()
def getBldgDoorOrigin( | self):
return self.bldg.getCogdoDoorOrigin()
def _getDoorsClosedInfo(self):
return ('cogdoInterior', 'cogdoInterior')
|
yhalk/vw_challenge_ECR | src/jetson/keras_frcnn/config.py | Python | apache-2.0 | 1,646 | 0.041312 | from keras import backend as K
class Config:
def __init__(self):
self.verbose = True
self.network = 'resnet50'
# setting for data augmentation
self.use_horizontal_flips = True
self.use_vertical_flips = True
self.rot_90 = True
# anchor box scales
self.anchor_box_scales = [1, 2, 4, 8, 16, 32, 64, ... | 1,5],[5,1],[1,6],[6,1],[1,7],[7,1],[1,8],[8,1],[1 | ,9],[9,1]]
# size to resize the smallest side of the image
self.im_size = 600
# image channel-wise mean to subtract
self.img_channel_mean = [103.939, 116.779, 123.68]
self.img_scaling_factor = 1.0
# number of ROIs at once
self.num_rois = 8
# stride at the RPN (this depends on the network configurati... |
azaghal/ansible | lib/ansible/plugins/action/fetch.py | Python | gpl-3.0 | 9,755 | 0.00369 | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) an... | lt['msg'] = "python isn't present on the system. Unable to compute checksum"
elif remote_checksum == '5':
result['msg'] = "stdlib json was not found on the remote machine. Only the raw module can work without those installed"
# Historically, these don't fail because ... | # ignore_errors or failed_when to the task. Control the behaviour
# via fail_when_missing
if fail_on_missing:
result['failed'] = True
del result['changed']
else:
result['msg'] += ", not transferring, i... |
leppa/home-assistant | homeassistant/components/met/config_flow.py | Python | apache-2.0 | 2,709 | 0.001107 | """Config flow to configure Met component."""
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import CONF_ELEVATION, CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME
from homeassistant.core import callback
import homeassistant.helpers.config_validation as cv
from .const import CONF_... | HOME_LOCATION_NAME
@callback
def configured_instances(hass):
"""Return a set of configured SimpliSafe instances."""
e | ntites = []
for entry in hass.config_entries.async_entries(DOMAIN):
if entry.data.get("track_home"):
entites.append("home")
continue
entites.append(
f"{entry.data.get(CONF_LATITUDE)}-{entry.data.get(CONF_LONGITUDE)}"
)
return set(entites)
class MetFl... |
ivaano/zato | code/zato-server/src/zato/server/base/singleton.py | Python | gpl-3.0 | 6,006 | 0.005162 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2010 Dariusz Suchojad <dsuch at zato.io>
Licensed under LGPLv3, see LICENSE.txt for terms and conditions.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
# stdlib
import logging
from datetime import datetime, timedelta
from time import... | is, we can't publish messages
from the scheduler yet. This would be good in itself, but we must be sure there is at least one server (worker) to handle
the message. We don't know how many server there are in this cluster so the only thing we can do is to assume that our
parallel_server's worker ... | worker_not_ready_sleep_time = 0.25 # In seconds
while not self.parallel_server.worker_store.is_ready:
self.logger.info('Worker not ready, sleeping for %s s', worker_not_ready_sleep_time)
sleep(worker_not_ready_sleep_time)
def become_cluster_wide(self, connector_server_keep_alive_... |
DESHRAJ/fjord | vendor/packages/nose/unit_tests/test_issue_064.py | Python | bsd-3-clause | 83 | 0 | def test_is_generator_alias | ():
from | nose.util import is_generator, isgenerator
|
yosshy/osclient2 | osclient2/exception.py | Python | apache-2.0 | 770 | 0 | # Copyright 20 | 14-2017 by Akira Yoshiyama <akirayoshiyama@gmail.com>.
# 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 agreed to in writing, software
# distributed under the License is distributed on an "AS IS... |
ah-anssi/SecuML | SecuML/core/ActiveLearning/QueryStrategies/AnnotationQueries/Category.py | Python | gpl-2.0 | 8,916 | 0.000336 | # SecuML
# Copyright (C) 2016-2017 ANSSI
#
# SecuML 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 option) any later version.
#
# SecuML is distributed in the h... | ):
for k, queries in self.annotation_queries.items():
| for q, query in enumerate(queries):
query.getManualAnnotation(iteration)
def checkAnnotationQueriesAnswered(self, iteration):
for k, queries in self.annotation_queries.items():
for q, query in enumerate(queries):
if not query.checkAnswered(iteration):
... |
jasonwee/asus-rt-n14uhp-mrtg | src/lesson_developer_tools/doctest_in_help.py | Python | apache-2.0 | 67 | 0 | def | my_function(a, b):
"""Returns a*b
"""
return a * | b
|
catapult-project/catapult | tracing/tracing_build/generate_about_tracing_contents.py | Python | bsd-3-clause | 1,914 | 0.008882 | # Copyright (c) 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import codecs
import argparse
import os
import sys
import py_vulcanize
import tracing_project
def Main(args):
parser = argparse.ArgumentParser(usag... | project = tracing_project.TracingProject()
vulcanizer = project.CreateVulcanizer()
load_sequence = vulcanizer.CalcLoadSequenceForModuleNames(names)
olddir = os.getcwd()
try:
if not os.path.exists(args.out_dir):
os.makedirs(args.out_dir)
o = codecs.open(os.path.join(args.out_d | ir, 'about_tracing.html'), 'w',
encoding='utf-8')
try:
py_vulcanize.GenerateStandaloneHTMLToFile(
o,
load_sequence,
title='chrome://tracing',
flattened_js_url='tracing.js',
minify=not args.no_min)
except py_vulcanize.module.DepsExceptio... |
nschloe/maelstrom | doc/conf.py | Python | mit | 8,234 | 0.001701 | # -*- coding: utf-8 -*-
#
# maelstrom documentation build configuration file, created by
# sphinx-quickstart on Tue Feb 18 00:56:56 2014.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# A... | se URL from which the finished HTML is served.
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = "maelstromdoc"
# -- Options for LaTeX output -----------------------------------------... | s = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, t... |
jmadajian/CinemaFlowWorks | kivy-designer-master/designer/components/dialogs/about.py | Python | gpl-3.0 | 342 | 0 | from kivy.uix.floatlayout import FloatLayout
class AboutDialog(FloatLayout):
'''AboutDialog, | to display about information.
It emits 'on_cancel' event when 'Cancel' button is released.
'''
__events__ = ('on_close',)
def on_close(s | elf, *args):
'''Default handler for 'on_close' event
'''
pass
|
cychenyin/windmill | apscheduler/jobstores/memory.py | Python | mit | 3,664 | 0.001365 | # coding: utf-8
from __future__ import absolute_import
from apscheduler.jobstores.base import BaseJobStore, JobLookupError, ConflictingIdError
from apscheduler.util import datetime_to_utc_timestamp
class MemoryJobStore(BaseJobStore):
"""
Stores jobs in an array in RAM. Provides no persistence support.
P... | mid_timestamp is None else mid_timestamp
if mid_timestamp > timestamp:
hi | = mid
elif mid_timestamp < timestamp:
lo = mid + 1
elif mid_job.id > job_id:
hi = mid
elif mid_job.id < job_id:
lo = mid + 1
else:
return mid
return lo
|
tchellomello/home-assistant | homeassistant/components/mysensors/cover.py | Python | apache-2.0 | 3,250 | 0.000308 | """Support for MySensors covers."""
from homeassistant.components import mysensors
from homeassistant.components.cover import ATTR_POSITION, DOMAIN, CoverEntity
from homeassistant.const import STATE_OFF, STATE_ON
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the ... | over_position(self, **kwargs):
"""Move the cover to a specific position."""
position = kwargs.get(ATTR_POSITION)
set_req = self.gateway.const.SetReq
self.gateway.set_child_value(
self.node_id, self.child_id, set_req.V_DIMMER, position, ack=1
)
if self.gateway.... | istically assume that cover has changed state.
self._values[set_req.V_DIMMER] = position
self.async_write_ha_state()
async def async_stop_cover(self, **kwargs):
"""Stop the device."""
set_req = self.gateway.const.SetReq
self.gateway.set_child_value(
self.... |
cphyc/MHD_simulation | python/simul.py | Python | apache-2.0 | 9,256 | 0.014156 | #!/usr/env python3
try:
import numpypy as np
except:
import numpy as np
try:
import cPickle as pickle
except ImportError:
import pickle
#import ipdb
## Tri Diagonal Matrix Algorithm(a.k.a Thomas algorithm) solver
def TDMAsolver(a, b, c, d):
'''
TDMA solver, a b c d can be NumPy array type or Py... | ) * self.wk1[0,n]
for k in range(1, self.p.Nz-1):
self.wk1[k,n] = 1 /(dia(k)-sub_f(k)*self.wk2[k-1,n])
self.wk2[k,n] = sup(k)*self.wk1[k,n]
self.wk1[-1,n] = 1/(dia(self.p.Nz-1) | -sub_f(self.p.Nz-1)*self.wk2[-2,n])
self.sub[:,n] = [sub_f(k) for k in range(self.p.Nz)]
def step(self):
rhs = self.p.psi.field.copy()
# boundary conditions k=0, Nz-1 : psi = 0
rhs[0, :] = 0
rhs[-1,:] = 0
for n in range(1,self.p.NFourier):
# tridi... |
mikofski/Carousel | carousel/tests/test_data.py | Python | bsd-3-clause | 5,322 | 0.000188 | """
Test data sources
"""
from nose.tools import ok_, eq_
from carousel.tests import logging
from carousel.core import UREG
from carousel.core.data_sources import DataSource, DataParameter
from carousel.core.data_readers import XLRDReader
from carousel.tests import PROJ_PATH, TESTS_DIR
import os
LOGGER = logging.getL... | Parameter(**{
"description": "inverter database",
"isconstant": True,
"dtype": "str"
})
Tamb = DataParameter(**{
"description": "average yearly ambient air temperature",
"units": "degC",
"isconstant": True,
"dtype": "flo... | "isconstant": True,
"dtype": "float",
"uncertainty": 1.0
})
surface_azimuth = DataParameter(**{
"description": "site rotation",
"units": "degrees",
"isconstant": True,
"dtype": "float",
"uncertainty": 1.0
})
... |
melrcm/Optimizepy | all_permutes.py | Python | lgpl-2.1 | 2,210 | 0.006335 | import numpy as np
import os
def itera_f(num, start, steps):
''' All possible portfolio configurations. BETTER IMPLEMENTATION??
steps = (int) Size of the steps. Input 100 would be interpreted as 1.
| Input 10, 0.1. Input 1, 0.01.
'''
if num[start]-steps >= 0:
array_ones = []
for itera in range(int(num[sta | rt]/steps)):
print '|',
num[start] -= steps
num[start+1] = 100+steps
for i in range(int(num[start+1]/steps)):
num[start+1] -= steps
if sum(num) == 100:
array_ones = np.append(array_ones, num, axis=0)
elif... |
CeltonMcGrath/TACTIC | 3rd_party/CherryPy/cherrypy/_cpchecker.py | Python | epl-1.0 | 14,288 | 0.004549 | import os
import warnings
import cherrypy
class Checker(object):
"""A checker for CherryPy sites and their mounted applications.
on: set this to False to turn off the checker completely.
When this object is called at engine startup, it executes each
of its own methods whose names start with... | ():
if not isinstance(app, cherrypy.Application):
continue
msg = []
for section, entries in app.config.iteritems():
if section.startswith('/'):
for key, value in entries.iteritems():
for n in ("e... | msg.append("[%s] %s = %s" % (section, key, value))
if msg:
msg.insert(0,
"The application mounted at %r contains the following "
"config entries, which are only allowed in site-wide "
"config. Move them... |
EvgeneOskin/termius-cli | termius/cloud/commands.py | Python | bsd-3-clause | 4,879 | 0 | # -*- coding: utf-8 -*-
"""Module for pull and push command."""
import abc
from base64 import b64decode
import six
from six.moves import configparser
from ..core.api import API
from ..core.commands import AbstractCommand
from ..core.models.terminal import clean_order
from .client.controllers import ApiController
from .... | = RNCryptor()
cryptor.password = password
cryptor.encryption_salt = encryption_salt
cryptor.hmac_salt = hmac_salt
for i in parsed_args.text:
result_text = getattr(cryptor, parsed_args.operation)(i)
self.app.stdout.write('{}\n | '.format(result_text))
|
cloudera/hue | desktop/core/ext-py/Django-1.11.29/tests/gis_tests/test_geoip.py | Python | apache-2.0 | 6,866 | 0.001603 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import socket
import unittest
import warnings
from unittest import skipUnless
from django.conf import settings
from django.contrib.gis.geoip import HAS_GEOIP
from django.contrib.gis.geos import HAS | _GEOS, GEOSGeometry
from django.test import ignore_warnings
from django.utils import six
from django.utils.deprecation import RemovedInDjango20Warning
from django.utils.encoding import force_text
if HAS_ | GEOIP:
from django.contrib.gis.geoip import GeoIP, GeoIPException
from django.contrib.gis.geoip.prototypes import GeoIP_lib_version
# Note: Requires use of both the GeoIP country and city datasets.
# The GEOIP_DATA path should be the only setting set (the directory
# should contain links or the actual databas... |
QuantiModo/QuantiModo-SDK-Python | SwaggerPetstore/apis/pairs_api.py | Python | gpl-2.0 | 5,412 | 0.010163 | #!/usr/bin/env python
# coding: utf-8
"""
PairsApi.py
Copyright 2015 SmartBear Software
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://ww | w.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 la | nguage governing permissions and
limitations under the License.
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
"""
from __future__ import absolute_import
import sys
import os
# python 2 and python 3 compatibility library
from six import iteritems
from ..... |
matteorr/coco-analyze | analysisAPI/occlusionAndCrowdingSensitivity.py | Python | mit | 9,340 | 0.019058 | ## imports
import os, time
import numpy as np
import m | atplotli | b.pyplot as plt
# package imports
from . import utilities
def occlusionAndCrowdingSensitivity( coco_analyze, oks, saveDir ):
loc_dir = saveDir + '/benchmarks_sensitivity/occlusion_crowding'
if not os.path.exists(loc_dir):
os.makedirs(loc_dir)
f = open('%s/std_out.txt'%loc_dir, 'w')
f.write("R... |
qbazd/leo_pass_selector | granule_selector.py | Python | mit | 3,028 | 0.023448 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#example AVHRR file selector
import logging
logging.basicConfig()
#logging.debug("-- log message: ")
from granule_utils import generate_avhrr_platform_passes_over_aoi, get_pass_for_granule,save_passes_as_shp, read_tle_from_file_db, get_tle_spacetrack
import numpy as np... | .isfile(passes_predict_file): #cache predictions in file
print "passes already predicted in %s Abording!" % passes_predict_file |
exit()
# read aoi_passes_timeslots from file
import yaml
aoi_predicted_passes = yaml.load(file(platform_passes_predict_file, 'r'))
for platform in aoi_predicted_passes.keys():
aoi_timeslots = aoi_predicted_passes[platform]
print aoi_timeslots
print "Selected passes:"
# filter aoi_slots
aoi_timeslots_tmp = aoi_t... |
tudennis/LeetCode---kamyu104-11-24-2015 | Python/longest-palindrome.py | Python | mit | 985 | 0.001015 | # Time: O(n)
# Space: O(1)
# Given a string which consists of lowercase or uppercase letters,
# find the length of the longest palindromes that can be built with those letters.
#
# This is case sensitive, for example "Aa" is not considered a palindrome here.
#
# Note:
# Assume the length of given string will not exce... | an be built is "dccaccd", whose length is 7.
import collections
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: int
"""
odds = 0
for k, v in collections.Counter(s).iteritems():
odds += v & 1
return len(s) - odds +... | .values()))
return len(s) - odd + int(odd > 0)
|
unitycoders/uc-django-site | lectern/admin.py | Python | gpl-3.0 | 495 | 0.024242 | from django.contrib import admin
from models import Article, RelatedLink, Category
# Register your models here.
class RelatedLinkInline(admin.T | abularInline):
model = RelatedLink
extra = 1
class ArticleAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("title",) | }
search_fields = ['title']
list_display = ['title', 'slug', 'category']
list_filter = ['created', 'modified']
inlines = [
RelatedLinkInline
]
admin.site.register(Article, ArticleAdmin)
admin.site.register(Category)
|
boffi/boffi.github.io | dati_2016/07/exercise1.py | Python | mit | 3,949 | 0.031907 | ######################################################################
# Preliminaries,
import scipy as sp
mat=sp.matrix
from scipy.linalg import inv
######################################################################
# an utility function to format a matrix for inclusion in a LaTeX file
def latex_print(data,name,fm... | free vibrations for psi_0i = | 1
for i in range(3):
Omega2=Omegas[0,i]/1200
coef=mat(((3.-3.*Omega2,-2.),(-2.,5.-4.*Omega2)))
bottom=coef.I*known
# this sets the bottom part of each eigenvector
Eigenv[1:,i]=bottom
latex_print(Eigenv,"mat",title="Eigenvectors Matrix")
MStar=Eigenv.T*Mass*Eigenv
latex_print(MStar,"mat",title="Mod... |
saeschdivara/myclothing | website/manage.py | Python | mit | 241 | 0.004149 | #!/usr/bin/env python
import os
import sys
if __name__ == "__m | ain__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
from django.core.management import | execute_from_command_line
execute_from_command_line(sys.argv) |
samuelclay/NewsBlur | vendor/reverend/ui/trainer.py | Python | mit | 13,036 | 0.003529 | # This module is part of the Divmod project and is Copyright 2003 Amir Bakhtiar:
# amir@divmod.org. This is free software; you can redistribute it and/or
# modify it under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
from tkinter import *
import t... | else:
self.guesser = guesser
if itemClass is None:
self.itemClass = TextItem
else:
self.itemClass = itemClass
for row in self.rows:
row.summary.set('foo')
| self.initViews()
def initViews(self):
self.nb = Notebook(self)
## frame1 = Frame(self.nb())
## self.poolView = PoolView(frame1, guesser=self.guesser, app=self)
## self.poolView.pack(side=TOP)
frame2 = Frame(self.nb())
self.poolView = PoolView(frame2, guesser=self.g... |
eduNEXT/edx-platform | openedx/core/djangoapps/embargo/tests/test_models.py | Python | agpl-3.0 | 12,595 | 0.000953 | """Test of models for embargo app"""
import json
import pytest
from django.db.utils import IntegrityError
from django.test import TestCase
from opaque_keys.edx.locator import CourseLocator
from openedx.core.djangolib.testing.utils import CacheIsolationTestCase
from ..models import (
Country,
CountryAccessRu... | cauth.save()
# Now, course should be embargoed
assert EmbargoedCourse.is_embargoed(course_id)
assert str(cauth) == f"Course '{course_id}' is Embargoed"
# Unauthorize by explicitly setting email_enabled to False
cauth.embargoed = False
ca | uth.save()
# Test that course is now unauthorized
assert not EmbargoedCourse.is_embargoed(course_id)
assert str(cauth) == f"Course '{course_id}' is Not Embargoed"
def test_state_embargo(self):
# Azerbaijan and France should not be blocked
good_states = ['AZ', 'FR']
#... |
azumimuo/family-xbmc-addon | plugin.video.bubbles/resources/lib/externals/hachoir/hachoir_core/field/link.py | Python | gpl-2.0 | 3,240 | 0.001235 | from resources.lib.externals.hachoir.hachoir_core.field import Field, FieldSet, ParserError, Bytes, MissingField
from resources.lib.externals.hachoir.hachoir_core.stream import FragmentedStream
class Link(Field):
def __init__(self, parent, name, *args, **kw):
Field.__init__(self, parent, name, 0, *args, *... | f _createFields(self, field_generator):
if self._first is None:
for field in field_generator:
if self._first is not None:
break
yield field
else:
raise ParserError("Fragme | nt.setLinks not called")
else:
field = None
if self._first is not self:
link = Link(self, "first", None)
link._getValue = lambda: self._first
yield link
if self._next:
link = Link(self, "next", None)
link.createValue = self.... |
DarthMaulware/EquationGroupLeaks | Leak #5 - Lost In Translation/windows/Resources/Python/Core/Lib/encodings/utf_8.py | Python | unlicense | 1,084 | 0.00369 | # uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: utf_8.py
""" Python 'utf-8' Codec
Written by Marc-Andre Lemburg (mal@lemburg.com).
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
"""
impo... | er(codecs.StreamWriter):
encode = codecs.utf_8_encode
class StreamReader(codecs.StreamReader):
decode = codecs.utf_8_decode
def getregentry():
return codecs.CodecInfo(name='utf-8', encod | e=encode, decode=decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter) |
mlperf/training_results_v0.5 | v0.5.0/google/cloud_v100x8/code/resnet/benchmarks/scripts/tf_cnn_benchmarks/models/nasnet_utils.py | Python | apache-2.0 | 18,310 | 0.008192 | # Copyright 2018 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... |
filter_shape = _operation_to_filter_shape(operation)
return num_layers, filter_shape
def _stacked_separable_conv(net, stride, operation, filter_size):
"""Takes in an | operations and parses it to the correct sep operation."""
num_layers, kernel_size = _operation_to_info(operation)
net_type = net.dtype
net = tf.cast(net, tf.float32) if net_type == tf.float16 else net
for layer_num in range(num_layers - 1):
net = tf.nn.relu(net)
net = slim.separable_conv2d(
net... |
Berling/project-zombye-exporter | io_exporter_zombye/export_zmdl.py | Python | mit | 8,360 | 0.024883 | # The MIT License (MIT)
#
# Copyright (c) 2015 Georg Schäfer
#
# 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, mod... | in dvert.items():
bone_name = | vertex_groups[key].name
index = bone_ids[bone_name]
vertexattributes["indices"].append(index)
vertexattributes["weights"].append(value)
material = obj.material_slots[face.material_index].material
submeshes[material.name]["indices"].append(triangle)
meshdata["vertices"] = vertices
meshdata["sub... |
ww9rivers/pysnmp | examples/v3arch/agent/ntforg/inform-v2c.py | Python | bsd-2-clause | 2,964 | 0.013833 | #
# Notification Originator
#
# Send SNMP INFORM notification using the following options:
#
# * SNMPv2c
# * with community name 'public'
# * over IPv4/UDP
# * send INFORM notification
# * to a Manager at 127.0.0.1:162
# * with TRAP ID 'coldStart' specified as an OID
# * include managed objects information:
# 1.3.6.1... | TargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 1)
# Setup transport endpoint and bind it with security settings yielding
# a target name
config.addTransport(
snmpEngine,
udp.domainName,
udp.UdpSocketTransport().openClientMode()
)
config.addTargetAddr(
snmpEngine, 'my-nms',
udp | .domainName, ('127.0.0.1', 162),
'my-creds',
tagList='all-my-managers'
)
# Specify what kind of notification should be sent (TRAP or INFORM),
# to what targets (chosen by tag) and what filter should apply to
# the set of targets (selected by tag)
config.addNotificationTarget(
snmpEngine, 'my-notification',... |
Eric89GXL/mne-python | tutorials/intro/plot_10_overview.py | Python | bsd-3-clause | 19,522 | 0 | # -*- coding: utf-8 -*-
"""
.. _tut-overview:
Overview of MEG/EEG analysis with MNE-Python
============================================
This tutorial covers the basic EEG/MEG pipeline for event-related analysis:
loading data, epoching, averaging, plotting, and estimating cortical activity
from sensor data. It introdu... | (raw)
print(raw.info)
###############################################################################
# | `~mne.io.Raw` objects also have several built-in plotting methods; here we
# show the power spectral density (PSD) for each sensor type with
# `~mne.io.Raw.plot_psd`, as well as a plot of the raw sensor traces with
# `~mne.io.Raw.plot`. In the PSD plot, we'll only plot frequencies below 50 Hz
# (since our data are low... |
a2sheppy/kuma | kuma/search/management/commands/reindex.py | Python | mpl-2.0 | 1,103 | 0.000907 | import logging
from django.core.management.base import BaseCommand, CommandError
from kuma.wiki.search import WikiDocumentType
class Command(BaseCommand):
help = "Reindex the database for Elastic."
def add_arguments(self, parser):
parser.add_argument(
| "-c",
"--chunk",
help="Chunk size when reindexing (default 250). Lower is better"
"for slow computers with little memory",
type=int,
dest="chunk_size",
default=250,
)
parser.add_argument(
"-p",
"--perc... | default=100,
)
def handle(self, *args, **options):
logging.basicConfig(level=logging.INFO)
percent = options["percent"]
if not 1 <= percent <= 100:
raise CommandError("percent should be between 1 and 100")
message = WikiDocumentType.reindex_all(options["c... |
hotpxl/mxnet | example/neural-style/end_to_end/basic.py | Python | apache-2.0 | 6,447 | 0.004188 | import sys
sys.path.insert(0, "../../mxnet/python/")
import mxnet as mx
import numpy as np
import model_vgg19 as vgg
class PretrainedInit(mx.init.Initializer):
def __init__(self, prefix, params, verbose=False):
self.prefix_len = len(prefix) + 1
self.verbose = verbose
self.arg_params = {k :... | e = get_loss_module("loss", dshape, ctx, vgg_params)
extra_args = {"target_gram_%d" % i : style_array[i] for i in range(len(style_array))}
extra_args["target_content"] = content_array
mod.set_params(extra_args, {}, True, True)
grad_array = []
for i in range(len(style_array)):
grad_array.appe... | ))
# train
img = mx.nd.zeros(content_np.shape, ctx=ctx)
img[:] = mx.rnd.uniform(-0.1, 0.1, img.shape)
lr = mx.lr_scheduler.FactorScheduler(step=80, factor=.9)
optimizer = mx.optimizer.SGD(
learning_rate = 0.001,
wd = 0.0005,
momentum=0.9,
lr_scheduler ... |
IlyaGusev/PoetryCorpus | poetry/apps/corpus/migrations/0004_auto_20170414_2304.py | Python | apache-2.0 | 757 | 0.002837 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
| from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('corpus', '0003_generationsettings_line'),
| ]
operations = [
migrations.AlterModelOptions(
name='poem',
options={'verbose_name': 'Стихотворение', 'verbose_name_plural': 'Стихотворения', 'permissions': (('can_view_restricted_poems', 'Can view restricted poems'),)},
),
migrations.AddField(
model_... |
napalm-automation/napalm-yang | napalm_yang/models/openconfig/network_instances/network_instance/protocols/protocol/isis/interfaces/interface/levels/level/afi_safi/af/segment_routing/prefix_sids/__init__.py | Python | apache-2.0 | 15,542 | 0.001222 | # -*- coding: utf-8 -*-
from operator import attrgetter
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType
from pyangbind.lib.yangtypes import RestrictedClassType
from pyangbind.lib.yangtypes import TypedListType
from pyangbind.lib.yangtypes import YANGBool
from pyangbind.lib.yangtypes import YANGListTy... | ments:
if not hasattr(args[0], e):
all_attr = False
break
if not all_attr:
raise ValueError("Sup | plied object did not have the correct attributes")
for e in self._pyangbind_elements:
nobj = getattr(args[0], e)
if nobj._changed() is False:
continue
setmethod = getattr(self, "_set_%s" % e)
if load is None:
... |
manyunkai/dannysite4 | src/manage.py | Python | apache-2.0 | 256 | 0 | #!/us | r/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dannysite_web.settings")
from django.core.management import execute_from_command_line |
execute_from_command_line(sys.argv)
|
rajeeshnair/Django-monitor | django_monitor/tests/test_app/models.py | Python | bsd-3-clause | 2,234 | 0.015219 | from django.db import models
from django.contrib import admin
from django.contrib.auth.models import User
import django_monitor
class Author(models.Model):
""" Moderated model """
name = models.CharField(max_length = 100)
age = models.IntegerField()
# To make sure that post_moderation signal is emitte... | ission of post_moderation signals"""
self.signal_emitted = True
self.save()
django_monitor.nq(Author)
def auth_moderation_handler(sender, instance, **kwargs): |
"""
Receives the post_moderation signal from Author & passes it to the instance
"""
instance.collect_signal()
django_monitor.post_moderation.connect(
auth_moderation_handler, sender = Author
)
class Publisher(models.Model):
""" Not moderated model """
name = models.CharField(max_length = ... |
justanothercoder/LSTM-Optimizer-TF | plotting.py | Python | mit | 9,450 | 0.004974 | import os
import math
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import seaborn as sns
import util
import util.paths as paths
def save_figure(fig, filename):
filename = str(filename)
fig.savefig('{filename}.svg'.format(filename=filename), fo... | flags.stochastic)
cur_ax += 1
if trainable_opt and flags.plot_lr:
#p = axes[2 - int(flags.stochastic)].plot(lrs_mean, label=name)
#axes[2 - int(flags.stochastic)].fill_between(np.arange(lrs_mean.shape[0]),
# lrs_mean + ... | pha=0.3,
# facecolor=p[-1].get_color())
p = axes[cur_ax].semilogy(np.exp(lrs_mx), label=name)
p = axes[cur_ax].semilogy(np.exp(lrs_max), label=name)
p = axes[cur_ax].semilogy(np.exp(lrs_mean), label=name)
#axes[2 - ... |
RedMap/Django-ImmOrbit | example/src/Demo/urls.py | Python | apache-2.0 | 1,077 | 0.000929 | from __future__ import print_function
from cms.sitemaps import CMSSitemap
from django.conf.urls import * # NOQA
from django.conf.urls.i18n import i18n_patterns
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from django.conf import settings
fr | om ImmOrbit.api import router
admin.autodiscover()
urlpatterns = i18n_patterns('',
url(r'^admin/', include(admin.site.urls)), # NOQA
url(r'^sitemap\.xml$', 'django.contrib.sitemaps.views.sitemap',
{ | 'sitemaps': {'cmspages': CMSSitemap}}),
url(r'^select2/', include('django_select2.urls')),
url(r'^api/', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^', include('cms.urls')),
)
# This is only needed when using runserver.
if settings.DEBUG... |
Gandi/baobab | baobab/utils/authentication.py | Python | gpl-3.0 | 950 | 0 | # -*- coding: utf-8 -*-
from oauth2 import Consumer, Client, Token
from httplib2 import ProxyInfo
from httplib2.socks import PROXY_TYPE_HTTP
from django.conf import settings
class Authentication(object):
def __init__(self, consumer_key, consumer_secret, token_key, token_secret):
consumer = Consumer(key... | OXY_TYPE_HT | TP,
proxy_host=settings.PROXY_HOST,
proxy_port=settings.PROXY_PORT)
self.client = Client(
consumer=consumer,
token=token,
proxy_info=proxy_info)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
... |
SINGROUP/pycp2k | pycp2k/classes/_define_region4.py | Python | lgpl-3.0 | 797 | 0.001255 | from pycp2k.inputsection import InputSection
class _define_region4(InputSection):
def __init__(self):
InputSection.__init__(self)
self.List = []
self.Molname = []
self.Segname = self.Molname
sel | f.Mm_subsys = None
self.Qm_subsys = None
self._name = "DEFINE_REGION"
self._keywords = {'Mm_subsys': 'MM_SUBSYS', 'Qm_subsys': 'QM_SUBSYS'}
self._repeated_keywords = {'Molname': 'MOLNAME', 'List': 'LIST'}
self._aliases = {'Protein': 'Mm_subsys'}
self._repeated_aliases = { | 'Segname': 'Molname'}
@property
def Protein(self):
"""
See documentation for Mm_subsys
"""
return self.Mm_subsys
@Protein.setter
def Protein(self, value):
self.Mm_subsys = value
|
whiskyechobravo/flask-debut | debut/public/__init__.py | Python | bsd-3-clause | 84 | 0 | """The public module, including the homepage and user auth."""
from . import views | ||
stackforge/monasca-common | monasca_common/kafka_lib/producer/__init__.py | Python | apache-2.0 | 121 | 0 | from .keyed import KeyedProducer
from .simple import SimpleProducer
__all__ = [
'Simp | lePro | ducer', 'KeyedProducer'
]
|
mhanus/GOAT | material_data_parser.py | Python | mit | 2,467 | 0.021484 | import os
import numpy
__author__ = 'Milan'
class NewXS(Exception):
pass
# noinspection PyUnboundLocalVariable
def parse_material(data_file_name):
xs = ''
new_xs = ''
xs_data = dict()
data_buffer = []
xs_names = \
{
'St': 'St',
'Ss': 'Ss',
'nSf': 'nSf',
'chi': 'chi',
'Q... | Ssk = numpy.diag(xs_data['Ss'][k])
xs_d | ata['C'][k,:,:] = numpy.diag( (2 * k + 1) * Ssk / (4 * numpy.pi * St * (St - Ssk)) )
xs_data['dimensions'] = (G, K)
# Save the dictionary of xs data
numpy.savez(os.path.splitext(data_file_name)[0] + '.npz', **xs_data)
return G, K |
openslack/openslack-web | openslack/openslack/models.py | Python | apache-2.0 | 7,902 | 0.001206 | # encoding:utf-8
import datetime
from django.core.urlresolvers import reverse
from django.db import models
class Country(models.Model):
"""
国家
"""
name = models.CharField(u'名称', max_length=200, blank=True)
chart = models.CharField(u'url标志', max_length=200, blank=True)
ename = models.CharField... | rd.
"""
if not | name:
raise ValueError('The given name must be set')
link = self.model(name=name, order=order, url=url, enabled=True, **extra_fields)
link.save()
return link
class Link(models.Model):
name = models.CharField(u"名称", max_length=200)
picture = models.ImageField(u"图片", width_fie... |
MS3FGX/rpi_lcars | screens/authorize.py | Python | gpl-3.0 | 4,092 | 0.002933 | import pygame
from pygame.mixer import Sound
from ui import colours
from ui.widgets.background import LcarsBackgroundImage
from ui.widgets.gifimage import LcarsGifImage
from ui.widgets.lcars_widgets import LcarsText, LcarsButton
from ui.widgets.screen import LcarsScreen
class ScreenAuthorize(LcarsScreen):
def set... | f num_4(self, item, event, clock):
if str(self.pin)[self.pin_i] == '4':
self.correct += 1
self.pin_i += 1
def num_5(self, item, event, clock):
if str(self.pin)[self.pin_i] == '5':
self.correct += 1
self.pi | n_i += 1
def num_6(self, item, event, clock):
if str(self.pin)[self.pin_i] == '6':
self.correct += 1
self.pin_i += 1
def num_7(self, item, event, clock):
if str(self.pin)[self.pin_i] == '7':
self.correct += 1
self.pin_i += 1
def num_8(self, item, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.