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
roryk/recipes
recipes/weeder/weeder2.py
Python
mit
833
0.0012
#!/usr/bin/env python # Small wrapper
script for weeder2, which needs the FreqFiles directory # where it is executed. This script allows running weeder2 from anywhere. import os import sys import argparse import subprocess as sp # Weeder install dir weeder_dir = os.path.realpath(os.path.join(os.path
.dirname(__file__), "..", "share", "weeder2")) weeder_exe = "weeder2" weeder_help = sp.check_output( os.path.join(weeder_dir, weeder_exe), stderr=sp.STDOUT).decode() parser = argparse.ArgumentParser() parser.add_argument("-f", dest="fname") args, unknownargs = parser.parse_known_args() if not args.fnam...
ader1990/cloudbase-init
cloudbaseinit/metadata/services/azureservice.py
Python
apache-2.0
18,702
0
# Copyright 2017 Cloudbase Solutions Srl # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable l...
nable_retry = True self._goal_state = None self._config_set_drive_path = None self._ovf_env = None self._headers = {"x-ms-guest-agent-name": "cloudbase-init"}
self._osutils = osutils_factory.get_os_utils() def _get_wire_server_endpoint_address(self): total_time = 300 poll_time = 5 retries = total_time / poll_time while True: try: options = dhcp.get_dhcp_options() endpoint = (options or {})...
KarimAllah/nova
nova/tests/test_xenapi.py
Python
apache-2.0
69,840
0.00126
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2010 Citrix Systems, 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/L...
.setUp() self.network = utils.import_object(FLAGS.network_manager) self.stubs = stubout.StubOutForTesting() self.flags(xenapi_connection_url='test_url', xenapi_connection_password='test_pass', instance_name_template='%d', firewall
_driver='nova.virt.xenapi.firewall.' 'Dom0IptablesFirewallDriver') xenapi_fake.reset() xenapi_fake.create_local_srs() xenapi_fake.create_local_pifs() db_fakes.stub_out_db_instance_api(self.stubs) xenapi_fake.create_network('fake', FLAGS.flat_net...
DamnWidget/anaconda_go
lib/cache.py
Python
gpl-3.0
2,829
0.000707
# Copyright (C) 2014 - Oscar Campos <oscar.campos@member.fsf.org> # This program is Free Software see LICENSE file for details import os import json import platform from collections import defaultdict from anaconda_go.lib import go from anaconda_go.lib.plugin import typing cachepath = { 'linux': os.path.join('~...
ef package_in_cache(package: typing.Dict) -> bool: """Look for the given p
ackage in the cache and return true if is there """ for pkg in PACKAGES_CACHE[go.GOROOT]: if pkg['ImportPath'] == package['ImportPath']: return True return False def lookup(node_name: str='') -> typing.Dict: """Lookup the given node_name in the cache and return it back """ ...
Alberto-Beralix/Beralix
i386-squashfs-root/usr/share/pyshared/ubuntuone-client/ubuntuone/syncdaemon/hash_queue.py
Python
gpl-3.0
9,720
0.000412
# ubuntuone.syncdaemon.hash_queue - hash queues # # Authors: Facundo Batista <facundo@canonical.com> # Guillermo Gonzalez <guillermo.gonzalez@canonical.com> # Alejandro J. Cura <alecu@canonical.com> # # Copyright 2009-2011 Canonical Ltd. # # This program is free software: you can redistribute it and/o...
def stop(self): """Stop the hasher. Will be effective in the next loop if a hash is in progress. """ # clear the queue to push a end_mark, just to unblok if we are waiting # for a new item self.queue.clear() # set the end_mark in case we are waiting a path ...
True def _hash(self, path): """Actually hashes a file.""" hasher = content_hash_factory() crc = 0 size = 0 try: initial_stat = stat_path(path) with open_file(path, 'rb') as fh: while True: # stop hashing if path_to_...
gpfreitas/bokeh
bokeh/embed.py
Python
bsd-3-clause
20,330
0.005804
''' Provide functions to embed Bokeh models (e.g., plots, widget, layouts) in various different ways. There are a number of different combinations of options when embedding Bokeh plots. The data for the plot can be contained in the document, or on a Bokeh server, or in a sidecar JavaScript file. Likewise, BokehJS may ...
in_function(code): # indent and wrap Bokeh function def around code = "\n".join([" "
+ line for line in code.split("\n")]) return 'Bokeh.$(function() {\n%s\n});' % code def components(plot_objects, resources=None, wrap_script=True, wrap_plot_info=True): ''' Return HTML components to embed a Bokeh plot. The data for the plot is stored directly in the returned HTML. An example can ...
zetaops/ulakbus
selenium_tests/test_ogrenci_iletisim_bilgileri.py
Python
gpl-3.0
1,614
0.006196
# -*- coding: utf-8 -*- from test_settings import Settings class TestCase(Settings): def test_sidebar(self): # Ayarlari yapiyor. self.do_settings() # Genel'e tikliyor. self.driver.find_element_by_css_selector( 'li.ng-binding:nth-child(3) > a:nth-child(1) > span:nth-chil...
r('#ikamet_il').send_keys('Bilecik') # Ikamet Ilce'ye deger gonderiyor. self.driver.find_element_by_css_selector('#ikamet_ilce').send_keys('Merkez') # Ikametgah Adresine deger yolluyor. self.driver.find_element_by_css_selector('#ikamet_adresi'
).send_keys('balim sokak') # Posta Kodu'na deger yolluyor. self.driver.find_element_by_css_selector('#posta_kodu').send_keys('11000') # Telefon Numarasi'na deger yolluyor. self.driver.find_element_by_css_selector('#tel_no').send_keys('0534626286816') # Kaydet'e tikliyor s...
reyrodrigues/EU-SMS
temba/values/tests.py
Python
agpl-3.0
20,151
0.00263
from __future__ import unicode_literals import json from datetime import timedelta from django.core.urlresolvers import reverse from django.utils import timezone from mock import patch from temba.contacts.models import ContactField from temba.flows.models import RuleSet from temba.orgs.models import Language from tem...
result['unset']) self.assertResult(result, 0, now.replace(hour=0, minute=0, second=0, microsecond=0), 2) self.assertResult(result, 1, (now - timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0), 1) # make sure categories returned are sorted by count, not name c2.set_fie...
sertEquals(2, len(result['categories'])) self.assertEquals(3, result['set']) self.assertEquals(2, result['unset']) # this is two as we have the default contact created by our unit tests self.assertFalse(result['open_ended']) self.assertResult(result, 0, "Male", 2) self.assertResu...
softinus/Movie_DataMiner
boxofficemojo.com/BoxOfficeMojo_Scraping_Code.py
Python
apache-2.0
13,739
0.011427
# written in python 3.6.1 #-*- coding: utf-8 -*- from urllib.request import urlopen import json import string import re from bs4 import BeautifulSoup import logging import time FILE_PATH = "./boxofficemojo.com/movie_data.txt" LOG_PATH = "./boxofficemojo.com/scraping.log" logging.basicConfig(filename=LOG_PATH,level=...
if tds[0].text.strip() == "Domestic:": arrData["Total Gross"] = tds[1].text.strip()
arrData["% ofTotal"] = tds[2].text.strip() arrData[tds[0].text.strip()+"_Gross"] = tds[1].text.strip() arrData[tds[0].text.strip()+"_Percentage"] = tds[2].text.strip() if(box.text == "Domestic Summary"): div_con...
makkus/pyclist
pyclist/model_helpers.py
Python
apache-2.0
8,972
0.000892
import booby from booby import fields from booby.inspection import get_fields, is_model from booby.validators import Required from pydoc import locate from collections import OrderedDict from collections import OrderedDict from tabulate import tabulate import readline MODEL_MAP = {} class tabCompleter(object): ...
completes from the given list. Since the autocomplete function can't be given a list to complete from a closure is
used to create the listCompleter function with a list to complete from. """ def listCompleter(text, state): line = readline.get_line_buffer() if not line: return [c + " " for c in ll][state] else: return [c + " " for c in ll ...
heatseeknyc/data-science
src/wunderground.py
Python
mit
2,014
0.036743
import urllib2, json, time, sys from datetime import date, datetime from dateutil.rrule import rrule, DAILY from optparse import OptionParser parser = OptionParser() parser.add_option("-f", dest="fahrenheit", action="store", default=False, type="string", help="Convert to FAHRENHEIT") parser.add_option("-e", dest="end"...
l.read()) except: print "Error reading URL " + wunderground_url print "Is your token correct?" url.close() sys.exit() try: for mean in parsed_json['history']['observations']: if fahrenheit: total += float(mean['tempi']) else: total += float(mean['tempm']) count += 1 temp = (tot...
except: print "Error retrieving temperature records for start date " + str(start) + " end date " + str(end) url.close() time.sleep(10)
michaelcho/redberry
redberry/utils/logger.py
Python
apache-2.0
327
0.003058
import logging def init_logger(): formatter = logging.Formatter('%(asctime)s
%(levelname)s: %(message)s [in %(pathname)s:%
(lineno)d]') logger = logging.getLogger('redberry') logger.setLevel(logging.DEBUG) console = logging.StreamHandler() console.setFormatter(formatter) logger.addHandler(console)
pexip/os-python-amqp
t/unit/test_abstract_channel.py
Python
lgpl-2.1
4,759
0
from __future__ import absolute_import, unicode_literals import pytest from case import Mock, patch from vine import promise from amqp.abstract_channel import AbstractChannel from amqp.exceptions import AMQPNotImplementedError, RecoverableConnectionError from amqp.serialization import dumps class test_AbstractChann...
elf.method} def test_enter_exit(self): self.c.close = Mock(name='close') with self.c: pass
self.c.close.assert_called_with() def test_send_method(self): self.c.send_method((50, 60), 'iB', (30, 0)) self.conn.frame_writer.assert_called_with( 1, self.channel_id, (50, 60), dumps('iB', (30, 0)), None, ) def test_send_method__callback(self): callback = M...
PrefPy/opra
compsocsite/appauth/migrations/0017_userprofile_exp_data.py
Python
mit
453
0
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2018-01-24 07:34 from __future_
_ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('appauth', '0016_userprofile_numq'), ] operations =
[ migrations.AddField( model_name='userprofile', name='exp_data', field=models.TextField(default='{}'), ), ]
duy/python-foafcert
foafcert/gen_cacert.py
Python
gpl-2.0
4,578
0.008301
#!/usr/bin/python # vim: set expandtab tabstop=4 shiftwidth=4: # -*- coding: utf-8 -*- # gen_cacert <http://rhizomatik.net/> # Python functions for generate a X509 CA certificate # # Copyright (C) 2010 duy at rhizomatik dot net # # This program is free software; you can redistribute it and/or modify # it under the te...
OU = arg elif opt in ("-e","--email"): Email = arg if DEBUG: print "CN: "+CN print "C: "+C print "O: "+O print "OU: "+OU print
"Email: "+Email mkcacert_save(cacert_path, cakey_path, CN, C, O, OU, Email) if __name__ == "__main__": main(sys.argv[1:])
bamueh/dark-matter
test/test_alignments.py
Python
mit
7,278
0
import six from unittest import TestCase from dark.reads import Read, Reads from dark.score import HigherIsBetterScore from dark.hsp import HSP, LSP from dark.alignments import ( Alignment, bestAlignment, ReadAlignments, ReadsAlignmentsParams, ReadsAlignments) class TestAlignment(TestCase): """ Tests...
Alignments.getSubjectSequence, 'title'
)
MirichST/patchcap
src/daemon/platedetector.py
Python
gpl-2.0
11,192
0.028145
import cv2 import logging import numpy as np import os import sys from lib.warping import ImageBlobWarping from lib.singleton import Singleton from logging import FileHandler, StreamHandler from multiprocessing import Pool from ocr import Ocr from timeit import default_timer as timer from vlogging import VisualRecord ...
def prepare_night(self, img): tinit= timer() self.original_image= img gray= cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) gauss_gray= cv2.GaussianBlur(gray, (5, 5), 0) max_gray= np.max(gray) std_gray= np.std(gray) saturated_night= np.uint8(( gray > ( max_gray - 2 * s...
self.vlogger.debug(VisualRecord("thresholding > (max - 2 * std)", [saturated_night], fmt = "jpg")) print "e:%.3f"%(timer()-tinit) return self.edged #################################################################################################### def prepare_day(self, img): se...
interrogator/corpkit
corpkit/dictionaries/__init__.py
Python
mit
774
0.002584
__all__ = ["wo
rdlists", "roles", "bnc", "processes", "verbs", "uktous", "tagtoclass", "queries", "mergetags"] from corpkit.dictionaries.bnc import _get_bnc from corpkit.dictionaries.process_types import processes from corpkit.dictionaries.process_types import verbs from corpkit.dictionaries.roles import roles from corpk...
aglemma from corpkit.dictionaries.word_transforms import mergetags from corpkit.dictionaries.word_transforms import usa_convert roles = roles wordlists = wordlists processes = processes bnc = _get_bnc queries = queries tagtoclass = taglemma uktous = usa_convert mergetags = mergetags verbs = verbs
bilbeyt/ituro
ituro/simulation/admin.py
Python
mit
972
0.007202
from django.contrib import admin from simulation.models import SimulationStage, SimulationStageMatch, Simulatio
nStageMatchResult class SimulationStageAdmin(admin.ModelAdmin): list_display = ["number", "
created_at"] list_filter = ["created_at"] class SimulationStageMatchAdmin(admin.ModelAdmin): list_display = ["stage", "order", "raund", "cat", "rat", "won", "created_at"] list_filter = ["stage", "created_at"] search_fields = ["cat", "rat"] readonly_fields = ["won", "cat_password", "rat_pa...
asoliveira/NumShip
scripts/entrada/padrao/plot-1cg.py
Python
gpl-3.0
489
0.02686
#!/usr/bin/env pytho
n # -*- coding: utf-8 -*- import matplotlib.pyplot as plt import scipy as sp #Nome do arquivo em que está os dados da posição arq = 'CurvaGiro/pos.dat' #Limites dos eixos v = [-10,1000, 0, 1000] #Título eixo x xl = r'y metros' #Título do eixo y yl = r'x metros' x = sp.genfromtxt('CurvaGiro/pos.dat') a = plt.plot(x[:...
lt.show(a)
elektito/finglish
finglish/f2p.py
Python
mit
6,952
0.002158
#!/usr/bin/env python3 import os import re import itertools from functools import reduce from .version import __version__ sep_regex = re.compile(r'[ \-_~!@#%$^&*\(\)\[\]\{\}/\:;"|,./?`]') def get_portable_filename(filename): path, _ = os.path.split(__file__) filename = os.path.join(path, filename) retur...
"i'", "u'", "A'"]: return [[word[0] + "'"]] elif word in ["'a", "'e", "'o", "'i", "'u", "'A"]: return [["'" + word[1]]] elif len(word) == 2 and word[0] == word[1]: return [[word[0]]] if word[:2] == 'aa': return [['A'] + i for i in variations(word[2:])] elif
word[:2] == 'ee': return [['i'] + i for i in variations(word[2:])] elif word[:2] in ['oo', 'ou']: return [['u'] + i for i in variations(word[2:])] elif word[:3] == 'kha': return \ [['kha'] + i for i in variations(word[3:])] + \ [['kh', 'a'] + i for i in variation...
mattvonrocketstein/smash
smashlib/ipy3x/kernel/zmq/ipkernel.py
Python
mit
13,151
0.000912
"""The IPython kernel implement
ation""" import getpass import sys import traceback from IPython.core import release from IPython.html.widgets import Widget from IPython.utils.py3compat import builtin_mod, PY3 from IPython.utils.tokenutil import token_at_cursor, line_at_cursor from IPython.utils.traitlets imp
ort Instance, Type, Any from IPython.utils.decorators import undoc from ..comm import CommManager from .kernelbase import Kernel as KernelBase from .serialize import serialize_object, unpack_apply_message from .zmqshell import ZMQInteractiveShell class IPythonKernel(KernelBase): shell = Instance('IPython.core.in...
pombredanne/opc-diag
opcdiag/phys_pkg.py
Python
mit
5,859
0
# -*- coding: utf-8 -*- # # phys_pkg.py # # Copyright (C) 2013 Steve Canny scanny@cisco.com # # This module is part of opc-diag and is released under the MIT License: # http://www.opensource.org/licenses/mit-license.php """Interface to a physical OPC package, either a zip archive or directory""" import os import shut...
def _filepaths_in_dir(dirpath): """ Return a sorted list of
relative paths, one for each of the files under *dirpath*, recursively visiting all subdirectories. """ filepaths = [] for root, dirnames, filenames in os.walk(dirpath): for filename in filenames: filepath = os.path.join(root, filename) filepa...
geosolutions-it/ckanext-geonetwork
ckanext/geonetwork/harvesters/__init__.py
Python
gpl-3.0
309
0
try: import pkg_resources pkg_resources.declare_namespace(__name__) ex
cept ImportError: import pkgutil __path__ = pkgutil.extend_path(__path__, __name__) from ckanext.geonetwork.harvesters.geonetwork import GeoNet
workHarvester from ckanext.geonetwork.harvesters.utils import GeoNetworkClient
google/in-silico-labeling
isl/augment_test.py
Python
apache-2.0
2,507
0.002792
# Copyright 2017 Google 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
_future__ import division from __future__ import print_function import tensorflow as tf
# pylint: disable=g-bad-import-order from isl import augment from isl import test_util from isl import util flags = tf.flags test = tf.test lt = tf.contrib.labeled_tensor FLAGS = flags.FLAGS class CorruptTest(test_util.Base): def setUp(self): super(CorruptTest, self).setUp() self.signal_lt = lt.select...
horejsek/python-webdriverwrapper
tests/test_info.py
Python
mit
735
0.004082
import pytest from webd
riverwrapper.exceptions import InfoMessagesException def test_check_info_messages(driver_info_msgs): with pytest.raises(InfoMessagesException) as excinfo: driver_info_msgs.check_infos(expected_info_messages=('some-info',)) def test_check_expected_info_messages(driver_info_msgs): driver_info_msgs.che...
nfo_messages=('some-info', 'another-info')) def test_check_allowed_info_messages(driver_info_msgs): driver_info_msgs.check_infos(allowed_info_messages=('some-info', 'another-info')) def test_check_expected_and_allowed_info_messages(driver_info_msgs): driver_info_msgs.check_infos(expected_info_messages=('som...
felix-dumit/campusbot
yowsup2/yowsup/layers/protocol_iq/protocolentities/iq_ping.py
Python
mit
555
0.030631
from yowsup.structs import ProtocolEntity, ProtocolTreeNode from .iq import I
qProtocolEntity class PingIqProtocolEntity(IqProtocolEntity): ''' Receive <iq type="get" xmlns="urn:xmpp:ping" from="s.wh
atsapp.net" id="1416174955-ping"> </iq> Send <iq type="get" xmlns="w:p" to="s.whatsapp.net" id="1416174955-ping"> </iq> ''' def __init__(self, _from = None, to = None, _id = None): super(PingIqProtocolEntity, self).__init__("urn:xmpp:ping" if _from else "w:p", _id = _id, _type = "get", ...
xmikos/soapy_power
soapypower/psd.py
Python
mit
4,040
0.001733
#!/usr/bin/env python3 import math, logging, threading, concurrent.futures import numpy import simplespectral from soapypower import threadpool logger = logging.getLogger(__name__) class PSD: """Compute averaged power spectral density using Welch's method""" def __init__(self, bins, sample_rate, fft_windo...
elf._fft_overlap) self._crop_factor = crop_factor self._log_scale = log_scale self._remove_dc = remove_dc self._detrend = detrend self._lnb_lo = lnb_lo se
lf._executor = threadpool.ThreadPoolExecutor( max_workers=max_threads, max_queue_size=max_queue_size, thread_name_prefix='PSD_thread' ) self._base_freq_array = numpy.fft.fftfreq(self._bins, 1 / self._sample_rate) def set_center_freq(self, center_freq): ""...
imperial-genomics-facility/data-management-python
igf_data/utils/project_data_display_utils.py
Python
apache-2.0
8,493
0.01672
import os import pandas as pd from igf_data.utils.seqrunutils import get_seqrun_date_from_igf_id def _count_total_reads(data,seqrun_list): ''' An internal function for counting total reads required params: :param data, A dictionary containing seqrun ids a key an read counts as values :param seqrun_list, ...
s[path_col]=os.path.join(seqrun_date,flowcell_id) # adding path to data series del data_series[seqrun_col] return data_series except: raise def add_seqrun_path_info(input_data,output_file,seqrun_col='seqrun_igf_id', flowcell_col='flowcell_id',path_col='path'): '...
following columns seqrun_igf_id flowcell_id :param seqrun_col, Column name for sequencing run id, default seqrun_igf_id :param flowcell_col, Column namae for flowcell id, default flowcell_id :param path_col, Column name for path, default path output_file: An output filepath for the json dat...
ioam/topographica
topo/hardware/robotics.py
Python
bsd-3-clause
4,844
0.010735
""" Classes for using robotic or other hardware using Topographica. This module contains several classes for constructing robotics interfaces to Topographica simulations. It includes modules that read input from or send output to robot devices, and a (quasi) real-time simulation object that attempts to maintain a cor...
: # if we don't have an image then block until we get one
im_spec = self.camera.image_queue.get() self.camera.image_queue.task_done() # Make sure we clear the image queue and get the most recent image. while not self.camera.image_queue.empty(): im_spec = self.camera.image_queue.get_nowait() self.camera.image_queue.t...
mgmtech/sys76_unity_webmic
unity_avindicator/webmic.py
Python
gpl-3.0
751
0.011984
#!/usr/bin/env python ''' A/V control for System76 laptop using Unity ''' import os from execute import returncode # check for the existence of /dev/video0 which is us
ed currently for webcam webcam = lambda: os.path.exists('/dev/video0') == False def webcam_toggle(): if webcam(): returncode('sudo /sbin/modprobe uvcvideo') else: returncode('sudo /sbin/modprobe -rv uvcvideo') # use the amixer applicati
on to glean the status of the microphone microphone = lambda: returncode("amixer get Capture | grep Capt | grep off") == 0 microphone_toggle = lambda: returncode("amixer set Capture toggle") def main(): print "Mic muted ? {0}, Webcam off ? {1}".format(microphone(), webcam()) if __name__ == '__main__': main()
ychen820/microblog
y/google-cloud-sdk/platform/google_appengine/lib/django-1.2/django/utils/dateformat.py
Python
bsd-3-clause
8,796
0.002046
""" PHP date() style date formatting See http://www.php.net/date for format strings Usage: >>> import datetime >>> d = datetime.datetime.now() >>> df = DateFormat(d) >>> print df.format('jS F Y H:i') 7th October 2003 11:39 >>> """ import re import time import calendar from django.utils.dates import MONTHS, MONTHS_3, ...
. '1' to '12'" if self.data.hour == 0: return 12 if self.data.hour > 12: return self.data.hour - 12 return self.data.hour def G(self): "Hour, 24-hour format without leading zeros; i.e. '0' to '23'" return self.data.hour def h(self): "Hour...
self.G() def i(self): "Minutes; i.e. '00' to '59'" return u'%02d' % self.data.minute def P(self): """ Time, in 12-hour hours, minutes and 'a.m.'/'p.m.', with minutes left off if they're zero and the strings 'midnight' and 'noon' if appropriate. Examples: '1 a.m...
ctiller/grpc
tools/run_tests/artifacts/distribtest_targets.py
Python
apache-2.0
17,548
0.000399
#!/usr/bin/env python # Copyright 2016 gRPC authors. # # 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 o...
th('..')) import python_utils.jobset as jobset def create_docker_jobspec(name, dockerfile_dir, shell_co
mmand, environ={}, flake_retries=0, timeout_retries=0, copy_rel_path=None, timeout_seconds=30 * 60): """Creates jobspec for a task running under docker.""" environ = environ.copy() ...
trevor/calendarserver
calendarserver/tap/util.py
Python
apache-2.0
38,773
0.00227
# -*- test-case-name: calendarserver.tap.test.test_caldav -*- ## # Copyright (c) 2005-2014 Apple 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.apach...
= ConnectionWithPeer(skt, protocol) protocol.makeConnection(transport) transport.startReading() return protocol.newTransaction class ConnectionDispenser(object): """ A L{ConnectionDispenser} can dispense already-connected file descriptors, for use with subprocess spawning. """ # Very ...
a single stdio AMP connection that # multiplexes between multiple protocols. def __init__(self, connectionPool): self.pool = connectionPool def dispense(self): """ Dispense a socket object, already connected to a server, for a client in a subprocess. """ # ...
pbmanis/acq4
acq4/devices/PatchPipette/__init__.py
Python
mit
77
0
from __future__ im
port print_function from
.patchpipette import PatchPipette
ahmedaljazzar/edx-platform
common/djangoapps/util/models.py
Python
agpl-3.0
1,962
0.001019
"""Models for the ut
il app. """ import cStringIO import gzip import logging from config_models.models import ConfigurationModel from django.db import models from django.utils.text import compress_string from opaque_keys.edx.django.models import CreatorMixin logger = logging.getLogger(__name__) # pylint: disable=invalid-name class Ra...
"""Configuration flag to enable/disable rate limiting. Applies to Django Rest Framework views. This is useful for disabling rate limiting for performance tests. When enabled, it will disable rate limiting on any view decorated with the `can_disable_rate_limit` class decorator. """ class Me...
erjac77/ansible-module-f5bigip
library/f5bigip_ltm_profile_sip.py
Python
apache-2.0
8,676
0.003112
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2016-2018, Eric Jacob <erjac77@gmail.com> # # 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/LICENS...
pe='str'), description=dict(type='str'), dialog_aware=dict(type='str', choices=F5_ACTIVATION_CHOICES), dialog_establishment_timeout=dict(type='int'), enable_sip_firewall=dict(type='str', choices=F5_POLAR_CHOICES), insert_record
_route_header=dict(type='str', choices=F5_ACTIVATION_CHOICES), insert_via_header=dict(type='str', choices=F5_ACTIVATION_CHOICES), log_profile=dict(type='str'), log_publisher=dict(type='str'), max_media_sessions=dict(type='int'), max_registrations=dict(type='in...
2ndQuadrant/ansible
lib/ansible/modules/cloud/ovirt/ovirt_auth.py
Python
gpl-3.0
11,230
0.002048
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (c) 2016 Red Hat, Inc. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUME...
. Default value is set by I(OVIRT_URL) environment variable." - "Either C(url) or C(hostname) is required." hostname: required: False description: - "A string containing the hostname of the server. For example: I(server.example.com). ...
variable." - "Either C(url) or C(hostname) is required." version_added: "2.6" insecure: required: False description: - "A boolean flag that indicates if the server TLS certificate and host name should be checked." type: bool ca_file: required: Fals...
davidveen/nolava
src/main.py
Python
gpl-3.0
234
0.004274
""" Application entry point """ def main(): pass if __name__ == "__ma
in__": # delegates to main_debug during construction try: import main_debug main_debug.main() e
xcept ImportError: main()
GbalsaC/bitnamiP
venv/lib/python2.7/site-packages/social/backends/xing.py
Python
agpl-3.0
1,519
0
""" XING OAuth1 backend, docs at: http://psa.matiasaguirre.net/docs/backends/xing.html """ from social.backends.oauth import BaseOAuth1 class XingOAuth(BaseOAuth1): """Xing OAuth authentication backend""" name = 'xing' AUTHORIZATION_URL = 'https://api.xing.com/v1/authorize' REQUEST_TOKEN_URL = 'ht...
TOR = '+' EXTRA_DATA = [ ('id', 'id'), ('user_id', 'user_id') ] def get_user_details(self, response): """Return user details from Xing account""" email = r
esponse.get('email', '') fullname, first_name, last_name = self.get_user_names( first_name=response['first_name'], last_name=response['last_name'] ) return {'username': first_name + last_name, 'fullname': fullname, 'first_name': first_name,...
NLeSC/Xenon-examples
readthedocs/code-tabs/python/tests/test_slurm_queues_getter_with_props.py
Python
apache-2.0
192
0.005208
#!/usr/bin/env python import pytest from pyxenon_snippets import slurm_queues_get
ter_with_props def test_slurm_queues_getter_with_p
rops(): slurm_queues_getter_with_props.run_example()
homeworkprod/byceps
byceps/services/shop/article/dbmodels/article.py
Python
bsd-3-clause
3,124
0.00128
""" byceps.services.shop.article.dbmodels.article ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from datetime import datetime from decimal import Decimal from typing import Optional from sqlalchemy.ext.hybrid import...
umeric(3, 3), nullable=False) available_from = db.Column(db.DateTime, nullable=True) available_until = db.Column
(db.DateTime, nullable=True) total_quantity = db.Column(db.Integer, nullable=False) quantity = db.Column(db.Integer, db.CheckConstraint('quantity >= 0'), nullable=False) max_quantity_per_order = db.Column(db.Integer, nullable=False) not_directly_orderable = db.Column(db.Boolean, default=False, nullable=...
idaholab/raven
framework/SupervisedLearning/ScikitLearn/LinearModel/LassoLarsCV.py
Python
apache-2.0
6,473
0.00896
# Copyright 2017 Battelle Energy Alliance, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed t...
(1 / (2 * n\_samples)) * ||y - Xw||^2\_2 + alpha * ||w||\_1 \end{equation} \zNormalizationNotPerformed{LassoLarsCV} """ specs.addSub(InputData.parameterInputFactory("fit_intercept", contentType=InputTypes.BoolType, ...
ot. If False, the data is assumed to be already centered.""", default=True)) specs.addSub(InputData.parameterInputFactory("max_iter", contentType=InputTypes.IntegerType, descr=r"""The maximum number of iterations.""", ...
ericmjl/bokeh
examples/reference/models/Triangle.py
Python
bsd-3-clause
749
0.001335
import numpy as np from bokeh.io import curdoc, show from bokeh.models import ColumnDataSource, Grid, LinearAxis, Plot, Triangle N = 9 x = np.linspace(-2, 2, N) y = x**2 sizes = np.linspace(10, 20, N) source = ColumnDataSource(dict(x=x, y=y, sizes=sizes)) plot = Plot( title=None, plot_width=300, plot_height=300...
gle(x="x", y="y", size="sizes", line_color="#99d594", line_width=2, fill_color=None
) plot.add_glyph(source, glyph) xaxis = LinearAxis() plot.add_layout(xaxis, 'below') yaxis = LinearAxis() plot.add_layout(yaxis, 'left') plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker)) plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker)) curdoc().add_root(plot) show(plot)
krazybean/message_agent_abandoned
lin/lin_notify_lib.py
Python
apache-2.0
282
0.01773
#!/us
r/bin/env python import pynotify ''' No purpose here other than creating a callable library for system notifications ''' class message: def
__init__(self, messagex): pynotify.init('EventCall') m = pynotify.Notification("RSEvent Notification", "%s" % messagex) m.show()
tiborsimko/invenio-records
invenio_records/admin.py
Python
mit
2,051
0.000488
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2015-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Admin model views for records.""" import json from flask import flash from flask...
s=True))) ) column_filters = ('created', 'updated', ) column_default_sort = ('updated', True) page_size = 25 def delete_model(self, model): """Delete a record."
"" try: if model.json is None: return True record = Record(model.json, model=model) record.delete() db.session.commit() except SQLAlchemyError as e: if not self.handle_view_exception(e): flash(_('Failed to delete...
zmathe/WebAppDIRAC
WebApp/handler/Palette.py
Python
gpl-3.0
3,496
0.016304
import hashlib as md5 class Palette: def __init__(self, palette={}, colors=[]): self.job_status_palette = { 'Received': '#D9E7F8', 'Checking': '#FAFAFA', 'Staging': '#6190CD', 'Waiting': '#004EFF', 'Matched': '#FEF7AA', 'Running': '#FDEE65', 'Stalled': '#BC5757'...
'#52FF4F', 'Received Kill signal' : '#FF312F', 'Socket read timeout exceeded' : '#B400FE', 'Stalled' : '#FF655E', 'Uploading Job Outputs' : '#FE8420', 'Watchdog identified this job as stalled' : '#FFCC99' } self.miscelaneous_pallette = { 'Others': '#666666',
'NoLabels': '#0025AD', 'Total': '#00FFDC', 'Default': '#FDEE65' } self.country_palette = { 'France':'#73C6BC', 'UK':'#DCAF8A', 'Spain':'#C2B0E1', 'Netherlands':'#A9BF8E', 'Germany':'#800000', 'Russia':'#00514A', 'Italy':'#004F00', 'Switzerland':'...
tanglu-org/tgl-misago
misago/migrations/0015_remove_users_reported.py
Python
gpl-3.0
33,856
0.008034
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import DataMigration from django.db import models class Migration(DataMigration): def forwards(self, orm): orm.MonitorItem.objects.filter(pk='users_reported').delete() def backwards(self, orm): raise RuntimeError("C...
els.SET_NU
LL', 'blank': 'True'}), 'user_name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'user_slug': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, 'misago.fixture': { 'Meta': {'object_name': 'Fixture'}, u'id': ('django....
tonioo/modoboa
modoboa/lib/db_utils.py
Python
isc
848
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.
db impor
t connection from django.utils.translation import ugettext as _ from modoboa.lib.exceptions import InternalError def db_table_exists(table): """Check if table exists.""" return table in connection.introspection.table_names() def db_type(cname="default"): """Return the type of the *default* database ...
lmcro/webserver
qa/014-Broken-Key3.py
Python
gpl-2.0
294
0.013605
from base import * class Test (TestBase):
def __init__ (self): TestBase.__init__ (self, __file__) self.name = "Broken header entry III" self.expected_error = 200 self.request = "GET / HTTP/1.
0\r\n" +\ "Entry:value\r\n"
mcltn/ansible
lib/ansible/inventory/__init__.py
Python
gpl-3.0
28,850
0.00357
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) an...
mpile('\[([a-f:A-F0-9]*[%[0-z]+]?)\](?::(\d+))?') for x in host_list: m = ipv6_re.match(x) if m: all.add_host(Host(m.groups()[0], m.groups()[1])) else: if ":" in x: tokens = x.rsplit(":", 1) ...
f there is ':' in the address, then this is an ipv6 if ':' in tokens[0]: all.add_host(Host(x)) else: all.add_host(Host(tokens[0], tokens[1])) else: all.add_host(Host(x)) ...
bizalu/sImulAcre
core/lib/speech_recognition/__init__.py
Python
gpl-2.0
10,485
0.010205
"""Library for performing speech recognition with the Google Speech Recognition API.""" __author__ = 'Anthony Zhang (Uberi)' __version__ = '1.0.4' __license__ = 'BSD' import io, subprocess, wave, shutil import math, audioop, collections import json, urllib.request #wip: filter out clicks and other too short parts c...
r = process.communicate(wav_data) return flac_data def record(self, source, duration = None): assert isinstance(source, AudioSource) and source.stream frames = io.BytesIO() seconds_per_buffer = source.CHUNK / source.RATE elapsed_time = 0 while True: # loop for the t...
if duration and elapsed_time > duration: break buffer = source.stream.read(source.CHUNK) if len(buffer) == 0: break frames.write(buffer) frame_data = frames.getvalue() frames.close() return AudioData(source.RATE, self.samples_to_flac(source, frame_da...
aaalgo/cls
train-slim-fcn.py
Python
mit
13,078
0.005811
#!/usr/bin/env python3 import os import sys os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'models/research/slim')) import time import datetime import logging from tqdm import tqdm import numpy as np import cv2 import simplejson as json from sklearn.met...
(weight_decay=weight_decay, batch_norm_decay=0.9, batch_norm_epsilon=5e-4, batch_norm_scale=False) nets_factory.arg_scopes_map['resnet_v1_50'] = resnet_arg_scope nets_factory.arg_scopes_map['resnet_v1_1
01'] = resnet_arg_scope nets_factory.arg_scopes_map['resnet_v1_152'] = resnet_arg_scope nets_factory.arg_scopes_map['resnet_v1_200'] = resnet_arg_scope nets_factory.arg_scopes_map['resnet_v2_50'] = resnet_arg_scope nets_factory.arg_scopes_map['resnet_v2_101'] = resnet_arg_scope nets_factory.arg_scop...
iABC2XYZ/abc
DM_RFGAP_3/PartGen.py
Python
gpl-3.0
516
0.05814
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Aug 2 17:52:19 2017
Author: Peiyong Jiang : jiangpeiyong@impcas.ac.cn Function: ______________________________________________________ """ from numpy.random import multivariate_normal as npmvn from numpy import diag def
PartGen(emitT,numPart): meanPart=[0.,0.,0.,0.,0.,0.] covPart=diag([emitT[0],emitT[0],emitT[1],emitT[1],emitT[2],emitT[2]]) x,xp,y,yp,z,zp=npmvn(meanPart,covPart,numPart).T return x,xp,y,yp,z,zp
twhyte/openparliament
parliament/imports/hans_old/current.py
Python
agpl-3.0
11,722
0.006398
"""This *was* the parser for the current HTML format on parl.gc.ca. But now we have XML. See parl_document.py. This module is organized like so: __init__.py - utility functions, simple parse interface common.py - infrastructure used in the parsers, i.e. regexes current.py - parser for the Hansard format used from 200...
atch: logger.error("Invalid bill link %s" % string) return string bill = Bill.obje
cts.create_temporary_bill(legisinfo_id=resid, number=match.group(0), session=self.hansard.session) except Exception, e: print "Related bill search failed for callback %s" % resid print repr(e) return string return u'<bill id="%d...
kubeflow/pipelines
components/gcp/container/component_sdk/python/tests/google/bigquery/test__query.py
Python
apache-2.0
5,793
0.005351
# you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIE...
al_job_config = mock_client().query.call_args_list[0][0][1] self.assertDictEqual( expected
_job_config.to_api_repr(), actual_job_config.to_api_repr() ) extract = mock_client().extract_table.call_args_list[0] self.assertEqual(extract[0], (mock_dataset.table('query_ctx1'), 'gs://output/path',)) self.assertEqual(extract[1]["job_config"].destination_format, "CSV",) ...
wulczer/ansible
lib/ansible/inventory/ini.py
Python
gpl-3.0
7,628
0.003146
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) an...
.group import Group from ansible.inventory.expand_hosts import detect_range from ansible.inventory.expand_hosts import expand_hostname_range from ansible import errors from ansible import utils import shlex import re import ast class InventoryParser(object): """ Host inventory for ansible. """ def __i...
t__(self, filename=C.DEFAULT_HOST_LIST): with open(filename) as fh: self.lines = fh.readlines() self.groups = {} self.hosts = {} self._parse() def _parse(self): self._parse_base_groups() self._parse_group_children() self._add_allgrou...
phantomii/restalchemy
restalchemy/tests/functional/restapi/sa_based/microservice/db.py
Python
apache-2.0
1,082
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2016 Eugene Frolov <eugene@frolov.net.ru> # # All Rights Reserved. # # Licensed under the Apac
he 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...
cense for the specific language governing permissions and limitations # under the License. import uuid import sqlalchemy as sa from sqlalchemy import orm _engine = None _session_maker = None DB_CONNECTION = "sqlite:////tmp/restalchemy-%s.db" % uuid.uuid4() def get_engine(): global _engine if _engine ...
udayinfy/openerp-7.0
gap_analysis_project/gap_analysis_project.py
Python
agpl-3.0
13,460
0.008915
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (c) 2010-2013 Elico Corp. All Rights Reserved. # Author: Yannick Gouin <yannick.gouin@elico-corp.com> # # This program is free software: you c...
} maintask_id = task_pool.create(cr, uid, maintask_vals, context=context) maintask_id = [int(maintask_id)] if time4test > 0: task_vals4test = {
'name': gap_line.functionality.name[0:100] + " [TEST]", 'code_gap': gap_line.code or "", 'project_id': project_id, 'notes': ustr(gap_line.functionality.description or gap_line.functionality.name), ...
joshisa/mistub
mistub/models/concepts.py
Python
apache-2.0
833
0
#!/usr/bin/env python """Contains the Data Model for a cool Resource. """ __author__ = "Sanjay Joshi" __copyright__ = "IBM Copyright 2017" __credits__ = ["Sanjay Joshi"] __license__ = "Apache 2.0" __version__ = "1.0" __maintainer__ = "Sanjay Joshi" __email__ = "joshisa@us.ibm.com" __status__ = "Prototype" schema = { ...
'default': 'Powered by IBM
Bluemix and Python Eve' }, 'base16': { 'type': 'string', 'default': '######' }, 'hex': { 'type': 'string', 'default': '##-##-##' }, 'organization': { 'type': 'string', 'default': 'Doh!MissingOrg' ...
buzmakov/tomography_scripts
tomo/yaivan/dispersion/alg.py
Python
mit
1,930
0.031088
import astra def gpu_fp(pg, vg, v): v_id = astra.data2d.create('-vol', vg, v) rt_id = astra.data2d.create('-sino', pg) fp_cfg = astra.astra_dict('FP_CUDA') fp_cfg['VolumeDataId'] = v_id fp_cfg['ProjectionDataId'] = rt_id fp_id = astra.algorithm.create(fp_cfg) astra.algorithm.run(fp_id) out = astra.data...
t) v_id = astra.data2d.create('-vol', vg) sirt_cfg = astra.astra_dict(
'SIRT_CUDA') sirt_cfg['ReconstructionDataId'] = v_id sirt_cfg['ProjectionDataId'] = rt_id #sirt_cfg['option'] = {} #sirt_cfg['option']['MinConstraint'] = 0 sirt_id = astra.algorithm.create(sirt_cfg) astra.algorithm.run(sirt_id, n_iters) out = astra.data2d.get(v_id) astra.algorithm.delete(sirt_id) ast...
quantumlib/Cirq
dev_tools/import_test.py
Python
apache-2.0
8,158
0.000981
# Copyright 2019 The Cirq Developers # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
xecutions # type: ignore sys.path[:] = orig_path # Restore the path. sys.path.append(project_dir) # Ensure the cirq package is in the path. # note that with the cirq.google injection we do change the metapath with wrap_module_executions('' if track_others else 'cirq', wrap_module, after_exec, False...
cirq # pylint: disable=unused-import sys.path[:] = orig_path # Restore the path. if fail_list: print() # Only print the first because later errors are often caused by the # first and not as helpful. print(f'Invalid import: {fail_list[0]}') if timeit: worst_loads ...
deklungel/iRulez
src/webservice/_inputPin.py
Python
mit
1,909
0.001572
from flask import jsonify from flask_sqlalchemy import SQLAlchemy from sqlalchemy import Table, Column, Integer, ForeignKey from src.webservice.base import Base from src.webservice._action import Action db = SQLAlchemy() Base.query = db.session.query_property() class Input(Base): __tablename__ = 'tbl_InputPin' ...
ns': actions} output.append(input_data) db.session.commit() return jsonify({'response': output}) @staticmethod def update_input(request): data = request.get_json() input = db.session.query(Input).filter_by(id=data['id']).first() if 'name' in
data: input.name = data['name'] if 'time_between_clicks' in data: input.time_between_clicks = data['time_between_clicks'] if 'actions_id': actions = Action.get_actions(data['actions_id']) input.actions = actions db.session.commit() return ...
seenaburns/Chroma
setup.py
Python
bsd-3-clause
768
0.001302
from distutils.core import
setup setup( name='Chroma', version='0.2.0', author='Seena Burns', author_email='hello@seenaburns.com', url='https://github.com/seenaburns/Chroma', license=open('LICENSE.txt').read(), description='Color handlin
g made simple.', long_description=open('README.rst').read() + '\n\n' + open('HISTORY.rst').read(), packages=['chroma'], classifiers=( 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Natural Language :: English', 'License...
ygenc/onlineLDA
onlineldavb_new/build/scipy/scipy/odr/odrpack.py
Python
gpl-3.0
39,749
0.001157
""" Python wrappers for Orthogonal Distance Regression (ODRPACK). Classes ======= Data -- stores the data and weights to fit against RealData -- stores data with standard deviations and covariance matrices Model -- stores the model and its related information Output -- stores all of the output from an ODR run ODR...
ant weighting matrix broadcast to each observation. If `we` is a rank-2 array of shape (q, n), then `we[:,i]` is the diagonal of the covariant weighting matrix for the i'th observation. If `we` is a rank-3 array of shape (q, q, n), then `we[:,:,i]` is the full specification of the covari...
ive scalar value is used. wd : array_like, optional If `wd` is a scalar, then that value is used for all data points (and all dimensions of the input variable). If `wd` = 0, then the covariant weighting matrix for each observation is set to the identity matrix (so each dimension of e...
CLVsol/odoo_addons
clv_medicament_template/wkf/__init__.py
Python
agpl-3.0
1,439
0.011814
# -*- encoding: utf-8 -*- ################################################################################ # # # Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol # # ...
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 hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of ...
sidhart/antlr4
runtime/Python2/src/antlr4/dfa/DFASerializer.py
Python
bsd-3-clause
3,848
0.002339
# # [The "BSD license"] # Copyright (c) 2012 Terence Parr # Copyright (c) 2012 Sam Harwell # Copyright (c) 2014 Eric Vergnaud # 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. Redis...
ollowing disclaimer in the # documentation and/or other materials provided with the distribution. # 3. The name of the author may not be used to endorse or p
romote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # ...
shalakhin/disqus-api
disqus_api/api.py
Python
mit
1,082
0.005545
import requests import json class DisqusAPI(object): """ Lightweight solution to make API calls to Disqus: More info: https://disqus.com/api/docs """ def __init__(self, api_key, api_secret, version='3.0', formats='json' ): self.api_k...
ey, 'api_secret': self.api_secret, })
response = requests.get(url, params=kwargs) # TODO: support other formats like rss if self.formats == 'json': return json.loads(response.content.decode())
hideoussquid/aureus-12-bitcore
qa/rpc-tests/multi_rpc.py
Python
mit
4,609
0.005424
#!/usr/bin/env python2 # Copyright (c) 2015 The Aureus Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Test mulitple rpc user config option rpcauth # from test_framework.test_framework import AureusTestFramewo...
uest('POST', '/', '{"method": "getbestblockhash"}', headers)
resp = conn.getresponse() assert_equal(resp.status==401, True) conn.close() #Wrong password for rt authpairnew = "rt:"+password+"wrong" headers = {"Authorization": "Basic " + base64.b64encode(authpairnew)} conn = httplib.HTTPConnection(url.hostname, url.port) c...
nuobit/odoo-addons
partner_default_journal/models/res_partner.py
Python
agpl-3.0
511
0.001957
# Copyright NuoBiT Solutions, S.L. (<https://www.nuobit.com>) # Eric Antones <eantones@nuobit.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl) from odoo import fields, models class ResPartner(model
s.Mod
el): _inherit = "res.partner" sale_journal_id = fields.Many2one( "account.journal", "Default journal", domain=[("type", "=", "sale")] ) purchase_journal_id = fields.Many2one( "account.journal", "Default journal", domain=[("type", "=", "purchase")] )
nlhepler/pysam
tests/AlignedSegment_test.py
Python
mit
17,059
0.000117
import os import pysam import unittest from TestUtils import checkFieldEqual import copy SAMTOOLS = "samtools" WORKDIR = "pysam_test_work" DATADIR =
"pysam_data" class ReadTest(unittest.TestCase): def buildRead(self): '''build an example read.''' a = pysam.AlignedSegment() a.query_name = "read_12345" a.query_sequence = "ACGT" * 10 a.flag = 0 a.reference_id = 0 a.reference_start = 20 a.mapping_q...
a.cigartuples = ((0, 10), (2, 1), (0, 9), (1, 1), (0, 20)) a.next_reference_id = 0 a.next_reference_start = 200 a.template_length = 167 a.query_qualities = pysam.fromQualityString("1234") * 10 # todo: create tags return a class TestAlignedSegment(ReadTest): ''...
pclubuiet/website
home/views.py
Python
gpl-3.0
3,396
0.008539
from django import views from django.shortcuts import render, get_object_or_404 from django.views.generic import TemplateView from django.views.generic.edit import CreateView from .models import * from .forms import * import requests import http from django.urls import reverse_lazy from django.views.decorators.csrf imp...
rces/resources.html", {'resources': topic.resource_set.all(), 'topic' : topic}) class BlogPostList(views.View): def get(self, request, *args, **kwargs): posts = BlogPost.objects.all(
) return render(request, "home/blog/index.html", {'posts': posts}) class BlogPostView(views.View): def get(self, request, pk, *args, **kwargs): post = get_object_or_404(BlogPost, pk=pk) return render(request, "home/blog/blog_post.html", {'post': post}) class Leaderboard(views.View): de...
SirDavidLudwig/KattisSolutions
problems/sidewayssorting/sidewayssorting.py
Python
gpl-3.0
372
0.024194
import sys r, c = map(int, input().split()) while r and c: lines = [input().strip() for i in range(r)] rotatedLines = [] for i in range(c): rotatedLines.append("".join([lines[j][i] for j in range(r)])) rotatedLines.sort(key=lambda s: s.lower()) for i in
range(r): print("".join([rotatedLines[j][i] for j in range(c)])) print() r
, c = map(int, input().split())
mbramr/My-Zork
room.py
Python
mit
1,035
0.017391
import json import sqlite3 def get_room(id, dbfile): ret = None con = sqlite3.connect(dbfile) for row in con.execute("select json from rooms where id=?",(id,)): jsontext = row[0] # Outputs the JSON response #print("json = " + jsontext) d = json.loads(jsontext)...
self.neighbors = neighbors def _neighbor(self, direction): if direction in self.neighbors: return self.neighbors[direction] else: return None def north(self): return self._neighbor('n') def south(self): return self._neighbor('s') def ea...
return self._neighbor('e') def west(self): return self._neighbor('w')
mozilla/normandy
normandy/studies/migrations/0002_auto_20180510_2256.py
Python
mpl-2.0
272
0.003676
# Generated by Django 2.0.5 on 2018-05-10 22:56 from django.db import migrations class Migration(migrations.Migration): dependencies = [("studies", "0001_initial")] operations = [migrations.Al
terModelOptions(nam
e="extension", options={"ordering": ("-id",)})]
feilaoda/FlickBoard
project/cache/files.py
Python
mit
3,576
0.007271
from markupsafe import escape import re from pymongo.objectid import ObjectId from pymongo.errors import InvalidId from app.people.people_model import People from app.board.board_model import BoardTopic, BoardNode from beaker.cache import CacheManager from beaker.util import parse_cache_config_options from lib.fi...
port html_escape, br_escape cache_opts =
{ 'cache.type': 'file', 'cache.data_dir': '/tmp/caches/data', 'cache.lock_dir': '/tmp/caches/lock', 'cache.regions': 'short_term, long_term', #'cache.short_term.type': 'ext:memcached', #'cache.short_term.url': '127.0.0.1.11211', 'cache.short_term.type': 'file', 'cache.short_term.expire'...
tensor-tang/Paddle
python/paddle/fluid/tests/unittests/test_program_code.py
Python
apache-2.0
2,769
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 app...
Process import signal import numpy import paddle.fluid as fluid import paddle.fluid.layers as layers from paddle.fluid.layers.io import ListenAndServ from paddle.fluid.layers.io import Recv from paddle.fluid.layers.io import Send import paddle.fluid.layers.ops as op
s from paddle.fluid.transpiler.details import program_to_code class TestProgram2Code(unittest.TestCase): def test_print(self): place = fluid.CPUPlace() self.init_serv(place) self.init_client(place, 9123) def init_serv(self, place): main = fluid.Program() with fluid.p...
pymal-developers/pymal
pymal/consts.py
Python
bsd-3-clause
496
0
__authors__ = "" __copyright__ = "(c) 2014, pymal" __li
cense__ = "BSD License" __contact__ = "Name Of Current Guardian of this file <email@address>" USER_AGENT = 'api-indiv-0829BA2B33942A4A5E6338FE05EFB8A1' HOST_NAME = "http://myanimelist.net" DEBUG = False RETRY_NUMBER = 4 RETRY_SLEEP = 1 SHORT_SITE_FORMAT_TIME = '%b %Y' LONG_SITE_FORMAT_TIME = '%b %d, %Y' MALAPPINFO_...
" MALAPPINFO_NONE_TIME = "0000-00-00" MALAPI_FORMAT_TIME = "%Y%m%d" MALAPI_NONE_TIME = "00000000"
inflector/atomspace
tests/cython/bindlink/test_bindlink.py
Python
agpl-3.0
7,002
0.001285
from unittest import TestCase import os from opencog.atomspace import AtomSpace, TruthValue, Atom, types from opencog.bindlink import stub_bindlink, bindlink, single_bindlink,\ first_n_bindlink, af_bindlink, \ satisfaction_link, satisfying_set, \ ...
pencog(self.atomspace) set_type_ctor_atomspace(self.atomspace) # Define several animals and something of a di
fferent type as well InheritanceLink( ConceptNode("Frog"), ConceptNode("animal")) InheritanceLink( ConceptNode("Zebra"), ConceptNode("animal")) InheritanceLink( ConceptNode("Deer"), ConceptNode("animal")) InheritanceLink( ConceptNode("Spaceship"), ConceptNode("machine")...
pybursa/homeworks
i_pogorelko/hw4_i_pogorelko/hw4_solution1.py
Python
gpl-2.0
804
0.008706
#!/usr/bin/env python # -*- coding: <
encoding name> -*- __author__ = "i_pogorelko" __email__ = "i.pogorelko@gmail.com" __date__ = "2014-11-16" text='Proin eget tortor risus. Cras ultricies ligula sed magna dictum porta.\ Donec rutrum cong
ue leo eget malesuada.' def percentage_1(text): print '' print 'input: ', text text = text.lower() text2 = '' for x in text: if ord(x) >= ord('a') and ord(x) <= ord('z'): text2 = text2 + x d = {} m = 0 for j in text2: if d.has_key(j): d[j] += 1....
JournalMap/GeoParsers
pyparser_geoparser_testing.py
Python
gpl-2.0
3,064
0.011624
#parser_testing.py import os, sys, re, StringIO sys.path.append('/Users/Jason/Dropbox/JournalMap/scripts/GeoParsers') #from jmap_geoparser_re import * from jmap_geoparser import * #def test_parsing(): test = "blah blah blah 45º 23' 12'', 123º 23' 56'' and blah blah blah 32º21'59''N, 115º 23' 14''W blah blah blah" co...
tude': -45.38667, 'longitude': 123.39889} test = "32º21'59''N, 115º 23' 14''W" assert coordinate(coordinateParser.parseString(test)).calcDD() == {'latitude': 32.36639, 'longitude': -115.38722} test = "12 43 56 North, 23 56 12 East" assert coordinate
(coordinateParser.parseString(test)).calcDD() == {'latitude': 12.73222, 'longitude': 23.93667} test = "52 15 10N, 0 01 54W" assert coordinate(coordinateParser.parseString(test)).calcDD() == {'latitude': 52.25278, 'longitude': -0.03167} test = "52 35 31N, 1 28 05E" assert coordinate(coordinateParser.parseString(test))...
maraoz/proofofexistence
pycoin/serialize/__init__.py
Python
mit
200
0.01
import bi
nascii def b2h(the_bytes): return binascii.hexlify(the_bytes).decode("utf8") def b2h_rev(the_bytes): return binascii.hexlify(bytearra
y(reversed(the_bytes))).decode("utf8")
Fansion/sharefun
sharefun/__init__.py
Python
mit
5,284
0.000593
# -*- coding: utf-8 -*- __author__ = 'frank' from flask import Flask, request, url_for, render_template, g, session, flash from flask_wtf.csrf import CsrfProtect from flask_debugtoolbar import DebugToolbarExtension from flask.ext.login import LoginManager from flask.ext.moment import Moment from . import filters, pe...
on['user_id']).first() if not user: signout_user() return None return user def create_app(): app = Flas
k(__name__) app.config.from_object(config) # CSRF protect CsrfProtect(app) if app.debug: DebugToolbarExtension(app) register_jinja(app) register_routes(app) register_error_handle(app) register_db(app) register_logger(app) register_login_manager(app) register_moment...
dhcrzf/zulip
zerver/views/muting.py
Python
apache-2.0
2,792
0.005372
from django.http import HttpResponse, HttpRequest from typing import Optional import ujson from django.utils.translation import ugettext as _ from zerver.lib.actions import do_mute_topic, do_unmute_topic from zerver.lib.request import has_request_variables, REQ from zerver.lib.response import json_success, json_erro...
ream, topic_name) return json_success() @has_request_variables def update_muted_topic(request: HttpRequest, user_profile: UserProfile, stream_id: Optional[int]=REQ(validator=check_int, default=None), stream: Optional[str]=REQ(default=None), ...
if op == 'add': return mute_topic( user_profile=user_profile, stream_id=stream_id, stream_name=stream, topic_name=topic, ) elif op == 'remove': return unmute_topic( user_profile=user_profile, stream_id=stream_id, ...
woltage/ansible
lib/ansible/cli/__init__.py
Python
gpl-3.0
20,703
0.007149
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) an...
"and su arguments ('-su', '--su-user', and '--ask-su-pass') " "and become arguments ('--become', '--become-user', and '--ask-become-pass')" " are exclusive of each other") @staticmethod def expand_tilde(option, opt, value, parser): se...
dotKom/onlineweb4
apps/events/tests/all_tests.py
Python
mit
3,574
0.003637
# -*- coding: utf-8 -*- import datetime from django.conf import settings from django.test import TestCase, override_settings from django.utils import timezone from django_dynamic_fixture import G from apps.events.models import AttendanceEvent, Event class EventOrderedByRegistrationTestCase(TestCase): def setUp...
ay + datetime.timedelta(days=30) month_ahead_plus_five = month_ahead + datetime.timedelta(days=5) month_back = today - datetime.timedelta(days=30) normal_event = G(Event, event_start=month_ahead, event_end=month_ahead) pushed_event = G(Event, event_start=month_ahead_plus_five, event_end=...
nceEvent, registration_start=month_back, registration_end=month_back, event=pushed_event) expected_order = [normal_event, pushed_event] with override_settings(settings=self.FEATURED_TIMEDELTA_SETTINGS): self.assertEqual(list(Event.by_registration.all()), expected_order)
nicholasserra/sentry
src/sentry/web/frontend/create_project.py
Python
bsd-3-clause
2,910
0.002062
from __future__ import absolute_import from django import forms from django.contrib import messages from django.core.urlresolvers import reverse from sentry.models import Project, Team from sentry.web.forms.add_project import AddProjectForm from sentry.web.frontend.base import OrganizationView from sentry.utils.http ...
odel = Project def __init__(self, user, team_list, *args, **kwargs): super(AddProjectWithTeamForm, self).__init__(*args, **kwargs) self.team_list = team_list if len(self.team_list) == 1: del self.fields['team'] else: self.fields['t
eam'].choices = ( (t.slug, t.name) for t in team_list ) self.fields['team'].widget.choices = self.fields['team'].choices def clean_team(self): value = self.cleaned_data['team'] for team in self.team_list: if value == team.slug: ...
tpainter/df_everywhere
df_everywhere/test/sdltest/StackOverflow_Question_Code.py
Python
gpl-2.0
1,568
0.017857
import os os.environ["PYSDL2_DLL_PATH"] = os.getcwd() import sdl2 import win32gui def get_windows_bytitle(title_text, exact = False): """ Gets window by title text. [Windows Only] """ def _window_callback(hwnd, all_windows): all_windows.append((hwnd, win32gui.GetWindowText(hwnd))...
hint as recommended by SDL documentation: https://wiki.libsdl.org/SDL_CreateWindowFrom#Remarks r
esult = sdl2.SDL_SetHint(sdl2.SDL_HINT_VIDEO_WINDOW_SHARE_PIXEL_FORMAT, hex(id(a))) print(sdl2.SDL_GetError()) np_window = sdl2.SDL_CreateWindowFrom(window_handle[0]) print(sdl2.SDL_GetError()) np_sur = sdl2.SDL_GetWindowSurface(np_window) print(sdl2.SDL_GetError()) save_sur = sdl2.SDL_CreateRGBSurface(0,np_sur[0].w...
ArioX/tools
shodan.py
Python
gpl-2.0
9,697
0.028359
#!/usr/bin/python # Exploit toolkit using shodan module for search exploit & host lookup # Code : by jimmyromanticdevil # # Download : # Before you run this code you must install shodan lib. # $ wget [url]http://pypi.python.org/packages/source/s/shodan/shodan-0.4.tar.gz[/url] # $ tar xvf shodan-0.2.tar.gz # $ c...
> )| | | | /_______ //__/\_ \| __/ |____/ \____/ |__| |__| \/ \/|__|/ Toolkit Coder by : %s Contach : %s ////////////////////////////////////////////////////// '''%(__Auth__,__Eml__) tayping(title) def expoitdb(): try: searching_Exploit= r...
al'] print '[!]Found [%s] exploit with result [%s]'%(more,searching_Exploit) try: display =raw_input('[!]See all list exploit found?(y/n)') if display =='y': ds = wtf['matches'] for i in ds : print'%s: %s' % (i['id'],i['description'])...
jonathanlurie/BLANK_PY2WX
src/main.py
Python
mit
492
0.006098
# importing wxPython library, see the reference here : # http://www.wxpython.org/docs/a
pi/wx-module.html # and an excelent step by step tutorial there : # http://zetcode.com/wxpython import wx from Controller import * # main function def main(): # each wx application must have a wx.App object app = wx.App
() controller = Controller(title = "BLANK_PY2WX") # entering the endless loop that catches all the events app.MainLoop() if __name__ == '__main__': main()
haimich/knick-knack
doc/folderstructure/v3.2/ .knick-knack/python-fabric/files/setup.py
Python
mit
309
0.02589
import sys from fabric.api
import * from fabric.contrib import * from fabric.contrib.project import rsync_project from defaults import fab from config import ssh, sudoers import {%= name %} @task def prepare_vm(): sudoers.setup_sudoers_on_vm() @task(default=True) def system():
print 'start here'
ryfx/modrana
modules/_mod_clickMenu.py
Python
gpl-3.0
2,761
0.002898
# -*- coding: utf-8 -*- #---------------------------------------------------------------------------- # Menu for quickly adding waypoints when on move #---------------------------------------------------------------------------- # Copyright 2007-2008, Oliver White # # This program is free software: you can redistribute...
TY; 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 this program. If not, see <http://www.gnu.org/licenses/>. #-------------------------...
tModule(*args, **kwargs): return ClickMenu(*args, **kwargs) class ClickMenu(RanaModule): """Overlay info on the map""" def __init__(self, *args, **kwargs): RanaModule.__init__(self, *args, **kwargs) self.lastWaypoint = "(none)" self.lastWaypointAddTime = 0 self.messageLing...
havard024/prego
venv/lib/python2.7/site-packages/django/db/models/base.py
Python
mit
44,041
0.002021
from __future__ import unicode_literals import copy imp
ort sys from functools import update_wrapper from django.utils.six.moves import zip import django.db.models.manager # Imported to register signal handle
r. from django.conf import settings from django.core.exceptions import (ObjectDoesNotExist, MultipleObjectsReturned, FieldError, ValidationError, NON_FIELD_ERRORS) from django.core import validators from django.db.models.fields import AutoField, FieldDoesNotExist from django.db.models.fields.related import (ManyToO...
ericpre/hyperspy
hyperspy/io_plugins/sur.py
Python
gpl-3.0
49,142
0.01691
# -*- coding: utf-8 -*- # # 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 your option) any later version. # # HyperSpy...
'b_unpack_fn': self._get_int32, 'b_pack_fn': self._set_int32, }, "_15_Size_of_Points": { 'value':16, 'b_unpack_fn':lambda f: self._get_int16(f,32), 'b_pack_fn': self._set_int16, }, ...
ue':0, 'b_unpack_fn':self._get_int32, 'b_pack_
buhe/judge
executors/ruby.py
Python
agpl-3.0
393
0.005089
from .base_executor import ScriptExecutor from judgeenv import env class RubyExec
utor(ScriptExecutor): ext = '.rb' name = 'RUBY' address_grace = 65536 fs = ['.*\.(?:so|rb$)', '/etc/localtime$', '/dev/urandom$', '/proc/self', '/usr/lib/ruby/gems/'] test_program = 'puts gets' @classmethod
def get_command(cls): return env['runtime'].get(cls.name.lower())
nachandr/cfme_tests
cfme/containers/service.py
Python
gpl-2.0
4,417
0.002264
import attr from navmazing import NavigateToAttribute from navmazing import NavigateToSibling from cfme.common import Taggable from cfme.common import TagPageView from cfme.containers.provider import ContainerObjectAllBaseView from cfme.containers.provider import ContainerObjectDetailsBaseView from cfme.containers.pro...
etails_view = ServiceDetailsView name = attr.ib() project_name = attr.ib() provider = attr.ib() @attr.s class ServiceCollection(GetRandomInstancesMixin, BaseCollection): """Collection object for :py:class:`Service`.""" ENTITY = Service def all(self): # container_services table has e...
service_table = self.appliance.db.client['container_services'] ems_table = self.appliance.db.client['ext_management_systems'] project_table = self.appliance.db.client['container_projects'] service_query = ( self.appliance.db.client.session .query(service_table.name, p...
buske/variant-subscription-service
vss/scripts/import.py
Python
gpl-3.0
2,871
0.002438
import sys import gzip import logging from csv import DictReader from datetime import datetime from . import app, connect_db from ..constants import DEFAULT_GENOME_BUILD, BENIGN, UNCERTAIN, UNKNOWN, PATHOGENIC from ..extensions import mongo from ..backend import build_variant_doc, get_variant_category, update_variant...
ld_doc, new_doc) def main(clinvar_filename): db = connect_db() notifier = UpdateNotifier(db, app.config) started_at = datetime.utcnow() task_list = [] variant_iterator = iter_variants(clinvar_filename) for i, (old_doc, new_doc) in enumerate(iter_variant_updates(db, variant_iterator)): ...
_doc: # Variant is already known, either: # - someone subscribed before it was added to clinvar, or # - it was already in clinvar, and we might have new annotations task = update_variant_task(db, old_doc, new_doc) else: # Add clinvar annotations with ...
HiSPARC/sapphire
sapphire/simulations/ldf.py
Python
gpl-3.0
16,510
0
""" Lateral distribution functions that can be used for simulating particle densities and for fitting to data. Example usage:: >>> import tables >>> from sapphire import NkgLdfSimulation, ScienceParkCluster >>> data = tables.open_file('/tmp/test_ldf_simulation.h5', 'w') >>> cluster = ScienceParkClus...
f parti
cles in a detector :param detector: :class:`~sapphire.clusters.Detector` for which the number of particles will be determined. :param shower_parameters: dictionary with the shower parameters. """ x, y = detector.xy_coordinates core_x, core_y = shower_pa...
ashander/msprime
msprime/trees.py
Python
gpl-3.0
89,405
0.001455
# -*- coding: utf-8 -*- # # Copyright (C) 2015-2017 University of Oxford # # This file is part of msprime. # # msprime 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 ...
ta: bytes """ def __init__(se
lf, id_, site, node, derived_state, parent, metadata): self.id = id_ self.site = site self.node = node self.derived_state = derived_state self.parent = parent self.metadata = metadata class Migration(SimpleContainer): """ A :ref:`migration <sec_migration_table_d...
patrykomiotek/seo-monitor-api
app/db.py
Python
mit
524
0.003817
import pym
ongo from flask import g from flask import current_app as app def get_db(): if not hasattr(g, 'conn'): print(app.config) g.conn = pymongo.MongoClient( app.config['MONGODB_HOST'], int(app.config['MONGODB_PORT']) ) if not hasattr(g, 'db'): g.db = g.conn[...
n is not None: # conn.close()