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
jmcarp/nplusone
nplusone/ext/flask_sqlalchemy.py
Python
mit
1,648
0.000607
# -*- coding: utf-8 -*- import six from flask import g from flask import request from nplusone.core import signals from nplusone.core import listeners from nplusone.core import notifiers import nplusone.ext.sqlalchemy # noqa def get_
worker(): try: r
eturn request._get_current_object() except RuntimeError: return None def setup_state(): signals.get_worker = get_worker setup_state() class NPlusOne(object): def __init__(self, app=None): self.app = app if app is not None: self.init_app(app) def load_config(self,...
Boris-Barboris/rsoi
lab01/client/client_app/views.py
Python
mit
2,533
0.00556
from django.shortcuts import render from django.http import HttpResponse, HttpResponseForbidden, \ HttpResponseRedirect, HttpResponseBadRequest, HttpResponseNotAllowed import logging log = logging.getLogger('client_app') # Create your views here. from .oauthclient import * OAUTH_URL = 'http://192.168.243.5:3900...
://192.168.243.5:39001' def index(request): log_request(request) if request.method == 'GET': # check if we have code in parameters code = request.GET.get('code', None) if code: # get token gp = GrantPlugin(code) client = OAuthC
lient(OAUTH_URL, gp, CLIENT_ID, 'clientsecret', CLIENT_URL) try: tclient = client.make_token_client() except ExpiredException as ee: tokens = str(ee) verify_status = 'None, auth_code expired!' else: tokens = tclient.auth...
jbchouinard/jbnetwork
jbnetworkfactory.py
Python
mit
2,645
0.001134
""" Functions for generating several types of classic networks. Functions: build_star_network build_chain_network build_ring_network build_random_network build_clique_network build_hypercube_network build_grid_network """ import jbnetwork as jbn def build_star_network(size): """Build a star network. Returns Netwo...
for j in range(i+1, size):
network.add_link(i, j) return network def build_hypercube_network(size): """Build a hypercube network. Returns Network object.""" # pylint: disable=missing-docstring def _rec_build_hc_net(size): if size == 1: return {0:{}} network = {} network1 = _rec_build_...
open-craft/opencraft
api/urls.py
Python
agpl-3.0
2,688
0.002232
# -*- coding: utf-8 -*- # # OpenCraft -- tools to aid developing and hosting free software projects # Copyright (C) 2015-2019 OpenCraft <contact@opencraft.com> # # 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 Fre...
as_view(url='v1/', permanent=False), name='index'), # v1 urls url(r'^v1/', include((v1_router.urls, 'api_v1'),
namespace='v1')), url(r'^v1/auth/', include('rest_framework.urls', namespace='rest_framework')), # v2 urls url(r'^v2/', include((v2_router.urls, 'api_v2'), namespace='v2')), url(r'^v2/auth/token/', JWTAuthToken.as_view(), name='token_obtain_pair'), # They are required to check if the token is valid...
jeboehm/uhcx-xchat
uhcx_xchat.py
Python
gpl-2.0
2,529
0.001582
""" uh.cx X-Chat Version @homepage: http://uh.cx @copyright: Copyright (C) 2015 J. Boehm """ __module_name__ = "uh.cx" __module_version__ = "0.2" __module_description__ = "Make a shortened URL with uh.cx and post it to a channel or user." __module_author__ = "uh.cx (J. Boehm)" import urllib import traceback import j...
raise Manager.InvalidResponseException() if not Manager.ResponseValidator.check(response_data): raise Manager.InvalidResponseException() link = Manager.Link()
link.qr_preview = response_data['QrPreview'] link.qr_redirect = response_data['QrDirect'] link.url_original = response_data['UrlOriginal'] link.url_preview = response_data['UrlPreview'] link.url_redirect = response_data['UrlDirect'] return link def on_uhcx(word, word_eol...
NJ-zero/Android
requests_demo/bas_pd/Public_Client_Method.py
Python
mit
1,331
0.031555
#coding=utf-8 #author='Shichao-Dong' import requests def r_post(url,headers,data): r=requests.post(url=url,headers=headers,data=data) return r def login_func(host,name,code,password): url="http://"+ host +'/portal/logon.action' headers = {"Connection": "keep-alive", "Referer": "http://172...
OW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3)", "Content-Length": "195", "Host": host } data={'identifiers.src': 'waiqin365',
'identifiers.password':password, "refer":"http://172.31.3.73:8888", 'identifiers.type': '1', 'identifiers.tenantname':name, 'identifiers.code':code } r=requests.post(url=url,headers=headers,data=data) return r
google/TensorNetwork
tensornetwork/linalg/initialization.py
Python
apache-2.0
8,131
0.005042
# Copyright 2019 The TensorNetwork Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
except TypeError as e: error = "Input to zeros_like has invalid " \ "type causing error massage: \n" + str(e) raise TypeError(error) from e the_tensor = initialize_tensor("zeros", tensor.shape, backend=backend, dtype=dtype) return the_tensor ...
Tensor: """Return a Tensor of shape `shape` of Gaussian random floats. The Tensor has one dangling Edge per dimension. Args: shape : Shape of the array. dtype, optional: dtype of array (default np.float64). seed, optional: Seed for the RNG. backend (optional): The backend or its name. Returns: ...
patrebert/pynet_cert
class2/walk2.py
Python
apache-2.0
1,368
0.001462
#!/usr/bin/env python """ Demonstrate use of pysnmp walks """ import sys import re from pysnmp.entity.rfc3413.oneliner import cmdgen cmdGen = cmdgen.CommandGenerator() devip = sys.argv.pop(1) errorIn
dication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd( cmdgen.CommunityData('server', 'galileo', 1), cmdgen.UdpTransportTarget((devip, 161)), cmdgen.MibVariable('IF-MIB', '').loadMibs(), lexicographicMode=True, maxRows=150 ) if errorIndication: print errorIndication else: if errorSta...
][int(errorIndex)-1] or '?' ) else: ifdescr = [] inoctets = [] outoctets = [] for varBindTableRow in varBindTable: for name, val in varBindTableRow: np = name.prettyPrint() vp = val.prettyPrint() if re.search(r"...
karlfloersch/pyethereum
ethereum/todo_tests/test_pruning_trie.py
Python
mit
13,719
0.000146
import ethereum.pruning_trie as pruning_trie from ethereum.db import EphemDB from ethereum.refcount_db import RefcountDB import rlp import ethereum.utils as utils from ethereum.utils import to_string import sys import itertools import ethereum.testutils as testutils from ethereum.testutils import fixture_to_bytes impor...
count_changes(i + NODES) db.cleanup(i + NODES) for i in range(NODES): t.delete(to_string(i)) db.commit_refcount_changes(i + NODES * 2) db.cleanup(i + NODES * 2) for i in range(NODES // 4): db.cleanup(i + NODES * 3) assert len(t.t
o_dict()) == 0 assert len(db.kv) == 0 def test_clear(): db = RefcountDB(EphemDB()) NODES = 60 t = pruning_trie.Trie(db) db.ttl = 0 for i in range(NODES): t.update(to_string(i), to_string(i)) db.commit_refcount_changes(i) db.cleanup(i) t.clear_all() db.commit_ref...
fairdk/lcrs-embedded
lcrs_embedded/jobs.py
Python
gpl-3.0
1,345
0
""" Here we put all the classes that run specific jobs """ import logging import time from . import models from .system.dmesg import dmesg_analysis from .system.lspci import lspci_analysis from .system.smartctl import smartinfo from .utils.job import Job logger = logging.getLogger(__name__) class ScanJob(Job): ...
t = sum(x[1] for x in job_progress_map) total_progress_weight = float(total_progress_weight) for job_func, progress in job_progress_map: job_func(scan_results) self.progress += progre
ss / total_progress_weight class FailJob(Job): """ Purpose: testing """ def job(self): raise Exception("I'm a failing thread, I died.") class WaitJob(Job): """ Purpose: testing """ def job(self, **kwargs): logger.debug(kwargs) wait_time = self.kwargs['wait_t...
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_11_01/aio/operations/_express_route_links_operations.py
Python
mit
8,718
0.004474
# 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 may ...
ated. # -
------------------------------------------------------------------------- from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, Resou...
rahulunair/nova
nova/tests/functional/api_sample_tests/test_aggregates.py
Python
apache-2.0
5,569
0.00018
# Copyright 2012 Nebula, Inc. # Copyright 2013 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required...
compute.host) def test_remove_host(self): self.test_add_host() subs = { "host_name": self.compute.host, } response = self._do
_post('os-aggregates/1/action', 'aggregate-remove-host-post-req', subs) subs.update(self.extra_subs) self._verify_response('aggregates-remove-host-post-resp', subs, response, 200) def test_update_aggregate(self): aggregate_id = ...
apdjustino/urbansim
urbansim/urbanchoice/tests/test_interaction.py
Python
bsd-3-clause
1,734
0
import numpy as np import numpy.testing as npt import pandas as pd import pytest from .. import interaction as inter @pytest.fixture def choosers(): return pd.DataFrame( {'var1': range(5, 10), 'thing_id': ['a', 'c', 'e', 'g', 'i']}) @pytest.fixture def alternatives(): return pd.DataFrame( ...
'var1'] npt.assert_array_equal( merged['var1'].values, choosers['var1'].values.repeat(len(alternatives))) npt.assert_array_equal( merged['thing_id'].values, choosers['thing_id'].values.repeat(len(alternatives))) npt.assert_array_equal( m
erged['join_index'], choosers.index.values.repeat(len(alternatives))) npt.assert_array_equal( merged['var2'].values, np.tile(alternatives['var2'].values, len(choosers))) npt.assert_array_equal( merged['var3'].values, np.tile(alternatives['var3'].values, len(choosers)))
metagriffin/pysyncml
pysyncml/change/__init__.py
Python
gpl-3.0
1,255
0.003984
# -*- coding: utf-8 -*- #------------------------------------------------------------------------------ # file: $Id$ # auth: metagriffin <mg.github@uberdev.org> # date: 2012/04/20 # copy: (C) Copyright 2012-EOT metagriffin -- see LICENSE.txt #----------------------------------------
-------------------------------------- # This software is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as # publish
ed by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This software 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...
Southpaw-TACTIC/TACTIC
3rd_party/python2/site-packages/cherrypy/test/helper.py
Python
epl-1.0
17,316
0
"""A library of helper functions for the CherryPy test suite.""" import datetime import io import logging import os import re import subprocess import sys import time import unittest import warnings import portend import pytest import six from cheroot.test import webtest import cherrypy from cherrypy._cpcompat impo...
use a relative import # would stick a second instance of webtest in sys.modules, # an
d we wouldn't be able to globally override the port anymore. if supervisor.scheme == 'https': webtest.WebCase.HTTP_CONN = HTTPSConnection return baseconf @classmethod def setup_class(cls): '' # Creates a server conf = { 'scheme': 'http', ...
hersonls/django-queryset-join
src/querysetjoin/tests/tests.py
Python
bsd-3-clause
1,232
0.006494
from django.conf import settings from django.test im
port TestCase from querysetjoin import QuerySetJoin from querysetjoin.tests.models import ModelOne, ModelTwo def test_print(p): print "*" * 70 print p print "*" * 70 class QuerySetJoinTests(TestCase): fixtures = ['querysetjoin-test-data.json'] def testJoin(self): qs1 = ModelOne.objects.al...
test_print("Counting of all itens of the joined querysets:") print qs_join.count() # Printing the attributes in common test_print("Printing attributes in common of the joined QuerySets:") for qs in qs_join: print qs.name # Ordering objects by attrib...
reverieinc/RevCode
revcode/mappings/kannada_to_rev.py
Python
gpl-3.0
1,908
0
# -*- coding: utf-8 -*- offset = 0x0C80 rev_code = { 0xC81: "M", # - 0xC82: "x", # ಂ 0xC83: "X", # ಃ 0xC85: "a", # ಅ 0xC86: "A", # ಆ 0xC87: "i", # ಇ 0xC8
8: "I", # ಈ 0xC89: "u", # ಉ 0xC8A: "U", # ಊ 0xC8B: "WR", # ಋ 0xC8C: "", # - 0xC8D: "WA", # - 0xC8E: "e", # ಎ 0xC8F: "E", # ಏ 0xC90: "YE", # ಐ 0xC91: "WO", # - 0xC92: "o", # ಒ 0xC93: "O", # ಓ 0xC94: "YO", # ಔ 0xC95: "k", # ಕ 0xC96: "K
", # ಖ 0xC97: "g", # ಗ 0xC98: "G", # ಘ 0xC99: "z", # ಙ 0xC9A: "c", # ಚ 0xC9B: "C", # ಛ 0xC9C: "j", # ಜ 0xC9D: "J", # ಝ 0xC9E: "Z", # ಞ 0xC9F: "T", # ಟ 0xCA0: "HT", # ಠ 0xCA1: "D", # ಡ 0xCA2: "HD", # ಢ 0xCA3: "N", # ಣ 0xCA4: "t", # ತ 0xCA5: "Ht",...
68foxboris/enigma2-openpli-vuplus
lib/python/Components/MovieList.py
Python
gpl-2.0
31,608
0.032713
from GUIComponent import GUIComponent from Tools.FuzzyDate import FuzzyTime from ServiceReference import ServiceReference from Components.MultiContent import MultiContentEntryText, MultiContentEntryPixmapAlphaTest, MultiContentEntryProgress from Components.config import config import os import struct import random from...
ne: self.invalidateItem(index) self.l.invalidateEntry(index) self._playInBackground = value playInBackground = property(get_playInBackground, set_playInBackground) def updateRecordings(self
, timer=None): if timer is not None: if timer.justplay: return result = {} for timer in NavigationInstance.instance.RecordTimer.timer_list: if timer.isRunning() and not timer.justplay: result[os.path.split(timer.Filename)[1]+'.ts'] = timer if self.runningTimers == result: return self.runningT...
plotly/python-api
packages/python/plotly/plotly/validators/pie/hoverlabel/_align.py
Python
mit
566
0.001767
import _plotly_utils.basevalidat
ors class AlignValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__(self, plotly_name="align", parent_name="pie.hoverlabel", **kwargs): super(AlignValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, array_ok=kwargs.pop("arra...
one"), role=kwargs.pop("role", "style"), values=kwargs.pop("values", ["left", "right", "auto"]), **kwargs )
mequanta/z-runner
examples/quanto/multiple_security_example.py
Python
agpl-3.0
2,391
0.002928
# This example runs the same momentum play as the first sample # (https://www.quantopian.com/help#sample-basic), but this time it uses more # securities during the backtest. # Important note: All securities in an algorithm must be traded for the # entire length of the backtest. For instance, if you try to backtest bo...
ibraries. import datetime import pytz def initialize(context): # Here we initialize each stock. # By calling symbols(
'AAPL', 'IBM', 'CSCO') we're storing the Security objects. context.stocks = symbols('AAPL', 'IBM', 'CSCO') context.vwap = {} context.price = {} # Setting our maximum position size, like previous example context.max_notional = 1000000.1 context.min_notional = -1000000.0 # Initializing the t...
PolarCommunity/SimpleInventoryControl
egresos/admin.py
Python
gpl-3.0
461
0.013015
from django.contrib import admin from .models
import * # Register your models here. clas
s DetalleEgresaAdmin(admin.TabularInline): model = DetalleEgreso class EgresoAdmin(admin.ModelAdmin): inlines = [ DetalleEgresaAdmin, ] list_display = ['fecha','descripcion','user'] ordering = ['user'] list_filter = ('user','fecha') date_hierarchy = 'fecha' search_fields = ['des...
meine-stadt-transparent/meine-stadt-transparent
mainapp/migrations/0017_merge_20181221_1508.py
Python
mit
272
0
# Generated by Django 2.1.4 on 2018-12-21 14:08 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('mainapp', '0016_auto_20181
202_2205'), ('mainapp', '0016_auto_20181221_1432'),
] operations = [ ]
jessicalucci/NovaOrc
nova/tests/api/openstack/compute/contrib/test_admin_actions_with_cells.py
Python
apache-2.0
3,528
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 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.a...
ance(INSTANCE_IDS.get(instance_uuid), name=values.get('display_name')) return (inst, inst) def fake_cast_to_cells(context, instance, method, *args, **kwargs): """ Makes sure that the cells receive the cast to update the ce
ll state """ self.cells_received_kwargs.update(kwargs) self.admin_api = admin_actions.AdminActionsController() self.admin_api.compute_api = compute_cells_api.ComputeCellsAPI() self.stubs.Set(self.admin_api.compute_api, '_cell_read_only', _fake_cell...
SelfKit/SelfKit
web/server.py
Python
gpl-3.0
2,036
0.007367
import BaseHTTPServer, SimpleHTTPServer import subprocess, shlex import ssl import time import os from optparse import OptionParser port = 4443 execfile('./variables.py') parser = OptionParser() parser.add_option('-p', "--port", dest='port', help='Run HTTPS server on PORT', metavar='PORT') (options, args) = parser....
print './server.pem does not exist. Creating...' command = 'openssl req -new -x509 -keyout ./server.pem -out ./server.pem -days 3650 -nodes -subj "/C=/ST=/L=/O=/CN=localhost"' print (command) args = shlex.split(command) p = subprocess.call(args) print ('Running web server...') class SKWebHandler(...
if os.path.exists('content' + self.path): f = open('content' + self.path) page = f.read() page = replaceVariables(page) self.send_response(200) self.send_header('Content-Type', 'text/html') self.send_header('X-SelfKit-...
aibon/django-stripe-payments
payments/settings.py
Python
mit
1,269
0.000788
import six from django.conf import settings from .utils import load_path_attr STRIPE_PUBLIC_KEY = settings.STRIPE_PUBLIC_KEY INVOICE_FROM_EMAIL = getattr( settings, "PAYMENTS_INVOICE_FROM_EMAIL", "billing@example.com" ) PAYMENTS_PLANS = getattr(settings, "PAYMENTS_PLANS", {}) PLAN_CHOICES = [ (plan, ...
six.string_types): PLAN_QUANTITY_CALLBACK = load_path_attr(PLAN_QUANTITY_CALLBACK) SEND_EMAIL_RECEIPTS = getattr(settings, "SEND_EMAIL_RECEIPTS", True) TAX = getattr( settings, "PAYMENTS_TAX", None ) def plan_from_stripe_id(stripe_id): for key in PAYMENTS_PLANS.keys(): if PAYMENTS_PLANS[k...
"stripe_plan_id") == stripe_id: return key
petewarden/tensorflow
tensorflow/compiler/tests/stateful_random_ops_test.py
Python
apache-2.0
17,958
0.010246
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
self.skipTest("The expected values in this test is inconsistent with " "CPU/GPU. testXLAEqualsCPU has the correct checks of the " "new states for the new version.") with ops.device(xla_device_name()): counter = 57 key = 0x1234 size = 46 state =
[counter, key] gen = random.Generator(state=state, alg=random.RNG_ALG_THREEFRY) gen.uniform_full_int(shape=(size,), dtype=dtypes.uint32) self.assertAllEqual([counter+(size+1)//2, key], gen.state.read_value()) gen.reset(state) gen.uniform_full_int(shape=(size,), dtype=dtypes.uint64) ...
oberstet/autobahn-python
examples/twisted/wamp/rpc/progress/backend.py
Python
mit
2,522
0.000793
############################################################################### # # The MIT License (MIT) # # Copyright (c) Crossbar.io Technologies GmbH # # 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 ...
thout 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 Software is # furnished to do so, subject to the following co
nditions: # # The above copyright notice and this permission notice shall be included in # all copies 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 PARTICU...
showyou/anzu
pickup_reply/model.py
Python
mit
3,074
0.01808
#!/usr/bin/env python # -*- coding: utf-8 -*- # マルコフテーブル等定義 import sqlalchemy from sqlalchemy.orm import scoped_session, sessionmaker, mapper from sqlalchemy import MetaData from sqlalchemy import Column, MetaData, Table, types from datetime import datetime class Status(object): pass class Reply(object): pas...
', types.BigInteger(20), primary_key=True), Column('is_reply_analyze', types.SmallInteger, default=False), mysql_engine = 'InnoDB', mysql_charset = 'utf8'
) """ status_reply = Table("status_reply", metadata, Column('id', types.Integer, primary_key=True), Column('status_id', types.Integer, ForeignKey('twit.id')), Column('reply_id', types.Integer, ForeignKey('twit2.id')), mysql_engine = 'MyISA...
ojii/readthedocs.org
readthedocs/doc_builder/backends/sphinx.py
Python
mit
9,006
0.002998
import os import shutil import codecs import re import logging import zipfile from django.template import Template, Context from django.contrib.auth.models import SiteProfileNotAvailable from django.core.exceptions import ObjectDoesNotExist from django.conf import settings from doc_builder.base import BaseBuilder, re...
tic' % TEMPLATE_DIR def _get_conf_py_path(version): conf_py_path = version.project.conf_file(version.slug) conf_py_path = conf_py_path.replace(version.project.checkout_path(version.slug), '') return conf_p
y_path.replace('conf.py', '') def _get_github_username_repo(version): REGEX1 = re.compile('github.com/(.+)/(.+)(?:\.git){1}') REGEX2 = re.compile('github.com/(.+)/(.+)') REGEX3 = re.compile('github.com:(.+)/(.+).git') repo_url = version.project.repo if 'github' in repo_url: try: ...
shirtsgroup/pygo
analysis/MBAR_all_umbrella.py
Python
gpl-2.0
4,994
0.018222
#!/usr/bin/python2.4 import numpy from math import * import pymbar import timeseries import commands import os import pdb #import matplotlib.pyplot as plt import optparse import wham import cPickle import MBAR_pmfQz import MBAR_4_state_pmf def parse_args(): parser = optparse.OptionParser(description='Calculates t...
th skip %i' %(options.N_max,options.skip) # set constants kB = 0.00831447/4.184 nbins_per = 25 spring_constant = 1 # get temperature and distance states T = numpy.loadtxt(options.tfile) # T = numpy.array([305.,320.,330.,340.]) # smaller subset for testing purposes beta_k = 1 / (kB * T...
rint 'temperature states are\n', T Z = numpy.arange(9,31.5,1.5) Z = numpy.concatenate((Z,numpy.array([33,36,39,42,45,48]))) # Z = numpy.array([15,16.5,18]) # smaller subset for testing purposes print 'distance states are\n', Z K = len(T)*len(Z) # read in data U_kn, Q_kn, z_kn, N_max = MBAR_...
Lukasa/spdypy
spdypy/stream.py
Python
mit
4,701
0
# -*- coding: utf-8 -*- """ spdypy.stream ~~~~~~~~~~~~~ Abstractions for SPDY streams. """ import collections from .frame import (SYNStreamFrame, SYNReplyFrame, RSTStreamFrame, DataFrame, HeadersFrame, WindowUpdateFrame, FLAG_FIN) class Stream(object): """ A SPDY connection is made up of ...
queued_frame.flags.discard(FLAG_FIN) if last: frame.flags.add(FLAG_FIN) frame.data = data self._queued_frames.append(frame) def send_outstanding(self, connection): """ Sends any outstanding frames on a given connection. :param connection: The c...
""" frame = self._next_frame() while frame is not None: data = frame.to_bytes(self._compressor) connection.send(data) frame = self._next_frame() def process_frame(self, frame): """ Given a SPDY frame, handle it in the context of a given stream. ...
mitchellzen/pops
satchmo/apps/satchmo_ext/newsletter/mailman.py
Python
bsd-3-clause
5,119
0.0084
"""A Mailman newsletter subscription interface. To use this plugin, enable the newsletter module and set the newsletter module and name settings in the admin settings page. """ from django.utils.translation import ugettext as _ from Mailman import MailList, Errors from models import Subscription from livesettings imp...
not listname: listname = config_value('NEWSLETTER', 'NEWSLETTER_NAME') if listname == "": log.warn("NEWSLETTER_NAME not set in store settings") raise NameError('No NEWSLET
TER_NAME in settings') return MailList.MailList(listname, lock=0), listname except Errors.MMUnknownListError: print >> sys.stderr, "Can't find the MailMan newsletter: %s" % listname raise NameError('No such newsletter, "%s"' % listname)
ioram7/keystone-federado-pgid2013
keystone/common/sql/migrate_repo/versions/016_normalize_domain_ids.py
Python
apache-2.0
19,792
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 OpenStack LLC # Copyright 2013 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/...
' ':p
assword, :enabled);', {'id': user.id, 'name': user.name, 'extra': user.extra, 'expires': user.expires, 'password': user.password, 'enabled': user.enabled}) # Now swit...
psbanka/yamzam
server/main/serializers.py
Python
gpl-3.0
603
0
__author__ = 'bankap' from django.contrib.auth.models import User from models import UserProfile, EmailSummary from rest_framework.serializers import ModelSerializer class EmailSummarySerializer(ModelSerializer): """ A serializer for EmailSummary. """ class Meta(object): model = EmailSummar...
odelSerializer): """ A serializer for Users. """ class Meta(object): model = User class UserProfileSerializer(ModelSerializer): """ A serializer for UserProfiles. """ class Meta(obje
ct): model = UserProfile
shaunokeefe/hoponit
hoponit/sightings/models.py
Python
mit
583
0.005146
from django.db import models from django.contrib.auth import models as auth_models #TODO (shauno): Change this to use explicit imports from venues import models as venue_models # Create your models here. class Sighting(models.Model): when = models.DateTimeField() venue = models.ForeignKey(venue_models.Venue)...
s User(models.Model): name = models.CharField(max_length="64") url = models.URLField()
django_user = models.ForeignKey(auth_models.User, blank=True, null=True)
homeworkprod/byceps
tests/integration/blueprints/admin/ticketing/conftest.py
Python
bsd-3-clause
1,795
0
""" :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ import pytest from byceps.services.ticketing import ( category_service, ticket_bundle_service as bundle_service, ticket_creation_service as creation_service, ticket_service, ) from tests.helpers ...
tegory, ticket_owner): ticket = creation_service.create_ticket( category.party_id, category.id, ticket_owner.id ) ticket_id = ticket.id yield ticket ticket_service.delete_ticket(ticket_id) @pytest.fixture(scope='package') def bundle(category, ticket_owner): quantity = 4 bundle = ...
y, ticket_owner.id ) tickets = bundle.tickets yield bundle for ticket in tickets: ticket_service.delete_ticket(ticket.id) bundle_service.delete_bundle(bundle.id)
jestapinski/oppia
core/domain/classifier_domain.py
Python
apache-2.0
3,445
0.00029
# Copyright 2016 The Oppia 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 ...
esentation of Classifier domain object. """ r
eturn { 'classifier_id': self.id, 'exp_id': self.exp_id, 'exp_version_when_created': self.exp_version_when_created, 'state_name': self.state_name, 'algorithm_id': self.algorithm_id, 'cached_classifier_data': self.cached_classifier_data, ...
mmanto/sstuv
comun/models.py
Python
gpl-3.0
1,062
0.013183
from django.db import models class Partido(models.Model): # inscripcion = models.CharField(max_length=200) codigo= models.IntegerField(default=0) nombre = models.CharField(max_length=200) codcas=models.CharField(max_length=20, default=0) def __str__(self): return self.nombre cla...
"NOMBRE":"Almirant
e Brown", # "NOMENCLA":"003"
norayr/unisubs
apps/videos/migrations/0112_auto__add_field_subtitleversion_result_of_rollback.py
Python
agpl-3.0
17,922
0.008593
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'SubtitleVersion.result_of_rollback' db.add_column('videos_subtitleversion', 'result_of...
b.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '...
lds.TextField', [], {'max_length': '3000'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'content_type_set_for_comment'", 'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'obj...
proversity-org/edx-platform
common/djangoapps/entitlements/tests/test_models.py
Python
agpl-3.0
9,335
0.004178
"""Test Entitlements models""" import unittest from datetime import timedelta from django.conf import settings from django.test import TestCase from django.utils.timezone import now from lms.djangoapps.certificates.models import CertificateStatuses # pylint: disable=import-error from lms.djangoapps.certificates.api...
ys=70) entitlement = CourseEntitlementFactory.create(created=past_datetime) assert entitlement.is_entitlement_refundable() is False entitlement = CourseEntitlement
Factory.create(enrollment_course_run=self.enrollment) # Create a date 20 days in the past (less than the policy refund expire period of 60 days) # but more than the policy regain period of 14 days and also the course start past_datetime = now() - timedelta(days=20) entitlement.created = ...
tapomayukh/projects_in_python
classification/Classification_with_kNN/Single_Contact_Classification/Scaled_Features/best_kNN_PCA/2_categories/test11_cross_validate_categories_mov_fixed_1200ms_scaled_method_iii.py
Python
mit
5,012
0.02075
# Principal Component Analysis Code : from numpy import mean,cov,double,cumsum,dot,linalg,array,rank,size,flipud from pylab import * import numpy as np import matplotlib.pyplot as pp #from enthought.mayavi import mlab import scipy.ndimage as ni import roslib; roslib.load_manifest('sandbox_tapo_darpa_m3') import ro...
nd the mean return vec,val,mean_X, M, Mcov def my_mvpa
(Y,num2): #Using PYMVPA PCA_data = np.array(Y) PCA_label_1 = ['Fixed']*35 + ['Movable']*35 + ['Fixed']*35 + ['Movable']*35 PCA_chunk_1 = ['Styrofoam-Fixed']*5 + ['Books-Fixed']*5 + ['Bucket-Fixed']*5 + ['Bowl-Fixed']*5 + ['Can-Fixed']*5 + ['Box-Fixed']*5 + ['Pipe-Fixed']*5 + ['Styrofoam-Movable']*5 + [...
mcmartins/broccoli
broccoli/test/parse/test.py
Python
apache-2.0
711
0.004219
import unittest import broccoli.parser class BroccoliTest(unittest.TestCase): def test_job_creation(self): config = bro
ccoli.parser.parse('input.json') job = broccoli.job.Job(config) self.assertEqual(job.name, 'Job1') self.assertEqual(job.description, 'Job1 Desc
ription') self.assertIsNotNone(job.get_tasks()) self.assertEqual(len(job.get_tasks()), 2) task = job.get_tasks().get(0) self.assertEqual(task.name, 'Task1') self.assertEqual(task.description, 'Task1 Description') self.assertIsNotNone(task.get_sub_tasks()) self.ass...
RomainBrault/scikit-learn
sklearn/gaussian_process/gpc.py
Python
bsd-3-clause
31,963
0
"""Gaussian processes classification.""" # Authors: Jan Hendrik Metzen <jhm@informatik.uni-bremen.de> # # License: BSD 3 clause import warnings from operator import itemgetter import numpy as np from scipy.linalg import cholesky, cho_solve, solve from scipy.optimize import fmin_l_bfgs_b from scipy.special import erf...
of the optimizer for finding the kernel's parameters which maximize the log-mar
ginal likelihood. The first run of the optimizer is performed from the kernel's initial parameters, the remaining ones (if any) from thetas sampled log-uniform randomly from the space of allowed theta-values. If greater than 0, all bounds must be finite. Note that n_restarts_optimizer=0 ...
QuartetoFantastico/projetoPokemon
cliente.py
Python
gpl-2.0
6,564
0.03185
import xml.etree.ElementTree as ET import requests from flask import Flask import batalha import pokemon import ataque class Cliente: def __init__(self, execute = False, ip = '127.0.0.1', port = 5000, npc = False): self.ip = ip self.port = port self.npc = npc if (execute): self.iniciaBatalha() def writ...
quests.post('http://{}:{}/battle/'.format(self.ip, self.port), data = xml).text except requests.exceptions.ConnectionError: print("Não foi possível conectar ao servidor.") return None pkmn2 = pokemon.lePokemonXML(1, self.battle_state) s
elf.batalha = batalha.Batalha([pkmn, pkmn2]) if (self.npc): self.batalha.pkmn[0].npc = True print("Eu sou um NPC") self.batalha.turno = 0 self.batalha.display.showPokemon(self.batalha.pkmn[0]) self.batalha.display.showPokemon(self.batalha.pkmn[1]) return self.atualizaBatalha() def atualizaBatalha(sel...
TomAugspurger/pandas
pandas/core/indexes/range.py
Python
bsd-3-clause
27,484
0.000509
from datetime import timedelta import operator from sys import getsizeof from typing import Any, Optional import warnings import numpy as np from pandas._libs import index as libindex from pandas._libs.lib import no_default from pandas._typing import Label import pandas.compat as compat from pandas.compat.numpy impor...
------------------------------------ #
Rendering Methods def _format_attrs(self): """ Return a list of tuples of the (attr, formatted_value) """ attrs = self._get_data_as_items() if self.name is not None: attrs.append(("name", ibase.default_pprint(self.name))) return attrs def _format_da...
tum-i22/indistinguishability-obfuscation
obfusc8/test/__init__.py
Python
apache-2.0
100
0.02
__all__
= ['all_test', 'test_blocks', 'test_bp', 'test_circuit', 'test_mjp', 'test_obf', 'tes
t_rbp']
yashp241195/graphs
makeGraph.py
Python
mit
1,931
0.026929
# Graph - Data Structure ''' class "Edge" contains information about Source Node ID Destination Node ID Weight between Source and Destination ''' class Edge(object): def __init__(self,From,To,Weight): self.From = From self.To = To self.Weight = Weight ''' ...
self.VertexList = [] for i in range (0,self.size): self.VertexList.append(Vertex(i)) def addEdgedir(self,
From,To,Weight): self.VertexList[From].AdjecencyList.append(Edge(From,To,Weight)) def addEdgeUndir(self,From,To,Weight): self.addEdgedir(From,To,Weight) self.addEdgedir(To,From,Weight) # Defining the Graph size = 5 g = Graph(size) g.addEdgeUndir(1,2,5) g.addEdgedir(3,4,6) # Pr...
toptotem/randinterq
randinterq.py
Python
mit
7,003
0.003855
import os import sys import errno import random import glob import tkinter from tkinter import filedialog import pyautogui import time import configparser root = tkinter.Tk() root.withdraw() #Setting current Dir dir_path = os.path.dirname(os.path.realpath(__file__)) #Move mouse to upper left screen to kill in case ...
s") time.sleep(5) exit() if len(sys.argv) == 1: print("\nWelcome to the Apollo.rip Interviewer Companion app!") choosedir = input("\nWould you like to change the location of the question folders? (y/n): ") if choosedir == 'y': qpath = filedialog.askdirectory(initialdir='.') makedir = in...
dir == 'y': os.chdir(qpath) createdir() windows = input("Are you running windows and using autohotkey? (y/n): ") if windows == 'y': ahkchangedir = input("Do you wish to set/change where the ahk script is saved? (y/n): ") if ahkchangedir == 'y': ahkpath = filedialog.as...
sawyerhanlon/Calculate-Pi
calculatepi.py
Python
mit
998
0.006042
""" calculatepi.py Author: Sawyer Hanlon Credit: Mr Dennison Assignment: Write and submit a Python program that computes an approximate value of π by calculating the following sum: (see: https://github.com/HHS-IntroProgramming/Calculate-Pi/blob/master/README.md) This sum approaches the true value of π as n approache...
ld I use? 100 How many decimal places should I use in the result? 7 The approximate value of pi is 3.1315929 Note: remember that the printed value of pi will be an estimate! """ n = int(input("I will estimate pi. How many terms should I use? ")) decimals = int
(input("How many decimal places should I use in the result? ")) pi = 4*sum([((-1.0)**k)/(2*k+1) for k in range(0,n)]) print("The approximate value of pi is {0:.{1}f}".format(pi, decimals))
mskovacic/Projekti
raspberrypi/isprobavanje/pyqt5/Toggle_button.py
Python
mit
1,988
0.0166
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ ZetCode PyQt5 tutorial In this example, we create three toggle buttons. They will control the background colour of a QFrame. author: Jan Bodnar website: zetcode.com last edited: January 2015 """ import sys from PyQt5.QtWidgets import (QWidget, QPushButton, QF...
(self.setColor) blueb = QPushButton('Blue', self) blueb.setCheckable(True) blueb.move(10, 110) blueb.clicked[bool].connect(self.setColor) self.square = QFrame(self) self.square.setGeometry(150, 20, 100, 100) self.square.setStyleSheet("QWidget { background-co
lor: %s }" % self.col.name()) self.setGeometry(300, 300, 280, 170) self.setWindowTitle('Toggle button') self.show() def setColor(self, pressed): source = self.sender() if pressed: val = 255 else: v...
lpsinger/astropy
astropy/io/fits/tests/test_core.py
Python
bsd-3-clause
51,812
0.000347
# Licensed under a 3-clause BSD style license - see PYFITS.rst import gzip import io import mmap import errno import os import pathlib import urllib.request import zipfile from unittest.mock import patch import pytest import numpy as np from . import FitsTestCase from astropy.io.fits.convenience import _getext from...
header.append(card) header['BITPIX'] = 32 assert 'BITPIX' in header assert header['BITPIX'] == 32 assert header.cards[0].keyword == 'BITPIX' assert header.cards[0].val
ue == 32 assert header.cards[0].comment == comment def test_uint(self): filename = self.data('o4sp040b0_raw.fits') with fits.open(filename, uint=False) as hdulist_f: with fits.open(filename, uint=True) as hdulist_i: assert hdulist_f[1].data.dtype == np.float32 ...
mbaukes/ncclient
ncclient/operations/__init__.py
Python
apache-2.0
1,443
0.000693
# Copyright 2009 Shikhar Bhushan # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
hine, RebootMachine __all__ = [ 'RPC', 'R
PCReply', 'RPCError', 'RaiseMode', 'Get', 'GetConfig', 'GetReply', 'EditConfig', 'CopyConfig', 'Validate', 'Commit', 'DiscardChanges', 'DeleteConfig', 'Lock', 'Unlock', 'PoweroffMachine', 'RebootMachine', 'LockContext', 'CloseSession', 'KillSession...
robhowley/nhlscrapi
setup.py
Python
apache-2.0
1,144
0.011364
from distutils.core import setup from setuptools import find_packages import nhlscrapi setup( name="nhlscrapi", version=nhlscrapi.__version__, description='NHL Scrapr API for Python', long_description=open('README.rst').read(), author='Rob Howley', author_email='howley.robert@gmail.com', ...
packages=find_packages(), include_package_data=True, scripts=['bin/gamedata.py'], license="Apache Software License version 2.0", platforms='any', zip_safe=False, keywords='nhlscrapi', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience...
ramming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Operating System :: OS Independent', 'Topic :: Software Development :: Libraries :: Python Modules', ], test_suite='tests', # Dependent packages (distributions) install_...
xdevelsistemas/taiga-back-community
taiga/timeline/migrations/0005_auto_20160706_0723.py
Python
agpl-3.0
522
0.001916
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-07-06 07:23 from __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [
('timeline', '0004_auto_20150603_1312'), ] operations = [ migrations.AlterField( model_name='timeline', name='created', field=models.DateTimeField(db_index=True, defaul
t=django.utils.timezone.now), ), ]
raf-programmer/django-biblioteka
rental/views.py
Python
mit
290
0.003448
from django.shortcuts import render from django.views.generic.edit import
CreateView, UpdateView, DeleteView from
django.core.urlresolvers import reverse_lazy from .models import Rental class BookRentView(CreateView): model = Rental fields = ['who', 'what'] success_url = '/'
cryvate/project-euler
project_euler/library/number_theory/test_continued_fractions.py
Python
mit
2,486
0
from fractions import Fraction import pytest from typing import List, Tuple from .continued_fractions import convergent_sequence, \ continued_fraction_sqrt, \ convergents_sqrt CONVERGENTS = [ ( [0, 1, 5, 2, 2], [Fraction(0, 1), ...
, [4], ) ), ( 6, ( [2], [2, 4], ) ), ( 7, ( [2], [1, 1, 1, 4], ) ), ( 8, ( [2], [1, 4], ) ), ( 10, ( ...
( [3], [3, 6], ) ), ( 12, ( [3], [2, 6], ) ), ( 13, ( [3], [1, 1, 1, 1, 6], ) ), ] CONVERGENTS_SQRT = [ ( 2, [ Fraction(1, 1), ...
RobSpectre/New-York-Times-Conference-Room
app.py
Python
mit
2,630
0.003802
import os from flask import Flask from twilio import twiml import requests # Declare and configure application app = Flask(__name__, static_url_path='/static') app.config.from_pyfile('local_settings.py') app.config['API_PATH'] = \ "http://api.nytimes.com/svc/mostpopular/v2/"\ "mostviewed/all-sections/1.jso...
['NYTIMES_API_KEY']: api_request = requests.get("%s%s" % (app.config['API_PATH'], app.config['NYTIMES_API_KEY'])) if api_request.status_code == 200: json_response = api_request.json() if json_response: resp
onse.say("While you wait for your conference to connect," \ " here are today's headlines from the New York Times.", voice="alice") for result in json_response['results']: response.say(result['abstract'], voice='alice') ...
North-Empire-Codes/Online_Robot_Project
ORP-FMS/src/SerialStream.py
Python
gpl-2.0
2,106
0.022317
#!/usr/bin/python #Imports Serial into Python import serial #Function to initialize stream def initializeStream(portPath, frequency): #Makes variable stream global global stream print "Initializing stream with the port path '%s' with the frequency of %d..." %(portPath, frequency) strea...
else: print "Stream already opened" #Function to close stream def closeStream(): #Checks if stream is open if(stream.isOpen()): print "Closing stream..." stream.close() #Checks if stream closed if(not stream.isOpen()):...
print "Error could not close stream" else: print "Stream already closed" #Function to send data def send(data): #Checks if stream is opened if(stream.isOpen()): #Writes data to the serial stream print "Sending %s over stream..." %(data) ...
jpedrorl/Robotics-AI
vrep/vrepConst.py
Python
mit
45,009
0.034749
# This file is part of the REMOTE API # # Copyright 2006-2016 Coppelia Robotics GmbH. All rights reserved. # marc@coppeliarobotics.com # www.coppeliarobotics.com # # The REMOTE API is licensed under the terms of GNU GPL: # # ------------------------------------------------------------------- # The REMOTE A...
tribute 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. # # THE REMOTE API IS DISTRIBUTED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED # WARRANTY. THE USER WILL USE IT AT H...
RISK. THE ORIGINAL # AUTHORS AND COPPELIA ROBOTICS GMBH WILL NOT BE LIABLE FOR DATA LOSS, # DAMAGES, LOSS OF PROFITS OR ANY OTHER KIND OF LOSS WHILE USING OR # MISUSING THIS SOFTWARE. # # See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License...
jokull/kraftwerk
setup.py
Python
mit
920
0.038168
# -*- coding: utf-8 -*- from __future__ import with_statemen
t import sys from setuptools import setup, find_packages from kraftwerk imp
ort __version__ requires = [ "apache-libcloud>=0.7.1", "Jinja2>=2.6", "PyYAML>=3.10", "virtualenv>=1.7", "certifi>=0.0.7", ] if sys.version_info < (2, 7): requires.append('argparse>=1.2.1') setup( name = 'kraftwerk', version = __version__, author = ...
default-to-open/rpmdeplint
rpmdeplint/repodata.py
Python
gpl-2.0
12,665
0.004185
# This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. from __future__ import absolute_import import os try: from os imp...
r', 'tmp') REPO_CACHE_NAME_PREFIX = 'rpmdeplint-' class PackageDownloadError(Exception): """ Raised if a package is being downloaded for further analysis but the download fails. """ pass class RepoDownloadError(Exception): """ Raised if an error occurs downl
oading repodata """ pass def get_yumvars(): # This is not all the yumvars, but hopefully good enough... try: import dnf.conf, dnf.rpm except ImportError: pass else: installroot = '' subst = dnf.conf.Conf().substitutions subst['releasever'] = dnf.rpm.dete...
stonebig/bokeh
bokeh/util/tests/test_string.py
Python
bsd-3-clause
5,444
0.007164
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2019, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #-------------------------------------------------------------------...
indent\n goes here" def test_with_n(self): assert bus.indent(self.TEXT, n=3) == " some text\n to indent\n goes here" def test_with_ch(self): assert bus.indent(self.TEXT, ch="-") == "--some text\n--to indent\n-- goes here" class Test_nice_join(object): def test_default(self):...
ce_join(["one", "two"]) == "one or two" assert bus.nice_join(["one", "two", "three"]) == "one, two or three" assert bus.nice_join(["one", "two", "three", "four"]) == "one, two, three or four" def test_string_conjunction(self): assert bus.nice_join(["one"], conjuction="and") == "one" ...
thanm/devel-scripts
showdevices.py
Python
apache-2.0
2,992
0.014037
#!/usr/bin/python3 """Run 'adb devices' and show results in friendly way. Runs 'adb devices' and integrates the results with environment variables DEVTAGS and ANDROID_SERIAL to show model numbers for connected devices. """ import getopt import os import re import sys import script_utils as u valid_dispositions = {...
S+)\s*$") devices_found = {} for line in lines[1:]: if rxd1.match(line) or rxd2.match(line): continue m = rx1.match(line) if not m: u.warning("unable to
match adb output line: %s" % line) continue ser = m.group(1) disp = m.group(2) if disp not in valid_dispositions: u.warning("unknown device disposition %s in adb " "output line: %s" % (disp, line)) sel = "" if ser == andser: sel = ">>" if ser not in serial_to_t...
ltworf/DiveShare
memcache.py
Python
gpl-3.0
1,138
0.000879
from google.appengine.api import memcache def get(key, value_function=None, time=0, auto=True): ''' Gets a value from memca
che. This function is a wrapper and is used to avoid the ugliness of having c = memcache.get(key) if c is not None: return c content = generate_dynamic_content() memcache.add(key, content) This function is used in the following way: def generator(): return 'dynamicall...
generated content' return memcache.get(key, generator) Simplyifying the code. key: well, it's self explainatory value_function: callable It must return a string that get() will return if the item is not present in cache. If auto is true, this string will be ad...
SEA000/uw-empathica
empathica/gluon/contrib/login_methods/dropbox_account.py
Python
mit
3,886
0.016469
#!/usr/bin/env python # coding: utf8 """ Dropbox Authentication for web2py Developed by Massimo Di Pierro (2011) Same License as Web2py License """ # mind here session is dropbox session, not current.session import os import re import urllib from dropbox import client, rest, session from gluon import * fro...
ccess_token = self.sess.obtain_access_token(token) except: access_token = None if access_token: user = Storage() self.client = client.DropboxClient(self.sess) data = self.client.account_info() display_name = data.get('displa...
lit(' ',1) user = dict(email = data.get('email',None), first_name = display_name[0], last_name = display_name[-1], registration_id = data.get('uid',None)) if not user['registration_id'] and self.on_login_failure: ...
eliran-stratoscale/inaugurator
inaugurator/grub.py
Python
apache-2.0
2,786
0.004666
import os import logging from inaugurator import sh USER_SETTINGS_DIR = "etc/default" USER_SETTINGS_FILENAME = "grub" def setSerialDevices(serialDevices, destination): destUserSettingsDir = os.path.join(destination, USER_SETTINGS_DIR) existingConfiguration = "" if os.path.isfile(destUserSettingsDir): ...
"modify GRUB2 settings.", dict(path=destUserSettingsDir)) return wasGrubCmdlineLinuxParameterWritten = False logging.info("Modifying GRUB2 user settings file...") with open(destUserSettingsFilename, "wb") as userSettingsFile: for line in existingConfiguration.splitlines():
line = line.strip() if line.startswith("GRUB_CMDLINE_LINUX="): wasGrubCmdlineLinuxParameterWritten = True maxSplit = 1 cmdline = line.split("=", maxSplit)[1].strip(" \"") argsWithoutConsole = [arg for arg in cmdline.split(" ") if not ...
aonotas/chainer
chainer/functions/math/basic_math.py
Python
mit
25,229
0
import numpy import chainer from chainer.backends import cuda from chainer import function_node import chainer.functions from chainer.functions.math import floor as _floor from chainer.functions.math import matmul as _matmul from chainer import utils from chainer.utils import type_check from chainer import variable ...
ef neg(self): # -x """Element-wise negation. Returns: ~chainer.Variable: Output variable. """ return Neg().apply((self,))[0] class Absolute(function_node.FunctionNode): @property def label(self): return '|_|' def check_type_forward(self, in_types): type_check.ex...
self.retain_inputs((0,)) return utils.force_array(abs(x[0])), def backward(self, indexes, grad_outputs): x = self.get_retained_inputs()[0] return AbsoluteGrad(x.data).apply(grad_outputs) class AbsoluteGrad(function_node.FunctionNode): def __init__(self, x): super(Abs...
renatopp/psi-robotics
psi/engine/camera.py
Python
mit
2,961
0.004728
# ============================================================================= # Federal University of Rio Grande do Sul (UFRGS) # Connectionist Artificial Intelligence Laboratory (LIAC) # Renato de Pontes Pereira - renato.ppontes@gmail.com # ============================================================================...
self.adjust(old, self._scale_rate) def reset_zoom(self): self.zoom = 1. self._scale_rate = 1/self.zoom def pan(self, delta): self.pos += delta def locate(self): glTranslatef(-s
elf.pos.x+self.half_size.x, -self.pos.y+self.half_size.y, 0) glScalef(self._scale_rate, self._scale_rate, 0) def on_window_resize(self, size): half_size = size/2. diff = self.half_size - half_size # print self.half_size, '=>', half_size, '=', diff self.half_size = half_size...
qisanstudio/qsapp-score
src/score/migration/versions/42f4a0f4afd9_create_table.py
Python
mit
3,217
0.008082
"""create_table Revision ID: 42f4a0f4afd9 Revises: None Create Date: 2014-11-15 16:53:22.716676 """ # revision identifiers, used by Alembic. revision = '42f4a0f4afd9' down_revision = None from alembic import op import sqlalchemy as sa #from guokr.platform.sqlalchemy.types import JSONType def upgrade(): op.crea...
ate_created', sa.DateTime(timezone=True), nullable=False, index=True, server_default=sa.func.current_timestamp())) op.create_table(u'round', sa.Column('id', sa.Integer(), nullable=False, primary_key=True), sa.Column('board_id', sa....
r(), sa.ForeignKey('board.id'), nullable=True), sa.Column('num', sa.Integer(), nullable=False), sa.Column('date_created', sa.DateTime(timezone=True), nullable=False, index=True, server_default=sa.func.curre...
studioml/studio
studio/git_util.py
Python
apache-2.0
2,399
0
import re import subprocess import os def get_git_info(path='.', abort_dirty=True): info = {} if not is_git(path): return None if abort_dirty and not is_clean(path): return None info['url'] = get_repo_url(path) info['commit'] = get_commit(path) return info def is_git(path='...
re.sub('(?<=://).*@', '', url.decode('utf-8')) return url def get_branch(path='.'): p = subprocess.Popen( ['git', 'rev-parse', '--abbrev-ref', 'HEAD'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=path) stdout, _ = p.communicate() if p.returncode == 0: ...
urn stdout.strip().decode('utf8') def get_commit(path='.'): p = subprocess.Popen( ['git', 'rev-parse', 'HEAD'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=path) stdout, _ = p.communicate() if p.returncode != 0: return None return stdout.strip().deco...
infoxchange/docker-forklift
forklift/registry.py
Python
apache-2.0
1,142
0
# # Copyright 2014
Infoxchange Australia # # 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, softw...
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. """ Helpers related to maintaining a registry of classes """ class Registry(dict): """ A registry class, used for reg...
xuqingkuang/tsCloud
tsCloud/ad/management/commands/_private.py
Python
gpl-3.0
841
0.007134
from optparse import make_option from django.core.management.base import BaseCommand, CommandError from django.core.validators import URLValidator
from django.core.exceptions
import ValidationError class ADBaseCommand(BaseCommand): option_list = BaseCommand.option_list + ( make_option('--overwrite', action='store_true', dest='overwrite', default=False, help='Overwrite existed images'), ) url_validator = URLValidator() ...
zfergus2/Wrapping-Textures
src/affine_null_space.py
Python
mit
8,006
0.003372
# -*- coding: utf-8 -*- """ Given a system Ax = b, determine a matrix N spanning the right null space of A and a feasible solution x0 so that: A * (N * y + x0) = b for any y Written by Zachary Ferguson """ import numpy import scipy.sparse # import cvxopt import pdb import includes from luq import luq from spq...
he solution num_tests = 1000
# A * N * y for any y print("\nTest A * N * y = 0 for any y:") total_diff = sum([ abs(A.dot(N.dot(numpy.random.rand(N.shape[1], 1)))).sum() for i in range(num_tests)]) test_util.display_results(total_diff < 1e-8, format_str = "Expected total: %g, Actual total: %g\t%%s" % (0, tota...
nicproulx/mne-python
mne/datasets/__init__.py
Python
bsd-3-clause
374
0
"""
Functions for fetching remote
datasets.""" from . import brainstorm from . import visual_92_categories from . import eegbci from . import megsim from . import misc from . import sample from . import somato from . import multimodal from . import spm_face from . import testing from . import _fake from .utils import _download_all_example_data, fetch_...
all-of-us/raw-data-repository
rdr_service/dao/ce_health_reconciliation_dao.py
Python
bsd-3-clause
1,252
0.001597
from rdr_service.dao.base_dao import UpdatableDao from rdr_service.model.ce_health_reconciliation import CeHealthReconciliation class CeHealthReconciliationDao(UpdatableDao): def __init__(self): super(CeHealthReconciliationDao, self).__init__(CeHealthReconciliation, order_by_ending=["id"]) def _find...
on_list): records = list(ce_health_reconciliation_list) for record in records: dup_id = self._find_dup_with_session(session, record) if dup_id: record.id = dup_id session.merge(record) def get_missing_records_by_report_date(self, session, cutoff_d...
n.status.is_(False))) return query.all()
perfectsearch/sandman
test/buildscripts/textui_prompt_test.py
Python
mit
6,007
0.004162
# # $Id: build_ansi.py 9736 2011-06-20 16:49:22Z ahartvigsen $ # # Proprietary and confidential. # Copyright $Date:: 2011#$ Perfect Search Corporation. # All rights reserved. # import unittest, os, sys, StringIO from textui.prompt import * from nose.tools import istest, nottest from nose.plugins.attrib import...
elf.stuff('to seek the holy grail\n') answer = prompt('What is your quest?') self.assertTrue(an
swer) # Answer should never include trailing \n self.assertEquals(answer.rstrip(), answer) def test_prompt_bool_word_true(self): self.explain(''' Answer the following question accurately with a FULL WORD, not a single char. In other words, type "yes" or "no" as your answer. Case doesn'...
google/rekall
rekall-core/rekall/plugins/overlays/windows/tcpip_vtypes.py
Python
gpl-2.0
26,975
0.013012
# Rekall Memory Forensics # # Copyright 2013 Google 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 Foundation; either version 2 of the License, or (at # your option) any later v...
[0x34, ['unsigned be short']], 'Protocol' : [0x36, ['unsigned short']], 'Pid' : [0x14C, ['unsigned long']], 'CreateTime' : [0x158, ['WinFileTime', {}]], }], } TCP_STATE_ENUM = { 0: 'CLOSED', 1: 'LISTENING', 2: 'SYN_SENT',
3: 'SYN_RCVD', 4: 'ESTABLISHED', 5: 'FIN_WAIT1', 6: 'FIN_WAIT2', 7: 'CLOSE_WAIT', 8: 'CLOSING', 9: 'LAST_ACK', 12: 'TIME_WAIT', 13: 'DELETE_TCB' } # Structures used by netscan for x86 Vista and 2008 (all service packs). tcpip_vtypes_vista = { '_IN_ADDR' : [None, { 'addr4' : [0x0, ['Ipv4Address'...
teddziuba/pqauth
python/pqauth/pqauth_django_server/tests/settings.py
Python
mit
495
0
import os DIRNAME = os.path.dirname(__file__) DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3" } } INSTALLED_APPS = ( "django.contrib.auth", "django.contrib.contenttypes", "pqauth.pqauth_django_server" ) SECRET_KEY = "chicken butt" PQAUTH_SERVER_KEY = os.
path.join(DIRNAME, "server.key") ROOT_URLCONF
= "pqauth.pqauth_django_server.urls" TEST_CLIENT_KEY = os.path.join(DIRNAME, "client.key") TEST_EVIL_KEY = os.path.join(DIRNAME, "evil.key")
lepture/misaka
build_ffi.py
Python
mit
10,725
0.003357
# -*- coding: utf-8 -*- import cffi # Block-level extensions EXT_TABLES = (1 << 0) EXT_FENCED_CODE = (1 << 1) EXT_FOOTNOTES = (1 << 2) # Span-level extensions EXT_AUTOLINK = (1 << 3) EXT_STRIKETHROUGH = (1 << 4) EXT_UNDERLINE = (1 << 5) EXT_HIGHLIGHT = (1 << 6) EXT_QUOTE = (1 << 7) EXT_
SUPERSCRIPT = (1 << 8) EXT_MATH = (1 << 9) # Other flags EXT_NO_INTRA_EMPHASIS = (1 << 11) EXT_SPACE_HEADERS = (1 << 12) EXT_MATH_EXPLICIT = (1 << 13) # Negative flags EXT_DISABLE_INDENT
ED_CODE = (1 << 14) # List flags LIST_ORDERED = (1 << 0) LI_BLOCK = (1 << 1) # <li> containing block data # Table flags TABLE_ALIGN_LEFT = 1 TABLE_ALIGN_RIGHT = 2 TABLE_ALIGN_CENTER = 3 TABLE_ALIGNMASK = 3 TABLE_HEADER = 4 # HTML flags HTML_SKIP_HTML = (1 << 0) HTML_ESCAPE = (1 << 1) HTML_HARD_WRAP = (1 << 2) HTML_...
openai/multiagent-particle-envs
multiagent/policy.py
Python
mit
1,935
0.014987
import numpy as np from pyglet.window import key # individual agent policy class Policy(object): def __init__(self): pass def action(self, obs): raise NotImplementedError() # interactive policy based on keyboard input # hard-coded to deal only with movement, not communication class Interactive...
lf.key_release def action(self, obs): # ignore observation and just act based on keyboard events if self.env.discrete_action_input: u = 0 if self.move[0]: u = 1 if self.move[1]: u = 2
if self.move[2]: u = 4 if self.move[3]: u = 3 else: u = np.zeros(5) # 5-d because of no-move action if self.move[0]: u[1] += 1.0 if self.move[1]: u[2] += 1.0 if self.move[3]: u[3] += 1.0 if self.move[2]: u[4] += 1.0 ...
dimagi/commcare-hq
corehq/apps/saved_reports/management/commands/daylight_savings.py
Python
bsd-3-clause
1,620
0.002469
from datetime import datetime, timedelta from django.core.management import BaseCommand from corehq.apps.saved_reports.models import ReportNotification class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('domains', nargs='+') parser.add_argument('-F', '--forward', act...
tkey=key, endkey=key + [{}]) return reports DAYS_IN_WEEK = 7 def adjust_report(report, forward=False): day = report.day + 1 if report.interval == 'weekly' else report.day # account for 0-indexed days trigger_time = datetime.now().replace(hour=report.hour, minute=report.minute, day=day) if forward:...
time.hour if report.interval == 'weekly': report.day = (trigger_time.day - 1) % DAYS_IN_WEEK elif report.interval == 'monthly': report.day = trigger_time.day return report
rocky/python2-trepan
trepan/processor/command/set_subcmd/trace.py
Python
gpl-3.0
1,431
0.001398
# -*- coding: utf-8 -*- # Copyright (C) 2009-2010, 2013, 2015 Rocky Bernstein rocky@gnu.org # # This program is free software: you can redistribute it and/or modify # i
t 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 # M...
ed a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Our local modules from trepan.processor.command import base_subcmd as Mbase_subcmd class SetTrace(Mbase_subcmd.DebuggerSetBoolSubcommand): """**set trace** [ **on** | **off** ] Set event trac...
vangj/py-bbn
pybbn/pptc/inferencecontroller.py
Python
apache-2.0
2,747
0.001456
import copy from pybbn.graph.jointree import JoinTreeListener from pybbn.pptc.initializer import Initializer from pybbn.pptc.moralizer import Moralizer from pybbn.pptc.potentialinitializer import PotentialInitializer from pybbn.pptc.propagator import Propagator from pybbn.pptc.transformer import Transformer from pybbn...
eturn: Join tree. """ PotentialInitializer.init(bbn) ug = Moralizer.moralize(bbn) cliques = Triangulator.triangulate(ug) join_tree = Transformer.transform(cliques) join_tree.parent_info = {node.id: bbn.get_parent
s_ordered(node.id) for node in bbn.get_nodes()} Initializer.initialize(join_tree) Propagator.propagate(join_tree) join_tree.set_listener(InferenceController()) return join_tree @staticmethod def reapply(join_tree, cpts): """ Reapply propagation to join tree wi...
wscullin/spack
var/spack/repos/builtin/packages/r-iterators/package.py
Python
lgpl-2.1
1,647
0.000607
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
OF # MERCHANTABILITY or FI
TNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA ...
jorgehog/Deux-kMC
scripts/autocorr/analyze.py
Python
gpl-3.0
4,199
0.003572
from matplotlib.pylab import plot, show import sys import os from os.path import join import numpy as np from scipy.optimize import curve_fit from math import exp, sqrt sys.path.append(join(os.getcwd(), "..")) from parse_h5_output import ParseKMCHDF5 from scipy.stats import linregress def find_match(x, y, start, e...
np.zeros_like(RMSes) for data, L, W, run_id in parser: if data.attrs["diffuse"] != typeint: continue alpha = data.attrs["alpha"] height = data.attrs["confiningSurfaceHeight"] ia = alphas.index(alpha) ih = heights.index(height) autocor
r = np.array(data["autocorrelation"]) autocorrs[ih, ia, :, :] += autocorr labels = data["ignisEventDescriptions"] i = list(list(labels)[0]).index("HeightRMS@MainMesh") RMS = data["ignisData"][i, :] rms = (RMS[len(RMS)/2:]).mean() RMSes[ih, ia] += rms counts[ih,...
davy39/eric
Tools/TRPreviewer.py
Python
gpl-3.0
29,971
0.004438
# -*- coding: utf-8 -*- # Copyright (c) 2004 - 2014 Detlev Offe
nbach <detlev@die-offenbachs.de> # """ Module implementing the TR Previewer main window. """ from __future__ import unicode_literals import os from PyQt5.QtCore import QDir, QTimer, QFileInfo, pyqtSignal, QEvent, QSize, \ QTranslator, QObject, Qt, QCo
reApplication from PyQt5.QtGui import QKeySequence from PyQt5.QtWidgets import QSizePolicy, QSpacerItem, QWidget, QHBoxLayout, \ QWhatsThis, QMdiArea, qApp, QApplication, QComboBox, QVBoxLayout, \ QAction, QLabel from PyQt5 import uic from E5Gui import E5MessageBox, E5FileDialog from E5Gui.E5MainWindow import...
chalbersma/persist_transaction
perf/oldtx.py
Python
gpl-3.0
1,653
0.052632
#!/usr/bin/env python3 # Old Transactions import pymysql def mainactio
ns(args_list, configs, db_cur) : help_string=''' Usage: * Default: Returns the number of old, active transactions (By Default 1 Day). By Default Warn Crit Time is the format for customization otherwise it's 50/100''' unknown_error=False warn = 50 crit = 100 hours = 24 #print(args_list) if len(args_list) ...
its warn = int(args_list[0]) crit = int(args_list[1]) if len(args_list) == 3 : # I've additionally been provided a custom date range. hours = int(args_list[2]) query_args = [ hours ] oldtx_query = "select count(*) as count from trked_trans where active = true and firstseen < NOW() - INTERVAL %s HOUR ; " ...
cernops/keystone
keystone/conf/paste_deploy.py
Python
apache-2.0
1,163
0
# Licensed under the Apache License, Versi
on 2.0 (the "License"); you may # not use this file except in complia
nce 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 o...
opportunitynetwork/devault
devault/devault/versions/serializers.py
Python
bsd-3-clause
238
0.004202
from devault.versions.models import Version from rest_framework import se
rializers class VersionSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Version fields = ('name'
, 'created', 'modified')
Panos512/invenio
modules/bibauthorid/lib/bibauthorid_webauthorprofileinterface.py
Python
gpl-2.0
4,128
0.006783
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2011 CERN. # # Invenio is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later...
emitting #pylint: disable-msg=W0611 # from invenio.bibauthorid_config import CLAIMPAPER_CLAIM_OTHERS_PAPERS from invenio.bibauthorid_config import AID_ENABLED # emitting #pylint: disable-msg=W0611 from invenio.bibauthorid_config import AID_ON_AUTHORPAGES # emitting #pylint: disable-msg=W0611 from invenio import biba...
y_personid(pid): return [p[0] for p in get_names_count_of_author(pid)]
annikulin/sendspaceBox
client/sendspace.py
Python
mit
5,794
0.001726
import hashlib import xml.etree.ElementTree as ET import requests from requests_toolbelt import MultipartEncoder from client.model import Folder, File def post_request(url, expect_xml_response=True, **kwargs): response_xml = requests.post(url, **kwargs) if response_xml.status_code != 200: http_erro...
message: %s' % (
response_xml.status_code, response_xml.reason, response_xml.text) raise Exception(http_error_msg) if expect_xml_response: response = ET.fromstring(response_xml.text) if response.attrib['status'] != 'ok': message = 'Sendspace API request failed. Reason: %s' % (respons...
fatihzkaratana/cluster-organizer
__init__.py
Python
mit
1,472
0.000679
#!/usr/bin/python # coding: utf-8 """ The MIT License (MIT) Copyright (c) 2013 Fatih Karatana 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...
OF ANY KIND, EXPRESS OR IMPLIED, I
NCLUDING 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 FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE...
phil-lopreiato/frc-notebook-server
models/mobile_client.py
Python
mit
1,097
0.000912
import urllib from google.appengine.ext import ndb class Mobile
Client(ndb.Model): """ This class repesents a mobile client that has registered with the server We store a messaging ID (e.g. Google Cloud Messaging sender ID) as well as a per-user unique key that is generated client side and sent up. In order to make strongly consistent DB requests, instances of t...
indexed=True) messaging_id = ndb.StringProperty(required=True) client_type = ndb.IntegerProperty(required=True) display_name = ndb.StringProperty(default="Unnamed Device") device_uuid = ndb.StringProperty(default='') created = ndb.DateTimeProperty(auto_now_add=True) updated = ndb.DateTimePrope...
mapzen/vector-datasource
integration-test/629-trolleybus-is-a-bus.py
Python
mit
1,163
0
from . import FixtureTest class TrolleybusIsABus(FixtureTest): def test_industrial_street(self): self.load_fixtures([ 'http://www.openstreetmap.org/way/397268717', 'http://www.op
enstreetmap.org/relation/2996736', ], clip=self.tile_bbox(16, 10484, 25339)) self.assert_has_feature( 16, 10484, 25339, 'roads', {'is_bus_route': True, 'name': 'Industrial St.'}) def test_clayton_street(self): se
lf.load_fixtures([ 'http://www.openstreetmap.org/way/32929419', 'http://www.openstreetmap.org/relation/3412979', ], clip=self.tile_bbox(16, 10477, 25333)) self.assert_has_feature( 16, 10477, 25333, 'roads', {'is_bus_route': True, 'name': 'Clayton St.'}) ...
wax8280/web2kindle
web2kindle/script/zhihu_daily.py
Python
mit
9,297
0.001909
# !/usr/bin/env python # -*- encoding: utf-8 -*- # vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8: # Author: Vincent<vincent8280@outlook.com> # http://wax8280.github.io # Created on 18-2-12 上午2:34 # !/usr/bin/env python import datetime import os import re import time from copy import deepcopy from queue import Q...
ID_SET = set() TODAY_URL = 'http://news-at.zhihu.com/api/4/stories/latest' # http://http://news-at.zhihu.com/api/4/stories/before/20180212 YESTERDAY_URL = 'http://news-at.zhihu.com/api/4/stories/before/{}' IS_TODAY_URL = True META = make_crawler_meta(SCRIPT_CONFIG.get('HEADER'
, {}), ['referer', 'connection', 'accept-encoding', 'If-None-Match', 'host', 'X-CSRF-Token']) HTML_PARSER_NAME = 'lxml' def main(start=None, end=None, img=True, gif=False, email=False, **kw): # start:20120101 kw.update({ 'img': img, 'gif': gif, 'email': email,...
rwl/PyCIM
CIM15/IEC61970/Informative/InfCustomers/ComplianceEvent.py
Python
mit
2,503
0.001598
# Copyri
ght (C) 2010-2011 Richard Lincoln # # 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, pub
lish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWA...
jxtech/wechatpy
wechatpy/client/api/semantic.py
Python
mit
1,959
0.000635
# -*- coding: utf-8 -*- from optionaldict import optionaldict from wechatpy.client.api.base import BaseWeChatAPI class WeChatSemantic(BaseWeChatAPI): def search( self, query, category, uid=None, latitude=None, longitude=None, city=None, region=None...
:param uid: 可选,用户唯一id(非开发者id),用户区分公众号下的不同用户(建议填入用户openid) :param latitude: 可选,纬度坐标,与经度同时传入;与城市二选一传入 :param longitude: 可选,经度坐标,与纬度同时传入;与城市二选一传入 :param city: 可选,城市名称,与经纬度二选一传入 :param region: 可选,区域名称,在城市存在的情况下可省;与经纬度二选一传入 :return: 返回的 JSON 数据包
使用示例:: from wechatpy import WeChatClient client = WeChatClient('appid', 'secret') res = client.semantic.search( '查一下明天从北京到上海的南航机票', 'flight,hotel', city='北京' ) """ if isinstance(category, (tuple, list)):...
neuroticnerd/boxbox
boxbox/__init__.py
Python
bsd-3-clause
125
0
from .in
terface import CLI __version__ = "0.1.0" __all__ = ('interface', 'tasks', 'utils', 's3', 'vagrant'
, 'virtualbox')
radicalbit/ambari
ambari-server/src/main/resources/common-services/DRUID/0.9.2/package/scripts/broker.py
Python
apache-2.0
955
0.002094
""" 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 use this ...
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 druid_node import D...
r(DruidBase): def __init__(self): DruidBase.__init__(self, nodeType="broker") if __name__ == "__main__": DruidBroker().execute()
nmercier/linux-cross-gcc
linux/lib/python2.7/dist-packages/blueman/plugins/MechanismPlugin.py
Python
bsd-3-clause
1,268
0.018927
# Copyright (C) 2009 Valmantas Paliksa <walmis at balticum-tv dot lt> # # Licensed under the GNU General Public License Version 3 # # 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...
See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # class MechanismPlugin(object): def _
_init__(self, mechanism): self.m = mechanism self.timer = self.m.timer self.confirm_authorization = self.m.confirm_authorization self.on_load() def add_dbus_method(self, func, *args, **kwargs): self.m.add_method(func, *args, **kwargs) def add_dbus_signal(self, func, *args, **kwargs): self.m.add_si...