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 |
|---|---|---|---|---|---|---|---|---|
denizalti/concoord | concoord/proxygenerator.py | Python | bsd-3-clause | 3,595 | 0.008345 | '''
@author: Deniz Altinbuken, Emin Gun Sirer
@note: Proxy Generator that creates ConCoord proxy files from regular Python objects.
@copyright: See LICENSE
'''
import codegen
import ast, _ast
import os, shutil
import inspect, types, string
from concoord.enums import PR_BASIC, PR_BLOCK, PR_CBATCH, PR_SBATCH
class Proxy... | nit__":
pass
else:
args = ["\'"+ node.name +"\'"]+[i.id for i in node.args.args[1:]]
node. | body = compile("return self.proxy.invoke_command(%s)" % ", ".join(args),
"<string>",
"exec",
_ast.PyCF_ONLY_AST).body
return node
else:
return self.generic_visit(node)
def createc... |
CommonsCloud/Core-API | CommonsCloudAPI/models/oauth.py | Python | agpl-3.0 | 2,810 | 0.000712 | """
For CommonsCloud copyright information please see the LICENSE document
(the "License") included with this software package. This file may not
be used in any manner except in compliance with the License
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed ... | _redirect_uris.split()
return []
@property
def default_redirect_uri(self):
return self.redirect_uris[0]
@property
def default_scopes(self):
if self._default_scopes:
return self._default_scopes.split()
return []
class Grant(db.Model):
id = db.Column(db.... | ASCADE')
)
user = db.relationship('User')
client_id = db.Column(
db.String(40), db.ForeignKey('client.client_id'),
nullable=False,
)
client = db.relationship('Client')
code = db.Column(db.String(255), index=True, nullable=False)
redirect_uri = db.Column(db.String(255))
... |
luofei98/qgis | python/plugins/processing/algs/qgis/ftools/PointDistance.py | Python | gpl-2.0 | 7,944 | 0.001385 | # -*- coding: utf-8 -*-
"""
***************************************************************************
PointDistance.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
*************************... | rget unique ID field', self.TARGET_LAYER,
ParameterTableField.DATA_TYPE_ANY))
self.addParameter(ParameterSelection(self.MATRIX_TYPE,
'Output matrix type', self.MAT_TYPES, 0))
self.addParameter(ParameterNumber(self.NEAREST_POINTS,
... | e matrix'))
def processAlgorithm(self, progress):
inLayer = dataobjects.getObjectFromUri(
self.getParameterValue(self.INPUT_LAYER))
inField = self.getParameterValue(self.INPUT_FIELD)
targetLayer = dataobjects.getObjectFromUri(
self.getParameterValue(self.TARG... |
mava-ar/sgk | src/dj_auth/urls.py | Python | apache-2.0 | 1,618 | 0.003708 | from django.urls import path, re_path
from django.conf import settings
from django.contrib.auth import views as auth_views
urlpatterns = [
re_path(
'login/',
auth_views.LoginView.as_view(template_name='dj_auth/login.html'),
name='login'),
re_path(
'logout/',
auth_views.... | ordResetConfirmView.as_view(template_name='dj_auth/password_reset_confirm.html'),
name='password_reset_confirm'),
re_path(
r'^reset/done/$',
auth_views.PasswordResetCompleteView.as_view(template_name='dj_auth/password_reset_complete.html'),
name='password_reset_complete'),
re_pat... | as_view(template_name='dj_auth/password_change_form.html'),
name='password_change'),
re_path(
r'^password_change/done/$',
auth_views.PasswordChangeDoneView.as_view(template_name='dj_auth/password_change_done.html'),
name='password_change_done'),
]
|
marmyshev/item_title | openlp/core/ui/slidecontroller.py | Python | gpl-2.0 | 62,270 | 0.002955 | # -*- coding: utf-8 -*-
# vim: autoindent shiftwidth=4 expandtab textwidth=120 tabstop=4 softtabstop=4
###############################################################################
# OpenLP - Open Source Lyrics Projection #
# ------------------------------------------------------... | on, MA 02111-1307 USA #
###############################################################################
"""
The :mod:`slidecontroller` module contains the most important part of OpenLP - the slide controller
"""
import os
import logging
import copy
from collections import deque
from PyQt4 imp... | nList, build_icon, build_html, translate
from openlp.core.ui import HideMode, MainDisplay, Display, DisplayControllerType
from openlp.core.lib.ui import create_action
from openlp.core.utils.actions import ActionList, CategoryOrder
from openlp.core.ui.listpreviewwidget import ListPreviewWidget
log = logging.getLogger(_... |
hilaglanz/TCE | articles/A_evolve_outer_star_to_giant.py | Python | gpl-2.0 | 1,405 | 0.008541 | import os
import os.path
from amuse.units import units
from amuse.datamodel import Particle
from amuse.ext.star_to_sph import pickle_stellar_model
from amuse.community.mesa.interface i | mport MESA as stellar_evolution_code
from xiTau_parameters import triple_parameters
def evolve_giant(giant, stop_radius):
stellar_evolution = stellar_evolution_code()
giant_in_code = stellar_evolution.particles.add_particle(giant)
while (giant_in_code.radius < 0.7 | units.AU):
| giant_in_code.evolve_one_step()
print "Giant starts to ascend the giant branch, now saving model every step..."
print giant_in_code.as_set()
i = 0
while (giant_in_code.radius < stop_radius):
giant_in_code.evolve_one_step()
print giant_in_code.radius, giant_in_code.age
... |
hzlf/openbroadcast.org | website/apps/profiles/migrations/0002_auto_20200220_1430.py | Python | gpl-3.0 | 872 | 0.002294 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import tagging.fields
class Migration(migrations.Migration):
dependencies = [
('profiles', | '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='community',
name='d_tags',
),
migrations.RemoveField(
model_name='profile',
name='d_tags',
),
migrations.AddField(
model_name='community',
... | ield(
model_name='profile',
name='skype',
field=models.CharField(max_length=100, null=True, verbose_name='Skype', blank=True),
),
]
|
hlieberman/ansible-modules-core | cloud/docker/docker_login.py | Python | gpl-3.0 | 9,366 | 0.002669 | #!/usr/bin/python
#
# (c) 2016 Olaf Kilian <olaf.kilian@symanex.com>
# Chris Houseknecht, <house@redhat.com>
# James Tanner, <jtanner@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 ... | '
import base64
from ansible.module_utils.docker_common import *
class LoginManager(DockerBaseClass):
def __init__(self, client, results):
super(LoginManager, self).__init__()
self.client = client
self.results = results
| parameters = self.client.module.params
self.check_mode = self.client.check_mode
self.registry_url = parameters.get('registry_url')
self.username = parameters.get('username')
self.password = parameters.get('password')
self.email = parameters.get('email')
self.reau... |
reinbach/django-machina | machina/apps/forum_conversation/utils.py | Python | bsd-3-clause | 375 | 0 | # -*- | coding: utf-8 -*-
from __future__ import unicode_literals
def get_client_ip(request):
"""
Given an HTTP request, returns the related IP address. |
"""
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR', None)
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
return ip
|
sternshus/Arelle | arelle/ModelObjectFactory.py | Python | apache-2.0 | 8,302 | 0.006384 | '''
Created on Jun 10, 2011
Refactored on Jun 11, 2011 to ModelDtsObject, ModelInstanceObject, ModelTestcaseObject
@author: Mark V Systems Limited
(c) Copyright 2011 Mark V Systems Limited, All rights reserved.
'''
from arelle.ModelObject import ModelObject, init as moduleObject_init
elementSubstitutionModelClass = {... | self.modelXbrl = modelXbrl
self.streamingOrSkipDTS = modelXbrl.skipDTS or getattr(modelXbrl, "isStreamingMode", False)
self.baseUrl = baseUrl
self.discoveryAttempts = set()
global ModelFact, ModelDocument
if ModelDocument is None:
from arelle import ModelDocument
... | from arelle.ModelInstanceObject import ModelFact
def lookup(self, document, proxyElement):
# check if proxyElement's namespace is not known
ns, sep, ln = proxyElement.tag.partition("}")
if sep:
ns = ns[1:]
else:
ln = ns
ns = None
... |
quantmind/pulsar | pulsar/apps/wsgi/wrappers.py | Python | bsd-3-clause | 13,989 | 0 | """This section introduces classes used by pulsar
:ref:`wsgi application <apps-wsgi>` to pass a request/response state
during an HTTP request.
.. contents::
:local:
The :class:`WsgiRequest` is a thin wrapper around a WSGI ``environ``
dictionary.
It contains only the ``environ`` as its private data.
The :class:`Ws... | , create_future
from pulsar.utils.lib import WsgiResponse, wsgi_cached
from pulsar.utils.system import json
from pulsar.utils.httpurl import (
REDIRECT_CODES, ENCODE_URL_METHODS,
remove_double_slash, iri_to_uri, is_absolute_uri, parse_options_heade | r
)
from .content import HtmlDocument
from .utils import (set_wsgi_request_class, query_dict,
parse_accept_header, LOGGER, PULSAR_CACHE)
from .structures import ContentAccept, CharsetAccept, LanguageAccept
from .formdata import parse_form_data
from .headers import LOCATION
HEAD = 'HEAD'
MAX_BUFFE... |
androidarmv6/android_external_chromium_org | tools/telemetry/telemetry/core/backends/chrome/cros_browser_with_oobe.py | Python | bsd-3-clause | 698 | 0.007163 | # Copyrig | ht 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# | found in the LICENSE file.
from telemetry.core import browser
from telemetry.core.backends.chrome import cros_browser_backend
class CrOSBrowserWithOOBE(browser.Browser):
"""Cros-specific browser."""
def __init__(self, backend, platform_backend):
assert isinstance(backend, cros_browser_backend.CrOSBrowserBack... |
leleuj/cas | etc/loadtests/locust/cas5/bothLocust.py | Python | apache-2.0 | 9,997 | 0.0015 | from __future__ import print_function
import csv
import os
import random
import re
import urllib3
from urllib.parse import parse_qs, urlparse, unquote, urlencode, quote
from locust import HttpLocust, TaskSet, task, TaskSequence, seq_task, between
# SAML IdP Host
HOST = "https://axman000.local:8443"
# Run weighting f... | erify=False,
allow_redirects=False)
cas_response_url = cas_login_response.next.url
url_query = unquote(urlparse(cas_response_url).query)
cas_parsed_url = par | se_qs(url_query)
if 'ticket' in cas_parsed_url:
cas_ticket = cas_parsed_url['ticket'][0]
else:
print("CAS No Ticket found in returned form!")
self.interrupt()
print("Validating service ticket ...")
ticket_response = client.... |
flgiordano/netcash | +/google-cloud-sdk/lib/googlecloudsdk/api_lib/functions/cloud_storage.py | Python | bsd-3-clause | 1,984 | 0.006552 | # Copyright 2015 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 ag... | a full path to gsutil tool
"""
sdk_bin_path = config.Paths().sdk_bin_path
if not sdk_bin_path:
sdk_bin_path = ''
gsutil_file = os.path.join(sdk_bin_path, 'gsutil')
if platforms.OperatingSystem.Current() == platforms.OperatingSystem.WINDOWS:
gsutil_file += '.cmd'
ret | urn gsutil_file
def _RunGsutilCommand(gsutil_args):
"""Run a gsutil command.
Args:
gsutil_args: The list of arguments to pass to gsutil.
Returns:
The exit code of the call to the gsutil command.
"""
args = execution_utils.ArgsForBinaryTool(_GetGsutilPath(), *gsutil_args)
return execution_utils.E... |
SymbiFlow/edalize | tests/edalize_common.py | Python | bsd-2-clause | 8,229 | 0.000365 | from collections import OrderedDict
import os.path
import shutil
import pytest
from edalize import get_edatool
tests_dir = os.path.dirname(__file__)
class TestFixture:
"""A fixture that makes an edalize backend with work_root directory
Create this object using the make_edalize_test factory fixture. This ... | The directory to treat as a work root
test_name: The name to call the backend. Defaults to
`'test_<tool_name>_0'`
param_types: A list of parameter types. Defaults to `['plusarg',
'vlogdefine', 'vlogparam']` (the parameter types supported
by m... | e`, which means to use
:py:data:`FILES`.
tool_options: Dictionary passed to _setup_backend. Defaults to `{}`.
ref_dir: A reference directory relative to `test_<tool_name>`. Defaults
to `'.'`
use_vpi: If true, set up backend with definitions from :attr:`VPI`.
... |
noashin/Ising_model_gibbs_sampler | sampler_no_sparsity.py | Python | mit | 2,260 | 0.000885 | import numpy as np
import pypolyagamma as pypolyagamma
def calculate_D(S):
N = S.shape[1]
D = np.empty((N, N))
for i in range(N):
for j in range(N):
D[i, j] = np.dot(S[1:, i].T, S[:-1, j])
return D * 0.5
def calculate_C_w(S, w_i):
w_mat = np.diag(w_i)
return np.dot(S.... | ngs
:return: samples for w_i from a polyagamma distribution
"""
ppg = pypolyagamma.PyPolyaGamma(np.random.randint(2 ** 16))
T = S.shape[0]
A = np.ones(T)
w_i = np.zeros(T)
ppg.pgdrawv(A, np.dot(S, J_i), w_i)
return w_i
def sample_J_i(S, C, D_i, w_i, sigma_J):
N = S.shape[1]
... |
def sample_neuron(samp_num, burnin, sigma_J, S, D_i, ro, thin=0, save_all=True):
""" This function uses the Gibbs sampler to sample from w, gamma and J
:param samp_num: Number of samples to be drawn
:param burnin: Number of samples to burn in
:param sigma_J: variance of the J slab
:param S: Neuro... |
cloudbase/coriolis | coriolis/endpoints/api.py | Python | agpl-3.0 | 2,592 | 0.000772 | # Copyright 2016 Cloudbase Solutions Srl
# All Rights Reserved.
from coriolis import utils
from coriolis.conductor.rpc import client as rpc_conductor_client
from coriolis.minion_manager.rpc import client as rpc_minion_manager_client
class API(object):
def __init__(self):
self._rpc_conductor_client = rpc_... | connection_info, mapped_regions):
return self._rpc_conductor_client.create_endpoint(
ctxt, name, endpoint_type, description, connection_info,
mapped_regions)
def update(self, ctxt, endpoint_id, properties):
return self._rpc_conductor_client.update_endpoint(
... | f, ctxt):
return self._rpc_conductor_client.get_endpoints(ctxt)
def get_endpoint(self, ctxt, endpoint_id):
return self._rpc_conductor_client.get_endpoint(ctxt, endpoint_id)
def validate_connection(self, ctxt, endpoint_id):
return self._rpc_conductor_client.validate_endpoint_connection(... |
memsharded/conan | conans/test/unittests/client/tools/system_pm_test.py | Python | mit | 21,011 | 0.003332 | import mock
import platform
import six
import unittest
from six import StringIO
from conans import tools
from conans.client.output import ConanOutput
from conans.client.tools.files import which
from conans.client.tools.oss import OSInfo
from conans.client.tools.system_pm import ChocolateyTool, SystemPackageTool,\
... | runner = RunnerMock()
# fake os info to linux debian, default sudo
os | _info = OSInfo()
os_info.is_macos = False
os_info.is_linux = True
os_info.is_windows = False
os_info.linux_distro = "debian"
spt = SystemPackageTool(runner=runner, os_info=os_info, output=self.out)
spt.update()
self.assertEqual(runner.c... |
rbastic/glowing-tyrion | dotvim/.vim/bundle/ultisnips/pythonx/UltiSnips/snippet/source/file/snipmate.py | Python | mit | 4,070 | 0.002457 | #!/usr/bin/env python
# encoding: utf-8
"""Parses snipMate files."""
import os
import glob
from UltiSnips import _vim
from UltiSnips.snippet.definition import SnipMateSnippetDefinition
from UltiSnips.snippet.source.file._base import SnippetFileSource
from UltiSnips.snippet.source.file._common import handle_extends
f... | efin | tions."""
start_line_index = lines.line_index
trigger, description = head_tail(line[len("snippet"):].lstrip())
content = ""
while True:
next_line = lines.peek()
if next_line is None:
break
if next_line.strip() and not next_line.startswith('\t'):
break
... |
jakespringer/lostexhaust-v2 | api/lostexhaust/actions/authentication.py | Python | lgpl-3.0 | 1,285 | 0.006226 | import re, os, M2Crypto, base64, util
import lostexhaust.config as config
rsakey = M2Crypto.RSA.load_pub_key(os.path.join(config.get('rootDir'), config.get("catlinRsaPemFile")))
def check_token_validity(token, ip, timestamp):
parsed = parse_token(decrypt_rsa(token))
if parsed is None:
return False
... | one
else:
return tuple(tokens)
def get_person_from_token(token):
parsed = parse_token(decrypt_rsa(token))
if parsed is None:
return None
else:
(parsed_person_id, parsed_timestamp, parsed_ip) = parsed
return parsed_person_ | id
|
GoogleCloudPlatform/sap-deployment-automation | third_party/github.com/ansible/awx/awx/main/migrations/0056_v350_custom_venv_history.py | Python | apache-2.0 | 879 | 0.002275 | # -*- coding | : utf-8 -*-
# Generated by Django 1.11.16 on 2019-01-22 22:20
fro | m __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0055_v340_add_grafana_notification'),
]
operations = [
migrations.AddField(
model_name='inventoryupdate',
name='custom_... |
ChinaMassClouds/copenstack-server | openstack/src/nova-2014.2/nova/api/openstack/compute/plugins/v3/deferred_delete.py | Python | gpl-2.0 | 3,037 | 0.000329 | # Copyright 2011 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in com | pliance 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
# W | ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""The deferred instance delete extension."""
import webob
from nova.api.openstack import common
from nova.api.openstack import extensions
from ... |
coufon/neon-distributed | examples/cifar10.py | Python | apache-2.0 | 2,183 | 0.001374 | #!/usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright 2015 Nervana Systems Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# ... | ing_rate=0.01, momentum_coef=0.9)
# set up the model layers
layers = [Affine(nout=200, init=init_uni, activation=Rectlin()),
Affine(nout=10, init=init_uni, activation=Logistic(shortcut=True))]
cost = GeneralizedCost(costfunc=CrossEntropyBinary())
mlp = Model(layers=layers)
# configure callbacks
callbacks ... | num_epochs=args.epochs, cost=cost, callbacks=callbacks)
print('Misclassification error = %.1f%%' % (mlp.eval(test, metric=Misclassification())*100))
|
kbase/transform | t/demo/bin/convert_test.py | Python | mit | 7,352 | 0.006529 | #!/usr/bin/env python
import sys
import os
import datetime
import argparse
import blessings
import simplejson
import biokbase.Transform.Client
import biokbase.Transform.script_utils
import biokbase.Transform.drivers
import biokbase.userandjobstate.client
import biokbase.workspace.client
if __name__ == "__main__":... | he source workspace' | , const="", default="gavinws")
parser.add_argument('--source_object_name', nargs='?', help='name of the workspace object', const="", default="")
parser.add_argument('--destination_kbase_type', nargs='?', help='the kbase object type to create')
parser.add_argument('--destination_workspace_name', nargs='?', ... |
zorna/zorna | zorna/search/search_sites.py | Python | bsd-3-clause | 39 | 0.025641 | i | mport haystack
haystack.autodiscover() | |
manusev/plugin.video.kuchitv | resources/regex/streamingfreetv.py | Python | gpl-2.0 | 4,423 | 0.014483 | # -*- coding: utf-8 -*-
#------------------------------------------------------------
# MonsterTV Regex de streamingfreetv
# Version 0.1 (17.10.2014)
#------------------------------------------------------------
# License: GPL (http://www.gnu.org/licenses/gpl-3.0.html)
# Gracias a la librería plugintools de Jesús (www.... | "playpath=", "")
url_user["playpath"]=entry
elif entry.startswith("swfUrl"):
entry = entry.replace("swfUrl=", "")
url_user["swfurl"]=entry
elif entry.startswith("pageUrl"): |
entry = entry.replace("pageUrl=", "")
url_user["pageurl"]=entry
elif entry.startswith("token"):
entry = entry.replace("token=", "")
url_user["token"]=entry
elif entry.startswith("referer"):
entry = entry.replace("referer=", "")
... |
linux-ha-japan/pm_ctl-1.0 | pm_ctl_start.py | Python | gpl-2.0 | 3,713 | 0.005925 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# pm_ctl_start.py : Script of start pacemaker in target node
#
# Copyright (C) 2011 NIPPON TELEGRAPH AND TELEPHONE CORPORATION
#
# 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.
#
# This program is distr | ibuted in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public
# License along with this program; if n... |
analyst-collective/dbt | core/dbt/context/manifest.py | Python | apache-2.0 | 2,929 | 0 | from typing import List
from dbt.clients.jinja import MacroStack
from dbt.contracts.connection import AdapterRequiredConfig
from dbt.contracts.graph.manifest import Manifest
from dbt.context.macro_resolver import TestMacroNamespace
from .configured import ConfiguredContext
from .macros import MacroNamespaceBuilder
... | # subclasses are QueryHeaderContext and ProviderContext
def __init__(
self,
| config: AdapterRequiredConfig,
manifest: Manifest,
search_package: str,
) -> None:
super().__init__(config)
self.manifest = manifest
# this is the package of the node for which this context was built
self.search_package = search_package
self.macro_stack... |
hegdeashwin/learning-python | codes/session_8/libEg2.py | Python | mit | 1,043 | 0.010547 | # How to Run? Open Terminal> python3 libEg2.py
# | Read the code comments and outpu | t on the terminal
# Objective: Know about standard built-in library
# Dates and Times
from datetime import date
# Get today's date
now = date.today()
print("Today's date: ", now)
# Set date
customDate = date(2000, 12, 2)
print("Custom date: ", customDate)
print('\n')
# Data compression
import zlib
print('Data Co... |
SoftwareKing/zstack-utility | zstacklib/zstacklib/utils/jsonobject.py | Python | apache-2.0 | 5,869 | 0.010394 | '''
@author: frank
'''
import simplejson
import json
import types
import inspect
class NoneSupportedTypeError(Exception):
'''not supported type error'''
class JsonObject(object):
def __init__(self):
pass
def put(self, name, val):
setattr(self, name, val)
... | end(val)
elif isinstance(val, types.DictType):
nlst.append(val)
elif isinstance(val, types.ListType):
tlst = _dump_list(val)
| nlst.append(tlst)
elif isinstance(val, types.NoneType):
pass
else:
nmap = _dump(val)
nlst.append(nmap)
return nlst
def _dump_super(obj):
s = super(type(obj), obj)
def _dump(obj):
if _is_primitive_types(obj): return simp... |
shiningdesign/universal_tool_template.py | _ARCHIVE/UITranslator_v1.0.py | Python | mit | 34,443 | 0.010133 | '''
UITranslator v1.0
based on Univeral Tool Template based v006.1
update: 2016.07.22
by ying
usage in maya:
import UITranslator
UITranslator.main()
usage in commandline:
python UITranslator.py
'''
deskMode = 0
qtMode = 0 # 0: PySide; 1 : PyQt
try:
import maya.OpenMayaUI as mui
except ImportError:
deskMode... | or: gray;}")
def setupMenu(self):
self.quickMenu(['fi | le_menu;&File','setting_menu;&Setting','help_menu;&Help'])
cur_menu = self.uiList['setting_menu']
self.quickMenuAction('setParaA_atn','Set Parameter &A','A example of tip notice.','setParaA.png', cur_menu)
cur_menu.addSeparator()
# for file menu
cur_menu = self.uiList['file_menu'... |
vityurkiv/Ox | python/MooseDocs/html2latex/Extension.py | Python | lgpl-2.1 | 735 | 0.009524 | class Extension(object):
"""
Base class for creating extensions.
Args:
kwargs[dict]: All key, value pairings are stored as "configuration" options, see getConfigs.
"""
def __init__(self, **kwargs):
#: Configure options
| self._configs = kwargs
self._configs.setdefault('headings', ['section', 'subsection', 'subsubsection', 'textbf', 'underline', 'emph'])
def getConfigs(self):
"""
Return the dictionary of configure options.
"""
return self._configs
def extend(self, translator):
"""
Elements should be ad... | ator]: The object to be used for converting the html.
"""
pass
|
forgeservicelab/forge.benchmark | cas_log_in_and_measure.py | Python | mit | 4,515 | 0.003322 | #!/usr/bin/env python
# Script for measuring response time for redmine urls.
# It attempts to authenticate via html form which is it given on first GET.
# It should work generally for anything that forwards properly, and has
# "username" and "password" fields in the form.
#
# I tested it for CASino login and standard ... | viron['HOME'], '.ldappass')
pw = None
if os.path.isfile(dot_file):
with open(dot_file) as f:
pw = f.read().strip()
print "Using password from %s" % dot_file
if not pw:
pw = getpass.getpass(
prompt="Give password for username %s: " % user)
return pw
d... | , user, password, debug=False):
br = mechanize.Browser()
if debug:
br.set_debug_http(True)
br.set_debug_responses(True)
br.set_debug_redirects(True)
br.set_cookiejar(cookiejar)
br.set_handle_equiv(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set... |
odoo-brazil/l10n-brazil-wip | sped/models/sped_documento_item_declaracao_importacao.py | Python | agpl-3.0 | 2,534 | 0 | # -*- coding: utf-8 -*-
#
# Copyright 2016 Taŭga Tecnologia
# Aristides Caldeira <aristides.caldeira@tauga.com.br>
# License AGPL-3 or later (http://www.gnu.org/licenses/agpl)
#
from __future__ import division, print_function, unicode_literals
from odoo import fields, models
from odoo.addons.l10n_br_base.models.spe... | ão',
size=12,
)
data_registro = fields.Date(
string='Data de r | egistro',
)
local_desembaraco = fields.Char(
string='Local do desembaraço',
size=60,
)
uf_desembaraco_id = fields.Many2one(
comodel_name='sped.estado',
string='Estado do desembaraço',
)
data_desembaraco = fields.Date(
string='Data do desembaraço',
)
... |
chjost/analysis-code | analysis2/plot_functions.py | Python | gpl-3.0 | 10,517 | 0.003138 | """
Functions for plotting.
"""
import numpy as np
import matplotlib.pyplot as plt
from functions import (func_single_corr, func_ratio, func_const, func_two_corr,
func_single_corr2, compute_eff_mass)
def print_label(keys, vals, xpos=0.7, ypos=0.8):
"""Print a label in the plot.
Parameters
----------... | # check for plotting range
if isinstance(plotrange, (np.ndarray, list, tuple)):
_plo | trange = np.asarray(plotrange).flatten()
if _plotrange.size < 2:
raise IndexError("fitrange has not enough indices")
else:
lfunc = _plotrange[0]
ufunc = _plotrange[1]
x1 = np.linspace(X[lfunc], X[ufunc], 1000)
else:
x1 = np.linspace(X[0], X[-1]... |
viggates/nova | nova/compute/manager.py | Python | apache-2.0 | 269,840 | 0.000771 | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2011 Justin Santa Barbara
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance wi... | s to retry network allocation on failures"),
cfg.IntOpt('block_device_allocate_retries',
def | ault=60,
help='Number of times to retry block device'
' allocation on failures')
]
interval_opts = [
cfg.IntOpt('bandwidth_poll_interval',
default=600,
help='Interval to pull network bandwidth usage info. Not '
'supported on a... |
brandonPurvis/osf.io | website/views.py | Python | apache-2.0 | 11,973 | 0.00142 | # -*- coding: utf-8 -*-
import logging
import itertools
import math
import urllib
import httplib as http
from modularodm import Q
from flask import request
from framework import utils
from framework import sentry
from framework.auth.core import User
from framework.flask import redirect # VOL-aware redirect
from fram... | t be directly queried
nodes = filter(lambda node: not node.is_retracted and not node.is_pending_embargo, nodes)
keys = [node._id for node in nodes]
return [rubeus.to_project_root(node, auth, **kwargs) for node in nodes if node.ids_above.isdisjoint(keys)]
@must_be_logged_in
def get_dashboa | rd_nodes(auth):
"""Get summary information about the current user's dashboard nodes.
:param-query no_components: Exclude components from response.
NOTE: By default, components will only be shown if the current user
is contributor on a comonent but not its parent project. This query
para... |
MattG1942/KLTemplateParser | KLTemplateParser.py | Python | mit | 3,424 | 0.018107 | # KL Template Parser
import sys
# Default type groups
Floats = ['Float32', 'Float64']
Ints = ['UInt8', 'SInt8', 'UInt16', 'SInt16', 'UInt32', 'SInt32', 'UInt64', 'SInt64']
UInts = ['UInt8', 'UInt16', 'UInt32', 'UInt64']
SInts = ['SInt8', 'SInt16', 'SInt32', 'SInt64']
Num = ['UInt8', 'SInt8', 'UInt16', 'SInt16', 'UInt... | bstitutes = []
elif len(sys.argv) == 3:
TemplateFileName = sys.argv[1]
KLFileName = sys.argv[2]
Substitutes = []
else:
TemplateFileName = sys.argv[1]
KLFileName = sys.argv[2]
| Substitutes = sys.argv[3:]
do(TemplateFileName, KLFileName, Substitutes)
# -T = look in template for file name.
|
Gamebasis/3DGamebasisServer | GameData/blender-2.71-windows64/2.71/scripts/startup/bl_ui/properties_physics_softbody.py | Python | gpl-3.0 | 7,418 | 0.001483 | # ##### BEGIN GPL LICENSE BLOCK #####
#
# 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.
#
# This program is distrib... | oftbody, "error_threshold")
col.label(text="Helpers:")
col.prop(softbody, "choke")
col.prop(softbody, "fuz | zy")
layout.label(text="Diagnostics:")
layout.prop(softbody, "use_diagnose")
layout.prop(softbody, "use_estimate_matrix")
class PHYSICS_PT_softbody_field_weights(PhysicButtonsPanel, Panel):
bl_label = "Soft Body Field Weights"
bl_options = {'DEFAULT_CLOSED'}
def draw(self, contex... |
mathLab/RBniCS | rbnics/backends/online/numpy/proper_orthogonal_decomposition.py | Python | lgpl-3.0 | 1,710 | 0.002924 | # Copyright (C) 2015-2022 by the RBniCS authors
#
# This file is part of RBniCS.
#
# SPDX-License-Identifier: LGPL-3.0-or-later
from rbnics.backends.abstract import FunctionsList as AbstractFunctionsList
from rbnics.backends.abstract import ProperOrthogonalDecomposition as AbstractProperOrthogonalDecomposition
from rb... | ver
from rbnics.backends.online.numpy.functions_list import FunctionsList
from rbnics.backends.online.numpy.matrix import Matrix
from rbnics.backends.onl | ine.numpy.snapshots_matrix import SnapshotsMatrix
from rbnics.backends.online.numpy.transpose import transpose
from rbnics.backends.online.numpy.wrapping import get_mpi_comm
from rbnics.utils.decorators import BackendFor, ModuleWrapper
backend = ModuleWrapper(transpose)
wrapping = ModuleWrapper(get_mpi_comm)
online_ba... |
huseyinkabil/coral-ci | main/management/commands/insert_destination_data.py | Python | gpl-3.0 | 152 | 0 | from main.management.commands._private import SharedCommand
from main.models import De | stination
class Command(SharedCo | mmand):
model = Destination
|
joeywen/zarkov | zarkov/server.py | Python | apache-2.0 | 4,751 | 0.00421 | '''This is the main zarkov event server. It uses gevent for a fast event loop in
a single thread. It should typically be invoked with the zarkov-server script.'''
import sys
import time
import logging
from datetime import datetime, timedelta
import bson
import gevent
from gevent_zeromq import zmq
from zarkov import... | def _g_aggregate(self):
'''Execute all defined AggDef aggregations.'''
| zmr = self.context.socket(zmq.REQ)
zmr.connect(self._options.zmr['req_uri'])
sess =model.orm_session
next_agg = datetime.utcnow()
while True:
try:
now = datetime.utcnow()
if now < next_agg:
gevent.sleep((next_agg-now).se... |
BitcoinUnlimited/BitcoinUnlimited | qa/rpc-tests/minimaldata.py | Python | mit | 6,390 | 0.001878 | #!/usr/bin/env python3
# Copyright (c) 2019 The Bitcoin developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""
This tests the MINIMALDATA consensus rule.
- test rejection in mempool, with error changing before/after activat... | t(reject_reason.decode(), reject_code)
class P2PNode(P2PDataStore):
pass
class MinimaldataTest(BitcoinTestFramework):
def __init__(self):
super().__init__()
self.set_test_params()
def set_test_params(self):
| self.num_nodes = 1
self.block_heights = {}
self.extra_args = [["-debug=mempool"]]
def bootstrap_p2p(self):
"""Add a P2P connection to the node.
Helper to connect and wait for version handshake."""
self.p2p = P2PNode()
self.connection = NodeConn('127.0.0.1', ... |
wdbm/goutong | rec.py | Python | lgpl-3.0 | 3,034 | 0.012195 | #!/usr/bin/env python
"""
################################################################################
# #
# rec #
# ... | #
# 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 Foundati | on, 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;... |
vmr2117/nnet | src/adaboost/adaboostSAMME.py | Python | gpl-2.0 | 5,974 | 0.013559 | '''
adaboost.py script can be used to train and test adaboost with a SGDclassifier
for mnist data. Look up commandline options for more information.
'''
import argparse
import cPickle as pickle
import numpy as np
import pylab as pl
import time
from sklearn.ensemble import AdaBoostClassifier
from sklearn.linear_mod... | ore_const', dest = 'pen', const
= 'l1', help = 'use l1 penalty for training weak learners')
penalty_gp.add_argument('--l2', action = 'store_const' | , dest = 'pen', const
= 'l2', help = 'use l2 penalty for training weak learners')
train_parser.set_defaults(func = parse_train_args)
test_parser = subparsers.add_parser('test', help = 'test neural network')
test_parser.add_argument('test_file', help='path to test data')
test_parser.add_arg... |
tensorflow/tfjs | e2e/integration_tests/metadata.py | Python | apache-2.0 | 3,552 | 0.009291 | # @license
# Copyright 2020 Google LLC. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | Create saved models with TensorFlow.
# - Convert the saved models to tfjs format and store in files.
# - Store inputs in files.
# - M | ake inference and store outputs in files.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import functools
import json
import os
import subprocess
import shutil
import sys
import tempfile
import time
import numpy as np
import tensorflow as ... |
boyombo/smsbet | pins/admin.py | Python | mit | 933 | 0.001072 | from random import choice
from django.contrib import admin |
from pins.models import Batch, Pin
from pin | s.forms import BatchForm
def gen_randomdigits(size=10):
return ''.join([choice('1234567890') for i in range(size)])
class BatchAdmin(admin.ModelAdmin):
list_display = ('count', 'used', 'created_on', 'download_pins')
form = BatchForm
date_heirarchy = 'created_on'
def save_model(self, request, ob... |
mdzik/bearded-octo-wookie | BasicPrograms/lbm.py | Python | apache-2.0 | 9,200 | 0.051957 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 10 10:04:30 2015
@author: mdzikowski
"""
# -*- coding: utf-8 -*-
"""
Created on Sat May 2 22:37:49 2015
@author: michal
"""
import numpy as np
import matplotlib.pyplot as plt
# all basic const and tools for lbm are here
import bearded_octo_wookie.lbm as lbm
import be... | ===============================================================
#ux,uy = ubc(x0,y0)
#plt.streamplot(np.arange(ny0),np.arange(nx0),uy,ux )
#plt.show()
ubcC = ubc
#=================================== | ===========================================
# BC_fun_Left, BC_A_Left = BC.getUBc([0,1], 0., 0.)
# BC_fun_Right, BC_A_Right = BC.getUBc([0,-1], 0., 0.)
# BC_fun_Top, BC_A_Top = BC.getUBc([-1,0], 0., 0.0)
# BC_fun_Bottom, BC_A_Bottom = BC.getUBc([1,0], 0., 0.)
#============================================================... |
quanvm009/codev7 | openerp/addons_quan/lifestyle/wizard/wizard_print_order_tracking.py | Python | agpl-3.0 | 2,767 | 0.001084 | # -*- coding: utf-8 -*-
# #####################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2011 OpenERP s.a. (<http://openerp.com>).
# Copyright (C) 2013 INIT Tech Co., Ltd (http://init.vn).
# This program is free software: you can redistribute it and/or... | , context=None):
if context is None:
context = {}
res = {'value': {}}
line_obj = self.pool.get('sale.order.line')
plan_obj = self.pool.get('production.plan')
section_obj = self.pool.get('production.section')
if sale_id:
line_ids | = line_obj.search(cr, uid, [('order_id', '=', sale_id)])
stock_ids = []
for line in line_ids:
plan_ids = plan_obj.search(cr, uid, [('sale_line_id', '=', line)])
if plan_ids:
section_ids = section_obj.search(cr, uid, [('plan_id', '=', plan_ids)])
i... |
CS-SI/QGIS | tests/src/python/test_qgslayoutguides.py | Python | gpl-2.0 | 17,536 | 0.003935 | # -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsLayoutGuide/QgsLayoutGuideCollection.
.. note:: 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) ... | .LayoutMillimeters))
g.update()
self.assertFalse(g.item().isVisible())
# guide on page2
g3 = QgsLayoutGuide(Qt.Vertical, QgsLayoutMeasurement(5, QgsUnitTypes.LayoutCentimeters), l.pageCollection().page(1))
g3.setLayout(l)
g3.update()
self.assertTrue(g3.item().isV... | ).line().x2(), 50)
self.assertEqual(g3.item().line().y2(), 430)
self.assertEqual(g3.layoutPosition(), 50)
def testCollection(self):
p = QgsProject()
l = QgsLayout(p)
l.initializeDefaults() # add a page
guides = l.guides()
# no guides initially
self.a... |
imron/scalyr-agent-2 | scalyr_agent/third_party/pysnmp/hlapi/varbinds.py | Python | apache-2.0 | 2,626 | 0.00457 | from pysnmp.smi import view
from pysnmp.smi.rfc1902 import *
__all__ = ['CommandGeneratorVarBinds', 'NotificationOriginatorVarBinds']
class AbstractVarBinds:
def getMibViewController(self, snmpEngine):
mibViewController = snmpEngine.getUserContext('mibViewController')
if not mibViewController:
... | arBind = ObjectType(ObjectIdentity(varBind[0][0][0], varBind[0][0][1], *varBind[0][1:]), varBind[1])
else:
varBind = ObjectType(ObjectIdentity(varBind[0]), varBind[1])
__varBinds.append(varBind.resolveWithMib(mibViewController))
return __varBinds
def unmakeVarBinds... | snmpEngine, varBinds, lookupMib=True):
if lookupMib:
mibViewController = self.getMibViewController(snmpEngine)
varBinds = [ ObjectType(ObjectIdentity(x[0]), x[1]).resolveWithMib(mibViewController) for x in varBinds ]
return varBinds
class NotificationOriginatorVarBinds(Abstract... |
anhstudios/swganh | data/scripts/templates/object/building/poi/shared_corellia_smashball_small1.py | Python | mit | 456 | 0.046053 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.obj | ect import *
def create(kernel):
result = Building()
result.template = "object/building/poi/shared_corellia_smashball_small1.iff"
result.attribute_template_id = -1
result.stfName("poi_n","base_poi_building")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
|
return result |
beeftornado/sentry | tests/sentry/web/frontend/test_oauth_authorize.py | Python | bsd-3-clause | 13,174 | 0.002429 | from __future__ import absolute_import
from exam import fixture
from six.moves.urllib.parse import parse_qs, urlparse
from sentry.models import ApiApplication, ApiAuthorization, ApiGrant, ApiToken
from sentry.testutils import TestCase
class OAuthAuthorizeCodeTest(TestCase):
@fixture
def path(self):
... | s(urlparse(resp["Location"]).query) == parse_qs(
u"state=foo&code={}".format(grant.code)
)
assert not ApiToken.objects.filter(user=self.user).exists()
def test_approve_flow_bypass_prompt(self):
self.login_as(self.user)
ApiAuthorization.objects.create(user=self.user, ap... | grant = ApiGrant.objects.get(user=self.user)
assert grant.redirect_uri == self.application.get_default_redirect_uri()
assert grant.application == self.application
assert not grant.get_scopes()
assert resp.status_code == 302
assert resp["Location"] == u"https://example.com... |
lcharleux/argiope | doc/examples/mesh/Mesh-write_inp.py | Python | gpl-3.0 | 302 | 0.019868 | import numpy as np
import pandas as pd
import argiope
mesh = argiope.indentation.sample_mesh_2D("gmsh", "./workdir/")
#argiope.mesh.write_inp(mesh, "workdir/mesh.inp")
elemen | t_map = {"Tri3": "CAX3",
"Quad4": "CAX4", }
mesh.to_inp(path = "workdir/mesh.inp", element | _map = element_map)
|
jbdubois/obus | python/hmi/busdata.py | Python | lgpl-2.1 | 5,267 | 0.018796 | #===============================================================================
# wxpyobus - obus client gui in python.
#
# @file busdata.py
#
# @brief wxpython obus client bus data
#
# @author yves-marie.morgan@parrot.com
#
# Copyright (c) 2013 Parrot S.A.
# All rights reserved.
#
# Redistribution and use in source a... | INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMI | TED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF T... |
JohannesBuchner/syscorr | example/gen.py | Python | agpl-3.0 | 828 | 0.019324 | import numpy
import os
numpy.random.seed(0)
# generate test da | ta sets
def write(prefix, data):
if not os. | path.exists(prefix):
os.mkdir(prefix)
for i, (x, y) in enumerate(data):
numpy.savetxt('%s/chain%02d' % (prefix, i), numpy.transpose([x, y]))
# random
write('random', [[numpy.random.normal(x, 0.1, size=50), numpy.random.normal(y, 0.1, size=50)]
for x, y in zip(numpy.random.uniform(0, 1, size=100), numpy.random.u... |
srio/ShadowOui-Tutorial | SCRIPTS/script26_plot.py | Python | mit | 260 | 0.026923 | from matplotlib import py | lab as plt
(x,y,yEA) | = in_object
print(in_object)
plt.plot(x,y/y.max(),label="Fully coherent")
plt.plot(x,yEA/yEA.max(),label="Partial coherent")
plt.xlabel("Z [um]")
plt.ylabel("Intensity [Arbitrary Units]")
plt.legend()
plt.show() |
melphi/algobox | python/algobox/src/algobox/backtest/service.py | Python | apache-2.0 | 278 | 0 | from connexion import App
import logging
logging.basicConfig(level=logging.INFO)
app = App(__name__)
app.add_api('swagger.yaml')
# set the WSGI application callable to allow us | ing uWSGI
application = app | .app
if __name__ == '__main__':
app.run(port=8080, server='gevent')
|
joachimmetz/dfvfs | dfvfs/file_io/vshadow_file_io.py | Python | apache-2.0 | 4,122 | 0.004852 | # -*- coding: utf-8 -*-
"""The Volume Shadow Snapshots (VSS) file-like object implementation."""
import os
from dfvfs.file_io import file_io
from dfvfs.lib import errors
from dfvfs.lib import vshadow_helper
from dfvfs.resolver import resolver
class VShadowFile(file_io.FileIO):
"""File input/output (IO) object usi... | xt (Context): resolver context.
path_spec (PathSpec): a path specification.
"""
super(VShadowFile, self).__init__(resolver_context, path_spec)
self._file_system = None
self._vshadow_store = None
def _Close(se | lf):
"""Closes the file-like object."""
self._vshadow_store = None
self._file_system = None
def _Open(self, mode='rb'):
"""Opens the file-like object defined by path specification.
Args:
mode (Optional[str]): file access mode.
Raises:
AccessError: if the access to open the file... |
dmnfarrell/peat | PEATDB/scripts/multiProjects.py | Python | mit | 10,004 | 0.018193 | #!/usr/bin/env python
#
# Protein Engineering Analysis Tool DataBase (PEATDB)
# Copyright (C) 2010 Damien Farrell & Jens Erik Nielsen
#
# 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 ver... | DB.commit()
print 'merged results'
else:
mutlist = []
for p in DB.getRecs():
mutlist.append(DB.get(p).Mutations)
#print mutlist
pdbfile = PS.writetempPDB()
#we add source project data so exp data can be read f... | ame,'password':'123','port':'8080'}
PS.submitJob(name='mycalc', pdbname=DB.meta.refprotein, pdbfile=pdbfile,
mutations=mutlist, calcs=['stability'],
meta={'protein':name,'expcol':'Exp','project':prjdata})
#required to end process
PS.jobManag... |
corryl/facebook-leak | facebook-leak.py | Python | gpl-3.0 | 1,513 | 0.011897 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#This program is distributed i... | nt
cj = CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
values = "lsd=AVpaaUQL&charset_test=%E2%82%AC%2C%C2%B4%2C%E2%82%AC%2C%C2%B4%2C%E6%B0%B4%2C%D0%94%2C%D0%84&email="+email+"&did_submit=Cerca"
response = opener.open("https://m.facebook.com/login/identify/?ctx=recover", values)
content = r... | nt
print "Person:", risultato[0]
immagine = re.findall(r'<div class="s"><img src="(.*?)&size=square',str(content))
print
print "Profile Image: ",immagine[0]
print
|
conferency/find-my-reviewers | app/api/results.py | Python | mit | 12,128 | 0.003133 | import hashlib
import json
import os
from core.helper.pdf2string import text_blob_tokenise
from flask import render_template, request, current_app, jsonify, session, redirect, url_for
from app import db
from app.models import RecommendationResult
from app.modules.main.views import requires_auth
from core.matching.key... | url_for("main.results"))
# return redirect(url_for("main.result"))
@api.route('/get_result/<file_hash>', methods=['GET', 'POST'])
def get_result(file_hash):
"""
Find relevant reviewers based on the default LDA model from a PDF file. Fo | r anonymous user only.
:param file_hash: the hash of the uploaded PDF file.
:return: a json that containing the result.
"""
reviewers = pdf_match(file_hash)
if reviewers:
number_of_reviewers = len(reviewers)
reviewers = get_rows(reviewers)
if number_of_reviewers < 15:
... |
dhuang/incubator-airflow | airflow/providers/amazon/aws/operators/datasync.py | Python | apache-2.0 | 18,667 | 0.002679 | # 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... | ow.models import BaseOperator
from airflow.providers.amazon.aws.hooks.datasync import AWSDataSyncHook
class AWSDataSyncOperator(BaseOperator):
r"""Find | , Create, Update, Execute and Delete AWS DataSync Tasks.
If ``do_xcom_push`` is True, then the DataSync TaskArn and TaskExecutionArn
which were executed will be pushed to an XCom.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:... |
mayhem/sleep-debugger | sleepdebugger/process_lock.py | Python | bsd-2-clause | 1,445 | 0.002076 | import os
import sys
from atexit import register
class ProcessLock(object):
def __init__(self, lockfile):
self.lockfile = lockfile
def allowed_to_start(self):
if not os.path.exists(self.lockfile):
return True
try:
f = open(self.lockfile, "r")
pid... | r
register(lambda: self.cleanup())
# Create a lockfile
try:
f = open(self.l | ockfile, "w")
except IOError as e:
print "Cannot create lock file %s: %s" % (self.lockfile, e)
sys.exit(-2)
f.write("%d" % os.getpid())
f.close()
def cleanup(self):
# Remove the lock file
try:
os.unlink(self.lockfile)
except OSEr... |
KhronosGroup/COLLADA-CTS | StandardDataSets/collada/library_controllers/controller/morph/morph_vertices_with_position_texture/morph_vertices_with_position_texture.py | Python | mit | 3,979 | 0.006534 |
# Copyright (c) 2012 The Khronos Group Inc.
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and /or associated documentation files (the "Materials "), to deal in the Materials without restriction, including without limitation the rights to use, copy, modify, merge, publ... | uperior badge.
def Jud | geSuperior(self, context):
self.status_superior = self.status_baseline
return self.status_superior
# To pass exemplary you need to pass superior, this object could also include additional
# tests that were specific to the exemplary badge
def JudgeExemplary(self, conte... |
dparaujo/projeto | app_administrativo/candidato/urls.py | Python | gpl-3.0 | 688 | 0.010174 | # -*- coding: utf-8 -*-
from django.conf.ur | ls import url
from app_administrativo.candidato.views import *
urlpatterns = [
url(r'^$', CandidatoListView.as_view(), name=u'candidato_home'),
url(r'^cadastar/$', CandidatoFormView.as_view(), name=u'candidato_cadastrar'),
url(r'^(?P<p... | as_view(), name=u'candidato_atualizar'),
url(r'^(?P<pk>[\w-]+)/deletar/$', CandidatoDeleteView.as_view(), name=u'candidato_deletar'),
] |
eduNEXT/edunext-platform | import_shims/lms/bulk_email/models.py | Python | agpl-3.0 | 374 | 0.008021 | """Deprecated import support. Auto-generated by import_shims/generate_shims.sh."""
# pylint: disable=redefined-builtin,wrong-import-position,wildcard-import,useless-suppression,line-too-long
from import_ | shims.warn import w | arn_deprecated_import
warn_deprecated_import('bulk_email.models', 'lms.djangoapps.bulk_email.models')
from lms.djangoapps.bulk_email.models import *
|
techyteach-s/plugin.audio.abcradioaustralia | addon.py | Python | mit | 3,454 | 0.019398 | from xbmcswift2 import Plugin, xbmcgui
plugin = Plugin()
@plugin.route('/')
def main_menu():
items = [
{'label': plugin.get_string(30000), 'path': "http://www.abc.net.au/res/streaming/audio/mp3/radio_national.pls",
'is_playable': True},
{'label': plugin.get_string(30001), 'path': "htt... | /res/streaming/audio/mp3/local_adelaide.pls",
'is_playable': True},
{'label': plugin.get_string(30009), 'path': "http://www.abc.net.au/res/streaming/audio/mp3/local_hobart.pls",
'is_pl | ayable': True},
{'label': plugin.get_string(30010), 'path': "http://www.abc.net.au/res/streaming/audio/mp3/local_newcastle.pls",
'is_playable': True},
{'label': plugin.get_string(30011), 'path': "http://www.abc.net.au/res/streaming/audio/mp3/local_darwin.pls",
'is_p... |
izzi/ActivityTracker | tests/testException.py | Python | gpl-3.0 | 509 | 0.015717 | '''
Created on Aug 20, 2014
@author: valeriu
'''
impo | rt unittest
from activitytracker import ActivityError
class TestException(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_string_format(self):
exception = ActivityError(2, '{0}')
self.assertEqual('2', str(exception), "Incorect str... | formatting in exception")
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main() |
GroestlCoin/electrum-grs | electrum_grs/gui/kivy/uix/dialogs/qr_dialog.py | Python | gpl-3.0 | 3,011 | 0.001328 | from typing import TYPE_CHECKING
from kivy.factory import Factory
from kivy.lang import Builder
from kivy.core.clipboard import Clipboard
from kivy.app import App
from kivy.clock import Clock
from electrum_grs.gui.kivy.i18n import _
if TYPE_CHECKING:
from ...main_window import ElectrumWindow
Builder.load_strin... | one,
on_close=None):
Factory.Popup.__init__(self)
self.app = App.get_running_app() # type: ElectrumWindow
self.title = title
self.data = data
self.help_text = (data if show_text else help_text) or ''
self.failure_cb = failure_cb
self.text_for_clipboa... | if text_for_clipboard else data
self.close_button_text = close_button_text or _('Close')
self.on_close = on_close
def on_open(self):
self.ids.qr.set_data(self.data, self.failure_cb)
def copy_to_clipboard(self):
Clipboard.copy(self.text_for_clipboard)
msg = _('Text copie... |
saveman71/Anime-Ultime-Downloader | gui.py | Python | apache-2.0 | 6,830 | 0.002489 | #!/usr/bin/python
import sys
import re
import threading
import time
import signal
import urllib.request, urllib.error, urllib.parse
import json
import os.path
from bs4 import BeautifulSoup
from gi.repository import Gtk, GObject, GLib
import au
class AnimeDl(object):
def __init__(self):
self.ep = []
... | pisode_url
return False
def update_percent(self, ep):
store = interface.get_object('liststore1')
store[ep.treeiter][3] = self.percent
if self.perce | nt == 100:
return (False)
return True
def update_ep_status(self):
store = interface.get_object('liststore1')
for ep in self.ep:
store[ep.treeiter][5] = ep.status
return True
def update_treestore(self, ep):
GLib.timeout_add_seconds(1, self.update_... |
tsarpaul/poolhub | poolhub/frontend/utils.py | Python | mit | 250 | 0.004 | import os
import webbro | wser
def get_index_path():
path = os.path.join(os.path.dirname(__file__), 'poolhub_app', 'dist', 'index.html')
return path
def launch_inde | x_page():
path = get_index_path()
webbrowser.open('file://' + path)
|
badrihippo/sirius | sirius/views.py | Python | gpl-2.0 | 278 | 0.010791 | from django.shortcuts import rend | er_to_response
from issue.views import get_current_squiggle, get_upcoming_squiggles
def home(request):
return render_to_response('base.html',{
'csquig':get_current_squiggle(),
| 'upcoming_squiggles': get_upcoming_squiggles()})
|
russorat/savage-leads | settings/models/loginForm.py | Python | apache-2.0 | 353 | 0.002833 | from flask.ext.wtf import Form
from wtforms import StringField, BooleanField, PasswordField
from wtforms.validators import DataRequired
class LoginForm( | Form):
email = StringField('email', validators=[DataRequired()])
password = PasswordField('password', val | idators=[DataRequired()])
remember_me = BooleanField('remember_me', default=False)
|
Niklatz/Secret-Santa | SecretSanta.py | Python | mit | 2,355 | 0.010191 | #!/usr/bin/python
import argparse
import random
import os
parser = argparse.ArgumentParser()
parser.add_argument('-p', '--print-names', action='store_true',
| dest='printNames', default=False, help='print names to terminal')
parser.add_argument('-d', '--dry-run', action='store_true', dest='dryRun',
default=False, help='don\'t write output files')
def drawSecretSanta(names, invalidpairs):
ok = False
while not ok:
try:
# shuffle the... | }
# cheat and make windows compatible copy of the names here
for person in names:
curinvalid[person]=set(invalidpairs.get(person,set()))
curinvalid[person].add(person)
# draw the names
for person in names:
pairings[person] ... |
MaxHalford/Prince | prince/mfa.py | Python | mit | 8,572 | 0.001167 | """Multiple Factor Analysis (MFA)"""
import itertools
from matplotlib import markers
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn import utils
from . import mca
from . import one_hot
from . import pca
from . import plot
class MFA(pca.PCA):
def __init__(self, groups=None, ... | if self.normalize:
# Scale continuous variables to unit variance
num = X.select_dtypes(np.number).columns
# If a column's cardinality is 1 then it's variance is 0 which can
# can cause a division by 0
normalize = lambda x: x / (np.sqrt((x ** 2).sum()) or 1... | return X
def _build_X_global(self, X):
X_partials = []
self.cat_one_hots_ = {}
for name, cols in sorted(self.groups.items()):
X_partial = X.loc[:, cols]
if not self.all_nums_[name]:
oh = one_hot.OneHotEncoder().fit(X_partial)
X_par... |
gdbelvin/mail-safe-test | mail_safe_test/urls.py | Python | apache-2.0 | 2,217 | 0.009923 | """ urls.py
URL dispatch, route mappings
"""
from flask.ext import restful
from mail_safe_test import app
from mail_safe_test.resources.oauth import login, oauth_callback, logout, verify
from mail_safe_test.resources.user import | UserAPI, AdminUserAPI, AdminUserListAPI
from mail_safe_test.resources.contact import ContactListAPI, ContactAPI
from mail_safe_test.resources.doc import DocListAPI, DocAPI
from mail_safe_test.resources.link import Link
from mail_safe_test.resources.mail import Mail
app.add_url_rule('/login/', endpoint='login', view_fu... | _func = oauth_callback, methods=['GET', 'POST'])
app.add_url_rule('/logout/', endpoint='logout', view_func=logout, methods=['GET'])
app.add_url_rule('/verify/', endpoint='verify', view_func=verify, methods=['GET'])
app.api = restful.Api(app)
app.api.add_resource(AdminUserAPI, '/admin/user/<string:key_id>/', endpoint='... |
Genomon-Project/paplot | tests/python/test_qc.py | Python | mit | 8,792 | 0.006824 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 28 13:18:34 2016
@author: okada
"""
import unittest
import os
import sys
import test_utils
import subprocess
class TestSet(unittest.TestCase):
CURRENT = os.path.abspath(os.path.dirname(__file__) + "/../")
dataset = CURRENT + "/dataset/qc/"
REF = CURRENT + "... | ue)
ref = test_utils.load_text(self.REF + "test1_01_sample_header_id_csv/data_qc.js")
alt = test_utils.load_text(self.ALT + name + "/data_ | qc.js")
self.assertEqual(ref, alt)
ref = test_utils.load_html(self.REF + "test1_01_sample_header_id_csv/graph_qc.html")
alt = test_utils.load_html(self.ALT + name + "/graph_qc.html")
self.assertEqual(ref, alt)
def test1_09_sample_header_noid_csv(self):
name = sys._g... |
pystorm/pystorm | test/pystorm/serializers/test_msgpack_serializer.py | Python | apache-2.0 | 1,997 | 0.000501 | from __future__ import absolute_import, print_function, unicode_literals
from io import BytesIO
import warnings
try:
from unittest import mock
except ImportError:
import mock
try:
import msgpack
HAVE_MSGPACK = True
except:
warnings.warn(
"Cannot import msgpack. It is necessary for using ... | raise IOError()
bytes_io_mock.flush.side_effect = raiser
self.instance.output_stream = bytes_io_mock
with pytest.raises(StormWentAwayError):
self.instance.send_message({"hello" | : "world"})
|
Unidata/MetPy | tests/interpolate/test_grid.py | Python | bsd-3-clause | 11,413 | 0.002366 | # Copyright (c) 2018,2019 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""Test the `grid` module."""
import logging
import numpy as np
import pytest
from metpy.cbook import get_test_data
from metpy.interpolate.grid import (generate_grid, genera... | 248225, 3.16783697, 3.54497301, 3.89481001],
[1.61968826, 1.88924405, 2.19296648, 2.54191855, 2.91119712],
[1.09089606, 1.25384007, 1.46192044, 1.73476959, 2.05268876],
[0.97204726, 1.02016741, 1.11466014, 1.27721014, 1.4912234],
[1.0750152... | ],
[[0.61025484, 0.7315194, 0.85573147, 0.97430123, 1.08453329],
[0.31705299, 0.3987999, 0.49178996, 0.59602155, 0.71077394],
[0.1819831, 0.22650344, 0.28305811, 0.35654934, 0.44709885],
[0.15472957, 0.17382593, 0.20182338, 0.2445138, 0.3025... |
19kestier/taiga-back | taiga/projects/migrations/0001_initial.py | Python | agpl-3.0 | 6,634 | 0.004221 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
import django_pgjson.fields
import django.utils.timezone
import django.db.models.deletion
import djorm_pgarray.fields
import taiga.projects.history.models
class Migration(migratio... | ('videoconferences_salt', models.CharField(max_length=250, null=True, verbose_name='videoconference room salt', blank=True)),
('anon_permissions', djorm_pgarray.fields.TextArrayField(choices=[('view_project', 'View project'), ('view_milestones', 'View milestones'), ('view_us', 'View user stories'), ('vi... | xt', default=[], verbose_name='anonymous permissions')),
('public_permissions', djorm_pgarray.fields.TextArrayField(choices=[('view_project', 'View project'), ('view_milestones', 'View milestones'), ('view_us', 'View user stories'), ('view_issues', 'View issues'), ('vote_issues', 'Vote issues'), ('view_... |
Rathcke/uni | dis2/dis2-projekt/code/pocklington-test.py | Python | gpl-3.0 | 1,096 | 0.023723 | import math
import fractions
import operator
import factorization
import gmpy2
def pocklingtonTest(N):
if((N % 2) == 0 and N != 2):
return False
A = chooseAbeta(N);
primeFactorization = factorization.factorize(A);
primeFactors = getPrimeFactors(primeFactorization);
for x in primeFactors:
... | ditionsHold(x, N)):
return False;
return True;
def conditionsHold(p, N):
a = 2;
while(a < | N-1):
if(firstCondition(a, N) and secondCondition(a, p, N)):
return True;
a += 1;
return False;
def firstCondition(a, N):
print "a is " + str(a)
print a**(N-1)%N
return ((a**(N-1))%N == 1);
def secondCondition(a, p, N):
print a**((N-1)/p)-1
return fractions.gcd(a**... |
KaranToor/MA450 | google-cloud-sdk/lib/surface/pubsub/subscriptions/ack.py | Python | apache-2.0 | 2,299 | 0.002175 | # Copyright 2015 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 ag... | user runs this command.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
Ack display dictionary with information about the acknowledged messages
and related subscription.
"""
msgs = self.context['pubsub_msgs']
p... | geRequest(ackIds=args.ackid),
subscription=util.SubscriptionFormat(args.subscription))
pubsub.projects_subscriptions.Acknowledge(ack_req)
# Using this dict, instead of returning the AcknowledgeRequest directly,
# to preserve the naming conventions for subscriptionId.
return {'subscriptionId': ... |
54lihaoxin/leetcode_python | src/Subsets/solution.py | Python | apache-2.0 | 1,078 | 0.010204 | # Subsets
#
# Given a set of distinct integers, S, return all possible subsets.
#
# Note:
# | Elements in a subset must be in non-descending order.
# The solution set must not contain duplicate subsets.
# For example,
# If S = [1,2,3], a solution is:
#
# [
# [3],
# [1],
# [2],
# [1,2,3],
# [1,3],
# | [2,3],
# [1,2],
# []
# ]
debug = True
debug = False
class Solution:
# @param S, a list of integer
# @return a list of lists of integer
def subsets(self, S):
S.sort()
return self.sortedSubsets(S)
def sortedSubsets(self, S):
r = [[]] # ... |
cgwire/zou | zou/app/blueprints/crud/event.py | Python | agpl-3.0 | 336 | 0 | from zou.app.models.event import ApiEvent
from .base import BaseModelResource, BaseModelsResource
class EventsResource(BaseModelsResource):
def __init__(self):
BaseModelsResou | rce.__init__(self, ApiEvent)
class EventResource(BaseModelResource):
def __init__(self):
B | aseModelResource.__init__(self, ApiEvent)
|
wadoon/pytagsfs | tests/subspat.py | Python | gpl-2.0 | 11,977 | 0.001503 | # Copyright (c) 2007-2008 Forest Bond.
# This file is part of the pytagsfs software package.
#
# pytagsfs is free software; you can redistribute it and/or modify it under the
# terms of the GNU General Public License version 2 as published by the Free
# Software Foundation.
#
# A copy of the license has been included i... | or k, v in self.substitution_pattern_mapping.items():
mapping_lower[k] = v.lower()
self.assertEqual(
self.pattern.fill(mapping_lower),
self.substitution_pattern_filled_string,
)
def test_modified_fill_upper_case_input(sel | f):
mapping_upper = {}
for k, v in self.substitution_pattern_mapping.items():
mapping_upper[k] = v.upper()
self.assertEqual(
self.pattern.fill(mapping_upper),
self.substitution_pattern_filled_string,
)
def test_modified_fill_title_case_input(self):
... |
yunfanz/ReionBub | Choud14/Barrier.py | Python | mit | 11,268 | 0.044995 | import numpy as n, matplotlib.pyplot as p, scipy.special
import cosmolopy.perturbation as pb
import cosmolopy.density as cd
from scipy.integrate import quad, tplquad
import itertools
from scipy.interpolate import interp1d
from scipy.interpolate import RectBivariateSpline as RBS
import optparse, sys
from scipy.optimize ... | ,del0,s,s0,sx,epx,q,meanmu,varmu,varx,gamm,R0,V,z,err=False):
# EqA8, non-log intervaled integration axis
Bb = B(z,b,s)
#print 'gamm,epx,q =',gamm,epx,q
meanx = gamm*((Bb-del0*sx/s0)*(1-epx)/q/n.sqrt(s)+Bb*epx/n.sqrt(s))
fact = V/Vstar(R0)*pG(Bb/n.sqrt(s),meanmu, varmu)
#print b, Bb/n. | sqrt(s),meanmu,varmu,pG(Bb/n.sqrt(s),meanmu, varmu)
#print b
#x = n.linspace(b*gamm,100.,200) #TUNE
x = n.exp(n.linspace(n.log(b*gamm),n.log(100),200))
y = (x/gamm-b)*F(x)*pG(x,meanx,varx)
factint = trapz(x,y)
#print y
#print factint
#factint = quad(lambda x: (x/gamm-b)*F(x)*pG(x,meanx,... |
anntzer/seaborn | doc/tools/nb_to_doc.py | Python | bsd-3-clause | 8,312 | 0 | #! /usr/bin/env python
"""Execute a .ipynb file, write out a processed .rst and clean .ipynb.
The functions in this script were copied from the nbstripout tool:
Copyright (c) 2015 Min RK, Florian Rathgeber, Michael McNeil Forbes
2019 Casper da Costa-Luis
Permission is hereby granted, free of charge, to any person ob... | not keep_count, strip the counts
# from the output.
if keep_output_this_cell and not keep_count:
for output in cell['outputs']:
if 'execution_count' in output:
output['execution_count'] = None
# If keep_output_this_cell and... | herwise
if 'prompt_number' in cell and not keep_count:
cell['prompt_number'] = None
if 'execution_count' in cell and not keep_count:
cell['execution_count'] = None
# Always remove this metadata
for output_style in ['collapsed', 'scrolled']:
if output_... |
brsunter/TriviaQuestions | SampleParser.py | Python | apache-2.0 | 189 | 0.031746 | import csv
data=csv.reader(open('GeneralKnowledgeQuestions.csv',"rU"),delimiter=',',dialect=csv.excel_tab)
for question i | n data:
print "Question: "+question[0]+" An | swer: "+question[1]
|
shashank-sharma/mythical-learning | mysite/login/tokens.py | Python | mit | 422 | 0.007109 | from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.utils import six
class AccountActiva | tionTokenGenerator(PasswordResetTokenGenerator):
def _make_hash_value(self, user, timestamp):
return (
six.text_type(user.pk) + six.text_type(timestamp) +
six.text_type(us | er.profile.email_confirmed)
)
account_activation_token = AccountActivationTokenGenerator() |
AlceConsorcio/account-closing | account_cutoff_base/__openerp__.py | Python | agpl-3.0 | 2,130 | 0 | # -*- encoding: utf-8 -*-
##############################################################################
#
# Account Cut-off Base module for OpenERP
# Copyright (C) 2013 Akretion (http://www.akretion.com)
# @author Alexis de Lattre <alexis.delattre@akretion.com>
#
# This program is free software: you can re... | is module contains objets, fields and menu entries that are used by other
cut-off modules. So you need to install other cut-off modules to get the
additionnal func | tionalities :
* the module *account_cutoff_prepaid* will manage prepaid cut-offs based on
start date and end date,
* the module *account_cutoff_accrual_picking* will manage the accruals based
on the status of the pickings.
Please contact Alexis de Lattre from Akretion <alexis.delattre@akretion.com>
for any help o... |
blueyed/coveragepy | tests/test_files.py | Python | apache-2.0 | 12,898 | 0.000776 | # coding: utf-8
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt
"""Tests for files.py"""
import os
import os.path
import pytest
from coverage import files
from coverage.files import (
TreeMatcher, FnmatchM... | False),
(self.make_file("sub2/file3.h"), True),
(self.make_file("sub3/file4.py"), T | rue),
(self.make_file("sub3/file5.c"), False),
]
fnm = FnmatchMatcher(["*.py", "*/sub2/*"])
self.assertEqual(fnm.info(), ["*.py", "*/sub2/*"])
for filepath, matches in matches_to_try:
self.assertMatches(fnm, filepath, matches)
def test_fnmatch_matcher_overloa... |
lsa-pucrs/Player-Stage-Manual | code/Ch9.3/bigbob9_c.py | Python | gpl-3.0 | 1,538 | 0.013004 | #/* bigbob9.py - demo ranger interface
# * K. Nickels 7/24/13
# */
# Check with "locate playerc.py"
import sys,os
sys.path.append('/usr/local/lib/python2.7/site-packages/')
sys.path.append('/usr/local/lib64/python2.7/site-packages/')
import math
from playerc import *
# /* Create a client and connect it to the serve... | )
laserProxy.get_geom()
robot.read()
print "max range = ", laserProxy.max_range
print "%d sonar ranges: "% sonarProxy.ranges_count
for i in range(sonarProxy.ranges_count):
print "%.3f, " % sonarProxy.ranges[i],
print "."
print "%d tooth laser ranges: "% toothProxy.ranges_count
for i in range(toothProxy.ranges_count)... | y.ranges_count
for i in range(laserProxy.ranges_count):
print "%.3f, " % laserProxy.ranges[i],
print "."
# Clean up
sonarProxy.unsubscribe()
toothProxy.unsubscribe()
laserProxy.unsubscribe()
robot.disconnect()
|
kevinarpe/kevinarpe-rambutan3 | tests/check_args/binary_seq/test_RBinarySequenceMatcher.py | Python | gpl-3.0 | 2,247 | 0.00267 | import pytest
from rambutan3 import RTestUtil
from rambutan3.check_args.RCheckArgsError import RCheckArgsError
from rambutan3.check_args.binary_seq.RBinarySequenceEnum import RBinarySequenceEnum
from rambutan3.check_args.binary_seq.RBinarySequenceMatcher import RBinarySequenceMatcher
def test_ctor():
with pytest... | ck_arg(RBinarySequenceEnum.BYTES, b'abc', 'dummy_arg_name')
| with pytest.raises(RCheckArgsError):
__check_arg(RBinarySequenceEnum.BYTES, None, 'dummy_arg_name')
with pytest.raises(RCheckArgsError):
__check_arg(RBinarySequenceEnum.BYTES, 123, 'dummy_arg_name')
with pytest.raises(RCheckArgsError):
__check_arg(RBinarySequenceEnum.BYTES, bytearray(... |
mbayon/TFG-MachineLearning | venv/lib/python3.6/site-packages/scipy/special/tests/test_pcf.py | Python | mit | 664 | 0 | """Tests for parabolic cylinder functions.
"""
import numpy as np
from numpy.testing import assert_allclose, assert_equal
import scipy.special as sc
def test_pbwa_segfault():
# Regression test for https://github.com/scipy/scipy/issues/6208.
#
# Data generated by mpmath.
#
w = 1.022765672113168671... | 887053372346189882
assert_allclose(sc.pbwa(0, 0), (w, wp), rtol=1e-13, atol=0)
def test_pbwa_nan():
# Check that NaN's are returned outside of the range in which the
# implementation is accu | rate.
pts = [(-6, -6), (-6, 6), (6, -6), (6, 6)]
for p in pts:
assert_equal(sc.pbwa(*p), (np.nan, np.nan))
|
opadron/girder | plugins/oauth/plugin_tests/oauth_test.py | Python | apache-2.0 | 29,618 | 0.000675 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright 2014 Kitware Inc.
#
# Licensed under the Apache License, Version 2.0 ( the "License" );
# you may not use this file except in compliance with the License.
# You may obtain a cop... | csrfTokenParts[0], force=True, objectId=False)
self.assertLess(
token['expires'],
datetime.datetime.utcnow() + datetime.timedelta(days=0.30))
self.assertEqual(
csrfTokenParts[2],
'http://localhost/#foo/bar')
return pro... | # Try callback, for a non-existant provider
resp = self.request('/oauth/foobar/callback')
self.assertStatus(resp, 400)
# Try callback, without providing any params
resp = self.request('/oauth/%s/callback' % providerInfo['id'])
self.assertStatus(resp, 400)
# Try callba... |
hlzz/dotfiles | graphics/VTK-7.0.0/Filters/General/Testing/Python/clipComb.py | Python | bsd-3-clause | 2,190 | 0.000457 | #!/usr/bin/env python
import vtk
fro | m vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
# create pipeline
#
pl3d = vtk.vtkMultiBlockPLOT3DReader()
pl3d.SetXYZFileName(VTK_DATA_ROOT + "/Data/combxyz.bin")
pl3d.SetQFileName(VTK_DATA_ROOT + "/Data/combq.bin")
pl3d.SetScalarFunctionNumber(100)
pl3d.S... | etCenter()
sphere = vtk.vtkSphere()
sphere.SetCenter(center)
sphere.SetRadius(2.0)
sphere2 = vtk.vtkSphere()
sphere2.SetCenter(center[0] + 4.0, center[1], center[2])
sphere2.SetRadius(4.0)
boolOp = vtk.vtkImplicitBoolean()
boolOp.SetOperationTypeToUnion()
boolOp.AddFunction(sphere)
boolOp.AddFunction(sphe... |
johnaparker/Qbox | tests/dynamics/plot.py | Python | mit | 471 | 0.010616 | import h5py
import numpy as np
import matpl | otlib.pyplot as plt
import my_pytools.my_matpl | otlib.colors as colors
with h5py.File('out.h5', 'r') as f:
d = f["monitors/volume_monitor/vol/dft"][...]
Er = d['real']
Ei = d['imag']
I = Er**2 + Ei**2
I = I.squeeze()
phase = np.arctan2(Ei,Er).squeeze()
plt.gca().set_aspect('equal')
plt.pcolormesh(I.T, cmap=colors.cmap['parula'])
# pl... |
sbyount/pynet_test | class2ex2a.py | Python | apache-2.0 | 642 | 0 | import telnetlib
import time
IP = '184.105.247.70'
PORT = 23
TIMEOUT = 6
username = 'pyclass'
password = '88newclass'
# get connection with IP, port and timeout
my_conn = telnetlib.Telnet(IP, PORT, TIMEOUT)
# send username an | d password
output = my_conn.read_until('sername:', TIMEOUT)
my_conn.write | (username + '\n')
output = my_conn.read_until('assword:', TIMEOUT)
my_conn.write(password + '\n')
output = my_conn.read_very_eager()
# Disable paging and show version
output = my_conn.write('term len 0' + '\n')
output = my_conn.write('sh ip int br' + '\n')
time.sleep(1)
output = my_conn.read_very_eager()
print outpu... |
krahser/djbot | src/DJBot/utils/ansible_api.py | Python | gpl-3.0 | 8,299 | 0.00012 | #!/usr/bin/python2
from collections import namedtuple
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
from ansible.inventory import Inventory
from ansible.playbook.play import Play
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.plugins.callback i... | 'sftp_extra_args', 'scp_extra_args',
'become', 'become_method',
'become_user', 'verbosity', 'check'])
# Creat a callback object so we can capture the output
class ResultsCollector(Callback | Base):
def __init__(self, *args, **kwargs):
super(ResultsCollector, self).__init__(*args, **kwargs)
self.host_ok = {}
self.host_unreachable = {}
self.host_failed = {}
self.condition = threading.Semaphore(0)
def v2_runner_on_unreachable(self, result):
self.host_u... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.