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 |
|---|---|---|---|---|---|---|---|---|
PhonologicalCorpusTools/PolyglotDB | tests/test_acoustics_vot.py | Python | mit | 1,599 | 0.005003 | import os
from decimal import Decimal
import pytest
from polyglotdb import CorpusContext
@pytest.mark.acoustic
def test_analyze_vot(acoustic_utt_config, vot_classifier_path):
pytest.skip()
with CorpusContext(acoustic_utt_config) as g:
g.reset_acoustics()
g.reset_vot()
stops = ['p', ... | = q.all()
p_true = [(1.593, 1.649), (1.832, 1.848), (1.909, 1.98), (2.116, 2.137), (2.687, 2.703),
(2.829, 2.8440000000000003), (2.934, 2.9490000000000003), (3.351, 3.403), (5.574, 5.593999999999999),
(6.207, 6.2219999999999995), (6.736, 6.755999999999999), (7.02, 7.04899999... | (13.144, 13.206), (13.498, 13.523),
(25.125, 25.14)]
for t, r in zip(p_true, p_returns):
assert (r["node_vot_begin"][0], r["node_vot_end"][0]) == t
|
baocongchen/M101P-MONGODB-FOR-PYTHON-DEVELOPERS | week4/hw4-4/hw4-4.py | Python | mit | 595 | 0.021849 | #In this problem you will analyze a profile log taken from a mongoDB instance. To start, please download sysprofile.json
#fr | om Download Handout link and import it with the following command:
#
#mongoimport -d m101 -c profile < sysprofile.json
#Now query the profile data, looking for all queries to the students collection in the database school2, sorted in order
#of decreasing latency. What is the latency of the longest running operation to... | .profile.find().sort({millis:-1}).pretty().limit(1) |
jiahaoliang/group-based-policy | gbpservice/tests/contrib/gbpfunctests/testcases/tc_gbp_ri_func_4.py | Python | apache-2.0 | 3,891 | 0.000257 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l | aw 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 limitatio | ns
# under the License.
import commands
import logging
import sys
from libs import config_libs
from libs import utils_libs
from libs import verify_libs
def main():
# Run the Testcase:
test = test_gbp_ri_func_4()
test.run()
class test_gbp_ri_func_4(object):
# Initialize logging
logging.bas... |
Pirolf/Cabot | categorize.py | Python | mit | 2,623 | 0.0122 | import numpy as np
import scimath as sm
import matplotlib.pyplot as plt
import json
import yaml
import sys
import os
# Make sure that caffe is on the python path:
configStream = open("FluffyHaiiro.yaml", "r")
config = yaml.load(configStream)
caffe_root = config.get(':caffe_root_path')
sys.path.insert(0, caffe_root +... | ort caffe
plt.rcParams['figure.figsize'] = (10, 10)
plt.rcParams[' | image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
if not os.path.isfile(caffe_root + '/models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel'):
#print("Downloading pre-trained CaffeNet model...")
os.system('python ../scripts/download_model_binary.py ../models/bvlc_reference_caf... |
jorisvandenbossche/pandas | pandas/tests/io/json/test_json_table_schema.py | Python | bsd-3-clause | 28,054 | 0.000857 | """Tests for Table Schema integration."""
from collections import OrderedDict
import json
import numpy as np
import pytest
from pandas.core.dtypes.dtypes import (
CategoricalDtype,
DatetimeTZDtype,
PeriodDtype,
)
import pandas as pd
from pandas import DataFrame
import pandas._testing as tm
from pandas.i... | self.df.copy()
idx = pd.MultiIndex.from_product([("a", "b"), (1, 2)])
df.index = idx
result = build_table_schema(df, version=False)
expected = {
"fields": [
{"name": "level_0", | "type": "string"},
{"name": "level_1", "type": "integer"},
{"name": "A", "type": "integer"},
{"name": "B", "type": "string"},
{"name": "C", "type": "datetime"},
{"name": "D", "type": "duration"},
],
"primaryKey": ["... |
kevinarpe/kevinarpe-rambutan3 | rambutan3/check_args/set/RSetMatcher.py | Python | gpl-3.0 | 347 | 0 | from rambutan3 import RArgs
fr | om rambutan3.check_a | rgs.base.RInstanceMatcher import RInstanceMatcher
from rambutan3.check_args.set.RSetEnum import RSetEnum
class RSetMatcher(RInstanceMatcher):
def __init__(self, set_enum: RSetEnum):
RArgs.check_is_instance(set_enum, RSetEnum, "set_enum")
super().__init__(*(set_enum.value))
|
cpacia/Subspace | subspace/pyelliptic/hash.py | Python | mit | 1,739 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 Yann GUIBET <yannguibet@gmail.com>
# See LICENSE for details.
from .openssl import OpenSSL
# For python3
| def _equals_bytes(a, | b):
if len(a) != len(b):
return False
result = 0
for x, y in zip(a, b):
result |= x ^ y
return result == 0
def _equals_str(a, b):
if len(a) != len(b):
return False
result = 0
for x, y in zip(a, b):
result |= ord(x) ^ ord(y)
return result == 0
def equal... |
jawilson/home-assistant | tests/components/fronius/test_sensor.py | Python | apache-2.0 | 29,800 | 0.004832 | """Tests for the Fronius sensor platform."""
from homeassistant.components.fronius.const import DOMAIN
from homeassistant.components.fronius.coordinator import (
FroniusInverterUpdateCoordinator,
FroniusMeterUpdateCoordinator,
FroniusPowerFlowUpdateCoordinator,
)
from homeassistant.components.sensor import ... | pected_state):
state = hass.states.get(entity_id)
assert state
assert state.state == str(expected_state)
mock_responses(aioclient_mock)
await setup_fronius_integration(hass)
assert len(hass.states.async_all(domain_filter=SENSOR_DOMAIN)) == 25
# ignored constant entities:
# ... | tes are rounded to 4 decimals
assert_state(
"sensor.cash_factor_fronius_logger_info_0_http_fronius",
0.078,
)
assert_state(
"sensor.co2_factor_fronius_logger_info_0_http_fronius",
0.53,
)
assert_state(
"sensor.delivery_factor_fronius_logger_info_0_http_fronius... |
planrich/pypy-simd-benchmark | user/add.py | Python | gpl-3.0 | 458 | 0.019651 | im | port time
import sys
import array
# show start
def py_add(A,B,size):
i = 0
while i < size:
A[i] = A[i] + B[i]
i += 1
# show stop
if __name__ == '__main__':
s = int(sys.argv[1])
j = int(sys.argv[2])
a = array.array('d', [0.0]*s)
b = array.array('d', [1.0]*s)
for i in range(... | e.time()-t)
|
IPVL/Tanvin-PythonWorks | pythonOOP/codes/duck_test.py | Python | mit | 722 | 0.01662 | #! /usr/bin/env python
class Duck:
"""
this class implies a new way to express polymorphism using duck typing.
This class has 2 functions: quack() and fly() consisting no parameter.
"""
def quack(self):
print("Quack, quack!");
def fly(self):
print("Flap, Flap!");
... | rint("I'm Quackin'!");
def fly(self):
print("I'm Flyin'!");
def in_the_forest(mallard):
""" This functi | on is used for express polymorphism behavior except inheritance """
mallard.quack()
mallard.fly()
duck = Duck()
person = Person()
# passing object to in_the_forest() function
in_the_forest(Duck())
in_the_forest(Person())
|
D4rkC00d3r/locatebssid | locatebssid.py | Python | gpl-3.0 | 1,239 | 0.002421 | im | port urllib.request
import json
import webbrowser
___author___ = 'D4rkC00d3r'
bssid = input('Enter a BSSID: ') # Mac address of AP you want to locate
api_uri = 'https://api.mylnikov.org/geolocation/wifi?v=1.1&data=open&bssid=' # Api endpoint for database.
map_url = 'http://find-wifi.mylnikov.or | g/#' # Map provider for plotting results.
# Example of a MAC address; 00:0C:42:1F:65:E9 this can be used for testing.
def mappin():
while True:
confirm = input('Show on map? (Y)es or (N)o: ')
if 'Y' in confirm:
webbrowser.open(map_url + bssid)
return
else:
... |
everaldo/example-code | 19-dyn-attr-prop/oscon/test_schedule2.py | Python | mit | 1,753 | 0 | import shelve
import pytest
import schedule2 as schedule
@pytest.yield_ | fixture
def db():
with shelve.open(schedule.DB_NAME) as the_db:
if schedule.CONFERENCE not in the_db:
schedule.load_db(the_db)
yield the_db
def test_record_attr_access():
rec = schedule.Record(spam=99, eggs=12)
assert rec.spam == 99
assert rec.eggs == 12
def test_record_r... | 2)
assert 'DbRecord object at 0x' in repr(rec)
rec2 = schedule.DbRecord(serial=13)
assert repr(rec2) == "<DbRecord serial=13>"
def test_conference_record(db):
assert schedule.CONFERENCE in db
def test_speaker_record(db):
speaker = db['speaker.3471']
assert speaker.name == 'Anna Martelli Rave... |
henningpohl/WeMo | wemo.py | Python | mit | 327 | 0.015291 | from ctypes import *
| wemoDll | = cdll.LoadLibrary("WeMo.dll")
def turn_on():
wemoDll.turnOn()
def turn_off():
wemoDll.turnOff()
def get_state():
return wemoDll.getState() > 0
if __name__ == '__main__':
import time
turn_on()
print get_state()
time.sleep(3.0)
turn_off()
print get_state()
|
valhallasw/pywikibot-core | pywikibot/backports.py | Python | mit | 6,204 | 0.000322 | # -*- coding: utf-8 -*-
"""
This module contains backports to support older Python versions.
They contain the backported code originally developed for Python. It is
therefore distributed under the PSF license, as follows:
PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
--------------------------------------------
1. Th... | nings integration
_warnings_showwarning = None
class NullHandler(lo | gging.Handler):
"""
This handler does nothing.
It's intended to be used to avoid the "No handlers could be found for
logger XXX" one-off warning. This is important for library code, which
may contain code to log events. If a user of the library does not configure
logging, the one-off warning m... |
anokata/pythonPetProjects | var_scripts/sdl_test.py | Python | mit | 1,486 | 0.003365 | import sys
import sdl2.ext
def run():
resources = sdl2.ext.Resources(__file__, "platformer")
sdl2.ext.init()
window = sdl2.ext.Window("SRG", size=(200, 200))
window.show()
factory = sdl2.ext.SpriteFactory(sdl2.ext.SOFTWARE)
sprite = factory.from_image(resources.get_path("sky0.png"))
s2 = sp... | (2, 2, 10, 10))
s2r = sdl2.ext.Renderer(s2)
tfactory = sdl2.ext.SpriteFactory(sdl2.ext.TEXTURE, renderer=s2r)
texture = tfactory.from_image(resources.get_path("sky0.png"))
#s2r.copy(texture)
spriterenderer = factory.create_sprite_render_system(window)
running = True
i = 1000
fps ... | se
break
if event.type == sdl2.SDL_KEYDOWN:
key = event.key.keysym.sym
if key == 27:
running = False
break
if event.key.keysym.sym == sdl2.SDLK_UP:
print(key, sdl2.SDLK_q)
i -=... |
trychameleon/snippet.js | examples/chameleon-python.py | Python | mit | 415 | 0.031325 | {% if current_user %}<script>
// Add the snippet here with account id
// Assuming your page has loaded the current user as the object current_user
chmln.identify({
uid: | '{{ cur | rent_user.id }}',
created: '{{ current_user.created_at }}',
email: '{{ current_user.email }}',
plan: '{{ current_user.account.plan_name }}',
spend: '{{ current_user.account.plan_cost }}'
});
</script>{% endif %} |
chris-wood/onpath-NFD | docs/conf.py | Python | gpl-3.0 | 9,075 | 0.00595 | # -*- coding: utf-8 -*-
#
# NFD - Named Data Networking Forwarding Daemon documentation build configuration file, created by
# sphinx-quickstart on Sun Apr 6 19:58:22 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are prese... | _theme = 'named_data_theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available fo | r each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
html_theme_path = ['./']
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for ... |
quake0day/oj | ttt.py | Python | mit | 123 | 0.00813 | prices = [2, 1, 2, 1, 2, 1]
total = 0
for | i in xrange(1, len(pr | ices), 2):
total += prices[i] - prices[i-1]
print total |
google-research/disentanglement_lib | disentanglement_lib/evaluation/abstract_reasoning/relational_layers_test.py | Python | apache-2.0 | 4,868 | 0.003698 | # coding=utf-8
# Copyright 2018 The DisentanglementLib 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
#
# Un... | pe((4, 3))
# Compute the correct solutions.
shouldbe = np.matmul(input_tensor, kernel)
# Compute the solution based on the layer.
layer = relational_layers.MultiDimBatchApply(
tf.keras.layers.Lambda(lambda x: tf.matmul(x, tf.constant(kernel))),
num_dims_to_keep=1)
result = se | lf.evaluate(layer(tf.constant(input_tensor)))
# Check that they are the same.
self.assertAllClose(shouldbe, result)
if __name__ == '__main__':
tf.test.main()
|
MattJDavidson/python-adventofcode | advent/problem_03.py | Python | bsd-2-clause | 3,424 | 0.000292 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""--- Day 3: Perfectly Spherical Houses in a Vacuum ---
Santa is delivering presents to an infinite two-dimensional grid of houses.
He begins by delivering a present to the house at his starting location, and
then an elf at the North Pole calls him via radio and tells hi... | 0),
'v': (0, 1),
'>': (1, 0),
}
return (point[0]+moves.get(move, (0, 0))[0],
point[1]+moves.get(move, (0, 0))[1])
def map_single_delivery(text):
point = (0, 0)
points = set({point})
for move in text:
point = update_point(move, point)
points.add(point)
... |
len(map_multiple_deliveries(text))
def split_directions(directions):
lists = ('', '')
try:
lists = directions[0::2], directions[1::2]
except IndexError:
pass
return lists
def map_multiple_deliveries(text):
directions = split_directions(text)
points = map_single_deliv... |
absalon-james/graphite-api | graphite_api/utils.py | Python | apache-2.0 | 2,513 | 0.000398 | """Copyright 2008 Orbitz WorldWide
License | d 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,
WI... |
swegener/gruvi | tests/test_poll.py | Python | mit | 8,350 | 0.004192 | #
# This file is part of Gruvi. Gruvi is free software available under the
# terms of the MIT license. See the file "LICENSE" that was provided
# together with this source file for the licensing terms.
#
# Copyright (c) 2012-2014 the Gruvi authors. See the file "AUTHORS" for a
# complete list.
from __future__ import a... | s1, s2 = socketpair()
fd = s2.fileno()
handle = poll.add_callback(fd, WRITABLE, callback)
self.assertIsNotNone(handle)
called.wait(0.1)
self.assertEqual(cba | rgs, [(fd, WRITABLE)])
del cbargs[:]; called.clear()
poll.update_callback(fd, handle, READABLE|WRITABLE)
s1.send(b'x')
called.wait(0.1)
self.assertEqual(cbargs, [(fd, READABLE|WRITABLE)])
del cbargs[:]; called.clear()
poll.close()
s1.close(); s2.close()
... |
QuLogic/burnman | examples/example_composition.py | Python | gpl-2.0 | 6,658 | 0.016822 | # BurnMan - a lower mantle toolkit
# Copyright (C) 2012, 2013, Heister, T., Unterborn, C., Rose, I. and Cottaar, S.
# Released under GPL v2 or later.
"""
example_composition
-------------------
This example shows how to create different minerals, how to compute seismic
velocities, and how to compare them to a se... | te
rock = burnman.Composite([0.8, 0.2], phases=[preset_solidsolution, minerals.SLB_201 | 1.periclase()])
#Example 4: Defining your own solid solution
if False:
# Define a new SolidSolution with mg and fe perovskite endmembers
new_solidsolution = burnman.SolidSolution([[minerals.SLB_2011.mg_perovskite()],
[minerals.SLB_2011.fe_perovskite()]... |
jerodg/hackerrank-python | python/02.Strings/10.AlphabetRangoli/template.py | Python | mit | 118 | 0.016949 | def print_rangoli(size | ):
# your code goes here
if __name__ == '__main__':
| n = int(input())
print_rangoli(n)
|
TheWylieStCoyote/gnuradio | gr-digital/python/digital/__init__.py | Python | gpl-3.0 | 1,013 | 0 | # Copyright 2011-2013 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
'''
Blocks and utilities for digital modulation and demodulation.
'''
from __future__ import absolute_import
from __future__ import un | icode_literals
# The presence of | this file turns this directory into a Python package
import os
try:
from .digital_swig import *
except ImportError:
dirname, filename = os.path.split(os.path.abspath(__file__))
__path__.append(os.path.join(dirname, "..", "..", "swig"))
from .digital_swig import *
from .psk import *
from .qam import ... |
ndt93/tetris | scripts/agent3.py | Python | mit | 5,234 | 0 | import random
from datetime import datetime
from multiprocessing import Pool
import numpy as np
from scipy.optimize import minimize
def worker_func(args):
self = args[0]
m = args[1]
k = args[2]
r = args[3]
return (self.eval_func(m, k, r) -
self.eval_func(m, k, self.rt) -
... | ': self.max_iter, 'disp': True},
| callback=self.callback)
return res.x
|
stlemme/python-dokuwiki-export | entities/application.py | Python | mit | 202 | 0.034653 |
from . imp | ort NamedEntity
class Application(NamedEntity):
def __init__(self, name, provider):
NamedEntity.__init__(self, name)
| self.provider = provider
def get_descendants(self):
return []
|
jjas0nn/solvem | tensorflow/lib/python2.7/site-packages/tensorflow/contrib/slim/python/slim/learning_test.py | Python | mit | 34,627 | 0.008981 | # Copyright 2016 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... | = (gradient, variable)
gradients_to_variables = learning.clip_gradient_norms(
[gradients_to_variables], self._max_norm)[0]
# Ensure the built IndexedSlice has the right form.
self.assertEqual(gradient | s_to_variables[1], variable)
self.assertEqual(gradients_to_variables[0].indices, indices)
self.assertEqual(gradients_to_variables[0].dense_shape, dense_shape)
with session.Session() as sess:
actual_gradient = sess.run(gradients_to_variables[0].values)
np_testing.assert_almost_equal(actual_gradien... |
wevote/WeVoteServer | follow/models.py | Python | mit | 78,451 | 0.004015 | # follow/models.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from datetime import datetime, timedelta
from django.db import models
from election.models import ElectionManager
from exception.models import handle_exception, handle_record_found_more_than_one_exception,\
handle_record_not_found_exc... | paignx_on_stage_id,
'follow_campaignx': follow_campaignx_on_stage,
}
return results
def retrieve_follow_campaignx(self, follow_campaignx_id, voter_we_vote_id, issue_id, issue_we_vote_id):
"""
follow_campaignx_id is the identifier for records stored in this table... | ption_multiple_object_returned = False
follow_campaignx_on_stage = FollowIssue()
follow_campaignx_on_stage_id = 0
try:
if positive_value_exists(follow_campaignx_id):
follow_campaignx_on_stage = FollowIssue.objects.get(id=follow_campaignx_id)
follow_ca... |
aselle/tensorflow | tensorflow/python/estimator/keras.py | Python | apache-2.0 | 21,876 | 0.006491 | # Copyright 2015 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... | r_io) + 1)]
for key in estimator_io:
if key not in keras_io_names:
raise ValueError(
'Cannot find %s with name "%s" in Keras Model. '
'It needs to match one '
'of the following: %s' % ('input' if is_input else 'out | put', key,
', '.join(keras_io_names)))
tensors = [_convert_tensor(estimator_io[io_name])
for io_name in keras_io_names]
return tensors
else:
# Plain array.
return _convert_tensor(estimator_io)
def _in_place_subclassed_model_reset(model):
"""Subs... |
weaver-viii/h2o-3 | h2o-py/tests/testdir_misc/pyunit_assign.py | Python | apache-2.0 | 567 | 0.012346 | import sys
sys.path.insert(1, "../../")
import h2o
def pyunit_assign(ip,port):
pros = h2o.import_file(h2o.locate("smalldata/prostate/prostate | .csv"))
pq = pros.quantile()
PSA_outliers = pros[pros["PSA"] <= pq[1,1] or pros["PSA"] >= pq[1,9]]
PSA_outliers = h2o.assign(PSA_outliers, "PSA.outliers")
pros.head(show=True)
PSA_outliers.head(show=True)
assert PSA_outliers._id == "PSA.outliers", "Expected frame id to be PSA.outliers, but got ... |
h2o.run_test(sys.argv, pyunit_assign)
|
stack-of-tasks/rbdlpy | tutorial/lib/python2.7/site-packages/OpenGL/raw/GL/ATI/pixel_format_float.py | Python | lgpl-3.0 | 648 | 0.023148 | '''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.GL import _types as _cs
# End users want this...
from OpenGL.raw.G | L._types import *
from OpenGL.raw.GL import _errors
from OpenGL.constant import Constant as _C
import ctypes
_EXTENSION_NAME = 'GL_ATI_pixel_format_float'
def _f( function ):
return _p.createFunction( function,_p.PLATFORM.GL,'GL_ATI_pixel_format_float',error_c | hecker=_errors._error_checker)
GL_COLOR_CLEAR_UNCLAMPED_VALUE_ATI=_C('GL_COLOR_CLEAR_UNCLAMPED_VALUE_ATI',0x8835)
GL_RGBA_FLOAT_MODE_ATI=_C('GL_RGBA_FLOAT_MODE_ATI',0x8820)
|
DepthDeluxe/ansible | lib/ansible/modules/windows/win_scheduled_task.py | Python | gpl-3.0 | 3,418 | 0.000585 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# 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.
#
... | orted_by': 'community'}
DOCUMENTATION = r'''
---
module: win_scheduled_task
author: "Peter Mounce"
version_added: "2.0"
short_description: Manage scheduled tasks
description:
- Manage scheduled tasks
notes:
- This module requires Windows Server 2012 or later.
options:
name:
description:
- Name of ... | n:
- Enable/disable the task
choices:
- yes
- no
default: yes
state:
description:
- State that the task should become
required: true
choices:
- present
- absent
user:
description:
- User to run scheduled task as
executable:
description:
-... |
william-richard/moto | tests/test_swf/models/test_timeout.py | Python | apache-2.0 | 501 | 0 | from freezegun import freeze_time
import sure # noqa
from moto.swf.models import Timeout
from ..utils import make_workflow_execution
def test_timeout_creation():
wfe = make_workflow_execution()
# epoch 1420113600 == "2015-01-01 13:00:00"
| timeout = Timeout(wfe, 1420117200, "START_TO_CLOSE")
with freeze_time("2015-01-01 12:00:00"):
timeout.reached.should.be.falsy
with freeze_time("2015-01-01 13:00:00"):
timeout.reached.should.be.truthy
| |
xmendez/wfuzz | src/wfuzz/filters/simplefilter.py | Python | gpl-2.0 | 3,567 | 0.00028 | from ..exception import FuzzExceptBadOptions
import re
import collections
from ..facade import BASELINE_CODE
class FuzzResSimpleFilter:
def __init__(self, ffilter=None):
self.hideparams = dict(
regex_show=None,
codes_show=None,
codes=[],
words=[],
... | LINE_CODE in self.hideparams["words"]:
self.hideparams["words"].append(res.words)
if BASELINE_CODE in self.hideparams["chars"]:
self.hideparams["chars"].append(res.chars)
def is_visible(self, res):
if self.hideparams["codes_show"] is None:
cond1 = True
el... | not self.hideparams["codes_show"]
if self.hideparams["regex_show"] is None:
cond2 = True
else:
cond2 = not self.hideparams["regex_show"]
if (
res.code in self.hideparams["codes"]
or res.lines in self.hideparams["lines"]
or res.words ... |
isterin/flurry | examples/python/load_tests.py | Python | apache-2.0 | 252 | 0.003968 | from mult | iprocessing import Pool |
from client import FlurryClient, get_id
import time
p = Pool(10)
p.map_async(get_id, [('localhost', 9090, 10000)])
# p.map_async(get_id, [('localhost', 9091, 10000)] * 2)
# p.join()
p.close()
p.join()
# time.sleep(2) |
neilhan/tensorflow | tensorflow/python/framework/ops.py | Python | apache-2.0 | 150,185 | 0.005413 | # Copyright 2015 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... | type implementing the tensor interface.
Raises:
TypeError: If `tensor_type` does not implement the tensor | interface.
"""
try:
if not isinstance(tensor_type.name, property):
raise TypeError("Type %s does not define a `name` property")
except AttributeError:
raise TypeError("Type %s does not define a `name` property")
try:
if not isinstance(tensor_type.dtype, property):
raise TypeError("Type %... |
takeit/web-publisher | docs/_extensions/sensio/sphinx/bestpractice.py | Python | agpl-3.0 | 1,458 | 0.006173 | from docutils.parsers.rst import Directive, directives
from docutils import nodes
from docutils.parsers.rst.directives.admonitions import BaseAdmonition
from sphinx.util import compat |
compat.make_admonition = BaseAdmonition
from sphinx import addnodes
from sphinx.locale import _
class bestpractice(nodes.Admonition, nodes.Element):
pass
class BestPractice(Directive):
has_content = True
required_arguments = 0
optional_arguments = 1
final_argument_whitespace = Tr | ue
option_spec = {}
def run(self):
ret = make_admonition(
bestpractice, self.name, [_('Best Practice')], self.options,
self.content, self.lineno, self.content_offset, self.block_text,
self.state, self.state_machine)
if self.arguments:
argnodes, ms... |
scivision/raspberrypi_raw_camera | pibayer/io.py | Python | mit | 1,418 | 0 | from pathlib import Path
import xarray
KEY = 'imgs' # handle to write inside the output | file
CLVL = 1 # ZIP compression level
def writeframes(outfn: Path, img: xarray.DataArray):
"""writes image stack to disk"""
assert img.ndim == 3
if outfn is None:
return
outfn = Path(outfn).expanduser()
print('writing', outfn)
if outfn.suffix == '.nc':
# chunksizes made o... | etcher32': True,
'chunksizes': (1, img.shape[1], img.shape[2])}}
img.to_netcdf(outfn, mode='w', encoding=enc)
elif outfn.suffix == '.h5': # HDF5
import h5py
with h5py.File(outfn, 'w') as f:
f.create_dataset(KEY,
data=img.values,
... |
sanguinariojoe/FreeCAD | src/Mod/Path/PathTests/TestPathTool.py | Python | lgpl-2.1 | 4,116 | 0.001944 | # -*- coding: utf-8 -*-
# ***************************************************************************
# * Copyright (c) 2017 sliptonic <shopinthewoods@gmail.com> *
# * *
# * This program is free software; you can redistribute it a... | 0 = self.test00()
t1 = Path.Tool(t0.templateAttrs())
self.assertEqual(t0.Name, t1.Name)
self.assertEqual(t0.ToolType, t1.ToolType)
sel | f.assertEqual(t0.Material, t1.Material)
self.assertEqual(t0.Diameter, t1.Diameter)
self.assertEqual(t0.LengthOffset, t1.LengthOffset)
self.assertEqual(t0.FlatRadius, t1.FlatRadius)
self.assertEqual(t0.CornerRadius, t1.CornerRadius)
self.assertEqual(t0.CuttingEdgeAngle, t1.Cutting... |
goal/uwsgi | tests/websockets_chat_async.py | Python | gpl-2.0 | 3,284 | 0.000914 | #!./uwsgi --http-socket :9090 --async 100 ...
# same chat example but using uwsgi async api
# for pypy + continulets just run:
# uwsgi --http-socket :9090 --pypy-home /opt/pypy --pypy-wsgi-file tests/websockets_chat_async.py --pypy-eval "uwsgi_pypy_setup_continulets()" --async 100
import uwsgi
import time
import redis
... | tml')])
output = """
<html>
<head>
<script language="Javascript">
var s = new WebSocket("%s://%s/foobar/");
s.onopen = function() {
alert("connected !!!");
s.send("ciao");
};
s.onmessage = function(e) {
| var bb = document.getElementById('blackboard')
var html = bb.innerHTML;
bb.innerHTML = html + '<br/>' + e.data;
};
s.onerror = function(e) {
alert(e);
}
s.onclose = function(e) {
alert... |
jclgoodwin/bustimes.org.uk | busstops/management/commands/import_localities.py | Python | mpl-2.0 | 2,629 | 0.001902 | """
Usage:
im | port_localities < Localities.csv
"""
from django.contrib.gis.geos import GEOSGeometry
from django.util | s.text import slugify
from ..import_from_csv import ImportFromCSVCommand
from ...utils import parse_nptg_datetime
from ...models import Locality
class Command(ImportFromCSVCommand):
"""
Imports localities from the NPTG
"""
def handle_rows(self, rows):
existing_localities = Locality.objects.def... |
annoviko/pyclustering | pyclustering/core/mbsas_wrapper.py | Python | gpl-3.0 | 842 | 0.015439 | """!
@brief CCORE Wrapper for MBSAS algorithm.
@authors Andrei Novikov (pyclustering@yandex.ru)
@date 2014-2020
@copyright BSD-3-Clause
"""
from ctypes import c_double, c_size_t, POINTER;
from pyclustering.core.wrapper i | mport ccore_library;
from pyclustering.core.pyclustering_package import pyclustering_package, package_extractor, package_builder;
def mbsas(sample, amount, threshold, metric_pointer):
pointer_data = package_builder(sample, c_double).create();
ccore | = ccore_library.get();
ccore.mbsas_algorithm.restype = POINTER(pyclustering_package);
package = ccore.mbsas_algorithm(pointer_data, c_size_t(amount), c_double(threshold), metric_pointer);
result = package_extractor(package).extract();
ccore.free_pyclustering_package(package);
return resu... |
hasgeek/funnel | migrations/versions/3a6b2ab00e3e_session_proposal_one.py | Python | agpl-3.0 | 441 | 0.004535 | """Make session:proposal 1:1.
Revision ID: 3a6b2ab00e3e
| Revises: 4dbf686f4380
Create Date: 2013-11-09 13:51:58.343243
"""
# revision identifiers, used by Alembic.
revision = '3a6b2ab00e3e'
down_revision = '4dbf686f4380'
from alembic import op
def upgrade():
op.create_unique_constraint('session_proposal_id_key', 'session', ['propo | sal_id'])
def downgrade():
op.drop_constraint('session_proposal_id_key', 'session', 'unique')
|
google/transitfeed | transitfeed/farerule.py | Python | apache-2.0 | 2,778 | 0.009359 | #!/usr/bin/python2.5
# Copyright (C) 2007 Google Inc.
#
# License | d 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 s... |
stweil/ocropy | OLD/lineproc.py | Python | apache-2.0 | 6,891 | 0.026411 | ################################################################
### functions specific to text line processing
### (text line segmentation is in lineseg)
################################################################
from scipy import stats
from scipy.ndimage import interpolation,morphology,filters
from pylab impor... | ttoms[i]-tops[i]
y0 = int(maximum(0,bottoms[i]-r*d))
mask[y0:bottoms[i],i] = 1
return mask
@checks(DARKLINE)
def latin_filter(line,scale=1.0,r=1.5,debug=0):
"""Filter out noise from a text line in Latin alphabets."""
bin = (line>0.5*amax(line))
mask = latin_mask(bin,scale=scale,r=r,debu... | return line*mask
|
us-ignite/us_ignite | us_ignite/blog/urls.py | Python | bsd-3-clause | 266 | 0 | from django.conf.urls import patterns, url
|
urlpatterns = patterns(
'us_ignite.blog.views',
url(r'^$', 'post_list', name='blog_post_list'),
url(r'^(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<slug>[-\w]+)/$',
'post_detail', n | ame='blog_post_detail'),
)
|
aplicatii-romanesti/allinclusive-kodi-pi | .kodi/addons/plugin.video.familyfunflix/downloader.py | Python | apache-2.0 | 588 | 0.027211 | import xbmcgui
import urllib
def download(url, dest, dp = None):
if not dp:
dp = xbmcgui.DialogProgress()
dp.cr | eate("XBMCHUB...","Downloading & Copying File",' ', ' ')
dp.update(0)
urllib.urlretrieve(url,dest,lambda nb, bs, fs, url=url: _ | pbhook(nb,bs,fs,url,dp))
def _pbhook(numblocks, blocksize, filesize, url, dp):
try:
percent = min((numblocks*blocksize*100)/filesize, 100)
dp.update(percent)
except:
percent = 100
dp.update(percent)
if dp.iscanceled():
raise Exception("Canceled")
dp.close()... |
kelvinongtoronto/SecureCRT | shintdesc_legacy.py | Python | artistic-2.0 | 1,392 | 0.03592 | # $language = "python"
# $interface = "1.0"
# for GCCLABVM1,GCCLABVM2
import os
import csv
def main():
crt.Screen.Synchronous = True
# Create an Excel compatible spreadsheet
filename = crt.Dialog.Prompt("Enter file name to write to: ", "Show Interface Description", "intdesc.csv", False)
fileobj = open(filename... | d at the end of each line, or the shell
# prompt that indicates we're done.
result = crt.Screen.WaitForStrings( waitStrs )
# If see a prompt, we're done
if result == 2:
break
# Fetch current row and read the characters from the screen
screenrow = crt.Screen.CurrentRow - 1
readline = crt.Screen.Ge... | strip()]
worksheet.writerow(items)
fileobj.close()
#crt.Dialog.MessageBox("Done! Your file is saved in "+filename)
crt.Screen.Synchronous = False
main()
|
ask/carrot | carrot/messaging.py | Python | bsd-3-clause | 37,722 | 0.000265 | """
Sending/Receiving Messages.
"""
from itertools import count
from carrot.utils import gen_unique_id
import warnings
from carrot import serialization
class Consumer(object):
"""Message consumer.
:param connection: see :attr:`connection`.
:param queue: see :attr:`queue`.
:param exchange: see :att... | match) and
``"any"`` implies ``OR`` (at least one pair must match).
Use the :attr:`routing_key`` is used to specify the arguments,
the same when sending messages.
This description of AMQP exchange types was shamelessly stolen
from the blog post ` | AMQP in 10 minutes: Part 4`_ by
Rajith Attapattu. Recommended reading.
.. _`AMQP in 10 minutes: Part 4`:
http://bit.ly/amqp-exchange-types
.. attribute:: callbacks
List of registered callbacks to trigger when a message is received
by :meth:`wait`, :meth:`pr... |
Haravan/haravan_python_api | haravan/resources/shipping_line.py | Python | mit | 83 | 0 | from ..base import HaravanResource
class ShippingLi | ne(Har | avanResource):
pass
|
svperbeast/plain_data_companion | src/templates/renderer_result.py | Python | mit | 320 | 0.003125 | """
| RendererResult
"""
class RendererResult(object):
def __init__(self):
self.string_stream = ''
def append(self, s):
self.string_stream += s
def pop_back(self, index=1):
self.string_stream = self.string_stream[:-index]
def get_string(self):
return self.s | tring_stream
|
AllanNozomu/tecsaladeaula | core/migrations/0029_auto__add_field_courseprofessor_is_course_author.py | Python | agpl-3.0 | 13,255 | 0.007922 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'CourseProfessor.is_course_author'
db.add_column(u'core_co... | unique': 'True', 'null': 'True', 'to': u"orm['core.Class']"}),
'home_position': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'home_published': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'home_thumbnail': ('django.db.models.... | 'intro_video': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['core.Video']", 'null': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'professors': ('django.db.models.fields.related.ManyToManyField',... |
d2emon/generator-pack | src/fixtures/tools/outfit/scarf.py | Python | gpl-3.0 | 152 | 0.006579 | # scarf1{background-image: url('https://rollforfantasy.com/ima | ges/clothing/nmale/scarf1.png');}
scarf = ["scarf{}.png". | format(i) for i in range(1, 31)]
|
koebbe/homeworks | visit/migrations/0074_auto_20150826_2122.py | Python | mit | 670 | 0.002985 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migratio | ns.Migration):
dependencies = [
('visit', '0073_visit_student_absent_reason'),
]
| operations = [
migrations.AlterField(
model_name='visit',
name='caregiver',
field=models.ForeignKey(related_name='visits', blank=True, to='visit.Caregiver', null=True),
),
migrations.AlterField(
model_name='visit',
name='student',
... |
sassoftware/catalog-service | catalogService/libs/viclient_vendor/ZSI/generate/commands.py | Python | apache-2.0 | 19,840 | 0.009224 | ############################################################################
# Joshua Boverhof<JRBoverhof@lbl.gov>, LBNL
# Monte Goode <MMGoode@lbl.gov>, LBNL
# See Copyright for copyright notice!
############################################################################
import exceptions, sys, optparse, os, warning... | e_true", dest="address", default=False,
# help="ws-addressing support, must include WS-Addressing schema.")
# op.add_option("-d", "--debug",
# action="callback", callback=SetDebugCallback,
# help="debug output")
# op.add_option("-t", "--types",
# ... | t="types", default=None, type="string",
# help="Write generated files to OUTPUT_DIR")
# op.add_option("-o", "--output-dir",
# action="store", dest="output_dir", default=".", type="string",
# help="file to load types from")
# op.add_option("-s", "--simple-naming",... |
cmuphyscomp/physcomp-examples | support/rpi/Adafruit-Raspberry-Pi-Python-Code-master/Adafruit_ADXL345/Adafruit_ADXL345.py | Python | bsd-3-clause | 3,978 | 0.008296 | #!/usr/bin/python
# Python library for ADXL345 accelerometer.
# Copyright 2013 Adafruit Industries
# 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 li... | self.accel = Adafruit_I2C(self.ADXL345_ADDRESS, busnum, debug)
if self.accel.readU8(self.ADXL345_REG_DEVID) == | 0xE5:
# Enable the accelerometer
self.accel.write8(self.ADXL345_REG_POWER_CTL, 0x08)
def setRange(self, range):
# Read the data format register to preserve bits. Update the data
# rate, make sure that the FULL-RES bit is enabled for range scaling
format = ((self.a... |
noorelden/QuickBooking | QuickBooking/migrations/0002_auto_20150623_1913.py | Python | gpl-2.0 | 450 | 0.002222 | # -*- coding: utf-8 -*-
from __future__ imp | ort unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('QuickBooking', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='timing',
name='id',
field=models.AutoField(verb... | ),
]
|
GNOME/orca | src/orca/orca_gui_navlist.py | Python | lgpl-2.1 | 6,822 | 0.001906 | # Orca
#
# Copyright 2012 Igalia, S.L.
#
# Author: Joanmarie Diggs <jdiggs@igalia.com>
#
# This library 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 2.1 of the License, or (at your o... | nit__(self, title, columnHeaders, rows, selectedRow):
self._tree = None
self._activateButton = None
self._gui = self._createNavListDialog(columnHeaders, rows, selec | tedRow)
self._gui.set_title(title)
self._gui.set_modal(True)
self._gui.set_keep_above(True)
self._gui.set_focus_on_map(True)
self._gui.set_accept_focus(True)
self._script = orca_state.activeScript
self._document = None
def _createNavListDialog(self, columnHea... |
yznpku/HackerRank | solution/practice/data-structures/arrays/array-left-rotation/solution.py | Python | mit | 177 | 0.00565 | # We slice the array in two parts at index d, then print them
# in reverse order.
n, d = | map(int, input().split())
A = list(map(int, input().split()))
| print(*(A[d:] + A[:d]))
|
Tibo-R/jamplaygen | fabfile.py | Python | lgpl-3.0 | 2,830 | 0.006007 | """
REQUIREMENTS:
- install pip with distribute (http://packages.python.org/distribute/)
- sudo pip install Fabric
"""
from fabric.api import local
def lang(mode="extract"):
"""
REQUIREMENTS:
- Install before pip with distribute_setup.py (Read the environment setup document)
... | el update -l it_IT -d ./locale -i ./locale/messages.pot --previous --ignore-obsolete")
local("pybabel update -l zh_CN -d ./locale -i ./locale/messages.pot --previous --ignore-obsolete")
local("pybabel update -l id_ID -d ./locale -i ./locale/messages.pot --previous --ignore-obsolete")
local("pyba... | ate -l de_DE -d ./locale -i ./locale/messages.pot --previous --ignore-obsolete")
local("pybabel update -l ru_RU -d ./locale -i ./locale/messages.pot --previous --ignore-obsolete")
local("pybabel update -l pt_BR -d ./locale -i ./locale/messages.pot --previous --ignore-obsolete")
def start(mode="normal")... |
saramic/learning | dojo/adventofcode.com/2021/catchup/mcpower-day19_2.py | Python | unlicense | 4,767 | 0.004615 | import sys; sys.dont_write_bytecode = True; from mcpower_utils import *
def do_case(inp: str, sample=False):
# READ THE PROBLEM FROM TOP TO BOTTOM OK
def sprint(*a, **k): sample and print(*a, **k)
lines: typing.List[str] = inp.splitlines()
paras: typing.List[typing.List[str]] = lmap(str.splitlines, inp... | print(len(points))
# assume scanner 0 is good
FACINGS = [x for i in [-1, 1] for x in [[i, 0, 0], [0, i, 0], [0, 0, i]]]
def cross(a, b):
c = [a[1]*b[2] - a[2]*b[1],
a[2]*b[0] - a[0]*b[2],
a[0]*b[1] - a[1]*b[0]]
return c
def common(a, b):
aset ... | # return b's points, but now relative to a
for facing in FACINGS:
for up in [f for f in FACINGS if all(abs(x) != abs(y) for x, y in zip(f, facing) if x or y)]:
# facing's
right = cross(facing, up)
matrix = [facing, up, right]
... |
ssh0/growing-string | triangular_lattice/moving_string/moving_string_deadlock.py | Python | mit | 5,500 | 0.013057 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# written by Shotaro Fujimoto
# 2016-05-30
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from triangular import LatticeTriangular as LT
from base import Main as base
import numpy as np
import random
from tqdm import tq... | l, sizeset=sizeset, T=T)
# np.savez("2016-06-02.npz", trial=trial, sizeset=sizeset, T=T)
# np.savez("2016-06-03_80.npz", trial=trial, sizeset=sizeset, T=T)
# np.savez("2016-06-03_120.npz", trial=trial, sizeset=sizeset, T=T)
# np.savez("2016-06-07_40.npz", trial=trial, sizeset=sizeset, T=T)
# np.save... | ======================================================================
# プロット準備
# fig, ax = plt.subplots()
# ax.set_title("Deadlock time for the string size N on triangular lattice")
#=0========================================================================
# 普通に表示
# ax.plot(sizeset, T, marke... |
dannygoldstein/sncosmo | sncosmo/tests/test_salt2utils.py | Python | bsd-3-clause | 3,927 | 0.000255 | import os
import pickle
from astropy.extern import six
import numpy as np
from numpy.testing import assert_allclose
from scipy.interpolate import RectBivariateSpline
import sncosmo
from sncosmo.salt2utils import BicubicInterpolator, SALT2ColorLaw
# On Python 2 highest protocol is 2.
# Protocols 0 and 1 don't work o... | "data")
# created by running generate script in `misc` directory
fname_input = os.path.join(datadir, "interpolation_test_input.dat")
fname_evalx = | os.path.join(datadir, "interpolation_test_evalx.dat")
fname_evaly = os.path.join(datadir, "interpolation_test_evaly.dat")
# result file was created by running snfit software Grid2DFunction
fname_result = os.path.join(datadir, "interpolation_test_result.dat")
# load arrays
x, y, z = sncosmo.read_gr... |
rudyryk/python-samples | hello_tornado/hello_feed/core/handlers.py | Python | cc0-1.0 | 240 | 0.004167 | import tornado.gen
from .m | odels import Feed
# Handlers in Tornado like Views in Django
class FeedHandler(tornado.web.RequestHandler):
@tornado.gen.coroutine
| def get(self):
feed = yield Feed.fetch()
self.write(feed)
|
milanlenco/vpp | test/vpp_gre_interface.py | Python | apache-2.0 | 2,595 | 0 |
from vpp_interface import VppInterface
import socket
class VppGreInterface(VppInterface):
"""
VPP GRE interface
"""
def __init__(self, test, src_ip, dst_ip, outer_fib_id=0, is_teb=0):
""" Create VPP loopback interface """
self._sw_if_index = 0
super(VppGreInterface, self).__i... | VppGre6Interface, self).__init__(test)
self._test = test
self.t_src = src_ip
self.t_dst = dst_ | ip
self.t_outer_fib = outer_fib_id
self.t_is_teb = is_teb
def add_vpp_config(self):
s = socket.inet_pton(socket.AF_INET6, self.t_src)
d = socket.inet_pton(socket.AF_INET6, self.t_dst)
r = self.test.vapi.gre_tunnel_add_del(s, d,
o... |
glormph/msstitch | src/app/readers/fasta.py | Python | mit | 4,853 | 0.002885 | from Bio import SeqIO
def get_proteins_for_db(fastafn, fastadelim, genefield):
"""Runs through fasta file and returns proteins accession nrs, sequences
and evidence levels for storage in lookup DB. Duplicate accessions in
fasta are accepted and removed by keeping only the last one.
"""
records = {... | d.id
if dmod is not None:
test_name = record.id.replace(dmod, '')
if test_name.split('|')[0] in ['sp', 'tr']:
return 'swiss'
elif test_name[:3] == 'ENS':
return 'ensembl'
else:
return False
def get_decoy_mod_string(protein):
mods = ['tryp_reverse', 'reverse', 'decoy... | if mod in protein:
if protein.endswith('_{}'.format(mod)):
return '_{}'.format(mod)
elif protein.endswith('{}'.format(mod)):
return mod
elif protein.startswith('{}_'.format(mod)):
return '{}_'.format(mod)
elif protein.star... |
ApolloAuto/apollo | modules/tools/ota/create_sec_package.py | Python | apache-2.0 | 1,573 | 0 | #!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo 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... | TIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing per | missions and
# limitations under the License.
###############################################################################
import secure_upgrade_export as sec_api
import os
import sys
sys.path.append('/home/caros/secure_upgrade/python')
root_config_path = "/home/caros/secure_upgrade/config/secure_config.json"
ret ... |
nburn42/tensorflow | tensorflow/python/training/session_manager_test.py | Python | apache-2.0 | 32,764 | 0.009095 | # Copyright 2015 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... | ps.placeholder(dtypes.float32, shape=(3,))
v = variables.Variable(p, name="v")
sm = session_manager.SessionManager(
r | eady_op=variables.report_uninitialized_variables())
sess = sm.prepare_session(
"",
init_op=variables.global_variables_initializer(),
init_feed_dict={p: [1.0, 2.0, 3.0]})
self.assertAllClose([1.0, 2.0, 3.0], sess.run(v))
def testPrepareSessionSucceedsWithInitFn(self):
wit... |
StephanEwen/incubator-flink | flink-python/pyflink/fn_execution/coder_impl_slow.py | Python | apache-2.0 | 28,735 | 0.001183 | ################################################################################
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this... | alue, out_stream: OutputStream):
# encode mask value
self._mask_utils.write_mask(value, 0, out_stream)
| # enc |
5nizza/party-elli | rally_elli_bool.py | Python | mit | 3,337 | 0.002997 | #!/usr/bin/env python3
import logging
import signal
from typing import List
import elli
from LTL_to_atm import translator_via_spot
from config import Z3_PATH
from syntcomp.rally_template import main_template
from syntcomp.task import Task
from syntcomp.task_creator import TaskCreator
from synthesis.z3_via_pipe import ... | pass
if self.timeout:
logging.info('CheckUnrealTask | : setting timeout to %i' % self.timeout)
def signal_handler(sig, _):
if sig == signal.SIGALRM:
raise TimeoutException("CheckUnrealTask: timeout reached")
signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(self.timeout)
solver = Z3I... |
svn2github/pyopt | examples/rosenbrock.py | Python | gpl-3.0 | 2,679 | 0.011945 | #!/usr/bin/env python
'''
Solves Rosenbrock's Unconstrained Problem.
min 100*(x2-x1^2)**2 + (1-x1)^2
s.t.: -10 <= xi <= 10, i = 1,2
f* = 0 , x* = [1, 1]
'''
# =============================================================================
# Standard Python modules
# =================================... | ==================================================
#
# ===================================================================== | ========
opt_prob = Optimization('Rosenbrock Unconstraint Problem',objfunc)
opt_prob.addVar('x1','c',lower=-10.0,upper=10.0,value=-3.0)
opt_prob.addVar('x2','c',lower=-10.0,upper=10.0,value=-4.0)
opt_prob.addObj('f')
print opt_prob
# Instantiate Optimizer (PSQP) & Solve Problem
psqp = PSQP()
psqp.setOption('IPRINT',0... |
Meerkat007/Clothes-Shop-Website | server/clothes/tests.py | Python | mit | 369 | 0.00542 | from django.test import TestCase
from .models import Clothes
class ClothesModelTests(TestCase):
def setUp(self | ):
Clothes.objects.create(clothes_type='ladies dress', price=28.50)
Clothes.objects.create(clothes_type='men tie', price=8.50)
def test_number_of_clothes_created(self):
self.assertEq | ual(Clothes.objects.all().count(), 2)
|
jrabenoit/shopvec | shopvec.py | Python | gpl-3.0 | 1,402 | 0.017832 | #!/usr/bin/env python3
import os
import crossval, features, estimators, estpicker, bootstrap
def Vecuum():
print('\nGROUP CHOICES (automated order: 2,1,0,4,3,5,11,10,12)')
print('\nSymptom Severity:\n')
print(' 0= control/mild\n 1= control/severe\n 2= control/very severe\n 3= mild/severe\n 4= mild/ve... | unning. To run more groups | , you must construct additional pylons."')
return
|
istio/api | python/istio_api/mcp/v1alpha1/resource_pb2.py | Python | apache-2.0 | 3,416 | 0.005269 | # -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: mcp/v1alpha1/resource.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from ... | e=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='metadata', full_name='istio.mcp.v1alpha1.Resource.metadata', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, ... | key),
_descriptor.FieldDescriptor(
name='body', full_name='istio.mcp.v1alpha1.Resource.body', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None... |
rodxavier/open-pse-initiative | django_project/market/models.py | Python | mit | 445 | 0.008989 | from django.db import models
class NonTradingDay(models.Model):
non_trading_date = models.DateField()
class Meta:
ordering = ('non_trading_date',)
verbose_name = 'Non Trading Day'
verbose_name | _plural = 'Non Trading Days'
def __unicode__(self):
return self.non_trading_date.strftime('%B %d, %Y')
def __str__(self) | :
return self.non_trading_date.strftime('%B %d, %Y')
|
Desarrollo-CeSPI/meran | dev-plugins/node64/lib/node/wafadmin/Utils.py | Python | gpl-3.0 | 20,212 | 0.030972 | #!/usr/bin/env python
# Meran - MERAN UNLP is a ILS (Integrated Library System) wich provides Catalog,
# Circulation and User's Management. It's written in Perl, and uses Apache2
# Web-Server, MySQL database and Sphinx 2 indexing.
# Copyright (C) 2009-2013 Grupo de desarrollo de Meran CeSPI-UNLP
#
# This file is part ... | = kw['stderr'] = kw['log']
del(kw['log'])
kw['shell'] = isinstance(s, str)
if len(s) > 2000:
startupinfo = pproc.STARTUPINFO()
startupinfo.dwFlags |= pproc.STARTF_USESHOWWINDOW
kw['startupinfo'] = startupinfo
try:
if 'st | dout' not in kw:
kw['stdout'] = pproc.PIPE
kw['stderr'] = pproc.PIPE
proc = pproc.Popen(s,**kw)
(stdout, stderr) = proc.communicate()
Logs.info(stdout)
if stderr:
Logs.error(stderr)
return proc.returncode
else:
proc = pproc.Popen(s,**kw)
return proc.wait()
except OSError:
... |
alxgu/ansible | lib/ansible/modules/network/aci/mso_schema_site_vrf_region.py | Python | gpl-3.0 | 6,343 | 0.002207 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Dag Wieers (@dagwieers) <dag@wieers.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_ve... | /{1}/regions'.format(site_template, vrf)
ops = []
mso.previous = mso.existing
if state == 'absent':
if mso.existing:
mso.sent = mso.existing = {}
ops.append(dict(op='r | emove', path=region_path))
elif state == 'present':
payload = dict(
name=region,
)
mso.sanitize(payload, collate=True)
if mso.existing:
ops.append(dict(op='replace', path=region_path, value=mso.sent))
else:
ops.append(dict(op='add', pat... |
pyQuest/mount-api | mountapi/schema.py | Python | apache-2.0 | 2,575 | 0 | import abc
import inspect
import re
from mountapi.core import exceptions
class AbstractConverter(metaclass=abc.ABCMeta):
param_url: str = None
param_regex: str = None
@classmethod
def path_to_regex(cls, path):
return re.sub(cls.param_url, cls.param_regex, path) + '$'
class IntConverter(Abs... | outes:
schema[route.path] = {
'endpoint': route.endpoint,
'regex': self._get_path_regex(route.path),
**self._get_schema_http_methods(route)
}
return schema
def _g | et_path_regex(self, path):
for converter in self._converter_map.values():
path = converter.path_to_regex(path)
return path
def _get_schema_http_methods(self, route):
return {
http_method: {
'handler': getattr(route.endpoint, http_method.lower()),
... |
kierenbeckett/sentinel | sentinel/alert_plugins/rabbit_queues.py | Python | apache-2.0 | 1,275 | 0.003922 | import requests
from requests.auth import HTTPBasicAuth
def get_data(config):
auth = HTTPBasicAuth(config['authentication']['username | '], config['authentication']['password'])
resp = requests.get(config['host'] + '/api/queues', auth=auth)
queues = resp.json()
data = {}
for queue in queues:
name = queue['name']
message_stats = queue.get('message_stats', {})
queue_size = queue.get('messages')
ack_rate = ... | hreshold, active_threshold, nack_threshold) = (50, 5000, 1)
for qs_name, qs_threshold in config['queue_sizes'].items():
if name.startswith(qs_name):
(inactive_threshold, active_threshold, nack_threshold) = qs_threshold
data[name + ' queue'] = {
'state': 'FAIL' if... |
LockScreen/Backend | venv/lib/python2.7/site-packages/awscli/customizations/cloudsearch.py | Python | mit | 4,291 | 0.000466 | # Copyright 2014 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file acc... | stomizations.
"""
flattened = FlattenArguments('cloudsearch', FLATTEN_CON | FIG)
flattened.register(cli)
|
pantsbuild/pants | src/python/pants/jvm/run_deploy_jar_intergration_test.py | Python | apache-2.0 | 4,405 | 0.001135 | # Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import textwrap
from textwrap import dedent
from pants.engine.internals.native_engine import FileDigest
from pants.jvm.resolve.common import ArtifactRequirement, Coordinate, Coordinates
fr... | ),
),
)
)
)
.serialize(
[
ArtifactRequirement(
coordinate=Coordinate(
group="org.scala-lang", artifact="scala-library", version="2.13.6"
)
| )
]
)
.replace("{", "{{")
.replace("}", "}}")
)
DEFAULT_SCALA_LIBRARY_TARGET = textwrap.dedent(
"""\
jvm_artifact(
name="org.scala-lang_scala-library_2.13.6",
group="org.scala-lang",
artifact="scala-library",
version="2.13.6",
)
"""
)
def test_java() ->... |
hakyimlab/MetaXcan-Postprocess | source/deprecated/ProcessAlleleStatistics.py | Python | mit | 9,438 | 0.004238 | #!/usr/bin/env python
__author__ = 'heroico'
########################################################################################################################
# Gathers statistics on allele information.
# Produces a csv with the following columns:
# rsid,chromosome,wdb_ref_allele,wdb_eff_allele,legend_ref_allel... | TA)
line = "%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n" % tuple
return line
@classmethod
def CSVHeader(cls):
return "rsid,chromosome,wdb_ref_allele,wdb_eff_allele,legend_ref_allele,legend_eff_allele,legend_type,gwas_ref_allele,gwas_eff_allele,gwas_OR_BETA\n"
cl | ass ProcessAlleleStatistics(object):
def __init__(self, args):
self.data_folder = args.data_folder
self.weight_db = args.weight_db
self.db_path = os.path.join(self.data_folder, args.weight_db)
self.data_folder_phase = args.phase_folder
self.data_folder_gwas_dosage = args.gw... |
viniciusfk9/LearningFlask | votr/models.py | Python | gpl-3.0 | 3,878 | 0.001031 | import uuid
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import select, func
from sqlalchemy.ext.hybrid import hybrid_property
db = SQLAlchemy()
# Base model that for other models to inherit from
class Base(db.Model):
__abstract__ = True
id = db.Column(db.Integer, primary_key=True, autoincremen... | d'))
vote_count = db.Column(db.Integer, default=0)
# Relationship declaration (makes it easier for us to access t | he polls model
# from the other models it's related to)
topic = db.relationship('Topics', foreign_keys=[topic_id],
backref=db.backref('options', lazy='dynamic'))
option = db.relationship('Options', foreign_keys=[option_id])
def __repr__(self):
# a user friendly way t... |
ledatelescope/bifrost | test/test_gunpack.py | Python | bsd-3-clause | 4,872 | 0.007594 |
# Copyright (c) 2016, The Bifrost Authors. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions a... | run_unpack_to_ci8_test(self, iarray):
oarray = bf.ndarray(shape=iarray.shape, dtype='ci8', space='cuda')
oarray_known = bf.ndarray([[(0, 1), (2, 3)],
[(4, 5), (6, 7)],
[(-8, -7), (-6, -5)]],
dtype='ci... | oarray = oarray.copy(space='system')
np.testing.assert_equal(oarray, oarray_known)
def test_ci4_to_ci8(self):
iarray = bf.ndarray([[(0x10,),(0x32,)],
[(0x54,),(0x76,)],
[(0x98,),(0xBA,)]],
dtype='ci4')
... |
RCOS-Grading-Server/HWserver | bin/make_generated_output.py | Python | bsd-3-clause | 2,717 | 0.009201 | #!/usr/bin/env python3
"""
# USAGE
# make_generated_output.py <path to config file for gradeable> <assignment> <semester> <course>
"""
import argparse
import json
import os
from submitty_utils import dateutils
import sys
SUBMITTY_DATA_DIR = "/var/local/submitty"
def parse_args():
parser = argparse.Argume... | else:
sys.exit(1)
required_capabilities = config_file.get('required_capabilities','default')
testcases = config_file.get('testcases',[])
graded_file = {
"semester": args.semester,
"course": args.course,
"gradeable": args.assignment,
"requ | ired_capabilities": required_capabilities,
"queue_time": dateutils.write_submitty_date(milliseconds=True),
"generate_output": True,
"max_possible_grading_time" : -1,
"who" : "build",
"regrade" : False,
}
should_generated_output = False
for testcase in testcases:
... |
MassimoLauria/cnfgen | cnfgen/formula/linear.py | Python | gpl-3.0 | 7,042 | 0.000142 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""CNF formulas type with support of linear forms
This CNF formula type supports
- linear equations mod 2
- integer linear inequalities on literals (no coefficients)
for example 'atmost k'
Copyright (C) 2021 Massimo Lauria <lauria.massimo@gmail.com>
https://github.com/... | ----------
lists : iterable(int)
literals in the constraint
check : bool
check that the literals are valid and update the variable count
"""
if isgenerator(lits):
lits = list(lits)
threshold = ((len(lits) + 1) // 2)
return self.add_lin... | lits, check=True):
"""Clauses encoding a \"at most half\" constraint
Parameters
----------
lists : iterable(int)
literals in the constraint
check : bool
check that the literals are valid and update the variable count
"""
if isgenerator(lits... |
michaelcontento/whirlwind | whirlwind/view/paginator.py | Python | mit | 1,921 | 0.008329 | class Paginator(object):
def __init__(self, collection, page_number=0, limit=20, total=-1):
self.collection = collection
| self.page_number = int(page_number)
self.limit = int(limit)
self.total = int(total)
@property
| def page(self):
start = self.page_number * self.limit
end = start + self.limit
try:
return self.collection[start:end]
except Exception as detail:
print detail
return []
@property
def current_page(self):
return self.page_number + 1... |
iand/pynappl | old/sparql_select_result.py | Python | gpl-2.0 | 1,296 | 0.026235 | """sparql_select_result.py
Data structure for storing the results of SPARQL SELECT queries"""
__all__ = ["SPARQLSelectResult"]
from xml.etree | import ElementTree as et
| class SPARQLSelectResult(object):
def __init__(self):
self.variables = []
self.results = []
def parse(self, s):
tree = et.fromstring(s)
head = tree.find("{http://www.w3.org/2005/sparql-results#}head")
self.variables = [x.get("name") for x in head.findall("{http://www.w3.org/2005/sparql-results#}variable")]
... |
GRUPO-ES2-GJLRT/XADREZ_ES2 | src/cython/importer.py | Python | mit | 665 | 0 | import platform
import importlib
from utils.pyx_replace import read_file
name = 'cython._genpyx_' + '_'.join(platform.architecture()) + '_chess0x88'
try:
chess = importlib.import_module(name)
checksum = chess.CHECKSUM
expected_checksum = read_file("chess0x88.py", [], "cython")
if checksum != expected_... | ay want to run on cython folder:")
print("python setup.py build_ext --inplace")
from chess0x88 import Board, Move, mov | e_key
|
MrReN/django-oscar | oscar/templatetags/history_tags.py | Python | bsd-3-clause | 1,884 | 0.000531 | import six
from django import template
from oscar.core.loading import get_model
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import resolve, Resolver404
from oscar.apps.customer import history
from oscar.core.compat import urlparse
Site = get_model('sites', 'Site')
register =... | register.assignment_tag(takes_context=True)
def get_back_button(co | ntext):
"""
Show back button, custom title available for different urls, for
example 'Back to search results', no back button if user came from other
site
"""
request = context.get('request', None)
if not request:
raise Exception('Cannot get request from context')
referrer = req... |
plin1112/pysimm | tests/test.py | Python | mit | 1,809 | 0.012714 | from __future__ import print_function
import os
import sys
import imp
import shutil
from glob import glob
from pprint import pprint
from cStringIO import StringIO
class Capturing(list):
def __enter__(self):
self._stdout = sys.stdout
sys.stdout = self._stringio = StringIO()
return self
... | .models.monomers.gaff2 import *
print('passed')
example_dir = os.path.join(o | s.path.dirname(os.path.realpath(__file__)), os.pardir, os.pardir, 'Examples')
examples = glob(os.path.join(example_dir, '*'))
scripts = []
for example in examples:
scripts += glob(os.path.join(example, '*.py'))
scripts += glob(os.path.join(example, '*', '*.py'))
output = []
for script in sorted(scripts, key=... |
M3TIOR/Tactix | Tactix.py | Python | mit | 2,700 | 0.047778 | #!/usr/bin/python
#This is the old version of Tactix befor I decided to make the C version.
#I hope you all like it.
#I wanted to include it to make sure even if you only have a monochrome display you can still play!
# * HORRAY FOR GAMERS!
#I may very well have modded this a bit too, just so it feels more like the fu... | data[((c+xoff+l)*(c+yoff))] = data[l]
#outputs everything to screen.
def flush():
#... stuff...
global character_field
character_field = getTerminalSize()
#text orientation.
#def t_orient(text,x,y, | maxx,maxy):
#quadrants work as such
#
# +-----------------+
# | | | |
# | 0,0 | 1,0 | 2,0 |
# +-----------------+
# | | | |
# | 0,1 | 1,1 | 2,1 |
# +-----------------+
# | | | |
# | 0,2 | 1,2 | 2,2 |
# +-----------------+
class game:
main_menu = window... |
iModels/ffci | moleculeci/apps.py | Python | mit | 215 | 0 | from importlib import import_mod | ule
from django.apps import AppConfig as BaseAppConfig
class AppConfig(BaseAppConfig):
name = "moleculeci"
def ready(self):
import_module("moleculeci.rec | eivers")
|
ngageoint/gamification-server | gamification/core/models.py | Python | mit | 7,022 | 0.003987 | # -*- coding: utf-8 -*-
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sub... | l
# Geospatial-Intelligence Agency.
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABIL... | # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import json
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from dj... |
Talkdesk/graphite-web | webapp/graphite/browser/views.py | Python | apache-2.0 | 7,137 | 0.026482 | """Copyright 2008 Orbitz WorldWide
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... |
if not nodes:
no_graphs = { 'text' : "No saved graphs", 'id' : 'no | -click' }
no_graphs.update(leafNode)
nodes.append(no_graphs)
return json_response(nodes, request)
def json_response(nodes, request=None):
if request:
jsonp = request.REQUEST.get('jsonp', False)
else:
jsonp = False
#json = str(nodes) #poor man's json encoder for simple types
json_data = json... |
mikel-egana-aranguren/SADI-Galaxy-Docker | galaxy-dist/doc/patch.py | Python | gpl-3.0 | 34,815 | 0.014074 | #!/usr/bin/env python
""" Patch utility to apply unified diffs
Brute-force line-by-line non-recursive parsing
Copyright (c) 2008-2012 anatoly techtonik
Available under the terms of MIT license
Project home: http://code.google.com/p/python-patch/
$Id: patch.py 181 2012-11-23 16:03:05Z techtonik... | mp buffers for header an | d filenames info
header = []
srcname = None
tgtname = None
# start of main cycle
# each parsing block already has line available in fe.line
fe = wrapumerate(stream)
while fe.next():
# -- deciders: these only switch state to decide who should process
# -- line fetched ... |
mitodl/micromasters | dashboard/api_edx_cache.py | Python | bsd-3-clause | 15,571 | 0.002954 | """
APIs that deal with the edx cached data
"""
import datetime
import logging
from collections import namedtuple
from django.db import transaction
from requests.exceptions import HTTPError
from edx_api.client import EdxApi
from backends import utils
from backends.constants import COURSEWARE_BACKEND_URL, BACKEND_EDX_... | None
"""
with transact | ion.atomic():
# get the enrollment data
enrollment_data = enrollment.json
course_run = CourseRun.objects.get(edx_course_key=course_id)
updated_values = {
'user': user,
'course_run': course_run,
'data': enrollment_data,
... |
vga101/gaiasky | assets/scripts/tests/scroll-test.py | Python | mpl-2.0 | 452 | 0 | # Test script. Tests GUI scroll movement commands.
# Created by Toni Sagrista
from gaia.c | u9.ari.gaiaorbit.script import EventScriptingInterface
gs = EventScriptingInterface.instance()
gs.disableInput()
gs.cameraStop()
gs.setGuiScrollPosition(20.0)
gs.sleep(1)
gs.setGuiScrollPosition(40.0)
gs. | sleep(1)
gs.setGuiScrollPosition(60.0)
gs.sleep(1)
gs.setGuiScrollPosition(80.0)
gs.sleep(1)
gs.setGuiScrollPosition(100.0)
gs.sleep(1)
gs.enableInput()
|
unt-libraries/catalog-api | django/sierra/sierra/solr_backend.py | Python | bsd-3-clause | 11,551 | 0.001472 | """
This is a custom solr_backend for haystack. It fixes a few minor issues
with the out-of-the-box version.
1. Overrides the SolrSearchBackend._process_results() method. The
out-of-the-box haystack version uses pysolr._to_python() to parse any
results for indexes that aren't managed by haystack. This method for... | if hasattr(raw_results, 'facets'):
facets = {
'fields': raw_results.facets.get('facet_fields', {}),
'dates': raw_results.facets.get('facet_dates', {}),
'queries': raw_results.facets.get('facet_queries', {}),
}
for key in [... | for facet_field in facets[key]:
# Convert to a two-tuple, as Solr's json format returns a list of
# pairs.
facets[key][facet_field] = list(zip(facets[key][facet_field][::2], facets[key][facet_field][1::2]))
if self.include_spelling is True:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.