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 |
|---|---|---|---|---|---|---|---|---|
neharejanjeva/techstitution | venv/lib/python2.7/site-packages/pymongo/cursor.py | Python | cc0-1.0 | 46,027 | 0.000217 | # Copyright 2009-2015 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 applicable law or agreed to in writin... | .pool = pool
self.__closed = False
def __del__(self):
self.close()
def close(self):
"""Return this instance's socket to the connection pool.
"""
if not self.__closed:
self.__closed = True
self.pool.maybe_return_socket(self.s | ock)
self.sock, self.pool = None, None
def error(self):
"""Clean up after an error on the managed socket.
"""
if self.sock:
self.sock.close()
# Return the closed socket to avoid a semaphore leak in the pool.
self.close()
# TODO might be cool to be ... |
captiosus/treadmill | tests/services/cgroup_service_test.py | Python | apache-2.0 | 6,163 | 0 | """Unit test for cgroup_service - Treadmill cgroup service.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import tempfile
import unittest
import select
import shutil
import mock
import treadmill
from... | ber _unregister_oom_handler of a client
# class
# pylint: disable=W0212
svc = cgroup_service.CgroupResourceService(self.running)
request_id = 'myproid.test-0-ID1234'
svc.on_delete_request(request_id)
cgrp = os.path.join('treadmill/apps', request_id)
treadmill.c... | mock.call(ss, cgrp)
for ss in ['cpu', 'cpuacct', 'memory', 'blkio']
]
)
svc._unregister_oom_handler.assert_called_with(cgrp)
@mock.patch('treadmill.cgutils.get_memory_oom_eventfd',
mock.Mock(return_value='fake_efd'))
def test__register_... |
alex/txsni | twisted/plugins/txsni_endpoint.py | Python | mit | 79 | 0 |
from tx | sni.parser import SNIDirectoryParser
dirParser = SNIDi | rectoryParser()
|
vortex610/mos | run_tests/shaker_run/plugin/FuelTestrailAPI.py | Python | apache-2.0 | 5,980 | 0.003512 | import ConfigParser
import base64
import json
import urllib2
interface = "bond0"
parser = ConfigParser.SafeConfigParser()
parser.read('/root/env.conf')
fuel_ip = dict(parser.items('fuel'))['fuel_ip']
create_new_run = dict(parser.items('testrail'))['create_new_run']
suite_id = dict(parser.items('testrail'))['suite_id']... | = {'X-Auth-Token': token_id}
url = 'http://{0}:8000/api/clusters/{1}/network_configuration/neutron'.format(fuel_ip,cluster_id)
req = urllib2.Request(u | rl, headers=headers)
content = urllib2.urlopen(req)
json_data = json.load(content)
return json_data
def get_nodes(fuel_ip, token_id):
headers = {'X-Auth-Token': token_id}
url = 'http://{0}:8000/api/nodes/?cluster_id={1}'.format(fuel_ip, cluster_id)
req = urllib2.Request(url, headers=headers)
... |
kitsunde/django-pypi | pypi/migrations/0004_auto__chg_field_version_version.py | Python | mit | 2,623 | 0.008006 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'Version.version'
db.alter_column(u'pypi_version', 'version', self.gf('django.db.models.fi... | max_length': '200'}),
'version': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'releases'", 'to': u"orm['pypi.Version']"})
},
u'pypi.version': {
'Meta': {'unique_together': "(('package', 'version'),)", 'object_name': 'Version'},
u'id': ('django.... | ackage': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'versions'", 'to': u"orm['pypi.Package']"}),
'version': ('django.db.models.fields.CharField', [], {'max_length': '100'})
}
}
complete_apps = ['pypi'] |
lukas-linhart/pageobject | tests/unit/test_pageobjectbase.py | Python | mit | 6,421 | 0.005918 | import pytest
import logging
from pageobject import PageObject
from pageobject.pageobjectbase import PageObjectBase
from pageobject.locator import Locator
from .fixtures import mock_po_base
from selenium.webdriver import Remote as RemoteWebDriver
def test_dunder_repr_returns_correct_string(monkeypatch, mock_po_base):... | , '//body')
assert mock_po_base.locator == mock_po_base._locator_value
def test_webdriver_returns_parent_if_it_is_a_webdriver_instance(monkeypatch, mock_po_base):
class MockWebDriver(RemoteWebDriver) | :
def __init__(self): pass
parent = MockWebDriver()
monkeypatch.setattr(mock_po_base.__class__, 'parent', parent)
assert mock_po_base.webdriver == parent
def test_webdriver_returns_webdriver_of_parent_po_if_available(monkeypatch, mock_po_base):
parent_webdriver = 'parent_webdriver'
class Pa... |
kohnle-lernmodule/palama | exe/export/websitepage.py | Python | gpl-2.0 | 10,861 | 0.007734 | # ===========================================================================
# eXe
# Copyright 2004-2005, University of Auckland
# Copyright 2004-2007 eXe Project, New Zealand Tertiary Education Commission
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General... | html.replace("&concept", "&concept")
# R | emove "resources/" from data="resources/ and the url param
html = html.replace("video/quicktime\" data=\"resources/", "video/quicktime\" data=\"")
html = html.replace("application/x-mplayer2\" data=\"resources/", "application/x-mplayer2\" data=\"")
html = html.replace("audio/x-pn-realaudio-plugin\" data=\"resources/... |
CoinProjects/MineCoin | share/qt/clean_mac_info_plist.py | Python | mit | 897 | 0.016722 | #!/usr/bin/env python
# Jonas Schnelli, 2013
# make sure the MineCoin-Qt.app contains the right plist (including the rig | ht version)
# fix made because of serval bugs in Qt mac deployment (https://bugreports.qt-project.org/browse/QTBUG-21267)
from string import Template
from datetime import date
bitcoinDir = "./";
inFile = bitcoinDir+"/share/qt/Info.plist"
outFile = "MineCoin-Qt.app/Contents/Info.plist"
version = "unknown";
... | Dir+"bitcoin-qt.pro"
for line in open(fileForGrabbingVersion):
lineArr = line.replace(" ", "").split("=");
if lineArr[0].startswith("VERSION"):
version = lineArr[1].replace("\n", "");
fIn = open(inFile, "r")
fileContent = fIn.read()
s = Template(fileContent)
newFileContent = s.substitute(VERSION=version,YEAR=date.... |
Willyham/tchannel-python | tchannel/messages/cancel.py | Python | mit | 1,854 | 0 | # Copyright (c) 2015 Uber Technologies, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publ... | /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 SOFTWARE IS PROVI | DED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CON... |
tailhook/coyaml | coyaml/cgen.py | Python | mit | 36,976 | 0.005274 | import textwrap
from collections import defaultdict
from . import load, core
from .util import builtin_conversions, parse_int, parse_float, nested
from .cutil import varname, string, typename, cbool
from .cast import *
cmdli | ne_template = """\
Usage:
{m.program_name} [options]
Description:
{description}
Options:
-h, --help Print this help
-c, --config FILE Name of configuration file
--debug-config Print debugging information while parsing configuration file
--config-vars Enable variables in configuration file (b... | configuration file
--config-show-vars
Prints variables used in configuration file
-D,--config-var NAME=VALUE
Set value of configuration variable NAME to value VALUE
-P,--print-config Print read configuration. Including command-line overrides
Double this ... |
davegri/Sikumia | sikumim/settings/development.py | Python | gpl-2.0 | 162 | 0.012346 | # -*- coding: utf-8 -*-
from .base import *
|
# memcache
CACHES = {
| 'default' : {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'
}
}
|
rssalessio/MMSE15Project-RussoJohansson | mmse15project/ctrls/MainController.py | Python | gpl-2.0 | 11,737 | 0.001278 | import sys
from mmse15project.views.Administration import Administration
from mmse15project.views.CustomerService import CustomerService
from mmse15project.views.Financial import Financial
from mmse15project.views.HR import HR
from mmse15project.views.Marketing import Marketing
from mmse15project.views.Production impor... | nt_create(self, subview):
subview.form.create_widgets()
def new_discount_submit(self,subview):
data = subview.get_all()
new = Discount()
new.requestID = int(data[0])
new.amount = int(data[1])
new.comment = data[2]
new.date = data[3] |
self.model.discount_db.add(new)
self.clear_frame(subview)
###########################################################################
# Search
###########################################################################
def search_client_get(self,subview):
subview.result.create... |
leppa/home-assistant | homeassistant/components/config/entity_registry.py | Python | apache-2.0 | 4,820 | 0.001867 | """HTTP views to interact with the entity registry."""
import voluptuous as vol
from homeassistant.components import websocket_api
from homeassistant.components.websocket_api.const import ERR_NOT_FOUND
from homeassistant.components.websocket_api.decorators import (
async_response,
require_admin,
)
from homeass... | is None:
connection.send_message(
websocket_api.error_message(msg["id"], ERR_NOT_FOUND, "Entity not found")
)
return
connection.send_ | message(websocket_api.result_message(msg["id"], _entry_dict(entry)))
@require_admin
@async_response
@websocket_api.websocket_command(
{
vol.Required("type"): "config/entity_registry/update",
vol.Required("entity_id"): cv.entity_id,
# If passed in, we update value. Passing None will remove ... |
kkreis/espressopp | src/interaction/ReactionFieldGeneralizedTI.py | Python | gpl-3.0 | 11,247 | 0.01067 | # Copyright (C) 2012,2013,2016
# Max Planck Institute for Polymer Research
# Copyright (C) 2008,2009,2010,2011
# Max-Planck-Institute for Polymer Research & Fraunhofer SCAI
#
# This file is part of ESPResSo++.
#
# ESPResSo++ is free software: you can redistribute it and/or modify
# it under the terms... | m. If not, see <http://www.gnu.org/licenses/>.
r"""
*************************************************
espressopp.interaction.ReactionFieldGeneralizedTI
*************************************************
This module is for performing simulations (e.g. as part of Thermodynamic Integration) where some interactions are... | e :math:`U_C^A` is the standard Reaction Field interaction. This allows one to perform TI where the charges in TI state A (:math:`\lambda=0`) are the particle charges contained in the particle property ``charge`` and the charges in TI state B (:math:`\lambda=1`) are zero.
The user specifies a list of particles, pidli... |
googleapis/python-gke-hub | samples/generated_samples/gkehub_v1_generated_gke_hub_create_membership_sync.py | Python | apache-2.0 | 1,568 | 0.000638 | # -*- 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... | .
# It may require modifications to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-cloud-gke-hub
# [START gkehub_v1_generated_GkeHub_CreateMembership | _sync]
from google.cloud import gkehub_v1
def sample_create_membership():
# Create a client
client = gkehub_v1.GkeHubClient()
# Initialize request argument(s)
request = gkehub_v1.CreateMembershipRequest(
parent="parent_value",
membership_id="membership_id_value",
)
# Make the... |
bblacey/FreeCAD-MacOS-CI | src/Tools/SubWCRev.py | Python | lgpl-2.1 | 14,815 | 0.014175 | #! python
# -*- coding: utf-8 -*-
# (c) 2006 Werner Mayer LGPL
#
# FreeCAD RevInfo script to get the revision information from Subversion.
#
# Under Linux the Subversion tool SubWCRev shipped with TortoiseSVN isn't
# available which is provided by this script.
# 2011/02/05: The script was extended to support ... | ter repository"""
#referencecommit="f119e740c87918b103140b66b2316ae96f136b0e"
#referencerevision=4138
referencecommit="6b3d7b17a749e03bcbf2cf79bbbb903137298c44"
referencerevision=5235
result = None
countallfh=os.popen("git rev-list --count %s..HEAD" % \
... | referencecommit)
countallstr=countallfh.read().strip()
if countallfh.close() is not None: #reference commit not present
self.rev = '%04d (Git shallow)' % referencerevision
return
else:
countall = int(countallstr)
if origin is not None an... |
SurAnand/pyuthon | while2.py | Python | gpl-2.0 | 212 | 0.042453 | i=0
numbers = []
while i < 6:
print "A | t the top i is %d" %i
numbers.append(i)
i = i+1
print "Numbers now: ", numbers
print "At the bottom i is %d" %i
print "The numbers: | "
for num in numbers:
print num
|
fedoraredteam/elem | elem/host/assessor.py | Python | gpl-3.0 | 6,452 | 0.00341 | import subprocess
import re
from cpe import CPE
import platform
class Assessor(object):
def __init__(self):
self.cves = []
def assess(self):
pass
class YumAssessor(Assessor):
def __init__(self):
super(YumAssessor, self).__init__()
def assess(self):
lines = []
e... | if match:
return match.group(0)
return ""
def cpe(self):
cpe_string = ['cpe']
cpe_string.append('2.3')
cpe_string.append | ('a')
cpe_string.append('*')
cpe_string.append(self.name())
cpe_string.append(self.version())
cpe_fs = ":".join(cpe_string) + ":*:*:*:*:*:*:*"
return CPE(cpe_fs, CPE.VERSION_2_3)
def version_less_than(self, other_rpm):
if not isinstance(other_rpm, Rpm):
r... |
joelsmith/openshift-tools | scripts/monitoring/cron-haproxy-close-wait.py | Python | apache-2.0 | 3,742 | 0.001871 | #!/usr/bin/python
# vim: expandtab:tabstop=4:shiftwidth=4
# Disabling invalid-name because pylint doesn't like the naming convention we have.
# pylint: disable=invalid-name
''' Tool to detect haproxy processes that have been running longer than
the most recent haproxy process and have connection in CLOSE_WAIT stat... | us: temporary until we start testing in a container where our stuff is installed.
# pylint: disable=import-error
from openshift_tools.monitoring.metric_sender import MetricSender
ZABBIX_KEY = "openshift.haproxy.close-wait"
class HAProxy(object):
''' wrapper for finding and stopping stuck haproxy processes '''
... | msg):
''' wrap printing debug messages '''
if self.args.debug:
print msg
def parse_args(self):
''' get user args '''
parser = argparse.ArgumentParser(description='haproxy killer')
parser.add_argument('--debug', default=False, action='store_true')
self.arg... |
mozilla/make.mozilla.org | make_mozilla/events/migrations/0003_auto__add_field_event_source_id__add_field_event_organiser_email.py | Python | bsd-3-clause | 2,336 | 0.006421 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Event.source_id'
db.add_column('events_event', 'source_id',
self.gf('d... | 'source_id': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'start': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'venue': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['events.Ve | nue']"})
},
'events.venue': {
'Meta': {'object_name': 'Venue'},
'country': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'location': ('django.contrib.gis.db.model... |
Makeystreet/makeystreet | woot/apps/catalog/migrations/0112_auto__add_field_likevideo_fb_like_id__add_field_likeshop_fb_like_id__a.py | Python | apache-2.0 | 61,347 | 0.007286 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'LikeVideo.fb_like_id'
db.add_column(u'catalog_likevideo',... | } | ,
u'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('djang... |
EdisonAlgorithms/HackerRank | practice/ai/machine-learning/predicting-office-space-price/predicting-office-space-price.py | Python | mit | 596 | 0.010067 | import numpy as np
from sklearn.preprocessing import PolynomialFeatures
from sklearn import linear_mo | del
if __name__ == "__main__":
(f, n) = map(int, raw_input().split())
x = []
y = []
| poly = PolynomialFeatures(degree = 4)
for i in range(n):
v = map(float, raw_input().split())
x.append(poly.fit_transform(v[:-1])[0])
y.append(v[-1])
clf = linear_model.BayesianRidge()
clf.fit(x, y)
tc = int(raw_input())
for i in range(tc):
v = map(fl... |
yotchang4s/cafebabepy | src/main/python/test/test_defaultdict.py | Python | bsd-3-clause | 6,033 | 0.000995 | """Unit tests for collections.defaultdict."""
import os
import copy
import pickle
import tempfile
import unittest
from collections import defaultdict
def foobar():
return list
class TestDefaultDict(unittest.TestCase):
def test_basic(self):
d1 = defaultdict()
self.assertEqual(d1.default_fact... | efaultdict(None, {})")
self.assertEqual(eval(repr(d1)), d1)
d1[11] = 41
self.assertEqual(repr(d1), "defaultdict(None, {11: 41})")
d2 = defaultdict(int)
self.assertEqual(d2.default_factory, int)
d2[12] = 42
self.assertEqual(repr(d2), "defaultdict(<class 'int'>, {12... | )")
def foo(): return 43
d3 = defaultdict(foo)
self.assertTrue(d3.default_factory is foo)
d3[13]
self.assertEqual(repr(d3), "defaultdict(%s, {13: 43})" % repr(foo))
def test_print(self):
d1 = defaultdict()
def foo(): return 42
d2 = defaultdict(foo, {1... |
fatiherikli/kankim | urls.py | Python | gpl-3.0 | 1,217 | 0.019721 | from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
from kankim.utils import here
admin.autodiscover()
urlpatterns = patterns('',
# genel sayfalar
(r'^$', 'kankim.main.views.index') ,
(r'^register', 'kankim.main.views.r... | in') ,
(r'^logout', 'kankim.main.views.logout') ,
(r'^profile-edit', 'kankim.main.views.pro | file_edit') ,
(r'^change-profile-picture', 'kankim.main.views.change_profile_picture') ,
#friendship
(r'^friends/$', 'kankim.accounts.views.my_friends') ,
(r'^friends/add/(?P<username>.*)', 'kankim.accounts.views.add') ,
(r'^friends/accept/(?P<username>.*)', 'kankim.accounts.views.accept') ,
... |
obr/python-fedex | examples/freight_rate_request.py | Python | bsd-3-clause | 5,734 | 0.003837 | #!/usr/bin/env python
"""
This example shows how to use the FedEx RateRequest service.
The variables populated below represents the minimum required values.
You will need to fill all of these, or risk seeing a SchemaValidationError
exception thrown by suds.
TIP: Near the bottom of the module, see how to check the if t... | _config.py | in this dir.
rate_request = FedexRateServiceRequest(CONFIG_OBJ)
rate_request.RequestedShipment.ServiceType = 'FEDEX_FREIGHT_ECONOMY'
rate_request.RequestedShipment.DropoffType = 'REGULAR_PICKUP'
rate_request.RequestedShipment.PackagingType = 'YOUR_PACKAGING'
rate_request.RequestedShipment.FreightShipmentDetail.Tota... |
frewsxcv/lop.farm | app/run/views.py | Python | mpl-2.0 | 592 | 0 | import shutil
from django.http import HttpResponseServerError
from django.shortcuts import render
from run.models import Run
from run.tasks import run_afl, PY_AFL_FUZZ_CMD
def trigger_run(request):
if not shutil.which(PY_AFL_FUZZ_CMD):
return HttpResponseServerError()
run = Run.objects.create()
| run_afl.delay(run.id, 10)
return render(request, 'trigger_run.html')
def run(request, run_id):
try:
run = Run.objects.get | (id=run_id)
except Run.DoesNotExist:
pass
return render(request, 'run.html', {'run': run, 'afl_run': run.aflrun})
|
arista-eosplus/ansible | lib/ansible/playbook/included_file.py | Python | gpl-3.0 | 6,133 | 0.002935 | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) an... | s__ = type
import os
from ansible.playbook.task_include import TaskInclude
from ansible.template import Templar
try:
from __main__ import display
except ImportError:
from ansible.utils.display import Display
display = Display()
class IncludedFile:
def __init__(self, filename, args, task):
... | me = filename
self._args = args
self._task = task
self._hosts = []
def add_host(self, host):
if host not in self._hosts:
self._hosts.append(host)
def __eq__(self, other):
return other._filename == self._filename and other._args == self._args
def __repr_... |
RasaHQ/rasa_nlu | tests/nlu/featurizers/test_lexical_syntactic_featurizer.py | Python | apache-2.0 | 11,174 | 0.001521 | import numpy as np
import pytest
import re
from typing import Text, Dict, Any, Callable, List, Optional, Union
from rasa.engine.graph import ExecutionContext
from rasa.engine.storage.storage import ModelStorage
from rasa.engine.storage.resource import Resource
from rasa.nlu.constants import (
DENSE_FEATURIZABLE_AT... | "low"], ["digit"]],
[0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0],
# Note:
# 1. we just describe the features for | first token here
# 2. "123".islower() == "123".isupper() == False, which is why we end
# up with 7 features
),
# with part of speech
(
"The sun is shining",
["DET", "NOUN", "AUX", "VERB"],
[["pos", "pos2"]],
[
... |
matslindh/codingchallenges | adventofcode2017/21.py | Python | mit | 2,640 | 0.004545 | def expand(rules, iterations):
drawing = ['.#.', '..#', '###']
for i in range(0, iterations):
new_map = []
step = 2 if len(drawing) % 2 == 0 else 3
for offset_y in range(0, len(drawing), step):
line = []
for offset_x in range(0, len(drawing... | not line:
line += n
else:
for idx, row in enumerate(n):
line[idx] += row
new_map += line
drawing = new_map
return drawing
def ser(p):
return '/'.join(p)
def parse_rules(lines):
expanders = {}
for ... | t(' => ')
pattern = pattern.split('/')
replacement = replacement.split('/')
expanders[ser(pattern)] = replacement
expanders[ser(flip(pattern))] = replacement
for _ in range(0, 3):
pattern = rotate(pattern)
expanders[ser(pattern)] = replacement
... |
ramesharpu/python | basic-coding/built-in-functions/callable.py | Python | gpl-2.0 | 641 | 0.01092 | """
with attribute __call__, the object becomes callable
which means we can call the class __init__ method using class(). when class() | is used, def __call__() is called.
"""
class Add():
def __init__(self, num1, num2):
self.num1 = num1
self.num2 = num2
print "Sum of {} and {} is {}".format(self.num1, self.num2, self.num1+self.num2)
def __call__(self):
return (self.num1+self.num2)
# This calls the class __init... | et error stating "AttributeError: Add instance has no __call__ method"
print add() |
bharcode/MachineLearning | FacebookMissingLinks/candidate.py | Python | gpl-2.0 | 1,009 | 0.004955 | """
Responsible for selecting candidates.
"""
#!/usr/bin/env python
def get_surroundings(follow, followed, nodes):
""" Gets all followers and followees of a given sets of nodes. """
followers_and_followees = set()
for node in nodes:
followers_and_followees.update(follow[node])
fol | lowers_and_followees.update(followed[node])
return followers_and_followees
def get_candidates(follow, followed, node):
""" Gets candidates for node to suggest follow. """
nodes_exclude = follow[node].copy()
nodes_exclude.add(node)
l1_candidates = get_surroundings(follow, followed, [node])
l2_... | es)
candidates = set()
candidates.update(l1_candidates)
candidates.update(l2_candidates)
candidates.update(l3_candidates)
candidates.difference_update(nodes_exclude)
return candidates
if __name__ == '__main__':
pass
|
detiber/lib_openshift | test/test_v1beta1_deployment_rollback.py | Python | apache-2.0 | 1,366 | 0.004392 | # coding: utf-8
"""
OpenAPI spec version:
Generated by: https://github.com/swagger-api/swagger-codegen.git
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
... | ent_rollback import V1beta1DeploymentRollback
class TestV1beta1DeploymentRollback(unittest.TestCase):
""" V1beta1DeploymentRollbac | k unit test stubs """
def setUp(self):
pass
def tearDown(self):
pass
def testV1beta1DeploymentRollback(self):
"""
Test V1beta1DeploymentRollback
"""
model = lib_openshift.models.v1beta1_deployment_rollback.V1beta1DeploymentRollback()
if __name__ == '__mai... |
macrat/PyGenSound | tests/pep8_test.py | Python | mit | 625 | 0 | import typing
import unittest
import pep8
class PEP8Test(unittest.T | estCase):
def run_pep8_test(self, modules: typing.Iterable[str]):
pep8.DEFAULT_IGNORE = 'W503'
checker = pep8.StyleGuide()
result = checker.check_files(modules)
message = 'pep8: {} errors / {} warnings'.format(result.get_count('E'),
| result.get_count('W'))
self.assertEqual(result.total_errors, 0, message)
def test_pep8_gensound(self):
self.run_pep8_test(['gensound'])
def test_pep8_tests(self):
self.run_pep8_test(['tests'])
|
zappyk-github/zappyk-python | lib/lib_external/postgresql/sys.py | Python | gpl-2.0 | 2,125 | 0.031059 | ##
# .sys
##
"""
py-postgresql system functions and data.
Data
----
``libpath``
The local file system paths that contain query libraries.
Overridable Functions
---------------------
excformat
Information that makes up an exception's displayed "body".
Effectively, the implementation of `postgresql.exception.... | esep
)
after += indent(traceback.format_exc())
after = os.linesep + indent(after).rstrip()
else:
after = ''
return next(it)[1] \
+ os.linesep + ' ' \
+ (os.linesep + ' ').join(
k + ': ' + v for k, v in it
) + after
def default_msghook(msg, format_message = format_ | element):
"""
Built-in message hook. DON'T TOUCH!
"""
if sys.stderr and not sys.stderr.closed:
try:
sys.stderr.write(format_message(msg) + os.linesep)
except Exception:
try:
sys.excepthook(*sys.exc_info())
except Exception:
# gasp.
pass
def errformat(*args, **kw):
"""
Raised Database Err... |
sangoma/pytestlab | lab/utils.py | Python | mpl-2.0 | 1,650 | 0 | #
# Copyright 2017 Sangoma Technologies Inc.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
Handy utilities
"""
from builtins import map
import os
import string
... | :
"""Encode paths for use as file names the same way systemd does:
"Some unit names reflect paths existi | ng in the file system namespace.
Example: a device unit dev-sda.device refers to a device with the
device node /dev/sda in the file system namespace. If this applies, a
special way to escape the path name is used, so that the result is
usable as part of a filename. Basically, given a path, "/" i... |
mandiant/ioc_writer | examples/simple_ioc_writer/simple_ioc_writer.py | Python | apache-2.0 | 4,289 | 0.003031 | # simple_ioc_writer.py
#
# Copyright 2013 Mandiant Corporation.
# Licensed under the Apache 2.0 license. Developed for Mandiant by William
# Gibb.
#
# Mandiant licenses this file to you under the Apache License, Version
# 2.0 (the "License"); you may not use this file except in compliance with the
# License. You m... | etLogger(__name__)
def create_ioc_object(ioc_n | ame, items, and_or=True):
ioc = ioc_api.IOC(name=ioc_name)
top_level_or_node = ioc.top_level_indicator
# build the definition
if and_or:
second_level_and_node = ioc_api.make_indicator_node('AND')
top_level_or_node.append(second_level_and_node)
for item in items:
condition, do... |
pydanny/django-la-facebook | test_project/connect/urls.py | Python | mit | 187 | 0.010695 | from django. | conf.ur | ls.defaults import *
urlpatterns = patterns('test_project.connect.views',
url(r'^/?$', "test_index", name="index"),
url(r'^after/?$', "after", name="after"),
) |
stack-of-tasks/rbdlpy | tutorial/lib/python2.7/site-packages/OpenGL/raw/GLX/NV/video_capture.py | Python | lgpl-3.0 | 1,452 | 0.03168 | '''Autogener | ated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.GLX import _types as _cs
# End users want this...
from OpenGL.raw.GLX._types import *
from OpenGL.raw.GLX import _errors
from OpenGL.constant import Constant as _C
import ctypes
_EXTENSION... | return _p.createFunction( function,_p.PLATFORM.GLX,'GLX_NV_video_capture',error_checker=_errors._error_checker)
GLX_DEVICE_ID_NV=_C('GLX_DEVICE_ID_NV',0x20CD)
GLX_NUM_VIDEO_CAPTURE_SLOTS_NV=_C('GLX_NUM_VIDEO_CAPTURE_SLOTS_NV',0x20CF)
GLX_UNIQUE_ID_NV=_C('GLX_UNIQUE_ID_NV',0x20CE)
@_f
@_p.types(_cs.c_int,ctypes.POINTE... |
mjhennig/dyn-python | dyn/tm/services/dsf.py | Python | bsd-3-clause | 103,943 | 0.001193 | # -*- coding: utf-8 -*-
"""This module contains wrappers for interfacing with every element of a Traffic
Director (DSF) service.
"""
import dyn.tm.zones
from ..utils import APIList, Active
from ..errors import DynectInvalidArgumentError
from ..records import *
from ..session import DynectSession
from ...compat import f... | ._weight
@weight.setter
def weight(self, value):
self._weight = value
api_args = {'weight': self._weight}
response = DynectSession.get_session().execute(self.uri, 'PUT',
api_args)
self._build(response['data'])
@property
... | can be changed in response to monitoring. Must
be one of 'auto', 'auto_down', or 'manual'
"""
return self._automation
@automation.setter
def automation(self, value):
self._automation = value
api_args = {'automation': self._automation}
response = DynectSession.get_... |
tensorflow/datasets | tensorflow_datasets/text/wordnet_test.py | Python | apache-2.0 | 1,851 | 0.004322 | # coding=utf-8
# Copyright 2022 The TensorFlow Datasets Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | datasets.text import wordnet
class WordnetTest(tfds.testing.DatasetBuilderTestCase):
"""Tests for Wordnet dataset."""
DATASET_CLASS = wordnet.Wordnet
SPLITS = {
'train': 3,
| 'validation': 2,
'test': 1,
}
DL_EXTRACT_RESULT = {
'WN18': '',
'WN18RR': '',
}
def test_info(self):
"""Before download, there is no metadata."""
super(WordnetTest, self).test_info()
self.assertEmpty(self.builder.info.metadata)
def test_info_after_download_and_prepare(se... |
lielongxingkong/ics_demo | ics_demo/dao/db.py | Python | mit | 3,574 | 0.008114 | from sqlobject import *
from ics_demo.dao.orm.demo import Carrot, Rabbit, Corps
from ics_demo.dao.orm.host import Host
from ics_demo.dao.orm.block_device import BlockDevice
from ics_demo.dao.orm.vsan import Mon, Osd, VsanStore
f | rom ics_demo.helpers import uuidgen
def createTables(tables):
for table in tables:
table.createTable(ifNotExists=True)
def cleanTables(tables):
for table in tables[::-1]:
table.dropTable(ifExists=True)
demo_tables = [Rabbit, Carr | ot, Corps] # order by dependency
vsan_tables = [Mon, Osd, VsanStore] # order by dependency
base_tables = [Host, BlockDevice] # order by dependency
def init_demo():
cleanTables(demo_tables)
createTables(demo_tables)
# init test data
bunny_kun1 = Rabbit(uuid="11111111-1111... |
nicoddemus/pytest | testing/logging/test_reporting.py | Python | mit | 34,780 | 0.001323 | import io
import os
import re
from typing import cast
import pytest
from _pytest.capture import CaptureManager
from _pytest.config import ExitCode
from _pytest.fixtures import FixtureRequest
from _pytest.pytester import Pytester
from _pytest.terminal import TerminalReporter
def test_nothing_logged(pytester: Pytester... | logger = logging.getLogger(__name__)
def test_foo():
logger.info('text going to logger from call')
def teardown_function(function):
logger.info('text going to logger from teardown')
assert False
"""
)
result = pytester.runpytest("--log-level=INFO... | t == 1
result.stdout.fnmatch_lines(
[
"*- Captured *log call -*",
"*text going to logger from call*",
"*- Captured *log teardown -*",
"*text going to logger from teardown*",
]
)
@pytest.mark.parametrize("enabled", [True, False])
def test_log_cli_... |
Juniper/nova | nova/tests/functional/api_sample_tests/test_server_migrations.py | Python | apache-2.0 | 8,557 | 0 | # Copyright 2016 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | ute': 'compute1',
'dest_compute': 'compute2',
'dest_host': '1.2.3.4',
'status': 'running',
'instance_u | uid': UUID_1,
'migration_type': 'live-migration',
'hidden': False,
'memory_total': 123456,
'memory_processed': 12345,
'memory_remaining': 111111,
'disk_total': 234567,
'disk_processed': 23456,
'disk_remaining': 211111,
... |
cltl/lexical_pattern_extractor | lib/config_manager_indexer.py | Python | gpl-3.0 | 2,820 | 0.012411 | import ConfigParser
import os
class Config_manager:
def __init__(self):
self.config = ConfigParser.ConfigParser()
self.out_folder = None
def set_current_folder(self,t):
self.cwd = t
def set_config(self,file_cfg):
self.config.read(file_cfg)
output_folder_cfg = self.... | _len(self):
if self.config.has_option('general','min_ngram_len'):
return int(self.config.get('general','min_ngram_len'))
else:
return 1
def get_punctuation(self):
my_list = []
if self.config.has_option('general', 'punctuation'):
p = self.config.ge... | my_list = p.strip().split(' ')
print my_list
return my_list
def get_convert_to_lowercase(self):
c = False #Default
if self.config.has_option('general','convert_to_lowercase'):
c = self.config.getboolean('general','convert_to_lowercase')
return c
... |
punchagan/zulip | zerver/webhooks/slack/view.py | Python | apache-2.0 | 1,503 | 0.001331 | from django.http import HttpRequest
from django.utils.translation import gettext as _
from zerver.decorator import webhook_view
from zerver.lib.actions import check_send_stream | _message
from zerver.lib.exceptions import JsonableError
from zerver.lib.request import REQ, get_request_notes, has_request_variables
from zerver.lib.response import json_success
from zerver.models import UserProfile
ZULIP_MESSAGE_TEMPLATE = "**{message_sender}**: `{text}`"
VALID_OPTIONS = {"SHOULD_NOT_BE_MAPPED": "0"... | est: HttpRequest,
user_profile: UserProfile,
user_name: str = REQ(),
text: str = REQ(),
channel_name: str = REQ(),
stream: str = REQ(default="slack"),
channels_map_to_topics: str = REQ(default="1"),
) -> HttpRequest:
if channels_map_to_topics not in list(VALID_OPTIONS.values()):
rai... |
mozilla/firefox-flicks | vendor-local/lib/python/djcelery/snapshot.py | Python | bsd-3-clause | 5,591 | 0.002683 | from __future__ import absolute_import
from collections import defaultdict
from datetime import datetime, timedelta
from time import time
from django.db import transaction
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from celery import states
from celery.events.state import ... | ,
"state": task.state,
"tstamp": aware_tstamp(task.timestamp),
"result": task.result or task.exception,
"traceback": task.traceback,
"runtime": task.runtime,
| "worker": worker}
# If RECEIVED event is lost, some data is lost as it is stored
# only in RECEIVED event for efficiency. In this case we just
# do not overwrite this fields in TaskState instance row
[defaults.pop(attr, None) for attr in NOT_SAVED_ATTRIBUTES
... |
bretlowery/snakr | snakr/trafficfilters.py | Python | bsd-3-clause | 12,013 | 0.006493 | from patterns.singleton import Singleton
from secure | .gae import gaeinit
gaeinit()
import loggr
from utilities import Utils
import secure.s | ettings as settings
import urllib2
from django.utils import timezone
from snakr.models import CityLog, CountryLog, IPLog, HostLog, UserAgentLog, TPIpBls#
import ipaddr
import netaddr
class TrafficFilters():
def __init__(self, *args, **kwargs):
#
# there can be only one
# see Method 3 on ht... |
Muges/audiotsm | tests/unit/utils/test_normalizebuffer.py | Python | mit | 2,381 | 0 | # -*- coding: utf-8 -*-
"""
Tests for the audiotsm.utils.normalizebuffer package.
"""
import pytest
from numpy.testing import assert_almost_equal
from audiotsm.utils import N | ormalizeBuffer
def generate_normalize_buffers(array):
"""Generate different NormalizeBuffers containing the same data as
``array``."""
for i in range(0, len(arra | y)):
buffer = NormalizeBuffer(len(array))
buffer.remove(i)
buffer.add(array)
yield buffer
def generate_test_cases(cases):
"""For each tuple (data, *params) of an array, generate multiple test cases
(buffer, *params), where buffer is a NormalizeBuffer containing
``data``."""... |
wasit7/book_pae | pae/book_edit_bootstrap/django/webapp/webapp/settings.py | Python | mit | 2,978 | 0.001007 | """
Django settings for webapp project.
Generated by 'django-admin startproject' using Django 1.8.3.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths... | 'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'webapp.wsgi.application'
# Database
# https://doc | s.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE... |
Surouxx/Excalibur | brain.py | Python | gpl-3.0 | 2,436 | 0.054187 | // Program Name: chatterbot2
#pragma warning(disable: 4786)
include <iostream>
include <string>
include <vector>
include <ctime>
const int MAX_RESP = 3;
typedef std::vector<std::string> vstring;
vstring find_match(std::string input);
void copy(char *array[], vstring &v);
typedef struct {
char *input;
cha... | program
vstring find_match(std::string input) {
vstring result;
for(int i = 0; i < nKnowledgeBaseSize; ++i) {
if(std | ::string(KnowledgeBase[i].input) == input) {
copy(KnowledgeBase[i].responses, result);
return result;
}
}
return result;
}
void copy(char *array[], vstring &v) {
for(int i = 0; i < MAX_RESP; ++i) {
v.push_back(array[i]);
}
}
|
vgonisanz/wpm | src/old_cursesManager.py | Python | lgpl-3.0 | 11,293 | 0.004693 | import curses
import locale
from element_button import Button
"""
This python 3 class will manager a curses windows for you.
To generate HTML documentation for this module issue the command:
pydoc -w cursesManager
"""
class CursesManager(object):
"""
Reverse line y.
:return:... | rrent_window.attroff(attributes)
self._current_window.refresh()
return None
"""
Print book like.
:return: returns nothing
"""
def print_book(self, title, page | s, author = ""):
if self._current_window != None:
y_max, x_max = self._current_window.getmaxyx()
mid_y = (int)(y_max / 2)
q_y = (int)(y_max * 3/4)
q_x = (int)(x_max * 3/4)
# Print title, author, and wait
self.clear()
sel... |
gorcz/security_monkey | security_monkey/watchers/iam/iam_user.py | Python | apache-2.0 | 8,695 | 0.001725 | # Copyright 2014 Netflix, 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 applicable law... | ':
marker = response.marker
else:
break
return all_policy_names
def access_keys_for_user(self, conn, user):
all_access_keys = []
marker = None
while True:
response = self.wrap_aws_rate_limited_call(
conn.get_all... |
if response.is_truncated == u'true':
marker = response.marker
else:
break
return all_access_keys
def mfas_for_user(self, conn, user):
all_mfas = []
marker = None
while True:
response = self.wrap_aws_rate_limited_ca... |
walafc0/soclib | utils/lib/python/soclib_builder/bblock.py | Python | lgpl-2.1 | 5,660 | 0.00477 |
# SOCLIB_GPL_HEADER_BEGIN
#
# This file is part of SoCLib, GNU GPLv2.
#
# SoCLib 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; version 2 of the License.
#
# SoCLib is distributed in the hope that it will... | self.__exists = True
self.__mtime = os.stat(self.__filename).st_mtime
else:
self.__exists = False
self.__mtime = time.time() + 4096
def mtime(self):
return self.__mtime
def delete(self):
if os.path.isfile(self.__filename):
try:
... | def generate(self):
self.generator.process()
def exists(self):
return self.__exists
def __str__(self):
return self.__filename
def __repr__(self):
return '{%s}' % os.path.basename(self.__filename)
def __hash__(self):
return hash(self.__filename)
def __... |
EmreAtes/spack | var/spack/repos/builtin/packages/r-ampliqueso/package.py | Python | lgpl-2.1 | 2,435 | 0.000821 | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | s/ampliQueso', commit='9a4c26ec594171279aba8ab7fe59c4a2ea09b06b')
depends_on('r@3.4.0:3.4.9', when='@1.14.0')
depends_on('r-samr', type=('build', 'run'))
depends_on('r-deseq', type=('build', 'run'))
depends_on('r-edger', t | ype=('build', 'run'))
depends_on('r-xtable', type=('build', 'run'))
depends_on('r-statmod', type=('build', 'run'))
depends_on('r-genefilter', type=('build', 'run'))
depends_on('r-variantannotation', type=('build', 'run'))
depends_on('r-foreach', type=('build', 'run'))
depends_on('r-doparallel', ... |
googleapis/python-aiplatform | samples/generated_samples/aiplatform_v1_generated_vizier_service_delete_study_sync.py | Python | apache-2.0 | 1,389 | 0.00072 | # -*- 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... | e
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Generated code. DO NOT EDIT!
#
# Snippet for DeleteStudy
# NOTE: Thi... | nvironment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-cloud-aiplatform
# [START aiplatform_v1_generated_VizierService_DeleteStudy_sync]
from google.cloud import aiplatform_v1
def sample_delete_study():
# Create a client
client = aiplatfor... |
R-daneel-olivaw/CPET | module2/ProbeLogAggregator.py | Python | lgpl-3.0 | 3,096 | 0.010982 | '''
Created on Feb 26, 2015
@author: Akshat
'''
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.gridspec as mgrid
import ntpath
class PrbLogAgg:
'''
classdocs
'''
dataFrame = {}
csv = []
def __init__(self, output_directory, csvFilePath):
s... | book_repr_html', False)
pd.set_option('display.max_columns', 20)
pd.set_option('display.max_rows', 25)
# For Graph Plot
# df.plot(subplots=True, figsize=(20, 60)); plt.legend(loc='best')
plt.close('all')
fig, ((ax0, ax1, ax2), ( | ax3, ax4, ax5)) = plt.subplots(nrows=2, ncols=3)
fig.set_size_inches(15,5)
gs = mgrid.GridSpec(2, 3)
ax0 = plt.subplot(gs[0, 0])
ax1 = plt.subplot(gs[0, 1])
ax2 = plt.subplot(gs[0, 2])
ax3 = plt.subplot(gs[1, 0])
ax4 = plt.subplot(gs[1, 1])
... |
google/walt | server/main.py | Python | apache-2.0 | 1,813 | 0.002206 | #!/usr/bin/env python
#
# Copyright 2017 The Chromium OS Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org | /licenses/LICENSE-2.0
#
# Unless required by applicable | law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""
Runs a server that receives ... |
woutersmet/Molmodsummer | test/unit_cell.py | Python | gpl-3.0 | 3,464 | 0.008083 | # MolMod is a collection of molecular modelling tools for python.
# Copyright (C) 2007 - 2008 Toon Verstraelen <Toon.Verstraelen@UGent.be>
#
# This file is part of MolMod.
#
# MolMod 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... | uc.cell = numpy.random.uniform(-1, 1, (3, 3))
uc.update_reciproke()
for r_counter in xrange(10):
r0 = nu | mpy.random.normal(0, 10, 3)
r1 = uc.shortest_vector(r0)
self.assert_(numpy.linalg.norm(r0) <= numpy.linalg.norm(r1))
def test_radius_indexes(self):
cell = numpy.array([
[1.5, 0, 0],
[0, 1.5, 0],
[0, 0, 1.5],
], float)
uc = ... |
seraphlnWu/in_trip | in_trip/summary/config.py | Python | mit | 217 | 0 | # -*- coding: utf-8 -*-
# 结巴分词服务ip
JIEBA_SEG_SERVER_IP = "192.168 | .1.92"
# 设置timeout
LIMIT_SEG_SERVER_SECONDS = 0.5
PUNC_STR = (u'。', u'?', u'!', | u"?", u"!", u"\n")
# BM25参数
k1 = 2
b = 0.75
|
Alwnikrotikz/marinemap | lingcod/group_management/admin.py | Python | bsd-3-clause | 197 | 0.010152 | from django. | contrib import admin
from lingcod.group_management.models import GroupRequest
class GroupRequestAdmin(admin.ModelAdmin):
pass
admin.site.register(GroupRequest, GroupRe | questAdmin)
|
thomazs/geraldo | site/newsite/site-geraldo/django/db/backends/postgresql/client.py | Python | lgpl-3.0 | 654 | 0.001529 | from django.db.backends impor | t BaseDatabaseClient
from django.conf import settings
import os
class DatabaseClient(BaseDatabaseClient):
executable_name = 'psql'
def runshell(self):
args = [self.executable_name]
if settings.DATABASE_USER:
args += ["-U", settings.DATABASE_USER]
if settings.DATABASE_PASSWO... | args.extend(["-h", settings.DATABASE_HOST])
if settings.DATABASE_PORT:
args.extend(["-p", str(settings.DATABASE_PORT)])
args += [settings.DATABASE_NAME]
os.execvp(self.executable_name, args)
|
twoolie/Minecraft-Tools | src/minecraft/items.py | Python | mit | 6,762 | 0.145963 | #http://www.minecraftwiki.net/wiki/Data_values
blockids = {
0 :"air",
1 :"stone",
2 :"grass",
3 :"dirt",
4 :"cobblestone",
5 :"wood",
6 :"sapling",
7 :"bedrock",
8 :"water",
9 :"stationary water",
10 :"lava",
11 :"stationary lava",
12 :"sand",
13 :"gravel",
14 :"gold ore",
15 :"iron ore",
16 :"coal ore... | glowstone dust",
349 :"raw fish",
350 :"cooked fish",
351 :"ink sac",
352 :"bone",
353 :"sugar",
354 :"cake",
2256:"gold record",
2257:"green record",
}
item2name = dict([(itemids[id], id) for id in itemids])
item2underName = dict([(itemids[id].replace(" ","_"), id) for id in itemids])
def get_block_type(strin... | eturn int(string)
except:
return id2name[string]
|
bioinformatics-ua/catalogue | emif/developer/urls.py | Python | gpl-3.0 | 3,165 | 0.005371 | # -*- coding: utf-8 -*-
# Copyright (C) 2014 Universidade de Aveiro, DETI/IEETA, Bioinformatics Group - http://bioinformatics.ua.pt/
#
# 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 vers... | ormationView.as_view()),
url(r'^api/getFingerprints/$', getFingerprintsView.as_view()),
url(r'^api/getFingerprints/(?P<quest_slug>[^/]+)$', getFingerprintsView.as_view()),
# FingerprintProxy
url(r'^api/getFingerprintUID/(?P<fingerprint>[^/]+)$', getFingerprintUIDView.as_view()),
url(r'^api/getAnswe... | re/getDocuments/(?P<fingerprint>[^/]+)$', getDocumentsView.as_view()),
url(r'^api/store/putDocuments/(?P<fingerprint>[^/]+)$', putDocumentsView.as_view()),
url(r'^api/store/getPublications/(?P<fingerprint>[^/]+)$', getPublicationsView.as_view()),
url(r'^api/store/getComments/(?P<fingerprint>[^/]+)$', getC... |
SKA-ScienceDataProcessor/algorithm-reference-library | wrappers/serial/calibration/calibration.py | Python | apache-2.0 | 127 | 0.007874 | """ F | unctions to solve for antenna/station gain
"""
from processing_components.calibr | ation.calibration import solve_gaintable |
cowboysmall/rosalind | src/heights/rosalind_gs.py | Python | mit | 489 | 0.006135 | import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '../tools'))
import files
import graphs
def main(argv):
k, Gs = files.read_graphs(argv[0])
sinks = []
for G in Gs:
n, m = G[:2]
edges = G[2]
nodes = [n for n in xrange(1, n + 1)]
sinks.append(gr... |
print ' '.join(str(sink) for sink in sinks)
if __name__ == "__main__":
sys.setrecursionlimit(1048576 | )
main(sys.argv[1:])
|
openSUSE/docmanager | src/docmanager/fileutil.py | Python | gpl-3.0 | 1,478 | 0.016238 | #
# Copyright (c) 2015 SUSE Linux GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 3 of the GNU General Public License as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRAN... | # GNU General Public License for more details.
#
# You should have received a copy of th | e GNU General Public License
# along with this program; if not, contact SUSE LLC.
#
# To contact SUSE about this file by physical or electronic mail,
# you may find current contact information at www.suse.com
import datetime
import os.path
class FileUtil(object):
def __init__(self, filename):
# set the default va... |
project-owner/Peppy | ui/screen/language.py | Python | gpl-3.0 | 2,333 | 0.004715 | # Copyright 2016-2021 Peppy Player peppy.player@gmail.com
#
# This file is part of Peppy Player.
#
# Peppy Player 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 you... | Genre Screen. Extends base Screen class """
def | __init__(self, util, change_language, listeners, voice_assistant):
""" Initializer
:param util: utility object
:param listener: screen menu event listener
"""
Screen.__init__(self, util, "", PERCENT_TOP_HEIGHT, voice_assistant)
self.language_menu = LanguageMenu(... |
AndrewJamesTurner/Every-Womans-Ground | menu.py | Python | gpl-3.0 | 3,345 | 0.001495 |
import sys
import ezpygame
from Box2D import b2World, b2PolygonShape
import shapes
from game import *
class MenuScene(ezpygame.Scene):
class MenuOption:
def __init__(self, callback, image, y_pos, selectable):
self.callback = callback
self.image = image
self.y_pos = y... | selectable=True):
font = pygame.font.Font("assets/TitilliumWeb-Regular.ttf", font_size)
label = font.render(text, True, (255, 255, 255))
self.options.append(self.MenuOption(callback, label, self.next_y, selectable))
self.next_y += font_size*1 | .2
self.next_y += SCREEN_HEIGHT * 0.04
def handle_event(self, event):
# Called every time a pygame event is fired
# Processing keyboard input here gives one event per key press
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN or event.key == pygame.K_KP_... |
Reagankm/KnockKnock | venv/lib/python3.4/site-packages/nltk/help.py | Python | gpl-2.0 | 1,649 | 0.004245 | # Natural Language Toolkit (NLTK) Help
#
# Copyright (C) 2001-2015 NLTK Project
# Authors: Steven Bird <stevenbird1@gmail.com>
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
"""
Provide structured access to documentation.
"""
from __future__ import print_function
import re
from textwrap import w... | ef upenn_tagset(tagpattern=None):
_format_tagset("upenn_tagset", tagpattern)
#####################################################################
# UTILITIES
#####################################################################
def _print_entries(tags, tagdict):
for tag in tags:
entry = tagdict[tag]
... | + examples))
def _format_tagset(tagset, tagpattern=None):
tagdict = load("help/tagsets/" + tagset + ".pickle")
if not tagpattern:
_print_entries(sorted(tagdict), tagdict)
elif tagpattern in tagdict:
_print_entries([tagpattern], tagdict)
else:
tagpattern = re.compile(tagpattern)
... |
billzorn/msp-pymodel | lib/msp_fr5969_model.py | Python | mit | 7,045 | 0.007239 | # fr5969 model parameters
reg_size = 16
reg_bits = 20
mem_bits = 8
word_bits = 2 * mem_bits
ram_size = 2048
ram_start = 0x1c00
fram_size = 64512
fram_start = 0x4400
ivec_start = 0xff90
ivec_count = 56
lower_start = fram_start
lower_size = 0xbb80
upper_start = 0x10000
upper_size = 0x4000
resetvec = 0xfffe
reg_bitmask... | print(repr(self))
print('-- registers --')
if check:
regdump = utils.de | scribe_regs(self.regs)
assert(self.regs == utils.parse_regs(regdump))
print(regdump)
print('-- ram --')
ramidump = utils.describe_interesting_memory(self.ram, ram_start, fill=[0xff, 0x3f])
if check:
ramdump = utils.describe_memory(self.ram, ram_start)
... |
italomaia/turtle-linux | games/DigbyMarshmallow/lib/oxygen.py | Python | gpl-3.0 | 510 | 0.005882 | import actor
class Oxygen(actor.Act | or):
extra_keys = ['capacity', 'pipe_length', 'is_initial']
de | f __init__(self, *args, **kwargs):
super(Oxygen, self).__init__(*args, **kwargs)
self.capacity = kwargs.get('capacity', 3000)
self.contained = self.capacity
self.pipe_length = kwargs.get('pipe_length', 5000)
self.is_initial = kwargs.get('is_initial', False)
def tick(self):
... |
DIRACGrid/DIRAC | src/DIRAC/FrameworkSystem/private/monitoring/ColorGenerator.py | Python | gpl-3.0 | 2,117 | 0.001889 | class ColorGenerator:
def __init__(self):
self.lUsedColors = []
def __equalColors(self, c1, c2):
return c1[0] == c2[0] and c1[1] == c2[1] and c1[2] == c2[2]
def __equalColorInList(self, c1, cl2):
return any(self.__equalColors(c1, c2) for c2 in cl2)
def __toHex(self, n):
... | C2[2]) / 2)
if self.__equalColo | rInList(rC, self.lUsedColors):
im += 1
if im == iM:
iM += 1
im = 0
self.lUsedColors.append(rC)
return self.lUsedColors[iNumColorsUsed % 128]
def getFloatColor(self):
fC = self.__generateColor()
... |
mocobeta/janome | janome/system_dic.py | Python | apache-2.0 | 2,058 | 0.001944 | # Copyright 2022 moco_beta
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softwa... | ies, connections, chardefs, unknowns):
RAMDictionary.__init__(self, entries, connections)
UnknownsDictionary.__init__(self, chardefs, unknowns)
class MMapSystemDictionary(MMapDictionary, UnknownsDictionary):
"""
MMap System dictionary class
"""
__INSTANCE = None
__lock = threading... | _INSTANCE:
cls.__INSTANCE = MMapSystemDictionary(mmap_entries(), connections, chardef.DATA, unknowns.DATA)
return cls.__INSTANCE
def __init__(self, mmap_entries, connections, chardefs, unknowns):
MMapDictionary.__init__(self, mmap_entries[0], mmap_entries[1], mmap_entries[2], co... |
deonwu/robotframework-debuger | rdb_postinstall.py | Python | gpl-2.0 | 1,398 | 0.004292 | import os
import sys
from distutils.sysconfig import get_python_lib
import shutil
def _get_installation_dir():
"""Returns installation location. Works also with easy_install."""
try:
import rdb
except ImportError:
# Workaround for Windows installer problem with Python 2.6.1
# http:/... | detail?id=196
class FakeModule:
def __getattr__(self, name):
raise RuntimeError('Fake module set by rdb_postinstall.py')
sys.modules | ['urllib'] = FakeModule()
import rdb
return os.path.dirname(os.path.abspath(rdb.__file__))
def windows_binary_install():
data_path = os.path.join(sys.prefix, 'rdb', 'settings.rdb',)
install_rdb_path = _get_installation_dir()
rdb_path = os.path.join(install_rdb_path, 'settings.rdb',)
try: ... |
cojacoo/testcases_echoRD | gen_test2123.py | Python | gpl-3.0 | 4,416 | 0.045969 | import numpy as np
import pandas as pd
import scipy as sp
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import os, sys
try:
import cPickle as pickle
except:
import pickle
#connect echoRD Tools
pathdir='../echoRD' #path to echoRD
lib_path = os.path.abspath(pathdir)
#sys.path.append(lib_pa... | ec_2D= | False,maccoat=macscale,saveDT=saveDT,clogswitch=clogswitch,infilt_method=infiltmeth,exfilt_method=exfiltmeth,film=film,infiltscale=infiltscale)
TSstore[i,:,:]=rE.part_store(particles,mc)
#if i/5.==np.round(i/5.):
with open(''.join([wdir,'/results/Z',runname,'_Mstat.pick']),'wb') as handle:
pick... |
jacobjbollinger/sorbet | sorbet/feedmanager/migrations/0006_chg_field_feed_title.py | Python | bsd-2-clause | 5,274 | 0.007205 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'Feed.title'
db.alter_column('feedmanager_feed', 'title', self.gf('django.db.models.fields.... | edmanager.feed': {
'Meta': {'object_name': 'Feed'},
'added': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'hash': ('django.db.models.fields.CharField', [], {'max_length': '32' | }),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'last_checked': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'last_updated': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
... |
brentd-smith/smolkinsite | songs/migrations/0007_auto_20170515_1940.py | Python | gpl-3.0 | 442 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-05-15 19:40
from __future__ import unicode_literals
from django.db import migrations
class Mig | ration(migrations.M | igration):
dependencies = [
('songs', '0006_alternatebookname_alternativeparshaname'),
]
operations = [
migrations.RenameModel(
old_name='AlternativeParshaName',
new_name='AlternateParshaName',
),
]
|
markpasc/arghlog | setup.py | Python | mit | 337 | 0 | from distut | ils.core import setup
setup(
name='arghlog',
version='0.9',
description='Logging integ | ration for argh commands',
author='Mark Paschal',
author_email='markpasc@markpasc.org',
url='https://github.com/markpasc/arghlog',
packages=[],
py_modules=['arghlog'],
requires=['argparse', 'argh'],
)
|
Statoil/libecl | python/tests/ecl_tests/test_grid.py | Python | gpl-3.0 | 23,060 | 0.025369 | #!/usr/bin/env python
# Copyright (C) 2014 Equinor ASA, Norway.
#
# The file 'test_grid.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT 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 ... | fset),
GridGen.create_grid(dim, dV, offset=offset, irregular_offset=True),
GridGen.create_grid(dim, dV, offset=offset, concave=True),
GridGen.create_grid(dim, dV, offset=offset, irregular=True),
GridGen.create_grid(dim, dV, offset=offset, concave=True, irregular=True),
... | grid(dim, dV, offset=0, faults=True),
GridGen.create_grid(dim, dV, offset=offset, faults=True),
GridGen.create_grid(dim, dV, escape_origo_shift=(100, 100, 0), scale=2),
GridGen.create_grid(dim, dV, escape_origo_shift=(100, 100, 0), scale=0.5),
GridGen.create_grid(dim, dV,... |
tanghaibao/goatools | goatools/rpt/write_hierarchy_base.py | Python | bsd-2-clause | 5,169 | 0.002515 | """Print a GO term's lower-level hierarchy."""
__copyright__ = "Copyright (C) 2016-2018, DV Klopfenstein, H Tang. All rights reserved."
__author__ = "DV Klopfenstein"
import sys
# pylint: disable=too-many-instance-attributes,too-few-public-methods
class WrHierPrt(object):
"""Print the hierarchy of a set of obje... | g['dash_len'] + cfg.get('id_len', 10) + 2
def prt_hier_rec(self, item_id, depth=1):
"""Write hierarchy for a GO Term record and all GO IDs down to the leaf level."""
# Shortens hierarchy report by only printing the hierarchy
# for the sub-set of user-specified GO terms which are connected.
... | # Do not print hierarchy from this item downwards if hierarchy is being
# printed as a flat list - that is, with strictly no duplications - and the item has
# already been printed.
# Note that, by default, no_dup_prt is False. *However*, if it is set to
# True then this will ove... |
ldjebran/robottelo | robottelo/decorators/func_shared/__init__.py | Python | gpl-3.0 | 130 | 0 | from robottelo.decorators.func_shared.shared import ( # no | qa
shared,
| SharedFunctionError,
SharedFunctionException,
)
|
uclmr/inferbeddings | data/nations/make_folds_stratified.py | Python | mit | 3,031 | 0.003959 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import argparse
import logging
i | mport numpy as np
from sklearn.cross_validation import Stratifie | dKFold, train_test_split
def read_triples(path):
with open(path, 'rt') as f:
lines = f.readlines()
triples = [(s.strip(), p.strip(), o.strip()) for [s, p, o] in [l.split() for l in lines]]
return triples
def main(argv):
def formatter(prog):
return argparse.HelpFormatter(prog, max_hel... |
emCOMP/visualization | src/python/collection_list.py | Python | mit | 1,564 | 0.014066 | #!/usr/bin/env python
import json, os, csv
import argparse, sys, unicodedata
from pprint import pprint
import requests
from server_messenger import ServerMessenger
def main():
connectToServer();
collections = [];
# Iterate through the database
url = 'jobs/?format=json';
while(True):
... | )
if(item["has_stats"] and item["total_count"] is not None and item["total_count"] > 1000):
collections.append(item)
if(fetched_data["next"] is None):
break
else:
url = '/'.join(fetched_data["next"].split('/')[-2:])
# Write co... | with open('../capture_stats/collections.json', 'w') as out_file:
json.dump(collections, out_file)
def connectToServer():
with open('../local.conf') as config_file:
global server
config = json.load(config_file)
server = ServerMessenger(
base_url = config["se... |
gallandarakhneorg/autolatex | tests/autolatex2tests/config/scm_test.py | Python | lgpl-3.0 | 2,060 | 0.014563 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 1998-2021 Stephane Galland <galland@arakhne.org>
#
# This program is free library; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; either version 3 of the
... | get_commitCLI(s | elf):
self.assertEqual(list(), self.config.commitCLI)
def test_set_commitCLI(self):
self.config.commitCLI = None
self.assertEqual([], self.config.commitCLI)
self.config.commitCLI = list(['a', 'b'])
self.assertEqual(list(['a', 'b']), self.config.commitCLI)
self.config.commitCLI = 'a b'
self.assertEq... |
AddonScriptorDE/plugin.video.vidstatsx_com | default.py | Python | gpl-2.0 | 16,692 | 0.031645 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import xbmcaddon,xbmcplugin,xbmcgui,sys,urllib,urllib2,re,socket,os
socket.setdefaulttimeout(30)
pluginhandle = int(sys.argv[1])
addonID = 'plugin.video.vidstatsx_com'
xbox = xbmc.getCondVisibility("System.Platform.xbox")
addon = xbmcaddon.Addon(addonID)
channelFavsFile=xbmc.t... | deoChartsSortType==str(translation(30105)):
addDir(translation(30010),url,"listVideoCharts","")
addDir(translation(30013),url.replace("/most-popular-","/top-favorited-"),"videoChartsOrderBy2","")
addDir(translation(30011),url.replace("/most-popular-","/top-rated-"),"videoChartsOrderB... | most-popular-","/most-commented-"),"videoChartsOrderBy2","")
addDir(translation(30016),url.replace("/most-popular-","/most-responded-"),"videoChartsOrderBy2","")
xbmcplugin.endOfDirectory(pluginhandle)
elif videoChartsSortType==translation(30010):
videoChartsOrderBy2(url)
... |
michaelmendoza42/robotframework-appiumlibrary | src/AppiumLibrary/keywords/_screenshot.py | Python | apache-2.0 | 1,938 | 0.002064 | # -*- coding: utf-8 -*-
import os
import robot
from keywordgroup import KeywordGroup
class _ScreenshotKeywords(KeywordGroup):
def __init__(self):
self._screenshot_index = 0
# Public
def capture_page_screenshot(self, filename=None):
"""Takes a screenshot of the current page... | no `filename` is given, the screenshot is saved into file
`appium-screenshot-<counter>.png` under the directory where
the Robot Framework log file is written into. The `filename` is
also considered relative to the same directory, if it is not
given in absolute format.
| `css` can be used to modify how the screenshot is taken. By default
the bakground color is changed to avoid possible problems with
background leaking when the page layout is somehow broken.
"""
path, link = self._get_screenshot_paths(filename)
if hasattr(self._current_a... |
wzmao/mbio | mbio/EM/analysis.py | Python | mit | 39,422 | 0.002486 | # -*- coding: utf-8 -*-
"""This module contains some functions for EM analysis.
"""
__author__ = 'Wenzhi Mao'
__all__ = ['genPvalue', 'calcPcutoff', 'showPcutoff', 'transCylinder',
'showMRCConnection', 'showMRCConnectionEach', 'gaussian3D']
def interpolationball(matrix, index, step, r, **kwargs):
"""I... | index[1] + (r / step[1])) // 1 + 1):
for k in arange(ceil(index[2] - (r / step[2])) // 1, floor(index[2] + (r / step[2])) // 1 + | 1):
if (((index[0] - i) * step[0]) ** 2 + ((index[1] - j) * step[1]) ** 2 + ((index[2] - k) * step[2]) ** 2) <= r ** 2:
w.append(1.0 / ((((index[0] - i) * step[0]) ** 2 + (
(index[1] - j) * step[1]) ** 2 + ((index[2] - k) * step[2]) ** 2) ** 2) ** .5)
... |
comicxmz001/LeetCode | Python/58_LengthofLastWord.py | Python | mit | 291 | 0.027491 | class Solution(object):
def lengthOfLastWord(self, s):
| """
:type s: str
:rtype: int
"""
if len(s.split()) == 0:
return 0
return len(s.split()[-1])
if __name__ == '__main__':
s = " sdf"
print Sol | ution().lengthOfLastWord(s) |
bamford/astrobamf | osiris_leastsq_demo.py | Python | mit | 4,729 | 0.005075 | # demonstration of fitting a function to data
from math import sqrt, pi
import numpy
from scipy.optimize import leastsq
from numpy.polynomial import Polynomial
from numpy.polynomial.chebyshev import Chebyshev
from numpy.random import normal, uniform
from matplotlib import pyplot
colors='bgrcmy'*100
def fit_example(... | l = numpy.arange(xmin, xmax, deltax)
nwl = len(wl)
f = gaussian(wl, 0.75, 4750.0, 150.0)
x = numpy.array([])
y = numpy.array([])
id = numpy.array([], numpy.int)
pyplot.ion()
pyplot.close('all')
psim = numpy.zeros(2*nset+order)
offsets = []
scales = []
for i in range(nset):
... | ffset = uniform(-0.2, 0.2)
offsets.append(offset)
scale = uniform(0.8, 1.2)
scales.append(scale)
x = numpy.concatenate((x, wl))
yi = offset + scale * f
pyplot.plot(wl, yi, '--', color=colors[i])
# add some noise to the simulated data
yi += normal(0.0, 0.1,... |
yuanzhao/gpdb | gpMgmt/test/data/dump_pipe.py | Python | apache-2.0 | 360 | 0.005556 | #!/usr/bin/env python
i | mport os
import cPickle
import sys
#communicate with another process through named pipe
#one for receive command, the other for send command
data_file = sys.argv[1]
tmp_fname = "/tmp/%s" % os.path.split(data_file)[1]
with open(data_file, 'r') as rp:
response = rp.read()
with open(tmp_fname, 'w' | ) as fp:
fp.write(response)
|
galbramc/gpkit | docs/source/examples/beam.py | Python | mit | 3,127 | 0.00032 | """
A simple beam example with fixed geometry. Solves the discretized
Euler-Bernoulli beam equations for a constant distributed load
"""
import numpy as np
import gpkit
from gpkit.shortcuts import Var, Vec, Model
from gpkit.small_scripts import mag
class Beam(Model):
"""Discretization of the Euler beam equations ... | e the beam.
L : float
| [m] Length of beam.
EI : float
[N m^2] Elastic modulus times cross-section's area moment of inertia.
q : float or N-vector of floats
[N/m] Loading density: can be specified as constants or as an array.
"""
def setup(self, N=4):
EI = Var("EI", 1e4, "N*m^2")
dx = Var("dx"... |
opennode/nodeconductor-assembly-waldur | src/waldur_mastermind/invoices/filters.py | Python | mit | 1,887 | 0.00265 | import django_filters
from rest_framework import filters
from waldur_core.core import filters as core_filters
from . import models
class InvoiceFilter(django_filters.FilterSet):
customer = core_filters.URLFilter(
view_name='customer-detail', field_name='customer__uuid'
)
customer_uuid = django_f... | , 'year', 'month']
class PaymentProfileFilter(django | _filters.FilterSet):
organization = core_filters.URLFilter(
view_name='customer-detail', field_name='organization__uuid'
)
organization_uuid = django_filters.UUIDFilter(field_name='organization__uuid')
payment_type = django_filters.MultipleChoiceFilter(
choices=models.PaymentType.CHOICES... |
Udayraj123/dashboard_IITG | Binder/discussions/migrations/0005_auto_20160621_1438.py | Python | mit | 572 | 0.001748 | # -*- coding: utf-8 -*-
# Generated by Django 1.10a1 on 2016-06-21 09:08
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('discussions', '0004_post_a... | tings.AUT | H_USER_MODEL),
),
]
|
apark263/tensorflow | tensorflow/contrib/tensorrt/test/neighboring_engine_test.py | Python | apache-2.0 | 2,729 | 0.004764 | # Copyright 2018 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)
e = constant_op.constant(
np.random.normal(.3, 0.05, [3, 2, 3, 4 | ]), name="weights", dtype=dtype)
conv = nn.conv2d(
input=x,
filter=e,
data_format="NCHW",
strides=[1, 1, 1, 1],
padding="VALID",
name="conv")
b = constant_op.constant(
np.random.normal(1.0, 1.0, [1, 4, 1, 1]), name="bias", dtype=dtype)
... |
algorithm-ninja/pixie | src/pixied.py | Python | apache-2.0 | 4,785 | 0.002299 | #!/usr/bin/env python3
import argparse
import ipaddress
import gevent
import gevent.wsgi
import hashlib
import json
import traceback
from gevent import monkey
from werkzeug.exceptions import (BadRequest, HTTPException,
InternalServerError, NotFound)
from werkzeug.routing import Map, R... | parser = argparse.ArgumentParser(
description="pixied",
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("configs", action="store", type=str, nargs="+",
help="config files to load")
parser.add_argument("-a", "--addr", action="store", type=str... | help="port to bind to (default 8080)")
parser.add_argument("-c", "--collector-prefix", action="store", type=str, default="/pixie_collector",
help="prefix on which the collector is served")
args = parser.parse_args()
server = gevent.wsgi.WSGIServer(
(args.addr, args.... |
janol77/rest-api | app/api/models/user.py | Python | gpl-3.0 | 494 | 0 | from app.db import db
from task import Task
class User(db.Document):
name = db.StringField(required=True)
passw | ord = db.StringField(required=True)
email = db.StringField(required=True)
tasks = db.ListField(db.ReferenceField(Task))
def serialize(self):
return {
'id': str(self.id),
| 'name': self.name,
'email': self.email,
'password': self.password,
'tasks': [t.serialize() for t in self.tasks]
}
|
jeff-allen-mongo/mut | mut/state.py | Python | apache-2.0 | 1,173 | 0 | import abc
from typin | g import Dict, List
class State(metaclass=abc.ABCMeta):
"""Base class for inheritable state objects, such as would represent an
| input element's attributes."""
@abc.abstractproperty
def replacements(self) -> Dict[str, str]:
"""Return a dictionary mapping template replacements."""
pass
@abc.abstractproperty
def ref(self) -> str:
"""Return a string uniquely identifying this element."""
pass
... |
piratos/ctfbulletin | challenges/admin.py | Python | mit | 423 | 0.004728 | from django.contrib import admin
from challenges.models import *
class WriteUpAdmin(admin.ModelAdmin):
list_display = ('author', 'challenge', 'date_writeup')
class ChallengeAdmin(admin.ModelAdmin):
list_display = ('name', 'category', 'score', 'fla | g')
admin.site.register(CategoryChallenge)
admin.site.register(Challenger)
admin.site.register(Challenge, ChallengeAdmin)
admin.site.register(WriteUp, W | riteUpAdmin) |
PyAr/PyZombis | tests/test_navigation.py | Python | agpl-3.0 | 874 | 0.001147 | def get_menu_titles(page) -> list:
page.wait_for_load_state()
menu_list = page.query_selector_all("//*[@class='toctree-wrapper compound']/ul/li/a")
return [title.as_element().inner_text() for title in menu_list]
flag = True
def test_check_titles(page):
global flag
if flag:
page.goto("in... | _menu_titles(page)
page.wait_for_load_state()
for menu_item in menu_list:
right_arrow = page.query_selector("//*[@id='rela | tions-next-bottom']/a")
if right_arrow:
page.click("//*[@id='relations-next-bottom']/a")
page.wait_for_load_state()
page_title = page.title().split(" — ")[0]
assert page_title == menu_item
if "toctree" in page.url:
flag = False
... |
archsh/tg2ext.express | example/tg2express/tests/models/__init__.py | Python | mit | 1,626 | 0.000615 | # -*- coding: utf-8 -*-
"""Unit test suite for the models of the application."""
from nose.tools import eq_
from tg2express.model import DBSession
from tg2express.tests import load_app
from tg2express.tests import setup_db, teardown_db
__all__ = ['ModelTest']
def setup():
"""Setup test fixture for all | model tests."""
load_app()
setup_db()
def teardown():
"""Tear down test fixture for all model tests."""
teardown_db()
class ModelTest(object):
"""Base unit test case for the models."""
klass = None
attrs = {}
def setUp(self):
"""Setup test fixture for each model test method... | f.attrs)
new_attrs.update(self.do_get_dependencies())
self.obj = self.klass(**new_attrs)
DBSession.add(self.obj)
DBSession.flush()
return self.obj
except:
DBSession.rollback()
raise
def tearDown(self):
"""Tear down ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.