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
bigodines/api-health
tests/test_verifier.py
Python
mit
1,105
0.00181
# -*- coding: utf-8 -*- import unittest import json from api_health.verifier import Verifier class JsonVerifier(unittest.TestCase): def test_constructor_should_be_smart_about_params(self): simple_json = u'{ "foo": "bar" }' json_dict = json.loads(simple_json) try: v1 = Verifier(...
deal with both ' 'string and object json') self.assertTrue(v1.has_property('foo')) self.assertTrue(v2.has_property('foo')) def test_should_check_for_json_property(self): simple_json = u'{ "foo": "bar" }' verifier =
Verifier(simple_json) self.assertTrue(verifier.has_property('foo')) self.assertTrue(verifier.does_not_have_property('bu')) self.assertFalse(verifier.has_property('bleh')) def test_should_check_arrays(self): array_json = u'{ "foo": "bar", "baz": [ 1, 2, 3] }' verifier = Verif...
kaye64/gem
content/player.py
Python
gpl-3.0
838
0.001193
# This file is part of Gem. # # Gem 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. # # Gem 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 copy of the GNU General Public License # along with Gem. If not, see <http://www.gnu.org/licenses/\>. from gem.api import Location from enum import Enum LOG_TAG = "player" def player_position_update(player, location, warped): profile = player.profile profile.locati...
namunu/MBS_Patent
parser_test/test.py
Python
bsd-2-clause
962
0.008316
from cStringIO import StringIO from datetime import datetime from unidecode import unidecode from handler import Patobj, PatentHandler import re import uuid import xml.sax import xml_util import xml_driver xml_string = 'ipg050104.xml' xh = xml_driver.XMLHandler() parser = xml_dri
ver.make_parser() parser.setContentHandler(xh) parser.setFeature(xml_driver.handler.feature_external_ges, False) l = xml.sax.xmlreader.Locator() xh.setDocumentLocator(l) #parser.parse(StringIO(xml_string)) parser.parse(xml_string) print "parsing done" #print type(xh.root.us_bibliographic_data_grant.publication_refer...
e) #print type(xh.root.us_bibliographic_data_grant.publication_reference.contents_of('document_id', '', as_string=True)) #print xh.root.us_bibliographic_data_grant.publication_reference.contents_of('document_id', '', as_string=True)
mbrubeck/servo
tests/wpt/web-platform-tests/webdriver/tests/get_window_rect/user_prompts.py
Python
mpl-2.0
2,153
0.000464
from tests.support.asserts import assert_error, assert_dialog_handled from tests.support.fixtures import create_dialog from tests.support.inline import inline alert_doc = inline("<script>window.alert()
</script>") def get_window_rect(session): return session.transport.send
( "GET", "session/{session_id}/window/rect".format(**vars(session))) def test_handle_prompt_dismiss_and_notify(): """TODO""" def test_handle_prompt_accept_and_notify(): """TODO""" def test_handle_prompt_ignore(): """TODO""" def test_handle_prompt_accept(new_session, add_browser_capabilites):...
rismalrv/edx-platform
lms/djangoapps/courseware/testutils.py
Python
agpl-3.0
7,642
0.002355
""" Common test utilities for courseware functionality """ from abc import ABCMeta, abstractmethod from datetime import datetime import ddt from mock import patch from urllib import urlencode from lms.djangoapps.courseware.url_helpers import get_redirect_url from student.tests.factories import AdminFactory, UserFacto...
self.verify_response() def test_success_unenrolled_staff(self): self.setup_course() self.setup_user(admin=True, enroll=False, login=True) self.verify_response() def test_success_enrolled_
student(self): self.setup_course() self.setup_user(admin=False, enroll=True, login=True) self.verify_response() def test_unauthenticated(self): self.setup_course() self.setup_user(admin=False, enroll=True, login=False) self.verify_response(expected_response_code=404)...
pierky/ripe-atlas-tools
ripe/atlas/tools/settings/__init__.py
Python
gpl-3.0
7,761
0
# Copyright (c) 2016 RIPE NCC # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the h...
"port": 443 }, "ntp": { "packets": 3, "timeout": 4000 }, "dns": { "set-cd-bit": False, "set-
do-bit": False, "protocol": "UDP", "query-class": "IN", "query-type": "A", "query-argument": None, "set-nsid-bit": False, "udp-payload-size": 512, "set-rd-bit": True, ...
jat255/hyperspy
hyperspy/learn/ornmf.py
Python
gpl-3.0
13,811
0.00029
# -*- coding: utf-8 -*- # Copyright 2007-2022 The HyperSpy developers # # This file is part of HyperSpy. # # HyperSpy 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 y...
, np.ndarray): raise ValueError("can't batch iterating data") else: prod = np.dot length = X.shape[0]
num = max(length // batch_size, 1) X = np.array_split(X, num, axis=0) if isinstance(X, np.ndarray): num = X.shape[0] X = iter(X) h, e = self.h, self.e for v in progressbar(X, leave=False, total=num, disable=num == 1): h, e = _solvep...
Tinkerforge/brickv
src/brickv/plugin_system/plugins/uv_light_v2/__init__.py
Python
gpl-2.0
931
0
# -*- coding: utf-8 -*- """ UV Light 2.0 Plugin Copyright (C) 2018 Ishraq Ibne Ashraf <ishraq@tinkerforge.com> __init__.py: Package initialization 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; eit...
, USA. """ from brickv.plugin_system.plugins.uv_light_v2.uv_l
ight_v2 import UVLightV2 device_class = UVLightV2
sassoftware/conary
conary/local/schema.py
Python
apache-2.0
36,311
0.003883
# # Copyright (c) SAS Institute Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in w...
dataItems( metadataId INTEGER NOT NULL, class INTEGER NOT NULL, data TEXT NOT NULL, language VARCHAR(254) NOT NULL DEFAULT 'C' )
""") cu.execute("CREATE INDEX MetadataItemsIdx ON MetadataItems(metadataId)") commit = True if commit: db.commit() db.loadSchema() def createDataStore(db): if "DataStore" in db.tables: return cu = db.cursor() cu.execute(""" CREATE TABLE DataStore( has...
JulienMcJay/eclock
windows/Python27/Lib/site-packages/pywin32-218-py2.7-win32.egg/win32service.py
Python
gpl-2.0
283
0.035336
def __bootstrap__(): global __boo
tstrap__, __loader__, __file__ import sys, pkg_resources, imp __file__ = pkg_resources.resource_filename(__name__,'win32service.pyd') __loader__ = None; del __bootstrap__, __loader__ imp.load_dynamic(__name__,__file__) _
_bootstrap__()
reyoung/Paddle
python/paddle/fluid/layers/ops.py
Python
apache-2.0
3,701
0.00027
# Copyright (c) 2018 PaddlePaddle 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 app...
import print_function from .layer_function_generator import generate_layer_fn, generate_laye
r_fn_noattr from .. import core from ..framework import convert_np_dtype_to_dtype_ __activations_noattr__ = [ 'sigmoid', 'logsigmoid', 'exp', 'tanh', 'tanh_shrink', 'softshrink', 'sqrt', 'abs', 'ceil', 'floor', 'cos', 'sin', 'round', 'reciprocal', 'square', ...
Huyuwei/tvm
tests/webgl/test_static_webgl_library.py
Python
apache-2.0
2,490
0.001606
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
"-s", "USE_GLFW=3", "-s", "USE_WEBGL2=1", "-lglfw", ]) # Create "tvm_runtime.js" and "identity_static.html" in lib/ shutil.copyfile(os.path.join(curr_path, "../../web/
tvm_runtime.js"), "tvm_runtime.js") shutil.copyfile(os.path.join(curr_path, "test_static_webgl_library.html"), "identity_static.html") port = 8080 handler = SimpleHTTPServer.SimpleHTTPRequestHandler httpd = SocketServer.TCPServer(("", port), handler) print("P...
plotly/plotly.py
packages/python/plotly/plotly/validators/scatter/marker/colorbar/_xpad.py
Python
mit
460
0.002174
import _pl
otly_utils.basevalidators class XpadValidator(_plotly_utils.basevalidators.NumberValidator): def __init__( self, plotly_name="x
pad", parent_name="scatter.marker.colorbar", **kwargs ): super(XpadValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "colorbars"), min=kwargs.pop("min", 0), **kwargs )
lmittmann/clr
style/__init__.py
Python
mit
533
0
import sys import pkg_resources from style.styled_string_builder import _StyledStringBuilder t
ry: __version__ = pkg_resources.get_distribution
('style').version except Exception: __version__ = 'unknown' _enabled = sys.stdout.isatty() if '--color' in sys.argv: _enabled = True elif '--no-color' in sys.argv: _enabled = False styled_string_builder = _StyledStringBuilder([], True) styled_string_builder.enabled = _enabled styled_string_builder.__versi...
jpetto/olympia
src/olympia/addons/tests/test_decorators.py
Python
bsd-3-clause
5,023
0
from django import http import mock from nose.tools import eq_ from olympia.amo.tests import TestCase from olympia.addons import decorators as dec from olympia.addons.models import Addon class TestAddonView(TestCase): def setUp(self): super(TestAddonView, self).setUp() self.addon = Addon.object...
jects.filter(type=1) view = dec.addon_view_factory(qs=qs)(self.func) res = view(self.request, str(self.addon.id)) self.assert3xx(res, self.slug_path, 301) def test_alternate_qs_200_by_slug(self): def qs(): return Addon.objects.filter(type=1) view = dec.addon_vi...
es = view(self.request, self.addon.slug) eq_(res, mock.sentinel.OK) def test_alternate_qs_404_by_id(self): def qs(): return Addon.objects.filter(type=2) view = dec.addon_view_factory(qs=qs)(self.func) with self.assertRaises(http.Http404): view(self.request, ...
PrzemekBurczyk/dalvik-compiler
src/items/string_id_item.py
Python
mit
347
0.005764
''' Created on 3 cze 2014 @author: Przemek ''' from src.items.bytes import Bytes from src.parser.measurable import Measurable class StringIdItem(Measurable): ''' classdocs ''' def __init__(self, parent): '''
Constructor ''' Measurable.__init__(self, par
ent) self._data = Bytes(self, 4)
superstack/nova
nova/tests/api/openstack/__init__.py
Python
apache-2.0
3,850
0.000519
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 OpenStack LLC. # 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/...
set(['usr1:POST', 'usr1:POST serve
rs', 'usr2:POST'])) def test_POST_servers_action_correctly_ratelimited(self): middleware = RateLimitingMiddleware(simple_wsgi) # Use up all of our "POST" allowance for the minute, 5 times for i in range(5): self.exhaust(middleware, 'POST', '/servers/4', 'usr1', 10) #...
Micronaet/micronaet-quality
quality/etl/errata_corrige.py
Python
agpl-3.0
1,215
0.014815
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Modules used for ETL - Create User # Modules required: import os import xmlrpclib, sys, csv, ConfigParser from datetime import datetime # Set up parameters (for connection to Open ERP Database) ********************* config = ConfigParser.ConfigParser() file_config = o...
me = config.get('dbaccess','dbname') user = config.get('dbaccess','user') pwd = config.get('dbaccess','pwd') server = config.get('db
access','server') port = config.get('dbaccess','port') # verify if it's necessary: getint separator = eval(config.get('dbaccess','separator')) # test # XMLRPC connection for autentication (UID) and proxy sock = xmlrpclib.ServerProxy('http://%s:%s/xmlrpc/common' % (server, port), allow_none=True) uid = sock.login(dbn...
Cheaterman/kivy
examples/3Drendering/main.py
Python
mit
2,405
0
''' 3D Rotating Monkey Head ======================== This example demonstrates using OpenGL to display a rotating monkey head. This includes loading a Blender OBJ file, shaders written in OpenGL's Shading Language (GLSL), and using scheduled callbacks. The monkey.obj file is an OBJ file output from the Blender free 3...
vertex and fragment shader written in GLSL. ''' from kivy.app import App from kivy.clock import Clock from kivy.core.window import Window from kivy.uix.widget import Widget from kivy.resources import resource_find from kivy.graphics.transformation import Matrix from kivy.graphics.opengl import * from kivy.graphics im...
.canvas = RenderContext(compute_normal_mat=True) self.canvas.shader.source = resource_find('simple.glsl') self.scene = ObjFile(resource_find("monkey.obj")) super(Renderer, self).__init__(**kwargs) with self.canvas: self.cb = Callback(self.setup_gl_context) PushMat...
alexgorban/models
official/nlp/xlnet/xlnet_config.py
Python
apache-2.0
6,110
0.003764
# Copyright 2019 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...
with mean 0 and stddev init_std. Only effective when init="normal". mem_len: int, the number of tokens to cache. reuse_len: int, the number of tokens in the currect batch to be cached and reused in the future. bi_data: bool, whether to use bidirectional input pipeline.
Usually set to True during pretraining and False during finetuning. clamp_len: int, clamp all relative distances larger than clamp_len. -1 means no clamping. same_length: bool, whether to use the same attention length for each token. use_cls_mask: bool, whether to intro...
sanchopanca/my-long-term-memory
app.py
Python
apache-2.0
269
0
#!/usr/bin/env python3 import sys from mltm.cli import add_
entry, show_entries if __name__ == '__main__': n = len(sys.argv[1:]) if n == 0: show_entries() elif sys.argv[1] == 'add': a
dd_entry() else: show_entries(sys.argv[1])
biomodels/BIOMD0000000102
BIOMD0000000102/model.py
Python
cc0-1.0
427
0.009368
import os path = os.path.di
rname(os.path.realpath(__file__)) sbmlFilePath = os.path.join(path, 'BIOMD0000000102.xml') with open(sbmlFilePath,'r') as f: sbmlString = f.read() def module_exists(module_name): try: __import__(module_name) except ImportError: return False
else: return True if module_exists('libsbml'): import libsbml sbml = libsbml.readSBMLFromString(sbmlString)
testbhearsum/balrog
src/auslib/web/admin/views/releases.py
Python
mpl-2.0
26,017
0.003306
import difflib import json import connexion from flask import Response, abort, jsonify from auslib.blobs.base import BlobValidationError, createBlob from auslib.db import OutdatedDataError, ReadOnlyError from auslib.global_state import dbo from auslib.web.admin.views.base import AdminView, requirelogin, serialize_sig...
for release '%s'" % (product, releaseInfo["product"], rel) log.warning("Bad input: %s", rel) return problem(400, "Bad Request", msg) if "hashFunction" in releaseInfo["data"] and hashFunction and hashFunction != releaseInfo["data"]["hashFunction"]: ...
se " "object ('{1}') for release '{2}'".format( hashFunction, releaseInfo["data"]["hashFunction"], rel ) log.warning("Bad input: %s", rel) return problem(400, "Bad Request", msg) # If this isn't the release in the URL... ...
openstack/tempest
tempest/test_discover/test_discover.py
Python
apache-2.0
1,891
0
# Copyright 2013 IBM Corp. # # 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 t...
return suite # Load any installed plugin tests for plugin in plugin_load_tests: test_dir, top_path = plugin_load_tests[plugin] if not pattern: suite.addTests(loader.dis
cover(test_dir, top_level_dir=top_path)) else: suite.addTests(loader.discover(test_dir, pattern=pattern, top_level_dir=top_path)) return suite
sahdman/Plane
Servo.py
Python
gpl-3.0
804
0.039801
import Adafruit_BBIO.PWM as PWM class Servo: def __init__(self, pin): self.servo_pin = pin self.duty_min = 3 self.duty_max = 14.5
self.duty_span = self.duty_max - self.duty_min def StartServo(self): print("Starting servo") print(self.servo_pin) PWM.start(self.servo_pin, (100 - self.duty_min), 60.0, 1) self.current_angle = 90.0 self.SetAngle(self.current_angle) def SetAngle(self, angle): angle_f = float(angle) duty = 100 - (...
uty_span + self.duty_min) PWM.set_duty_cycle(self.servo_pin, duty) def IncreaseAngle(self, angle): self.current_angle += angle self.SetAngle(self.current_angle) def DecreaseAngle(self, angle): self.current_angle -= angle self.SetAngle(self.current_angle) def StopServo(self): PWM.stop(self.servo_pin)
atvcaptain/enigma2
lib/python/Components/Renderer/Progress.py
Python
gpl-2.0
1,048
0.02958
from __future__ import absolute_import from Components.VariableValue import VariableValue from Components.Renderer.Renderer import Renderer from enigma import eSlider class Progress(VariableValue, Renderer): def __init__(self): Renderer.__init__(self) VariableValue.__init__(self) self.__start = 0 self.__end ...
f.CHANGED_CLEAR: (self.range, self.value) = ((0, 1), 0) return range = self.source.range or 100 value = self.source.value if value is None: value = 0 if range > 2**31-1: range = 2**31-1 if value > range: value = range if value < 0: value
= 0 (self.range, self.value) = ((0, range), value) def postWidgetCreate(self, instance): instance.setRange(self.__start, self.__end) def setRange(self, range): (self.__start, self.__end) = range if self.instance is not None: self.instance.setRange(self.__start, self.__end) def getRange(self): return ...
1mentat/card
setup.py
Python
gpl-2.0
417
0.002398
from distutils.core import setup setup(name="card", auth
or="Benoit Mich
au", author_email="michau.benoit@gmail.com", url="http://michau.benoit.free.fr/codes/smartcard/", description="A library to manipulate smartcards used in telecommunications systems (SIM, USIM)", long_description=open("README.txt", "r").read(), version="0.1.0", license="GPLv2", ...
cheral/orange3
Orange/widgets/visualize/tests/test_owscatterplot.py
Python
bsd-2-clause
3,898
0.000257
# Test methods with long descriptive names can omit docstrings # pylint: disable=missing-docstring from unittest.mock import MagicMock import numpy as np from AnyQt.QtCore import QRectF from Orange.data import Table, Domain, ContinuousVariable, DiscreteVariable from Orange.widgets.tests.base import WidgetTest, Widge...
self.assertEqual(self.widget.attr_x, None) self.assertEqual(self.widget.attr_y, None) self.assertEqual(self.widget.graph.attr_color, None) # and remove the legend self.assertEqual(self.widget.graph.legend, None) # Connect iris again # same attributes t
hat were used last time should be selected self.send_signal("Data", self.data) self.assertIs(self.widget.attr_x, self.data.domain[2]) self.assertIs(self.widget.attr_y, self.data.domain[3]) def test_score_heuristics(self): domain = Domain([ContinuousVariable(c) for c in "abcd"], ...
stack-of-tasks/rbdlpy
tutorial/lib/python2.7/site-packages/OpenGL/raw/GLX/OML/sync_control.py
Python
lgpl-3.0
1,569
0.045252
'''Autogenerated by xml_generate script, do not edit!''' from OpenGL import platform as _p, arrays # Code generation uses this from OpenGL.raw.GLX import _types as _cs # End users want this... from OpenGL.raw.GLX._types import * from OpenGL.raw.GLX import _errors from OpenGL.constant import Constant as _C import ctype...
types(_cs.Bool,ctypes.POINTER(_cs.Display),_cs.GLXDrawable,_cs.int64_t,ctypes.POINTER(_cs.int64_t),ctypes.POINTER(_cs.int64_t),ctypes.POINTER(_cs.int6
4_t)) def glXWaitForSbcOML(dpy,drawable,target_sbc,ust,msc,sbc):pass
rosspalmer/bitQuant
bitquant/data/clss.py
Python
mit
3,127
0.011193
import conv import tools from ..api.clss import api from ..sql.clss import sql from pandas import DataFrame import time as tm class data(object): def __init__(self): self.a = api() self.s = sql() self.jobs = [] self.trd = DataFrame() self.prc = DataFrame() def add_tra...
self.run_trades(job['exchange'], job['symbol']) if tm.time() > dump: dump = tm.time() + to_sql self.to_sql(log) def get_price(self, exchange='', symbol='', freq='', start=''): prc = self.s.select('price',exchange=exchange,symbol=symbol, ...
freq=freq, start=start) self.prc = self.prc.append(prc) self.prc = self.prc.drop_duplicates(['timestamp','exchange', 'symbol','freq']) return prc def run_price(self, exchange, symbol, freq, label='left', from_sql='no', ...
pydsigner/taskit
setup.py
Python
lgpl-3.0
1,455
0.003436
#! /usr/bin/env python try: from setuptools import setup except ImportError:
from distutils.core import setup import sys import taskit long_description = '''TaskIt -- A light-weight task management library. TaskIt is a light-weight library to turn a function into a full-featured, threadable task. It is completely X-Python Compatible and has no external dependencies. The simple version ...
ple, obvious way to connect with the backends.''' def main(): setup(script_args=sys.argv[1:] if len(sys.argv) > 1 else ['install'], name='taskit', version=taskit.__version__, description='TaskIt -- A light-weight task management library.', long_description=long_description,...
wavicles/pycode-browser
Code/Physics/spring2.py
Python
gpl-3.0
1,784
0.040919
""" spring2.py The rk4_two() routine in this program does a two step integration using an array method. The current x and xprime values are kept in a global list named 'val'. val[0] = current positi
on; val[1] = current velocity The results are compared with analytically calculated values. """ from pylab import * def accn(t, v
al): force = -spring_const * val[0] - damping * val[1] return force/mass def vel(t, val): return val[1] def rk4_two(t, h): # Time and Step value global xxp # x and xprime values in a 'xxp' k1 = [0,0] # initialize 5 empty lists. k2 = [0,0] k3 = [0,0] k4 = [0,0] tmp= [0,0] k1[0] = vel(t,xxp) k1[1] = accn...
tridge/DavisSi1000
Firmware/tools/davis_log.py
Python
bsd-2-clause
715
0.004196
#!/usr/bin/env python # reflect input bytes to output, printing as it goes import serial, sys, optparse, time parser = optparse.OptionParser("davis_log") parser.add_option("--baudrate", type='int', default=57600, help='baud rate') opts, args = parser.parse_args() if len(args) != 2: print("usage: reflector.py <D...
(device, opts.baudrate, timeout=5, dsrdtr=False, rtscts=False, xonxoff=False) log = open(logfile, mode="a") while True: line = port.readline() line = line.rstrip(
) out = "%s %.2f\n" % (line, time.time()) log.write(out); log.flush() sys.stdout.write(out) sys.stdout.flush()
ywangd/stash
bin/crypt.py
Python
mit
2,462
0.001219
# -*- coding: utf-8 -*- ''' File encryption for stash Uses AES in CBC mode. usage: crypt.py [-h] [-k KEY] [-d] infile [outfile] positional arguments: infile File to encrypt/decrypt. outfile Output file. optional arguments: -h, --help show this help message and exit -k KEY, --ke...
main__': ap = argparse.ArgumentParser() ap.add_argument( '-k', '--key', action='store', default=None, help='Encrypt/Decrypt Key.', ) ap.add_argument( '-d', '--decrypt', action='store_true', default=False, help='Flag to decry...
/decrypt.') ap.add_argument('outfile', action='store', nargs='?', help='Output file.') args = ap.parse_args() crypt = Crypt(args.infile, args.outfile) if args.decrypt: crypt.aes_decrypt(args.key.encode()) else: nk = crypt.aes_encrypt(args.key) if args.key is None: ...
operepo/ope
laptop_credential/winsys/tests/test_event_logs.py
Python
mit
6,794
0.002944
# -*- coding: utf-8 -*- from __future__ import unicode_literals import sys from winsys._compat import unittest import uuid import winerror import win32api import win32con import win32evtlog import win32security import pywintypes from winsys.tests import utils as testutils from winsys import event_logs, registry, uti...
hLog, win32evtlog.EVENTLOG_BACKWARDS_READ | w
in32evtlog.EVENTLOG_SEQUENTIAL_READ, 0 ) if entries: for entry in entries: yield entry else: break finally: win32evtlog.CloseEventLog(hLog) # # TESTS # @unittest.skipUnless(testutils.i_am_admin(), "Thes...
jntkym/rappers
utils.py
Python
mit
1,664
0.001202
#!/usr/bin/env python # -*- coding:utf-8 -*- # from __future__ import unicode_literals import codecs import sys reload(sys) sys.setdefaultencoding('utf8') # ranges of ordinals of unicode ideographic characters ranges = [ {"from": ord(u"\u3300"), "to": ord(u"\u33ff")}, #
compatibility ideographs {"from": ord(u"\ufe30"), "to": ord(u"\ufe4f")}, # compatibility ideographs {"from": ord(u"\uf900"), "to": ord(u"\ufaff")}, # compatibility ideographs # {"from": ord(u"\U0002f800"), "to": ord(u"\U0002fa1f")}, # compatibility ideographs {"from": ord(u"\u30a0"), "to": or
d(u"\u30ff")}, # Japanese Kana {"from": ord(u"\u2e80"), "to": ord(u"\u2eff")}, # cjk radicals supplement {"from": ord(u"\u4e00"), "to": ord(u"\u9fff")}, {"from": ord(u"\u3400"), "to": ord(u"\u4dbf")}, # {"from": ord(u"\U00020000"), "to": ord(u"\U0002a6df")}, # {"from": ord(u"\U0002a700"), "to": or...
xinruobingqing/robotChat
vector.py
Python
apache-2.0
1,599
0.012203
# -*- coding:utf-8 -*- import os import random import sys import importlib importlib.reload(sys) UNK_ID = 3 train_encode_file = 'data/middle_data/train.enc' train_decode_file = 'data/middle_data/train.dec' test_encode_file = 'data/middle_data/test.enc' test_decode_file = 'data/middle_data/test.dec' train_encode_vo...
ata/vector_data/trai
n_decode.vec') convert_to_vector(test_encode_file, train_encode_vocabulary_file, 'data/vector_data/test_encode.vec') convert_to_vector(test_decode_file, train_decode_vocabulary_file, 'data/vector_data/test_decode.vec')
lukw00/spaCy
tests/spans/test_span.py
Python
mit
579
0.001727
from __future__ import unicode_literals import pytest @pytest.fixture def doc(EN): return EN('This is a sentence. Th
is is another sentence. And a third.') @pytest.mark.models def test_sent_spans(doc): sents = list(doc.sents) assert sents[0].start == 0 assert sents[0].end == 5 assert len(sents) == 3 assert sum(len(sent) for sent in sents) == len(doc
) @pytest.mark.models def test_root(doc): np = doc[2:4] assert len(np) == 2 assert np.orth_ == 'a sentence' assert np.root.orth_ == 'sentence' assert np.root.head.orth_ == 'is'
luke0922/celery_learning
manage.py
Python
apache-2.0
1,290
0.000775
#!/usr/bin/env python # encoding: utf-8 import sys import subprocess from flask_script import Manager from flask_script.commands import ShowUrls from flask_migrate import MigrateCommand from application import create_app from application.extensions import db from utils.commands import GEventServer, ProfileServer ma...
--ignore=E402,F403,E501', 'application/', 'manage.py', 'tests/']) == 0 if lint: print('OK') sys.exit(lint) @manager.command def test(): """Runs unit te
sts.""" tests = subprocess.call(['python', '-c', 'import tests; tests.run()']) sys.exit(tests) @manager.command def create_db(): """create tables""" db.create_all() if __name__ == "__main__": manager.run()
dmacvicar/spacewalk
client/solaris/smartpm/smart/sorter.py
Python
gpl-2.0
22,108
0.001357
# # Copyright (c) 2004 Conectiva, Inc. # # Written by Gustavo Niemeyer <niemeyer@conectiva.com> # # This file is part of Smart Package Manager. # # Smart Package Manager 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 Fou...
loop = {} while path:
head = path[-1] dct = successors.get(head) if dct: for succ, kind in dct: if (head, succ, kind) not in self._disabled: if succ in loop or succ == end: loop.update(dict.fromkeys(path, True)) ...
sixtyfive/pcsc-ctapi-wrapper
PCSC/UnitaryTests/control_get_firmware.py
Python
lgpl-2.1
2,053
0.001461
#! /usr/bin/env python """ # control_get_firmware.py: get firmware version of Gemalto readers # Copyright (C) 2009-2012 Ludovic Rousseau """ # 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...
is program; if not, see <http://www.gnu.org/licenses/>. from smartcard.System import readers from smartcard.pcsc.PCSCPart10 import (SCARD_SHARE_DIRECT, SCARD_LEAVE_CARD, SCARD_
CTL_CODE, getTlvProperties) for reader in readers(): cardConnection = reader.createConnection() cardConnection.connect(mode=SCARD_SHARE_DIRECT, disposition=SCARD_LEAVE_CARD) print "Reader:", reader # properties returned by IOCTL_FEATURE_GET_TLV_PROPERTIES properties = getTlvProperties(car...
WING-NUS/corpSearch
system/systems.py
Python
lgpl-3.0
2,889
0
from corpsearchsystem import CorpSearchSystem from modules.editdistance.normalized import \ NormalizedEditDistanceQueryToHandle,\ NormalizedEditDistanceQueryToDisplayName from modules.editdistance.lengths import \ LengthOfQuery, LengthOfHandle, LengthOfDisplayName from modules.editdistance.stopwords import...
layName, OccurrencesOfQueryInDescCaseInsensitive, CosineSimilarityDescriptionAndQuery, CosineSimilarityDescripti
onAndDDG, DescriptionLanguageModel, PostContentLanguageModel ])
ottodietz/rough-q1d
q1d/q1d_step.py
Python
gpl-3.0
2,411
0.014932
#!/usr/bin/env python from __future__ import division from math import * import numpy as np from numpy.fft import fft, fftshift, fftfreq def fermi(x, smearing): """Return Fermi function""" return 1./(1. + np.exp(x/smearing)) def step(x, delta, smearing): """Return smoothed step-function Fermi(x-Delta)-Fe...
) return wire def powerspectrum(data, dx): """Return power-spectrum of input signal""" powerspec = np.abs(fftshift(fft(data))*dx)**2 freq = 2.*pi*fftfreq(data.size, dx) return freq, powerspec def AGS(k, heights, delta, smearing): """Return roughness-height power spectrum W(k)""" N_module ...
exp(-1j*n*k*delta)*heights[n] for n in N_module ]) omega = np.sum(omega, axis=0) omega = np.abs(omega)**2 / heights.size return (1./delta * (2.*pi*smearing* np.sinh(k*pi*smearing)**(-1)*np.sin(k*delta/2.))**2) * omega def SGS(k, heights, delta, smearing): """Return roughness-height power sp...
ipernet/RatticWeb
ratticweb/context_processors.py
Python
gpl-2.0
1,262
0.001585
from cred.models import CredChangeQ from django.conf import settings from django.utils import timezone def base_template_reqs(request): cntx = { 'pageurl': request.path, 'LDAP_ENABLED': settings.LDAP_ENABLED, 'GOAUTH2_ENABLED': settings.GOAUTH2_ENABLED, 'EXPORT_ENABLED': not settin...
not (settings.LDAP_ENABLED and not settings.AUTH_LDAP_ALLOW_
PASSWORD_CHANGE), 'rattic_icon': 'rattic/img/rattic_icon_normal.png', 'rattic_logo': 'rattic/img/rattic_logo_normal.svg', } if settings.HELP_SYSTEM_FILES: cntx['helplinks'] = True else: cntx['helplinks'] = False if request.user.is_authenticated(): cntx['changeqc...
allisson/django-tiny-rest
testproject/blog/tests/test_views.py
Python
mit
10,142
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.test import TestCase from django.contrib.auth import get_user_model from django.core.urlresolvers import reverse import json from model_mommy import mommy from io import BytesIO from PIL import Image from tiny_rest.tests import Client import s...
ode()) self.assertEqual(data['title'], 'my post') self.assertEqual(data['slug'], 'my-post') self.assertEqual(data['body'], 'my body') self.assertEqual(data['user']['id'], self.user.pk)
self.assertEqual(response.status_code, status.HTTP_201_CREATED) def test_update(self): response = self.client.put(self.detail_url, {}) data = json.loads(response.content.decode()) self.assertEqual(data['error']['body'][0], 'This field is required.') self.assertEqual(data['error'...
sarojaerabelli/HVGS
CareerTinderServer/CareerTinder/migrations/0005_auto_20160918_0221.py
Python
mit
573
0
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2016-09-18 06:21 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies
= [ ('CareerTinder', '0004_auto_20160918_0152'), ] operations = [ migrations.RenameField( model_name='hiree', old_name='first_name', new_name='email', ), migrations.RenameField( model_name='hiree', old_name='last_name',...
w_name='name', ), ]
fjpena/sword-of-ianna-zx
python_src/ianna_score.py
Python
apache-2.0
6,072
0.049407
import pygame import time import scripts """ Score class Handles all the score area package: ianna """ class IannaScore(): def __init__ (self, buffer, screen, game_entities): self.score_image = pygame.image.load('artwork/marcador.png').convert() self.font = pygame.image.load('artwork/font.png').convert() ...
.append(pygame.image.load('artwork/marcador_armas_eclipse.png').convert()) self.weapons.append(pygame.image.load('artwork/marcador_armas_axe.png').convert()) self.weapons.append(pygame.image.load('artwork/marcador_armas_blade.png').convert()) self.first_object_in_inventory = 0 # We
have 64 chars, in ASCII order starting by BLANK (32) # There are some special chars, look at the font! for tile_x in range (0,32): rect = (tile_x*8, 0, 8, 8) self.chars.append(self.font.subsurface(rect)) for tile_x in range (0,32): rect = (tile_x*8, 8, 8, 8) s...
srjoglekar246/sympy
sympy/printing/tests/test_jscode.py
Python
bsd-3-clause
8,432
0.010911
from sympy.core import pi, oo, symbols, Function, Rational, Integer, GoldenRatio, EulerGamma, Catalan, Lambda, Dummy from sympy.functions import Piecewise, sin, cos, Abs, exp, ceiling, sqrt from sympy.utilities.pytest import raises from sympy.printing.jscode import JavascriptCodePrinter from sympy.utilities.lambdify im...
) j = Idx('j', n) k = Idx('k', o) l = Idx('l', p) s = ( 'for (var i=0; i<m; i++){\n' ' y[i] = 0;\n' '}\n' 'for (var i=0; i<m; i++){\n' ' for (var j=0; j<n; j++){\n' ' for (var k=0; k<o; k++){\n' ' for (var l=0; l<p; l++){\n' ' y[i] = y[i] + b[j*o*p + k*p + l]*a[i*n*o*p + j*o...
code_loops_addfactor(): from sympy.tensor import IndexedBase, Idx from sympy import symbols n, m, o, p = symbols('n m o p', integer=True) a = IndexedBase('a') b = IndexedBase('b') c = IndexedBase('c') y = IndexedBase('y') i = Idx('i', m) j = Idx('j', n) k = Idx('k', o) l = Id...
shuoli84/gevent_socketio2
socketio/__init__.py
Python
mit
583
0.003431
import logging log = logging.getLogger(__name__) def has_bin(arg): """ Helper function checks whether args contains binary data :param args: list | tuple | bytearray | dict :return: (bool) """ if type(arg)
is list or type(arg) is tuple: return reduce(lambda has_binary, item: has_binary or has_bin(item), arg, False) if type(arg) is bytearray or hasattr(arg, 'read'):
return True if type(arg) is dict: return reduce(lambda has_binary, item: has_binary or has_bin(item), [v for k, v in arg.items()], False) return False
allisson/python-vindi
setup.py
Python
mit
1,845
0
import codecs import os import re from setuptools import Command, find_packages, setup here = os.path.abspath(os.path.dirname(__file__)) version = "0.0.0" changes = os.path.join(here, "CHANGES.rst") match = r"^#*\s*(?P<version>[0-9]+\.[0-9]+(\.[0-9]+)?)$" with codecs.open(changes, encoding="utf-8") as changes: f...
raries", ], keywords=
"rest client http vindi", packages=find_packages(exclude=["docs", "tests*"]), setup_requires=["pytest-runner"], install_requires=install_requirements, tests_require=tests_requirements, cmdclass={"version": VersionCommand}, )
factorlibre/odoo-addons-cpo
purchase_compute_order_product_filter_season/models/__init__.py
Python
agpl-3.0
197
0
# -*- coding: utf-8 -*- # © 2016
FactorLibre - Hugo Santos <hugo.santos@factorlibre.com> # License AGPL-3.0 or later (http://w
ww.gnu.org/licenses/agpl.html). from . import computed_purchase_order
elfnor/sverchok
nodes/vector/interpolation_mk2.py
Python
gpl-3.0
7,301
0.003013
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distrib...
e that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th
e # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### import bisect i...
Fahrenholz/maat-analyzer
functions/debugging_functions.py
Python
gpl-3.0
537
0.005587
from functions import global_functions def debug_step_here(): ""
" Creates a Breakpoint when executed in debug-mode :return: """ if global_functions.get_config_key("debug"): try: input("Press any key to continue") except SyntaxError: pass def print_out_var(variable): """ Prints out a variable when executed in debug-m...
Tigge/trello-to-web
markdown_imaged.py
Python
mit
1,141
0.003506
import os.path import urllib.parse import requests import rfc6266 import settings import utilities from
markdown import Extension from markdown.inlinepatterns import ImagePattern, IMAGE_LINK_RE class ImageDownloadPattern(ImagePattern): def handleMatch(self, match): el = super(ImageDownloadPattern, self).handleMatch(match) urlparts = urllib.parse.urlparse(el.attrib["src"]) if urlparts.netloc...
()) response.raise_for_status() filename = rfc6266.parse_requests_response(response).filename_unsafe with open(os.path.join(settings.get("folder"), filename), "wb") as f: f.write(response.content) el.attrib["src"] = filename utilities.fix_i...
pidydx/grr
grr/checks/rsyslog_test.py
Python
apache-2.0
1,801
0.004442
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for rsyslog state checks.""" from grr.lib import flags from grr.lib import test_lib from grr.lib.checks import checks_test_lib from grr.parsers import config_file class RsyslogCheckTests(checks_test_lib.HostChe
ckTest): """Test the rsyslog checks.""" @classmethod def setUpClass(cls): cls.LoadCheck("rsyslog.yaml") cls.parser = config_file.RsyslogParser() def testLoggingAuthRemoteOK(self): chk_id = "CIS-LOGGING-AUTH-REMOTE" test_data = { "/etc/rsyslog.conf": "*.* @@tcp.example.com....
results) def testLoggingAuthRemoteFail(self): chk_id = "CIS-LOGGING-AUTH-REMOTE" test_data = {"/etc/rsyslog.conf": "*.* /var/log/messages"} host_data = self.GenFileData("LinuxRsyslogConfigs", test_data, self.parser) sym = "Missing attribute: No remote destination for auth logs." found = ["Expec...
PeytonXu/learn-python
cases/errbot/config.py
Python
mit
761
0.011827
import logging # This is a minimal configuration to get you started with the Text mode. # If you want to connect Errbot to chat services, checkout
# the options i
n the more complete config-template.py from here: # https://raw.githubusercontent.com/errbotio/errbot/master/errbot/config-template.py BACKEND = 'Text' # Errbot will start in text mode (console only mode) and will answer commands from there. BOT_DATA_DIR = r'D:\Work\Python\learn-python\cases\errbot\data' BOT_EXTRA_P...
wendlers/usherpa-pysherpa
setup.py
Python
lgpl-2.1
1,459
0.023304
#!/usr/bin/env python ## # This file is part of the uSherpa Python Library project # # Copyright (C) 2012 Stefan Wendler <sw@kaltpost.de> # # The uSherpa Python 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 Sof...
A. ## ''' uSherpa Python Library setup-script. To install this library use: sudo python setup.py install ''' from distutils.core import setup setup(name='pysherpa', version='0.1', description='uSherpa Python Library', long_description='Client library for Python to use MCU running uSherpa Firmware. Depend...
://www.usherpa.org/', license='LGPL 2.1', packages=['usherpa'], platforms=['Linux'], package_dir = {'': 'src'}, requires = ['serial(>=2.4)'] )
maurizi/otm-core
opentreemap/treemap/views/misc.py
Python
agpl-3.0
8,998
0
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import unicode_literals from __future__ import division import string import re import sass import json from django.utils.translation import ugettext as _ from django.core.
urlresolvers import reverse from django.conf import settings from django.contrib.gis.geos import Polygon from django.core.exceptions import ValidationError from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, get_object_or_404 from stormwater.models
import PolygonalMapFeature from treemap.models import User, Species, StaticPage, Instance, Boundary from treemap.plugin import get_viewable_instances_filter from treemap.lib.user import get_audits, get_audits_params from treemap.lib import COLOR_RE from treemap.lib.perms import map_feature_is_creatable from treemap....
robotic-ultrasound-image-system/ur5
build/ur5-master/universal_robot-kinetic-devel/ur_description/catkin_generated/pkg.installspace.context.pc.py
Python
apache-2.0
380
0
# generated from catkin/cmake/templat
e/pkg.context.pc.in CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else [] PROJECT_CATKIN_DEPENDS = "".replace(';', ' ') PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else [] PROJECT_NAME =
"ur_description" PROJECT_SPACE_DIR = "/home/us-robot/catkin_ws/install" PROJECT_VERSION = "1.2.0"
jjdmol/LOFAR
LCS/Tools/src/makeClass.py
Python
gpl-3.0
17,838
0.029432
#! /usr/bin/env python # Copyright (C) 2005 # ASTRON (Netherlands Institute for Radio Astr
onomy) # P.O.Box 2, 7990 AA Dwingeloo, The Netherlands # # This file is part of the LOFAR software suite. # The LOFAR software suite 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 Lice...
e that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with the LOFAR software suite. If not, s...
pelson/biggus
biggus/tests/unit/init/__init__.py
Python
gpl-3.0
882
0
# (C) British Crown Copyright 2016, Met Office # # This file is part of Biggus. # # Biggus is free software: you can redistribute it and/or modify it under # the terms of
the GNU Lesser General Public License as published by the # Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Biggus is distributed in the hope that it will be useful, # but WITHOU
T ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Biggus. If not, see <http://www.gnu.org/licenses/>. """Unit ...
endlessm/chromium-browser
tools/web_dev_style/presubmit_support.py
Python
bsd-3-clause
1,332
0.010511
# Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # fo
und in the LICENSE
file. import css_checker import html_checker import js_checker import resource_checker def IsResource(f): return f.LocalPath().endswith(('.html', '.css', '.js')) def CheckStyle(input_api, output_api, file_filter=lambda f: True): apis = input_api, output_api wrapped_filter = lambda f: file_filter(f) and IsR...
MikaelSchultz/dofiloop-sentinel
sentinel/manage.py
Python
mit
257
0
#!/usr/bin/env python import
os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sentinel.settings.local") from django.core.mana
gement import execute_from_command_line execute_from_command_line(sys.argv)
takwas/flask_app_template
template_app/forms.py
Python
mit
2,863
0.028292
# Extension imports from flask.ext.wtf import Form, RecaptchaField from flask_wtf.html5 import TelField, IntegerField from wtforms import StringField, PasswordField, BooleanField, SubmitField, TextAreaField, SelectField, DecimalField from wtforms.validators import Email, DataRequired, EqualTo #from flask_wtf.file imp...
ck-box: Subscribe submit_btn = SubmitField('Sign me up!') #
Button: Submit Form
MalloyPower/parsing-python
front-end/testsuite-python-lib/Python-3.2/Lib/distutils/tests/test_archive_util.py
Python
mit
7,249
0.001104
"""Tests for distutils.archive_util.""" __revision__ = "$Id: test_archive_util.py 86596 2010-11-20 19:04:17Z ezio.melotti $" import unittest import os import tarfile from os.path import splitdrive import warnings from distutils.archive_util import (check_archive_formats, make_tarball, ...
t_tarfi
le_vs_tar(self): tmpdir, tmpdir2, base_name = self._create_files() old_dir = os.getcwd() os.chdir(tmpdir) try: make_tarball(base_name, 'dist') finally: os.chdir(old_dir) # check if the compressed tarball was created tarball = base_name + ...
ryankanno/py-utilities
tests/fs/test_path_utilities.py
Python
mit
1,597
0
#!/usr/bin/env python # -*- coding: utf-8 -*- from nose.tools imp
ort ok_ import os from py_utilities.fs.path_utilities import expanded_abspath from py_utilities.fs.path_utilities import filename from py_utilities.fs.path_utilities import get_first_dir_path from py_utilities.fs.path_utilities import get_first_file_path import tempfile import unittest class TestPath(unittest.TestCas...
ome = os.environ["HOME"] ok_(expanded_abspath("~") == home) ok_(expanded_abspath("~/foo") == os.path.join(home, 'foo')) ok_(expanded_abspath("/foo") == "/foo") ok_(expanded_abspath("/foo/bar") == "/foo/bar") def test_filename(self): paths = ['/foo/bar/', '/foo/bar', 'foo/bar...
dmazzer/nors
remote/GrovePi/Software/Python/GrovePi_Hardware_Test.py
Python
mit
2,308
0.011698
#!/usr/bin/env python # # GrovePi Hardware Test # Connect Buzzer to Port D8 # Connect Button to Analog Port A0 # # The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.grovepi.com # # Have a question about this example? Ask on the forums here: http://www.dexteri...
HORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILIT
Y, 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 time import grovepi # Connect the Grove Button to Analog Port 0. button = 14 # This is the A0 pin. buzzer = 8 # This is the D8 pin. grovepi.pinMode...
hellhovnd/dentexchange
dentexchange/apps/libs/tests/haystack/test_get_indexes.py
Python
bsd-3-clause
1,159
0.001726
# -*- coding:utf-8 -*- import unittest import mock from ...haystack.utils import get_indexes class GetIndexesTestCase(unittest.TestCase): @mock.patch('libs.haystack.utils.connections') @mock.patch('libs.haystack.utils.connection_router.for_write') def test_get_indexes_should_yield_get_index( ...
for_write.return_value = [using] connection = mock.Mock() connections.__getitem__ = mock.MagicMock(return_value=connection) # action
returned_value = list(get_indexes(model_class)) # assert self.assertDictEqual(dict(models=[model_class]), for_write.call_args[1]) self.assertTupleEqual((using,), connections.__getitem__.call_args[0]) self.assertEqual(1, connection.get_unified_index.call_count) self.assertTupleE...
j2ali/FlightScraper
Scraper.py
Python
bsd-3-clause
1,950
0.007179
from bs4 import BeautifulSoup import helper from datetime import datetime import click import time import calendar #Example values #START_DATE = datetime(2014, 05, 15) #END_DATE = datetime(2015, 05, 15) #DAY_DELTA = 7 #TIMEOUT_SECONDS = 30 #Example Command #python Scraper.py 2014/05/25 2015/05/15 4 0 YYZ POS @click....
') @click.argument('day_delta') @click.argument('time_out') @click.argument('origin_airport') @click.argument('destination_airport') def find_flights(start_date, end_date, day_delta, time_out, origin_airport, destination_airport): start_date = datetime.strptime(start_date
, "%Y/%m/%d") end_date = datetime.strptime(end_date, "%Y/%m/%d") day_delta = int(day_delta) time_out = int(time_out) flight_dates = helper.generate_dates(start_date, end_date, day_delta) #There is a new output file for each run. #Use something like time.ctime(int("1284101485")) to get back dat...
agronick/WebServiceExample
smarterer/smarterer/wsgi.py
Python
gpl-2.0
395
0
""" WSGI config for smarterer project.
It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO
_SETTINGS_MODULE", "smarterer.settings") application = get_wsgi_application()
steventimberman/masterDebater
debate/migrations/0010_auto_20170808_2242.py
Python
mit
466
0
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-08-09 03:42 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('debate', '0009_auto_20170807_2329'), ] operat
ions = [ migrations.AlterField( model_name='debatetopic', name='timestamp', field=models.DateTimeField(auto_now_add=True), ),
]
openprocurement/openprocurement.edge
openprocurement/edge/tests/traversal.py
Python
apache-2.0
638
0.001567
# -*- coding: utf-8 -*- import unittest from mock import MagicMock, patch from mu
nch import munchify from openprocurement.edge.traversal import Root class TestTraversal(unittest.TestCase): def test_Root(self): request = munchify({'registry': {'db': 'database'}}) root = Root(request) self.assertEqual(root.request, request) self.assertEqual(root.db, request.regi...
suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestTraversal)) return suite if __name__ == '__main__': unittest.main(defaultTest='suite')
edx/xblock-lti-consumer
lti_consumer/lti_1p3/tests/extensions/rest_framework/test_authentication.py
Python
agpl-3.0
4,164
0.00024
""" Unit tests for LTI 1.3 consumer implementation """ from unittest.mock import MagicMock, patch import ddt from Cryptodome.PublicKey import RSA from django.test.testcases import TestCase from rest_framework import exceptions from lti_consumer.lti_1p3.consumer import LtiConsumer1p3 from lti_consumer.lti_1p3.extensi...
Mock Request that can be used to test the LTI auth. """ mock_request = MagicMock() # G
enerate a valid access token token = self.lti_consumer.key_handler.encode_and_sign( { "sub": self.lti_consumer.client_id, "iss": self.lti_consumer.iss, "scopes": "", }, expiration=3600 ) mock_request.headers = { ...
zappala/bene
examples/broadcast.py
Python
gpl-2.0
2,081
0.001922
from __future__ import print_function import sys sys.path.append('..') from src.sim import Sim from src.packet import Packet from networks.network import Network class BroadcastApp(object): def __init__(self, node): self.node = node def receive_packet(self, packet): print(Sim.scheduler.cu...
nodes.txt') # get nodes n1 = net.get_node('n1') n2 = net.get_node('n2') n3 = net.get_node('n3') n4 = net.get_node('n4') n5 = net.get_node('n5') # setup broadcast application b1 = BroadcastApp(n1) n1.add_protocol(protocol="broadcast",
handler=b1) b2 = BroadcastApp(n2) n2.add_protocol(protocol="broadcast", handler=b2) b3 = BroadcastApp(n3) n3.add_protocol(protocol="broadcast", handler=b3) b4 = BroadcastApp(n4) n4.add_protocol(protocol="broadcast", handler=b4) b5 = BroadcastApp(n5) n5.add_protocol(protocol="broadcast", ...
lichinka/pystella
coriolis_alla_stella.py
Python
bsd-2-clause
3,432
0.015443
import random # -------------------------------------------------------------- # DEFINITION of the Coriolis stencil object coriolis = Stencil ( ) # # add the U stage to the Coriolis stencil # uSlowTensStage = coriolis.addStage ( ) @uSlowTensStage.attachD
o def uStageDo (utens, v, fc): """ The 'Do' function of the U stage, with the Coriolis force directly applied: utens a STELLA data field, representing ???; v a STELLA data fiedl, representing ???; fc a scalar representing the force.- """ res = fc * average (v...
ncil # vSlowTensStage = coriolis.addStage ( ) @vSlowTensStage.attachDo (IJKRealField, IJKRealField, Scalar) def vStageDo (vtens, u, fc): """ The 'Do' function of the V stage, with the Coriolis force defined as a private function: vtens a STELLA data field, representing ???; u ...
jwittenbach/thunder
thunder/__init__.py
Python
apache-2.0
347
0.008646
from . import series fr
om . import images def _setup(): import logging logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) formatter = logging.Formatter('[%(name)s] %(levelname)s %(message)s') ch = logging.StreamHandler() ch.setFormatter(formatter) logger.addHandler(ch) _setup() __version__
= '1.1.1'
Lily-Ayta/aosc-os-abbs
extra-games/pingus/autobuild/overrides/usr/share/pingus/images/fonts/buildset.py
Python
gpl-2.0
155
0.006452
#!/usr/bin/env pytho
n imp
ort sys str = sys.stdin.read().decode('utf-8') characters = set(str) for c in characters: print c.encode('utf-8') # EOF #
CodyKochmann/battle_tested
battle_tested/beta/fuzz_planner.py
Python
mit
68
0.014706
from battle_te
sted.beta.input_type_combos import input_typ
e_combos
Hybrid-Cloud/cinder
cinder/tests/unit/api/contrib/test_quotas_classes.py
Python
apache-2.0
6,020
0
# Copyright 2013 Huawei Technologies Co., Ltd # 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 # # Unl...
ody(tenant_id=None)) def test_update_with_more_volume_types(self): volume_types.create(self.ctxt, 'fake_type_1') volume_types.create(self.ctxt, 'fake_type_2') body = {'quota_class_set': {'gigabytes_fake_type_1': 1111, 'volumes_fake_type_2': 2222}} ...
troller.update(self.req, fake.PROJECT_ID, body) self.assertDictMatch(make_response_body(ctxt=self.ctxt, quota_class=fake.PROJECT_ID, request_body=body, tenant_id=None),...
invitecomm/asterisk-ivr
pigeonhole/wardial.py
Python
gpl-3.0
3,694
0.004061
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim: set et sw=4 fenc=utf-8: # # Copyright 2016 INVITE Communications Co., Ltd. All Rights Reserved. # # 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 Founda...
port ConfigParser from datetime import date, datetime, timedelta import mysql.connector as mariadb def question(file, valid_digits): regexp = re.compile(r'[' + valid_digits + ']') res = agi.get_data(file, 20000, 1) if regexp.search(res) is not None: return res res = agi.get_data(file, 20...
not None: return res if not res: agi.hangup() settings = ConfigParser.RawConfigParser() settings.read('/etc/asterisk/res_config_mysql.conf') config = { 'user': settings.get('general', 'dbuser'), 'password': settings.get('general', 'dbpass'), 'host': settings.get('general', 'dbhost'...
Dronecode/MAVProxy
MAVProxy/modules/lib/mp_image.py
Python
gpl-3.0
20,342
0.00295
#!/usr/bin/env python from __future__ import print_function ''' display a image in a subprocess Andrew Tridgell June 2012 ''' import time from MAVProxy.modules.lib.wx_loader import wx import cv2 import numpy as np import warnings from MAVProxy.modules.lib import mp_util from MAVProxy.modules.lib import mp_widgets f...
can_drag = can_drag sel
f.mouse_events = mouse_events self.key_events = key_events self.auto_size = auto_size self.report_size_changes = report_size_changes self.menu = None self.popup_menu = None self.in_queue = multiproc.Queue() self.out_queue = multiproc.Queue() self.default...
dafrito/trac-mirror
tracopt/versioncontrol/svn/tests/__init__.py
Python
bsd-3-clause
731
0.002736
# -*- coding: utf-8 -*- # # Copyright (C) 2012-2013 Edgewall Software # All rights reserved. # # This software is licensed as d
escribed in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://trac.edgewall.org/wiki/TracLicense. # # This software consists of voluntary contributions made by many # individuals. For the exact contribution history, see the revision # history and l...
le at http://trac.edgewall.org/log/. import unittest from tracopt.versioncontrol.svn.tests import svn_fs def suite(): suite = unittest.TestSuite() suite.addTest(svn_fs.suite()) return suite if __name__ == '__main__': unittest.main(defaultTest='suite')
googleapis/python-recaptcha-enterprise
samples/snippets/migrate_site_key.py
Python
apache-2.0
1,870
0.001604
# Copyright 2021 Google Inc. All Rights Reserved. # # Licensed under the Apache
License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Li
cense is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # [START recaptcha_enterprise_migrate_site_key] from google.cloud import recaptchaenterprise_v1 fr...
Canpio/Paddle
python/paddle/fluid/tests/unittests/test_elementwise_pow_op.py
Python
apache-2.0
1,482
0
# Copyright (c) 2018 PaddlePaddle 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 appli...
type = "elementwise_pow" self.inputs = { 'X': np.random.rand(2, 3, 4).astype('float32'), 'Y': np.ra
ndom.rand(1).astype('float32') } self.outputs = {'Out': np.power(self.inputs['X'], self.inputs['Y'])} if __name__ == '__main__': unittest.main()
SmartcitySantiagoChile/onlineGPS
drawroute/views.py
Python
mit
422
0.018957
from django.http impor
t JsonResponse from django.shortcuts import render from django.views.generic import View # model #from drawroute.models import * # Create your views here. class MapHandler(View): '''This class manages the map where lines are drawn ''' def __init__(self): self.context={} def get(self, request): ...
xrloong/Xie
src/xie/graphics/stroke_path.py
Python
apache-2.0
24,937
0.0473
from .shape import Shape from .shape import Pane from .shape import mergeBoundary from .shape import offsetBoundary class StrokePath(Shape): def __init__(self, segments): self.segments = segments boundary = self.computeBoundary() self.pane = Pane(*boundary) def __eq__(self, other): return (isinstance(other...
t): l=parameterExpressionList assert len(l)==3 assert int(l[0]
)>0 assert int(l[1])>0 assert int(l[2])>0 return [int(l[0]), int(l[1]), int(l[2]), ] def computeStrokeSegments(self, paramList): w1=paramList[0] w2=paramList[1] h2=paramList[2] segments=[] segments.extend(self.getSegmentFactory().generateSegments_橫(w1)) segments.extend(self.getSegmentFactory().gene...
lmazuel/azure-sdk-for-python
azure-servicefabric/azure/servicefabric/models/fabric_error.py
Python
mit
1,580
0.000633
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Chang
es may cause incorrect behavior and will be lost if the code is # regenerated. # ------
-------------------------------------------------------------------- from msrest.serialization import Model from msrest.exceptions import HttpOperationError class FabricError(Model): """The REST API operations for Service Fabric return standard HTTP status codes. This type defines the additional information ...
jefftranter/udis
z80.py
Python
apache-2.0
32,759
0.094142
########################################################################## # # Processor specific code # CPU = "Z80" # Description = "Zilog 8-bit microprocessor." # DataWidth = 8 # 8-bit data # AddressWidth = 16 # 16-bit addresses # Maximum length of an instruction (for formatting purposes) maxLength = 4 # Leadin ...
: "hl,(${1:02X}{0:02X})", "hl,nn" : "hl,${1:02X}{0:02X}", "hl,sp" : "hl,sp", "i,a" : "i,a", "indaa,bc" : "(${1:02X}{0:02X}),bc", "indaa,de" : "(${1:02X}{0:02X}),de", "indaa,ix" : "
(${1:02X}{0:02X}),ix", "indaa,iy" : "(${1:02X}{0:02X}),iy", "indaa,sp" : "(${1:02X}{0:02X}),sp", "indbc,a" : "(bc),a", "indc,a" : "(c),a", "indc,b" : "(c),b", "indc,c" : "(c),c", "indc,d" : "(c),d", "indc,e" : "(c),e", "indc,h" : "(c),h", "indc,l" : "(c),l", "indde,a" : "(de),a", "...
isarlab-department-engineering/ros_dt_lane_follower
deprecated_nodes/old-lane-detection.py
Python
bsd-3-clause
9,077
0.048695
#!/usr/bin/env python from __future__ import print_function import roslib roslib.load_manifest('lane_detection') import rospy import sys from std_msgs.msg import Int32 import cv2 from sensor_msgs.msg import Image from cv_bridge import CvBridge, CvBridgeError from picamera import PiCamera from picamera.array import PiRG...
:rows,0:cols] = 255 street = cv2.bitwise_and(img,roi_mask) stop_roi_mask = np.zeros(gray.shape,dtype=np.uint8) stop_roi_mask[100:rows,150:250] = 255 right_roi_mask = np.zeros(gray.shape,dtype=np.uint8) right_r
oi_mask[rows/3:rows,220:360] = 255 right_roi = cv2.bitwise_and(img,img,right_roi_mask) left_roi_mask = np.zeros(gray.shape,dtype=np.uint8) left_roi_mask[rows/3:rows,0:180] = 255 left_roi = cv2.bitwise_and(img,img,left_roi_mask) # define range of color in HSV hsv = cv2.cvtColor(street,cv2.COLOR_BGR2HSV) sensit...
agoose77/hivesystem
dragonfly/scene/bound/moverel.py
Python
bsd-2-clause
978
0.002045
from bee import * from bee.segments import * import libcontext from libcontext.socketclasses import * from libcontext.pluginclasses import * def get_worker(name, xyz): class moverel(worker): """Relative movement along %s axis""" % xyz __beename__ = name moverel = antenna("push", "float") ...
axis = self.get_matrix().get_proxy("AxisSystem") axis.origin += getattr(axis, xyz) * self.movement axis.commit() trigger(movement, do_move) def set_get_matrix(self, function): self.g
et_matrix = function def place(self): libcontext.socket(("entity", "bound", "matrix"), socket_single_required(self.set_get_matrix)) return moverel moverelX = get_worker("moverelX", "x") moverelY = get_worker("moverelY", "y") moverelZ = get_worker("moverelZ", "z")
zhimin711/nova
nova/virt/imagecache.py
Python
apache-2.0
4,660
0.000215
# Copyright 2013 OpenStack Foundation # 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 requ...
ates.RESIZE_FINISH] def _get_base(self): """Returns the base directory of the cached images."""
raise NotImplementedError() def _list_running_instances(self, context, all_instances): """List running instances (on all compute nodes). This method returns a dictionary with the following keys: - used_images - image_popularity - instance_names "...
Idematica/django-oscar
oscar/apps/dashboard/orders/views.py
Python
bsd-3-clause
28,253
0.000035
import datetime from decimal import Decimal as D, InvalidOperation from django.contrib import messages from django.utils.translation import ugettext_lazy as _ from django.core.urlresolvers import reverse from django.core.exceptions import ObjectDoesNotExist from django.db.models.loading import get_model from django.db...
order.number}) return HttpResponseRedirect(url) return super(OrderListView, self).get(request, *args, **kwargs) def get_desc_context(self, data=None): # noqa (too complex (16)) """Update the title that describes the q
ueryset""" desc_ctx = { 'main_filter': _('All orders'), 'name_filter': '', 'title_filter': '', 'upc_filter': '', 'sku_filter': '', 'date_filter': '', 'voucher_filter': '', 'payment_filter': '', 'status_fi...
ROldford/tvregex
tests/experiments/json_test.py
Python
mit
261
0
import json SHOWNAMES_DICT = { "lipsyncb
attle": "Lip Sync Battle", "archer2009": "Archer (2009)", "thedailyshow": "The Daily Show", "atmidnight": "@midnig
ht" } with open("test_file.json", "w") as f: json.dump(SHOWNAMES_DICT, f, indent=4)
e1211205/pimouse_ros
scripts/buzzer4.py
Python
gpl-3.0
701
0.011412
#!/usr/bin/env python #encoding: utf8 import rospy, actionlib from std_msgs.msg import UInt16 from pimouse_ros.msg import MusicAction, MusicResult, MusicFeedback def write_freq(hz=0): bfile = "/dev/rtbuzzer0" try:
with open(bfile,"w") as f: f.write(str(hz) + "\n") except IOError: rospy.logerr("can't write to " + bfile) def recv_buzzer(data): write_freq(data.data) def exec_music(goal): pass if __name__ == '__main
__': rospy.init_node('buzzer') rospy.Subscriber("buzzer", UInt16, recv_buzzer) music = actionlib.SimpleActionServer('music', MusicAction, exec_music, False) music.start() rospy.on_shutdown(write_freq) rospy.spin()
rbian/avocado-vt
virttest/remote_commander/messenger.py
Python
gpl-2.0
7,889
0.000127
#!/usr/bin/env python ''' Created on Dec 6, 2013 :author: jzupka ''' import os import logging import select import cPickle import time import remote_interface import cStringIO import base64 class IOWrapper(object): """ Class encaptulates io opearation to be more consist in different implementations. (...
Write formated message to communication interface.
""" self.stdout.write(self.format_msg(data)) def _read_until_len(self, timeout=None): """ Deal with terminal interfaces... Read input until gets string contains " " and digits len(string) == 10 :param timeout: timeout of reading. """ data = "" ...
rlrs/deep-rl
dqn/ParallelAgent.py
Python
mit
2,448
0.003268
""" Experimental agent implementation running separate threads for emulation and GPU training. This is slightly (estimate ~20%) faster than the sequential implementation, but results might be different. Copyright 2016 Rasmus Larsen This software may be modified and distributed under the terms of the MIT license. See ...
ead(target=self.gpu_worker) gpu_2 = threading.Thread(target=self.gpu_worker) for i in xrange(int(self.train_start)): # wait for replay memory to fill self.next(random.randrange(self.emu.num_actions)) cpu.start() gpu_1.start() gpu_2.start() gpu_1.join()
gpu_2.join() return def test(self): self.testing = True time.sleep(0.5) # wait a bit for ALE worker to stop super(ParallelAgent, self).test() self.testing = False def ale_worker(self): """ Performs epsilon greedy action selection, updating the repla...
Endika/django
tests/update/tests.py
Python
bsd-3-clause
5,112
0.000196
from __future__ import unicode_literals from django.test import TestCase from .models import A, B, D, Bar, DataPoint, Foo, RelatedPoint class SimpleTest(TestCase): def setUp(self): self.a1 = A.objects.create() self.a2 = A.objects.create() for x in range(20): B.objects.create(...
(y=100) self.assertEqual(num_updated, 0) cnt = B.objects.filter(y=100).count() self.assertEqual(cnt, 0) def test_nonempty_update_with_inheritance(self)
: """ Test that update changes the right number of rows for an empty queryset when the update affects only a base table """ num_updated = self.a1.d_set.update(y=100) self.assertEqual(num_updated, 20) cnt = D.objects.filter(y=100).count() self.assertEqual(c...
emkailu/PAT3DEM
bin/p3convert.py
Python
mit
998
0.036072
#!/usr/bin/env python import os import sys import argparse import subprocess from shutil import copyfile def main(): progname = os.
path.basename(sys.argv[0]) usage = progname + """ [options] <*.png> convert -average *.png output.png In total 210 images, first average 15, then 14. """ args_def = {} parser = argparse.ArgumentParser() parser.add_argument("png", nargs='*', help="specify png to be averaged") args = parser.parse_args()
if len(sys.argv) == 1: print "usage: " + usage print "Please run '" + progname + " -h' for detailed options." sys.exit(1) # get default values for i in args_def: if args.__dict__[i] == None: args.__dict__[i] = args_def[i] # for i in xrange(14): cmd = ['convert', '-average'] + args.png[15*i:15*(i+1)] +...
campaignmonitor/createsend-python
samples/subscribers.py
Python
mit
411
0.004866
from createsend import * auth = { 'access_token': 'YOUR_ACCE
SS_TOKEN', 'refresh_token': 'YOUR_REFRESH_TOKEN' } listId = 'YOUR_LIST_ID' emailAddress = 'YOUR_SUBSCRIBER_EMAIL_ADDRESS' subscriber = Subscriber(auth, listId, emailAddress) # Get the details for a subscriber subscriberDetail = subscriber.get() for property, value in vars(subscriberDetail).items(): prin...
", value)
eduNEXT/edx-platform
common/lib/xmodule/xmodule/video_module/video_xfields.py
Python
agpl-3.0
9,242
0.004653
""" # lint-amnesty, pylint: disable=cyclic-import XFields for video module. """ import datetime from xblock.fields import Boolean, DateTime, Dict, Float, List, Scope, String from xmodule.fields import RelativeTime # Make '_' a no-op so we can scrape strings. Using lambda instead of # `django.utils.translation.ug...
y_name=_("Transcript Languages"), scope=Scope.settings, default={} ) transcript_language = String( help=_("Preferred language for transcript."), display_name=_("Preferred language for transcript"),
scope=Scope.preferences, default="en" ) transcript_download_format = String( help=_("Transcript file format to download by user."), scope=Scope.preferences, values=[ # Translators: This is a type of file used for captioning in the video player. {"display_n...