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
wittawatj/fsic-test
fsic/kernel.py
Python
mit
3,695
0.006766
"""Module containing kernel related classes""" __author__ = 'wittawat' from abc import ABCMeta, abstractmethod import numpy as np import scipy.signal as sig class Kernel(object): """Abstract class for kernels""" __metaclass__ = ABCMeta @abstractmethod def eval(self, X1, X2): """Evalute the k...
self, sigma2): assert sigma2 > 0, 'sigma2 must be > 0. Wa
s %s'%str(sigma2) self.sigma2 = sigma2 def eval(self, X1, X2): """ Evaluate the Gaussian kernel on the two 2d numpy arrays. Parameters ---------- X1 : n1 x d numpy array X2 : n2 x d numpy array Return ------ K : a n1 x n2 Gram matrix...
tkliuxing/bookspider
booksite/booksite/book/migrations/0010_auto_20171205_1436.py
Python
apache-2.0
1,020
0
# -*- coding: utf-8 -*- # Generated by Django 1.9.8 on 2017-12-05 06:36 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('book', '0009_auto_20171205_1432'), ] operations = [ migrations.AlterField( ...
fault='0', max_length=24), ), migrations.AlterField( model_name='bookpage', name='page_number', field=models.CharField(db_index=True,
max_length=24), ), migrations.AlterField( model_name='bookpage', name='prev_number', field=models.CharField(db_index=True, default='0', max_length=24), ), ]
muroi/sample-rpc
server.py
Python
apache-2.0
1,588
0.003778
#!/usr/bin/env python # coding: utf-8 fro
m oslo_config import cfg import oslo_messaging as messaging import oslo_messaging.rpc as rpc import logging import time import sys import eventlet eventlet.monkey_patch() logging.basicConfig() log = loggi
ng.getLogger() log.addHandler(logging.StreamHandler()) log.setLevel(logging.INFO) class ServerControlEndpoint(object): target = messaging.Target(namespace='congress-rpc', version='1.0') def __init__(self, server): self.server = server self.service_name = 'rpc_server' def stop(self, ctx)...
guyc/py-gaugette
gaugette/ssd1306.py
Python
lgpl-3.0
18,416
0.003475
#---------------------------------------------------------------------- # ssd1306.py from https://github.com/guyc/py-gaugette # ported by Guy Carpenter, Clearwater Software # # This library works with # Adafruit's 128x32 SPI monochrome OLED http://www.adafruit.com/products/661 # Adafruit's 128x64 SPI monochrome O...
es, # so both must divide evenly by 8 to avoid surprises. # # bitmap: instance of Bitmap # The number of rows in the bitmap must be a multiple of 8. # row: Starting row to write to - must be multiple of 8 # col: Starting col to write to. # col_count: Number of ...
# col_offset: column offset in buffer to write from # def display_block
mzdaniel/oh-mainline
vendor/packages/ghettoq/ghettoq/backends/mongodb.py
Python
agpl-3.0
1,263
0.000792
from pymongo.connection import Connection from pymongo.errors import OperationFailure from ghettoq.backends.base import BaseBackend from ghettoq.messaging import Empty __author__ = "Flavio [FlaPer87] Percoco Premoli <flaper87@flaper87.org>" DEFAULT_HOST = "127.0.0.1" DEF
AULT_PORT = 27017 class MongodbBackend(BaseBackend): def es
tablish_connection(self): self.port = self.port or DEFAULT_PORT self.host = self.host or DEFAULT_HOST self.connection = Connection(host=self.host, port=self.port) dbname = self.database if not dbname or dbname == "/": dbname = "ghettoq" self.database = getattr...
ohaz/amos-ss15-proj1
FlaskWebProject/storageinterface.py
Python
agpl-3.0
3,348
0.000299
from config import cloudplatform storage_adapter = None if cloudplatform == "google": import googlestorage storage_adapter = googlestorage elif cloudplatform == "aws": import awsstorage storage_adapter = awsstorage elif cloudplatform == "azure": from FlaskWebProject import azurestorage storage...
ID, filename, path) def download_file_to_text(bucketID, filename): """ Downloads file from container to text :param string bucketID: container name :param string filename: file to download :return string: text that go
t downloaded """ return storage_adapter.download_file_to_text(bucketID, filename) def get_download_url(bucketID, filename): """ Returns a download for specified file in container :param string bucketID: container name :param string filename: file to download :return string: the url to downloa...
shaggytwodope/qutebrowser
qutebrowser/completion/models/sortfilter.py
Python
gpl-3.0
6,490
0
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2014-2016 Florian Bruhin (The Compiler) <mail@qutebrowser.org> # # This file is part of qutebrowser. # # qutebrowser 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 S...
cat = self.index(i, 0) qtutils.ensure_valid(cat) if cat.model().hasChildren(cat): index = self.index(0, 0, cat) qtutils.ensure_valid(index) return index
return QModelIndex() def last_item(self): """Return the last item in the model.""" for i in range(self.rowCount() - 1, -1, -1): cat = self.index(i, 0) qtutils.ensure_valid(cat) if cat.model().hasChildren(cat): index = self.index(self.rowCount(ca...
internap/almanach
integration_tests/test_collector_volume_type.py
Python
apache-2.0
1,547
0.003232
# Copyright 2016 Internap. # # 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, so...
) self._wait_until_volume_type_is_created(volume_type_id=volume_type_id) volume_type_get_query = "{url}/volume_type/{volume_type_id}" response = self.almanachHelper.get(url=volume_type_get_query, volume_type_id=volume_type_id) assert_that(response.status_code, equal_to(200)) a...
ype_name}))
mbollmann/perceptron
test/test_feature_extractor.py
Python
mit
554
0.001805
# -*- coding: utf-8 -*- import pytest from mmb_perceptron.feature_extractor import FeatureE
xtractor class TestFeatureExtractor(object): """Tests for feature extractors. """ def test_context_size(self): f = FeatureExtractor() assert f.contex
t_size == (0, 0) f.context_size = (1, 2) assert f.context_size == (1, 2) with pytest.raises(ValueError): f.context_size = (-1, 1) with pytest.raises(ValueError): f.context_size = (1, -1) assert f.context_size == (1, 2)
thomasbarillot/DAQ
TOF/ADQAPI_python/FWDAQ/ADQ14_FWDAQ_streaming_example.py
Python
mit
10,179
0.010708
#!/usr/bin/env python3 # # Copyright 2015 Signal Processing Devices Sweden AB. All rights reserved. # # Description: ADQ14 FWDAQ streaming example # Documentation: # import numpy as np import ctypes as ct import matplotlib.pyplot as plt import sys import time import os sys.path.insert(1, os.path.dir...
hannels)() # Initiate pointers with allocated header buffers for ch,headerbufp in enumerate(headerbufp_list): headerbufp.contents = headerbuf_list[ch] # Create a second level pointer to each buffer pointer, # these will only be used to change the bufferp_list pointer values headerbufvp_list = [ct.cast(ct.poin...
erbufp_list[ch]), ct.POINTER(ct.c_void_p)) for ch in range(number_of_channels)] # Allocate length output variable samples_added = (4*ct.c_uint)() for ind in range(len(samples_added)): samples_added[ind] = 0 headers_added = (4*ct.c_uint)() for ind in range(len(headers_added)): headers_added[ind] = 0 ...
inuitwallet/plunge_android
main.py
Python
mit
10,983
0.004461
from kivy.core.window import Window from kivy.uix.textinput import TextInput __author__ = 'woolly_sammoth' from kivy.config import Config Config.set('graphics', 'borderless', '1') Config.set('graphics', 'resizable', '0') Config.set('graphics', 'fullscreen', '1') from kivy.app import App from kivy.uix.boxlayout impo...
self.is_min = False self.set_monitor() Window.fullscreen = 1 if self.config.getint('standard', 'show_disclaimer') == 1: Clock.schedule_once(self.show_disclaimer, 1) return self.root def show_disclaimer(self, dt): content = BoxLayout(orientat
ion='vertical') content.add_widget(TextInput(text=self.get_string('Disclaimer_Text'), size_hint=(1, 0.8), font_size=26, read_only=True, multiline=True, background_color=(0.13725, 0.12157, 0.12549, 1), foreground_color=(1, 1, 1, 1))) ...
andydandy74/ClockworkForDynamo
nodes/0.9.x/python/FamilyInstance.SubComponents.py
Python
mit
435
0.025287
import clr clr.AddReference('RevitAPI') from Autodesk.Revit.DB import * clr.AddReference("RevitNodes") import Revit clr.ImportExtensions(Revit.Elements) items = UnwrapElement(IN[0]) elementlist = list() for item in items: itemlist = list() try: for subcomp in item.GetSubComponentIds(): itemlist.append(item.Do...
ent(subcomp).ToDSType(True)) exce
pt: donothing = 1 elementlist.append(itemlist) OUT = elementlist
cmu-db/cmdbac
core/drivers/extract/extract.py
Python
apache-2.0
3,075
0.027642
import os, sys sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)) import utils import json from cmudbac.settings import * EXTRACT_WAIT_TIME = 0 def extract_forms(url, follow = "false", cookie_jar = None, filename = "forms.json"): utils.remove_file(os.path.join(os.path.dirname(__file__), ...
kie_jar_path)), EXTRACT_WAIT_TIME) with open(os.path.join(os.path.dirname(__file__), filename)) as json_urls: urls = json.load(json_urls) utils.remove_file(os.path.join(os.path.
dirname(__file__), filename)) return urls def extract_all_urls(url, filename): return extract_urls(url, "true", filename = filename) def extract_all_urls_with_cookie(url, cookie_jar, filename): return extract_urls(url, "true", cookie_jar, filename)
jdgwartney/meter-plugin-sdk-python
meterplugin/collector.py
Python
apache-2.0
2,041
0.00098
# # Copyright 2016 BMC Software, 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...
on of measurements :return: None """ while self.run_event.is_set(): self.collect() sleep(self.interval) def initialize(self): """ Default initialze method, sub-classes override as needed :return: None """ logger.debug('initial...
e()') def begin(self): """ Default start method, sub-classes override if needed to be signalled before running :return: """ logger.debug('start()') def collect(self): """ Default collection method, sub-classes need to override to do anything usef...
QInfer/python-qinfer
src/qinfer/tomography/__init__.py
Python
bsd-3-clause
251
0
from __fu
ture__ import absolute_import from qinfer.tomography.distributions import * from qinfer.tomography.models import * from qinfer.tomography.plotting_tools import * from qinfer.tomography.bases import * from qinfer.tomography.expdesign
import *
Stanford-Online/edx-platform
cms/djangoapps/contentstore/management/commands/migrate_transcripts.py
Python
agpl-3.0
4,653
0.003224
""" Command to migrate transcripts to django storage. """ import logging from django.core.management import BaseCommand, CommandError from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import CourseKey from opaque_keys.edx.locator import CourseLocator from cms.djangoapps.contentstore.tasks import ( ...
tMigrationSetting from xmodule.modulestore.django import modulestore log = logging.getLogger(__name__) class Command(BaseCommand): """ Example usage: $ ./manage.py cms migrate_transcripts --all-courses --force-update --commit $ ./manage.py cms migrate_transcripts --course-id 'Course1' --cours...
ripts --from-settings """ help = 'Migrates transcripts to S3 for one or more courses.' def add_arguments(self, parser): """ Add arguments to the command parser. """ parser.add_argument( '--course-id', '--course_id', dest='course_ids', acti...
openearth/delft3d-gt-server
delft3dworker/migrations/0008_delft3dworker_info.py
Python
gpl-3.0
512
0
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-02-04 10:47 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("delft3d
worker", "0007_delft3dworker_workerid"), ] operations = [ migrations.AddField( model_name="delft3dworker", name="info"
, field=models.CharField(default="", max_length=256), preserve_default=False, ), ]
apdjustino/DRCOG_Urbansim
src/opus_gui/main/views/ui_list_editor.py
Python
agpl-3.0
3,680
0.002989
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file '/Users/ckla/Documents/workspace/opus_trunk/opus_gui/main/views/list_editor.ui' # # Created: Sun May 10 00:57:43 2009 # by: PyQt4 UI code generator 4.4.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore,...
self.tb_change.setText(QtGui.QApplication.translate("ListEditor", "=", None, QtGui.QApplication.UnicodeUTF8)) self.tb_add.setText(QtGui.QApplication.translate("Lis
tEditor", "+", None, QtGui.QApplication.UnicodeUTF8))
markwal/octoflashsailfish
octoprint_flashsailfish/__init__.py
Python
gpl-3.0
4,023
0.027591
# coding=utf-8 from __future__ import absolute_import import octoprint.plugin from octoprint.server.util.flask import restricted_access from octoprint.server import admin_permission from octoprint.plugin import BlueprintPlugin import flask from flask import request, make_response import requests import xmltodict cl...
info(self, *args, **kwargs): return self._firmware_info() @BlueprintPlugin.route("/refresh_firmware_info", methods=["POST"]) @restricted_access @admin_permission.require(403) def refresh_firmware_info(self, *args, **kwargs): if not request.json is None and "url" in request.json: self._settings.set(["url"],...
try: self.xml = requests.get(url) except: self._logger.exception("Unable to retrieve firmware information from {0}".format(url)) return make_response("Unable to retrieve firmware information from {0}".format(url), 400) try: self.firmware_info = xmltodict.parse(self.xml.text) except: self._...
HopkinsIDD/EpiForecastStatMech
epi_forecast_stat_mech/__init__.py
Python
apache-2.0
375
0.002667
from .intensity_family import IntensityFamily from . import viboud_chowell from .viboud_chowell impor
t ViboudChowellFamily from . import gaussian from .gaussian import GaussianFamily from . import soft_laplace from .soft_laplace import SoftLaplaceFamily from
.high_level import * from . import constants from . import data_model from . import sir_sim from . import sparse
vdloo/raptiformica
tests/unit/raptiformica/utils/test_list_all_files_in_directory.py
Python
mit
1,134
0.000882
from raptiformica.utils import list_all_files_in_directory from tests.testcase import TestCase class TestListAllFilesInDirector
y(TestCase): def setUp(self): self.walk = self.set_up_patch('raptiformica.utils.walk') self.walk.return_value = [ ('/tmp/a/directory', ['dir'], ['file.txt', 'file2.txt']), ('/tmp/a/directory/dir', ['dir2'], ['file3.txt']), ('/tmp/a/directory/dir/dir2', [], ['file5...
t_list_all_files_in_directory_lists_all_files_in_directory_walks_path(self): list_all_files_in_directory('/tmp/a/directory') self.walk.assert_called_once_with('/tmp/a/directory') def test_list_all_files_in_directory_returns_all_files(self): ret = list_all_files_in_directory('/tmp/a/directo...
calexil/FightstickDisplay
pyglet/libs/win32/constants.py
Python
gpl-3.0
122,448
0.003569
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # Copyright (c) 2008-2021 pyglet contributors # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the follo...
HE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LO...
, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. P # From WinGDI.h PFD_TYPE_RGBA = 0 PF...
deggis/weekview
utils/data_importer.py
Python
mit
2,256
0.009309
#!/usr/bin/env python import os import datetime os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' from weekview.models import EventCategory, Event from django.contrib.auth.models import User def get_categories(filename, username): """Reads categories from txt. If some category is missing, it's added. ...
cat.color = "ffff00" cat.description = "[Generated]" cat.save() catdict[name.lower()] = cat return catdict def parse_date(str): datestr, timestr = str.split(' ') year,month,day = datestr.split('.') hour,minute = timestr.split(':') try: ...
atestring: '"+str+"', got: "+inst.__str__() def get_user(username): return User.objects.get(username__iexact=username) def import_file(filename, username): catdict = get_categories(filename, username) user = get_user(username) file = open(filename) print """Beginning to import data. All needed cat...
adfernandes/pcp
src/pmdas/bpftrace/bpftrace/cluster.py
Python
lgpl-2.1
9,225
0.003577
from typing import Dict import re from pcp.pmda import PMDA, pmdaMetric from pcp.pmapi import pmUnits import cpmapi as c_api from .models import Script, MetricType, VariableDefinition, Logger from .service import BPFtraceService from .uncached_indom import UncachedIndom class Consts: class Script: """it...
trace_service.refresh_script(self.script.script_id)
if not script: return self.script = script # refresh instance domains for var_name, var_def in self.script.variables.items(): # parser found variable definition in script, # but maybe variable doesn't exist in bpftrace output due to an error if no...
trangnm58/idrec
localization_cnn/create_ground_truth.py
Python
mit
5,533
0.031448
import cv2 import numpy as np import os from math import sqrt from constants import ( GROUND_TRUTH, RAWDATA_FOLDER) FONT = cv2.FONT_HERSHEY_SIMPLEX WINDOW_NAME = "Labeling" CTRL_PT_RADIUS = 10 class Boundary: def __init__(self, width, height): self.top = height self.right = width self.bottom = 0 self.lef...
if len(self.points) == 0: self.in_use = False def draw(self, img, debug=True): color = (0,0,255) if debug else (255,255,255) pts = [] for point in self.points: if debug: point.draw(img) pts.append([point.x, point.y]) cv2.polylines(img, np.array([pts]), False, color) class Scene
Mode: ADD_POINT = "ADD_POINT" ADD_MARKING = "ADD_MARKING" EDIT_POINT = "EDIT_POINT" DELETE_POINT = "DELETE_POINT" class Scene: def __init__(self, width, height, frame_idx): self.frame_idx = frame_idx self.mode = SceneMode.ADD_MARKING self.points = [] self.markings = [] self.boundary = Boundary(width, h...
ldotlopez/eina
toys/clutter-ui.py
Python
gpl-3.0
9,266
0.041658
#!/usr/bin/python import os import sys import urllib from gi.repository import Clutter, ClutterX11, Mx, Lomo, GObject, GLib class Cover(Clutter.Box): __gtype_name__ = 'GlosseCover' # # Member, setter and getter for the 'lomo' property # def _get_lomo_player_prop(self): return self._lomo_player_prop def _set...
lomo = None _controls = None _cover = None def _set_lomo(self, lomo): self._lomo = lomo d = { 'controls' : self._controls
, 'cover' : self._cover } for widget in (self._cover, self._controls): if widget: widget.set_property('lomo', lomo) def _get_lomo(self): return self._lomo lomo = GObject.property(type = Lomo.Player, setter = _set_lomo, getter = _get_lomo) def __init__(self, uris): Clutter.Stage.__init__(self, us...
nizhikebinesi/code_problems_python
stepik/programming_on_python/3.4/task_2.py
Python
gpl-2.0
417
0.004796
import sys import math # dataset_3363_3 name = input().strip() + ".txt" lines = '' with open(name, 'r') as r: for line in r: lines += line.strip() + " " string = [i.lower() for i in lines.split()] from collections import Counter result = Counter(string).most_common(1)[0] #print(result) output
= "output_2.txt" with open(output, 'w') as out: out.write("{} {}\n".form
at(result[0], result[1]))
borsboom/babal
src/JGLBabalCanvas.py
Python
gpl-2.0
3,751
0.004799
import time from java.lang import Thread, Runnable from java.awt import Canvas, Dimension from java.awt.event import KeyListener, KeyEvent, ComponentListener from java.awt.image import MemoryImageSource from synchronize import make_synchronized import jgl.GL import jgl.GLU import jgl.GLUT from Game import Game import ...
self.game.begin_accel() elif code == KeyEvent.VK_DOWN: self.game.begin_decel() elif code == KeyEvent.VK_SPACE: self.game.begin_jump() keyPressed = make_synchronized(keyPressed) def keyReleased(self, e): code = e.getKeyCode() if code == KeyEvent.VK_LEF...
d_left() elif code == KeyEvent.VK_RIGHT: self.game.end_right() elif code == KeyEvent.VK_UP: self.game.end_accel() elif code == KeyEvent.VK_DOWN: self.game.end_decel() elif code == KeyEvent.VK_SPACE: self.game.end_jump() keyReleased = ma...
ijat/Hotspot-PUTRA-Auto-login
PyInstaller-3.2/tests/functional/test_import.py
Python
gpl-3.0
16,563
0.001691
# -*- coding: utf-8 -*- #----------------------------------------------------------------------------- # Copyright (c) 2005-2016, PyInstaller Development Team. # # Distributed under the
terms of the GNU General Public License with exception # for distributing bootloader. # # The full license is in the file COPYING.txt, distributed with this software. #---------------------------
-------------------------------------------------- import os import pytest import glob import ctypes, ctypes.util from PyInstaller.compat import is_darwin from PyInstaller.utils.tests import skipif, importorskip, \ skipif_notwin, xfail, is_py2 # :todo: find a way to get this from `conftest` or such # Directory wi...
RyanYoung25/tensorflow
tensorflow/examples/tutorials/word2vec/word2vec_basic.py
Python
apache-2.0
8,773
0.011399
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
ion.run() _, loss_val = session.run([optimizer, loss], feed_dict=feed_dict) average_loss += loss_val if step % 2000 == 0: if step > 0: average_loss /= 2000 # The average loss is an estimate of
the loss over the last 2000 batches. print("Average loss at step ", step, ": ", average_loss) average_loss = 0 # Note that this is expensive (~20% slowdown if computed every 500 steps) if step % 10000 == 0: sim = similarity.eval() for i in xrange(valid_size): valid_word = revers...
Himon-SYNCRAFT/taskplus
tests/core/actions/get_role_details/test_get_role_details_action.py
Python
bsd-3-clause
2,317
0
from unittest import mock from taskplus.core.actions import GetRoleDetailsAction, GetRoleDetailsRequest from taskplus.core.domain import UserRole from taskplus.core.shared.response import ResponseFailure def test_get_role_details_action(): role = mock.Mock() role = UserRole(name='admin', id=1) roles_repo...
METER_ERRO
R, 'message': 'role_id: is required' } def test_get_role_details_action_handles_generic_error(): error_message = 'Error!!!' roles_repo = mock.Mock() roles_repo.one.side_effect = Exception(error_message) request = GetRoleDetailsRequest(role_id=1) action = GetRoleDetailsAction(roles_rep...
antoinecarme/pyaf
tests/artificial/transf_Difference/trend_ConstantTrend/cycle_30/ar_12/test_artificial_32_Difference_ConstantTrend_30_12_0.py
Python
bsd-3-clause
269
0.085502
import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artifi
cial_da
taset as art art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "ConstantTrend", cycle_length = 30, transform = "Difference", sigma = 0.0, exog_count = 0, ar_order = 12);
adamnew123456/spc
spc/require_processor.py
Python
mit
9,398
0.002128
""" This is meant for loading the definitions from an external file. """ import os.path from .backend import EmptyBackend from .driver import Driver from .errors import CompilerError from .lexer import Lexer from . import symbols from . import types # Since a file isn't going to change in the middle of our run, there...
eturn (name in self.context.types and self.context.types.is_visible(name)) def _platform(self): """
Returns the (OS, architecture) pair of the underlying backend. """ return self.real_backend._platform() def update_position(self, line, col): """ Updates the processor with the current location in the input file. """ self.line = line self.col = col ...
fvpolpeta/devide.johannes
extra/soappy-cvp/SOAPpy/Types.py
Python
bsd-3-clause
51,870
0.009273
""" ################################################################################ # Copyright (c) 2003, Pfizer # Copyright (c) 2001, Cayce Ullman. # Copyright (c) 2001, Brian Matthews. # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provid...
alid namespace for type %s" % self._type class voidType(anyType): pass class stringType(anyType): def _checkValueSpace(self, data): if data == None: raise ValueError, "must supply initial %s value" % self._type if type(data) not in (StringType, UnicodeType): raise Attr...
_type return data class untypedType(stringType): def __init__(self, data = None, name = None, attrs = None): stringType.__init__(self, data, name, 0, attrs) class IDType(stringType): pass class NCNameType(stringType): pass class NameType(stringType): pass class ENTITYType(stringType): pass class ...
mtsgrd/PynamoDB2
pynamodb/connection/table.py
Python
mit
7,391
0.000271
""" PynamoDB Connection classes ~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ from .base import Connection class TableConnection(object): """ A higher level abstraction over botocore """ def __init__(self, table_name, region=None, host=None): self._hash_keyname = None self._range_keyname = None ...
return self.connectio
n.create_table( self.table_name, attribute_definitions=attribute_definitions, key_schema=key_schema, read_capacity_units=read_capacity_units, write_capacity_units=write_capacity_units, global_secondary_indexes=global_secondary_indexes, ...
702nADOS/sumo
tools/import/vissim/convert_detectors2SUMO.py
Python
gpl-3.0
13,776
0.000363
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @file convert_detectors2SUMO.py @author Lukas Grohmann <Lukas.Grohmann@ait.ac.at> @date Aug 14 2015 @version $Id: convert_detectors2SUMO.py 22608 2017-01-17 06:28:54Z behrisch $ Parses induction loops and travel time measurements from a VISSIM .inpx file and wr...
, "ind_out.xml") ind_loop.setAttribute("freq", "900") root.appendChild(ind_loop) for det in travel_time_tab: travel_time = result_doc.createElement("entryExitDetector") travel_time.setAttribute("id", det["no"]
) travel_time.setAttribute("freq", "900") travel_time.setAttribute("file", "time_out.xml") start_edge = [edge for edge in edge_tab if edge["id"] == det["startLink"]] if len(start_edge) > 0: start_point = get_detector_coords_from_link(start_edge[0]["id"]...
basicworld/py_structure
chap6_haffman/bin_tnode.py
Python
mit
3,231
0.003391
# -*- coding: utf-8 -*- """ 二叉树节点类 """ import sys class BinTNode(object): def __init__(self, dat, left=None, right=None): self.data = dat self.left = left self.right = right def count_BinTNode(t): """统计二叉树的节点 @t 一颗二叉树""" if t is None: return 0 else: return 1...
yield t.data stack.append(t.right) t = t.left t = stack.pop() def postorder_non_rec(t, proc): """非递归的后根序遍历""" stack = [] while t is not None or stack: while t is not None: stack.append(t) t = t.left if t.left is not None else t.right ...
roc): """后根序遍历 wlfei自定义""" if t: if t.left: postorder_wlfei(t.left, proc) if t.right: postorder_wlfei(t.right, proc) proc(t.data) def sum_BinTNode(t): """ 二叉树节点求和 """ if t is None: return 0 else: return t.data + sum_BinTNod...
sidzan/netforce
netforce_terminal/netforce_terminal/field_char.py
Python
mit
2,609
0.022231
# Copyright (c) 2012-2015 Netforce Co. Ltd. # # 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, publ...
def focus(self): val=self.data.get(self.name) or "" self.win.clear() self.win.addstr(0,0,"%s."%self.key,curses.A_BOLD|curses.color_pair(2)) self.win.addstr(0,3,"Enter %s: %s"%(self.string,val)) curses.curs_set(1) val="" while True: c=self.win.getc...
elif c==10: self.data[self.name]=val return elif curses.ascii.isprint(c): if len(val)<40: val+=chr(c) elif c==curses.KEY_BACKSPACE or c==curses.KEY_DC or c==127: # XXX val=val[:-1] self.wi...
skuda/client-python
kubernetes/test/test_v1beta1_subject_access_review_status.py
Python
apache-2.0
999
0.004004
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.6.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys im...
sReviewStatus(self): """ Test V1beta1SubjectAccessReviewStatus """ model = kubernetes.
client.models.v1beta1_subject_access_review_status.V1beta1SubjectAccessReviewStatus() if __name__ == '__main__': unittest.main()
ESOedX/edx-platform
openedx/core/djangoapps/video_pipeline/migrations/0002_auto_20171114_0704.py
Python
agpl-3.0
837
0.002389
# -*- coding: utf-8 -*- from __future__ import unicode_literals from __future__ import absolute_import from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('video_pipeline', '0001_initial'), ] operat
ions = [ migrations.AddField( model_name='videopipelineintegration', name='client_name', field=models.CharField(default=b'VEDA-Prod', help_text='Oauth client name of video pipeline service.', max_length=100), ), migrations.AlterField( model_name='v...
deo Pipeline Integration, e.g. veda_service_user.', max_length=100), ), ]
filipp/Servo
servo/views/device.py
Python
bsd-2-clause
20,045
0.001846
# -*- coding: utf-8 -*- # Copyright (c) 2013, First Party Software # All rights reserved. # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, # t...
init': if request.method == 'POST': from gsxws import diagn
ostics order = request.POST.get('order') order = device.order_set.get(pk=order) email = request.POST.get('email') diag = diagnostics.Diagnostics(serialNumber=device.sn) diag.emailAddress = email diag.shipTo = order.location.gsx_shipto ...
Sumith1896/sympy
sympy/printing/ccode.py
Python
bsd-3-clause
12,886
0.001009
""" C code printer The CCodePrinter converts single sympy expressions into single C expressions, using the functions defined in math.h where possible. A complete code generator, which uses ccode extensively, can be found in sympy.utilities.codegen. The codegen module can be used to generate complete source code files...
"}") return "\n".join(lines) else: # The piecewise was used in an expression, need to do inline
# operators. This has the downside that inline operators will # not work for statements that span multiple lines (Matrix or # Indexed expressions). ecpairs = ["((%s) ? (\n%s\n)\n" % (self._print(c), self._print(e)) for e, c in expr.args[:-1]] las...
potash/scikit-learn
sklearn/tests/test_pipeline.py
Python
bsd-3-clause
24,571
0
""" Test the pipeline module. """ import numpy as np from scipy import sparse from sklearn.externals.six.moves import zip from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_raises_regex from sklearn.utils.testing import assert_raise_message from sklearn.utils.testing import assert...
urn self class NoInvTransf(NoTrans): def transform(self, X, y=None): return X class Transf(NoInvTransf): def transform(self, X, y=None): return X def inverse_transform(self, X): return X class Mult(BaseEstimator): def __init__(self, mult=1): self.mult = mult d...
urn np.asarray(X) / self.mult def predict(self, X): return (np.asarray(X) * self.mult).sum(axis=1) predict_proba = predict_log_proba = decision_function = predict def score(self, X, y=None): return np.sum(X) class FitParamT(BaseEstimator): """Mock classifier """ def __init_...
AutorestCI/azure-sdk-for-python
azure-batch/azure/batch/models/cloud_job.py
Python
mit
9,338
0.001071
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
erminated
or disabled by some other means. terminateJob - terminate the job. The job's terminateReason is set to 'AllTasksComplete'. The default is noAction. Possible values include: 'noAction', 'terminateJob' :type on_all_tasks_complete: str or ~azure.batch.models.OnAllTasksComplete :param on_task_failure...
axtl/cryptools
doc/conf.py
Python
mit
8,120
0.006034
# -*- coding: utf-8 -*- # # cryptools documentation build configuration file, created by # sphinx-quickstart on Wed Mar 27 03:23:33 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # A...
------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctes...
es_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'cryptools' copyright = u'2013, xorbyte' # The version info for th...
joelagnel/trappy
trappy/plotter/ILinePlot.py
Python
apache-2.0
11,149
0.000718
# Copyright 2015-2017 ARM Limited # # 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...
ngle graph :type concat: bool :param permute: Draw one plot for each of the traces specified :type permute: bool :param fill: Fill the area under the plots :type fill: bool :param fill_alpha: Opacity of filled area under the plots. Implies fill=True. :type fill_alpha: float :...
ple representing the upper and lower xlimits :type xlim: tuple :param ylim: A tuple representing the upper and lower ylimits :type ylim: tuple :param drawstyle: Set the drawstyle to a matplotlib compatible drawing style. .. note:: Only "steps-post" is supported as a valid...
DeveloperMal/wger
wger/gym/managers.py
Python
agpl-3.0
2,069
0
# -*- coding: utf-8 -*- # This file is part of wger Workout Manager. # # wger Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any ...
Gyms ''' def
get_members(self, gym_pk): ''' Returns all members for this gym (i.e non-admin ones) ''' perm_gym = Permission.objects.get(codename='manage_gym') perm_gyms = Permission.objects.get(codename='manage_gyms') perm_trainer = Permission.objects.get(codename='gym_trainer') ...
aitoralmeida/geo-lak
LAK_2014/LAK_2014/wsgi.py
Python
gpl-2.0
1,138
0.000879
""" WSGI config for LAK_2014 project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi``
commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the D
jango one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "LAK_2014.settings") # This application object is used by any WSGI server configured to use this # file. This inclu...
cmap/cmapPy
cmapPy/clue_api_client/clue_api_client.py
Python
bsd-3-clause
3,549
0.00479
import requests import logging import cmapPy.clue_api_client.setup_logger as setup_logger import json __authors__ = "David L. Lahr" __email__ = "dlahr@broadinstitute.org" logger = logging.getLogger(setup_logger.LOGGER_NAME) class ClueApiClient(object): """Basic class for running queries against CLUE api ""...
able from CLUE account Returns: """ self.base_url = base_url self.headers = {"user_key":user_key} def run_filter_query(self, resource_name, filter_clause): """run a query (get) against the CLUE api, using the API and user key fields of self and the fitler_clause provided ...
ilter to pass to API to; uses loopback specification Returns: list of dictionaries containing the results of the query """ url = self.base_url + "/" + resource_name params = {"filter":json.dumps(filter_clause)} r = requests.get(url, headers=self.headers, params=params) ...
Gweylorth/PyCubic
g62cub.py
Python
gpl-3.0
4,690
0.008316
#!/usr/bin/python #-*- coding:utf-8 -*- """G6 to CUB file(s) conversion tool Usage: g62cub FILE [FILE]... [DEST] FILE can either be a G6 file or a ZIP containing G6 files. DEST, if present, specifies the path where to save the converted file(s). Beware, DEST must be present if there are multiple FILE. """ import r...
in a tempFile file tempFile = tempfile.NamedTemporaryFile() tempFile.readline() subprocess.call("showg " + "\"" +
g6_file.name + "\" " + tempFile.name, shell = True) # Look for the order of the graph in the file # Typically, will match "Graph X, order N." and capture N for line in tempFile : matchObj = re.match(r'^.+,\s\D+\s(\d+).\s$', line) if matchObj : order = int(matchObj.group(1)); ...
davgibbs/euros-france
apps/manage.py
Python
gpl-3.0
254
0
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefa
ult("DJANGO_SETTINGS_MODULE", "eurosfrance.settings") from django.core.management import execute_from_comma
nd_line execute_from_command_line(sys.argv)
simonw/djng
example_template.py
Python
bsd-2-clause
320
0.009375
import djng, os, datetime djng.template.configure( os.path.join(os.path.dirname(__file__), 'example_templates') ) def index(request): retur
n djng.TemplateResponse(request, 'example.html', { 'time': str(datetime.datetime.now()), }) if __name__ == '__main__': djng.serve(index, '0.0.0.0', 888
8)
diego0020/va_course_2015
SVM/svm_gui.py
Python
mit
11,180
0.002504
""" ========== Libsvm GUI ========== A simple graphical frontend for Libsvm mainly intended for didactic purposes. You can create data points by point and click and visualize the decision region induced by different kernels and parameter settings. To create positive examples click the left mouse button; to create neg...
train[:, 0:2] y = train[:, 2] C = float(self.complexity.get()) gamma = float(self.gamma.get()) coef0 = float(self.coef0.get()) degree = int(self.degree.get()) kernel_map = {0: "linear", 1: "rbf", 2: "poly"} if len(np.unique(y)) == 1: clf = svm.OneClas...
gamma=gamma, coef0=coef0, degree=degree) clf.fit(X) else: clf = svm.SVC(kernel=kernel_map[self.kernel.get()], C=C, gamma=gamma, coef0=coef0, degree=degree) clf.fit(X, y) if hasattr(clf, 'score'): print ("Accuracy:" % (cl...
alphageek-xyz/site
tests/test_middleware.py
Python
bsd-3-clause
1,350
0.000741
from django.http import HttpResponse from django.urls import reverse from django.utils.decorators import decorator_from_middleware from django.test import ( TestCase, RequestFactory, modify_settings, override_settings, ) from headers.middleware import ( MultipleProxyMiddleware, ViaHeaderMiddlewa...
del(req.META['HTTP_X_FORWARDED_SERVER']) req.META['HTTP_X_FORWARDED_FOR'] += ',Foo' req.META['SERVER_SOFTWARE'] = 'foo/1.1' viawrap = decorator_from_middleware(ViaHeaderMiddleware) mulwrap = decorator_from_middleware(MultipleProxyMiddleware) viawrap(mulwrap(goodview))(re...
s = self.client.get( reverse('contact'), CONTENT_LENGTH=123 ) self.assertEqual(200, res.status_code) self.assertFalse(res.has_header('ETag'))
vicamo/pcsc-lite-android
UnitaryTests/control_get_firmware.py
Python
bsd-3-clause
1,904
0.001576
#! /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...
areID'] print " Firmware:", frimware
except KeyError: print " PCSCv2_PART10_PROPERTY_sFirmwareID not supported"
kmod/icbd
icbd/compiler/type_conversion.py
Python
mit
10,551
0.002843
import os import sys from icbd.type_analyzer import type_system, type_checker, builtins from . import compiler_types from .code_emitter import CodeEmitter class InferredTypeOutput(object): def __init__(self, fn, pythonpath=[]): self._made_classes = {} fn = os.path.abspath(fn) e = type_che...
rn compiler
_types.TupleMT.make_tuple(elt_types) if t.cls is builtins.SetClass: assert len(t.unions) == 1 elt_type = self._make_type(t.unions[0], to_initialize) return compiler_types.SetMT.make_set(elt_type) if t.cls is builtins.DequeClass: ass...
toobaz/pandas
pandas/core/indexes/datetimes.py
Python
bsd-3-clause
57,519
0.000487
from datetime import datetime, time, timedelta import operator import warnings import numpy as np from pandas._libs import Timestamp, index as libindex, lib, tslib as libts import pandas._libs.join as libjoin from pandas._libs.tslibs import ccalendar, fields, parsing, timezones from pandas.util._decorators import App...
is_month_end is_quarter_start is_quarter_end is_year_start is_year_end is_leap_year inferred_freq Methods ------- normalize strftime snap tz_convert tz_localize round floor ceil to_period to_perioddelta to_pydatetime to_series to_fra...
riod data. to_datetime : Convert argument to datetime. date_range : Create a fixed-frequency DatetimeIndex. Notes ----- To learn more about the frequency strings, please see `this link <http://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`__. Creating a Da...
pymedia/pymedia
examples/vplayer_threads.py
Python
lgpl-2.1
15,017
0.059066
import sys, thread, time, traceback, Queue, os import pymedia import pymedia.muxer as muxer import pymedia.audio.acodec as acodec import pymedia.video.vcodec as vcodec import pymedia.audio.sound as sound if os.environ.has_key( 'PYCAR_DISPLAY' ) and os.environ[ 'PYCAR_DISPLAY' ]== 'directfb': import pydfb as pygame...
cache= Cache() ########################################################################3 # Simple video player class VPl
ayer: # ------------------------------------ def aud( self, queue ): self.snd= None resampler= None ac= None print 'VPlayer: Audio thread has started' try: while 1: d= queue.get() if type( d )== str: if d== 'SEEK': if ac: ac.reset() #if sel...
bigdig/vnpy
vnpy/api/sec/generator/DFITC_struct.py
Python
mit
49,441
0
DFITCSECRspInfoField = { "requestID": "int", "sessionID": "int", "accountID": "string", "errorID": "int", "localOrderID": "int", "spdOrderID": "int", "errorMsg": "string", } DFITCSECRspNoticeField = { "noticeMsg": "string", } DFITCSECReqUserLoginField = { "requestID": "int", "a...
"interest": "double", "tradeTime": "string", } DFITCStockReqQryPositionField = { "r
equestID": "int", "exchangeID": "string", "accountID": "string", "securityID": "string", "posiQryFlag": "int", } DFITCStockRspQryPositionField = { "requestID": "int", "accountID": "string", "currency": "string", "sellTurnover": "double", "sellTradeQty": "int", "sellEntrustQty": ...
FMF-studenti/backend
fmf/discourse/auth/discourse.py
Python
gpl-2.0
2,814
0.000355
import os from social.backends.base import BaseAuth from social.exceptions import AuthException from .sso import DiscourseSSO class DiscourseAssociation(object): """ Use Association model to save the nonce by force. """ def __init__(self, handle, secret='', issued=0, lifetime=0, assoc_type=''): self...
st) return self.host + self.sso.build_login_URL(nonce, self.redirect_uri) def auth_complete(self, *args, **kwa
rgs): """Completes login process, must return user instance.""" if not self.sso.validate(self.data['sso'], self.data['sig']): raise Exception("Someone wants to hack us!") nonce = self.sso.get_nonce(self.data['sso']) nonce_obj = self.get_nonce(nonce) if nonce_obj: ...
scikit-build/scikit-ci-addons
anyci/publish_github_release.py
Python
apache-2.0
19,722
0.000558
""" This add-on allows to automatically create GitHub releases or prereleases and upload associated packages. It respectively provides a "release" and a "prerelease" sub-command. """ from __future__ import print_function import argparse import datetime as dt import errno import glob import os import platform import re...
"PATTERN", help="Globbing pattern selecting the set of packages to remove" ) prerelease_group.add_argument( "--prerelease-packages-keep-pattern",
type=str, metavar="PATTERN", help="Globbing pattern identifying the subset of packages to keep" ) prerelease_group.add_argument( "--prerelease-tag", type=str, help="Name of the tag to associat
JasonHow44/mbed
workspace_tools/targets.py
Python
apache-2.0
49,386
0.004394
""" mbed SDK Copyright (c) 2011-2015 ARM Limited 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 writin...
ess or implied. See the License for the specific language governing permissions and limitations under the License. """ CORE_LABELS = { "ARM7TDMI-S": ["ARM7"], "Cortex-M0" : ["M0", "CORTEX_M"], "Cortex-M0+": ["M0P", "CORTEX_M"], "Cortex-M1" : ["M1", "CORTEX_M"], "Cortex-M3" : ["M3", "CORTEX_M"], ...
x-M4" : ["M4", "CORTEX_M"], "Cortex-M4F" : ["M4", "CORTEX_M"], "Cortex-M7" : ["M7", "CORTEX_M"], "Cortex-M7F" : ["M7", "CORTEX_M"], "Cortex-A9" : ["A9", "CORTEX_A"] } import os import binascii import struct import shutil from workspace_tools.patch import patch from paths import TOOLS_BOOTLOADERS class...
telukir/PubMed2Go
full_text_index/search_near_title.py
Python
isc
3,208
0.013716
#!/usr/bin/env python # -*- coding: UTF-8 -*- """ Copyright (c) 2014, Kersten Doering <kersten.doering@gmail.com>, Bjoern Gruening <bjoern.gruening@gmail.com> """ #Kersten Doering 16.06.2014 #check http://xapian.org/docs/queryparser.html for syntax and functions import xappy searchConn = xappy.SearchConnection("x...
machting documents in "results" (starting with rank 0 - check help documentation of function "search") results = searchConn.search(title_q, 0, searchConn.get_doccount()) print "number of matches: ", results.matches_estimated ### debug: ### #print "Rank\tPubMed-ID\tTitle (query term highlighted)" #for index,result in ...
numerate(results): # if "<b>" in results.get_hit(index).highlight('title')[0]: # print index, "\t", result.id, "\t", results.get_hit(index).highlight('title')[0] # else: # print resuld.id, "does not contain a highlighted term" ## if index > 5: ## break #HTML output: #open HTML fil...
kaiping/incubator-singa
python/singa/image_tool.py
Python
apache-2.0
19,335
0.000207
# 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 Apa
che 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 ...
implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================= ''' An utility model for image augmentation. Example usage:: from singa import image_tool tool = image_tool.ImageTool...
postrational/django
tests/queries/models.py
Python
bsd-3-clause
13,028
0.005834
""" Various complex queries that have been problematic in the past. """ from __future__ import unicode_literals import threading from django.db import models from django.utils import six from django.utils.encoding import python_2_unicode_compatible class DumbCategory(models.Model): pass class ProxyCategory(Dum...
om = models.ForeignKey(CustomPk) # An
inter-related setup with a model subclass that has a nullable # path to another model, and a return path from that model. @python_2_unicode_compatible class Celebrity(models.Model): name = models.CharField("Name", max_length=20) greatest_fan = models.ForeignKey("Fan", null=True, unique=True) def __str__(...
theJollySin/pytextgame
test/geometry_test.py
Python
mit
2,020
0
import unittest from pytextgame.geometry import Direction, Position, Rectangle class TestGeometry(unittest.TestCase): def setUp(self): self.pos1 = Position(5, 0) self.pos2 = Position(10, 0) self.pos3 = Position(9, 3) self.dir1 = Direction(1, 1) self.dir2 = Direction(5, 0)...
0) self.assertEqual(self.dir2.dy, 0) def test_direction_descale(self): self.dir3.descale(7) self.assertEqual(self.dir3.dx, 1) self.assertEqual(self.dir3.dy
, 2) if __name__ == '__main__': unittest.main()
alchemistry/alchemtest
src/alchemtest/amber/access.py
Python
bsd-3-clause
3,102
0.003546
"""Accessors for Amber TI datasets. """ from os.path import dirname, join from glob import glob from .. import Bunch def load_bace_improper(): """Load Amber Bace improper solvated vdw example Returns ------- data: Bunch Dictionary-like object, the interesting attributes are: - 'd...
th, 'bace_C
AT-13d~CAT-17a', 'descr.rst')) as rst_file: fdescr = rst_file.read() return Bunch(data=data, DESCR=fdescr) def load_simplesolvated(): """Load the Amber solvated dataset. Returns ------- data : Bunch Dictionary-like object, the interesting attributes are: ...
briancurtin/python-openstacksdk
openstack/compute/v2/server_group.py
Python
apache-2.0
1,373
0
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
ompute import compute_service from openstack import resource2 class ServerGroup(resource2.Resource): resource_key = 'server_group' resources_key = 'server_groups' base_path = '/os-server-groups' service = compute_service.ComputeService(
) _query_mapping = resource2.QueryParameters("all_projects") # capabilities allow_create = True allow_get = True allow_delete = True allow_list = True # Properties #: A name identifying the server group name = resource2.Body('name') #: The list of policies supported by the ser...
jjgomera/pychemqt
lib/mEoS/R114.py
Python
gpl-3.0
3,439
0
#!/usr/bin/python3 # -*- coding: utf-8 -*- '''Pychemqt, Chemical Engineering Process simulator Copyright (C) 2009-2017, Juan José Gómez Romera <jjgomera@gmail.com> 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 Softwar...
"__doi__": {"autor": "Platzer, B., Polt, A., Maurer, G.", "title": "Thermo
physical Properties of Refrigerants", "ref": "Berlin: Springer-Verlag, 1990.", "doi": ""}, "R": 8.31451, "cp": CP1, "ref": "NBP", "Tmin": 273.15, "Tmax": 507.0, "Pmax": 21000.0, "rhomax": 8.942, "nr1": [-0.340776521414, 0.323001398420, ...
wolfstein9119/django-esia-auth
esia_auth/apps.py
Python
bsd-2-clause
178
0
from django.apps im
port AppConfig from django.utils.translation import ugettext_lazy as _ class AuthConfig(AppConfig): name = 'esia_auth' verbose_name = _('
Esia META')
mhrivnak/pulp
server/setup.py
Python
gpl-2.0
684
0.004386
from setuptools import setup, find_packages setup( name='pulp-server', version='2.7.0a1', license='GPLv2+', packages=find_packages(exclude=['test']), author='Pulp Team', author_email='pulp-list@redhat.com', entry_points={ 'console_scripts': [ '../libexec/pulp-manage-wor...
lp.server.async.manage_workers:main', 'pulp-manage-db = pulp.server.db.manage:main', ] }, install_requires=[ 'blinker', 'celery >=3.1.0, <3.2.0', 'django>=1.4.0', 'httplib2', 'iniparse', 'isodate>=0.5.0', 'm2crypto', 'mon
goengine>=0.7.10', 'oauth2>=1.5.211', 'pymongo>=2.5.2', 'setuptools', 'web.py'] )
Oeyvind/interprocessing
codeUtility.py
Python
lgpl-3.0
12,966
0.008098
#!/usr/bin/python # -*- coding: latin-1 -*- # Copyright 2015 Oeyvind Brandtsegg # # This file is part of the Signal Interaction Toolkit # # The Signal Interaction Toolkit is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 # as publi...
if sys.argv[1] == 'pluck': effectname = 'pluck' parameters = [('inlevel', (0, 1.0, 1, 0.3, 0.01)), ('freq', (1, 1450, 400, 0.3, 0.01)), ('filt_fq', (1000, 16000, 7000, 0.35, 1)), ('feedback', (0.8, 0.9999, 0.95, 1.9, 0.0001)),
('mix', (0, 1.0, 1, 0.3, 0.01)) ] if sys.argv[1] == 'lpf18dist': effectname = 'lpf18dist' parameters = [('Drive', (1, 12, 2, 1, 0.1)), ('Freq', (20, 10000, 3000, 0.35, 1)), ('Resonance', (0.001, 0.95, 0.3, 1, 0.001)), ('Dist', (0.001, 1...
looker/sentry
src/sentry/web/forms/accounts.py
Python
bsd-3-clause
29,165
0.001646
""" sentry.web.forms.accounts ~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import import pytz import six from datetime import datetime from django import forms from django.conf im...
self.user_cache = authenticate(username=username, password=password) if self.user_cache is None: raise forms.ValidationError(
self.error_messages['invalid_login'] % {'username': self.username_field.verbose_name} ) self.check_for_test_cookie() return self.cleaned_data def check_for_test_cookie(self): if self.request and not self.request.session.test_cookie_worked(): raise f...
seraph115/ceep_api
ceep_api/run.py
Python
apache-2.0
1,398
0.008584
import sys import os sys.path.append(os.path.join(os.path.dirname(__file
__), '..')) import logging.config from flask import Flask, Blueprint from werkzeug.contrib.fixers import ProxyFix from ceep_api import settings from ceep_api.api import restplus from ceep_api.api.endpoints.adbmonitors import ns as adbmonitors_namespace from ceep_api.api.restplus import api from ceep_api.database i...
fig['SQLALCHEMY_DATABASE_URI'] = settings.SQLALCHEMY_DATABASE_URI flask_app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = settings.SQLALCHEMY_TRACK_MODIFICATIONS flask_app.config['SWAGGER_UI_DOC_EXPANSION'] = settings.RESTPLUS_SWAGGER_UI_DOC_EXPANSION flask_app.config['RESTPLUS_VALIDATE'] = settings.RESTPLUS_V...
dmonllao/moodleinspire-python-backend
moodleinspire/processor/estimator.py
Python
gpl-3.0
4,622
0.003029
"""Abstract estimator module, will contain just 1 class.""" import os import logging import warnings im
port time import numpy as np from sklearn.utils import shuffle from sklearn.externals import joblib class Classifi
er(object): """Abstract estimator class""" PERSIST_FILENAME = 'classifier.pkl' OK = 0 GENERAL_ERROR = 1 NO_DATASET = 2 EVALUATE_LOW_SCORE = 4 EVALUATE_NOT_ENOUGH_DATA = 8 def __init__(self, modelid, directory): self.classes = None self.modelid = modelid self...
ldcorpe/HGCanalysis
python/VBFH125toTauTau_cfi.py
Python
gpl-3.0
4,717
0.0159
import FWCore.ParameterSet.Config as cms from Configuration.Generator.PythiaUEZ2starSettings_cfi import * generator = cms.EDFilter("Pythia6GeneratorFilter", pythiaPylistVerbosity = cms.untracked.int32(1), # put here the efficiency of your filter (1. if no filter) ...
'MDME(217,1)=0 !Higgs decay into Higgs decay', 'MDME(218,1)=0 !Higgs decay into e nu e',
'MDME(219,1)=0 !Higgs decay into mu nu mu', 'MDME(220,1)=1 !Higgs decay into tau nu tau', ...
plotly/python-api
packages/python/plotly/plotly/validators/contour/hoverlabel/_alignsrc.py
Python
mit
466
0.002146
import _plotly_utils.basevalidators class AlignsrcValidator(_plotly_utils.basevalidators.SrcValidator): def __init__( self, plotly_name="alignsrc",
parent_name="contour.hoverlabel", **kwargs ): super(AlignsrcValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "none"), role=kwargs.pop("role", "info"),
**kwargs )
kennedyshead/home-assistant
homeassistant/components/gtfs/sensor.py
Python
apache-2.0
29,393
0.000646
"""Support for GTFS (Google/General Transport Format Schema).""" from __future__ import annotations import datetime import logging import os import threading from typing import Any, Callable import pygtfs from sqlalchemy.sql import text import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SC...
2: "Station Entrance/Exit", 3: "Other", } PICKUP_TYPE_DEFAULT = STATE_UNKNOWN PICKUP_TYPE_OPTIONS = { 0: "Regular", 1: "None Available", 2: "Call Agency", 3: "Contact Driver", } ROUTE_TYPE_OPTIONS = { 0: "
Tram", 1: "Subway", 2: "Rail", 3: "Bus", 4: "Ferry", 5: "Cable Tram", 6: "Aerial Lift", 7: "Funicular", 100: "Railway Service", 101: "High Speed Rail Service", 102: "Long Distance Trains", 103: "Inter Regional Rail Service", 104: "Car Transport Rail Service", 105: "Sl...
whitestone-no/Cambion
docs/conf.py
Python
mit
511
0.005871
import time project = 'Cambion' copyright = str(time.localtime().tm_year) + ', Whitestone.' author = 'Whitestone' source_suffix = ['.rs
t'] master_doc = 'index' highlight_language = 'csharp' html_favicon
= 'favicon.ico' # html_logo = 'images/logoTiny.png' html_scaled_image_link = False html_theme = 'sphinx_rtd_theme' html_theme_options = { # 'logo_only': True, 'collapse_navigation': False, 'prev_next_buttons_location': 'None' } html_static_path = ['_static'] html_css_files = [ 'custom.css' ]
ngageoint/scale
scale/job/migrations/0026_auto_20170510_1151.py
Python
apache-2.0
481
0
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-05-10 15:51 from __future__ import unicode_literal
s from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('job', '0025_auto_20170504_1534'), ] operations = [ migrations.AlterField( model_name='job', name='last_status_change', field=models.DateTimeField(blan...
]
OCA/sale-workflow
sale_delivery_state/tests/__init__.py
Python
agpl-3.0
34
0
from . i
mport test_delivery_st
ate
TPei/jawbone_visualizer
main_gui.py
Python
mit
3,797
0.003424
__author__ = 'TPei' from tkinter import * from data.manager import * from data.DataHandler import DataHandler class App: def __init__(self, master): master.wm_title("Jawbone Visualizer") self.button_width = 25 self.description = Label(master, text="Please choose a visualization mode:") ...
@staticmethod def sleep_vs_coffee(): sleep_effect_on_coffee(get_all_the_data()) @staticmethod def sleep(): plot_sleep(get_all_the_data()) @staticmethod def steps(): plot_step_graph() @staticmethod def sums(): step_sleep_total()
@staticmethod def sleep_per_weekday(): visualize_sleep_per_weekday() @staticmethod def coffee_per_weekday(): visualize_coffee_per_weekday() @staticmethod def composite(self): values = [] if self.composite_sleep.get() == 1: values.append(1) if se...
jlaunonen/kirppu
kirppu/migrations/0040_remove_itemtype_key.py
Python
mit
408
0
from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('kirppu', '0039_counter_private_key'), ] operations =
[ migrations.AlterUniqueTogether( name='itemtype', unique_together={('event', 'order')},
), migrations.RemoveField( model_name='itemtype', name='key', ), ]
hpe-storage/python-hpedockerplugin
source/hpedockerplugin/i18n.py
Python
apache-2.0
1,419
0
# Copyright 2014 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the Lice
nse. 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 th...
der the License. """oslo.i18n integration module. See http://docs.openstack.org/developer/oslo.i18n/usage.html . """ import oslo_i18n as i18n DOMAIN = 'hpedockerplugin' _translators = i18n.TranslatorFactory(domain=DOMAIN) # The primary translation function using the well-known name "_" _ = _translators.primary ...
boya-zhou/kaggle_bimbo_reformat
docs/conf.py
Python
mit
7,917
0.001389
# -*- coding: utf-8 -*- # # bimbo_kaggle_competition documentation build configuration file, created by # sphinx-quickstart. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configurat...
, authors, manual section). man_pages = [ ('index', 'bimbo_kaggle_competition', u'bimbo_kaggle_competition Documentation', [u"Boya Zhou"], 1) ] # If t
rue, show URL addresses after external links. # man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_do...
openspending/babbage.fiscal-data-package
babbage_fiscal/tasks.py
Python
mit
2,046
0.002444
import logging import traceback import sys from celery import Celery from .callbacks import STATUS_LOADING_DATA from .config import get_engine, _set_connection_string from .loader import FDPLoader from .callbacks import do_request, STATUS_INITIALIZING, STATUS_FAIL, STATUS_DONE app = Celery('fdp_loader') app.config_f...
')[4:]), status, count, error) do_request(self.callback, self.package, status, progress=count, e
rror=error, data=data) @app.task def load_fdp_task(package, callback, connection_string=None): send_progress = ProgressSender(callback, package) if connection_string is not None: _set_connection_string(connection_string) try: logging.info("Starting to load %s" % package) send_progr...
jose-caballero/cvmfsreplica
cvmfsreplica/plugins/repository/acceptance/Updatedserver.py
Python
gpl-3.0
3,761
0.007711
#!/usr/bin/env python import logging import os import urllib from cvmfsreplica.cvmfsreplicaex import PluginConfigurationFailure from cvmfsreplica.interfaces import RepositoryPluginAcceptanceInterface import cvmfsreplica.pluginsmanagement as pm class Updatedserver(RepositoryPluginAcceptanceInterface): def __ini...
ile .cvmfspublished # was updated more recently than variable #
repository.last_published # ''' # try: # # FIXME # # maybe we should try a couple of times in case of failures before failing definitely # for line in urllib.urlopen('%s/.cvmfspublished' %self.url).readlines(): # if line.startswith('T'): # ...
libvirt/autotest
client/virt/tests/whql_submission.py
Python
gpl-2.0
12,255
0.000979
import logging, os, re from autotest_lib.client.common_lib import error from autotest_lib.client.virt import virt_utils, rss_client, aexpect def run_whql_submission(test, params, env): """ WHQL submission test: 1) Log into the client machines and into a DTM server machine 2) Copy the automation progra...
se: raise error.TestError("Error running automation program: " "could not find '%s' prompt" % prompt) # Tell the automation program which device to test find_prompt("Device to test:")
server_session.sendline(params.get("test_device")) # Tell the automation program which jobs to run find_prompt("Jobs to run:") server_session.sendline(params.get("job_filter", ".*")) # Set submission DeviceData find_prompt("DeviceData name:") for dd in params.objects("device_data"): ...
open-switch/ops-cli
tests/test_vtysh_ct_show_version_detail.py
Python
gpl-2.0
3,544
0.000282
#!/usr/bin/python # # (c) Copyright 2016 Hewlett Packard Enterprise Development LP # # 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-...
lf.s1.cmdCLI('show version detail').split('\n') lines = [line.replace(' ', '') for line in lines] output = ''.join(lines) return output def __add_git_entry_to_package_info(self): self.s1.ovscmd('ovsdb-client transact \'["OpenSwitch", \
{"op":"insert", "table": "Package_Info", "row": \ {"name": "test-repo-1", "src_type": "git", \ "src_url": "git.testRepo1.net", \ "version":"abcdef007" } } ]\'') def __add_other_entry_to_package_info(self): self.s1.ov...
FrancescoCeruti/linux-show-player
lisp/modules/remote/remote.py
Python
gpl-3.0
1,375
0.000727
# -*- coding: utf-8 -*- # # This file is part of Linux Show Player # # Copyright 2012-2016 Francesco Ceruti <ceppofrancy@gmail.com> # # Linux Show Player 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 ...
Module from lisp.modules.remote.controller import RemoteController class Remote(Module): """Provide remote control over cues via RPCs calls.""" def __init__(self): ip = config['Remote']['BindIp'] port = int(config['Remote']['BindPort']) RemoteControll
er(ip=ip, port=port) RemoteController().start() def terminate(self): RemoteController().stop() def compose_uri(url, port, directory='/'): return 'http://' + url + ':' + str(port) + directory
Camiloasc1/AstronomyUNAL
CelestialMechanics/canonical_units/canonical_units.py
Python
mit
781
0.005122
from typing import List from scipy.optimize import brentq import numpy as np
def m1(m2: float) -> float: return 1 - m2 def x1(m2: float) -> float: return -m2 def x2(m2: float) -> float:
return 1 - m2 def lagrange_points(m2: float) -> List[float]: """ The 3 colinear Lagrange points :param m2: mass 2 :type m2: float :return: L1, L2, L3 :rtype: list """ DELTA = 0.01 f = lambda x: x - (1 - m2) * (x + m2) / (abs(x + m2) ** 3) - m2 * (x - 1 + m2) / (abs(x - 1 +...
zhuyue1314/claripy
tests/test_serial.py
Python
bsd-2-clause
2,258
0.003986
import claripy import ana import nose import pickle import tempfile import logging l = logging.getLogger('claripy.test.serial') def test_pickle(): bz = claripy.backend_z3 a = claripy.BitVecVal(0, 32) b = claripy.BitVec('x', 32, explicit_name=True) c = a+b nose.tools.assert_equal(c.resolved_with(...
, str(ss.variables)) s = claripy.CompositeFrontend(claripy.backend_z3) x = claripy.BitVec("x", 32) s.add(x == 3) s.finalize() ss = claripy.CompositeFrontend.ana_load(s.ana_store()) old_constraint_sets = [[hash(j) for j in k.constraints] for k in s._solver_list] new_constraint_sets = [[hash(...
les), str(ss.variables)) if __name__ == '__main__': test_pickle() test_datalayer()
robotpilot/crazyflie-clients-python
lib/cflib/drivers/cfusb.py
Python
gpl-2.0
5,737
0.001743
#!/usr/bin/env python # -*- coding: utf-8 -*- # # || ____ _ __ # +------+ / __ )(_) /_______________ _____ ___ # | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \ # +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/ # || || /_____/_/\__/\___/_/ \__,_/ /___/\___/ # # Copyright (C) 20...
radio dongle The ack contains information about the packet transmition and a data payload if the ack packet contained any """ try: if (pyusb1 is False):
count = self.handle.bulkWrite(1, dataOut, 20) else: count = self.handle.write(endpoint=1, data=dataOut, timeout=20) except usb.USBError as e: pass def receive_packet(self): dataIn = () try: if (pyusb1 is False): da...
ajyong/corstutorial
website/corstutorial/apps/api/urls.py
Python
apache-2.0
413
0.012107
from django.conf.urls import patterns, include, url from rest_framework import routers from views import * router = routers.DefaultRouter() urlpatterns = patterns('', # Examples:
# url(r'^$', 'corstutorial.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^', include(router.urls)), url(r'^oauth/', include('
oauth2_provider.urls', namespace='oauth2_provider')), )
capoe/espressopp.soap
src/tools/topology.py
Python
gpl-3.0
6,258
0.058805
# Copyright (C) 2012,2013 # Max Planck Institute for Polymer Research # Copyright (C) 2008,2009,2010,2011 # Max-Planck-Institute for Polymer Research & Fraunhofer SCAI # # This file is part of ESPResSo++. # # ESPResSo++ is free software: you can redistribute it and/or modify # it under the terms of t...
dBonds[-1]] bonds += addBonds x += addX[1:-1] + [addX[-1]] y += addY[1:-1] + [addY[-1]] z += addZ[1:-1] + [addZ[-1]] return bonds, x, y, z def starPolymerSAW(pid, startpos, bondlength, numberOfArms, numberOfMonomers, excludedVolumeRadius, partlist, maxtries=100): bonds = [] x=[startpos[0]] y=[start...
, partlist, maxtries=100) addBonds = [(pid,addBonds[0][1])] + addBonds[1:-1] + [addBonds[-1]] bonds += addBonds x += addX[1:-1] + [addX[-1]] y += addY[1:-1] + [addY[-1]] z += addZ[1:-1] + [addZ[-1]] for j in range(len(x)-1): partlist += [ [(x[j+1],y[j+1],z[j+1]), excludedVolumeRadius] ] return bonds, x,...
openstack/manila-ui
manila_ui/dashboards/project/shares/urls.py
Python
apache-2.0
2,838
0
# Copyright 2012 Nebula, 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 agree...
reateReplicaView.as_view(), name='cr
eate_replica'), urls.url( r'^(?P<share_id>[^/]+)/replicas/$', replica_views.ManageReplicasView.as_view(), name='manage_replicas'), urls.url( r'^replica/(?P<replica_id>[^/]+)$', replica_views.DetailReplicaView.as_view(), name='replic...
DuCorey/bokeh
bokeh/tests/test_client_server.py
Python
bsd-3-clause
37,673
0.002761
from __future__ import absolute_import, print_function from mock import patch import unittest import logging import bokeh.document as document from bokeh.application import Application from bokeh.application.handlers import FunctionHandler from bokeh.client import pull_session, push_session, ClientSession from bokeh....
nect_on_error', websocket_url=ws_url(server), io_loop =
server.io_loop) session.connect() assert session.connected # send a bogus message using private fields session._connection._socket.write_message(b"xx", binary=True) # connection should now close on the server side # and the client loop should end ...
state-hiu/cybergis-scripts
bin/cybergis-script-ittc-register-snapshot-layer.py
Python
mit
1,526
0.010485
#!/usr/bin/python from base64 import b64encode from optparse import make_option import json import urllib import urllib2 import argparse import time import sys import os import subprocess #==# sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'lib', 'cybergis'))) import gs._geoserver_animate...
le.") #==# parser.add_argument("--username", default="postgres", help="The username to access the database.") parser.add_argument("--password", help="The password to access the database.") #==# parser.add_argument('--table', help="The snapshot table.") #==# parser.add_argument('--repo', help="The source repo.") parser....
store.") parser.add_argument('--source_layer', help="The source layer.") parser.add_argument('-ts', '--timestamp', help="The timestamp of the snapshot.") parser.add_argument('--snapshot_layer', help="The new snapshot layer.") #==# parser.add_argument('--verbose', '-v', default=0, action='count', help="Print out interme...
linyaoli/acm
backtrack/intermediate/permutations_ii.py
Python
gpl-2.0
851
0.00235
class Solution: # @param num,
a list of integer # @return a list of lists of integers def permuteUnique(self, num): res = [] visited = [0 for _ in xrange(len(num))] self.helper(sorted(num), 0, res, visited, []) return res def helper(self, num, i, res, visited, sol): if i == len(num): ...
visited[j] == 0: if j > 0 and num[j] == num[j-1] and visited[j-1] == 0: continue sol.append(num[j]) visited[j] = 1 self.helper(num, i+1, res, visited, sol) sol.pop() vis...
mathLab/RBniCS
tests/performance/backends/dolfin/test_dolfin_linear_solver.py
Python
lgpl-3.0
3,651
0.002191
# Copyright (C) 2015-2022 by the RBniCS authors # # This file is part of RBniCS. # # SPDX-License-Identifier: LGPL-3.0-or-later import pytest from numpy import isclose from dolfin import (assemble, dx, Function, FunctionSpace, grad, inner, solve, TestFunction, TrialFunction, UnitSquareMesh) from rb...
ctory": FactoryLinearSolver} class Data(object): def __init__(self, Th, callback_type):
# Create mesh and define function space mesh = UnitSquareMesh(Th, Th) self.V = FunctionSpace(mesh, "Lagrange", 1) # Define variational problem u = TrialFunction(self.V) v = TestFunction(self.V) self.a = inner(grad(u), grad(v)) * dx + inner(u, v) * dx self....