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
TwolDE2/enigma2
lib/python/Components/Element.py
Python
gpl-2.0
2,950
0.028136
from Tools.CList import CList # down up # Render Converter Converter Source # a bidirectional connection def cached(f): name = f.__name__ def wrapper(self): cache = self.cache if cache is None: return f(self) if name not in cache: cache[name] = (True, f(self)) return cache[nam...
state CHANGED_ALL = 1 # really everything changed CHANGED_CLEAR = 2 # we're expecting a real update soon. don't bother polling NOW, but c
lear data. CHANGED_SPECIFIC = 3 # second tuple will specify what exactly changed CHANGED_POLL = 4 # a timer expired SINGLE_SOURCE = True def __init__(self): self.downstream_elements = CList() self.master = None self.sources = [] self.source = None self.__suspended = True self.cache = None def ...
ProfessorX/Config
.PyCharm30/system/python_stubs/-1247972723/samba/dcerpc/lsa/ForestTrustInformation.py
Python
gpl-2.0
1,274
0.007064
# encoding: utf-8 # module samba.dcerpc.lsa # from /usr/lib/python2.7/dist-packages/samba/dcerpc/lsa.so # by generator 1.135 """ lsa DCE/RPC """ # imports import dcerpc as __dcerpc import talloc as __talloc class ForestTrustInformation(__talloc.Object): # no doc def __init__(self, *args, **kwargs): # real si...
dr_unpack(class, blob, allow_remaining=False) -> None NDR unpack """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc
__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass count = property(lambda self: object(), lambda self, v: None, lambda self: None) # default entries = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
SlashDK/Memify
Main/Memify.py
Python
mit
4,703
0.0202
import cv2 import sys import datetime import numpy import subprocess def makeThug(frame,faces,mouths,eyes): glasses = cv2.imread("glasses.png",-1) joint = cv2.imread("joint.png",-1) t=datetime.datetime.now().time() filename="Saved/"+str(t.hour)+str(t.minute)+str(t.second)+".jpg" #work only inside f...
, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale( gray, scaleFactor=1.2, minNeighbors=10, minSize=(30, 30), flags=cv2.cv.CV_HAAR_SCALE_IMAGE )
mouths = mouthCascade.detectMultiScale( gray, scaleFactor=1.7, minNeighbors=10, minSize=(30, 30), flags=cv2.cv.CV_HAAR_SCALE_IMAGE ) eyes = eyesCascade.detectMultiScale( gray, scaleFactor=1.1, minNeighbo...
Pyrrvs/txdbus
txdbus/test/test_message.py
Python
mit
815
0.006135
import os import unittest from txdbus import error, message class MessageTester(unittest.TestCase): def test_too_long(self): class E(message.ErrorMessage): _maxMsgLen = 1 def c(): E('foo.bar', 5) self.assertRaises(error.MarshallingError, c) def test_r...
ed_path(self): def c(): message.MethodCallMessage('/org/freedesktop/DBus/Local', 'foo') self.assertRaises(error.MarshallingError, c) def test_invalid_message_type(self): class E(message.ErrorMessage): _messageType=99 try: message.parseMessage(E('f...
.rawMessage) self.assertTrue(False) except Exception as e: self.assertEquals(str(e), 'Unknown Message Type: 99')
sklam/numba
numba/core/typing/templates.py
Python
bsd-2-clause
43,345
0.000323
""" Define typing templates """ from abc import ABC, abstractmethod import functools import sys import inspect import os.path from collections import namedtuple from collections.abc import Sequence from types import MethodType, FunctionType import numba from numba.core import types, utils from numba.core.errors impor...
o disable unsafe cast. # subclass overide-able unsafe_casting = True # Set to true to require exact match without casting. # subclass overide-able exact_match_required = False # Set to true to prefer literal arguments. # Useful for definitions
that specialize on literal but also support # non-literals. # subclass overide-able prefer_literal = False def __init__(self, context): self.context = context def _select(self, cases, args, kws): options = { 'unsafe_casting': self.unsafe_
rrrrrr8/vnpy
vnpy/api/fcoin/vnfcoin.py
Python
mit
8,705
0.015528
# encoding: UTF-8 from __future__ import print_function import hashlib import hmac import json import ssl import traceback import base64 from queue import Queue, Empty from multiprocessing.dummy import Pool from time import time from urlparse import urlparse from copy import copy from urllib import urlencode from thr...
eq(self, req, i): """处理请求""" method, path, callback, params, postdict, reqid = req url = REST_HOST + path timestamp = str(int(time()) * 1000) header = {} header['FC-ACCESS-TIMESTAMP'] = timestamp header['FC-ACCESS-KEY'] = self.apiKey header['FC-A...
timestamp, params, postdict) try: # 使用长连接的session,比短连接的耗时缩短80% session = self.sessionDict[i] resp = session.request(method, url, headers=header, params=params, json=postdict) #resp = requests.request(method, url, headers=header, params=params, data=postdi...
jonparrott/gcloud-python
bigquery/google/cloud/bigquery/table.py
Python
apache-2.0
48,513
0
# Copyright 2015 Google 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 to in writing, s...
if not isinstance(other, EncryptionConfiguration): return NotImplemented return self.kms_key_name == other.kms_key_name def __ne__(self, other): return not self == other def __hash__(self): return hash(self.kms_key_name) def __repr__(self):
return 'EncryptionConfiguration({})'.format(self.kms_key_name) class TableReference(object): """TableReferences are pointers to tables. See https://cloud.google.com/bigquery/docs/reference/rest/v2/tables Args: dataset_ref (google.cloud.bigquery.dataset.DatasetReference): A pointe...
the-blue-alliance/the-blue-alliance
src/backend/web/handlers/tests/error_test.py
Python
mit
933
0
from typing import Tuple import bs4 from werkzeug.test import Client def get_error_title(resp_data: str) -> Tuple[str, str]: soup = bs4.BeautifulSoup(resp_data, "html.parser") return soup.find("h1").string, soup.find("h2").string def test_handle_404(web_cl
ient: Client) -> None: resp = web_client.get("/asdf") assert resp.status_code == 404 error_header, error_type = get_error_title(resp.
data) assert error_header == "Oh Noes!1!!" assert error_type == "Error 404" def test_handle_500() -> None: from backend.web.main import app def always_throw() -> str: raise Exception("welp") app.add_url_rule("/throw_500", view_func=always_throw) client = app.test_client() resp =...
AlienCowEatCake/ImageViewer
src/ThirdParty/Exiv2/exiv2-0.27.5-Source/tests/bugfixes/github/test_issue_867.py
Python
gpl-3.0
656
0.003049
# -*- coding: utf-8 -*- from system_tests import CaseMeta, path class OutOfBoundsReadInIptcParserDecode(metaclass=CaseMeta): """ Regression test for the bug described in: https://github.com/Exiv2/exiv2/issues/867 """ url = "https://github.com/Exiv2/exiv2/issues/867" filename = path("$data_pa...
["$exiv2 $filename"] stdout = ["""File name : $filename File size : 9830 Bytes MIME type : image
/x-photoshop Image size : 150 x 91 """ ] stderr = [ """Warning: Failed to decode IPTC metadata. $filename: No Exif data found in the file """ ] retval = [253]
cellnopt/cellnopt
cno/misc/dependencies.py
Python
bsd-2-clause
1,784
0.007848
import easydev from cno import CNOGraph def plot_dependencies(package='cno', show=False, filename=None): main = easydev.dependencies.get_dependencies(package) # first, we fetch all dependencies c = CNOGraph() deps = easydev.dependencies.get_dependencies(package) package_version = [dep.version fo...
encies.get_dependencies(dep.project_name): if this.project_name != dep.project_name: newdeps.append(this) version = dep.version name= dep.project_name c.add_reaction(this.project_name +"-" +this.version+"="+name + "-" + version) ...
Not use this is the good way of doing it... c2 = CNOGraph() import networkx as nx for clique in list(nx.find_cliques(c.to_undirected())): for i in range(0, len(clique)-1): c2.add_edge(clique[i], clique[i+1]) c2.plot(filename=filename, show=show)
deepmind/alphafold
alphafold/data/parsers.py
Python
apache-2.0
21,397
0.012058
# Copyright 2021 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
ons def parse_stockholm(stockholm_string: str) -> Msa: """Parses sequences and deletion matrix from stockholm format alignment. Args: stockholm_string: The string contents of a stockholm file. The first sequence in the file should be the query sequence. Returns: A tuple of: * A list of
sequences that have been aligned to the query. These might contain duplicates. * The deletion matrix for the alignment as a list of lists. The element at `deletion_matrix[i][j]` is the number of residues deleted from the aligned sequence i at residue position j. * The names of the ta...
ghchinoy/tensorflow
tensorflow/python/tools/optimize_for_inference_test.py
Python
apache-2.0
13,544
0.005833
# pylint: disable=g-bad-file-header # Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # #
http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by 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 language governing permiss...
====================================================== """Tests for tensorflow.python.client.graph_util.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.core.framework import attr_value_pb2 from tensorflow.core.framewo...
catalyst/l3overlay
src/l3overlay/util/exception.py
Python
gpl-3.0
914
0
# # IPsec overlay network manager (l3overlay) # l3overlay/util/exception.py - exception base class # # Copyright
(c) 2017 Catalyst.net Ltd # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # #
This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along w...
infinit/couchdb-python
couchdb/client.py
Python
bsd-3-clause
45,376
0.000375
# -*- coding: utf-8 -*- # # Copyright (C) 2007-2009 Christopher Lenz # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. """Python client API for CouchDB. >>> server = Server() >>> db = server.create('python-tests') >>> ...
rce': source, 'target': target} data.update(options) status, headers, data = self.resource.post_json('_replicate', data) return data class Database(object): """Re
presentation of a database on a CouchDB server. >>> server = Server() >>> db = server.create('python-tests') New documents can be added to the database using the `save()` method: >>> doc_id, doc_rev = db.save({'type': 'Person', 'name': 'John Doe'}) This class provides a dictionary-like interface...
ComprasTransparentes/api
endpoints/ministerio.py
Python
gpl-3.0
9,007
0.001665
import json import falcon import peewee from models import models_api from utils.myjson import JSONEncoderPlus class MinisterioId(object): """Endpoint para un ministerio en particular, identificado por id""" @models_api.database.atomic() def on_get(self, req, resp, ministerio_id): """Obtiene la...
erio_id** en la categoria de producto **categoria_id** :param req: Falcon request object :param resp: Falcon response object :param ministerio_id: ID de minsiterio :param categoria_id: ID de categoria de producto :return: """ # Validar que ministeri...
ategoria_id = int(categoria_id) except ValueError: raise falcon.HTTPNotFound() # Obtener las estadisticas try: stats = models_api.Comparador.get( models_api.Comparador.id_ministerio == ministerio_id, models_api.Comparador.id_categoria_nive...
horpto/peewee-async
peewee_async.py
Python
mit
16,722
0.000897
""" peewee-async ============ Asynchronous interface for `peewee`_ ORM powered by `asyncio`_: https://github.com/05bit/peewee-async .. _peewee: https://github.com/coleifer/peewee .. _asyncio: https://docs.python.org/3/library/asyncio.html Licensed under The MIT License (MIT) Copyright (c) 2014, Alexey Kinev <rudy@0...
peewee.UpdateQuery),\ ("Error, trying to run update coroutine" "with wrong query class %s" % str(query)) cursor = yield from cursor_with_query(query) rowcount = cursor.rowcount cursor.release() return rowcount @asyncio.coroutine def delete(query): """Perform DELETE query
asynchronously. Returns number of rows deleted. """ assert isinstance(query, peewee.DeleteQuery),\ ("Error, trying to run delete coroutine" "with wrong query class %s" % str(query)) cursor = yield from cursor_with_query(query) rowcount = cursor.rowcount cursor.release() return...
Ashkeelun/GitHealth
Testing/UnitTest.py
Python
mit
4,788
0.003133
import requests import unittest class APITestCase(unittest.TestCase): def setUp(self): self.url = 'http://127.0.0.1:8000/health/api/' self.payload = {"url":"https://github.com/celalgorgun/TestFile"} def testResponse(self): r = requests.post(self.url, self.payload) #Test Reque...
quals(r.json()["root"]["sub_files"][0]["slc_num"], 1) self.assertEquals(r.json()["root"]["sub_files"][0]["comt_size"], 88) self.assertEquals(r.json()["root"]["sub_files"][0]["code_size"], 125) #Test 2 file self.assertEquals(r.json()["root"]["sub_files"][1]["mlc_size"], 97) self.a...
t"]["sub_files"][1]["slc_size"], 27) self.assertEquals(r.json()["root"]["sub_files"][1]["slc_num"], 2) self.assertEquals(r.json()["root"]["sub_files"][1]["comt_size"], 124) self.assertEquals(r.json()["root"]["sub_files"][1]["code_size"], 148) #Test 3 file self.assertEquals(r.json...
google/rappor
tests/fastrand.py
Python
apache-2.0
1,198
0.001669
# Copyright 2014 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
r the specific language governing permissions and # limitations under the License. """fastrand.py - Python wrapper for _fastrand.""" # NOTE: We could retire this module in favor of the C++ client? One reason to # keep it is if it supports a wider range of params (e.g. more than 32 or 64 # bits.) import random impo...
its = _fastrand.randbits # accelerated function num_bits = params.num_bloombits # IRR probabilities self.p_gen = lambda: randbits(params.prob_p, num_bits) self.q_gen = lambda: randbits(params.prob_q, num_bits)
kaiserroll14/301finalproject
main/pandas/tslib.py
Python
gpl-3.0
300
0.016667
def __bootstrap__(): global __bootstrap__, __loader__, __file__
import sys, pkg_resources, imp __file__ = pkg_resources.resource_filename(__name__, 'tslib.cpython-35m-darwin.so') __load
er__ = None; del __bootstrap__, __loader__ imp.load_dynamic(__name__,__file__) __bootstrap__()
Vagab0nd/SiCKRAGE
lib3/bencode/__init__.py
Python
gpl-3.0
1,155
0
# The contents of this file are subject to the BitTorren
t Open Source License # Version 1.1 (the License). You may not copy or use this file, in either # source code or executable form, except in compliance with the Lice
nse. You # may obtain a copy of the License at http://www.bittorrent.com/license/. # # Software distributed under the License is distributed on an AS IS basis, # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License # for the specific language governing rights and limitations under the # License. ...
PytLab/VASPy
vaspy/elements.py
Python
mit
617
0.001621
''' Module to store chemical elements related data. ''' C12 = 1.99264648e-26 # mass of C12 (kg/atom) amu = 1.66053904e-27 # atomic mass unit (kg) chem_elements = {} chem_elements['H'] = dict(index=1, mass=1.00794) chem_el
ements['C'] = dict(index=6, mass=12.0107) chem_elements['N'] = dict(index=7, mass=14.0067) chem_elements['O'] = dict(index=8, mass=15.9994) chem_elements['F'] = dict(index=9, mass=18.9984032) chem_elements['Ne'] = dict(index=10, mass=20.1797) chem_elements
['S'] = dict(index=16, mass=32.065) chem_elements['Cl'] = dict(index=17, mass=35.453) chem_elements['Ni'] = dict(index=28, mass=58.693)
LondoMundo/githubFrontendPy
gitGUI.py
Python
gpl-3.0
1,265
0.029249
import wx import os class bucky(wx.Frame): def __init__(self, parent, id): wx.Frame.__init__(self, parent, id, 'Git GUI', size =(500,500)) panel = wx.Panel(self) gitAddB = wx.Button(panel, label = "add", pos = (0,0), size =(60,60)) gitCommitB = wx.Button(panel, label="commit", pos ...
box.GetValue() print repo secondBox=wx.DirDialog(None) secondBox.ShowModal() path = secondBox.GetPath() print path
os.system("mkdir /Users/colin/Desktop/helloworld") #os.system("git clone " + repo) #use os.system(mkdir) with the git clone command so that we navigate to the directory THEN clone the file if __name__ =='__main__': app=wx.PySimpleApp() frame = bucky(parent = None, id = -1) frame.Show() ...
mvaled/sentry
src/sentry/models/monitor.py
Python
bsd-3-clause
5,443
0.00147
from __future__ import absolute_import, print_function import pytz import six from croniter import croniter from datetime import datetime, timedelta from dateutil import rrule from django.db import models from django.db.models import Q from django.utils import timezone from uuid import uuid4 from sentry.constants im...
next_schedule = rule[1] else: raise NotImplementedError("unknown schedule_type") return next_schedule class MonitorStatus(ObjectStatus): OK = 4 ERROR = 5 @classmethod def as_choices(cls): return (
(cls.ACTIVE, "active"), (cls.DISABLED, "disabled"), (cls.PENDING_DELETION, "pending_deletion"), (cls.DELETION_IN_PROGRESS, "deletion_in_progress"), (cls.OK, "ok"), (cls.ERROR, "error"), ) class MonitorType(object): UNKNOWN = 0 HEALTH_CHECK ...
rudhir-upretee/Sumo17_With_Netsim
tools/visualization/mpl_dump_onNet.py
Python
gpl-3.0
17,970
0.010128
#!/usr/bin/env python """ @file mpl_dump_onNet.py @author Daniel Krajzewicz @author Michael Behrisch @date 2007-10-25 @version $Id: mpl_dump_onNet.py 13811 2013-05-01 20:31:43Z behrisch $ This script reads a network and a dump file and draws the network, coloring it by the values found within the dump-file....
oHex(colormap[-1][1][1]) + toHex(colormap[-1][1][2]) def parseColorMap(mapDef): ret = [] defs = mapDef.split(",") for d in defs: (value, color) = d.split(":") r = color[1:3] g = color[3:5] b = color[5:7] ret.append( (float(value), ( toFloat(r), toFloat(g), toFloat(...
twork, storing the edge geometries, lane numbers and max. speeds""" def __init__(self): self._id = '' self._edge2lanes = {} self._edge2speed = {} self._edge2shape = {} self._edge2from = {} self._edge2to = {} self._node2x = {} self._node2y = {} ...
annarev/tensorflow
tensorflow/python/data/experimental/kernel_tests/assert_cardinality_test.py
Python
apache-2.0
3,962
0.002019
# Copyright 2020 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...
f.evaluate(cardinality.cardinality(dataset)), 10) self.assertDatasetProduces(dataset, expected_output=range(10)) @combinations.generate( combinations.times( test_base.default_test_combinations(), combinations.combine( num_elements=10, asserted_cardinality=20,...
taset was expected to contain 20 " "elements but contained only 10 elements.") + combinations.combine( num_elements=1, asserted_cardinality=20, expected_error="Input dataset was expected to contain 20 " "elements but contained only 1 elemen...
it-projects-llc/odoo-saas-tools
saas_portal_subscription/models/subscription_log.py
Python
lgpl-3.0
352
0
from odoo import fields, models class SaasSubscriptionLog(models.Model):
_name = 'saas_portal.subscription_log' _order = 'id desc' client_id = fields.Many2one('saas_portal.client', 'Client') expiration = fields.Datetime('Previous expiration') expiration_new = fields.Datetime('New expiration')
reason = fields.Text('Reason')
jtrebosc/JTutils
TSpy/norm_noise_per_scan.py
Python
bsd-3-clause
1,676
0.011337
# -*- coding: utf-
8 -*- ## normalize the noise level to one scan : divide intensity by sqrt(NS) def norm(ns=None, dataset=None): import sys import os import os.path import subprocess import JTutils # if this function is called from imported module then one needs to import TOPSPIN functions # so that they are...
NPUT_DIALOG, MSG if dataset == None: dataset = CURDATA() # process the arguments that are handled by this script if ns == None: ns = GETPARSTAT("NS") fulldataPATH = JTutils.fullpath(dataset) opt_args = ["--ns", str(ns)] JTutils.run_CpyBin_script('norm_noise_per_scan_.py', opt...
SylvainCecchetto/plugin.video.catchuptvandmore
plugin.video.catchuptvandmore/resources/lib/channels/fr/alsace20.py
Python
gpl-2.0
7,749
0.000516
# -*- coding: utf-8 -*- """ Catch-up TV & More Copyright (C) 2019 SylvainCecchetto This file is part of Catch-up TV & More. Catch-up TV & More 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 Foundat...
ddon"] = "inputstream.adaptive" item.property["inputstream.adaptive.manifest_type"] = "mpd" item.label = get_selected_item_label() item.art.update(get_selected_item_art()) item.info.update(get_selected_item_info()) return item @Resolver.register def g
et_live_url(plugin, item_id, **kwargs): is_helper = inputstreamhelper.Helper('mpd') if not is_helper.check_inputstream(): return False resp = urlquick.get( URL_LIVE, headers={"User-Agent": web_utils.get_random_ua()}, max_age=-1) root = resp.parse() url_live_datas = URL_ROOT + root....
radicalbit/ambari
ambari-server/src/main/resources/common-services/AMBARI_METRICS/0.1.0/package/scripts/hbase_master.py
Python
apache-2.0
1,892
0.014271
#!/usr/bin/env python """ Licensed to the Apache Software Foundation (ASF) under one or more contributor license agree
ments. 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 use this file except in compliance with the License. Y
ou may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the s...
phracek/rebase-helper
rebasehelper/tests/test_archive.py
Python
gpl-2.0
2,830
0.000353
# -*- coding: utf-8 -*- # # This tool helps you to rebase package to the latest version # Copyright (C) 2013-2014 Red Hat, Inc. # # 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...
License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Authors: Petr Hracek <phracek@redhat.com> # Tomas Hozza <thozza@redh...
import os import pytest from rebasehelper.archive import Archive class TestArchive(object): TAR_GZ = 'archive.tar.gz' TGZ = 'archive.tgz' TAR_XZ = 'archive.tar.xz' TAR_BZ2 = 'archive.tar.bz2' ZIP = 'archive.zip' BZ2 = 'file.txt.bz2' INVALID_TAR_BZ2 = 'archive-invalid.tar.bz2' INVAL...
alfasin/st2
st2common/tests/unit/test_policies.py
Python
apache-2.0
4,902
0.000816
# Licensed to the StackStorm, Inc ('StackStorm') 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 use th...
for _, fixture in six.iteritems(FIXTURES['runners']): instance = RunnerTypeAPI(**fixture) RunnerType.add_or_update(RunnerTypeAPI.to_model(instance)) for _, fixture in six.iteritems(FIXTURES['actions']): instance = ActionAPI(**fixture) Action.add_or_update(Ac...
s']): instance = PolicyTypeAPI(**fixture) PolicyType.add_or_update(PolicyTypeAPI.to_model(instance)) for _, fixture in six.iteritems(FIXTURES['policies']): instance = PolicyAPI(**fixture) Policy.add_or_update(PolicyAPI.to_model(instance)) def test_get_by_ref...
mahaveerverma/hand-gesture-recognition-opencv
GestureAPI.py
Python
mit
3,579
0.021794
#!/usr/bin/python import math import numpy as np class Gesture(object): def __init__(self,name): self.name=name def getName(self): return self.name def set_palm(self,hand_center,hand_radius): self.hand_center=hand_center self.hand_radius=hand_radius def set_finger_pos(s...
f-radius_diff) if(length_score<0.09): result=src2.getName() else: result=0 else: angle_diff=[] for i in range(src1.fin
ger_count): angle_diff.append(src1.angle[i]-src2.angle[i]) angle_score=max(angle_diff)-min(angle_diff) if(angle_score<15): length_diff=[] for i in range(src1.finger_count): len1 = np.sqrt((src1.finger_pos[i][0]- src1.hand_center...
BreakVoid/DL_Project
data_utils.py
Python
mit
12,608
0.003252
import os import copy import scipy.interpolate as spi import math import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit data_root = 'toneclassifier' train_data_path = "%s/train" % data_root val_data_path = "%s/test" % data_root test_data_path = "%s/test_new" % data_root def SetPath(r...
global data_root, train_data_path, val_data_path, test_data_path data_root = root train_data_path = "%s/train" % data_root val_data_path = "%s/test" % data_root test_data_path = "%s/test_new" % data_root labels = { 'one': 0, 'two': 1, 'three': 2, 'four': 3 } def LoadData(mode='trai...
ain_data_path if mode == 'val': data_path = val_data_path elif mode == 'test': data_path = test_data_path Engy = [] F0 = [] y = [] for labelName, label in labels.iteritems(): data_subset_path = "%s/%s" % (data_path, labelName) data_names = set() for filena...
rainysia/dotfiles
doc/python/test/dict_clear.py
Python
mit
172
0
#!/usr/bin/env python # coding=utf-8 x = {} y = x x['key'] = 'value' print y x = {} print y print x print '-'*50 a = {} b = a a['key'] = 'value' print b a.clear
() print b
stackforge/tacker
tacker/db/migration/alembic_migrations/versions/d6ae359ab0d6_add_tenant_id_to_lcm_subscriptions_and_.py
Python
apache-2.0
1,237
0.001617
# Copyright 2022 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 law ...
buted on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # """add tenant_id to lcm_subscriptions and lcm_op_occs Revision ID: d6ae359ab0d6 Revises: 3ff50553e9d3 ...
ed by Alembic. revision = 'd6ae359ab0d6' down_revision = '3ff50553e9d3' def upgrade(active_plugins=None, options=None): op.add_column('vnf_lcm_subscriptions', sa.Column('tenant_id', sa.String(length=64), nullable=False)) op.add_column('vnf_lcm_op_occs', s...
HydrelioxGitHub/home-assistant
homeassistant/components/rpi_gpio/cover.py
Python
apache-2.0
3,595
0
"""Support for controlling a Raspberry Pi cover.""" import logging from time import sleep import voluptuous as vol from homeassistant.components.cover import CoverDevice, PLATFORM_SCHEMA from homeassistant.const import CONF_NAME from homeassistant.components import rpi_gpio import homeassistant.helpers.config_validat...
t_state, invert_relay): """Initialize the cover.""" self._name = name self._state = False
self._relay_pin = relay_pin self._state_pin = state_pin self._state_pull_mode = state_pull_mode self._relay_time = relay_time self._invert_state = invert_state self._invert_relay = invert_relay rpi_gpio.setup_output(self._relay_pin) rpi_gpio.setup_input(self._st...
janjaapbos/nanotest
example1/example1/example1svc.py
Python
mit
3,143
0.001273
import oi import os import sys import logging from logging.handlers import SysLogHandler import time import service try: import config except ImportError: import example1.config as config def stop_function(): ctl = oi.CtlProgram('ctl program', config.ctl_url) ctl.call('stop') ctl.client.close() c...
s=globals(), program=self.program
) ) self.program.run() logging.warning("Stopping") scheduler.shutdown() if not self.program.continue_event.wait(0.1): break self.stop() os.unlink('/tmp/demo.pid') os.execl(sys.executable, sys.argv...
TomAugspurger/pandas
pandas/tests/arithmetic/test_interval.py
Python
bsd-3-clause
10,306
0.000776
import operator import numpy as np import pytest from pandas.core.dtypes.common import is_list_like import pandas as pd from pandas import ( Categorical, Index, Interval, IntervalIndex, Period, Series, Timedelta, Timestamp, date_range, period_range, timedelta_range, ) impo...
( "other", [ 0, 1.0, True, "foo", Timestamp("2017-01-01")
, Timestamp("2017-01-01", tz="US/Eastern"), Timedelta("0 days"), Period("2017-01-01", "D"), ], ) def test_compare_scalar_other(self, op, array, other): result = op(array, other) expected = self.elementwise_comparison(op, array, other) tm.assert...
kenorb-contrib/BitTorrent
icmp/test.py
Python
gpl-3.0
1,236
0.005663
# This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # bu...
path=", path exit -1 sock = socket.socket( AF_UNIX, SOC
K_STREAM, 0 ); sock.connect(path) print "connected to ", path while 1: buf = sock.recv(4) len = toint(buf) print "lenbuf=", buf print "len=", len buf = sock.recv(len) print "buf=", buf.encode("hex")
michalkaptur/buildbot_indicator
state.py
Python
gpl-3.0
479
0.002088
class State: def __init__(se
lf, state_checker): self.state_checker = state_checker self.state = None self.previous_state = None def get_current_state(self): return self.state def update_state(self): self.state_checker.update_builders_status() self.previous_state = self.state self.s...
s_state != self.state
ewiger/tree_output
tree_output/log_handler.py
Python
mit
958
0.001044
from logging import Handler, NOTSET class HierarchicalOutputHandler(Handler): def __init__(self, level=NOTSET, houtput=None): Handler.__init__(self, level) self.houtput = houtput def emit(self, record): try: msg
= self.format(record) add_hlevel = record.__dict__.get('add_hl
evel', False) remove_hlevel = record.__dict__.get('remove_hlevel', False) hclosed = record.__dict__.get('hclosed', False) # Do output with thread-safe locking. self.acquire() try: if add_hlevel: self.houtput.add_level() ...
jhogsett/linkit
python/pinwheel.py
Python
mit
6,131
0.022998
#!/usr/bin/python import serial import time import random import sys s = None num_leds = 93 play_time = 0 def flush_input(): s.flushInput() def wait_for_ack(): while s.inWaiting() <= 0: pass ...
s.read(s.inWaiting())
def command(cmd_text): s.write((cmd_text + ':').encode()) wait_for_ack() def setup(): global s, ticks, play_time s = serial.Serial("/dev/ttyS0", 115200) flush_input() choose_colors() command(":::pau:clr") if len(sys.argv) > 1: command(sys.argv[1]) if len(sys.argv) > 2: ...
timberline-secondary/hackerspace
src/manage.py
Python
gpl-3.0
262
0.003817
#!/usr/bin/e
nv python import sys import os if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hackerspace_online.settings") from django.core.management import execute
_from_command_line execute_from_command_line(sys.argv)
kparal/anaconda
pyanaconda/kickstart.py
Python
gpl-2.0
89,420
0.003825
# # kickstart.py: kickstart install support # # Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007 # Red Hat, Inc. All rights reserved. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Fou...
:returns: names of matching devices :rtype: list of str parse methods will not have access to a devicetree, while execute methods will. The devicetree is superior in that it can resolve md array names and in that it reflects scheduled device removals, but for normal local disks
udev.resolve_devspec should suffice. """ full_spec = spec if not full_spec.startswith("/dev/"): full_spec = os.path.normpath("/dev/" + full_spec) # the regular case matches = udev.resolve_glob(full_spec) # Use spec here instead of full_spec to preserve the spec and let the #
itmard/Simple-blog-with-flask
project/apps/main/__init__.py
Python
lgpl-3.0
149
0.006711
# -*- coding: utf-8 -*-
__author__ = 'itmard' # flask imports from flask import Blueprint main = Blueprint('main', __name__)
from . import views
efforia/eos-dashboard
pandora-ckz/pandora/correios/scraping.py
Python
lgpl-3.0
1,673
0.013748
import re import urllib2 from BeautifulSoup import BeautifulSoup from encomenda import Encomenda, Status class CorreiosWebsiteScraper(object): def __init__(self, http_client=urllib2): self.url = 'http://websro.correios.com.br/sro_bin/txect01$.QueryList?P_ITEMCODE=&P_LINGUA=001&P_TESTE=&P_TIPO=001&P_...
if html: encomenda = Encomenda(numero) [encom
enda.adicionar_status(status) for status in self._get_all_status_from_html(html)] return encomenda def _get_all_status_from_html(self, html): html_info = re.search('.*(<table.*</TABLE>).*', html, re.S) try: table = html_info.group(1) except AttributeError,e: return [-1] ...
aficiomaquinas/ega
encuentro-gob/ega.py
Python
apache-2.0
2,649
0.01661
import webapp2 import jinja2 import sys sys.path.insert(0, 'lib') import httplib2 import os from google.appengine.ext.webapp import template from apiclient.discovery import build from oauth2client.appengine import AppAssertionCredentials class ShowHome(webapp2.RequestHandler): def get(self): temp_data = {...
self.response.out.write(template.render(temp_path,temp_data)) class ShowDashInteres(webapp2.RequestHandler): def get(self): temp_data = {} temp_path = 'Templates/dashInteres.html' self.response.out.
write(template.render(temp_path,temp_data)) class ShowDashPorcentaje(webapp2.RequestHandler): def get(self): temp_data = {} temp_path = 'Templates/dashPorcentaje.html' self.response.out.write(template.render(temp_path,temp_data)) class ShowMapa(webapp2.RequestHandler): def get(self): ...
qedsoftware/commcare-hq
corehq/messaging/smsbackends/push/models.py
Python
bsd-3-clause
3,673
0.000545
import requests from corehq.apps.sms.models import SQLSMSBackend from corehq.messaging.smsbackends.push.forms import PushBackendForm from django.conf import settings from lxml import etree from xml.sax.saxutils import escape OUTBOUND_REQUEST_XML = """<?xml version="1.0" encoding="UTF-8"?> <methodCall> <methodName...
sponse_is_error(self, response): return response.status_code != 200 def handle_error(self, response, msg): raise PushException("Received HTTP response %s from push backend" % response.status_code) def handle_success(self, response, msg): response.encoding = 'utf-8' if not respo...
nts = xml.xpath('/methodResponse/params/param/value/struct/member') for data_point in data_points: name = data_point.xpath('name/text()') name = name[0] if name else None if name == 'Identifier': value = data_point.xpath('value/string/text()') ...
Johnetordoff/osf.io
osf/exceptions.py
Python
apache-2.0
7,309
0.003284
import contextlib from django.core.exceptions import ValidationError as DjangoValidationError # Remants from MODM days # TODO: Remove usages of aliased Exceptions ValidationError = DjangoValidationError ValidationValueError = DjangoValidationError ValidationTypeError = DjangoValidationError class TokenError(Excepti...
gs): super(TokenHandlerNotFound, self).__init__(*args, **kwargs) self.action = action class UnsupportedSanctionHan
dlerKind(Exception): pass class OSFError(Exception): """Base class for exceptions raised by the Osf application""" pass class NodeError(OSFError): """Raised when an action cannot be performed on a Node model""" pass class NodeStateError(NodeError): """Raised when the Node's state is not su...
ibis-inria/wellFARE
wellfare/json_api.py
Python
lgpl-3.0
16,896
0.000533
""" This module contains helper functions to communicate with wellfare using JSON dictionnaries. The main function is json_process, which will call one of the subsequent functions depending on the TASK to be performed. """ import numpy as np from .curves import Curve from .ILM import (infer_growth_rate, ...
me'], data['values_volume']) positive = False if 'positive' in data: positive = data['positive'] check_noNaN(curve_v.y, "curve_v.y", "wellfare_growth") n_control_points = get_var_with_default(data, 'n_control_points') ttu = np.l
inspace(curve_v.x.min(), curve_v.x.max(), n_control_points + 3)[:-3] eps_L = get_var_with_default(data, 'eps_L') alphalow = get_var_with_default(data, 'alphalow') alphahigh = get_var_with_default(data, 'alphahigh') nalphastep = get_var_with_default(data, 'nalphastep') a...
stackforge/solum
solum/common/policies/service.py
Python
apache-2.0
1,970
0
# Copyright 2018 ZTE Corporation. # 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 ...
es/{service_id}', 'method': 'PUT'}]), policy.DocumentedRuleDefault( name='create_service', check_str=base.RULE_DEFAULT, description='Create a new service.', operations=[{'path': '/v1/services', 'method': 'POST'}]), policy.Docum
entedRuleDefault( name='delete_service', check_str=base.RULE_DEFAULT, description='Delete a service.', operations=[{'path': '/v1/services/{service_id}', 'method': 'DELETE'}]) ] def list_rules(): return service_policies
xianjunzhengbackup/code
data science/machine_learning_for_the_web/chapter_6/test_server/addressesapp/migrations/0002_remove_person_mobilephone.py
Python
mit
351
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('addressesapp', '0001_initial'), ] operations = [ migr
ations.RemoveField( mode
l_name='person', name='mobilephone', ), ]
aeklant/scipy
scipy/_lib/tests/test_import_cycles.py
Python
bsd-3-clause
1,210
0.000826
import sys import subprocess MODULES = [ "scipy.cluster", "scipy.cluster.vq", "scipy.cluster.hierarchy", "scipy.constants", "scipy.fft", "scipy.fftpack", "scipy.integrate", "scipy.interpolate", "scipy.io", "scipy.io.arff", "scipy.io.harwell_boeing", "scipy.io.idl", ...
nalg.cython_lapack", "scipy.linalg.interpolative", "scipy.misc", "scipy.ndimage", "scipy.odr", "scipy.optimize", "scipy.signal", "scipy.signal.windows", "scipy.sparse", "scipy.sparse.linalg", "scipy.sparse.csgraph", "scipy.spatial", "scipy.spatial.distance", "scipy.sp...
st_modules_importable(): # Check that all modules are importable in a new Python process. #This is not necessarily true if there are import cycles present. for module in MODULES: cmd = 'import {}'.format(module) subprocess.check_call([sys.executable, '-c', cmd])
bolt-project/bolt
bolt/spark/construct.py
Python
apache-2.0
7,798
0.001411
from numpy import unravel_index, prod, arange, asarray, float64 from itertools import product from bolt.construct import ConstructBase from bolt.spark.array import BoltArraySpark from bolt.spark.utils import get_kv_shape, get_kv_axes class ConstructSpark(ConstructBase): @staticmethod def array(a, context=N...
t64 The desired data-type for the array. If None, will be determined from the data. (see numpy) npartitions : int Number of partitions for parallization. Returns
------- BoltArraySpark """ from numpy import ones return ConstructSpark._wrap(ones, shape, context, axis, dtype, npartitions) @staticmethod def zeros(shape, context=None, axis=(0,), dtype=float64, npartitions=None): """ Create a spark bolt array of zeros...
dikaiosune/whether
py_whether/processor.py
Python
mit
2,959
0.002028
__author__ = 'adam' import configparser import os import os.path from sys import argv import logging import postgresql import db import parsing # read configuration config = configparser.ConfigParser() config.read(argv[1:]) gsod_conf = config['GSOD FILES'] pg_conf = config['POSTGRES'] gsod_root = gsod_conf['bas...
atter = logging.Formatter('%(asctime)s %(name)s^%(levelname)s: %(message)s') fh.setForma
tter(formatter) ch.setFormatter(formatter) log.addHandler(fh) log.addHandler(ch) # start of main execution log.info("Starting whether parser...") # instantiate database connection connection = postgresql.open(user=pg_user, password=pg_pass, host=pg_host, port=pg_port, database=pg_db) log.info("Connected to database!...
mpetyx/palmdrop
venv/lib/python2.7/site-packages/cms/middleware/language.py
Python
apache-2.0
722
0.00277
# -*- coding: utf-8 -*- import datetime from django.utils.translation import get_language from django.conf import settings class LanguageCookieMiddleware(object): def process_response(self, request, response): language = get_language() if settings.LANGUAGE_COOKIE_NAME in request.COO
KIES and \ request.COOKIES[settings.LANGUAGE_COOKIE_NAME] == language: return response max_age = 365 * 24 * 60 * 60 # 10 years expires = datetime.datetime.now() + datetime.timedelta(seconds=max_age)
response.set_cookie(settings.LANGUAGE_COOKIE_NAME, language, expires=expires.utctimetuple(), max_age=max_age) return response
catapult-project/catapult
telemetry/telemetry/timeline/model_unittest.py
Python
bsd-3-clause
3,395
0.002356
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from __future__ import absolute_import import unittest from telemetry import decorators from telemetry.testing import tab_test_case from telemetry.timeline ...
nabled('has tabs') def testGetFirstRendererThread_multipleTabs(self): # Make sure a couple of tabs exist. first_tab = self.tabs[0
] second_tab = self.tabs.New() second_tab.Navigate('about:blank') second_tab.WaitForDocumentReadyStateToBeInteractiveOrBetter() self.tracing_controller.StartTracing(self.config) first_tab.AddTimelineMarker('background-tab') second_tab.AddTimelineMarker('foreground-tab') trace = self.tracing...
xk0/SmartRPyC
smartrpyc/client/exceptions.py
Python
apache-2.0
120
0
cl
ass ServerUnavailable(Exception): """ Raised when server is not available for consuming a request ""
"
pernici/sympy
sympy/simplify/tests/test_simplify.py
Python
bsd-3-clause
24,474
0.006292
from sympy import Symbol, symbols, hypersimp, factorial, binomial, \ collect, Function, powsimp, separate, sin, exp, Rational, fraction, \ simplify, trigsimp, cos, tan, cot, log, ratsimp, Matrix, pi, integrate, \ solve, nsimplify, GoldenRatio, sqrt, E, I, sympify, atan, Derivative, \ S, ...
assert fraction(x/2) == (x, 2) assert fraction(x*y/z) == (x*y, z) assert fraction(x/(y*z)) == (x, y*z) assert fraction(1/y**2) == (1, y**2) assert fraction(x/y**2) == (x, y**2) assert fraction((x**
2+1)/y) == (x**2+1, y) assert fraction(x*(y+1)/y**7) == (x*(y+1), y**7) assert fraction(exp(-x), exact=True) == (exp(-x), 1) def test_separate(): x, y, z = symbols('x,y,z') assert separate((x*y*z)**4) == x**4*y**4*z**4 assert separate((x*y*z)**x) == x**x*y**x*z**x assert separate((x*(y*z)**2)...
kjedruczyk/phabricator-tools
py/phl/phlmail_sender.py
Python
apache-2.0
2,042
0
"""A mail sender that sends mail via a configured sendmail.""" # ============================================================================= # CONTENTS # ----------------------------------------------------------------------------- # phlmail_sender # # Public Classes: # MailSender # .send # # -------------------...
resses, cc_addresses=None): mime = phlmail_format.text( subject, message, self._from_email, to_addresses, cc_addresses) self._sendmail.send(mime) # ----------------------------------------------------------------------------- # Copyright (C) 2013-2014 Bloomberg Finance L.P. # # Licensed un...
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 language governing permis...
terna/SLAPP3
6 objectSwarmObserverAgents_AESOP_turtleLib_NetworkX/oligopoly/partial_corr.py
Python
cc0-1.0
2,311
0.007789
# from https://gist.github.com/fabianp/9396204419c7b638d38f """ Partial Correlation in Python (clone of Matlab's partialcorr) This uses the linear regression approach to compute the partial correlation (might be slow for a huge number of variables). The algorithm is detailed here: http://en.wikipedia.org/wiki/...
target and Z as the predictor 2) calculate the residuals in Step #1 3) perform a normal linear least-squares regression with Y as the ta
rget and Z as the predictor 4) calculate the residuals in Step #3 5) calculate the correlation coefficient between the residuals from Steps #2 and #4; The result is the partial correlation between X and Y while controlling for the effect of Z Date: Nov 2014 Author: Fabian Pedregosa-Izquierdo, f@bianp.ne...
jgravois/ArcREST
samples/create_replica_portal_item.py
Python
apache-2.0
2,205
0.005896
""" This sample shows how to create a replica from portal of a feature service """ import arcrest from arcrest.security import AGOLTokenSecurityHandler def trace(): """ trace finds the line, the filename and error message and returns it to the user """ import traceback, inspe...
Type="export") if status['status'].lower() == 'failed': print status break del status exportItem = content.item(exportItemId) itemDataPath = exportItem.itemData(f=None, savePath=savePath) uc.deleteItem(item_id=exportItemId) ...
= trace() print("error on line: %s" % line) print("error in file name: %s" % filename) print("with error message: %s" % synerror)
natb1/query-tools
tests/examples/fixture_model.py
Python
mit
554
0.005415
class Penguin
(object): def __init__(self, name, mood, id=None): self.name = name self.mood = mood self.id = id def __repr__(self): return '< %s the %s penguin >' % (self.name, self.mood) class Goose(object): def __init__(self, name, favorite_penguin, id=None): self.name = ...
enguin self.id = id def __repr__(self): template = '< %s, the goose that likes %s >' return template % (self.name, repr(self.favorite_penguin))
lduarte1991/edx-platform
openedx/core/djangoapps/schedules/migrations/0006_scheduleexperience.py
Python
agpl-3.0
750
0.004
# -*- coding: utf-8 -*-
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('schedules', '0005_auto_20171010_1722'), ] operations = [ migrations.CreateModel( name='ScheduleExperience', fields=[ ...
eld(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('experience_type', models.PositiveSmallIntegerField(default=0, choices=[(0, b'Recurring Nudge and Upgrade Reminder'), (1, b'Course Updates')])), ('schedule', models.OneToOneField(related_name='experience', to...
RobinQuetin/CAIRIS-web
cairis/cairis/TCNarrativeTextCtrl.py
Python
apache-2.0
3,495
0.021745
# 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...
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 language governing ...
viouralCharacteristicsDialog from Borg import Borg from AssumptionTaskModel import AssumptionTaskModel from ATModelViewer import ATModelViewer class TCNarrativeTextCtrl(wx.TextCtrl): def __init__(self, parent, winId): wx.TextCtrl.__init__(self,parent,winId,size=(150,100),style=wx.TE_MULTILINE) self.ctrlMenu ...
ColumbiaCMB/kid_readout
apps/data_taking_scripts/2015-10-jpl-park/sweep_and_stream_at_min_s21_two_groups_cw_noise_power.py
Python
bsd-2-clause
4,432
0.008348
__author__ = 'gjones' import time import sys import numpy as np from kid_readout
.roach import heterodyne from kid_readout.utils import data_file, sweeps from kid_readout.equipment import hittite_controller, lockin_controller hittite = hittite_controller.hittiteController(addr='192.168.0.200') lockin = lockin_controller.lockinController() print lockin.get_idn() ri = heterodyne.RoachHeterodyne(adc...
1410.0 #all_f0s = np.load('/data/readout/resonances/2016-01-13-jpl-2015-10-park-dark-32-resonances-split-at-1300.npy') -0.5 #group_1_f0 = all_f0s[all_f0s < 1300] #group_2_f0 = all_f0s[all_f0s > 1300] """ all_f0s = np.load('/data/readout/resonances/2016-02-12-jpl-park-100nm-32-resonances.npy') group_1_f0 = all_f0s[all_...
kizniche/Mycodo
mycodo/inputs/ads1256_analog_ph_ec.py
Python
gpl-3.0
31,269
0.001664
# coding=utf-8 import traceback from flask_babel import lazy_gettext from mycodo.config import SQL_DATABASE_MYCODO from mycodo.databases.models import Conversion from mycodo.databases.models import DeviceMeasurements from mycodo.databases.utils import session_scope from mycodo.inputs.base_input import AbstractInput f...
ed = True # Ensure value is positive if value <= 0: all_passed = False
errors.append("Must be a positive value") return all_passed, errors, mod_input def execute_at_modification( messages, mod_input, request_form, custom_options_dict_presave, custom_options_channels_dict_presave, custom_options_dict_postsave, custom_options_cha...
xdevelsistemas/taiga-back-community
taiga/timeline/management/commands/_update_timeline_for_updated_tasks.py
Python
agpl-3.0
3,369
0.000594
# -*- coding: utf-8 -*- # Copyright (C) 2014-2016 Andrey Antukh <niwi@niwi.nz> # Copyright (C) 2014-2016 Jesús Espino <jespinog@gmail.com> # Copyright (C) 2014-2016 David Barragán <bameda@dbarragan.com> # Copyright (C) 2014-2016 Alejandro Alonso <alejandro.alonso@kaleidos.net> # This program is free software: you can r...
(): print("%s/%s"%(counter, total)) task_id = timeline.object_id task = tasks_per_id.get(task_id, None) if not task: counter += 1 contin
ue user_story = tasks_per_id[task_id].user_story if not user_story: counter += 1 continue timeline.data["task"]["userstory"] = userstory_timeline(user_story) timeline.save(update_fields=["data"]) counter += 1 class Command(BaseCommand): help = 'Reg...
hamtamtots/website
matt_site/blog/views/articlelistview.py
Python
mit
240
0.012605
from django.views.generic import ListView fr
om blog.models.article import Article class ArticleListView(ListView): model = Article template_name = 'blog/articlelist.html' queryset = Article.objec
ts.order_by('-created')
sumanthjamadagni/OZ
SinglePointCalculation.py
Python
gpl-3.0
1,299
0.018476
import OZ.Potentials as Potentials import OZ.OZ_Functions as OZF import OZ.PP_Functions as PP_Functions #import FigFuncs #import HNC import OZ.RHNC as RHNC import numpy as np def SinglePointCalculation(r, k, Ur, Ur_ref, rho, T=1.0, OutFile=None, cr_guess=None, tol=1e-8): #RHNC Solver print "Function = Sin...
k, Ur, Ur_ref, rho, T = T, maxiter=10000, w_old_start=0.50,w_old_max=0.99,tol=tol, cr_guess=cr_guess) B2 = Potentials.CalcB2(r,Ur,T=T) mu_ex, mu = PP_Functions.ExcessChemPot(r, hr, cr, rho, T=T) rmin = 0.50 if Flag == 0: gr = hr + 1.0
P_virial = PP_Functions.Calc_Pvirial(r, gr, Ur, rho, T=T, rmin=0.50) s2 = PP_Functions.s2(r, gr, rho) ListHeader=['T', 'rho', 'B2', 'P_virial' ,'Sk0', 'kappa', 'mu', 's2','Sk_max'] ListValues = [T, rho, B2, P_virial, Sk[0], Sk[0]/(rho*T), mu, s2, np.max(Sk)] i...
PnEcrins/GeoNature-atlas
atlas/configuration/config_schema.py
Python
gpl-3.0
7,525
0.001464
from marshmallow import ( Schema, fields, validates_schema, ValidationError, validates_schema, EXCLUDE, ) from marshmallow.validate import Regexp MAP_1 = { "name": "OpenStreetMap", "layer": "//{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png", "attribution": "&copy OpenStreetMap", } M...
False) DISPLAY_PATRIMONIALITE = fields.Boolean(load_defaul
t=False) PATRIMONIALITE = fields.Dict( load_default={ "label": "Patrimonial", "config": { "oui": { "icon": "custom/images/logo_patrimonial.png", "text": "Ce taxon est patrimonial", } }, } ...
aeklant/scipy
scipy/stats/_distn_infrastructure.py
Python
bsd-3-clause
127,400
0.000314
# # Author: Travis Oliphant 2002-2011 with contributions from # SciPy Developers 2004-2011 # from scipy._lib._util import getfullargspec_no_self as _getfullargspec import sys import keyword import re import types import warnings from itertools import zip_longest from scipy._lib import doccer from ._distr_p...
distribution function. """ _doc_sf = """\ sf(x, %(shapes)s, loc=0, scale=1) Survival function (also defined as ``1 - cdf``, but `sf` is sometimes more accurate). """ _doc_logsf = """\ logsf(x, %(shapes)s, loc=0, scale=1) Log of the survival function.
""" _doc_ppf = """\ ppf(q, %(shapes)s, loc=0, scale=1) Percent point function (inverse of ``cdf`` --- percentiles). """ _doc_isf = """\ isf(q, %(shapes)s, loc=0, scale=1) Inverse survival function (inverse of ``sf``). """ _doc_moment = """\ moment(n, %(shapes)s, loc=0, scale=1) Non-central moment of order n...
cliftonmcintosh/openstates
openstates/id/__init__.py
Python
gpl-3.0
4,242
0
from pupa.scrape import Jurisdiction, Organization from .people import IDPersonScraper from .committees import IDCommitteeScraper from .bills import IDBillScraper class Idaho(Jurisdiction): """ IDAHO Scraper """ division_id = "ocd-division/country:us/state:id" classification = "government" n...
islature_name, classification="legislature") upper = Organization(upper_chamber_name, classifi
cation='upper', parent_id=legislature._id) lower = Organization(lower_chamber_name, classification='lower', parent_id=legislature._id) for n in range(1, upper_seats+1): upper.add_post( label=str(n), role=upper_title, ...
unicefuganda/edtrac
edtrac_project/rapidsms_xforms_src/setup.py
Python
bsd-3-clause
1,235
0.004858
from setuptools import setup, find_packages setup( name='rapidsms-xforms', version=__import__('rapidsms_xforms').__version__, license="BSD", install_requires
= [ "django>=1.3", "rapidsms==0.9.6a", "django-uni-form==0.8.0", "django-eav==0.9.2", "python-digest==1.7", "django-digest==1.13" ], dependency_links = [ "https://git
hub.com/mvpdev/django-eav/tarball/master#egg=django-eav-0.9.2" ], description='Interactive form builder for both XForms and SMS submissions into RapidSMS', long_description=open('README.rst').read(), author='Nicolas Pottier, Eric Newcomer', author_email='code@nyaruka.com', url='http://github....
ralphbean/moksha
moksha/api/widgets/amqp/amqp.py
Python
apache-2.0
7,523
0.000798
# This file is part of Moksha. # Copyright (C) 2008-2010 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
get('moksha.socket.notify', False)) self.orbited_host = config.get('orbited_host', 'localhost') self.orbited_port = str(config.get('orbited_port', 9000)) self.orbited_schem
e = config.get('orbited_scheme', 'http') self.orbited_url = '%s://%s:%s' % ( self.orbited_scheme, self.orbited_host, self.orbited_port) self.orbited_js = tw.api.JSLink( link=self.orbited_url + '/static/Orbited.js') self.moksha_domain = config.get('moksha.domain', 'localho...
pombredanne/drf-toolbox
tests/models.py
Python
bsd-3-clause
2,563
0.00039
from __future__ import absolute_import, unicode_literals from drf_toolbox.compat import models, django_pgfields_installed from drf_toolbox import serializers from tests.compat import mock class ExplicitAPIEndpointsModel(models.Model): api_endpoints = models.IntegerField() something = models.CharField(max_leng...
rue) class Meta: app_label = 'tests' if django_pgfields_installed: with mock.patch.multiple(models.CompositeField, create_type=mock.DEFAULT, create_type_sql=mock.DEFAULT, regi
ster_composite=mock.DEFAULT): class CoordsField(models.CompositeField): x = models.IntegerField() y = models.IntegerField() class SizeField(models.CompositeField): width = models.IntegerField() height = models.IntegerField() def get_drf_seria...
amarandon/pinax
pinax/apps/account/tests/test_password_reset.py
Python
mit
7,013
0.007557
import os import re from django.conf import settings from django.core import mail from django.core.urlresolvers import reverse from django.test import TestCase from django.contrib.auth.models import User import pinax from emailconfirmation.models import EmailAddress, EmailConfirmation class PasswordResetTest(Test...
self.assertEquals(response.status_code, 200) # check the password has been changed user = User.objects.
get(email="bob@example.com") self.assert_(user.check_password("newpassword")) # check we can't GET with same path response = self.client.get(path) self.assertEquals(response.status_code, 200) self.assertContains(response, "The password reset link was invalid") ...
pattisdr/lookit-api
accounts/migrations/0014_auto_20170726_1403.py
Python
mit
702
0.001425
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-07-26 14:03 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('accounts', '0013_auto_20170718_2137'), ] operations = [ migrations.AlterModelOption...
s': (('can_view_organization', 'Can View Organization'), ('can_edit_organization', 'Can Edit Organization'), ('can_create_organization', 'Can Create Organization'), ('can_remove_organizat
ion', 'Can Remove Organization'), ('can_view_experimenter', 'Can View Experimenter'))}, ), ]
aroth-arsoft/arsoft-web-crashupload
app/manage.py
Python
gpl-3.0
266
0.003759
#!/usr/bi
n/env python3 import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "arsoft.web.crashupload.settings") from django.core.management import execute_from_command_line execute_from_command_line(s
ys.argv)
pktrigg/pygsf
pygsf.py
Python
apache-2.0
38,850
0.028603
#name: pygsf #created: July 2017 #by: p.kennedy@fugro.com #description: python module to read and write a Generic Sensor Formaty (GSF) file natively #notes: See main at end of script for example how to use this #based on GSF Version 3.05 # See readme.md for more details import sys from glob import glob import ...
self.compressionFlag = 0 #/* Specifies bytes of storage in high order nibble and type of compression in low order nibble */ self.multiplier = 0.0 self.offset = 0 self.name = "scaleFac
tor" def __str__(self): ''' pretty print this class ''' return pprint.pformat(vars(self)) class SWATH_BATHYMETRY_PING : def __init__(self, fileptr, numbytes, recordidentifier, hdrlen): self.recordidentifier = recordidentifier # assign the GSF code for this datagram type self.offset = fileptr.tell() #...
kiniou/blender-smooth-slides
tools/lpod/test/test_content.py
Python
gpl-3.0
4,392
0.000683
# -*- coding: UTF-8 -*- # # Copyright (c) 2009 Ars Aperta, Itaapy, Pierlis, Talend. # # Authors: Romain Gauthier <romain@itaapy.com> # Hervé Cauwelier <herve@itaapy.com> # David Versmisse <david.versmisse@itaapy.com> # # This file is part of Lpod (see: http://lpod-project.org). # Lpod is free software...
may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 #
# Import from the Standard Library from unittest import TestCase, main # Import from lpod from lpod.document import odf_get_document class ContentTestCase(TestCase): def setUp(self): self.document = document = odf_get_document('samples/base_text.odt') def tearDown(self): del self.document...
GPflow/GPflow
gpflow/conditionals/dispatch.py
Python
apache-2.0
1,281
0.000781
# Copyright 2017-2020 The GPflow Contributors. 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 language governing permissions and # limitations under the License. from deprecated impo...
type-ignore below is because mypy doesn't like it when we assign to a function. conditional.register = deprecated( # type: ignore reason="Registering new implementations of conditional() is deprecated. " "Instead, create your own subclass of gpflow.posteriors.AbstractPosterior " "and register an implement...
grahame/ealgis
django/ealgis/ealauth/migrations/0004_auto_20161217_0949.py
Python
gpl-3.0
1,175
0.002553
# -*- coding: utf-8 -*- # Generated by Django
1.10.4 on 2016-12-17 09:49 from __future__ import unicode_literals from django.conf import settings import d
jango.contrib.postgres.fields.jsonb from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('ealauth', '0003_auto_20161217_0940'), ] operations = [ ...
googleapis/python-monitoring
google/cloud/monitoring_v3/services/service_monitoring_service/transports/grpc.py
Python
apache-2.0
22,884
0.002054
# -*- coding: utf-8 -*- # Copyright 2022 Google 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...
else: self._ssl_channel_credentials = SslCredentials().ssl_credentials else: if client_cert_source_for_mtls and
not ssl_channel_credentials: cert, key = client_cert_source_for_mtls() self._ssl_channel_credentials = grpc.ssl_channel_credentials( certificate_chain=cert, private_key=key ) # The base transport sets the host, credentials and ...
AlexBoogaard/Sick-Beard-Torrent-Edition
sickbeard/metadata/generic.py
Python
gpl-3.0
35,514
0.003097
# Author: Nic Wolfe <nic@wolfeden.ca> # URL: http://code.google.com/p/sickbeard/ # # This file is part of Sick Beard. # # Sick Beard 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 t...
ault behavior is m
eant to mostly follow XBMC 12+ metadata standards. Has support for: - show metadata file - episode metadata file - episode thumbnail - show fanart - show poster - show banner - season thumbnails (poster) - season thumbnails (banner) - season all poster - season all...
chfoo/wpull
wpull/util_test.py
Python
gpl-3.0
4,235
0.000236
# encoding=utf-8 import os import sys import tempfile import unittest from dns.resolver import NoNameservers from wpull.util import (datetime_str, python_version, filter_pem, parse_iso8601_str, is_ascii, close_on_error, get_exception_message, GzipPickleStream) DEFAULT_...
tEqual( 'NoNameservers', get_exception_message(error) )
try: raise NoNameservers() except NoNameservers as error: self.assertEqual( 'NoNameservers', get_exception_message(error) ) def test_pickle_stream_filename(self): with tempfile.TemporaryDirectory() as temp_dir: filename = os.pat...
valdergallo/mock_django_orm
app/forms.py
Python
mit
374
0.002674
from django.forms import ModelForm, ValidationError from app.models import AppOne import re class FormAppOne(ModelForm): class Meta: model = AppOne def clean_
name(self): cleaned_name = self.cleaned_data.get('name') if re.findall('\d+', cleaned_name): raise ValidationError("Name must be only text") r
eturn cleaned_name
akissa/baruwa2
baruwa/lib/mq/commands.py
Python
gpl-3.0
5,582
0.000179
# -*- coding: utf-8 -*- # vim: ai ts=4 sts=4 et sw=4 # Baruwa - Web 2.0 MailScanner front-end. # Copyright (C) 2010-2015 Andrew Colin Kissa <andrew@topdog.za.net> # # 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 S...
gs[0])
self.update_parser() return Command.run(self, args[1:]) # return super(BasePasterCommand, self).run(args[1:]) def update_parser(self): """ Abstract method. Allows for the class's parser to be updated before the superclass's `run` method is called. Necessary to a...
SamGinzburg/GeneOntologyTools
generate_pie_charts.py
Python
mit
8,151
0.036437
""" Author: Sam Ginzburg Description: This script reads in a blast2go sequence table output of GO Term mappings, and calculates frequencies of GO Terms at specific GO Levels Example run: python generate_pie_charts.py [blast2go_file.txt] [GO Level] """ import sys from GeneOntologyLibrary import obo_parser from GeneOnt...
s:\t" + str(sum(molecular_function.values()))) print ("Number of biological process go terms:\t" + str(sum(biological_process.values()))) print ("Number of cellular component go terms:\t" + str(sum(cellular_component.values()))) parser = obo_parser("go.obo") parser.build_obo_file() generate_counts(biolog...
rint (sum(biological_process.values())) biological_process = filter_by_level(biological_process,args[1], parser, "biological_process") molecular_function = filter_by_level(molecular_function,args[1], parser, "molecular_function") cellular_component = filter_by_level(cellular_component,args[1], parser, "cellular_c...
isezen/pytkm
tkmdecrypt.py
Python
mit
6,869
0.000437
#!/usr/bin/python # noqa # -*- coding: utf-8 -*- # pylint: disable=C0103 """This is decryption module for tkm.py""" from array import array import numpy as np # region Constants _REF_TABLE_1 = array('i', ( 237, 220, 239, 100, 120, 248, 241, 54, 244, 169, 178, 230, 68, 203, 43, 127, 175, 114, 154, 60, 218, 20,...
i in range(5)]) l4 = l6[(55 + _KEY_SIZE):(55 + _KEY_SIZE + int(l5))] l3 = '' for i in range(int(l5)): l19 = ord(l4[i]) l20 = l9[i % _KEY_SIZE] l19 = (l19 >> l20 | (l19 << 8 - l20 & 255)) & 25
5 l19 -= int(l10) l3 += _INT_TO_CHAR_TABLE.decode('utf-8')[l19] return l3.encode('utf-8') def decrypt2(encrypted_text): """Decrypt an encrypted text. This function is used to decrypt static files. :type encrypted_text: str :param encrypted_text: Encrypted text :return: Decryp...
CGATOxford/CGATPipelines
obsolete/pipeline_annotations.py
Python
mit
90,231
0.000188
"""=================== Annotation pipeline =================== The annotation pipeline imports various third party annotations or creates them for use in other pipelines. The purpose of this pipeline is to automate and standardize the way we retrieve and build genomic annotations but also to allow sharing of annotati...
g used in the downstream pipeline explicitely (for example, for protein coding genes):: mkdir ensembl.dir cp <MYDATADIR>/my_gtf_geneset.gtf.gz ensembl.dir/geneset_coding.gtf.gz Roadmap ------- There are many annotations that could possibly be brought into this pipeline: * ENCODE data Can be used directly...
genome, but on the cell type as well and thus might be project specific? * Gene networks Functional assocation between genes. Outside of the scope of this pipeline? * Mapability Mapability tracks are not available from all genomes. The pipeline could include runnig GEM on the assembly. For no...
allisonrandal/sphinx-strat-doc-base
source/conf.py
Python
apache-2.0
793
0.007566
# -*- coding: utf-8 -*- # # Minimum neccessary conf options for LaTeX output. # Replaces sphinx-quickstart generated conf.py. # import sys im
port os # -- General configuration ------------------------------------------------ source_suffix = '.rst' master_doc = 'index' project = u'Document Title' copyright = u'years, Author Name' version = '0.0' release = version # -- Options for LaTeX output --------------------------------------------- latex_elements...
usepackage{strat}', } latex_documents = [ ('index', 'output_file.tex', '', u'Author Name', 'howto'), ] latex_additional_files = ['strat.sty']
viggates/nova
nova/tests/api/openstack/compute/plugins/v3/test_extended_status.py
Python
apache-2.0
4,622
0.000649
# Copyright 2011 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...
res = req.get_response(fakes.wsgi_app_v3( init_only=('servers', 'os-extended-status'))) return res def _get_server(self, body):
return jsonutils.loads(body).get('server') def _get_servers(self, body): return jsonutils.loads(body).get('servers') def assertServerStates(self, server, vm_state, power_state, task_state, locked_by): self.assertEqual(server.get('%svm_state' % self.prefix), v...
beeftornado/sentry
src/sentry/auth/providers/saml2/okta/apps.py
Python
bsd-3-clause
304
0
from __future__ import absolute_import from django.apps import AppCo
nfig class Config(AppConfig): name = "sentry.auth.providers.saml2.okta" def ready(self): from sentry.auth import register from .provider import OktaSAML2Provider
register("okta", OktaSAML2Provider)
dmlc/tvm
gallery/how_to/work_with_schedules/reduction.py
Python
apache-2.0
7,673
0.000521
# 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...
the License is distributed on an # "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """ Reduction ========= **Author**: `Tianqi Chen <https://tqchen.github.io>`_ This is an introduction material on how to do reduction in TV...
boisvert42/npr-puzzle-python
2016/0424_drugstore_section.py
Python
cc0-1.0
1,003
0.011964
''' NPR Puzzle 2016-04-24 http://www.npr.org/2016/04/24/475299329/finish-this-puzzle-and-youll-be-just-like-overachievers-you-both-exceed Name a famous singer -- first and last names. The last four letters of the first name spelled backward plus the first four letters of the last name spelled forward, read togethe...
er()]) names = get_famous_names() for name in names.iterkeys(): if name.count(' ') == 1: first_name, last_name = name.lower().split(' ') if len(first_name) >= 4 and len(last_name) >= 4: word = first_name[-1:-5:-1] + last_name[:4] try: print lemma_dict[word], n...
except KeyError: pass
karlinjf/ChromiumXRefs
lib/chromium_code_search.py
Python
apache-2.0
7,067
0.018537
# Copyright 2017 Josh Karlin. All rights reserved. # Use of this source code is governed by the Apache license found
in the LICENSE # file. import argparse import datetime import getopt import json import sys import tempfile import threading import time import urllib.request import urllib.parse gFileCache = None; # A key/value store that stores objects to disk in temporary objects # for 30 minutes. class FileCache: def __init__(...
TemporaryFile(); f.write(data); self.store[url] = (f, datetime.datetime.now()); def get(self, url): if not url in self.store: return '' (f, timestamp) = self.store[url] f.seek(0); return f.read(); def gc(self): threading.Timer(15 * 60, self.gc).start(); expired = datetime.dat...
devurandom/portage
pym/portage/tests/emerge/test_emerge_slot_abi.py
Python
gpl-2.0
5,878
0.032154
# Copyright 2012 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 import subprocess import sys import portage from portage import os from portage import _unicode_decode from portage.const import (BASH_BINARY, PORTAGE_BIN_PATH, PORTAGE_PYM_PATH, USER_CONFIG_PATH) from portage.proce...
" % (os.environ["PORTAGE_GRPNAME"],), "PORTAGE_USERNAME=\"%s\"\n" % (os.environ["PORTAGE_USERNAME"],), "PKGDIR=\"%s\"\n" % (pkgdir,), "PORTAGE_INST_GID=%s\n" % (portage.data.portage_gid,), "PORTAGE_INST_UID=%s\n" % (portage.data.portage_uid,), "PORTAGE_TMPDIR=\"%s\"\n" % (portage_tmpdir,), "CLEAN_DELA...
not path.strip(): path = None if path is None: path = "" else: path = ":" + path path = fake_bin + path pythonpath = os.environ.get("PYTHONPATH") if pythonpath is not None and not pythonpath.strip(): pythonpath = None if pythonpath is not None and \ pythonpath.split(":")[0] == PORTAGE_PYM_...
ceph/autotest
frontend/shared/rest_client.py
Python
gpl-2.0
8,328
0.003002
import copy, getpass, logging, pprint, re, urllib, urlparse import httplib2 from django.utils import datastructures, simplejson from autotest_lib.frontend.afe import rpc_client_lib from autotest_lib.client.common_lib import utils _request_headers = {} def _get_request_headers(uri): server = urlparse.urlparse(ur...
): self._http = http assert 'href' in representation_dict for key, value in representation_dict.iteritems(): setattr(self, str(key), value) def __repr__(self): return 'Resource(%r)' % self._representation() def pprint(self): # pretty-print support for debu...
uri, http=None): if not http: http = httplib2.Http() directory = cls({'href': uri}, http) return directory.get() def _read_representation(self, value): # recursively convert representation dicts to Resource objects if isinstance(value, list): return ...
titipata/pubmed_parser
docs/conf.py
Python
mit
2,161
0
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
-----------------------
------ project = 'Pubmed Parser' copyright = '2020, Titipat Achakulvisut' author = 'Titipat Achakulvisut' version = pubmed_parser.__version__ release = pubmed_parser.__version__ # -- General configuration --------------------------------------------------- # Add any Sphinx extension module names here, as strings. T...