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
filipp/Servo
servo/migrations/0014_orderstatus_duration.py
Python
bsd-2-clause
439
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [
('servo', '0013_auto_2015020
4_1113'), ] operations = [ migrations.AddField( model_name='orderstatus', name='duration', field=models.IntegerField(default=0), preserve_default=True, ), ]
wsricardo/mcestudos
treinamento-webScraping/Abraji/p11.py
Python
gpl-3.0
468
0.021786
import urllib.request import
time preço = 99.99 #algum valor maior while preço >= 4.74: pagina = urllib.request.urlopen( 'http://beans.itcarlow.ie/prices-loyalty.html') texto = pagina.read().decode('ut
f8') onde = texto.find('>$') início = onde + 2 fim = início + 4 preço = float(texto[início:fim]) if preço >= 4.74: print ('Espera...') time.sleep(600) print ('Comprar! Preço: %5.2f' %preço)
openEduConnect/eduextractor
eduextractor/sis/illuminate/illuminate_exporter.py
Python
mit
1,702
0.006463
import pandas as pd from ...config import _load_secrets import sqlalchemy import os from tqdm import tqdm class IlluminateSQLInterface: """A class representing a SQL interface to Illuminate """ def __init__(self, secrets=None): if secrets is None: secrets = _load_secrets() ...
file_dir='./sql'): return os.listdir(file_dir) def download_files(): files = self._list_queries() for file_name in tqdm(files): with open('./sql/' + file_name, 'r') as filebuf: data = filebuf.read() df = query_to_df(data)
file_name = file_name.replace('.sql','.csv') df.to_csv('/tmp/' + file_name) if __name__ == '__main__': IlluminateSQLInterface.download_files()
Nablaquabla/sns-analysis
run-ba-analysis-v4.py
Python
gpl-3.0
5,144
0.033826
import os import time as tm import sys # Handles the creation of condor files for a given set of directories # ----------------------------------------------------------------------------- def createCondorFile(dataDir,outDir,run,day,times): # Condor submission file name convention: run-day-time.condor with ope...
6-09-12'] # run = 'Run-15-05-11-11-46-30' # run = 'Run-15-05-19-17-04-44' # run = 'Run-15-05-27-11-13-46' # runDirs = ['Run-15-05-05-16-09-12','Run-15-05-11-11-46-30','Run-15-05-19-17-04-44','Run-15-05-27-11-13-46'] runDirs = ['Run-15-03-27-12-42-26','Run-15-03-30-13-33-05','Run-15-04-08-11-38-28','Run-...
ays_in = {'Run-15-03-27-12-42-26': ['150327','150328','150329','150330'], 'Run-15-03-30-13-33-05': ['150330','150331','150401','150402','150403','150404','150405','150406','150407','150408'], 'Run-15-04-08-11-38-28': ['150408','150409','150410','150411','150412','150413','150414','150415',...
arrabito/DIRAC
Core/Utilities/File.py
Python
gpl-3.0
7,925
0.012744
"""Collection of DIRAC useful file related modules. .. warning:: By default on Error they return None. """ # pylint: skip-file # getGlobbedFiles gives "RuntimeError: maximum recursion depth exceeded" in pylint import os import hashlib import random import glob import sys import re import errno __RCSID__ = "$Id$"...
"" try: return os.stat(fileName)[6] except OSError: return - 1 def getGlobbedTotalSize(files): """Get total size of a list of files or a single file. Globs the parameter to all
ow regular expressions. :params list files: list or tuple of strings of files """ totalSize = 0 if isinstance(files, (list, tuple)): for entry in files: size = getGlobbedTotalSize(entry) if size == -1: size = 0 totalSize += size else: for path in glob.glob(files): if o...
otherway/loc-spain
l10n_es_account_asset/account_asset.py
Python
agpl-3.0
9,813
0.002244
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (c) 2012 Serv. Tecnol. Avanzados (http://www.serviciosbaeza.com) # Pedro Manuel Baeza <pedro.baeza@serviciosbaeza.com> # # This...
General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without ev
en the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############...
ospaceteam/outerspace
client/osci/dialog/ColorDefinitionDlg.py
Python
gpl-2.0
6,398
0.027665
# # Copyright 2001 - 2016 Ludek Smid [http://www.ospace.net/] # # This file is part of Outer Space. # # Outer Space is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (...
display(self, color = None, confirmAction = None): self.confirmAction = confirmAction if color == None: self.color = (0xff,0xff,0xff) else: self.color = color self.show() def show(self): self.win.vR.text = hex(self.color[0]) self.win.vG.text ...
vB.text = hex(self.color[2]) self.win.vRS.slider.min = 0 self.win.vRS.slider.max = 265 self.win.vRS.slider.position = self.color[0] self.win.vGS.slider.min = 0 self.win.vGS.slider.max = 265 self.win.vGS.slider.position = self.color[1] self.win.vBS.slider.min = 0 ...
fharenheit/template-spark-app
src/main/python/mllib/ranking_metrics_example.py
Python
apache-2.0
2,197
0.00091
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
import RegressionMetrics, RankingMetrics # $example off$ from pyspark import SparkContext if __name__ == "__main__": sc = SparkContext(appName="Ranking Metrics Example") # Several of the methods available in scala are currently missing from pyspark # $exampl
e on$ # Read in the ratings data lines = sc.textFile("data/mllib/sample_movielens_data.txt") def parseLine(line): fields = line.split("::") return Rating(int(fields[0]), int(fields[1]), float(fields[2]) - 2.5) ratings = lines.map(lambda r: parseLine(r)) # Train a model on to predic...
ktan2020/legacy-automation
win/Lib/site-packages/jpype/_jpackage.py
Python
mit
1,988
0.013078
#***************************************************************************** # Copyright 2004-2008 Steve Menard # # 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...
e) : if not n[:len("_JPackage")] == '_JPackage' and not intern : # NOTE this shadows name mangling raise RuntimeError, "Cannot set attributes in a package"+n object.__setattr__(self, n, v) def __str__(self) : return "<Java package %s>" % self.__name ...
ble"
kenshay/ImageScript
ProgramData/SystemFiles/Python/Lib/site-packages/spyderlib/widgets/internalshell.py
Python
gpl-3.0
16,008
0.005748
# -*- coding: utf-8 -*- # # Copyright © 2009-2010 Pierre Raybaut # Licensed under the terms of the MIT License # (see spyderlib/__init__.py for details) """Internal shell widget : PythonShellWidget + Interpreter""" # pylint: disable=C0103 # pylint: disable=R0903 # pylint: disable=R0911 # pylint: disable=R0201 #FIXME...
if hasattr(builtins, 'open_in_spyder'): self.connect(self, SIGNAL("go_to_error(QString)"), self.open_with_external_spyder) #------ Interpreter def start_interpreter(self, namespace): """Start Python interpreter""" self.clear() if self....
rpreter = Interpreter(namespace, self.exitfunc, SysOutput, WidgetProxy, DEBUG) self.connect(self.interpreter.stdout_write, SIGNAL("void data_avail()"), self.stdout_avail) self.connect(self.interpreter.stderr_write, SIGNAL("...
ayziao/niascape
niascape/usecase/postcount.py
Python
mit
1,264
0.01494
""" nias
cape.usecase.postcount 投稿件数ユースケース """ import niascape from niascape.repository import postcount from niascape.utility.database import get_db def day(option: dict) -> list: with get_db(niascape.ini['database']) as db: # type: ignore # XXX セクションぶっこむとmypyさんにおこられ 辞書化すべきか return postcount.day(db, **option) def mo...
def hour(option: dict) -> list: with get_db(niascape.ini['database']) as db: # type: ignore # XXX セクションぶっこむとmypyさんにおこられ 辞書化すべきか return postcount.hour(db, **option) def week(option: dict) -> list: with get_db(niascape.ini['database']) as db: # type: ignore # XXX セクションぶっこむとmypyさんにおこられ 辞書化すべきか return postcou...
waseem18/oh-mainline
vendor/packages/celery/funtests/suite/test_leak.py
Python
agpl-3.0
3,713
0.001616
import gc import os import sys import shlex import subprocess sys.path.insert(0, os.getcwd()) sys.path.insert(0, os.path.join(os.getcwd(), os.pardir)) from nose import SkipTest from celery import current_app from celery.tests.utils import unittest import suite GET_RSIZE = "/bin/ps -p %(pid)s -o rss=" QUICKTEST = i...
self.append(item) def average(self): return sum(self) / len(self) class LeakFunCase(unittest.TestCase): def setUp(self): self.app = current_app self.debug = os.enviro
n.get("TEST_LEAK_DEBUG", False) def get_rsize(self, cmd=GET_RSIZE): try: return int(subprocess.Popen( shlex.split(cmd % {"pid": os.getpid()}), stdout=subprocess.PIPE).communicate()[0].strip()) except OSError, exc: raise Ski...
antiface/Django-Actuary
actuary/tasks.py
Python
mit
377
0.005305
from celery.task import Task from celery.registry import tasks import datetime import requests import datetime import settings c
lass Actuary(Task): def run(self, user_id, page, **kwargs): logger = self.get_logger(**kwargs) logger.error("Actuary event captured.") ts = datetime.datetime.now()
print "%s - %s - %s" % (ts, user_id, page)
Shaswat27/scipy
scipy/sparse/csc.py
Python
bsd-3-clause
6,349
0.001733
"""Compressed Sparse Column matrix format""" from __future__ import division, print_function, absolute_import __docformat__ = "restructuredtext en" __all__ = ['csc_matrix', 'isspmatrix_csc'] import numpy as np from scipy._lib.six import xrange from ._sparsetools import csc_tocsr from . import _sparsetools from .sp...
indptr = np.array([0, 2, 3, 6]) >>> indices = np.array([0, 2, 2, 0, 1, 2]) >>> data = np.array([1, 2, 3, 4, 5, 6]) >>> csc_matrix((data, indices, indptr), shape=(3, 3)).toarray() array([[1, 0, 4], [0, 0, 5], [2, 3, 6]]) """ format = 'csc' def transpose(self, copy=Fal...
self.tocsr() for r in xrange(self.shape[0]): yield csr[r,:] def tocsc(self, copy=False): if copy: return self.copy() else: return self def tocsr(self): M,N = self.shape idx_dtype = get_index_dtype((self.indptr, self.indices), ...
ankur0493/google_python_exercises
basic/list2.py
Python
apache-2.0
2,574
0.012044
#!/usr/bin/python -tt # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ # Additional basic list exercises # D. Given a list of numbers, return a list where # al...
te a new list or # modify the passed i
n list. def remove_adjacent(nums): num1 = nums[:] for index,num in enumerate(nums[1:], start=1): if num == nums[index-1]: num1.remove(num) else: pass return num1 # E. Given two lists sorted in increasing order, create and return a merged # list of all the elements in sorted order. You may mo...
nopassword/nopassword.py
tests/test_keyfile.py
Python
apache-2.0
707
0.015559
import math import sys sys.path.append("..") import nopassword print print "Predfined runes" runes = nopassword.get_runes() for k, v in runes.item
s(): print k.ljust(20), len(v),"\t", v p
rint print "Generate alphabets" alphabets = {} length = 5 itterations = 0 rr = runes["digits"] while True: itterations += 1 alphabet = nopassword.generate_alphabet(runes = rr, length=length) if alphabet in alphabets: print "Duplicate after %d itterations" % itterations print "Length:%d\tR...
eayunstack/neutron
neutron/tests/unit/agent/l3/test_dvr_snat_ns.py
Python
apache-2.0
2,142
0
# Copyright (c) 2016 OpenStack Foundation # # 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 ...
d class TestDvrSnatNs(base.BaseTestCase): def setUp(self): super(TestDvrSnatNs, self).setUp() self.conf = mock.Mock() self.conf.state_path = cfg.CONF.state_path self.driver = mock.Mock() self.driver.DEV_NAME_LEN = 14 self.router_id = _uuid() self.snat_ns = d...
use_ipv6=False) @mock.patch.object(utils, 'execute') @mock.patch.object(ip_lib, 'create_network_namespace') @mock.patch.object(ip_lib, 'network_namespace_exists') def test_create(self, exists, create, execute): exists.return_value = False self.snat_ns.create() ...
lvisdd/qnabot
webapp/data/jmafaq.py
Python
mit
3,058
0.024526
# -*- coding: utf-8 -*- import csv import os import re try: # Python 3 from urllib import request except ImportError: # Python 2 import urllib2 as request from bs4 import BeautifulSoup def extractFaqURL(url): html = request.urlopen(url).rea
d() soup = BeautifulSoup(html, "html.parser") faqs = soup.find_all("ul", class_="pagelink mtx") urls = [] for faq in faqs: for a in faq.findAll('a'): try: pattern = r"^http://" if re.match(pattern , a.attrs['href']): # urls.append(a.attrs['href']) pass ...
except Exception as ex: print(ex) # print(urls) return urls def extractFaqText(url): html = request.urlopen(url).read() soup = BeautifulSoup(html, "html.parser") if soup.find_all("div", class_="qa-box"): main = soup.find_all("div", class_="qa-box") else: main = soup.f...
chudichudichudi/neuro-tedx-2
tedx2/extensions.py
Python
bsd-3-clause
655
0.010687
# -*- coding: utf-8 -*- """Extensions module. Each extension is initialized in the app fact
ory located in app.py """ from flask.ext.bcrypt import Bcrypt bcrypt = Bcrypt() from flask.ext.login import LoginManager login_manager = LoginManager() from flask.ext.sqlalchemy import SQLAlchemy db = SQLAlchemy() from flask.ext.migrate import Migrate migrate = Migrate() from flask.ext.cache import Cache cache = C...
rom flask.ext.admin import Admin admin = Admin(url='/its_a_secret')
BillBillBillBill/Tickeys-linux
tickeys/kivy_32/kivy/uix/bubble.py
Python
mit
12,590
0.000715
''' Bubble ====== .. versionadded:: 1.1.0 .. image:: images/bubble.jpg :align: right The Bubble widget is a form of menu or a small popup where the menu options are stacked either ve
rtically or horizontally. The :class:`Bubble` contains an arrow pointing in the direction you choose. Simple example ------
-------- .. include:: ../../examples/widgets/bubble_test.py :literal: Customize the Bubble -------------------- You can choose the direction in which the arrow points:: Bubble(arrow_pos='top_mid') The widgets added to the Bubble are ordered horizontally by default, like a Boxlayout. You can change that by:...
mn1del/rpi_cnc_img
secondboot_arduino.py
Python
gpl-3.0
1,627
0.014136
#!/usr/bin/env python # deals with uploading grbl to arduino # placed in a separate script to secondboot.py because I couldn't figure out how to CD into # the right directory within python, so instead I'll do the "cd'ing" in rc.local, and call standalone script*** #*** EDIT: apparently passing cwd="directory" as an ar...
cwd="") # test that the sketch compiles sp.call(["sudo", "make", "upload"], cwd="/usr/share/arduino/libraries/grbl
/examples/GRBLtoArduino") # upload to arduino # set call for everyboot.py # replaces previous call for secondboot.py #sp.call(["sudo", "sed", "-i", "/cd \/home\/pi/,/^exit 0/{//!d}", "/etc/rc.local"]) sp.call(["sudo", "sed", "-i", "/^exit 0/ i\sudo python /home/pi/rpi_cnc_img/everyboot.py", "/etc/rc.local"]) #check b...
Ultimaker/Cura
plugins/DigitalLibrary/src/ExportFileJob.py
Python
lgpl-3.0
2,208
0.00317
# Copyright (c) 2021 Ultimaker B.V. # Cura is released under the terms of the LGPLv3 or higher. import io from typing import List, Optional, Union from UM.FileHandler.FileHandler import FileHandler from UM.FileHandler.FileWriter import FileWriter from UM.FileHandler.WriteFileJob import WriteFileJob from UM.Logger imp...
de") super().__init__(file_writer, self.createStream(mode = mode), nodes, mode) # Determine the filename. self.setFileName("{}.{}".format(job_name, extension))
def getOutput(self) -> bytes: """Get the job result as bytes as that is what we need to upload to the Digital Factory Library.""" output = self.getStream().getvalue() if isinstance(output, str): output = output.encode("utf-8") return output def getMimeType(self) -> ...
ayust/pluss
pluss/util/ratelimit.py
Python
mit
1,111
0.007201
import functools from pluss.app import app from pluss.util.cache import Cache RATE_LIMIT_
CACHE_KEY_TEMPLATE = 'pluss--remoteip--ratelimit--1--%s'
def ratelimited(func): """Includes the wrapped handler in the global rate limiter (60 calls/min).""" @functools.wraps(func) def wrapper(*args, **kwargs): ratelimit_key = RATE_LIMIT_CACHE_KEY_TEMPLATE % flask.request.remote_addr # Increment the existing minute's counter, or start a new one...
mtils/ems
ems/qt/graphics/storage/dict_scene_serializer.py
Python
mit
921
0.003257
from ems.qt.graphics.storage.interfaces import SceneSerializer from ems.qt.graphics.page_item import PageItem class DictSceneSerializer(SceneSerializer): def serialize(self, scene, tools):
saveData = { '@author': 'Michael Tils', '@desciption': 'Graphics Scene Contents', '@data': { 'pages': []
} } items = [] for item in scene.items(): if isinstance(item, PageItem): continue items.append(tools.serialize(item)) saveData['@data']['pages'].append({'items':items}) return saveData def deserialize(self, sceneData, scene, tool...
miltonsarria/dsp-python
filters/FIR/filter_sine1.py
Python
mit
1,128
0.027482
#Milton Orlando Sarria #filtrado elemental de ruido sinusoidal from scipy import signal import matplotlib.pyplot as plt import numpy as np #disenar el filtro usando una ventana hamming b = signal.firwin(9, 0.8, window='hamming', pass_zero=True) #definir la frecuencia de mu
estreo y generar un vector de tiempo hasta 5 segundos fs=1e3 longitud = 5 t=np.linspace(1./fs,longitud,fs*longitud); F=10 #frecuencia fundamental 10 hz w=2*np.pi*F #frecuencia an
gular Vm=4 #valor de amplitud de la onda #generar onda sinusoidal pura x=Vm*np.cos(w*t) #generar onda de ruido sinusoidal, alta frecuencia y baja amplitud #usar una frecuencia 30 veces mayor a la inicial ruido=2*np.cos(30*w*t) #onda con ruido: sumar las dos sinusoidales x_n=x+ruido #filtrar la onda con rui...
ricomoss/open-west-2015-fixtureless
owc_fixtureless/owc_fixtureless/tests.py
Python
mit
927
0
from django.test import TestCase from fixtureless import Factory from owc_fixtureless import co
nstants from owc_fixtureless import models class MageTestCase(TestCase): def setUp(self): self.factory = Factory() def test_brothers_in_arms(self): # Exclude the mage itself mage_1 = self.factory.create( models.Mage, {'magic_type': constants.ARCANE}) expected = 0 ...
rothers_in_arms.count(), expected) # Let's add another mage with another magic_type self.factory.create(models.Mage, {'magic_type': constants.BLACK}) expected = 0 self.assertEqual(mage_1.brothers_in_arms.count(), expected) # Let's add another mage with the same magic_type ...
hydroshare/hydroshare
hs_core/migrations/0036_auto_20171117_0422.py
Python
bsd-3-clause
639
0.00313
# -*- coding: utf-8 -*- from dja
ngo.db import migrations, models import django.contrib.postgres.fields.hstore class Migration(migrations.Migration): dependencies = [ ('hs_core', '0035_remove_deprecated_fields'), ] operations = [ migrations.AddField( model_name='contributor', name='identifiers', ...
d=django.contrib.postgres.fields.hstore.HStoreField(default={}), ), migrations.AddField( model_name='creator', name='identifiers', field=django.contrib.postgres.fields.hstore.HStoreField(default={}), ), ]
pramitchoudhary/Experiments
notebook_gallery/other_experiments/explore-models/modelinterpretation/lime/LIME_Explanation.py
Python
unlicense
3,638
0.007971
# coding: utf-8 # In[1]: import lime import sklearn import numpy as np import sklearn import sklearn.ensemble import sklearn.metrics from __future__ import print_function # In[2]: from sklearn.datasets import fetch_20newsgroups categories = ['alt.atheism', 'soc.religion.christian'] newsgroups_train = fetch_20news...
rn.metrics.accuracy_score(labels_test, rf.predict(test)) # In[101]: import pandas as pd pd.DataFrame(test).head() # In[115]: explainer
= lime.lime_tabular.LimeTabularExplainer(train, feature_names=iris.feature_names, class_names=iris.target_names, discretize_continuous=True) i = np.random.randint(0, test.shape[0]) exp_num = explainer.explain_instance(test[i], rf.predict_proba, num_features=4, top_la...
paulross/cpip
tests/integration/util/UnitTestsPerf.py
Python
gpl-2.0
4,715
0.009332
#!/usr/bin/env python # CPIP is a C/C++ Preprocessor implemented in Python. # Copyright (C) 2008-2017 Paul Ross # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License...
########### def usage(): print( """spam.py - Usage: python spam.py [-hl: --help] Options: -h, --help ~ Help (this screen) and exit. -l: ~ set the logging level higher is quieter. Default is 20 (INFO) e.g.: CRITICAL 50 ERROR 40 WARNING ...
' % (__version__, __date__)) print('Author: %s' % __author__) print(__rights__) print import sys, getopt print('Command line:') print(' '.join(sys.argv)) print() try: opts, args = getopt.getopt(sys.argv[1:], "hl:", ["help",]) except getopt.GetoptError as myErr: usage(...
kadarakos/funktional
funktional/context.py
Python
mit
540
0.007407
imp
ort sys from contextlib import contextmanager # Are we training (or testing) training = False @contextmanager def context(**kwargs): """Temporarily change the values of context variables passed. Enables the `with` syntax: >>> with context(training=True): ... """ current = dict((k, getattr...
urrent.items(): setattr(sys.modules[__name__], k, v)
vponomaryov/manila
manila/tests/api/v1/test_limits.py
Python
apache-2.0
29,404
0.000034
# Copyright 2011 OpenStack LLC. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # #
http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific langua...
sions and limitations # under the License. """ Tests dealing with HTTP rate-limiting. """ from oslo_serialization import jsonutils import six from six import moves from six.moves import http_client import webob from manila.api.v1 import limits from manila.api import views import manila.context from manila import ...
AsherBond/MondocosmOS
grass_trunk/temporal/tr3.unregister/tr3.unregister.py
Python
agpl-3.0
1,642
0.017052
#!/usr/bin/env python # -*- coding: utf-8 -*- ##################
########################################################## # # MODULE: tr3.unregister # AUTHOR(S): Soeren Gebbert # # PURPOSE: Unregister raster3d maps from space time raster3d datasets # COPYRIGHT: (C) 2011 by the GRASS Development Team # # This program is free software under the GNU General Public # ...
####### #%module #% description: Unregister raster3d map(s) from a specific or from all space time raster3d dataset in which it is registered #% keywords: spacetime raster3d dataset #% keywords: raster3d #%end #%option #% key: dataset #% type: string #% description: Name of an existing space time raster3d dataset. If...
deepforge-dev/deepforge-keras
test/test-cases/activations.py
Python
apache-2.0
2,712
0.000369
from __future__ import absolute_import import six import warnings from . import backend as K from .utils.generic_utils import deserialize_keras_object from .engine import Layer def softmax(x, axis=-1): """Softmax activation function. # Arguments x : Tensor. axis: Integer, axis along which the...
else: raise ValueError('Cannot apply softmax to a tensor that is 1D') def elu(x, alpha=1.0): return K.elu(x, alpha) def selu(x): """Scaled Exponential Linear Unit. (Klambauer et al., 2017) # Arguments x: A tensor or variable to compute the activation function for. # References...
Self-Normalizing Neural Networks](https://arxiv.org/abs/1706.02515) """ alpha = 1.6732632423543772848170429916717 scale = 1.0507009873554804934193349852946 return scale * K.elu(x, alpha) def softplus(x): return K.softplus(x) def softsign(x): return K.softsign(x) def relu(x, alpha=0., max_v...
amagdas/superdesk
server/apps/item_lock/components/item_lock.py
Python
agpl-3.0
5,241
0.00229
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license from ..mode...
t(item, user_id) if can_user_edi
t: if item.get(LOCK_USER): if str(item.get(LOCK_USER, '')) == str(user_id) and str(item.get(LOCK_SESSION)) != str(session_id): return False, 'Item is locked by you in another session.' else: if str(item.get(LOCK_USER, '')) != str(user_i...
tilacog/rows
rows/cli.py
Python
gpl-3.0
4,322
0.000231
# coding: utf-8 # Copyright 2014-2015 Álvaro Justen <https://github.com/turicas/rows/> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at yo...
this whole module # TODO: add option to pass 'create_table' options in command-line (like force # fields) import click import rows from rows.utils import import_from_uri, export_to_uri @click.group() def cli(): pass @cli.command(help='Convert table on `source` URI to `destination`') @click.option('--i...
, default='utf-8') @click.option('--output-encoding', default='utf-8') @click.option('--input-locale', default='en_US.UTF-8') @click.option('--output-locale', default='en_US.UTF-8') @click.argument('source') @click.argument('destination') def convert(input_encoding, output_encoding, input_locale, output_locale, ...
fokusov/moneyguru
core/model/date.py
Python
gpl-3.0
21,665
0.004339
# Created By: Eric Mc Sween # Created On: 2007-12-12 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-...
nge. That is, the part of the range that is earlier than today. """ today = date.today() if self.end < today: return self
else: return DateRange(self.start, today) class NavigableDateRange(DateRange): """A navigable date range. Properly implements navigation-related methods so that subclasses don't have to. Subclasses :class:`DateRange`. """ def adjusted(self, new_date): result = self.around(new...
tbelhalfaoui/giddle
giddle/controllers/autocomplete_api.py
Python
gpl-2.0
2,924
0.005472
import logging import requests from collections import OrderedDict import operator as op from ..lib import text from ..controllers.request_maker import Reque
stMaker, RequestException class AutocompleteApi(object): base_url
= 'http://suggestqueries.google.com/complete/search' base_params = {'client': 'firefox'} def __init__(self, n_secondary_results=0): self.n_secondary_results = n_secondary_results self.request_maker = RequestMaker() self.tokenise = text.get_tokeniser(clean=False) def run(se...
wileeam/airflow
tests/providers/amazon/aws/sensors/test_sagemaker_base.py
Python
apache-2.0
4,728
0.000212
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
: class SageMakerBaseSensorSubclass(SageMakerBaseSensor): def non_terminal_states(self): return ['PENDING', 'RUNNING', 'CONTIN
UE'] def failed_states(self): return ['FAILED'] def get_sagemaker_response(self): return { 'SomeKey': {'State': 'PENDING'}, 'ResponseMetadata': {'HTTPStatusCode': 200} } def state_from_response...
statik/grr
lib/flows/general/timelines_test.py
Python
apache-2.0
1,939
0.011346
#!/usr/bin/env python # -*- mode: python; encoding: utf-8 -*- """Tests for the Timelines flow.""" from grr.lib import action_mocks from grr.lib import aff4 from grr.lib import flags from grr.lib
import test_lib
# pylint: disable=unused-import from grr.lib.flows.general import timelines as _ # pylint: enable=unused-import from grr.lib.rdfvalues import paths as rdf_paths class TestTimelines(test_lib.FlowTestsBaseclass): """Test the timelines flow.""" client_id = "C.0000000000000005" def testMACTimes(self): """Test...
KelSolaar/sIBL_GUI
sibl_gui/globals/ui_constants.py
Python
gpl-3.0
9,825
0.002239
#!/usr/bin/env python # -*- coding: utf-8 -*- """ **ui_constants.py** **Platform:** Windows, Linux, Mac Os X. **Description:** Defines **sIBL_GUI** package ui constants through the :class:`UiConstants` class. **Others:** """ from __future__ import unicode_literals __author__ = "Thomas Mansencal" __copyri...
g" """ :param miscellaneous_hover_icon: Application **Miscellaneous** hover icon. :type miscellaneous_hover_icon: unicode """ miscellaneous_active_icon = "images/Miscellaneous_Active.png" """ :param miscellaneous_active_icon: Applic
ation **Miscellaneous** active icon. :type miscellaneous_active_icon: unicode """ library_icon = "images/Library.png" """ :param library_icon: Application **Library** icon. :type library_icon: unicode """ library_hover_icon = "images/Library_Hover.png" """ :param library_hover_i...
pjryan126/solid-start-careers
store/api/zillow/venv/lib/python2.7/site-packages/pandas/tests/frame/test_replace.py
Python
gpl-2.0
42,783
0.000093
# -*- coding: utf-8 -*- from __future__ import print_function from datetime import datetime import re from pandas.compat import (zip, range, lrange, StringIO) from pandas import (DataFrame, Series, Index, date_range, compat, Timestamp) import pandas as pd from numpy import nan import numpy as np...
taFrame(obj) # lists of regexes and values # list of [re1, re2, ..., reN] -> [v1, v2, ..., vN] to_replace_res = [r'\s*\.\s*', r'e|f|g'] values = [nan, 'cr
ap'] res = dfobj.replace(to_replace_res, values, regex=True) expec = DataFrame({'a': ['a', 'b', nan, nan], 'b': ['crap'] * 3 + ['h'], 'c': ['h', 'crap', 'l', 'o']}) assert_frame_equal(res, expec)
mancoast/CPythonPyc_test
cpython/242_test_codecs.py
Python
gpl-3.0
27,615
0.001811
from test import test_support import unittest import codecs import sys, StringIO class Queue(object): """ queue: write bytes at one end, read bytes from the other end """ def __init__(self): self._buffer = "" def write(self, chars): self._buffer += chars def read(self, size=-1...
Request.getArg()\r\n', 'if arg=="today":\r\n', ' #-------------------- TODAY\'S ARTICLES\r\n', ' self.write("<h2>Today\'s articles</h2>")\r\n', ' showdate = frog.util.isodatestr() \r\n', ' entries = readArticlesFromDate(showdate)\r\n',
'elif arg=="active":\r\n', ' #-------------------- ACTIVE ARTICLES redirect\r\n', ' self.Yredirect("active.y")\r\n', 'elif arg=="login":\r\n', ' #-------------------- LOGIN PAGE redirect\r\n', ' self.Yredirect("login.y")\r\n', ...
rehmanz/salt-reactors-demo
salt/formulas/base/reactor/ui_reactor.py
Python
mit
2,365
0.00592
#!/usr/bin/env python import os import time import logging import argparse from Queue import Queue from threading import Thread from salt.utils.event import LocalClientEvent LOGGER = logging.getLogger() MAX_TIMEOUT_VALUE=60*5 def __parse_record(event): payload = event.get('data', {}) return payload.get('rec...
vironment tag_id = 'salt/%s/ui/slave/dead' %(target_env) client = LocalClientEvent("/var/run/salt/master") # Setup file handler fh= logging.FileHandler("/var/log/%s.log" %target_env) fh.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')...
) worker = Thread(target=process_events) worker.setDaemon(True) worker.start() while True: event_payload = get_event_payload(tag_id) q.put(event_payload) LOGGER.info("Received an event=%s" %event_payload)
leetreveil/tulip
examples/cachesvr.py
Python
apache-2.0
9,357
0
"""A simple memcache-like server. The basic data structure maintained is a single in-memory dictionary mapping string keys to string values, with operations get, set and delete. (Both keys and values may contain Unicode.) This is a TCP server listening on port 54321. There is no authentication. Requests provide an...
st_type is None: return {'error': 'no type in request'} if request_type not in {'get', 'set', 'delete'}: return {'error': 'unknown request type'} key = request.get('key') if not isinstance(key, str):
return {'error': 'key is not a string'} if request_type == 'get': return self.handle_get(key) if request_type == 'set': value = request.get('value') if not isinstance(value, str): return {'error': 'value is not a string'} return...
cbertinato/pandas
pandas/tests/io/parser/test_mangle_dupes.py
Python
bsd-3-clause
3,885
0
""" Tests that duplicate columns are handled appropriately when parsed by the CSV engine. In general, the expected result is that they are either thoroughly de-duplicated (if mangling requested) or ignored otherwise. """ from io import StringIO import pytest from pandas import DataFrame import pandas.util.testing as ...
"a.1.1.1.1", "a.1.1.1.1.1"])), ("a,a,a.3,a.1,a.2,a,a\n1,2,3,4,5,6,7", DataFrame([[1, 2, 3, 4, 5, 6, 7]], columns=["a", "a.1", "a.3", "a.1.1",
"a.2", "a.2.1", "a.3.1"])) ]) def test_thorough_mangle_columns(all_parsers, data, expected): # see gh-17060 parser = all_parsers result = parser.read_csv(StringIO(data)) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("data,names,expected", [ ("a,b,b\n1,2,3"...
taghq/radcity_site
pdxrad/cms_plugins.py
Python
apache-2.0
573
0.005236
from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_po
ol from cms.models.pluginmodel import CMSPlugin from django.utils.translation import ug
ettext_lazy as _ from .models import Feature class FeaturePlugin(CMSPluginBase): model = Feature name = _("RAD Feature Plugin") render_template = "plugins/feature.html" cache = False def render(self, context, instance, placeholder): context = super(FeaturePlugin, self).render(context, ins...
GoogleCloudPlatform/sap-deployment-automation
third_party/github.com/ansible/awx/awx_collection/plugins/modules/tower_receive.py
Python
apache-2.0
5,506
0.001453
#!/usr/bin/python # coding: utf-8 -*- # (c) 2017, John Westcott IV <john.westcott.iv@redhat.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': ...
ements='str'), job_template=dict(type='list', default=[], elements='str'), notification_
template=dict(type='list', default=[], elements='str'), organization=dict(type='list', default=[], elements='str'), project=dict(type='list', default=[], elements='str'), team=dict(type='list', default=[], elements='str'), user=dict(type='list', default=[], elements='str'), workf...
lsalzman/iqm
blender-2.49/iqm_export.py
Python
mit
40,875
0.006312
#!BPY """ Name: 'Inter-Quake Model' Blender: 249 Group: 'Export' Tip: 'Export Inter-Quake Model files' """ import struct, math import Blender import BPyArmature IQM_POSITION = 0 IQM_TEXCOORD = 1 IQM_NORMAL = 2 IQM_TANGENT = 3 IQM_BLENDINDEXES = 4 IQM_BLENDWEIGHTS = 5 IQM_COLOR ...
esttri] scores[besttri] = -666.0 trischedule.append(tri) for v in tri: if v.cacherank < 0: # debug info vertloads += 1 # debug info if v.index < 0: v.index = len(vertschedule) vertsc...
in tri if v.uses ] + [ v for v in vcache if v.cacherank >= 0 ] for i, v in enumerate(vcache): v.cacherank = i v.calcScore() besttri = -1 bestscore = -42.0 for v in vcache: for i in v.uses: v0, ...
webcomponents/webcomponents.org
src/datamodel_test.py
Python
apache-2.0
5,078
0.007089
from datamodel import Library, Version, Status, VersionCache, CollectionReference, Dependency from google.appengine.ext import ndb from test_base import TestBase class VersionCacheTests(TestBase): def test_versions_for_key(self): library_key = ndb.Key(Library, 'a/b') Version(id='v2.0.0', sha='x', status=St...
_key).put() Version(id='v4.0.0', sha='x', status=Status.error, parent=library_key).put() Version(id='v5.0.0', sha='x', status=Status.pending, parent=library_key).put() Version(id='xxx', sha='x', status=Status.ready, parent=library_key).put() versions = yield Library.uncached_versions_for_key_async(
library_key) self.assertEqual(versions, ['v1.0.0', 'v2.0.0', 'v3.0.0']) @ndb.toplevel def test_version_cache(self): library_key = ndb.Key(Library, 'a/b') Version(id='v2.0.0', sha='x', status=Status.ready, parent=library_key).put() Version(id='v1.0.0', sha='x', status=Status.ready, parent=library_ke...
devopshq/vspheretools
pysphere/ZSI/generate/pyclass.py
Python
mit
9,999
0.007101
############################################################################ # Joshua R. Boverhof, LBNL # See LBNLCopyright for copyright notice! ########################################################################### import pydoc, sys from pysphere.ZSI import TC # If function.__name__ is read-only, fail def _x()...
t(self): return getattr(self, what.aname) if what.maxOccurs > 1: def _set(self, value): if not (value is None or hasattr(value, '__iter__')): raise Typ
eError('expecting an iterable instance') setattr(self, what.aname, value) else: def _set(self, value): setattr(self, what.aname, value) else: def get(self): return getattr(self, what().aname) if what.max...
nwoeanhinnogaehr/live-python-jacker
examples/pitchshift.py
Python
gpl-3.0
349
0.002865
fr
om stft import STFT from pvoc import PhaseVocoder import numpy as np stft = STFT(1024, 2, 4) pvoc = PhaseVocoder(stft) def process(input, output): for x in stft.forward(input): x = pvoc.forward(x) x = pvoc.shift(x, lambda y: y * 1.5) x = pvoc.backward(x)
stft.backward(x) stft.pop(output) output *= 2
divmain/GitSavvy
common/util/file.py
Python
mit
4,644
0.000861
from collections import defaultdict from contextlib import contextmanager import os import plistlib import re import threading import yaml import sublime MYPY = False if MYPY: from typing import DefaultDict, List, Optional if 'syntax_file_map' not in globals(): syntax_file_map = defaultdic
t(list) # type: DefaultDict[str, List[str]] if 'determine_syntax_thread' not in globals(): determine_syntax_thread = None def determine_syntax_files(): # type: () -> None global determine_syntax_thread if not syntax_file_map: determine_syntax_thread
= threading.Thread( target=_determine_syntax_files) determine_syntax_thread.start() def try_parse_for_file_extensions(text): # type: (str) -> Optional[List[str]] match = re.search(r"^file_extensions:\n((.*\n)+?)^(?=\w)", text, re.M) if match: return _try_yaml_parse(match.group...
braams/shtoom
shtoom/doug/conferencing.py
Python
lgpl-2.1
8,770
0.005701
"Conferencing code" # XXX A relatively simple enhancement to this would be to store the # volumes for each source in the conference, and use an exponential # decay type algorithm to determine the "loudest". from shtoom.doug.source import Source from twisted.internet.task import LoopingCall from twisted.python impor...
hasattr(self._audioCalcLoop, 'cancel'): self._audioCalcLoop.cancel() else:
self._audioCalcLoop.stop() # XXX close down any running sources! self._members = Set() del self._audioOut self._open = False removeRoom(self._name) def addMember(self, confsource): self._members.add(confsource) if CONFDEBUG: print "added...
gilt/nova
nova/core/cfn_pyplates/options.py
Python
mit
1,386
0
# Copyright (c) 2013 MetaMetrics, Inc. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, d...
u can enter it now (or
leave blank for None/null): > ''' class OptionsMapping(defaultdict): def __init__(self, *args, **kwargs): super(OptionsMapping, self).__init__(None, *args, **kwargs) def __missing__(self, key): try: value = input(prompt_str.format(key)) except KeyboardInterrupt: ...
hsolbrig/shexypy
shexypy/utils/dict_compare.py
Python
mit
3,967
0.005294
# -*- coding: utf-8 -*- # Copyright (c) 2015, Mayo Clinic # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # Redistributions of source code must retain the above copyright notice, this # list...
keys()) - set(d2.keys()))): if not f((e, d1[e]), None): n_errors += 1 print("+ %s:
%s" % (n1(e), d1[e]), file=file) for e in sorted(list(set(d2.keys()) - set(d1.keys()))): if not f(None, (e, d2[e])): n_errors += 1 print("- %s: %s" % (n2(e), d2[e]), file=file) for k, v in sorted(d1.items()): if k in d2 and d2[k] != d1[k] and not f((k, d1[k]), (k, d2[k])...
openstack/python-congressclient
doc/source/conf.py
Python
apache-2.0
3,547
0.000282
# -*- coding: utf-8 -*- # 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...
e name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of glob-style pattern
s that should be excluded when looking for # source files. They are matched against the source file names relative to the # source directory, using slashes as directory separators on all platforms. exclude_patterns = ['reference/api/congressclient.tests.*'] # -- Options for HTML output --------------------------------...
SuLab/biothings.api
biothings/www/api/es/handlers/query_handler.py
Python
apache-2.0
15,331
0.006392
from tornado.web import HTTPError from biothings.www.api.es.handlers.base_handler import BaseESRequestHandler from biothings.www.api.es.transform import ScrollIterationDone from biothings.www.api.es.query import BiothingScrollError, BiothingSearchError from biothings.www.api.helper import BiothingParameterTypeError fro...
Tornado handler `.initialize() <http://www.tornadoweb.org/en/stable/web.html#tornado.web.RequestHandler.initialize>`_ function for all requests to the query endpoint. Here, the allowed arguments are set (depending on the request method) for each kwarg category.''' super(QueryHandler, self
).initialize(web_settings) self.ga_event_object_ret['action'] = self.request.method if self.request.method == 'GET': self.ga_event_object_ret['action'] = self.web_settings.GA_ACTION_QUERY_GET self.control_kwargs = self.web_settings.QUERY_GET_CONTROL_KWARGS self.es_kwa...
adngdb/socorro
alembic/versions/3a5471a358bf_adding_a_migration_f.py
Python
mpl-2.0
1,624
0.010468
"""Adding a migration for the exploitability report. Revision ID: 3a5471a358bf Revises: 191d0453cc07 Create Date: 2013-10-25 07:07:33.968691 """ # revision identifiers, used by Alembic. revision = '3a5471a358bf' down_revision = '4aacaea3eb48' from alembic import op from socorro.lib import citexttype, jsontype from ...
eports', sa.Column(u'product_version_id', sa.INTEGER(), nullable=False)) ### end Alembic commands ### load_stored_proc(op, ['update_exploitability.sql']) for i in range(15, 30): backfill_date = '2013-11-%s' % i op.execute(""" SELECT backfill_exploitability('%s') ...
ill_date) op.execute(""" COMMIT """) def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_column(u'exploitability_reports', u'product_version_id') op.drop_column(u'exploitability_reports', u'product_name') op.drop_column(u'exploitability_reports', u'version_string')...
mlperf/training_results_v0.7
Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/tvm/tests/python/relay/test_op_level5.py
Python
apache-2.0
27,128
0.003834
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
for j in range(in_width): center_w = (j + offset_w) * steps_w for k in range(num_sizes + num_ratios - 1):
w = size_ratio_concat[k] * in_height / in_width / 2.0 if k < num_sizes else \ size_ratio_concat[0] * in_height / in_width * math.sqrt(size_ratio_concat[k + 1]) / 2.0 h = size_ratio_concat[k] / 2.0 if k < num_sizes else \ size_ratio_conc...
baalkor/timetracking
opconsole/templatetags/duration.py
Python
apache-2.0
253
0.007905
from django impor
t template register = template.Library() @register.filter def duration(td): seconds = td minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60) return "%d:%02d:%02d" % (hours, minutes, seconds)
xzturn/tensorflow
tensorflow/python/training/warm_starting_util.py
Python
apache-2.0
23,798
0.005042
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
name: # Assume tensor name remains the same. prev_tensor_name = current_var_name return prev_tensor_name, var # pylint: disable=protected-access # Accesses protected members of tf.Variable to reset the variable's internal # state. def _warm_start_var_with_vocab(var, current_v...
prev_ckpt, prev_vocab_path, previous_vocab_size=-1, current_oov_buckets=0, prev_tensor_name=None, initializer=None, ...
intel-ctrlsys/actsys
actsys/control/commands/resource_pool/resource_pool_remove.py
Python
apache-2.0
933
0.003215
# -*- coding: utf-8 -*- # # Copyright (c) 2016 Intel Corp. # """ Resource Pool Remove Plugin """ from control.commands.command import CommandResult from control.plugin.manager import DeclarePlugin from .resource_p
ool import ResourcePoolCommand @DeclarePlugin('resource_pool_remove', 100) class ResourcePoolRemoveCommand(ResourcePoolCommand): """ResourcePoolRemoveCommand""" def __init__(self, device_name, configuration, plugin_manager, logger=None): """Retrieve dependencies and prepare for power on""" Re...
ce_name, configuration, plugin_manager, logger) def execute(self): """Execute the command""" setup_results = self.setup() if setup_results is not None: return setup_results ret_code, message = self.resource_manager.remove_nodes_from_resource_pool(self.device_name) ...
lmazuel/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2017_11_01/models/virtual_network_gateway_connection_list_entity_py3.py
Python
mit
7,889
0.004056
# 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 ...
'}, 'virtual_network_gateway2': {'key': 'properties.virtualNetworkGateway2', 'type': 'VirtualNetworkConnectionGatewayReference'}, 'local_network_gateway2': {'key': 'properties.localNetworkGateway2', 'type': 'VirtualNetworkConnectionGatewayReference'}, 'con
nection_type': {'key': 'properties.connectionType', 'type': 'str'}, 'routing_weight': {'key': 'properties.routingWeight', 'type': 'int'}, 'shared_key': {'key': 'properties.sharedKey', 'type': 'str'}, 'connection_status': {'key': 'properties.connectionStatus', 'type': 'str'}, 'tunnel_conn...
TheStackBox/xuansdk
SDKLibrary/com/cloudMedia/theKuroBox/sdk/paramComponents/kbxSlider.py
Python
gpl-3.0
1,696
0.005896
################################
############################################################## # Copyright 2014-2015 Cloud Media Sdn. Bhd. # # This file is part of Xuan Application Development SDK. # # Xuan A
pplication Development SDK 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. # # Xuan Application Development SDK is distributed in ...
th0th/harmony
setup.py
Python
gpl-3.0
403
0
# -*- coding: utf-8 -*- from dis
tutils.core import setup setup( name='Harmony', version='0.1', author='H. Gökhan Sarı', author_email='th0th@returnfalse.net', packages=['harmony'], scripts=['bin/harmony'], url='https://github.com/th0th/harmony/', license='LICENSE.txt', description='Musi
c folder organizer.', long_description=open('README.asciidoc').read(), )
MakeHer/edx-platform
common/lib/xmodule/xmodule/contentstore/content.py
Python
agpl-3.0
14,964
0.003609
import re import uuid from xmodule.assetstore.assetmgr import AssetManager XASSET_LOCATION_TAG = 'c4x' XASSET_SRCREF_PREFIX = 'xasset:' XASSET_THUMBNAIL_TAIL_NAME = '.jpg' STREAM_DATA_CHUNK_SIZE = 1024 import os import logging import StringIO from urlparse import urlparse, urlunparse, parse_qsl from urllib import ...
sion information - is_thumbnail: is whether or not we want the thumbnail version of this asset """ path = path.replace('/', '_') return course_key.make_asset_key( 'asset' if not is_thumbnail else 'thumbnail', AssetLocator.clean_keeping_underscores(path...
ta(self): return self._data ASSET_URL_RE = re.compile(r""" /?c4x/ (?P<org>[^/]+)/ (?P<course>[^/]+)/ (?P<category>[^/]+)/ (?P<name>[^/]+) """, re.VERBOSE | re.IGNORECASE) @staticmethod def is_c4x_path(path_string): """ Returns a boolean i...
ketor/z-vimrc
.vim/bundle/taghighlight/plugin/TagHighlight/module/config.py
Python
gpl-2.0
3,393
0.003831
#!/usr/bin/env python # Tag Highlighter: # Author: A. S. Budden <abudden _at_ gmail _dot_ com> # Copyright: Copyright (C) 2009-2013 A. S. Budden # Permission is hereby granted to use and distribute this code, # with or without modifications, provided that this copyright # notice is c...
': 'Unreleased', 'revision_id': 'Unreleased', } def SetInitialOptions(new_options, manual_options): global config for key in new_options: config[key] = new_options[key] if 'DebugLevel' in config: SetDebugLogLevel(config['DebugLevel']) if 'DebugFile' in co...
File']) config['ManuallySetOptions'] = manual_options def LoadLanguages(): global config if 'LanguageHandler' in config: return from .languages import Languages config['LanguageHandler'] = Languages(config) full_language_list = config['LanguageHandler'].GetAllLanguages() if len(con...
zentralopensource/zentral
zentral/contrib/simplemdm/models.py
Python
apache-2.0
3,296
0.002731
import logging from django.core.exceptions import ObjectDoesNotExist from django.db import models from django.urls import reverse from zentral.utils.osx_package import get_standalone_package_builders from .utils import delete_app, build_and_upload_app logger = logging.getLogger("zentral.contrib.simplemdm.models") c...
the enrollment secret verification events, via the enrollment""" instance = self.simplemdm_instance meta_business_unit = instance.business_unit.meta_business_unit return {"simplemdm_app": {"pk": self.pk, "instance": {"pk": instance.pk, ...
"meta_business_unit": {"pk": meta_business_unit.pk, "name": meta_business_unit.name}}}}
meisamhe/GPLshared
Programming/MPI — AMath 483 583, Spring 2013 1.0 documentation_files/matrix_search.py
Python
gpl-3.0
2,103
0
import sys import random # @include def matrix_search(A, x): row, col = 0, len(A[0]) - 1 # Start from the top-right corner. # Keeps searching while there are unclassified rows and columns. while row < len(A) and col >= 0: if A[row][col] == x: return True elif A[row][col] < x: ...
ert matrix_search(A, 1) A = [[1, 5], [2, 6]] assert no
t matrix_search(A, 0) assert matrix_search(A, 1) assert matrix_search(A, 2) assert matrix_search(A, 5) assert matrix_search(A, 6) assert not matrix_search(A, 3) assert not matrix_search(A, float('inf')) A = [[2, 5], [2, 6]] assert not matrix_search(A, 1) assert matrix_search(A, 2) ...
pantsbuild/pex
pex/resolve/requirement_configuration.py
Python
apache-2.0
2,532
0.00079
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import absolute_import from pex.fetcher import URLFetcher from pex.network_configuration import NetworkConfiguration from pex.requirements import Constraint, parse_require...
ts)) if self.requirement_files: fetcher = URLFetcher(network_configuration=network_configuration) for requirement_file in self.requirement_files: parsed_requirements.extend( requirement_or_constraint for requirement_or_constraint in...
if not isinstance(requirement_or_constraint, Constraint) ) return parsed_requirements def parse_constraints(self, network_configuration=None): # type: (Optional[NetworkConfiguration]) -> Iterable[Constraint] parsed_constraints = [] # type: List[Constraint] if self....
Distrotech/notify-python
tests/test-xy.py
Python
lgpl-2.1
418
0.004785
#!/usr/bin/env python import pygtk pygtk.require('2.0') import pynotify import sys if __name__ == '__main__': if not pynotify.init("XY"): sys.exit(1) n = pynotify.Notification(
"X, Y Test", "This notification should poin
t to 150, 10") n.set_hint("x", 150) n.set_hint("y", 10) if not n.show(): print "Failed to send notification" sys.exit(1)
JohnRandom/django-aggregator
dasdocc/aggregator/tests/commands/TestUpdateFeeds.py
Python
bsd-3-clause
786
0.002545
from nose.tools import * from nose.plugins.attrib import attr from django.test import TestCase from django.core.management import call_command as call from das
docc.aggregator.tests.factories import FeedFactory, InvalidFeedFactory from dasdocc.aggregator.models import Feed class UpdateValidFeedsTests(TestCase): def setUp(self): self.feed = FeedFactory() def teardown(self): pass def test_updating_valid_feeds_works(self): assert_equals(Fe...
'updatefeeds') assert_equals(Feed.objects.get().title, u'c-base logbuch') def test_updating_does_not_delete_valid_tests(self): assert_equals(Feed.objects.count(), 1) call('updatefeeds') assert_equals(Feed.objects.count(), 1)
fairdk/fair-ubuntu-centre
installscripts/data/intranet/fairintranet/technicians/management/commands/install_site.py
Python
gpl-3.0
1,436
0.004875
from __future__ import print_function from __future__ import absol
ute_import from __future__ import unicode_literals import logging import sys
from django.core.management.base import BaseCommand from core import models logger = logging.getLogger('fairintranet.technicians') class Command(BaseCommand): help = ( 'Asks for computers, printers, etc...' ) args = '' def handle(self, *args, **options): try: page = m...
18F/regulations-site
regulations/tests/diff_applier_tests.py
Python
cc0-1.0
8,525
0
from unittest import TestCase from regulations.generator.layers import diff_applier from regulations.generator.layers import tree_builder from regulations.generator.node_types import REGTEXT from collections import deque class DiffApplierTest(TestCase): def test_create_applier(self): diff = {'some': 'di...
of_requested('204-30-Interp')) da.label_requested = '204-3-Interp-4' self.assertFalse(da.is_child_of_requested('204-3-a-Interp')) self.assertFalse(da.is_child_of_requested('204-3-Interp-1')) self.assertTrue(da.is_child_of_requested('204-3-Interp-4-a')) def test_tree_changes_new_sec...
ed', 'node': {'text': 'Some Text',
hilgroth/fiware-IoTAgent-Cplusplus
tests/e2e_tests/component/iot_api/services/create/setup.py
Python
agpl-3.0
10,033
0.011562
from lettuce import step, world from iotqautils.gtwRest import Rest_Utils_SBC from common.user_steps import UserSteps from common.gw_configuration import IOT_SERVER_ROOT,CBROKER_HEADER,CBROKER_PATH_HEADER api = Rest_Utils_SBC(server_root=IOT_SERVER_ROOT+'/iot') user_steps = UserSteps() @step('a Service wi...
world.value2 = value2 if typ1=='attr': attributes=[ { "name": name1, "type": type1, "object_id": value1 } ] if typ2=='attr': attribute={ "name": name2, "type": type2, ...
attribute) if typ1=='st_att': st_attributes=[ { "name": name1, "type": type1, "value": value1 } ] if typ2=='st_att': st_attribute={ "name": name2, "type": type2, ...
dmccloskey/ddt_python
ddt_python/ddt_tile_html.py
Python
mit
2,646
0.032905
from .ddt_tile import ddt_tile class ddt_tile_html(ddt_tile): def make_parameters_form_01(self, formparameters={}, ): '''Make htmlparameters INPUT: OUTPUT: ''' #defaults: htmlid='filtermenuform1'; htmltype='form_01'; formsubmi...
"formsubmitbuttonidtext":formsubmitbuttonidtext, "formresetbuttonidtext":formresetbuttonidtext, "formupdatebuttonidtext":formupdatebuttonidtext }; self.make_htmlparameters(htmlparameters=formparameters_O); def make_parameters_datalist_01(self, ...
INPUT: OUTPUT: ''' #defaults htmlid='datalist1'; htmltype='datalist_01'; datalist=[ {'value':'hclust','text':'by cluster'}, {'value':'probecontrast','text':'by row and column'}, {'value':'probe','text':'by row'}, {'val...
lawrenceakka/SoCo
soco/core.py
Python
mit
73,424
0
# -*- coding: utf-8 -*- # pylint: disable=fixme, protected-access """The core module contains the SoCo class that implements the main entry to the SoCo functionality """ from __future__ import unicode_literals import datetime import logging import re import socket from functools import wraps import warnings from soco...
super(SoCo, self).__init__() # Check if ip_address is a valid IPv4 representation
. # Sonos does not (yet) support IPv6 try: socket.inet_aton(ip_address) except socket.error: raise ValueError("Not a valid IP address string") #: The speaker's ip address self.ip_address = ip_address self.speaker_info = {} # Stores information abo...
zhanghui9700/eonboard
eoncloud_web/biz/network/admin.py
Python
apache-2.0
487
0
from django.contrib import admin from biz.network.models import Network, Subnet, Router class NetworkAdmin(admin.ModelAdmin): list_display = ("id", "name", "is_default") class SubnetAdmin(admin.ModelAdmin): list_display = ("id", "name"
, "address", "ip_version") class RouterAdmin(admin.ModelAdmin): list_display = ("id", "name", "gateway") admin.site.register(Network
, NetworkAdmin) admin.site.register(Subnet, SubnetAdmin) admin.site.register(Router, RouterAdmin)
swagner-de/irws_homeworks
word_embeddings/embedding.py
Python
mit
1,203
0.003325
import glob import os import numpy as np def load_emebeddings(folder): files = [filename for filename in glob.iglob(folder + '**', recursive=True) if not os.path.isdir(filename)] w2v = {} for file in files: with open(file, "r", encoding='utf8') as lines: for line in lines: ...
for emb in range(le
n(emb_vec)): try: res[emb] += _tfidf * float(emb_vec[emb]) except IndexError: res.append(_tfidf * float(emb_vec[emb])) for k in res: k /= divisor return res
cupcicm/bson
bson/codec.py
Python
bsd-3-clause
10,379
0.030061
#!/usr/bin/python -OOOO # vim: set fileencoding=utf8 shiftwidth=4 tabstop=4 textwidth=80 foldmethod=marker : # Copyright (c) 2010, Kou Man Tong. All rights reserved. # For licensing, see LICENSE file included in the package. """ Base codec functions for bson. """ import struct import cStringIO import calendar, pytz fro...
urn (base + 8, struct.unpack("<d", data[base: base + 8])[0]) ELEMENT_TYPES = { 0x01 : "double", 0x02 : "string", 0x03 : "document", 0x04 : "array",
0x05 : "binary", 0x08 : "boolean", 0x09 : "UTCdatetime", 0x0A : "none", 0x10 : "int32", 0x12 : "int64" } def encode_double_element(name, value): return "\x01" + encode_cstring(name) + encode_double(value) def decode_double_element(data, base): base, name = decode_cstring(data, base + 1) base, value =...
weiweihuanghuang/Glyphs-Scripts
Hinting/Delete Hints in Visible Layers.py
Python
apache-2.0
520
0.036538
#MenuTitle: Delete Hints in Visible Layers # -*- coding: utf-8 -*- __doc__=""" Deletes all hints in active layers of selected glyphs. """ import GlyphsApp Font = Glyphs.font selectedLayers = Font.selectedLayers print "Deleting hints
in active layer:" def process( thisLayer ): for x in reversed( range( len( thisLayer.hints ))): del thisLayer.hints[x] Font.disableUpdateInterface() for thisLayer in selectedLayers: print "Processing", thisLayer.parent.name proces
s( thisLayer ) Font.enableUpdateInterface()
mdrohmann/txtemplates
tests/echo/conftest.py
Python
bsd-3-clause
199
0
server_module = 'txtemplates.echo' backend_
options = [{}] backend_ids = ['default'] full_server_options = [({}, {})] full_server_ids = ['default'] # vim: set
ft=python sw=4 et spell spelllang=en:
marrow/dsl
marrow/dsl/core/lines.py
Python
mit
4,465
0.051064
# encoding: utf-8 from __future__ import unicode_literals from collections import deque from .buffer import Buffer from .compat import py2, str from .line import Line log = __import__('logging').getLogger(__name__) def _pub(a): return {i for i in a if i[0] != '_'} class Lines(object): """An iterable set of n...
new set of buffers for the given input, or an empty buffer.""" tags = kw.pop('tags', None) self.buffers = {} # Named references to buffers. self.lines = deque() # Indexed references to buffers. if isinstance(buffers, str)
and args: buffers = [(i, Buffer(())) for i in [buffers] + list(args)] elif isinstance(buffers, str): buffers = [('default', Buffer(buffers))] elif isinstance(buffers, Lines): self.buffers = buffers.buffers.copy() self.lines.extend(buffers.lines) buffers = () for name, buffer in buffers: ...
PawarPawan/h2o-v3
h2o-py/tests/testdir_algos/glm/pyunit_NOFEATURE_prostateGLM.py
Python
apache-2.0
956
0.032427
import sys sys.path.insert(1, "../../../") import h2o import pandas as pd import statsmodels.api as sm def prostate(ip,port): # Log.info("Importing prostate.csv data...\n") h2o_data = h2o.upload_file(path=h2o.locate("smalldata/logreg/prostate.csv")) #prostate.summary() sm_data = pd.read_csv(h2o.locate...
= sm.GLM(endog=sm_data_
response, exog=sm_data_features, family=sm.families.Binomial()).fit() assert abs(sm_glm.null_deviance - h2o_glm._model_json['output']['training_metrics']['null_deviance']) < 1e-5, "Expected null deviances to be the same" if __name__ == "__main__": h2o.run_test(sys.argv, prostate)
napalm-automation/napalm-yang
napalm_yang/models/openconfig/network_instances/network_instance/protocols/protocol/bgp/global_/dynamic_neighbor_prefixes/__init__.py
Python
apache-2.0
15,976
0.001064
# -*- coding: utf-8 -*- from operator import attrgetter from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType from pyangbind.lib.yangtypes import RestrictedClassType from pyangbind.lib.yangtypes import TypedListType from pyangbind.lib.yangtypes import YANGBool from pyangbind.lib.yangtypes import YANGListTy...
"dynamic-neighbor-prefixes", ] def _get_dynamic_neighbor_prefix(self): """ Getter method for dynamic_neighbor_prefix, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/global/dynamic_neighbor_prefixes/dynamic_neighbor_prefix (list) YANG Descri...
ghbor_prefix(self, v, load=False): """ Setter method for dynamic_neighbor_prefix, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/global/dynamic_neighbor_prefixes/dynamic_neighbor_prefix (list) If this variable is read-only (config: false) in the source YANG file...
GreenSteam/pep257
src/pydocstyle/violations.py
Python
mit
12,345
0.000081
"""Docstring violation definition.""" from collections import namedtuple from functools import partial from itertools import dropwhile from typing import Any, Callable, Iterable, List, Optional from .parser import Definition from .utils import is_blank __all__ = ('Error', 'ErrorRegistry', 'conventions') ErrorParam...
= '+' + 6 * '-' + '+' + '-' * (max_len + 2) + '+\n' blank_line = '|' + (max_len + 9) * ' ' + '|\n' table = '' for group in cls.groups: table += sep_line table += blank_line
table += '|' + f'**{group.name}**'.center(max_len + 9) + '|\n' table += blank_line for error in group.errors: table += sep_line table += ( '|' + error.code.center(6) + '| ' + error.sh...
NewEvolution/django-rest
tutorial/settings.py
Python
mit
3,277
0.001221
""" Django settings for tutorial project. Generated by 'django-admin startproject' u
sing Django 1.10. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = o...
eployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'c0=1yf+w%u=5sgv$bnbvtg8e(3u*!4##_bal@s3ra!ll7o%(3j' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'rest_framewor...
SF-Zhou/LeetCode.Solutions
solutions/multiply_strings.py
Python
mit
194
0
class Solution(object): def multiply(self, num1, num2): """
:type num1: str :type num2: str :rtype: str """ return str(int(num1) * int(num2)
)
JDQuackers/xbox-remote-power
xbox-remote-power.py
Python
mit
2,719
0.00331
import sys, socket, select, time from optparse import OptionParser XBOX_PORT = 5050 XBOX_PING = "dd00000a000000000000000400000002" XBOX_POWER = "dd02001300000010" help_text = "xbox-remote-power.py -a <ip address> -i <live id>" py3 = sys.version_info[0] > 2 def main(): parser = OptionParser() parser.add_opti...
= True elif result == "n": opts.live_id = user_input("Enter the Live ID: ") s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setblocking(0) s.bind(("", 0)) s.connect((opts.ip_addr, XBOX_PORT)) if ping: print("Attempting to ping
Xbox for Live ID...") s.send(bytearray.fromhex(XBOX_PING)) ready = select.select([s], [], [], 5) if ready[0]: data = s.recv(1024) opts.live_id = data[199:215] else: print("Failed to ping Xbox, please enter Live ID manually") opts.live_id ...
atodorov/blivet
tests/clearpart_test.py
Python
gpl-2.0
9,228
0.000759
import unittest import mock import blivet from pykickstart.constants import CLEARPART_TYPE_ALL, CLEARPART_TYPE_LINUX, CLEARPART_TYPE_NONE from parted import PARTITION_NORMAL from blivet.flags import flags DEVICE_CLASSES = [ blivet.devices.DiskDevice, blivet.devices.PartitionDevice ] @unittest.skipUnless(not...
"unpartitioned disks") self.assertFalse(b.should_clear(sdc), msg="type none should not clear empty disk without " "initlabel") self.assertFalse(b.should_clear(sdd), msg="type none should not cle...
ks = True self.assertFalse(b.should_clear(sda), msg="type none should not clear non-empty disks even " "with initlabel") self.assertFalse(b.should_clear(sdb), msg="type non should not clear formatting from " ...
HybridF5/tempest_debug
tempest/lib/services/compute/limits_client.py
Python
apache-2.0
1,138
0
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
ther express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_serialization import jsonutils as json from tempest.lib.api_schema.response.compute.v2_1 import limits as schema from tempest.lib.common import rest_client from tempest.lib.s...
how_limits(self): resp, body = self.get("limits") body = json.loads(body) self.validate_response(schema.get_limit, resp, body) return rest_client.ResponseBody(resp, body)
UstadMobile/exelearning-ustadmobile-work
twisted/persisted/styles.py
Python
gpl-2.0
27,358
0.007932
# -*- test-case-name: twisted.test.test_persisted -*- # Copyright (c) 2001-2004 Twisted Matrix Laboratories. # See LICENSE for details. """ Different styles of persisted objects. """ # System Imports import types import copy_reg import copy try: import cStringIO as StringIO except ImportError: import Strin...
, # letting any exception stop this before the real requireUpgrade() log.debug("doUpgrade performing a pre-Merge safety check.") for versioned in versionedsToUpgrade.values(): requireUpgrade(versioned, new
Package, isMerge, preMergePackage, mergeCheck=True) log.debug("doUpgrade completed the pre-Merge safety check.") for versioned in versionedsToUpgrade.values(): requireUpgrade(versioned, newPackage, isMerge, preMergePackage, mergeCheck=False) ...
obi-two/Rebelion
data/scripts/templates/object/mobile/shared_dressed_commoner_old_human_male_02.py
Python
mit
459
0.04793
#### NO
TICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Creature() result.template = "object/mobile/shared_dressed_commoner_old_human_male_02.iff" result.attribute_template_id ...
sult
sidzan/netforce
netforce_stock/netforce_stock/models/barcode_issue_line.py
Python
mit
2,232
0.003584
# Copyright (c) 2012-2015 Netforce Co. Ltd. # # Permission is hereby granted, free of charge, to any pers
on obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Softw...
pies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE ...
fab13n/caracole
villes/migrations/0001_initial.py
Python
mit
5,318
0.005641
# Generated by Django 3.2 on 2021-08-25 20:55 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Ville', fields=[ ('id', models.IntegerField(d...
=True, db_column='ville_canton', max_length=4, null=True)), ('amdi', models.IntegerField(blank=True, db_column='ville_amdi', null=True)), ('population_2010', models.IntegerField(blank=True, db_column='ville_population_2010', null=True)), ('population_1999', models.Integer...
els.IntegerField(blank=True, db_column='ville_population_2012', null=True)), ('densite_2010', models.IntegerField(blank=True, db_column='ville_densite_2010', null=True)), ('surface', models.FloatField(blank=True, db_column='ville_surface', null=True)), ('longitude_deg', m...
webbhm/OpenAg_MVP_UI
MVP_UI/python/temp_chart.py
Python
mit
966
0.012422
# /usr/bin/env python import pygal import requests import json #Use a view in CouchDB to get the data #use the first key for attribute type #order descending so when limit the results will get the latest at the top r = requests.get('http://127.0.0.1:5984/mvp_sensor_data/_design/doc/_view/attribute_value?startkey=["te...
() line_chart.x_labels = ts_lst #need to reverse order to go from earliest to latest v_lst.reverse() li
ne_chart.add('Air Temp', v_lst) line_chart.render_to_file('/home/pi/MVP_UI/web/temp_chart.svg')
ministryofjustice/manchester_traffic_offences_pleas
apps/plea/views.py
Python
mit
8,700
0.002069
import datetime import json from brake.decorators import ratelimit from django.utils.decorators import method_decorator from django.utils.translation import get_language from django.conf import settings from django.core.urlresolvers import reverse_lazy from django.http import HttpResponseRedirect, HttpResponse from dj...
lf, request, *args, **kwargs): # If the session has timed out, redirect to start page if all([ not request.session.get("plea_data"), kwargs.get("stage
", self.start) != self.start, ]): return HttpResponseRedirect("/") # Store the index if we've got one idx = kwargs.pop("index", None) try: self.index = int(idx) except (ValueError, TypeError): self.index = 0 # Load storage s...
Mezgrman/TweetPony
setup.py
Python
agpl-3.0
1,186
0.029511
#!/usr/bin/env python # Copyright 2013-2015 Julian Metzler """ This program 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 later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY o...
U Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ from setuptools import setup, find_packages metadata = {} with open('tweetpony/metadata.py') as f: exec(f.read(), metad...
lmazuel/azure-sdk-for-python
azure-mgmt-monitor/azure/mgmt/monitor/models/activity_log_alert_resource.py
Python
mit
3,303
0.000606
# 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 ...
:type tags: dict[str, str] :param scopes: Required. A list of resourceIds that will be used as prefixes. The alert will only apply to activityLogs with resourceIds that fall under one of these prefixes. This list must include at least one item. :type scopes: list[str] :param enabled: Ind...
:type enabled: bool :param condition: Required. The condition that will cause this alert to activate. :type condition: ~azure.mgmt.monitor.models.ActivityLogAlertAllOfCondition :param actions: Required. The actions that will activate when the condition is met. :type actions: ~azure.mgmt.monit...
davidbgk/udata
udata/core/dataset/factories.py
Python
agpl-3.0
1,823
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals import factory from udata.factories import ModelFactory from .models import Dataset, Resource, Checksum, CommunityResource, License from udata.core.organization.factories import OrganizationFactory fro
m udata.core.spatial.factories import SpatialCoverageFactory class DatasetFactory(ModelFactory): class Meta: model = Dataset title = factory.Faker('sentence') description = factory.Faker('text') frequency = 'unknown' class Params: geo = factory.Trait( spatial=factory....
isible = factory.Trait( resources=factory.LazyAttribute(lambda o: [ResourceFactory()]) ) org = factory.Trait( organization=factory.SubFactory(OrganizationFactory), ) class VisibleDatasetFactory(DatasetFactory): @factory.lazy_attribute def resources(self): ...