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
Nachtfeuer/pipeline
tests/components/test_shell_config.py
Python
mit
2,422
0.001652
"""Testing of module config.""" # pylint: disable=no-self-use, invalid-name, redundant-unittest-assert import unittest from hamcrest import assert_that, equal_to, contains_string from ddt import ddt, data from spline.components.config import ShellConfig @ddt class TestShellConfig(unittest.TestCase): """Testing of...
: False, 'item': None, 'env': {}, 'model': {}, 'variables': {}} final_kwargs.update(kwargs) config = ShellConfig(**final_kwargs) for key, value in final_kwargs.i
tems(): assert_that(key in config.__dict__, equal_to(True)) assert_that(config.__dict__[key], equal_to(value)) def test_missing_mandatory(self): """Testing invalid parameter.""" try: ShellConfig() self.assertFalse("RuntimeError expected") exce...
ipostuma/MCNPtools
WriteTally.py
Python
gpl-3.0
1,830
0.004372
from MCNPtools import Gen # example usage of the module # first you initialize the tally by defining the bins: segment (surface number), angle (cosine) and energy (MeV) cos = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1] seg = [666,667] erg =[1.000E
-10, 1.259E-10, 1.585E-10, 1.995E-10, 2.512E-10, 3.162E-10, 3.981E-10, 5.012E-10, 6.310E-10, 7.943E-10, 1.000E-09, 1.259E-09, 1.585E-09, 1.995E-09, 2.512E-09, 3.162E-09, 3.981E-09, 5.012E-09, 6.310E-09, 7.943E-09, 1.000E-08, 1.259E-08, 1.585E-08, 1.995E-08, 2.512E-08, 3.162E-08, 3.981E-08, 5.012...
00E-06, 1.259E-06, 1.585E-06, 1.995E-06, 2.512E-06, 3.162E-06, 3.981E-06, 5.012E-06, 6.310E-06, 7.943E-06, 1.000E-05, 1.259E-05, 1.585E-05, 1.995E-05, 2.512E-05, 3.162E-05, 3.981E-05, 5.012E-05, 6.310E-05, 7.943E-05, 1.000E-04, 1.259E-04, 1.585E-04, 1.995E-04, 2.512E-04, 3.162E-04, 3.981E-...
2ndQuadrant/ansible
lib/ansible/plugins/action/pause.py
Python
gpl-3.0
10,780
0.001299
# Copyright 2012, Tim Bielawa <tbielawa@redhat.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later...
None: if s
econds < 1: seconds = 1 # setup the alarm handler signal.signal(signal.SIGALRM, timeout_handler) signal.alarm(seconds) # show the timer and control prompts display.display("Pausing for %d seconds%s" % (seconds, echo_pr...
ryandub/simpl
simpl/exceptions.py
Python
apache-2.0
3,556
0.000281
# Copyright (c) 2011-2015 Rackspace US, 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 # # Unle...
' % repr(self.oserror) rpr += ')' return rpr class Simp
lGitNotRepo(SimplGitError): """The directory supplied is not a git repo.""" class SimplCalledProcessError(SimplException): """Raised when a process run by execute() returns non-zero. The exit status will be stored in the returncode attribute; check_output() will also store the output in the output ...
matslindh/codingchallenges
adventofcode2021/day10.py
Python
mit
2,156
0.000928
from math import floor def score_syntax_errors(program_lines): points = {')': 3, ']': 57, '}': 1197, '>': 25137} s = 0 scores_auto = [] for line in program_lines: corrupted, stack = corrupted_character(line) if corrupted: s += points[corrupted] else: s...
en(scores_auto)/2)] def corrupted_character(inp): stack = [] lookup = {'(': ')', '[': ']', '{': '}', '<': '>'} lookup_close = {v: k for k, v in lookup.items()} def stack_converter(st): return [lookup[element] for element in st[::-1]] for char in inp: if char in lookup: ...
char, stack_converter(stack) else: print(f"INVALID {char}") return None, stack_converter(stack) def score_autocomplete(stack): points_autocomplete = {')': 1, ']': 2, '}': 3, '>': 4} s_auto = 0 for char in stack: s_auto *= 5 s_auto += points_autocomplete[char] ...
akshayarora2009/vayu
vayu/routes/projects.py
Python
mit
7,845
0.002549
from flask import Blueprint, render_template, request, make_response, jsonify import os import vayu.core.local_utils as lutils import vayu.core.fabric_scripts.utils as futils from vayu.core.constants.model import machine_info from vayu.core.VayuException import VayuException import vayu.core.constants.local as constant...
as e: errors.append(str(e)) if not errors: return make_response("OK", 200) else: v = VayuException(400, "Please corr
ect the errors", errors) return make_response(v.to_json(), 400) @project_app.route('/projects/<project_id>/delete-data-center', methods=['POST']) def delete_data_center(project_id): """ This method deletes a data center associated with a particular project_id :param project_id: :return: ""...
ErickMurillo/ciat_plataforma
ciat_plataforma/wsgi.py
Python
mit
403
0.002481
""" WSGI config for ciat_plaforma project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "c
iat_plataforma.settings") from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
liqd/a4-meinberlin
tests/offlineevents/dashboard_components/test_views_project_offlineevents.py
Python
agpl-3.0
3,388
0
import pytest from dateutil.parser import parse from django.urls import reverse from adhocracy4.dashboard import components from adhocracy4.test.helpers import assert_template_response from adhocracy4.test.helpers import redirect_target from adhocracy4.test.helpers import setup_phase from meinberlin.apps.ideas.phases ...
kwargs={'slug': event.slug}) data = { 'name': 'name', 'event_type': 'event_type', 'description': 'desc', 'date_0': '2013-01-01',
'date_1': '18:00', } client.login(username=initiator.email, password='password') response = client.post(url, data) assert redirect_target(response) == 'offlineevent-list' event.refresh_from_db() assert event.description == data.get('description') assert event.date == parse("2013-01-01 ...
aljim/deploymentmanager-samples
examples/v2/waiter/instance.py
Python
apache-2.0
2,634
0.004176
# Copyright 2016 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...
ns and # limitations under the License. """Creates a VM with the provided name, metadata, and auth scopes.""" COMPUTE_URL_BASE = 'https://www.googleapis.com/compute/v1/' def GlobalComputeUrl(project, collection, name): return ''.join([COMPUTE_URL_BASE, 'projects/', project, '/global/', collecti...
def ZonalComputeUrl(project, zone, collection, name): return ''.join([COMPUTE_URL_BASE, 'projects/', project, '/zones/', zone, '/', collection, '/', name]) def GenerateConfig(context): """Generate configuration.""" base_name = context.properties['instanceName'] items = [] for key, valu...
Islandman93/reinforcepy
examples/ALE/DQN_Async/run_a3c.py
Python
gpl-3.0
1,478
0.00406
import json import datetime from reinforcepy.environments import ALEEnvironment from reinforcepy.networks.dqn.tflow.nstep_a3c import NStepA3C from reinforcepy.learners.dqn.asynchronous.q_thread_learner import QThreadLearner from reinforcepy.learners.dqn.asynchronous.async_thread_host import AsyncThreadHost
def main(rom_args, learner_args, network_args, num_threads, epochs, logdir, save_interval): # create envs for each thread environments = [ALEEnvironment(**rom_args) for _ in range(num_threads)] # create shared network num_actions = environments[0].get_num_actions() input_shape = [learner_args['ph...
e_shape() network = NStepA3C(input_shape, num_actions, **network_args) # create thread host thread_host = AsyncThreadHost(network, log_dir=logdir) # create threads threads = [QThreadLearner(environments[t], network, thread_host.shared_dict, **learner_args) for t in range(num_threads)] reward_...
google-research/google-research
aloe/aloe/rfill/utils/program_struct.py
Python
apache-2.0
6,121
0.008822
# coding=utf-8 # Copyright 2022 The Google Research 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 applicab...
nodes or single node) """ self.syntax = syntax self.value = value self.children = [] if subtrees is not None:
for e_type, children in subtrees: if isinstance(children, list): for c in children: add_edge(parent_node=self, child_node=c, edge_type=e_type) else: add_edge(parent_node=self, child_node=children, edge_type=e_type) def get_name(self): if self.value is None: ...
openstack/ceilometer
ceilometer/tests/unit/publisher/test_prometheus.py
Python
apache-2.0
4,934
0
# # Copyright 2016 IBM # # 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...
e': 'TestPublish'}, ), sample.Sample( name='beta', type=sample.TYPE_DELTA, unit='', volume=3, user_id='test', project_id='test', resource_id=resource_id, timestamp=datetime.datetime.utcnow().isoformat(), ...
volume=5, user_id='test', project_id='test', resource_id=resource_id, timestamp=datetime.datetime.now().isoformat(), resource_metadata={'name': 'TestPublish'}, ), sample.Sample( name='delta.epsilon', type=sam...
ttreeagency/PootleTypo3Org
pootle/apps/pootle_notifications/views.py
Python
gpl-2.0
8,843
0.000565
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2009-2012 Zuza Software Foundation # # This file is part of Pootle. # # 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...
} # Find lan
guage and project defaults, passed to handle_form proj = None lang = None if not directory.is_language() and not directory.is_project(): trans_proj = directory.translation_project lang = trans_proj.language proj = trans_proj.project elif directory.is_language(): lang = di...
hduongtrong/hyperemble
hyperemble/neural_net/tests/test_neural_net.py
Python
bsd-2-clause
760
0
from __future__ import (absolute_import, division, print_function, unicode_literals) from keras.datasets import mnist from hyperemble.neural_net import VanillaNeuralNet def test_vanilla_neural_net(): (X_train, y_train),
(X_test, y_test) = mnist.load_data() X_train = X_train.reshape(60000, 784) X_test = X_test.reshape(10000, 784) X_train = X_train.astype('float32') X_test = X_test.astype('float32') X_train /= 255 X_test /= 255 clf = VanillaNeuralNet(n_layers=2, hidden_dim=200, k...
andom_state=1) clf.fit(X_train, y_train) res = clf.score(X_test, y_test) assert res > 0.92
eteq/ginga
ginga/misc/plugins/IRAF.py
Python
bsd-3-clause
32,083
0.00106
""" The IRAF plugin implements a remote control interface for the Ginga FITS viewer from an IRAF session. In particular it supports the use of the IRAF 'display' and 'imexamine' commands. Instructions for use: Set the environment variable IMTDEV appropriately, e.g. $ export IMTDEV=inet:45005 (or) $ ...
info("setting mode to IRAF") self.setMode('IRAF', chname) def add_channel(self, viewer, chinfo): self.logger.debug("channel %s added." % (chinfo.name)) n = self.channel_to_frame(chinfo.name) if n is None: found = len(self.fb) for n, fb in self.fb.ite
ms(): if fb.chname is None: found = n fb = self.init_frame(found) fb.chname = chinfo.name fmap = self.get_channel_frame_mapping() self.fv.gui_do(self.update_chinfo, fmap) chinfo.fitsimage.add_callback('image-set', self.new_image_cb, ...
p4lang/p4factory
targets/l2_switch/tests/of-tests/openflow.py
Python
apache-2.0
7,004
0.004997
""" Openflow tests on an l2 table """ import sys import os import logging from oftest import config import oftest.base_tests as base_tests import ofp from oftest.testutils import * from oftest.parse import parse_mac import openflow_base_tests sys.path.append(os.path.join(sys.path[0], '..', '..', '..', '..', ...
sts.OFTestInterface.__init__(self, "l2_switch") def runTest(self): setup(self) ports = sorted(config["port_map"].keys()) in_port = ports[0] table = openflow_tables["dmac"] table.match_fields[eth_dst_addr].testval = "00:01:02:03:04:05" pkt, match = get_match(table.m...
TROLLER } instr = get_apply_actions(output) req = flow_add(table_id=table.id, match=match, instructions=instr, buffer_id=buf, priority=1, cookie=42) self.controller.message_send(req) do_barrier(self.controller) self.dataplane.send(in_port, pkt) ...
PyListener/CF401-Project-1---PyListener
pylistener/models/mymodel.py
Python
mit
1,872
0.001068
from sqlalchemy import ( Column, Index, Integer, Text, LargeBinary, Unicode, ForeignKey, Table ) from sqlalchemy.orm import relationship from .meta import Base class User(Base): """This class defines a User model.""" __tablename__ = 'users' id = Column(Integer, primary_key...
lumn(Integer, ForeignKey('attributes.id'), nullable=False, primary_key=True) priority = Column(Integer, default=1, nullable=False) num_hits = Column(Integer, default=0, nullable=False) user_rel = relationship("User")
attr_rel = relationship("Attribute")
cpennington/course-discovery
course_discovery/urls.py
Python
agpl-3.0
1,899
0.00158
"""course_discovery URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') C...
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ import os from django.conf import settings from django.conf.urls import include, url fro...
.views import logout from django.core.urlresolvers import reverse_lazy from django.views.generic import RedirectView from course_discovery.apps.core import views as core_views admin.autodiscover() # pylint: disable=invalid-name # Always login via edX OpenID Connect login = RedirectView.as_view(url=reverse_lazy('soci...
mrachinskiy/booltron
lib.py
Python
gpl-3.0
1,452
0.001377
# SPDX-License-Identifier: GPL-3.0-or-later # Copyright 2014-2022 Mikhail Rachinskiy import random from typing import Optional import bpy from bpy.types import Object, Operator from mathutils import Vector def object_offset(obs: list[Object], offset: float) -> None: for ob in obs: x = random.uniform(-of...
ect": ob1} bpy.ops.object.modifier_apply(override, modifier=md.name) if remove_ob2: bpy
.data.meshes.remove(ob2.data)
mac389/LVSI
src/main.py
Python
apache-2.0
885
0.035028
import json import utils as tech import numpy as np cols_with_grades = [1,2,3] pathologists = open('../data/rater-names','rb').read().splitlines() contingency_tables = {} possible_values = list(np.array(cols_with_g
rades)-1) #No stains f1 = '../data/no-stain.xls' f2 = '../data/no-stain.xls' contingency_tables['no-stain'] = tech.kappa(f1,f2,pathologists,cols_with_grades,'lvsi-grades-s-stains',possible_values) #Stains f1 = '../data/stains.xls' f2 = '../data/stains.xls' contingency_tables['stain'] = tech.kappa(f1,f2,pathologists,co...
les['Intra-rater'] = tech.kappa(f1,f2,pathologists,cols_with_grades,'intra-rater-reliability',possible_values) json.dump(contingency_tables,open('../data/contingency_tables.json','wb'))
mmerce/python
bigml/tests/read_statistical_tst_steps.py
Python
apache-2.0
923
0.002167
# -*- coding: utf-8 -*- # # Copyr
ight 2015-2020 BigML # # 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 lang...
richardkiss/pycoin
tests/bloomfilter_test.py
Python
mit
2,635
0.004934
import binascii import unittest from pycoin.bloomfilter import filter_size_required, hash_function_count_req
uired, BloomFilter, murmur3 from pycoin.symbols.btc import network Spendable = network.tx.Spendable h2b = binascii.unhexlify class BloomFilterTest(unittest.TestCase): def test_filter_size_required(self): for ec, fpp, ev in [ (1, 0.00001, 3), (1, 0.00000001, 5), (100,...
0.000001, 360), ]: fsr = filter_size_required(ec, fpp) self.assertEqual(fsr, ev) def test_hash_function_count_required(self): for fs, ec, ev in [ (1, 1, 6), (3, 1, 17), (5, 1, 28), (360, 100, 20), ]: av = ha...
mnazim/django-rest-kickstart
users/views.py
Python
mit
362
0
fr
om rest_framework.decorators import list_route from rest_framework.permissions import IsAuthenticated from rest_framework import viewsets from .models import User from .serializers import UserSerializer class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer ...
thod_names = ['get', 'patch']
mvaled/sentry
src/sentry/api/endpoints/project_user_stats.py
Python
bsd-3-clause
1,034
0.000967
from __future__ import absolute_import from datetime import timedelta from django.utils import timezone from rest_framework.response import Response from sentry.app import tsdb from sentry.api.base import EnvironmentMixin from sentry.api.bases.project import
ProjectEndpoint from sentry.api.exceptions import ResourceDoesNotExist from sentry.models import Environment class ProjectUserStatsEndpoint(EnvironmentMixin, ProjectEndpoint): def get(self, request, project): try: environment_id = self._get_environment_id_from_request(request, project.organiz...
except Environment.DoesNotExist: raise ResourceDoesNotExist now = timezone.now() then = now - timedelta(days=30) results = tsdb.get_distinct_counts_series( tsdb.models.users_affected_by_project, (project.id,), then, now, ...
karthikdevel/fit
gui/wxpython/fitlistbox.py
Python
mit
546
0.001832
import wx class FitListBox(wx.ListBox): def GetDropList(self, itemlist): selections = [self.GetString(i) for i in self.GetSelect
ions()] drop_list = [] for i in itemlist: if i not in selections: dr
op_list.append(i) return drop_list def GetSelList(self, itemlist): selections = [self.GetString(i) for i in self.GetSelections()] sel_list = [] for i in itemlist: if i in selections: sel_list.append(i) return sel_list
benreynwar/fpga-sdrlib
python/fpga_sdrlib/b100.py
Python
mit
3,118
0.002886
""" Synthesise a QA module into the B100 FPGA. """ import os import shutil import subprocess from jinja2 import Environment, FileSystemLoader from fpga_sdrlib import config from fpga_sdrlib.config import uhddir, miscdir, fpgaimage_fn b100dir = os.path.join(uhddir, 'fpga', 'usrp2', 'top', 'B100') custom_src_dir = o...
#custom_defs=custom_defs, )) f_out.close() def synthesise(name, builddir): output_dir = os.path.join(builddir, 'build-B100_{name}'.format(name=name)) # Synthe
sise currentdir = os.getcwd() os.chdir(b100dir) if os.path.exists(output_dir): shutil.rmtree(output_dir) make_fn = os.path.join(builddir, 'Make.B100_{0}'.format(name)) logfile_fn = os.path.join(builddir, 'Make.B100_{0}.log'.format(name)) logfile = open(logfile_fn, 'w') p = subprocess...
jplusplus/wikileaks-cg-analyser
ngrams.py
Python
gpl-3.0
991
0.009082
# -*- coding: utf-8 -*- import argparse def ngrams(input='', n_min=0, n_max=5): input = input.split(' ') output = {} end = n_max for n in range(n_min+1, end+n_min+1): for i in range(len(input)-n+1): token = " ".join(input[i:i+n]) # Count the ngram output[toke...
max=5): # Print out ngrams return ngrams( str(tokens), int(n_min), int(n_max) ) # Command-line execution of the module if __name__ == "__main__": parser = argparse.ArgumentParser() # Command arguments parser.add_argument('-m', '--min', help="Minimum gram to extract.", dest
="n_min", default=0) parser.add_argument('-x', '--max', help="Maximum gram to extract.", dest="n_max", default=5) parser.add_argument('tokens', help="String to analyze.") # Parse arguments args = parser.parse_args() # Print out the main function print main( **vars(args) )
koolfreak/volunteer_planner
scheduler/templatetags/number_registrations.py
Python
agpl-3.0
260
0
import datetime from django import template from registration.models import RegistrationProfile register = template.Library() @register.simple_tag def get_volunteer_number(): vol
unteers = RegistrationProfile.objects.all().count(
) return volunteers
jessefeinman/FintechHackathon
python-getting-started/nlp/classificationTools.py
Python
bsd-2-clause
2,927
0.003075
import nltk import os from random import shuffle from nltk.classify.scikitlearn import SklearnClassifier from sklearn.naive_bayes import MultinomialNB, BernoulliNB from sklearn.linear_model import LogisticRegression, SGDClassifier from sklearn.svm import SVC, LinearSVC, NuSVC from datetime import datetime from nltk imp...
er from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier from sklearn.naive_bayes import GaussianNB from sklearn.discriminant_analysis impo
rt QuadraticDiscriminantAnalysis import pickle def listOfFiles(flagged): files = os.listdir(os.getcwd() + "/emailNames" + flagged) listToReturn = [] for file in files: with open("emailNames" + flagged + "/" + file, 'r') as names: listToReturn.append(([word[:-1].lower for word in names]...
marlboromoo/basinboa
basinboa/system/config.py
Python
mit
869
0.003452
#!/usr/bin/env python """ server config. """ from basinboa.system.loader import YamlLoader class Config(object): """docstr
ing for Config""" def __init__(self, name): super(Config, self).__init__() self.name = name self.items = 0 def __repr__(self): return "Config: %s, items: %s" % \ (self.name, self.items) cl
ass ConfigLoader(YamlLoader): """docstring for ConfigLoader""" SERVER_CONFIG = 'server' def __init__(self, data_dir): super(ConfigLoader, self).__init__(data_dir) def get(self, name): """docstring for get""" data = self.load(name) if data: return self.regist...
astrodsg/django-stock-up
stock_up/settings/__init__.py
Python
mit
36
0.027778
from stock_up.se
ttings.base import
*
hds-lab/textvisdrg-prototype
textvis/topics/urls.py
Python
mit
545
0.007339
from django.conf.urls import patterns, include, url import views urlpatterns = patterns('', url(r'^$', views.TopicModelIndexView.as_view(), name='topics_models'), url(r'^model/(?P<model_id>\d+)/$', views.TopicModelDetailView.as_view(
), name='topics_model'), url(r'^model/(?P<model_id>\d+)/topic/(?P<topic_id>\d+)/$', views.TopicDetailView.as_view(), name='topics_topic'), url(r'^model/(?P<model_id>\d+)/topic/(?P<topic_id>\d+)/wor
d/(?P<word_id>\d+)/$', views.TopicWordDetailView.as_view(), name='topics_topic_word'), )
catapult-project/catapult
third_party/gsutil/third_party/pyasn1-modules/tests/test_rfc2314.py
Python
bsd-3-clause
2,078
0.000481
# # This file is part of pyasn1-modules software. # # Copyright (c) 2005-2017, Ilya Etingof <etingof@gmail.com> # License: http://pyasn1.sf.net/license.html # import sys from pyasn1.codec.der import decoder as der_decoder from pyasn1.codec.der import encoder as der_encoder from pyasn1_modules import pem from pyasn1_m...
4IBDwAw ggEKAoIBAQC9n2NfGS98JDBmAXQn+vNUyPB3QPYC1cwpX8UMYh9MdAmBZJCnvXrQ Pp14gNAv6AQKxefmGES1b+Yd+1we9HB8AKm1/8xvRDUjAvy4iO0sqFCPvIfSujUy pBcfnR7QE2itvyrMxCDSEVnMhKdCNb23L2TptUmpvLcb8wfAMLFsSu2yaOtJysep oH/mvGqlRv2ti2+E2YA0M7Pf83wyV1XmuEsc9tQ225rprDk2uyshUglkDD2235rf 0QyONq3Aw3BMrO9ss1qj7vdDhVHVsxHnTVbEgrxEWkq2GkVKh9QR...
9M2bsNNm 9KfxqiGMqqcGCtzIlpDz/2NVwY93cEZsbz3Qscc0QpknRmyTSoDwIG+1nUH0vzkT Nv8sBmp9I1GdhGg52DIaWwL4t9O5WUHgfHSJpPxZ/zMP2qIsdPJ+8o19BbXRlufc 73c03H1piGeb9VcePIaulSHI622xukI6f4Sis49vkDaoi+jadbEEb6TYkJQ3AMRD WdApGGm0BePdLqboW1Yv70WRRFFD8sxeT7Yw4qrJojdnq0xMHPGfKpf6dJsqWkHk b5DRbjil1Zt9pJuF680S9wtBzSi0hsMHXR9TzS7HpMjykL2nmCV...
meta1203/Trigonometry-Programlets
vector_dimensions.py
Python
apache-2.0
525
0.013333
import stdutils, math fro
m stdutils import inputAsDict, cTheta, niceRoot, cApprox vals = inputAsDict(('size',cTheta)) real = math.cos(vals[cTheta]) comp = math.sin(vals[cTheta]) #str1 = '{} ({} + i {})'.format(niceRoot(vals['size']).getString(),niceRoot(real).getString(),niceRoot(comp).getString()) str2 = '<{}, {}>'.format(niceRoot(vals['siz...
r3))
ContinuumIO/ashiba
enaml/docs/source/sphinxext/refactordoc/fields.py
Python
bsd-3-clause
8,370
0.00359
# -*- coding: UTF-8 -*- #------------------------------------------------------------------------------ # file: fields.py # License: LICENSE.TXT # Author: Ioannis Tziakos # # Copyright (c) 2011, Enthought, Inc. # All rights reserved. #------------------------------------------------------------------------------ i...
trip(), arg_type.strip(), ['']) def to_rst(self, indent=4): """ Outputs field in rst as an itme in a definition list. Arguments --------- indent : int The indent to use for
the decription block. Returns ------- lines : list A list of string lines of formated rst. Example ------- >>> Field('Ioannis', 'Ιωάννης', 'Is the greek guy.') >>> print Field.to_rst() Ioannis (Ιωάννης) Is the greek guy. ...
MarHai/ScrapeBot
setup.py
Python
gpl-2.0
13,133
0.004797
import platform import os import getpass import sys import traceback from crontab import CronTab from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, scoped_session from scrapebot.configuration import Configuration from scrapebot.database import base, User, Instance def main(): print('Wel...
to the main MySQL database.' + 'Specify the all the necessary credentials on where to find it!') config.add_value('Database', 'Host', read_forcefully('- Database: Host', 'localhost')) config.add_value('Database', 'User', read_forcefully('- Database: User', 'root')) config.add_value('Databa
se', 'Password', read_forcefully('- Database: Password')) config.add_value('Database', 'Database', read_forcefully('- Database: Database Name', 'scrapebot')) if read_bool_forcefully('- Recipes sometimes take their time. In case your MySQL server has short timeouts set, ' \ 'you may w...
ajb/pittsburgh-purchasing-suite
migrations/versions/3de73bde77e_fix_opportunities_model.py
Python
bsd-3-clause
4,373
0.009376
"""fix opportunities model Revision ID: 3de73bde77e Revises: 22cc439cd89 Create Date: 2015-06-25 00:55:51.895965 """ # revision identifiers, used by Alembic. revision = '3de73bde77e' down_revision = '22cc439cd89' from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql def upgrade(...
association_category_id'), table_name='category_opportunity_association') op.drop_table('category_opportunity_association') op.drop_index(op.f('ix_documents_id'), table_name='document') op.drop_table('document') ### end Alembi
c commands ###
msipos/lasernotes
backend/webapp/tests.py
Python
agpl-3.0
3,156
0.001901
from django.test import TestCase from webapp.forms import ItemForm from webapp.models import User, Collection, CollectionPermission, Item, Accessor, OWNER, GUEST from webapp.util import server_side_md class ModelPermissionsTest(TestCase): def setUp(self): self.user1 = User.objects.create_user('a', 'a@a.c...
s(owner=True)) == 2 assert len(a2.query_items(owner=True)) == 0 class ValidationTest(TestCase): def test_url_validator(self): data = { 'title': 'My title', 'notes': '', 'content': 'Some
stuff', 'typ': 'E' } f = ItemForm(data) assert f.is_valid() data['typ'] = 'U' f = ItemForm(data) assert not f.is_valid() data['content'] = 'https://lasernotes.com' f = ItemForm(data) assert f.is_valid() class MarkdownTest(TestCase)...
zouzhberk/ambaridemo
demo-server/src/main/resources/stacks/BIGTOP/0.8/services/HIVE/package/scripts/webhcat_server.py
Python
apache-2.0
1,523
0.009192
""" 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 ...
import webhcat_service class WebHCatServer(Script): def install(self, env): self.install_packages(env) def configure(self, env): import params env.set_params(params) webhcat() def start(self, env): import params env.set_params(params) self.configure(env) # FOR SECURITY webhcat_s...
tion = 'stop') def status(self, env): import status_params env.set_params(status_params) check_process_status(status_params.webhcat_pid_file) if __name__ == "__main__": WebHCatServer().execute()
LTD-Beget/sprutio
app/modules/webdav/actions/files/copy.py
Python
gpl-3.0
934
0.004283
from core import FM from core.FMOperation import FMOperation class CopyFiles(FM.BaseAction): def __init__(self, request, paths, session, target, overwrite, **kwargs): super(CopyFiles, self).__init__(request=request, **kwargs) self.paths = paths self.session = session self.target =...
lf.get_rpc_request() operation = FMOperation.create(FM.Action.COPY, FMOperation.STATUS_WAIT) result = request.request('webdav/copy_files', login=self.request.get_current_user(), password=self.request.get_current_password(), status_id=operation.id, ...
ession, target=self.target, paths=self.paths, overwrite=self.overwrite) answer = self.process_result(result) answer["data"] = operation.as_dict() return answer
liangsun/me
webapp/models/user.py
Python
mit
573
0.001745
#!/usr/bin/python # -*- coding: utf-8 -*- class User(object): def __init__(self, id, email, passwd, session, session_expire_time, ctime, rtime): self.id = str(id) self.email = email self.passwd = passwd self.session = sess
ion self.session_expire_time = session_expire_time self.ctime = self.ctime @classmethod def get(cls, id): pass @classmethod def get_by_email(cls, email): pass @classmethod def register(cls, email, passwd): pass def login_user(em
ail, passwd):
wbvalid/python2
aioSqlQuery.py
Python
unlicense
1,328
0
#!/usr/bin/env python # -*- coding: utf-8 -*- import pdb import time import cx_Oracle import multiprocessing ipList = ("192.168.7.121", "192.168.7.122", "192.168.7.123", "192.168.7.124", "192.168.7.125", "192.168.7.126", "192.168.7.127", "192.168.7...
ose() pool.join() with open("Sqlout.log", "w") as fd: for i i
n result: for j in i[1].get(): strresult = '' # pdb.set_trace() for k in j: strresult += '%s,' % str(k) fd.write("%s\n" % strresult.rstrip(','))
cheer021/BikesPrediction_DP
bikes_prediction/manage.py
Python
mit
259
0.003861
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bikes_prediction.settings") from django.core.management import execute_from_comman
d_line e
xecute_from_command_line(sys.argv)
SamaraCardoso27/eMakeup
backend/test/course_test.py
Python
mit
950
0.012632
from base import GAETestCase from config.template_middleware import TemplateResponse from ro
utes.courses import new from tekton.gae.middl
eware.redirect import RedirectResponse from student.student_model import Course __author__ = 'samara' class NewTeste(GAETestCase): def test_sucesso(self): resposta = new.salvar(name='bla') self.assertIsInstance(resposta, RedirectResponse) self.assertEqual('/courses',resposta.context) ...
madj4ck/ansible
lib/ansible/plugins/lookup/file.py
Python
gpl-3.0
2,558
0.003518
# (c) 2012, Daniel Hokka Zakrisson <daniel@hozac.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any lat...
relative_
path = self._loader.path_dwim_relative(variables['role_path'], 'files', term, check=False) # FIXME: the original file stuff still needs to be worked out, but the # playbook_dir stuff should be able to be removed as it should # be covered by the fact that the loader con...
sa2ajj/DistroTracker
pts/mail/tests/tests_control.py
Python
gpl-2.0
90,050
0.000233
# -*- coding: utf-8 -*- # Copyright 2013 The Distro Tracker Developers # See the COPYRIGHT file at the top-level directory of this distribution and # at http://deb.li/DTAuthors # # This file is part of Distro Tracker. It is subject to the license terms # in the LICENSE file found in the top-level directory of this # d...
ue): """ Helper method which sets the given value for the given header. :param header_name: The name of the header to set :param header_value: The value of the header to set """
if header_name in self.message: del self.message[header_name] self.message.add_header(header_name, header_value) def set_input_lines(self, lines): """ Sets the lines of the message body which represent sent commands. :param lines: All lines of commands :param...
pkill-nine/qutebrowser
tests/unit/misc/test_readline.py
Python
gpl-3.0
11,925
0
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2014-2017 Florian Bruhin (The Compiler) <mail@qutebrowser.org> # # This file is part of qutebrowser. # # qutebrowser is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free S...
st.mark.parametrize('text, deleted, rest', [ ('delete this| test', 'delete this', '| test'), pytest.param('delete <this> test', 'delete this', '| test', marks=fixme), (
'delete <this> test', 'delete ', '|this test'), # wrong pytest.param('f<oo>bar', 'foo', '|bar', marks=fixme), ('f<oo>bar', 'f', '|oobar'), # wrong ]) def test_rl_unix_line_discard(lineedit, bridge, text, deleted, rest): """Delete from the curso
Ninjakow/TrueSkill
frc_trueskill.py
Python
gpl-3.0
3,512
0.005125
from trueskill import TrueSkill, Rating, rate import argparse import requests from datetime import datetime #from pytba import api as tba class FrcTrueSkill: def __init__(self): self.env = TrueSkill(draw_probability=0.02) self.trueskills = {} self.events = {} self.get_previous_matc...
blue['score'] += 100 if blu
e_stats["kPaRankingPointAchieved"]: blue['score'] += 20 self.update(red['teams'], red['score'], blue['teams'], blue['score'])
DayGitH/Python-Challenges
DailyProgrammer/DP20130422.py
Python
mit
818
0.00489
""" [04/22/13] REMINDER: Week-Long Challenge #1 due today! https://www.reddit.com/r/
dailyprogrammer/comments/1cv8oo/042213_reminder_weeklong_challenge_1_due_today/ Hey r/DailyProgrammers, As a friendly reminder, our first week-long challenge (making a (tiny) video game) concl
udes today, at midnight, here in the American Pacific Time zone (so that's GMT - 7:00). We've got about 6 submissions, so half of all submissions at-this-moment are essentially guaranteed winning already! If enough people post at the last minute, I may extend submissions by a few hours up to 24 hours at most. Don't for...
mapycz/mapnik
plugins/input/gdal/build.py
Python
lgpl-2.1
2,194
0.001823
# # This file is part of Mapnik (c++ mapping toolkit) # # Copyright (C) 2015 Artem Pavlenko # # Mapnik is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your op...
rsion. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General ...
n St, Fifth Floor, Boston, MA 02110-1301 USA # # Import ('plugin_base') Import ('env') from copy import copy PLUGIN_NAME = 'gdal' plugin_env = plugin_base.Clone() plugin_sources = Split( """ %(PLUGIN_NAME)s_datasource.cpp %(PLUGIN_NAME)s_featureset.cpp """ % locals() ) plugin_env['LIBS'] = [] plugin_env....
geoffjay/opendcs-core
examples/minimal.py
Python
lgpl-3.0
353
0.005666
#!/usr/bin/python3 from gi.repository import GLib from gi.re
pository import OpenDCS import sys class DcsExample(object): def __init__(self): self.dcsobject = OpenDCS.Object() self.dcsobject.set_property('id', 'test') print("Object hash: ", self.dcsobject.get_property('hash')) if __name__ == "__main__":
DcsExample()
googleads/google-ads-python
google/ads/googleads/v9/enums/types/change_event_resource_type.py
Python
apache-2.0
1,596
0.000627
# -*- coding: utf-8 -*- # Copyright 2020 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...
= 7 CAMPAIGN_CRITERION = 8 FEED = 9 FEED_ITEM = 10 CAMPAIGN_FEED = 11 AD_GROUP_FEED = 12 AD_GROUP_AD = 13 ASSET = 14 CUSTOMER_ASSET = 15 CAMPAIGN_ASSET =
16 AD_GROUP_ASSET = 17 __all__ = tuple(sorted(__protobuf__.manifest))
debalance/hp
hp/blog/querysets.py
Python
gpl-3.0
1,576
0.003807
# -*- coding: utf-8 -*- # # This file is part of the jabber.at homepage (https://github.com/jabber-at/hp
). # # This project 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 project 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 receive...
kleetus/bitcoin
qa/rpc-tests/wallet.py
Python
mit
13,538
0.006943
#!/usr/bin/env python2 # Copyright (c) 2014-2015 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * class W...
0].listunspent(1) assert_equal(len(node0utxos), 2) # create both transactions txns_to_send = [] for utxo in node0utxos: inputs = [] outputs = {} inputs.append({ "txid" : utxo["txid"], "vout" : utxo["vout"]})
outputs[self.nodes[2].getnewaddress("from1")] = utxo["amount"] - 3 raw_tx = self.nodes[0].createrawtransaction(inputs, outputs) txns_to_send.append(self.nodes[0].signrawtransaction(raw_tx)) # Have node 1 (miner) send the transactions self.nodes[1].sendrawtransaction(txns...
kido113/a-byte-of-python-learning-records
module_using_sys.py
Python
gpl-3.0
127
0.031496
import sys print('The command line arguments are:') f
or i in sys.argv: print(i) print('\n\nThe PYTHONPATH is',sys.path,'\n')
JoePelz/SAM
sam/pages/nodes.py
Python
gpl-3.0
4,239
0.002359
import re import base import sam.models.nodes from sam import errors from sam import common # This class is for getting the child nodes of all nodes in a node list, for the map class Nodes(base.headless_post): """ The expected GET data includes: 'address': comma-seperated list of dotted-decimal IP ad...
data.get('env') request = {'node': node} if alias is not None: request['alias'] = alias if tags is not None: request['tags'] = tags if env is not None: request['env'] = env return request def perform_post_command(self, request): ...
est.pop('node') for key, value in request.iteritems(): if key == 'alias': self.nodesModel.set_alias(node, value) elif key == 'tags': tags = filter(lambda x: bool(x), value.split(',')) self.nodesModel.set_tags(node, tags) elif ke...
skosukhin/spack
var/spack/repos/builtin/packages/gromacs/package.py
Python
lgpl-2.1
3,939
0.000254
############################################################################## # 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...
_DOUBLE:BOOL=ON') if '~shared' in self.spec: options.append('-DBUILD_SHARED_LIBS:BOOL=OFF') if '+cuda' in self.sp
ec: options.append('-DGMX_GPU:BOOL=ON') options.append('-DCUDA_TOOLKIT_ROOT_DIR:STRING=' + self.spec['cuda'].prefix) return options
meng89/hooky
hooky.py
Python
mit
6,757
0.000296
# coding=utf-8 from collections import MutableMapping, Sequence import copy __version__ = '0.5.0' class Hook(object): def _before_add(self, key, item): """ before add a item to the object will call this method. example: obj[key] = item """ def _after_add(self, key, item): ...
ill be here def __setitem__(self, key, item): if key in self.keys(): del self[key] self._before_add(key=key, item=item) self._data[key] = item
self._after_add(key=key, item=item) # all del action will be here def __delitem__(self, key): item = self[key] self._before_del(key=key, item=item) del self._data[key] self._after_del(key=key, item=item) def __iter__(self): return iter(self._data) def __getit...
alien4cloud/alien4cloud-cloudify3-provider
alien4cloud-cloudify3-provider/src/test/resources/outputs/blueprints/openstack/storage/wrapper/LinuxFileSystem_3/tosca.interfaces.node.lifecycle.Standard/start/_a4c_start.py
Python
apache-2.0
15,688
0.004717
from cloudify import ctx from cloudify.exceptions import NonRecoverableError from cloudify.state import ctx_parameters as inputs import subprocess import os import re import sys import time import threading import platform from StringIO import StringIO from cloudify_rest_client import CloudifyClient from cloudify im...
the node {2} instance {3}'.format(attribute_name, prop_value, entity.node.id, node_instance.id)) result_map[node_instance.id + '_'] = prop_value return result_map def get_property(entity, ...
e on the node property_value = entity.node.properties.get(property_name, None) if property_value is not None: ctx.logger.info('Found the property {0} with value {1} on the node {2}'.format(property_name, property_value, entity.node.id)) return property_value # No property found on the node, ...
jcbalmeida/onecloud-store
store/computing/serializers.py
Python
mit
816
0.002451
from rest_framework import serializers from .models import ( Provider, OsFamily, OperatingSystem, Instance, ServerPlan ) class ProviderSerializer(serializers.ModelSerializer): class Meta: model = Provider class OsFamilySerializer(serializers.ModelSerializer): class Meta: ...
mily class OperatingSystemSerializer(serializers.ModelSerializer): family = OsFamilySerializer() class Meta: model = OperatingSystem class InstanceSerializer(serializers.ModelSerializer): operating_system = OperatingSystemSerializer(many=True) class Meta: model = Instance class Se...
class Meta: model = ServerPlan
dgary50/eovsa
adc_plot_og.py
Python
gpl-2.0
8,417
0.022573
import roach as r import struct import numpy as np import matplotlib.pyplot as plt import threading from time import sleep,time from util import Time import matplotlib.animation as animation #set up threading class AGC_Thread (threading.Thread): def __init__(self, threadID): threading.Thread.__...
t self.name+" Execution Time= "+str(time()-start) #display the execution time def grab_all(self): roachname = self.name buf = [] #adc buffer for single slot an channel self.iter_n += 1 fh = open(r...
of data to return in form of [chan,slot,data] done = np.zeros((4,50),bool) #values in done array are true if a given slot and channel have been processed lasttm = time() #last time is needed to ensure proces...
PacketPerception/pyjuggling
tests/siteswap_tests.py
Python
mit
2,919
0.001028
import unittest from juggling.notation import siteswap class SiteswapUtilsTests(unittest.TestCase): def test_siteswap_char_to_int(self): self.assertEqual(siteswap.siteswap_char_to_int('0'), 0) self.assertEqual(siteswap.siteswap_char_to_int('1'), 1) self.assertEqual(siteswap.siteswap_char_...
siteswap.siteswap_int_to_char(9), '9') self.assertEqual(siteswap.siteswap_int_to_char(0), '0') self.assertEqual(siteswap.siteswap_int_to_char(10), 'a') self.assertEqual(siteswap.siteswap_int_to_char(15), 'f
') self.assertEqual(siteswap.siteswap_int_to_char(35), 'z') def test_invalid_int(self): self.assertRaises(ValueError, siteswap.siteswap_int_to_char, ['3']) self.assertRaises(ValueError, siteswap.siteswap_int_to_char, 'a') self.assertRaises(ValueError, siteswap.siteswap_int_to_char, ...
zag2me/plugin.program.video.node.editor
addon.py
Python
gpl-2.0
42,963
0.035451
# coding=utf-8 import os, sys, shutil, unicodedata, re, types from htmlentitydefs import name2codepoint import xbmc, xbmcaddon, xbmcplugin, xbmcgui, xbmcvfs import xml.etree.ElementTree as xmltree import urllib from unidecode import unidecode from urlparse import parse_qs from traceback import
print_exc if sys.version_info < (2, 7): import simplejson else: import json as simplejson __addon__ = xbmcaddon.Addon() __addonid__ = __addon__.getAddonInfo('id').decode( 'utf-8' ) __addonversion__ = __addon__.getAddonInfo('version') __language__ = __addon__.getLocalizedString __cwd__ ...
_cwd__, 'resources', 'lib' ) ).decode("utf-8") __datapath__ = os.path.join( xbmc.translatePath( "special://profile/" ).decode( 'utf-8' ), "addon_data", __addonid__ ) sys.path.append(__resource__) import rules, viewattrib, orderby RULE = rules.RuleFunctions() ATTRIB = viewattrib.ViewAttribFunctions() ORDERBY = ord...
pennersr/django-allauth
allauth/socialaccount/providers/foursquare/provider.py
Python
mit
967
0.001034
from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class FoursquareAccount(ProviderAccount): def get_profile_url(self): return "https://foursquare.com/user/" + self.account.extra_data.get("id") def get_avatar_url...
dflt = super(FoursquareAccount, self).to_str() return self.account.extra_data.get("name", dflt) class FoursquareProvider(OAuth2Provider): id = "foursquare" name = "Foursquare" account_class = FoursquareAccount def extract_uid(self, data): return str(data["id"]
) def extract_common_fields(self, data): return dict( first_name=data.get("firstname"), last_name=data.get("lastname"), email=data.get("contact").get("email"), ) provider_classes = [FoursquareProvider]
e-q/scipy
tools/refguide_check.py
Python
bsd-3-clause
32,497
0.001169
#!/usr/bin/env python """ refguide_check.py [OPTIONS] [-- ARGS] Check for a Scipy submodule whether the objects in its __all__ dict correspond to the objects included in the reference guide. Example of usage:: $ python refguide_check.py optimize Note that this is a helper script to be able to check if things ar...
issing; the output of this script does need to be checked manually. In some cases objects are lef
t out of the refguide for a good reason (it's an alias of another function, or deprecated, or ...) Another use of this helper script is to check validity of code samples in docstrings. This is different from doctesting [we do not aim to have scipy docstrings doctestable!], this is just to make sure that code in docstr...
cctaylor/googleads-python-lib
examples/adwords/v201409/extensions/add_site_links_using_feeds.py
Python
apache-2.0
9,573
0.00491
#!/usr/bin/python # # 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 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 gover...
dd sitelinks using the simpler ExtensionSetting services, see: add_sitelinks.py. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home directory. For more information, see the "Caching authentication information" section of our RE...
CanopyIQ/gmail_client
gmail_client/apis/users_api.py
Python
mit
459,442
0.003489
# coding: utf-8 """ Gmail Access Gmail mailboxes including sending user email. OpenAPI spec version: v1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import sys import os import re # python 2 and python 3 compatibility library fro...
_http_data_only'] = True if kwargs.get('callback'): return self.gmail_users_drafts_create_with_http_info(user_id, **kwargs) else: (data) = self.gmail_users_drafts_create_with_http_info(user_id, **kwargs) return data def gmail_users_drafts_create_with_http_info(se...
hronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.gmail_users_drafts_create_with_http_info(user_id, callback=callback_function) :param ca...
diogo149/simbo
simbo/base/api.py
Python
mit
1,542
0
import abc import json import flask class ApiBase(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def add_feature(self, feature_name, distribution, **kwargs): return @abc.abstractmethod def remove_feature(self, feature_name, **kwargs): return @abc.abstractmethod ...
return json.dumps(result or {}) def start_server(self): app = flask.Flask(__name__) @app.route('/', methods=['POST']) def api_call(): data = flask.request.json print("Received: %s" % data) try: return self.api_dispatch(data) ...
(ApiBase): def add_feature(self, **kwargs): return "foooo" foo = Foo() foo.start_server()
sim0629/irc
irc/tests/test_schedule.py
Python
lgpl-2.1
1,442
0.034674
import random import datetime import pytest from irc import schedule def test_delayed_command_order(): """ delayed commands should be sorted by delay time """ null = lambda: None delays = [random.randint(0, 99) for x in range(5)] cmds = sorted([ schedule.DelayedCommand.after(delay, null) for delay in dela...
eriodic command with a fixed initial delay. """ fd = sch
edule.PeriodicCommandFixedDelay.at_time( at = datetime.datetime.now(), delay = datetime.timedelta(seconds=2), function = lambda: None, ) assert fd.due() == True assert fd.next().due() == False class TestCommands(object): def test_command_at_noon(self): """ Create a periodic command that's run at noon ev...
google/edward2
experimental/attentive_uncertainty/contextual_bandits/pretrain.py
Python
apache-2.0
9,412
0.007969
# coding=utf-8 # Copyright 2022 The Edward2 Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
ction_pairs[perm, :], rewards[perm, :] def get_single_wheel_data(num_datapoints, num_actions, context_dim, delta): """Samples data for a single wheel with default benchmark configuration. Args:
num_datapoints: Number (n) of (context, action, reward) triplets to sample. num_actions: (a) Number of actions. context_dim: (c) Number of dimensions in the context. delta: Exploration parameter: high reward in one region if norm above delta. Returns: context_action_pairs: Sampled (context, action) ...
hmustafamail/digitalimageprocessing
HW 5 - Frequency Filtering/Spatial Filtering/spatialFiltering.py
Python
gpl-2.0
2,087
0.01677
# Mustafa Hussain # Digital Image Processing with Dr. Anas Salah Eddin # FL Poly, Spring 2015 # # Homework 3: Spatial Filtering # # USAGE NOTES: # # Written in Python 2.7 # # Please ensure that the script is running as the same directory as the images # directory! import cv2 import copy #import matplotlib.pyplot as p...
1 * float(image[i + 1][j]) total += -1 * float(image[i][j - 1]) filteredImage[i][j] = total / 9.0 filteredImage = (filteredImage / numpy.max(filteredImage)) * MAX_INTENSITY return filteredImage def saveImage(image, filename): """Saves the image in the output directory with the filename
given. """ cv2.imwrite(OUTPUT_DIRECTORY + filename + IMAGE_FILE_EXTENSION, image) def openImage(fileName): """Opens the image in the input directory with the filename given. """ return cv2.imread(INPUT_DIRECTORY + fileName + IMAGE_FILE_EXTENSION, 0) # Input images inputForSharpening = 'testImage1' # Imp...
horczech/coala-bears
tests/hypertext/HTMLLintBearTest.py
Python
agpl-3.0
863
0
from bears.hypertext.HTMLLintBear import HTMLLintBear from coalib.testing.LocalBearTestHelper import verify_local_bear test_file = """ <html> <body> <h1>Hello, world!</h1> </body> </html> """ HTMLLintBearTest = verify_local_bear(HTMLLintBear, valid_files=(), ...
al_bear( HTMLLintBear, valid_files=(test_file,), invalid_files=(), settings={'htmllint_ignore': 'optional_tag'}, tempfile_kwargs={'suffix': '.html'}) HTMLLintBearIgnoreQuotationTest = verify_local_bear( HTMLLintBear, v
alid_files=(), invalid_files=(test_file,), settings={'htmllint_ignore': 'quotation'}, tempfile_kwargs={'suffix': '.html'})
davidcox/genson
test/test_extra_kwargs.py
Python
mit
225
0.004444
from genson.functions impor
t GridGenerator def test_extra_kwargs(): raised = False try: g = GridGenerator(1, 2, 3, spurious_kwarg=4) except ValueError: raised = True
assert(raised == True)
infobloxopen/heat-infoblox
heat_infoblox/resources/ospf.py
Python
apache-2.0
7,481
0
# Copyright (c) 2016 Infoblox 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 require...
), ADVERTISE_INTERFACE_VLAN: properties.Schema( properties.Schema.STRING, _('The VLAN used as the advertising interface ' 'for sending OSPF announcements.'), update_allowed=True), AREA_ID: properties.Schema( properties.Schema.STRING, ...
pdate_allowed=True, required=True), AREA_TYPE: properties.Schema( properties.Schema.STRING, _('The OSPF area type.'), update_allowed=True, constraints=[ constraints.AllowedValues(AREA_TYPES) ]), AUTHENTICATION_KEY: p...
JacekPierzchlewski/RxCS
examples/signals/gaussNoise_ex1.py
Python
bsd-2-clause
1,774
0.002255
""" This script is an example of how to use the random gaussian noise generator module. |br| In this example only one signal is generated. Both the minimum and the maximum frequency component in the signal is regulated. After the generation, spectrum fo the signal is analyzed with an Welch analysis and ploted. *...
100e3 # Minimum frequency component [100 kHz] gaussNoise.fMax = 200e3 # Maximum frequency component [200 kHz] gaussNoise.run() # ... and run it! vSig = gaussNoise.mSig[0, :] # take the generated signal # ----------------------------------------------------------------- # Analyze t...
12) hFig1 = plt.figure(1) hSubPlot1 = hFig1.add_subplot(111) hSubPlot1.grid(True) hSubPlot1.set_title('Spectrum of the signal (psd)') hSubPlot1.set_xlabel('Frequency [kHz]') hSubPlot1.plot(vFxx/1e3, vPxx, '-') plt.show(block=True) # =========================================================...
artwr/airflow
tests/contrib/operators/test_gcp_sql_operator_system.py
Python
apache-2.0
2,927
0.002392
# -*- coding: utf-8 -*- # # 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 #...
tations # under the License. import os import unittest from airflow import AirflowException from tests.contrib.utils.base_gcp_system_test_case import \ SKIP_TEST_WARNING, DagGcpSystemTestCase from tests.contrib.operators.test_gcp_sql_operator_system_helper import \ CloudSqlQueryTestHelper from tests.contrib.ut...
ST_HELPER = CloudSqlQueryTestHelper() @unittest.skipIf(DagGcpSystemTestCase.skip_check(GCP_CLOUDSQL_KEY), SKIP_TEST_WARNING) class CloudSqlExampleDagsIntegrationTest(DagGcpSystemTestCase): def __init__(self, method_name='runTest'): super(CloudSqlExampleDagsIntegrationTest, self).__init__( meth...
grap/OCB
addons/project/project.py
Python
agpl-3.0
77,400
0.005969
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-today OpenERP SA (<http://www.openerp.com>) # # This program is free software: you can redistribute it and/or modify # it under the terms o...
""", (tuple(ids),)) ids = [t[0] for t in cr.fetchall()] res.update(ids) return list(res) # Deprecated; the _progress_rate method does not use this anymore def _get_project_and_children(self, cr, uid, ids, context=None): """ retrieve all children projects ...
""" res = dict.fromkeys(ids, None) while ids: cr.execute(""" SELECT project.id, parent.id FROM project_project project, project_project parent, account_analytic_account account WHERE project.analytic_account_id = account.id ...
Teamxrtc/webrtc-streaming-node
third_party/webrtc/src/chromium/src/build/protoc_java.py
Python
mit
2,330
0.009013
#!/usr/bin/env python # Copyright (c) 2012 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. """Generate java source files from protobuf files. This is a helper file for the genproto_java action in protoc_java.gypi. It per...
protoc, '--proto_path', options.proto_path, out_arg] + args) if options.java_out_dir: build_utils.DeleteDirectory(options.java_out_dir) shutil.copytree(temp_dir, options.java_out_dir) else: build_utils.ZipDir(options.srcjar, temp_dir) if options.depfile: build_utils.WriteDepfil...
honDependencies()) if options.stamp: build_utils.Touch(options.stamp) if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
sdgdsffdsfff/monitor-core
gmond/python_modules/memcached/memcached.py
Python
bsd-3-clause
13,648
0.010111
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import traceback import os import threading import time import socket import select descriptors = list() Desc_Skel = {} _Worker_Thread = None _Lock = threading.Lock() # synchronization lock Debug = False def dprint(f, *v): if Debug: print >>sys.s...
"units" : "items", "slope" : "positive", "description": "Number of keys that have been deleted and found present ", })) descriptors.append(create_desc(Desc_Skel, { "name" : mp+"_delete_misses", "units" : "it...
"description": "Number of items that have been deleted and not found", })) descriptors.append(create_desc(Desc_Skel, { "name" : mp+"_evictions", "units"
DannySapz/is210-week-04-warmup
task_05.py
Python
mpl-2.0
285
0
#!/usr/bin/
env python # -*- coding: utf-8 -*- """task 05""" def defaults(my_required, my_optional=True): """1. ``my_optional`` which has a default value of True 2. ``my_required`` which is a required param and has no default value""" return my_optional is my_req
uired
e-gob/plataforma-kioscos-autoatencion
scripts/ansible-play/.venv/lib/python2.7/site-packages/ansible/plugins/lookup/redis_kv.py
Python
bsd-3-clause
2,846
0.003514
# (c) 2012, Jan-Piet Mens <jpmens(at)gmail.com> # (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = """ lookup: redis_kv author: Jan-Piet M...
l of the Redis server and key to query options: _url: description: location of redis host in url format default: 'redis://localhost:6379' _key: description: key to query required: True """ EXAMPLES = """ - name: query redis for somekey debug...
n Redis """ import os import re HAVE_REDIS = False try: import redis HAVE_REDIS = True except ImportError: pass from ansible.errors import AnsibleError from ansible.plugins.lookup import LookupBase # ============================================================== # REDISGET: Obtain value from a GET on a ...
ishay2b/tensorflow
tensorflow/python/kernel_tests/variable_scope_test.py
Python
apache-2.0
48,184
0.009298
# 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 applica...
vs.get_variable("v", [1]) self.assertEqual(v, v1) def testResource(self): vs = variable_scope._get_default_variable_store() v1 = vs.get_variable("v", [1], use_resource=True) self.assertTrue(isinstance(v1, resource_variable_ops.ResourceVariable)) def testNameExists(self): vs = variable_scope._g...
we can both create and get existing names. v = vs.get_variable("v", [1]) v1 = vs.get_variable("v", [1]) self.assertEqual(v, v1) # When reuse is False, we fail when variables are already there. vs.get_variable("w", [1], reuse=False) # That's ok. with self.assertRaises(ValueError): vs.get_v...
harikishen/addons-server
src/olympia/migrations/532-unleash-payments-in-usa.py
Python
bsd-3-clause
266
0
from olympia import amo import mkt from mkt.webapps.models import AddonExcludedRegion def run():
"""Unleash payments in USA.""" (AddonExcludedRegion.objects .exclude(addon__premium_type=amo.ADDON_FREE) .filter(region=mkt.regions.US.
id).delete())
intelligent-agent/redeem
redeem/Stepper.py
Python
gpl-3.0
15,869
0.01002
#!/usr/bin/env python """ A Stepper Motor Driver class for Replicape. Author: Elias Bakken email: elias(dot)bakken(at)gmail(dot)com Website: http://www.thing-printer.com License: GNU GPL v3: http://www.gnu.org/copyleft/gpl.html Redeem is free software: you can redistribute it and/or modify it under the terms of the...
return self.state & 0xFF # Return the state of the serial to parallel def update(self): """ Commits the changes """ ShiftRegister.commit() # Commit the serial to parallel # Higher level commands def set_steps_pr_mm(self, steps_pr_mm): """ Set the number of steps pr mm. """ self.steps_pr_mm...
mm * self.microsteps * 1000.0 def get_step_bank(self): """ The pin that steps, it looks like GPIO1_31 """ return int(self.step_pin[4:5]) def get_step_pin(self): """ The pin that steps, it looks like GPIO1_31 """ return int(self.step_pin[6:]) def get_dir_bank(self): """ Get the dir pin shift...
joseamaita/guiprog-python
wxpython/files/generictable.py
Python
lgpl-3.0
787
0.001271
import wx import wx.grid class GenericTable(wx.grid.GridTableBase): def __init__(self, data, rowLabels=None, colLabels=None): wx.grid.GridTableBase.__init__(self) self.data = data self.rowLabels = rowLabels self.colLabels = colLabels def GetNumberRows(self): return len...
if self.colLabels: return self.colLabels[col] def GetRowLabelValue(self, row): if self.rowLabels: return self.rowLabels[row] def IsEmptyCell(self, row, col):
return False def GetValue(self, row, col): return self.data[row][col] def SetValue(self, row, col, value): pass
monouno/site
judge/widgets/select2.py
Python
agpl-3.0
7,832
0.001149
# -*- coding: utf-8 -*- """ Select2 Widgets based on https://github.com/applegrew/django-select2. These components are responsible for rendering the necessary HTML data markups. Since this whole package is to render choices using Select2 JavaScript library, hence these components are meant to be used with choice field...
def build_attrs(self, base_attrs, extra_attrs=None): """Add select2's tag attributes."""
extra_attrs = extra_attrs or {} extra_attrs.setdefault('data-minimum-input-length', 1) extra_attrs.setdefault('data-tags', 'true') extra_attrs.setdefault('data-token-separators', [",", " "]) return super(Select2TagMixin, self).build_attrs(base_attrs, extra_attrs) class Select2Widget...
artscoop/django-basemix
basemix/mixins/content/content.py
Python
bsd-3-clause
1,190
0.002521
# coding: utf-8 from django.db import models from django.
utils.translation import ugettext_lazy as _, pgettext_lazy class ContentBase(models.Model): """ Base class for models that share content attributes The attributes added by this mixin are ``title``, ``description``, ``content`` and ``is_visible``. Attributes: :is_visible: whether the cont...
ontent objects have a description, with an unlimited size :content: actual content of the object, with an unlimited size """ # Fields is_visible = models.BooleanField(default=True, verbose_name=pgettext_lazy('content', "visible")) title = models.CharField(blank=False, max_length=192, verbose_na...
Aalto-LeTech/a-plus-rst-tools
directives/annotated.py
Python
mit
15,406
0.00767
# -*- coding: utf-8 -*- import docutils from docutils import nodes from docutils.parsers.rst import Directive, directives from html import escape from collections import Counter import re import os from sphinx.directives.code import CodeBlock from sphinx.errors import SphinxError from sphinx.util.fileutil import copy_a...
ment): pass class Annotation(Directive): has_content = True required_arguments = 0 optional_arguments = 1 final_argument_whitespace = True option_spec = { } def run(self): self.assert_has_content() env = self.state.document.settings.env if not env.annotated_now_within...
e() self.state.nested_parse(self.content, 0, node) env.annotated_annotation_count += 1 node['annotation-number'] = env.annotated_annotation_count node['name-of-annotated-section'] = env.annotated_name if self.arguments: node['replacement'] = self.arguments[0] ...
pybuilder/pybuilder
src/main/python/pybuilder/_vendor/pkg_resources/_vendor/packaging/markers.py
Python
apache-2.0
8,485
0.000236
# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. import operator import os import platform import sys from typing import Any, Callable, Dict, List, Optional, Tuple, Union from ...extern.p...
s in rhs, "not in": lambda lhs, rhs: lhs not in rhs, "<": operator.lt, "<=": operator.le, "==": operator.eq, "!=": operator.ne, ">=": operator.ge, ">": operator.gt, } def _eval_op(lhs: str, op: Op, rhs: str) -> bool: try: spec = Specifier("".join([op.serialize(), rhs])) exc...
lhs) oper: Optional[Operator] = _operators.get(op.serialize()) if oper is None: raise UndefinedComparison(f"Undefined {op!r} on {lhs!r} and {rhs!r}.") return oper(lhs, rhs) class Undefined: pass _undefined = Undefined() def _get_env(environment: Dict[str, str], name: str) -> str: val...
eickenberg/scikit-learn
sklearn/dummy.py
Python
bsd-3-clause
14,149
0
# Author: Mathieu Blondel <mathieu@mblondel.org> # Arnaud Joly <a.joly@ulg.ac.be> # Maheshakya Wijewardena<maheshakya.10@cse.mrt.ac.lk> # License: BSD 3 clause from __future__ import division import numpy as np from .base import BaseEstimator, ClassifierMixin, RegressorMixin from .externals.six.moves ...
classes_] class_prior_ = [class_prior_] constant = [constant] # Compute probability only once if self.strategy == "stratified": proba = self.predict_proba(X) if self.n_outputs_ == 1:
proba = [proba] y = [] for k in xrange(self.n_outputs_): if self.strategy == "most_frequent": ret = np.ones(n_samples, dtype=int) * class_prior_[k].argmax() elif self.strategy == "stratified": ret = proba[k].argmax(axis=1) ...
anguoyang/SMQTK
OLD_ROOT/WebUI/QueryRecommend/query_recommend.py
Python
bsd-3-clause
7,183
0.002088
""" LICENCE ------- Copyright 2013 by Kitware, Inc. All Rights Reserved. Please refer to KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. """ import os import numpy as np import json thispath = os.path.dirname(os.path.abs...
es['E007'] = 'sc.transporting sc.manmade sc.using_tools sc.asphalt ob.round_shape ob.car' queries['E008'] = 'sc.congregating sc.has_audience ob.person sc.pavement' \ ' ob.large_group_of_people ob.crowd ob.small_group_of_people ob.railing ob.floor' queries['E009'] = 'sc.dirty sc.natural_light sc.nat...
' ob.truck ob.car ob.large_open_area ob.outdoor' queries['E010'] = 'sc.working sc.dirty sc.enclosed_area' queries['E011'] = 'sc.enclosed_area sc.wood_not_part_of_tree sc.electric_or_indoor_lighting' queries['E012'] = 'sc.congregating sc.has_audience sc.asphalt sc.pavement' \ ' ob.person ob.large_g...
KellyChan/python-examples
python/data_science/Titanic/complexHeuristic.py
Python
mit
2,546
0.007463
import numpy import pandas import statsmodels.api as sm def complex_heuristic(file_path): ''' You are given a list of Titantic passengers and their associating information. More information about the data can be seen at the link below: http://www.kaggle.com/c/titanic-gettingStarted/data For this e...
nger via passenger['Age']. Write your prediction back into the "predictions" dictionary. The key of the dictionary should be the Passenger's id (which can be accessed via passenger["PassengerId"]) and the associati
ng value should be 1 if the passenger survied or 0 otherwise. For example, if a passenger survived: passenger_id = passenger['PassengerId'] predictions[passenger_id] = 1 Or if a passenger perished in the disaster: passenger_id = passenger['PassengerId'] predictions[passenger_id] = 0 ...
wking/pygrader
pygrader/email.py
Python
gpl-3.0
10,392
0.000771
# -*- coding: utf-8 -*- # Copyright (C) 2012 W. Trevor King <wking@tremily.us> # # This file is part of pygrader. # # pygrader 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, o...
append(author.pgp_key) message = _pgp_mime.sign_and_encrypt( message=message,
signers=signers, recipients=recipients, always_trust=True) elif signers: message = _pgp_mime.sign(message=message, signers=signers) elif encrypt: message = _pgp_mime.encrypt(message=message, recipients=recipients) message['Date'] = _email_utils.formatdate() message['From'] ...
nijel/weblate
weblate/addons/autotranslate.py
Python
gpl-3.0
2,345
0.000427
# # Copyright © 2012–2022 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <https://weblate.org/> # # 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 Licens...
ion") description = _( "Automatically translates strings using machine translation or " "other components." ) settings_form = AutoAddonForm multiple = True
icon = "language.svg" def component_update(self, component): transaction.on_commit( lambda: auto_translate_component.delay( component.pk, **self.instance.configuration ) ) def daily(self, component): # Translate every component less frequenc...
szha/mxnet
python/mxnet/gluon/probability/distributions/cauchy.py
Python
apache-2.0
2,935
0.000681
# 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...
. See the License for the # specific language governing permissions and limitations # under the License. # coding: utf-8 # pylint: disable=wildcard-import """Cauchy distribution""" __all__ = ['Cauchy
'] from numbers import Number from numpy import nan, pi from .constraint import Real from .distribution import Distribution from .utils import sample_n_shape_converter from .... import np class Cauchy(Distribution): r"""Create a relaxed Cauchy distribution object. Parameters ---------- loc : Tensor ...
kanarinka/UFOScraper
scrape.py
Python
gpl-2.0
3,948
0.007345
import logging, sys, os, codecs import requests, cache, csv from bs4 import BeautifulSoup BASE_URL = "http://www.nuforc.org/webreports/" # needed to reconstruct relative URLs START_PAGE = "ndxshape.html" # uses shape page because least # requests to get all the data BASE_DIR = os.path.dirname(os.path.abspath(...
# set up logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) # let's scrape url = BASE_URL + START_PAGE logger.info("Scraping UFO reports from %s" % url) #
first grab the index page if not cache.contains(url): index_page = requests.get(url) logger.debug("\tadded to cache from %s" % url) cache.put(url, index_page.text) content = cache.get(url) # now pull out all the links to songs dom = BeautifulSoup(content) #/html/body/p/table/tbody/tr[1]/td[1]/fo...
jumpstarter-io/keystone
keystone/tests/unit/test_v3_credential.py
Python
apache-2.0
16,723
0
# Copyright 2013 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 or agreed to in...
tial_id = self._create_dict_blob_credential() list_r = self.get('/credentials') list_creds = list_r.result['credentials'] list_ids = [r['id'] for r in list_creds] self.assertIn(credential_id, list_ids) for r in list_creds: if r['id'] == credential_id: ...
def test_create_non_ec2_credential(self): """Call ``POST /credentials`` for creating non-ec2 credential.""" ref = self.new_credential_ref(user_id=self.user['id']) blob = {"access": uuid.uuid4().hex, "secret": uuid.uuid4().hex} ref['blob'] = json.dumps(blob) ...
liuhong1happy/DockerConsoleApp
views/login.py
Python
apache-2.0
2,538
0.019429
#!/usr/bin/env python # -*- coding: utf-8 -*- from services.user import UserService import tornado.web import tornado.gen import tornado.escape import json import settings from util.stmp import send_email from views import BaseHandler class LoginHandler(tornado.web.RequestHandler): def get(self): self.rend...
ields) if not user: self.render_error(error_code=404,msg='signup failed') else: self.write_result(data=user) class ForgetHandler(BaseHandler): s_user = UserService() @tornado.web.asynchronous @tornado.gen.coroutine def post(self): ...
user =yield self.s_user.forget(email) # 发送邮件 send_email() if not user: self.write_result(msg='user not exist') else: self.write_result(data=user)
heikoheiko/pyethapp
pyethapp/jsonrpc.py
Python
bsd-3-clause
41,771
0.001077
import time from copy import deepcopy from decorator import decorator from collections import Iterable import inspect import ethereum.blocks from ethereum.utils import (is_numeric, is_string, int_to_big_endian, big_endian_to_int, encode_hex, decode_hex, sha3, zpad) import ethereum.slogging a...
'result'): self.logger('RPC result', id=res.unique_id, result=res.result) else: self.logger('RPC error', id=res.unique_id, error=res.error) return response class JSONRPCServer(BaseService): """Service providing an HTTP server with JSON RPC interface. Other...
tively :attr:`dispatcher` can be extended directly (see https://tinyrpc.readthedocs.org/en/latest/dispatch.html). """ name = 'jsonrpc' default_config = dict(jsonrpc=dict(listen_port=4000, listen_host='127.0.0.1')) @classmethod def subdispatcher_classes(cls): return (Web3, Net, Compiler...
vayan/external-video
app/mpv.py
Python
mit
487
0
#!/usr/bin/env python2 import sys import json import struct import subprocess import shlex def getMessage(): rawLength = sys.stdin.read(4) if len(rawLength) == 0: sys.exit(0) messageLength = struct.unpack('@I', rawLength)[0] message = sys.stdin.read(messageLength) return json.loads(messag...
True: mpv_args = getMessage() if len(mpv_args) > 1: args = shlex.split("mpv " + mpv_args) subprocess.call(args)
sys.exit(0)