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
Rhombik/rhombik-object-repository
project/views.py
Python
agpl-3.0
13,528
0.016263
from os import path from django.core.paginator import Paginator, InvalidPage, EmptyPage from django.core.urlresolvers import reverse from django.shortcuts import render_to_response, render, redirect from django.http import HttpResponseRedirect, HttpResponse from django.template import RequestContext from django.views...
=texts, galleryname="base", mainthumb=[mainthumb], downloadurl=downloadurl)) return render_to_response('article.html', RequestContext(request, c)) def front(request): return render_to_response('list.html', dict(project=project, user=request.user,)) ''' - Needs to ...
gine some sort of algorithm to factor in upvotes/downloads/comments and staff interest is needed to decide what is "popular". ''' def list(request): """Main listing.""" ### get all the projects! ### newprojects = Project.objects.exclude(draft=True).order_by("-created") paginator = Paginator(newproject...
Tjorriemorrie/housing
src/settings.py
Python
mit
496
0.002016
from os.path import dirname, realpath from jinja2 import Environment, FileSystemLoader from google.appengine.ext import ndb DEBUG = True SECRET_KEY = 'asdfjasdflkjsfewi23kjl3kjl45kjl56jk6hjb76vsjsa' CONFIG = { } SRC_ROOT = dirname(realpath(__file__)) JINJA_ENVIRONMENT = Environment( loader=FileSy
stemLoader(SRC_ROOT), extensions=['jinja2.ext
.autoescape'], autoescape=True, ) REGIONS = ['NSW', 'VIC', 'QLD', 'WA', 'SA', 'TAS', 'ACT', 'NT'] PARENT_KEY = ndb.Key('daddy', 'oz')
Danielhiversen/home-assistant
tests/components/subaru/test_config_flow.py
Python
apache-2.0
8,146
0.000123
"""Tests for the Subaru component config flow.""" # pylint: disable=redefined-outer-name from copy import deepcopy from unittest import mock from unittest.mock import patch import pytest from subarulink.exceptions import InvalidCredentials, InvalidPIN, SubaruException from homeassistant import config_entries from hom...
CE_ID] = TEST_DEVICE_ID assert result == expected async def test_pin_form_incorrect_pin(hass, pin_form): """Test we handle invalid pin."
"" with patch( MOCK_API_TEST_PIN, side_effect=InvalidPIN("invalidPin"), ) as mock_test_pin, patch( MOCK_API_UPDATE_SAVED_PIN, return_value=True, ) as mock_update_saved_pin: result = await hass.config_entries.flow.async_configure( pin_form["flow_id"], user_...
Vvucinic/Wander
venv_2_7/lib/python2.7/site-packages/Django-1.9-py2.7.egg/django/contrib/gis/maps/google/overlays.py
Python
artistic-2.0
11,955
0.000836
from __future__ import unicode_literals from functools import total_ordering from django.contrib.gis.geos import ( LinearRing, LineString, Point, Polygon, fromstr, ) from django.utils import six from django.utils.encoding import python_2_unicode_compatible from django.utils.html import html_safe @html_safe @pyt...
hat this will not
depict a Polygon's internal rings. Keyword Options: stroke_color: The color of the polygon outline. Defaults to '#0000ff' (blue). stroke_weight: The width of the polygon outline, in pixels. Defaults to 2. stroke_opacity: The opacity of ...
rspavel/spack
var/spack/repos/builtin/packages/xsdk/package.py
Python
lgpl-2.1
9,658
0.003417
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * import sys class Xsdk(BundlePackage): """Xsdk is a suite of Department of Energy (DOE) packages...
_on('dealii@9.0.1~assimp~python~doc~gmsh+petsc~slepc+mpi~int64+hdf5~netcdf+metis~ginkgo~symengine', when='@0.4.0 +dealii') depends_on('pflotran@develop', when='@develop') depends_on('pflotran@xsdk-0.5.0', when='@0.5.0') depends_on('pflotran@xsdk-0.4.0', when='@0.4.0') depends_on('pflotran@xsdk-0.3.0', ...
.3.0') depends_on('pflotran@xsdk-0.2.0', when='@xsdk-0.2.0') depends_on('alquimia@develop', when='@develop') depends_on('alquimia@xsdk-0.5.0', when='@0.5.0') depends_on('alquimia@xsdk-0.4.0', when='@0.4.0') depends_on('alquimia@xsdk-0.3.0', when='@0.3.0') depends_on('alquimia@xsdk-0.2.0', when=...
endthestart/schwag
schwag/schwag/urls.py
Python
mit
1,849
0.005949
from django.conf.urls import patterns, include, url from django.conf import settings # Uncomment the next two lines to enable t
he admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', 'schwag.views.home', name
='home'), url(r'^about/$', 'schwag.views.about', name='about'), url(r'^location/$', 'schwag.views.location', name='location'), url(r'^contact/$', 'schwag.views.contact', name='contact'), url(r'^bmx/$', 'schwag.views.bmx', name='...
random-forests/tensorflow-workshop
archive/extras/cat_dog_estimator/extract_cats_dogs.py
Python
apache-2.0
1,545
0.01165
"""One-time script for extracting all the cat and dog images from CIFAR-10.""" import cPickle import numpy as np from PIL import Image TRAIN_FILES = ['cifar-10-batches-py/data_batch_%d' % i for i in range(1,6)] TEST_FILE = 'test_batch' CAT_INPUT_LABEL = 3 DOG_INPUT_LABEL = 5 CAT_OUTPUT_LABEL = 1 DOG_OUTPUT_LABEL = ...
np.empty((num_cats + num_dogs), dtype=np.uint8) index = 0 for data_batch in data: for batch_index, label in enumerate(data_batch['labels']): if label == CAT_INPUT_LABEL or label == DOG_INPUT_LABEL: # Data is stored in B x 3072 format, convert to B' x 32 x 32 x 3 images[index, :, :, :] = np.transpose(...
a'][batch_index, :], newshape=(3, 32, 32)), axes=(1, 2, 0)) if label == CAT_INPUT_LABEL: labels[index] = CAT_OUTPUT_LABEL else: labels[index] = DOG_OUTPUT_LABEL index += 1 np.save('catdog_data.npy', {'images': images, 'labels': labels}) # Make sure images look cor...
hustbeta/python-web-recipes
server-sent-events/bottle-sse.py
Python
mit
517
0.005803
#!/usr/bin/env python # -*- coding: utf
-8 -*- import bottle import datetime import time @bottle.get('/') def index(): return bottle.static_file('index.html', root='.') @bottle.get('/stream') def stream(): bottle.response.content_type = 'text/event-stream' bottle.response.cache_control = 'no-cache' while True:
yield 'data: %s\n\n' % str(datetime.datetime.now()) time.sleep(5) if __name__ == '__main__': bottle.run(host='0.0.0.0', port=8080, debug=True)
apanda/modeling
mcnet/components/aclfirewall.py
Python
bsd-3-clause
2,245
0.015145
from . import NetworkObject import z3 class AclFirewall (NetworkObject): def _init(self, node, network, context): super(AclFirewall, self).init_fail(node) self.fw = node.z3Node self.ctx = context self.constraints = list () self.acls = list () network.SaneSend (self) ...
acl_func'%(self.fw), self.ctx.address, self.ctx.address, z3.BoolSort()) self.constraints.append(z3.ForAll([n_0, p_0, t_0], z3.Implies(self.ctx.send(self.fw, n_0, p_0, t_0), \ z3.Exists([t_1], \ z3.And(t_1 < t_0, \ z3.Not(self.faile...
3.Not(self.failed(t_0)), \ z3.Exists([n_1], \ self.ctx.recv(n_1, self.fw, p_0, t_1)), \ z3.Not(self.acl_func(self.ctx.packet.src(p_0), self.ctx.packet.dest(p_0)))))))) def _aclConstraints(self, solver): if len(self.acls) == 0: ...
latrop/GRCF
GRCFlibs/GRCFifaceFunctions.py
Python
gpl-3.0
80,548
0.004407
#! /usr/bin/env python import os import Tkinter as Tk import tkFileDialog, tkMessageBox import shelve import time from scipy.odr.odrpack import * from scipy.ndimage import minimum_position from pylab import * import pylab from PIL import Image from PIL import ImageTk from GRCFcommonFunctions import fig2img, fig2da...
2 FIS555 4.84 4.84 # 33 FIS606 4.63 4.72 # 34 FIS702 4.32 4.59 # 35 FIS814 4.12 4.53 # 36 LRIS B 5.46 5.42 # 37 LRIS V 4.82 4.83 # 38 LRIS R 4.46 4.63 # 39 LRIS Rs 4.33 4.59 # 40 LRIS I 4.04 4.53 # 41 LRIS Z 4.00 4.52 # 42 SPH Un 5.43 6.49 # 43 SPH G 5.21 5.11 # 44 SPH Rs 4.39 4.6...
4.67 4.75 # 52 ACS SDSS i 4.14 4.54 # 53 ACS I814 4.11 4.53 # 54 ACS SDSS z 4.00 4.52 # 55 Bessell U 5.55 6.36 # 56 Bessell B 5.45 5.36 # 57 Bessell V 4.80 4.82 # 58 Bessell J 3.67 4.57 # 59 Bessell H 3.33 4.71 # 60 Bessell K 3.29 5.19 # 61 KPNO J 3.66 4.57 # 62 KPNO H 3.33 4.71 # 63...
bootleg/ret-sync
ext_bn/retsync/__init__.py
Python
gpl-3.0
2,930
0.003413
#!/usr/bin/env python3 """ Copyright (C) 2020, Alexandre Gazet. This file is part of ret-sync plugin for Binary Ninja. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, includ...
y, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTW...
TICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from collections im...
stefanseefeld/numba
numba/cuda/tests/cudapy/test_operator.py
Python
bsd-2-clause
899
0
from __future__ import print_function, absolute_import, division import numpy as np from numba.cuda.testing import unittest from numba import cuda import operator class TestOperatorModule(unittest.TestCase): """ Test if operator module is supported by the CUDA target. """ def operator_template(self, ...
, b[i]) a = np.ones(1) b = np.ones(1) res = a.copy() foo[1, 1](res, b) np.testing.assert_equal(res, op(a, b)) def test_add(self): self.operator_template(operator.add) def test_sub(self): self.operator_template(operator.sub) def test_mul(self): ...
if __name__ == '__main__': unittest.main()
satuma777/evoltier
evoltier/selection/nes_selection.py
Python
gpl-3.0
510
0.003922
import n
umpy as np from ..weight import RankingBasedSelection class NESSelection(RankingBasedSelection): """ This selection scheme is Non-increasing transformation as NES weight. See also, [Wierstra et. al., 2014]<http://jmlr.org/papers/v15/wierstra14a.html> """ def transform(self, rank_based_vals, xp=np...
p.maximum(0, xp.log((lam / 2) + 1) - xp.log(rank_based_vals)) weight /= weight.sum() return weight - 1. / lam
banacer/door-wiz
src/identification/Identifier.py
Python
mit
1,449
0.006901
import numpy as np import pandas as pd from pandas import Series, DataFrame from scipy.spatial import distance import matplotlib.pyplot as plt from sklearn.cluster import DBSCAN from sklearn import metrics from sklearn.datasets.samples_generator import make_blobs from sklearn.preprocessing import StandardScaler from s...
eight', 'mean_width', 'min_width', 'max_width', 'time', 'girth','id'] self.data = DataFrame(columns=columns) self.event = [] @staticmethod def subscribe(ch, method, properties, body): """ prints the body message. It's the default callback method :param ch: keep null ...
am body: the message :return: """ #first we get the JSON from body #we check if it's part of the walking event #if walking event is completed, we if __name__ == '__main__': # we setup needed params MAX_HEIGHT = 203 MAX_WIDTH = 142 SPEED = 3 SAMPLING_RATE =...
nbro/ands
ands/algorithms/dp/subset_sum.py
Python
mit
3,075
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ # Meta-info Author: Nelson Brochado Created: 03/09/2015 Updated: 07/03/2018 # Description # TODO - Add description. - Add complexity analysis. - Add documentation to functions. """ __all__ = ["recursive_subset_sum", "bottom_up_subset_sum"] from pprint import p...
j: m[i][j] = 1 else: # We can include the current element, # because it is less than the current number j. if subset[i - 1] <= j: m[i][j] = max(m[i - 1][j], m[i - 1][j - subset[i - 1]]) else: ...
, 1, 1, 6), 12)) pprint(bottom_up_subset_sum([2, 2, 2, 6], 6, return_matrix=True)) print(bottom_up_subset_sum((1, 1, 6), 2, return_matrix=True)) recursive_subset_sum([-2, 8, 6], 6) # recursive_subset_sum((4, 2, 6), 6) # recursive_subset_sum((0, 0, 6), 6) # recursive_subset_sum((1, 3, 5, 5, 2, 1,...
EricssonResearch/calvin-base
calvinextras/calvinsys/media/audio/play/BasePlay.py
Python
apache-2.0
1,328
0.002259
# -*- coding: utf-8 -*- # Copyright (c) 2017 Ericsson AB # # 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/lic
enses/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 Licen
se for the specific language governing permissions and # limitations under the License. from calvin.runtime.south.calvinsys import base_calvinsys_object class BasePlay(base_calvinsys_object.BaseCalvinsysObject): """ Play audio file """ init_schema = { "type": "object", "properties...
nicolas-petit/clouder
clouder/clouder_runner_docker/runner.py
Python
gpl-3.0
7,557
0.000662
# -*- coding: utf-8 -*- ############################################################################## # # Author: Yannick Buron # Copyright 2015, TODAY Clouder SASU # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License with Attribution # ...
################################ from openerp import models, api, _, modules from openerp.exceptions import except_orm import time import logging _logger = log
ging.getLogger(__name__) class ClouderImageVersion(models.Model): """ Add methods to manage the docker build specificity. """ _inherit = 'clouder.image.version' @api.multi def hook_build(self, dockerfile): res = super(ClouderImageVersion, self).hook_build(dockerfile) if sel...
lbryio/lbryum-server
benchmarks/test_claims.py
Python
agpl-3.0
1,512
0.000661
import os from ConfigParser import ConfigParser from lbryumserver import deserialize from lbryumserver.claims_storage import ClaimsStorage from lbryumserver.processor import Dispatcher from .fixtures import raw_tx_with_claim def _get_config_for_test_storage(tmpdir): config = ConfigParser() config.add_section...
r(64 * 1024 * 1024)) config.set('leveldb', 'hist_cache', str(80 * 1024)) config.set('leveldb', 'addr_cache', str(16 * 1024 * 1024)) config.set('leveldb', 'claimid_cache', str(16 * 1024 * 1024 * 8)) config.set('leveldb', 'claim_value_cache', str(1024 * 1024 * 1024)) config.set('leveldb', 'profiler'...
s.path.join(tmpdir.strpath, 'lbryum_db')) return config def setup_claim_storage(tmpdir): config = _get_config_for_test_storage(tmpdir) dispatcher = Dispatcher(config) shared = dispatcher.shared return ClaimsStorage(config, shared, False) def deserialize_raw_tx(raw_tx): vds = deserialize.BCDa...
dscottcs/superluminal
superluminal/sample/forward_sample.py
Python
apache-2.0
510
0.001961
import requests import json import logging LOG =
logging.getLogger(__name__) class Forwarder(object): def __init__(self): this.fwd_url = 'http://localhost:9999/forward' def forward(self, reason, host=None, data=None): body = { 'reason': reason } if host is not None: body['host'] = host if data ...
son.dumps(body))
SuLab/genewiki
old-assets/scripts/create_template.py
Python
mit
480
0.004167
# -*- coding: utf-8 -*- ''' Creates a Gene Wiki protein box template around a gene specified by the first argument passed to it on the command line. Usage: `python create_template.py <entrez_id>` ''' import sys from genewiki.mygeneinfo import parse if len(sys.argv[1]) > 1: entrez = sys.ar
gv[1] try: int(entrez) except ValueError: sys.stderr.write("Entrez ids must contain only digits.") sys.exit(1)
sys.stdout.write(str(parse(entrez)))
ramnes/qtile
libqtile/widget/gmail_checker.py
Python
mit
2,825
0.000354
# Copyright (c) 2014 Sean Vig # Copyright (c) 2014, 2019 zordsdavini # Copyright (c) 2014 Alexandr Kriptonov # Copyright (c) 2014 Tycho Andersen # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Softw...
arch(r'MESSAGES\s+(\d+)', dec).group(1)) unseen = int(re.search(r'UNSEEN\s+(\d+)', dec).group(1)) if(self.status_only_unseen): return self.display_fmt.format(unseen) else: return self.
display_fmt.format(messages, unseen) else: logger.exception( 'GmailChecker UNKNOWN error, answer: %s, raw_data: %s', answer, raw_data) return "UNKNOWN ERROR"
tensorflow/tensorboard
tensorboard/plugins/hparams/download_data_test.py
Python
apache-2.0
8,571
0.00035
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
name: 'initial_temp' type: DATA_TYPE_FLOAT64 }, { name: 'final_temp' type: DATA
_TYPE_FLOAT64 }, { name: 'string_hparam' }, { name: 'bool_hparam' }, { name: 'optional_string_hparam' } ] metric_infos: [ { name: { tag: 'current_temp' } }, { name: { tag: 'delta_temp' } }, { name: { tag: 'optional_metric' } } ] """ SESSION_GROUPS = """ session_groups { name: "group_1" hparams { key:...
FEniCS/dolfin
test/unit/python/mesh/test_manifold_point_search.py
Python
lgpl-3.0
971
0
#!/usr/bin/env py.test import pytest import numpy from dolfin import * def test_manifold_point_search(): # Simple two-triangle surface in 3d vertices = [ (0.0, 0.0, 1.
0), (1.0, 1.0, 1.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0), ] cells = [ (0, 1, 2), (0, 1, 3), ] mesh = Mesh() me = MeshEditor() me.open(mesh, "triangle", 2, 3) me.init_vertices(len(vertices)) for i, v in enumerate(vertices): me.add_vertex(i,...
ell(i, numpy.array(c, dtype='uint')) me.close() mesh.init_cell_orientations(Expression(("0.0", "0.0", "1.0"), degree=0)) bb = mesh.bounding_box_tree() p = Point(2.0/3.0, 1.0/3.0, 2.0/3.0) assert bb.compute_first_entity_collision(p) == 0 p = Point(1.0/3.0, 2.0/3.0, 2.0/3.0) assert bb.compu...
epage/Gonvert
gonvert/constants.py
Python
gpl-2.0
161
0
__pretty_app_name__ = "Gonvert" __app_name__ = "gonvert" __version__ = "1.1.6" __build__ = 0 __app_magic__
= 0xdeadbeef PROFILE_STARTUP = False IS_MAE
MO = True
GeeteshKhatavkar/gh0st_kernel_samsung_royxx
arm-2010.09/arm-none-eabi/lib/armv6-m/libstdc++.a-gdb.py
Python
gpl-2.0
2,346
0.00682
# -*- python -*- # Copyright (C) 2009 Free Software Foundation, Inc. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # ...
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 not, see <http...
cery/arm-none-eabi/lib/armv6-m' # This file might be loaded when there is no current objfile. This # can happen if the user loads it manually. In this case we don't # update sys.path; instead we just hope the user managed to do that # beforehand. if gdb.current_objfile () is not None: # Update module path. We w...
jdmonaco/vmo-feedback-model
src/remapping/trends.py
Python
mit
9,633
0.005294
# encoding: utf-8 """ trends.py -- Analysis of trends in response changes across mismatch angle Exported namespace: MismatchTrends Created by Joe Monaco on 2010-02-17. Copyright (c) 2009-2011 Johns Hopkins University. All rights reserved. This software is provided AS IS under the terms of the Open Source MIT Licens...
distributions self.out('Computing smoothed density estimates...') rot_pdf = [] corr_pdf = [] for data in data_list: rots, corrs = data['rotcorr'].copy() rots[rots>180] -= 360 # make distal rots negative rot_pdf.append(smooth_pdf(rots)) corr...
) self.results['rotations_pdf'] = np.array(rot_pdf, 'O') self.results['correlations_pdf'] = np.array(corr_pdf, 'O') # Population code rotation via correlation diagonals self.out('Collating correlation diagonals...') diags = [data['diags_MIS'] for data in data_list] ...
czielinski/portfolioopt
portfolioopt/portfolioopt.py
Python
mit
9,550
0.001152
# The MIT License (MIT) # # Copyright (c) 2015 Christian Zielinski # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, cop...
-np.identity(n)))) h = opt.matrix(np.vstack((-1.0, np.zeros((n, 1))))) else: # exp_rets*x >= 1 G = opt.matrix(-exp_rets.values).T h = opt.matrix(-1.0) # Solve optsolvers.options['show_progress'] = False sol = optsolvers.qp(...
nto a labeled series weights = pd.Series(sol['x'], index=cov_mat.index) # Rescale weights, so that sum(weights) = 1 weights /= weights.sum() return weights def max_ret_portfolio(exp_rets): """ Computes a long-only maximum return portfolio, i.e. selects the assets with maximal return. If t...
arbn/pysaml2
tests/sp_2_conf.py
Python
bsd-2-clause
1,571
0.007638
from pathutils import full_path CONFIG = { "entityid" : "urn:mace:example.com:saml:roland:sp", "name" : "urn:mace:example.com:saml:roland:sp", "description": "My own SP", "service": { "sp": {
"endpoints":{ "assertion_consumer_service": ["http://lingon.catalogix.se:8087/"], }, "required_attributes": ["surName", "givenName", "mail"], "optional_attribu
tes": ["title"], "idp": ["urn:mace:example.com:saml:roland:idp"], } }, "debug" : 1, "key_file" : full_path("test.key"), "cert_file" : full_path("test.pem"), "xmlsec_binary" : None, "metadata": { "local": [full_path("idp_2.xml")], }, "virtual_organizati...
darkonie/dcos
dcos_installer/test_backend.py
Python
apache-2.0
12,196
0.002378
import json import os import subprocess import uuid import passlib.hash import pytest import gen import gen.build_deploy.aws import release from dcos_installer import backend from dcos_installer.config import Config, make_default_config_if_needed, to_config os.environ["BOOTSTRAP_ID"] = "12345" @pytest.fixture(scop...
conf').ensure(dir=True) # TODO(cmaloney): Add test
s for the behavior around a non-existent config.yaml # Setting in a non-empty config.yaml which has no password set make_default_config_if_needed('genconf/config.yaml') assert 'superuser_password_hash' not in Config('genconf/config.yaml').config # Set the password create_fake_b...
darkwing/kuma
kuma/users/tests/test_templates.py
Python
mpl-2.0
13,321
0.00015
import requests_mock from django.conf import settings from jingo.helpers import urlparams from nose.tools import eq_, ok_ from pyquery import PyQuery as pq from waffle.models import Flag from kuma.core.urlresolvers import reverse from . import UserTestCase from .test_views import TESTUSER_PASSWORD def add_persona_v...
# * Username field, blank # # * Hidden email address field, pre-populated with the # address used to authentic
ate to Persona. 'Thanks for signing in to MDN with Persona.', ('<form class="submission readable-line-length" method="post" ' 'action="/en-US/users/account/signup">'), ('<input autofocus="autofocus" id="id_username" ' 'maxlength="30" name="username" placehol...
vdloo/raptiformica
tests/unit/raptiformica/shell/consul/test_ensure_latest_consul_release.py
Python
mit
2,741
0.002189
from raptiformica.settings import conf from raptiformica.shell.consul import ensure_latest_consul_release from tests.testcase import TestCase class TestEnsureLatestConsulRelease(TestCase): def setUp(self): self.log = self.set_up_patch('raptiformica.shell.consul.log') self.execute_process = self.se...
_zip(self): self.remove.side_effect = FileNotFoundError # Does not raise FileNotFoundError ensure_latest_consul_release('1.2.3.4', port=2222) def test_ensure_latest_consul_release_downloads_latest_consul_release_with_no_clobber(self): ensure_latest_consul_release('1.2.3.4', port=22...
RCH == 'armv7l': consul_zip = 'consul_1.0.2_linux_arm.zip' else: consul_zip = 'consul_1.0.2_linux_amd64.zip' expected_binary_command = [ '/usr/bin/env', 'ssh', '-A', '-o', 'ConnectTimeout=5', '-o', 'StrictHostKeyChecking=no', '-o', ...
AntonSax/plantcv
plantcv/invert.py
Python
mit
794
0.001259
# Invert gray image import cv2 from . import print_image from . import plot_image def invert(img, device, debug=None): """Inverts grayscale images. Inputs: img = image object, grayscale device = device number. Used to count steps in the pipeline debug =
None, print, or plot. Print = save to file, Plot = print to screen. Returns: device = device number img_inv = inverted image :param img: numpy array :param device: int :param debug: str :return device: int :return img_inv: numpy array """ device += 1 img_inv = cv2.bitwise...
ge(img_inv, cmap='gray') return device, img_inv
mitsuhiko/flask
src/flask/app.py
Python
bsd-3-clause
82,515
0.000267
import functools import inspect import logging import os import sys import typing as t import weakref from datetime import timedelta from itertools import chain from threading import Lock from types import TracebackType from werkzeug.datastructures import Headers from werkzeug.datastructures import ImmutableDict from ...
: 1.0 The ``host_matching`` and ``static_host`` parameters were added. .. versionadded:: 1.0 The ``subdomain_matching`` parameter was added. Subdomain matching needs to be enabled manually now. Setting :data:`SERVER_NAME` does not implicitly enable it.
:param import_name: the name of the application package :param static_url_path: can be used to specify a different path for the static files on the web. Defaults to the name of the `static_folder` folder. :param static_folder: The folder with static file...
fredokun/TikZ-Editor
setup.py
Python
gpl-2.0
1,449
0.031056
#!/usr/bin/env python # Copyright 2012 (C) Mickael Menu <mickael.menu@gmail.com> # # 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 lat...
am. If not, see <http://www.gnu.org/licenses/>. # automatically downloads setuptools if needed import distribute_setup distribute_setup.use_setuptools() from setuptools import setup, find_packages import tikz_editor.globals as globals setup( name = globals.APPLICATION_NAME, version = globals.VERSION, packages = ...
= globals.AUTHORS, author_email = globals.EMAIL, description = globals.APPLICATION_DESCRIPTION, license = "GPL v2", keywords = "tikz code editor latex preview", url = globals.WEBSITE, # auto-creates a GUI Python script to launch the application entry_points = {'gui_scripts': ['tikz-editor...
pmdarrow/locust
locust/test/test_web.py
Python
mit
3,957
0.009351
import csv import json import sys import traceback from six.moves import StringIO import requests import mock import gevent from gevent import wsgi from locust import web, runners, stats from locust.runners import LocustRunner from locust.main import parse_options from .testcases import LocustTestCase class TestWebU...
csv" % self.web_port) self.assertEqual(200, response.status_code) def test_distribution_stats_csv(self): stats.global_stats.get("/test", "GET").log(120, 5612) response = requests.get("http://127.0.0.1:%i/stats/distribution/csv" % self.web_port) self.assertEqual(200, response.sta...
sys.exc_info()[2] runners.locust_runner.log_exception("local", str(e), "".join(traceback.format_tb(tb))) runners.locust_runner.log_exception("local", str(e), "".join(traceback.format_tb(tb))) response = requests.get("http://127.0.0.1:%i/exceptions/csv" % self.web_port) s...
kartikshah1/Test
user_profile/countries.py
Python
mit
6,689
0
from model_utils import Choices COUNTRIES = Choices( ('AF', 'Afghanistan'), ('AX', 'Aland Islands'), ('AL', 'Albania'), ('DZ', 'Algeria'), ('AS', 'American Samoa'), ('AD', 'Andorra'), ('AO', 'Angola'), ('AI', 'Anguilla'), ('AQ', 'Antarctica'), ('AG', 'Antigua and Barbuda'), ...
('EC', 'Ecuador'), ('EG', 'Egypt'), ('SV', 'El Salvador'), ('GQ', 'Equatorial Guinea'), ('ER', 'Eritrea'), ('EE', 'Estonia'), ('ET', 'Ethiopia'), ('FK', 'Falkland Islands (Malvinas)'), ('FO', 'Faroe Islands'), ('FJ', 'Fiji'), ('FI', 'Finland'), ('FR', 'France'), ('GF'...
('TF', 'French Southern Territories'), ('GA', 'Gabon'), ('GM', 'Gambia'), ('GE', 'Georgia'), ('DE', 'Germany'), ('GH', 'Ghana'), ('GI', 'Gibraltar'), ('GR', 'Greece'), ('GL', 'Greenland'), ('GD', 'Grenada'), ('GP', 'Guadeloupe'), ('GU', 'Guam'), ('GT', 'Guatemala'), ...
henrysher/spec4pypi
pyp2rpm/utils.py
Python
mit
1,076
0.004647
import functools from pyp2rpm import settings def memoize_by_args(func): """Memoizes return value of a func based on args.""" memory = {} @functools.wraps(func) def memoized(*args): if not args in memory.keys(): value = func(*args) memory[args] = value return ...
trove classifiers Returns: Fedora name of the package license or empty string, if no licensing information is found in trove classifiers. """ license = []
for classifier in trove: if classifier is None: continue if 'License' in classifier != -1: stripped = classifier.strip() # if taken from EGG-INFO, begins with Classifier: stripped = stripped[stripped.find('License'):] if stripped in settings.TROVE_LICENSE...
ahmedaljazzar/edx-platform
cms/celery.py
Python
agpl-3.0
1,791
0.003908
""" Import celery, load its settings from the django settings and auto discover tasks in all installed djang
o apps. Taken from: https://celery.readthedocs.org/en/latest/django/first-steps-with-django.html """ from __future__ import absolute_import import os from celery import Celery from django.conf import settings from openedx.core.lib.celery.routers import AlternateEnvir
onmentRouter # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') APP = Celery('proj') # Using a string here means the worker will not have to # pickle the object when using Windows. APP.config_from_object('django.conf:settings') APP.auto...
abacuspix/NFV_project
Flask_By_Example/chapter6/crimemap.py
Python
mit
726
0
from dbhelper import DBHelper from flask import Flask from flask import rende
r_template from flask import request app = Flask(__name__) DB = DBHelper() @app.route("/") def home(): try: data = DB.get_all_inputs() except Exception as e: print e data = None return render_template("home.html", data=data) @app.route("/add", methods=["POST"]) def add(): tr...
() @app.route("/clear") def clear(): try: DB.clear_all() except Exception as e: print e return home() if __name__ == '__main__': app.run(port=5000, debug=True)
hwoods723/script.gamescenter
main.py
Python
gpl-2.0
2,988
0.005689
# -*- coding: utf-8 -*- ''' script.matchcenter - Football information for Kodi A program addon that can be mapped to a key on your remote to display football information. Livescores, Event details, Line-ups, League tables, next and previous matches by team. Follow what others are saying about the match ...
Cache from resources.lib.utilities import keymapeditor from resources.lib.utilities.common_addon import * def get_params(): pairsofparams = [] if len(sys.argv) >= 2: params=sys.argv[1] pairsofparams=params.split('/') pairsofparams = [parm for parm in pairsofparams if parm] return p...
() if not params: if "script-matchcenter-MainMenu.xml" not in xbmc.getInfoLabel('Window.Property(xmlfile)'): mainmenu.start() else: #Integration patterns below ''' Eg: xbmc.executebuiltin("RunScript(script.matchcenter, /eventdetails/506227)") ''' if params[0] == 'ignoreleagues': ...
FlashXT/XJTU_WorkLog
2017.10/Engineering/PyGame/alien_invasion/ship.py
Python
gpl-3.0
1,131
0.052166
#coding=utf-8 #2017.10.3£¬Flash,ship class import pygame class Ship(): def __init__(self,ai_settings,screen): """³õʼ»¯·É´¬²¢ÉèÖÃÆä³õʼλÖÃ""" self.screen=screen self.ai_settings = ai_settings #¼ÓÔØ·É´¬Í¼Ïñ²¢»ñÈ¡ÆäÍâ½Ó¾ØÐÎ self.image=pygame.image.load("images/ship.bmp") self.rect=self.imag...
self.center=float(self.rect.centerx) #ÒÆ¶¯±êÖ¾ self.moving_right = False self.moving_left = False def update(self): """¸ù¾ÝÒÆ¶¯±êÖ¾µ÷Õû·É´¬µÄλÖÃ""" #¸üзɴ¬µÄcenterÖµ£¬¶ø²»ÊÇrect if self.moving_right and self.rect.right < self.screen_rect.right: self.center += self.ai_settings.ship_speed...
rect.centerx = self.center def blitme(self): """ÔÚÖ¸¶¨Î»ÖûæÖÆ·É´¬""" self.screen.blit(self.image,self.rect)
fifoforlifo/pynja
packages/pynja/build.py
Python
apache-2.0
15,654
0.005366
import sys import os from . import io from . import root_paths from abc import * def ninja_esc_path(path): return path.replace('$','$$').replace(' ','$ ').replace(':', '$:') def xlat_path(project, path): """Translate common prefix to variable reference.""" if path.startswith(project.projectDir): ...
e of phony target to declare with this self._emitted = False def __enter__(self): if self._emitted: raise Exception("A task should not be re-used in a with statement.") return self def __exit__(self, type, value, traceback): self._emit_once() def _emit_once(sel...
d def emit(self): pass class BuildTasks: def __init__(self, tasks): self.__dict__["_tasks"] = tasks self.__dict__["_emitted"] = False def __len__(self): return self._tasks.__len__() def __getitem__(self, index): return self._tasks[index] def __iter__(self...
manufacturedba/pinax
pinax/apps/signup_codes/stats.py
Python
mit
548
0.00365
import datetime from pinax.apps.signup_codes.models import SignupCode def stats(): return { "signup_codes_total": SignupCode.objects.count(), "signup_codes_sent": SignupCode.objects.filter(sent__isnull=True).count(
), "signup_codes_used": SignupCode.objects.filter(use_count__gt=0).count(), "signup_codes_expired": SignupCode.object
s.exclude( expiry__isnull=True ).filter( expiry__lte=datetime.datetime.now(), use_count=0 ).count() }
xiangke/pycopia
SMI/setup.py
Python
lgpl-2.1
1,514
0.044914
#!/usr/bin/python2.4 # vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab import ez_setup ez_setup.use_setuptools() from glob import glob from setuptools import setup, Extension NAME = "pycopia-SMI" VERSION = "1.0a2" ENAME = NAME.replace("-", "_") DNAME = NAME.split("-", 1)[-1] _libsmi = Extension("_libsmi", ["libs...
["pycopia"], packages = ["pycopia", "pycopia.SMI"], # custom Python
wrapper - use this one. install_requires = ['pycopia-aid>=1.0a1,==dev'], scripts = glob("bin/*"), zip_safe = False, test_suite = "test.SMITests", author = "Keith Dart", author_email = "keith@kdart.com", description = "Python wrapper for libsmi, providing access to MIB/SMI data files.", ...
alexkasko/krakatau-java
krakatau-lib/src/main/resources/Lib/Krakatau/ssa/constraints/obj_c.py
Python
gpl-3.0
4,428
0.005194
import itertools from ..mixin import ValueType from .int_c import IntConstraint from .. import objtypes array_supers = 'java/lang/Object','java/lang/Cloneable','java/io/Serializable' obj_fset = frozenset([objtypes.ObjectTT]) def isAnySubtype(env, x, seq): return any(objtypes.isSubtype(env,x,y) for y in seq) clas...
sBot @staticmethod def constNull(env): return Ob
jectConstraint(True, TypeConstraint(env, [], [])) @staticmethod def fromTops(env, supers, exact, nonnull=False): types = TypeConstraint(env, supers, exact) if nonnull and not types: return None return ObjectConstraint(not nonnull, types) def _key(self): return self.null...
serghei/kde3-kdeutils
superkaramba/examples/setIncomingData/2.py
Python
gpl-2.0
2,246
0.007124
# # Written by Luke Kenneth Casson Leighton <lkcl@lkcl.net> # This theme is demonstrates how to #this import statement allows access to the karamba functions import karamba drop_txt = None #this is called when you widget is initialized def initWidget(widget): # this resets the text to "" so we know we've nev...
edrawWidget(widget) pass # This will be printed when the widget loads. print "Loaded my python
2.py extension!"
seims/SEIMS
scenario_analysis/util.py
Python
gpl-2.0
1,939
0.00361
import os, platform sysstr = platform.system() if sysstr == "Windows": LF = '\r\n' elif sysstr == "Linux": LF = '\n' def StripStr(str): # @Function: Remove space(' ') and indent('\t') at the begin and end of the string oldStr = '' newStr = str while oldStr != newStr: oldStr = newStr ...
path.isdir(path): if os.path.exists(path): return True else: return False else: return False def WriteLog(logfile, contentlist, MODE='replace'): if os.path.exists(logfile): if MODE == 'replace': os.remove(logfile) logStatus = op
en(logfile, 'w') else: logStatus = open(logfile, 'a') else: logStatus = open(logfile, 'w') if isinstance(contentlist, list) or isinstance(contentlist,tuple): for content in contentlist: logStatus.write("%s%s" % (content, LF)) else: logStatus.write(cont...
tensorflow/tensorflow
tensorflow/compiler/mlir/tensorflow/tests/tf_saved_model/shapes_for_arguments.py
Python
apache-2.0
1,730
0.009827
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in complia
nce with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or...
================================================================= # RUN: %p/shapes_for_arguments | FileCheck %s # pylint: disable=missing-docstring,line-too-long import tensorflow.compat.v2 as tf from tensorflow.compiler.mlir.tensorflow.tests.tf_saved_model import common class TestModule(tf.Module): # Check that...
puyilio/Application-for-PyBoard
About_author.py
Python
gpl-3.0
1,254
0.011962
#!/usr/bin/python # -*- coding: utf-8 -*- import sys from PyQt4 import QtGui,QtCore from Ui_about_author import Ui_About _IME = "<p
>Author: Bojan Ili""&#263;</p>" _FAKULTET = "Faculty
of Electrical Engineering, University of Belgrade - ETF" _MAIL = "https.rs@gmail.com" _URL = "<a href = ""https://www.facebook.com/puzicius>Facebook link</a>" #------------------------------------------------------------------------------- class AboutWindow2(QtGui.QDialog): """ Class wrapper for about window...
rajeev001114/Grade-Recording-System
project/MSG/migrations/0018_auto_20150917_0722.py
Python
gpl-3.0
550
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals fro
m django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('MSG', '0017_auto_20150917_0707'), ] operations = [ migrations.RemoveField( model_name='content', name='filename', ), migrations.AddField( mo...
pylanglois/Social-Network-Harvester
SocialNetworkHarvester/snh/management/commands/cronharvester/youtubech.py
Python
bsd-3-clause
8,013
0.009485
# coding=UTF-8 from datetime import timedelta import resource import time import urllib from django.core.exceptions import ObjectDoesNotExist from snh.models.youtubemodel import * from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned import snhlogger logger = snhlogger.init_logger(__name__, ...
e = ytcomment.author[0].name.text snhuser = update_user(harvester, author_name) split_uri = ytcomment.id.text.split("/") fid = split_uri[len(split_uri)-1] try: try: snhcomment = YTComment.objects.get(fid__exact=fid) except ObjectDoesNotExist: snhcomment = YTCommen...
snhcomment.update_from_youtube(snhvideo, snhuser, ytcomment) except: msg = u"Cannot update comment %s" % (unicode(ytcomment.id.text,'UTF-8')) logger.exception(msg) usage = resource.getrusage(resource.RUSAGE_SELF) logger.debug(u"Commment updated: comid:%s vidid:%s %s Mem:...
lmazuel/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2017_11_01/models/azure_reachability_report_parameters_py3.py
Python
mit
2,234
0.000895
# codi
ng=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ca...
st if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class AzureReachabilityReportParameters(Model): """Geographic and time constraints for Azure reachability report. All required parameters must be populated in ...
julietalucia/page-objects
page_objects/__init__.py
Python
mit
4,653
0.001075
from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.by import By # Map PageElement constructor arguments to webdriver locator enums _LOCATOR_MAP = {'css': By.CSS_SELECTOR, 'id_': By.ID, 'name': By.NAME, 'xpath': By.XPATH, ...
> 1: raise ValueError("P
lease specify only one locator") k, v = next(iter(kwargs.items())) self.locator = (_LOCATOR_MAP[k], v) self.has_context = bool(context) def find(self, context): try: return context.find_element(*self.locator) except NoSuchElementException: return None...
zhuangjun1981/retinotopic_mapping
retinotopic_mapping/DisplayStimulus.py
Python
gpl-3.0
29,197
0.002432
''' Visual Stimulus codebase implements several classes to display stimulus routi
nes. Can display frame by frame or compress data for certain stimulus routines and display by index. Used to manage information between experimental devices and interact with `Stim
ulusRoutines` to produce visual display and log data. May also be used to save and export movies of experimental stimulus routines for presentation. ''' from psychopy import visual, event import PIL import os import datetime import numpy as np import matplotlib.pyplot as plt import time from tools import FileTools as f...
soarpenguin/python-scripts
www-url.py
Python
gpl-3.0
823
0.013564
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Import system libs import re class WWW(): def __init__(self): pass def get_domain(self, site): if site.startswith('https://'): site = site[8:-1]
elif site.startswith('http://'): site = site[7:-1] return site.split('/')[0] def is_url_format(self, url):
regex = """ ^ #必须是串开始 (?:http(?:s)?://)? #protocol (?:[\w]+(?::[\w]+)?@)? #user@password ([-\w]+\.)+[\w-]+(?:.)? #domain (?::\d{2,5})? #port (/?[-:\w;\./?%&=#]*)? #params $ """ result = re....
volkodav1985/volkodavpython
model/contact.py
Python
apache-2.0
957
0.015674
from sys import maxsize class Contact: def __init__(self, firstname=None, lastname=None, company=None, homephone=None, workphone=None, mobilephone=None, secondphone=None, address=None
, year=None, secondaddress=None, id=None): sel
f.firsrtname=firstname self.lastname=lastname self.company=company self.homephone=homephone self.mobilephone=mobilephone self.workphone=workphone self.secondphone=secondphone self.address=address self.year=year self.secondaddress=secondaddress ...
andir/ganeti
lib/tools/burnin.py
Python
bsd-2-clause
47,078
0.00822
#!/usr/bin/python # # Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012 Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the ab...
_replace2", help="Skip disk replacement with a different secondary", action="store_false", default=True), cli.cli_option("--no-failover", dest="do_failover", help="Skip instance failovers", action="store_false", default=True), cli.cli_option("--no-...
instance live migration", action="store_false", default=True), cli.cli_option("--no-move", dest="do_move", help="Skip instance moves", action="store_false", default=True), cli.cli_option("--no-importexport", dest="do_importexport", help="Skip inst...
CPedrini/TateTRES
gspread/__init__.py
Python
apache-2.0
475
0
# -*- coding: utf-8 -*- """ gspread ~~~~~~~ Google Spreadsheets client library.
""" __version__ = '0.2.1' __author__ = 'Anton Burnashev' from .client import Client, login from .models import Spreadsheet, Worksheet, Cell from .exceptions import (GSpreadException, Authen
ticationError, SpreadsheetNotFound, NoValidUrlKeyFound, IncorrectCellLabel, WorksheetNotFound, UpdateCellError, RequestError)
emgirardin/compassion-modules
child_compassion/controllers/web_children_hold.py
Python
agpl-3.0
2,889
0
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (C) 2016 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Michael Sandoz <michaelsandoz87@gmail.com>, Emanuel Cino # # The licence is in ...
tastructures import Headers _logger = logging.getLogger(__name__) class RestController(http.Controller): @http.route('/web_children_hold', type='http', auth='public', methods=
[ 'GET']) def handler_web_children_hold(self): headers = request.httprequest.headers self._validate_headers(headers) # load children via a research on childpool child_research = request.env['compassion.childpool.search'].sudo() research = child_research.create({'tak...
neoranger/ActionLauncher
action_launcher.py
Python
gpl-3.0
8,866
0.012407
# -*- coding: utf-8 -*- # Action Launcher Bot: This is a bot how can execute differents actions depends commands # Code wrote by Zagur of PortalLinux.es and modified by NeoRanger of neositelinux.com # For a good use of the bot please read the README file import telebot from telebot import types import time ...
n(m, git_pull) @bot.message_handler(commands=['nmap_all']) def comman
d_nmap_all(m): nmap_all = commands.getoutput('sudo nast -m -i eth0') send_message_checking_permission(m, nmap_all) @bot.message_handler(commands=['nmap_active']) def command_nmap_active(m): nmap_active = commands.getoutput('sudo nast -g -i eth0') send_message_checking_permission(...
klebercode/lionsclub
eventi/subscriptions/tests/test_models.py
Python
mit
1,854
0.001618
# coding: utf-8 from django.test import TestCase from django.db import IntegrityError from datetime import datetime from eventex.subscriptions.models import Subscription class SubscriptionTest(TestCase): def setUp(self): self.obj = Subscription( name='Henrique Bastos', cpf='1234567...
Subsc
ription(name='Henrique Bastos', cpf='12345678901', email='outro@email.com', phone='21-96186180') self.assertRaises(IntegrityError, s.save) def test_email_can_repeat(self): """ Email is not unique anymore. """ s = Subscription.objects.create(name='Hen...
landism/pants
src/python/pants/backend/codegen/antlr/java/register.py
Python
apache-2.0
791
0.005057
# coding=utf-8 # Copyright 2016 Pants project contributors (see CONTRIBUTORS.md). # Licensed
under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_
statement) from pants.backend.codegen.antlr.java.antlr_java_gen import AntlrJavaGen from pants.backend.codegen.antlr.java.java_antlr_library import JavaAntlrLibrary from pants.build_graph.build_file_aliases import BuildFileAliases from pants.goal.task_registrar import TaskRegistrar as task def build_file_aliases(): ...
thiagof/treeio
treeio/identities/forms.py
Python
mit
15,660
0.00166
# encoding: utf-8 # Copyright 2011 Tree.io Limited # This file is part of Treeio. # License www.tree.io/license """ Identities module forms """ from django import forms from django.core.files.storage import default_storage from django.template import defaultfilters from django.core.urlresolvers import reverse from dja...
d"), choices=(('', '-----'), ('delete', _('Delete Completely')), ('trash', _('Move to Trash'))), required=False) instance = None def __init__(self, user, *ar
gs, **kwargs): if 'instance' in kwargs: self.instance = kwargs['instance'] del kwargs['instance'] super(MassActionForm, self).__init__(*args, **kwargs) self.fields['delete'] = forms.ChoiceField(label=_("With selected"), ...
googleapis/python-securitycenter
samples/generated_samples/securitycenter_v1_generated_security_center_get_iam_policy_sync.py
Python
apache-2.0
1,489
0.000672
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
# pyth
on3 -m pip install google-cloud-securitycenter # [START securitycenter_v1_generated_SecurityCenter_GetIamPolicy_sync] from google.cloud import securitycenter_v1 def sample_get_iam_policy(): # Create a client client = securitycenter_v1.SecurityCenterClient() # Initialize request argument(s) request ...
davyx8/Python
PRODICTIVE/tfidf.py
Python
gpl-3.0
2,184
0.005495
import nltk import string import operator from collections import Counter # # def get_tokens(): # with open('/home/davyx8/Downloads/data sets/lebowski/fargo.txt', 'r') as shakes: # text = shakes.read() # lowers = text.lower() # #remove the punctuation using the character deletion step of translate # ...
e time tfidf = TfidfVectorizer(tokenizer=tokenize, stop_words='english') tfs = tfidf.fit_transform(token_dict.values()) feature_names = tfidf.get_feature_names() sortedx = {} for filename in token_dict: print filename file = token_dict[filename] sortedx = {}
response = tfidf.transform([file]) for col in response.nonzero()[1]: sortedx[feature_names[col]] = tfs[0,col] sortedx2 = sorted(sortedx.items(), key=operator.itemgetter(1)) f = open('medicalTFIDF/'+filename,"w") for item in sortedx2: f.write(str(item[0])+ '- ' +str(item[1])+'\n') f....
abranches/backmonitor
backmonitor/tests/frame_tests.py
Python
apache-2.0
1,806
0.001661
import unittest import ran
dom from ..frame import Frame, decode_frame from ..message import MessageType from ..utilslib.strings import random_bytes class FrameTestCase(unittest.TestCase): MSG_TYPE = MessageType.HELLO PAYLOAD = "Hello World!" def frame_setup(self, msg_type, payload): self.msg_type = msg_type self.p...
PE, self.PAYLOAD) def tearDown(self): self.msg_type = None self.payload = None self.frame = None def test_eq_at_decode_after_encode(self): consumed_bytes, decoded = decode_frame(self.frame.encode()) self.assertIsNotNone(self, decoded) self.assertEqual(self.frame...
fudanchii/archie
archie/handlers/restore.py
Python
mit
753
0.003984
import os import tarfile from contextlib i
mport closing from archie import helpers def find_backup(cfg): files = [] rcfiles = cfg.options('rcfiles') for rc in rcfiles: backup = helpers.get_backupfile(cfg, rc) rcfile = helpers.get_rcfile(cfg, rc) if os.path.lexists(backup) and tarfile.is_tarf
ile(backup): files.append((backup, rcfile)) return files def gunzip_and_restore(cfg, backupfiles): for backup, rc in backupfiles: if os.path.islink(rc): os.unlink(rc) with closing(tarfile.open(backup, 'r:gz')) as tar: tar.extractall('/') return backupfile...
JackyChou/SGRS
SGRS/urls.py
Python
gpl-2.0
359
0.005571
from django.conf.
urls import include, url from django.contrib import admin def i18n_javascript(request): return admin.site.i18n_javascript(request) urlpatterns = [ url(r'^$', 'GeneralReport.views.index'), url(r'^sgrs/', include('GeneralReport.urls')), url(r'^admin/jsi18n', i1
8n_javascript), url(r'^admin/', include(admin.site.urls)), ]
OpenSoccerManager/opensoccermanager
uigtk/window.py
Python
gpl-3.0
3,411
0.002345
#!/usr/bin/env pyth
on3 # This file is part of OpenSoccerManager. # # OpenSoccerManager 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. # # OpenSocc...
SE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along with # OpenSoccerManager. If not, see <http://www.gnu.org/licenses/>. import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk from gi.repository import GdkPixbu...
andrewbates09/FERGUS
fergus/__init__.py
Python
gpl-3.0
291
0.024055
''' Library for d
oing fun things with computers. ''' __author__ = 'Andrew M Bates' __version__ = '0.001' import io, os, sys # the core imports go here # this should go in in the mods dir try: '''IF RASPBERRY PI & HAS A GPIO BOARD''' import RPi.GP
IO as RPi except ImportError: pass
ruaultadrien/canpy
canpy/defects_movie.py
Python
gpl-3.0
2,116
0.025083
# -*- coding: utf-8 -*- """ Created on Sun Feb 14 20:43:12 2016 @author: Adrien """ import canpy.point_defects def defects_movie(dl,t_start='standard',t_end='standard'): ''' Produce a movie in mp4 format of the defects. t_start is the time at which we want the movie to begin and t_end is th...
.set_ylim3d(0,self.length) ax.set_zlim3d(0,self.length) ax.legend(frameon = True, fancybox = True, ncol = 1, fontsize = 'x-small', loc = 'lower right') def animate(i): ax.scatter(xi, yi, zi, label='Interstitial...
t '+str(self.time)+' ps') # Animate anim = animation.FuncAnimation(fig, animate, init_func=init,frames=360, interval=speed*20, blit=True) # Save anim.save('rot_frame_anim_'+str(self.time)+'ps.mp4', fps=30, extra_args=['-vcodec', 'libx264'])
m110/pastevim
manage.py
Python
gpl-2.0
251
0
#!/usr/b
in/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pastevim.settings") from django.core.management import execute_from_command_line execute_from_command_
line(sys.argv)
Ckrisirkc/Red-DiscordBot
cogs/customcom.py
Python
gpl-3.0
5,602
0.003213
import discord from discord.ext import commands from .utils.dataIO import fileIO from .utils import checks from __main__ import user_allowed, send_cmd_help import os class CustomCommands: """Custom commands.""" def __init__(self, bot): self.bot = bot self.c_commands = fileIO("data/customcom/co...
say("There are no custom commands in
this server. Use addcom [command] [text]") @commands.command(pass_context=True, no_pm=True) async def customcommands(self, ctx): """Shows custom commands list""" server = ctx.message.server if server.id in self.c_commands: cmdlist = self.c_commands[server.id] if...
rdio/sentry
tests/sentry/nodestore/django/backend/tests.py
Python
bsd-3-clause
2,382
0.001679
# -*- coding: utf-8 -*- from __future__ import absolute_import from sentry.nodestore.django.models import Node from sentry.nodestore.django.backend import DjangoNodeStorage from sentry.testutils import TestCase class DjangoNodeStorageTest(TestCase): def setUp(self): self.ns = DjangoNodeStorage() de...
et(id=node_id).data == { 'foo': 'bar', } def test_delete(self): node = Node.objects.create(
id='d2502ebbd7df41ceba8d3275595cac33', data={ 'foo': 'bar', } ) self.ns.delete(node.id) assert not Node.objects.filter(id=node.id).exists()
hezuoguang/Yeps-Server
Yeps/Yep/tools.py
Python
mit
943
0.009967
#coding:utf-8 import hashlib, datetime, pdb from Yep import system_tags, system_schools MD5PERFIX = "YEPS_WEIMI" def md5_pwd(pwd): return hashlib.new("md5", MD5PERFIX + pwd).hexdigest() # 检查标签是否合法 def check_user_tag(tags): tag_list = system_tags.tag_list for tag in tags: if tag not in tag_list:...
return False return True # 检查学校是否合法 def check_school(school): school_list = system_schools.school_list if school in school_list: return True return False # 计算sha1 def sha1_with
_args(*kwargs): sha1 = hashlib.sha1() for arg in kwargs: sha1.update(arg) sha1 = sha1.hexdigest() return sha1 # 计算access_token def init_access_token(user_sha1, pwd): return hashlib.new("md5", MD5PERFIX + user_sha1 + pwd).hexdigest() # datetime to "XXXX-XX-XX : XX:XX:XX" def date_time_to_st...
ojengwa/grr
lib/flows/general/registry.py
Python
apache-2.0
6,980
0.008739
#!/usr/bin/env python """Gather information from the registry on windows.""" import re import stat from grr.lib import aff4 from grr.lib import artifact from grr.lib import artifact_lib from grr.lib import flow from grr.lib import rdfvalue from grr.lib import utils from grr.proto import flows_pb2 class RegistryFind...
dler(next_state="Done") def ParseRunKeys(self, responses): """Get filenames from the RunKeys and download the files."""
filenames = [] client = aff4.FACTORY.Open(self.client_id, mode="r", token=self.token) kb = artifact.GetArtifactKnowledgeBase(client) for response in responses: runkey = response.registry_data.string path_guesses = utils.GuessWindowsFileNameFromString(runkey) path_guesses = filter(self._...
exleym/simpaq
solvers/regressions.py
Python
mit
390
0
impor
t statsmodels.api as sm import numpy as np class LSM(object): def __init__(self, lambdas): self.lambdas = lambdas def calc(self, y, x): X = np.zeros((len(x), len(self.lambdas))) for i in range(0, len(self.lambdas)): X[:, i] = self.lambdas[i](x) ols = sm.OLS(y, sm....
t(X, prepend=False)).fit() return ols.params
sarbi127/inviwo
data/scripts/loadtransferfunction.py
Python
bsd-2-clause
150
0.026667
# I
nviwo Python script import inviwo inviwo.loadTransferFunction("SimpleRaycaster.transferFunction",inviwo.getDataPath() + "transferfunction.itf"
)
smallyear/linuxLearn
salt/salt/pillar/git_pillar.py
Python
apache-2.0
16,836
0
# -*- coding: utf-8 -*- ''' Use a git repository as a Pillar source --------------------------------------- .. note:: This external pillar has been rewritten for the :doc:`2015.8.0 </topics/releases/2015.8.0>` release. The old method of configuring this external pillar will be maintained for a couple relea...
# this repository - root: pillar - privkey: /path/to/key - pubkey: /path/to/key.pub - passphrase: CorrectHorseBatteryStaple # HTTPS authentication - master https://other-
git-server/pillardata-https.git: - user: git - password: CorrectHorseBatteryStaple The main difference between this and the old way of configuring git_pillar is that multiple remotes can be configured under one ``git`` section under :conf_master:`ext_pillar`. More than one ``git`` section can be us...
SEL-Columbia/commcare-hq
corehq/apps/cloudcare/touchforms_api.py
Python
bsd-3-clause
4,169
0.003118
from casexml.apps.case.models import CommCareCase from dimagi.utils.decorators.memoized import memoized from touchforms.formplayer.api import post_data import json from django.conf import settings from corehq.apps.cloudcare import CLOUDCARE_DEVICE_ID from django.core.urlresolvers import reverse from corehq.apps.users.m...
d self._delegation = delegation self.offline = offline @property @memoized def case(self): return CommCareCase.get(self.case_id) @property def case_type(self): return self.case.type @property def _case_parent_id(self): """Only makes sense if the cas...
tub""" return self.case.get_index_map().get('parent')['case_id'] @property def delegation(self): if self._delegation and self.case_id: assert self.case_type == DELEGATION_STUB_CASE_TYPE return self._delegation def get_session_data(self, device_id=CLOUDCARE_DEVICE_ID): ...
cspode/SU2
SU2_PY/SU2/util/filter_adjoint.py
Python
lgpl-2.1
16,651
0.025404
#!/usr/bin/env python ## \file filter_adjoint.py # \brief Applies various filters to the adjoint surface sensitivities of an airfoil # \author T. Lukaczyk, F. Palacios # \version 5.0.0 "Raven" # # SU2 Lead Developers: Dr. Francisco Palacios (Francisco.D.Palacios@boeing.com). # Dr. Thomas D. Ec...
by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # SU2 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 Public # License along with SU2. If not, see <http://www.gnu.org/licenses/>. import os, math from numpy import pi from optparse import OptionParser import numpy as np import libSU2, libSU2_mes...
amidvidy/mongo-orchestration
mongo_orchestration/sharded_clusters.py
Python
apache-2.0
18,384
0.000925
#!/usr/bin/python # coding=utf-8 # Copyright 2012-2014 MongoDB, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
if shard.get('isServer'): client = Servers()._storage[instance_id].connection elif shard.get('isReplicaSet'): client = ReplicaSets()._storage[instance_id].connection() db = client[self.auth_source] if self.x509_extr...
db.add_user(**secondary_login) if self.restart_required: # Do we need to add clusterAuthMode back? cluster_auth_mode = None for cfg in shard_configs: cam = cfg.get('clusterAuthMode') if cam: cluster_auth_mod...
codingforentrepreneurs/digital-marketplace
src/billing/models.py
Python
mit
589
0.027165
from django.conf import settings from django.db import models # Create your models here. from products.models import Product class Transaction(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) product = models.ForeignKey(P
roduct) price = models.DecimalField(max_digits=100, decimal_places=2, default=9.99, null=True,) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) success = models.BooleanField(default=True) # transaction_id_payment_system = Brain
tree / Stripe # payment_method # last_four def __unicode__(self): return "%s" %(self.id)
vlegoff/tsunami
src/secondaires/calendrier/evenement.py
Python
bsd-3-clause
4,012
0.006263
# -*-coding:Utf-8 -* # Copyright (c) 2010-2017 AYDIN Ali-Kémal # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this ...
T LIMITED TO, PROCUREMENT # OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTER
RUPTION) 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 THE # POSSIBILITY OF SUCH DAMAGE. """Ce fichier contient la classe Evenement, détaillée plus bas.""" imp...
bt3gl/Numerical-Methods-for-Physics
homework5_elliptic_PDES/main.py
Python
apache-2.0
2,009
0.019413
""" Any vector field U can be decomposed into a divergence free term Ud and the gradient of a scalar, phi: U = Ud + phi This program recovers a divergemce-free filed on a 2-d grid. Marina von Steinkirch, based on M. Zingale's codes, spring 2013 """ from part_a imp
ort doPartA from part_b import doPartB, error from part_c import doPartC import os import numpy def main(): """ Do you want to make plots??? """ DO_PLOTS = 1 """ create folder for plots """ try: os.makedirs("plots/") except OSError: if not os.path.isdir("plots/"): ...
"" [0,1]x[0,1]""" xmin = 0.0 xmax = 1.0 ymin = 0.0 ymax = 1.0 """ setting the number of cells """ nx = [32,64] ny = [32,64] ng = 1 for i in range(len(nx)): print "Calculating for [%d,%d] cells..." %(nx[i], ny[i]) """ set the limits, grid limits ...
Connexions/cnx-user
cnxuser/_sqlalchemy.py
Python
agpl-3.0
1,342
0
# -*
- coding: utf-8 -*- # ### # Copyright (c) 2013, Rice University # This software is subject to the provisions of the GNU Affero General # Public License version 3 (AGPLv3). # See LICENCE.txt for details. # ### import uuid from sqlalchemy.types import TypeDecorator, CHAR from sqlalchemy.dialects.postgresql import UUID ...
form-independent GUID type. Uses Postgresql's UUID type, otherwise uses CHAR(32), storing as stringified hex values. """ impl = CHAR def load_dialect_impl(self, dialect): if dialect.name == 'postgresql': return dialect.type_descriptor(UUID()) else: return d...
fapable/pygameproject2
Input.py
Python
apache-2.0
2,779
0.031306
import pygame import sys pygame.init() class Input: def __init__(self): self.shift = False self.white = (255,255,255) self.red = (255,10,10) self.black = (0,0,0) def get_key(self): while True: event = pygame.event.poll() if event.type == pygame.QUIT: p...
t(event.key) if event.key in [pygame.K_LSHIFT, pygame.K_RSHIFT]: self.shift = True continue if self.shift: #return ascii code if event.key >= 97 and event.key
<= 122: return event.key - 32 elif event.key == 50: return 64 #return @ elif event.key == 32: return 32 #return space even if shifted elif not self.shift: return event.key elif event.type == pygame....
tapple/nsize-web
nsize/body_detector/serializers.py
Python
agpl-3.0
1,173
0.00341
from rest_framework import serializers class AttachmentSerializer(serializers.Serializer): pass """ //* // As of 2017-06-13, up to 38 attachments can be worn per agent // max of 328 bytes per attach point (if name and description are maxed out). // x38 = 12464 byt
es // without descriptions: 188 * 38 = 7144 bytes top // I measured a real outfit with 38 attachments; it's json encoding was 6877 bytes string avatarAttachmentsJson(key id) { list ans = []; list attachments = llGetAttachedList(id); debug((string)llGetListLength(attachments) + " attachments"); integer i; for (i = l...
>= 0; i--) { key attachment = llList2Key(attachments, i); list details = llGetObjectDetails(attachment, [OBJECT_NAME, OBJECT_DESC, OBJECT_CREATOR, OBJECT_ATTACHED_POINT]); ans = [llList2Json(JSON_OBJECT, [ "id", attachment, // 6+2+36 = 44 bytes "name", llList2String(details, 0), // 6+4+64 = 74 bytes "desc", ll...
jupyter/dockerspawner
tests/test_deprecations.py
Python
bsd-3-clause
972
0.001029
import logging import pytest from traitlets.config import Config from dockerspawner import DockerSpawner def test_deprecated_config(caplog): cfg = Config() cfg.DockerSpawner.image_whitelist = {"1.0": "jupyterhub/singleuser:1.0"}
log = logging.getLogger("testlog") spawner = DockerSpawner(config=cfg, log=log) assert caplog.record_tuples == [ ( log.name, logging.WARNING, 'DockerSpawner.image_whitelist is deprecated in DockerSpawner 12.0, use ' 'DockerSpawner.allowed_images instead...
ed_images == {"1.0": "jupyterhub/singleuser:1.0"} async def test_deprecated_methods(): cfg = Config() cfg.DockerSpawner.image_whitelist = {"1.0": "jupyterhub/singleuser:1.0"} spawner = DockerSpawner(config=cfg) assert await spawner.check_allowed("1.0") with pytest.deprecated_call(): asser...
mancoast/CPythonPyc_test
cpython/223_test_minidom.py
Python
gpl-3.0
19,230
0.005668
# test for xml.dom.minidom from xml.dom.minidom import parse, Node, Document, parseString from xml.dom import HierarchyRequestErr import xml.parsers.expat import os import sys import traceback from test_su
pport import verbose if __name__ == "__mai
n__": base = sys.argv[0] else: base = __file__ tstfile = os.path.join(os.path.dirname(base), "test"+os.extsep+"xml") del base def confirm(test, testname = "Test"): if not test: print "Failed " + testname raise Exception Node._debug = 1 def testParseFromFile(): from StringIO import Str...
lcoandrade/DsgTools
gui/CustomWidgets/OrderedPropertyWidgets/orderedTableWidget.py
Python
gpl-2.0
24,412
0.001352
# -*- coding: utf-8 -*- """ /**********************
***************************************************** DsgTools A QGIS plugin Brazilian Army Cartographic Production Tools ------------------- begin : 2019-09-03 git sha : $Format:%H$ copyright ...
diao.joao@eb.mil.br ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or ...
joshcai/utdmathclub
math-club/settings.py
Python
mit
5,912
0.002368
# Django settings for math-club project. import dj_database_url import os from os import environ from urlparse import urlparse ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS if environ.has_key('DATABASE_URL'): DEBUG = False DATABASES = { 'default': dj_database_url.conf...
ous locations. STATICFILES
_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # Make this unique, and don't share it with anybody. SECRET_KEY = '9kc6*9+nr=8phoink1rpkn(*2d484@6k!dak&@gge#n!xp46f1'...
zsjohny/jumpserver
apps/users/signals_handler.py
Python
gpl-2.0
2,429
0.001249
# -*- coding: utf-8 -*- # from django.dispatch import receiver from django.db.models.signals import m2m_changed from django_auth_ldap.backend import populate_user from django.conf import settings from django_cas_ng.signals import cas_user_authenticated from jms_oidc_rp.signals import openid_create_or_update_user fro...
user.source = user.SOURCE_LDAP user.s
ave() @receiver(openid_create_or_update_user) def on_openid_create_or_update_user(sender, request, user, created, name, username, email, **kwargs): if created: logger.debug( "Receive OpenID user created signal: {}, " "Set user source is: {}".format(user, User.SOURCE_OPENID) ...
kevinrue/RNAfastqDeconvolute
src/__init__.py
Python
gpl-2.0
160
0
__author__ = 'David Magee
, Carolina Correia, and Kevin Rue-Albrecht' __copyright__ = "Copyright 2014, GPLv2" from . import RNAseqIO from . im
port SeqDataTypes
OCA/purchase-workflow
purchase_order_approval_block/__init__.py
Python
agpl-3.0
113
0
# License LGPL-3.0 or later (https://www.gnu.o
rg/licenses/lgpl.html). from . import model
s from . import wizard
plotly/python-api
packages/python/plotly/plotly/validators/bar/insidetextfont/_sizesrc.py
Python
mit
463
0
import _plotly_utils.basevalidators class Siz
esrcValidator(_plotly_utils.basevalidators.SrcValidator): def __init__( self, plotly_name="sizesrc", parent_name="bar.insidetextfont", **kwargs ): super(SizesrcValidator, self).__init__( plotly_n
ame=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "none"), role=kwargs.pop("role", "info"), **kwargs )
FederatedAI/FATE
python/fate_test/fate_test/_client.py
Python
apache-2.0
3,346
0.002989
# # Copyright 2019 The FATE 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 appli...
for tunnel_id, tunnel_conf in self._tunnel_id_to_tunnel.items(): tunnel = sshtunnel.SSHTunnelForwarder(ssh_address_or_host=tunnel_conf.ssh_address, ssh_username=tunnel_conf.ssh_username,
ssh_password=tunnel_conf.ssh_password, ssh_pkey=tunnel_conf.ssh_priv_key, remote_bind_addresses=tunnel_conf.services_address) tunnel.start() self._tunnels.append(tu...
materialsproject/MPContribs
mpcontribs-api/mpcontribs/api/contributions/generate_formulae.py
Python
mit
431
0
# -*- coding: utf-8 -*- import os impor
t json from pymatgen.ext.matproj import MPRester data = {} with MPRester() as mpr: for i, d in enumerate( mpr.query(criteria={}, properties=["task_ids", "pretty_formula"]) ): for task_id in d["task_ids"]: data[task_id] = d["pretty_formula"] out = os.path.join(os.pa
th.dirname(__file__), "formulae.json") with open(out, "w") as f: json.dump(data, f)
mujin/jhbuild
jhbuild/commands/autobuild.py
Python
gpl-2.0
3,732
0.001876
# jhbuild - a tool to ease building collections of source packages # Copyright (C) 2001-2004 James Henstridge # # autobuild.py: non-interactive build that generates a report # # 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...
report URL')), make_option('-v', '--verbose', action='store_true', dest='verbose', default=False, help=_('verbose mode'))
, ]) def run(self, config, options, args, help=None): config.set_from_cmdline_options(options) config.buildscript = 'autobuild' config.autobuild_report_url = None config.verbose = False config.interact = False if options.reporturl is not None: ...
TRox1972/youtube-dl
youtube_dl/extractor/orf.py
Python
unlicense
11,297
0.001151
# coding: utf-8 from __future__ import unicode_literals import re import calendar import datetime from .common import InfoExtractor from ..compat import compat_str from ..utils import ( HEADRequest, unified_strdate, strip_jsonp, int_or_none, float_or_none, determine_ext, remove_end, un...
True, }, { 'url': 'http://oe1.orf.at/konsole?show=ondemand&track_id=443608&load_day=/programm/konsole/tag/20160726', 'only_matching': True, }] def _real_extract(self, url): show_id = self._match_id(url) data = self._
download_json( 'http://oe1.orf.at/programm/%s/konsole' % show_id, show_id ) timestamp = datetime.datetime.strptime('%s %s' % ( data['item']['day_label'], data['item']['time'] ), '%d.%m.%Y %H:%M') unix_timestamp = calendar.timegm(timestamp....