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
Silmathoron/PyNeurActiv
analysis/__init__.py
Python
gpl-3.0
1,164
0.003436
#!/usr/bin/env python # -*- coding: utf-8 -*- # # This file is part of the PyNeurActiv project, which aims at providing tools # to study and model the activity of neuronal cultures. # Copyright (C) 2017 SENeC Initiative # # This program is free software: you can redistribute it and/or modify # it under the terms of th...
cense, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A P
ARTICULAR 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://www.gnu.org/licenses/>. """ =============== Analysis module =============== Tools to work on simulated or recorded data. Co...
kyleconroy/vogeltron
tests/test_sports.py
Python
mit
6,742
0
import mock from datetime import datetime, timezone import pytz from nose.tools import assert_equals, assert_raises from vogeltron import baseball from bs4 import BeautifulSoup YEAR = datetime.today().year def date_for_month(month, day, hour, minute): timez = pytz.timezone('US/Pacific') return timez.localize...
ge _, upcoming = baseball.schedule('WEST', 'http://example.com') print(upcoming[0].opponent) assert_equals(upcoming, [ baseball.Result('Toronto', june(4, 19, 15), True, None, '0-0'), baseball.Result('Toronto', june(5, 12, 45), True, None, '0-0'), baseball.Result('Arizona', june(7, ...
False, None, '0-0'), baseball.Result('Arizona', june(9, 13, 10), False, None, '0-0'), ]) @mock.patch('requests.get') def test_standings(_get): _get().content = open('tests/fixtures/standings.html').read() standings = baseball.current_standings('NATIONAL', 'WEST') examples = [ baseball...
keen99/SickRage
tornado/test/gen_test.py
Python
gpl-3.0
38,133
0.000367
from __future__ import absolute_import, division, print_function, with_statement import contextlib import datetime import functools import sys import textwrap import time import platform import weakref from tornado.concurrent import return_future, Future from tornado.escape import url_escape from tornado.httpclient i...
f.named_contexts.append(name) try: yield finally: self.assertEqual(self.named_contexts.pop(), name) return context def run_gen(self, f): f() return self.wait() def delay_callback(self, iterations, callback, arg): """Runs c...
ck(arg) else: self.io_loop.add_callback(functools.partial( self.delay_callback, iterations - 1, callback, arg)) @return_future def async_future(self, result, callback): self.io_loop.add_callback(callback, result) def test_no_yield(self): @gen.engine ...
debugchannel/debugchannel-python-client
test/DebugChannelTest.py
Python
mit
891
0.004489
from DebugChannel import DebugChannel from unittest import TestCase from model.Person import Person class DebugChannelTest(TestCase): def setUp(self): self.d = DebugChannel('http://192.168.2.17', '1025', 'hello/world') def testLogStringDoesNotThrowException(self): self.d.log("hello") de...
peterGriffin) self.d.log(chrisGriffin) def testLogRecursionDoesNotThrowException(se
lf): class Node(object): pass n1, n2 = Node(), Node() n1.name, n2.name = "NODE 1", "NODE 2" n1.neighbour, n2.neighbour = n2, n1 self.d.log(n1)
dmlc/tvm
python/tvm/topi/vision/ssd/multibox.py
Python
apache-2.0
10,269
0.000974
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
else: w = ( float32(sizes[0] * in_height) / in_width * sqrt(ratios[k - num_sizes + 1] * 1.0) / 2.0 ) h = sizes[0] / sqrt(ratios[k - num_sizes + 1] * 1.0) /...
+ j * (num_sizes + num_ratios - 1) + k ) output[0, count, 0] = center_w - w output[0, count, 1] = center_h - h output[0, count, 2] = center_w + w output[0, count, 3] = center_h + h return output def multibox_p...
niosus/EasyClangComplete
tests/test_thread_pool.py
Python
mit
3,316
0
"""Test delayed thread pool.""" import time from unittest import TestCase import EasyClangComplete.plugin.utils.thread_pool import EasyClangComplete.plugin.utils.thread_job ThreadPool = EasyClangComplete.plugin.utils.thread_pool.ThreadPool ThreadJob = EasyClangComplete.plugin.utils.thread_job.ThreadJob def run_me(r...
ntainer.wait_until_got_number_of_callbacks(3) self.assertEqual(len(test_container.futures), 3) # Here is what happens. job_1 runs so cannot be cancelled by job_2, so # job_1 keeps running while job_2 is added to the queue. Then we add # job_3, which cancels job_2, which immediately calls...
r.futures[0].cancelled()) self.assertFalse(test_container.futures[1].cancelled()) self.assertEqual(test_container.futures[1].result(), "job_1") self.assertFalse(test_container.futures[2].cancelled()) self.assertEqual(test_container.futures[2].result(), "job_3")
sstjohn/thundergate
py/cdpserver.py
Python
gpl-3.0
22,448
0.005034
''' ThunderGate - an open source toolkit for PCI bus exploration Copyright (C) 2015-2016 Saul St. John 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 Lice...
r": ss = GenericModel(r.name, r.parent) ss.display_name = "instruction register" ss
.accessor = lambda r=r:self._register_model.accessor(r) s2.children += [ss] if not _no_capstone: ss = GenericModel(r.name, r.parent) ss.display_name = "instruction register (decoded)" ss.a...
BrandonY/gsutil
gslib/tests/test_util.py
Python
apache-2.0
14,742
0.002171
# -*- coding: utf-8 -*- # Copyright 2013 Google Inc. All Rights Reserved. # # 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 u...
absolute_import from gslib import util import gslib.tests.testcase as testcase from gslib.tests.util import SetEnvironmentForTest from gslib.tests.util import TestParams from gslib.util import CompareVersions fro
m gslib.util import DecimalShort from gslib.util import HumanReadableWithDecimalPlaces from gslib.util import PrettyTime import httplib2 import mock class TestUtil(testcase.GsUtilUnitTestCase): """Tests for utility functions.""" def test_MakeHumanReadable(self): """Tests converting byte counts to human-reada...
gregnordin/micropython_pyboard
150729_pyboard_to_pyqtgraph/serial_pyboard_to_python.py
Python
mit
9,779
0.015339
#HV Control & #Read and Plot from the PMT #This code is to record the data that is received into the Teensy's ADC. #Includes the HV control and replotting the results at the end. #See CSV Dataplot notebook to plot old experiment data. from __future__ import division from __future__ import print_function from pyqtgr...
me being
today's date and current time and write headings to file in CSV format i = datetime.now() fileName = str(i.year) + str(i.month) + str(i.day) + "_" + str(i.hour) + str(i.minute) + str(i.second) + ".csv" ## File is saved to Documents/IPython Notebooks/RecordedData #f = open('RecordedData\\' + fileName, 'a') #f.write("#D...
dhuang/incubator-airflow
tests/models/test_dagparam.py
Python
apache-2.0
3,838
0.001563
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information #
regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this 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...
the License for the # specific language governing permissions and limitations # under the License. import unittest from datetime import timedelta from airflow.decorators import task from airflow.models.dag import DAG from airflow.utils import timezone from airflow.utils.state import State from airflow.utils.types imp...
daniestevez/jupyter_notebooks
december2021_eclipse/make_waterfalls.py
Python
gpl-3.0
1,664
0
#!/usr/bin/env python3 import argparse import pathlib import numpy as np def waterfall(input_filename, output_filename): fs = 200 nfft = 8192 w = np.blackman(nfft) x = np.fromfile(input_filename, 'int16') x = (x[::2] +
1j*x[1::2])/2**15 freq_span = 5
nbins = round(freq_span / fs * nfft) # In these recordings the internal reference was used, so there # is a frequency offset freq_offset = 11.6 if '2021-12-08T12:57:25' in input_filename.name else 0 band = int(input_filename.name.split('_')[-2].replace('kHz', '')) # 1.6 Hz offset is at 10 MHz fr...
GhostshipSoftware/avaloria
src/commands/cmdhandler.py
Python
bsd-3-clause
20,996
0.002286
""" Command handler This module contains the infrastructure for accepting commands on the command line. The process is as follows: 1) The calling object (caller) inputs a string and triggers the command parsing system. 2) The system checks the state of the caller - loggedin or not 3) If no command string was supplied...
t copy from traceback import format_exc from twisted.internet.defer import inlineCallbacks, returnValue from django.conf import settings from src.comms.channelhandler import CHANNELHANDLER from src.utils import logger, utils from src.commands.cmdparser import at_multimatch_cmd from src.utils.utils impor
t string_suggestions, to_unicode from django.utils.translation import ugettext as _ __all__ = ("cmdhandler",) _GA = object.__getattribute__ _CMDSET_MERGE_CACHE = WeakValueDictionary() # This decides which command parser is to be used. # You have to restart the server for changes to take effect. _COMMAND_PARSER = uti...
InspectorIncognito/visualization
login/apps.py
Python
gpl-3.0
150
0
# -*- coding: utf-8 -*-
from __future__ import unicode_literals from django.apps import AppConfig class LoginConfig(AppConfig): n
ame = 'login'
infoxchange/messagemedia-python
mmsoap/client.py
Python
apache-2.0
13,370
0.002917
# # Copyright 2014-2016 MessageMedia # 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, s...
ly.append(this_confirm_item) request_body = self.create('ConfirmRepliesBodyType') request_body.replies = confirm_reply_list return self.client.service.confirmReplies(self.authentication, request_body) def check_reports(self, maximum_reports=None): """ Check delivery reports...
:param maximum_reports: Limits the number of reports returned in the response. Default is to return all if this value isn't supplied. :return: Iterable containing the reports, never null. """ request_body = self.create('CheckReportsBodyType') if maxim...
scalyr/scalyr-agent-2
tests/unit/url_monitor_test.py
Python
apache-2.0
4,851
0.001237
# Copyright 2014 Scalyr 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 writing, so...
} config = MonitorConfig(content=config_data) url_monitor = UrlMonitor(monitor_config=config, logger=mock_logger) actual_request = url_monitor.build_request() self.assertEqual(actual_request.get_method(), "GET") self.assertFalse(actual_request.data is not None) self....
qual(actual_request.header_items(), EXPECTED_BASE_HEADERS) def test_get_request_with_headers(self): mock_logger = mock.MagicMock() config_data = { "url": "http://fooUrl", "request_method": "GET", "request_data": None, "request_headers": self.legit_hea...
TheTimmy/spack
var/spack/repos/builtin/packages/r-leaflet/package.py
Python
lgpl-2.1
2,218
0.000451
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, [email protected], All rights reserved. # LLNL-CODE-64...
thub.com/llnl/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free s
oftware; 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) version 2.1, February 1999. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF #...
Hiestaa/RLViz
experiments/gym_test_2.py
Python
mit
7,015
0
#! .env/bin/python # -*- coding: utf8 -*- from __future__ import unicode_literals # import time import random import itertools # from collections import d
efaultdict import gym import numpy as np # implementation of the sarsa algorithm on the mountain ca
r using values # rounding for value function approximation # Note: discarded because matplotlib was a bitch. # def plot(Q): # """ # Plot the mountain car action value function. # This only account for the two first dimensions of the state space. # This plots in a 2 dimensional space circle for each act...
certain/certain
certain/StoreServer/__init__.py
Python
agpl-3.0
325
0
"""StoreServer provides a number of plugins which can provide a store service on a server. There are currently 2 plugins available: ``webserver`` and ``gitdaemon``. These can be used to simplify provision of a store, e.g using the ``webserver`
` StoreServer instead of installing a 3rd party webserver suc
h as Apache. """
sourcepole/qgis-openlayers-plugin
openlayers/openlayers_overview.py
Python
gpl-2.0
2,585
0.000387
# -*- coding: utf-8 -*- """ /*************************************************************************** Openlayers Overview - A QGIS plugin to show map in browser(google maps and others) ------------------- begin : 2011-03-01 copyright : (C) 2011 by Luiz Mott...
; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * ...
*************************************************************/ """ from qgis.PyQt.QtCore import Qt from qgis.PyQt.QtWidgets import QApplication, QDockWidget from .openlayers_ovwidget import OpenLayersOverviewWidget class OLOverview(object): def __init__(self, iface, olLayerTypeRegistry): self._iface = if...
karlproject/karl.saml2
karl/saml2/identity.py
Python
gpl-2.0
473
0
from pyramid.view import view_config @view_config(name='sso', renderer='templates/login.pt') def sign_on(context, request): """ Perform the SAML2 SSO dance. - If the request already has
valid credentials, process the 'SAMLRequest' query string value and return a POSTing redirect. - If processing the POSTed login form, authenticate. - If no authenticated user is known, displa
y the login form. """ return {'hidden': request.GET.items()}
pap/rethinkdb
scripts/generate_serialize_macros.py
Python
agpl-3.0
9,043
0.003096
#!/usr/bin/env python # Copyright 2010-2014 RethinkDB, all rights reserved. import sys """This script is used to generate the RDB_MAKE_SERIALIZABLE_*() and RDB_MAKE_ME_SERIALIZABLE_*() macro definitions. Because there are so many variations, and because they are so similar, it's easier to just have a Python s
cript to generate them. This script is meant to be run as follows (assuming you are in the "rethinkdb/src" directory)
: $ ../scripts/generate_serialize_macros.py > rpc/serialize_macros.hpp """ def generate_make_serializable_macro(nfields): fields = "".join(", field%d" % (i + 1) for i in xrange(nfields)) zeroarg = ("UNUSED " if nfields == 0 else "") print "#define RDB_MAKE_SERIALIZABLE_%d(type_t%s) \\" % \ (nfie...
justb4/stetl
docs/conf.py
Python
gpl-3.0
7,939
0.00718
# -*- coding: utf-8 -*- # # Stetl documentation build configuration file, created by # sphinx-quickstart on Sun Jun 2 11:01:36 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All c...
project. project = u'Stetl' copyright = u'20
13+, Just van den Broecke' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '1.2-dev' # The full version, including alpha/beta/rc tags. release = '1.2-dev' ...
sdiazpier/nest-simulator
testsuite/summarize_tests.py
Python
gpl-2.0
3,966
0.001513
# -*- coding: utf-8 -*- # # summarize_tests.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST 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...
' Please report test failures by creating an issue at') print('
ERROR: type should be string, got " https://github.com/nest/nest_simulator/issues')\n print()\n print(tline)\n print()\n\n sys.exit(1)\n else:\n print('The NEST Testsuite passed successfully.')\n print()\n print(tline)\n print()\n"
guillaume-chevalier/HAR-stacked-residual-bidir-LSTMs
data/preprocess_data.py
Python
apache-2.0
13,571
0.002432
# Adapted from: https://github.com/sussexwearlab/DeepConvLSTM __author__ = 'fjordonez, gchevalier' from signal_filtering import filter_opportunity_datasets_accelerometers import os import zipfile import argparse import numpy as np import cPickle as cp from io import BytesIO from pandas import Series # Hardcoded num...
t/dataset/S2-ADL3.dat', 'OpportunityUCIDataset/dataset/S3-Drill.dat', 'OpportunityUCIDataset/dataset/S3-ADL1.dat', 'OpportunityUCIDataset/dataset/S3-ADL2.dat', 'OpportunityUCIDataset/dataset/S3-ADL3.dat' ] OPPORTUNITY_DATA_FILES_TEST = [ '
OpportunityUCIDataset/dataset/S2-ADL4.dat', 'OpportunityUCIDataset/dataset/S2-ADL5.dat', 'OpportunityUCIDataset/dataset/S3-ADL4.dat', 'OpportunityUCIDataset/dataset/S3-ADL5.dat' ] def select_columns_opp(data): """Selection of the 113 columns employed in the OPPORTUNITY challenge :param data: numpy...
google/tf-quant-finance
tf_quant_finance/experimental/pricing_platform/framework/core/models.py
Python
apache-2.0
1,474
0.005427
# Lint as: python3 # Copyright 2020 Google LLC # # Licensed under
the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is di...
RRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Supported pricing models.""" import enum from typing import Any import dataclasses class InterestRateModelType(enum.Enum): """Models for pricing ...
IskyN/submeter-bill-generator
scratch/testing_requests.py
Python
apache-2.0
1,093
0.000915
import requests site_url = "http://meterdata.submetersolutions.com" login_url = "/login.php" file_url = "/consumption_csv.php" username = input("Enter username: ") password = input("Enter password: ") # Thanks to tigerFinch @ http://stackov
erflow.com/a/17633072 # Fill in your details here
to be posted to the login form. login_payload = {"txtUserName": username, "txtPassword": password, "btnLogin": "Login"} query_string = {"SiteID": "128", "FromDate": "02/01/2017", "ToDate": "02/28/2017", "SiteName": "Brimley...
walterbender/turtleconfusion
plugins/rfid/rfidrweusb.py
Python
mit
6,437
0.000777
from device import RFIDDevice from serial import Serial import dbus from dbus.mainloop.glib import DBusGMainLoop import gobject from time import sleep import utils HAL_SERVICE = 'org.freedesktop.Hal' HAL_MGR_PATH = '/org/freedesktop/Hal/Manager' HAL_MGR_IFACE = 'org.freedesktop.Hal.Manager' HAL_DEV_IFACE = 'org.freede...
er.write('a') self.ser.write('t') self.ser.write('\x0d') resp = self.ser.read(33)[0:-1].split('_') if resp.__len__() is not 6 or resp in self.tags: return True self.tags.append(resp) anbit_bin = utils.dec2bin(int(resp[2])) reserved_bin = '000000000000...
nt(resp[3])) country_bin = utils.dec2bin(int(resp[0])) while country_bin.__len__() < 10: country_bin = '0' + country_bin id_bin = utils.dec2bin(int(resp[1])) while id_bin.__len__() < 10: id_bin = '0' + id_bin tag_bin = anbit_bin + reserved_bin + databit_b...
Christophe-Foyer/Naive_Bayes_Price_Prediction
Old files and backups/Naive Bayes Classifier - Copie.py
Python
gpl-3.0
7,147
0.019169
#!/usr/bin/env python # Wheat price prediction using Baysian classification. # Version 1.0 # Christophe Foyer - 2016 from xlrd import open_workbook import random import math #set filename: filename = 'Wheat-price-data.xlsx' #import wheat price data (will automate downloading later, probably a different script tha...
048, 2052, 2056, 2060, 2064, 2068, 2072, 2076, 2080, 2084, 2088, 2092, 2096] i = 0 leap = 0 #this will find how many years and how
many leftover days for that year while days >= (365 + leap): leap = 0 if i + 1900 in leap_years: leap = 1 days = days - 365 - leap i = i + 1 year = i #now find the month and leftover days given leftover days month = 1 ...
KeepSafe/ks-email-parser
setup.py
Python
apache-2.0
1,170
0.004274
import os from setuptools import setup, find_packages version = '0.3.2' install_requires = [ 'Markdown < 3', 'beautifulsoup4 < 5', 'inlinestyler==0.2.1', 'pystache < 0.6', 'parse < 2' ] tests_require = [ 'nose', 'flake8==2.5.4', 'coverage', ] devtools_require = [ 'twine', 'bu...
'License :: OSI Approved :: BSD License', 'Intended Audience :: Developers', 'Programming Language :: Python' ], author='Keepsafe', author_email='[email protected]', url='https://github.com/KeepSafe/ks-email-parser',
license='Apache', packages=find_packages(), install_requires=install_requires, tests_require=tests_require, extras_require={ 'tests': tests_require, 'devtools': devtools_require, }, entry_points={'console_scripts': ['ks-email-parser = email_parser.cmd:main']}, include_pack...
Microsoft/ApplicationInsights-Python
django_tests/tests.py
Python
mit
16,940
0.004073
import os import logging import django from django.test import TestCase, Client, modify_settings, override_settings from applicationinsights import TelemetryClient from applicationinsights.channel import TelemetryChannel, SynchronousQueue, SenderBase, NullSender, AsynchronousSender from applicationinsights.channel.Se...
l(data['responseCode'], 404, "Status code") self.assertEqual(data['success'], False, "Success value") self.assertEqual(data['url'], 'http://testserver/errorer', "Request url") def test_template(self): """Tests that views using templates operate correctly and that template data is logged""" ...
lf.get_events(1) data = event['data']['baseData'] self.assertEqual(event['name'], 'Microsoft.ApplicationInsights.Request', "Event type") self.assertEqual(data['success'], True, "Success value") self.assertEqual(data['responseCode'], 200, "Status code") self.assertEqual(data['prop...
cloudera/hue
apps/impala/src/impala/dbms.py
Python
apache-2.0
8,037
0.009332
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
erverException, QueryServerTimeoutException, \ get_query_server_config as beeswax_query_server_config, get_query_server_config_via_connector from impala import conf from impala.impala_flags imp
ort get_hs2_http_port if sys.version_info[0] > 2: from django.utils.translation import gettext as _ else: from django.utils.translation import ugettext as _ LOG = logging.getLogger(__name__) def get_query_server_config(connector=None): if connector and has_connectors(): query_server = get_query_server_co...
theskumar-archive/flask-api
flask_api/tests/test_app.py
Python
bsd-2-clause
4,692
0.001279
# coding: utf8 from __future__ import unicode_literals from flask import abort, make_response, request from flask_api.decorators import set_renderers from flask_api import exceptions, renderers, status, FlaskAPI import json import unittest app = FlaskAPI(__name__) app.config['TESTING'] = True class JSONVersion1(ren...
ontent"}' self.assertEqual(response.get_data().decode('utf8'), expected) def test_set_headers(self): with app.test_client() as client: response = client.get('/set_headers/') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response....
tEqual(response.get_data().decode('utf8'), expected) def test_make_response(self): with app.test_client() as client: response = client.get('/make_response_view/') self.assertEqual(response.content_type, 'application/json') self.assertEqual(response.headers['Location'], '...
rackerlabs/django-DefectDojo
dojo/db_migrations/0063_jira_refactor.py
Python
bsd-3-clause
2,280
0.002632
# Generated by Django 2.2.16 on 2020-11-07 11:31 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('dojo', '0062_add_vuln_id_from_tool'), ] operations = [ migrations.DeleteModel( name='JIRA_Clon...
, ), migrations.AlterField(
model_name='jira_project', name='jira_instance', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='dojo.JIRA_Instance', verbose_name='JIRA Instance'), ), ]
unioslo/cerebrum
Cerebrum/modules/no/uio/randsone_ldif.py
Python
gpl-2.0
1,562
0
# -*- coding: utf-8 -*- # # Copyright 2017-2020 University of Oslo, Norway # # This file is part of Cerebrum. # # Cerebrum 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 # ...
in ous: ous.extend(tree.get(ou, ())) self.ou_tree = dict((ou, tree[ou]) for ou in ous if ou in tree) def init_attr2id2contacts(self): self.attr2id2contacts = {} self.id2labeledURI = {} def init_person_titles(self): self.person_titles = {} def init_person_addres...
= {}
andrewjw/airplay2sonos
airplay2sonos/__init__.py
Python
gpl-2.0
689
0.001451
# airplay2sonos is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as
published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # This program is 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...
p://www.gnu.org/licenses/>. from main import main
Tarrasch/luigi
luigi/tools/deps.py
Python
apache-2.0
4,717
0.00318
#!/usr/bin/env python # Finds all tasks and task outputs on the dependency paths from the given downstream task T # up to the given source/upstream task S (optional). If the upstream task is not given, # all upstream tasks on all dependancy paths of T will be returned. # Terms: # if the execution of Task T depends ...
goal_task_family, path + [next]): yield t class upstream(luigi.task.Config): ''' Used to provide the parameter upstream-family ''' family = parameter.Parameter(default=None) def find_deps(task, upstream_task_family): '''
Finds all dependencies that start with the given task and have a path to upstream_task_family Returns all deps on all paths between task and upstream ''' return set([t for t in dfs_paths(task, upstream_task_family)]) def find_deps_cli(): ''' Finds all tasks on all paths from provided CLI task...
dgoldin/snakebite
doc/source/conf.py
Python
apache-2.0
8,202
0.007071
# -*- coding: utf-8 -*- # # snakebite documentation build configuration file, created by # sphinx-quickstart on Tue
Apr 30 11:39:44 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys impor...
es to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('../../snakebite')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphin...
VTabolin/vmware-dvs
vmware_dvs/agent/dvs_neutron_agent.py
Python
apache-2.0
17,391
0.000115
# Copyright 2015 Mirantis, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by a...
delete_network(current) @dvs_util.wrap_retry def update_network_precommit(self, current, segment, original): try: dvs = self._lookup_dvs_for_context(segment) except (exceptions.NoDVSForPhysicalNetwork) as e: LOG.info(_LI('Network %(id)s not updated. Reason: %(reason)s') ...
ns.InvalidNetwork: pass else: dvs.update_network(current, original) @dvs_util.wrap_retry def book_port(self, current, network_segments, network_current): physnet = network_current['provider:physical_network'] dvs = None dvs_segment = None for segm...
leapcode/soledad
tests/benchmarks/test_crypto.py
Python
gpl-3.0
3,238
0
""" Benchmarks for crypto operations. If you don't want to stress your local machine too much, you can pass the SIZE_LIMT environment variable. For instance, to keep the maximum payload at 1MB: SIZE_LIMIT=1E6 py.test -s tests/perf/test_crypto.py """ import pytest import os import json from uuid import uuid4 from lea...
def test_doc_encryption(soledad_client, txbenchmark, payload): """ Encrypt a document of a given size. """ crypto = soledad_client
()._crypto DOC_CONTENT = {'payload': payload(size)} doc = SoledadDocument( doc_id=uuid4().hex, rev='rev', json=json.dumps(DOC_CONTENT)) yield txbenchmark(crypto.encrypt_doc, doc) return test_doc_encryption # TODO this test is really bullshit, because it's still in...
anchore/anchore-engine
anchore_engine/decorators.py
Python
apache-2.0
1,604
0.002494
""" Generic decorators for use in all parts of the system """ def delegate_to_callable(fn, err_msg=None): """ Delegate a call of the same name to the object returned by the fn() invocation. Useful for lazy initializers and functions that return a common singleton. Can be used to hoist a singleton objects ...
gate {} to {}, no attribute to delegate to".format(
f.__name__, str(obj) ) ) delegated_attr = getattr(obj, f.__name__) if not callable(delegated_attr): raise Exception( "Cannot delegate {} to {} due to not a callable attribute".format( ...
asoliveira/NumShip
scripts/plot/leme-velo-u-cg-plt.py
Python
gpl-3.0
2,013
0.028957
#!/usr/bin/env python # -*- coding: utf-8 -*- #É adimensional? adi = False #É para salvar as figuras(True|False)? save = True #Caso seja para salvar, qual é o formato desejado? formato = 'jpg' #Caso seja para salvar, qual é o diretório que devo salvar? dircg = 'fig-sen' #Caso seja para salvar, qual é o nome do arquivo...
(acehis4[:, 0], acehis4[:, 1],color = r3c, linestyle = r3s, linewidth = 1, label=ur'1.3leme') plt.title(titulo) plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) plt.ylabel(ylabel) plt.xlabel(xveloabel) plt.axis(axl) plt.grid(True) if save: if not os.path.exists(dircg): os.makedirs(dircg) ...
+ '/' + nome + '.' + formato , format=formato) else: plt.show()
jfburkhart/shyft
shyft/tests/pyapi/test_selector_ts.py
Python
lgpl-3.0
7,317
0.00287
import math import socket import tempfile import unittest from contextlib import closing import numpy as np from shyft.api import ( Calendar, UtcPeriod, DtsServer, DtsClient, TimeAxis, TimeSeries, POINT_AVERAGE_VALUE, POINT_INSTANT_VALUE ) from shyft.pyapi import fixed_tsv, windowed_percentiles_tsv, peri...
r() self.server.set_listening_port(self.port) self.server.start_async() self.client = DtsClient(rf'localhost:{self.port}') def tearDown(self) -> None: self.server.clear() del self.server del self.port def test_fixed_tsv_empty(self) -> None: """Test th...
1), cal.time(2018, 1, 1)) tsv = fixed_tsv(period, []) self.assertEqual(len(tsv), 0) def test_fixed_tsv_values(self) -> None: """Test that a TsVector with fixed constant values is generated by fixed_tsv when given a sequence of values.""" cal = Calendar() period = Ut...
cherrishes/weilai
xingxing/protobuf/python/lib/Python3.4/google/protobuf/pyext/descriptor_cpp2_test.py
Python
apache-2.0
2,506
0.001995
#! /usr/bin/python # # Protocol Buffers - Google's data interchange format # Copyright 2008 Google Inc. All rights reserved. # https://developers.google.com/protocol-buffers/ # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are ...
DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF T...
for google.protobuf.pyext behavior.""" __author__ = '[email protected] (Anuraag Agrawal)' import os os.environ['PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION'] = 'cpp' os.environ['PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION_VERSION'] = '2' # We must set the implementation version above before the google3 imports. # pylint: di...
antoinecarme/pyaf
tests/model_control/detailed/transf_Fisher/model_control_one_enabled_Fisher_Lag1Trend_Seasonal_Hour_LSTM.py
Python
bsd-3-clause
154
0.051948
import tests.model_control.test_ozone_custom_models_enabled as testmod
testmod.build_model( [
'Fisher'] , ['Lag1Trend'] , ['Seasonal_Hour'] , ['LSTM'] );
unphased/Vim-IndentFinder
test_many_files.py
Python
bsd-2-clause
2,378
0.037006
#!/usr/bin/env pyt
hon # # Indentation finder, by Philippe Fremy <phil at freehackers dot org> # Copyright 2002,2005 Philippe Fremy # # This program is distributed under the BSD license. You should have received # a copy of t
he file LICENSE.txt along with this software. # import indent_finder import os, glob import unittest from pprint import pprint TEST_DEFAULT_RESULT=('',0) class Test_many_files( unittest.TestCase ): def check_file( self, fname, result, expected_vim_result ): ifi = indent_finder.IndentFinder( TEST_DEFA...
Jaza/url-for-s3
setup.py
Python
apache-2.0
1,123
0
import os import setuptools module_path = os.path.join(os.path.dirname(__file__), 'url_for_s3.py') version_line = [line for line in open(module_path) if line.startswith('__version__')][0] __version__ = version_line.split('__version__ = ')[-1][1:][:-2] setuptools.setup( name="url-for-s3", ver...
_description=open('README.rst').read(), py_modules=['url_for_s3'], zip_safe=False, platforms='any', install_requires=[], classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Operating System :: O...
nguage :: Python :: 3', 'Programming Language :: Python :: 3.3', ], )
kingsdigitallab/tvof-django
tvof/kiln/urls.py
Python
mit
232
0
from django.urls import re_path from .views import process urlpatterns = [ re_path( r'biblio
graphy/?$', process, {'kiln_url':
'bibliography', 'page_title': 'Bibliography'}, name='bibliography' ), ]
vlegoff/tsunami
src/primaires/information/__init__.py
Python
bsd-3-clause
13,007
0.00085
# -*-coding:Utf-8 -* # Copyright (c) 2010-2017 LE GOFF Vincent # 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 # ...
versions = self.importeur.supenr.charger_unique(Versions) if versions is None: versions = Versions() self.versions = versions annonces = self.importeur.supenr.charger_unique(Annonces) if annonces is None: annonces = Annonces() self.annonces = an...
tips = Tips() self.tips = tips self.newsletters = sorted(importeur.supenr.charger_groupe(Newsletter), key=lambda nl: nl.date_creation) self.roadmaps = sorted(importeur.supenr.charger_groupe(Roadmap), key=lambda r: r.no) # On lie la méthode joueur_conne...
sheplu/Anthill
Python/utils/Simulation.py
Python
mit
130
0.046154
#!/user/bin/
python # coding: utf8 class Simulation: """docstring for Simulation""" def __init__(self, arg):
self.arg = arg
mk8310/im_demo
views/index.py
Python
gpl-3.0
405
0
#!/usr/bin/env python # -*-coding:utf-8-*-
''' Author : ming date : 2016/11/27 上午12:20 role : Version Update ''' from tornado import web from tornado.web import HTTPError class IndexHandler(web.RequestHandler): def get(self, room):
if room == 'get': raise HTTPError(500) self.room = room self.render('index.html', room=self.room, host=self.request.host)
prat0318/bravado-core
tests/validate/validate_array_test.py
Python
bsd-3-clause
3,505
0.000571
from jsonschema.exceptions import ValidationError import pytest from bravado_core.validate import validate_array from tests.validate.conftest import email_address_format @pytest.fixture def int_array_spec(): return { 'type': 'array', 'items':
{ 'type': 'integer', } } def test_minItems_success(minimal_swagger_spec, in
t_array_spec): int_array_spec['minItems'] = 2 validate_array(minimal_swagger_spec, int_array_spec, [1, 2, 3]) def test_minItems_failure(minimal_swagger_spec, int_array_spec): int_array_spec['minItems'] = 2 with pytest.raises(ValidationError) as excinfo: validate_array(minimal_swagger_spec, int...
walchko/soccer2
pygecko_old/Example.py
Python
mit
4,227
0.023657
#!/usr/bin/env python ############################################## # The MIT License (MIT) # Copyright (c) 2016 Kevin Walchko # see LICENSE for full details ############################################## """ http://www.howtogeek.com/225487/what-is-the-difference-between-127.0.0.1-and-0.0.0.0/ What is the Differenc...
e loopback address (also known as localhost). * 0.0.0.0 is a non-routable meta-address used to designate an invalid, unknown, or non-applicable target (a no particular address place holder). In the con
text of a route entry, it usually means the default route. In the context of servers, 0.0.0.0 means all IPv4 addresses on the local machine. If a host has two IP addresses, 192.168.1.1 and 10.1.2.1, and a server running on the host listens on 0.0.0.0, it will be reachable at both of those IPs. """ from __future__ im...
michaelnt/doorstop
doorstop/core/tests/test_builder.py
Python
lgpl-3.0
2,052
0.000487
# SPDX-License-Identifier: LGPL-3.0-only """Unit tests for the doorstop.core.builder module.""" import unittest from unittest.mock import Mock, patch from doorstop.core.builder import _clear_tree, build, find_document, find_item from doorstop.core.tests import EMPTY, FILES, Mock
DocumentNoSkip, MockDocumentSkip from doorstop.core.tree import Tree class TestModule(unittest.TestCase): """Unit tests for the doorstop.core.builder module.""" @patch('doorstop.core.vcs.find_root', Mock(return_value=EMPTY)) def test_run_empty(self): """Verify an empty directory is an empty hiera...
core.vcs.find_root', Mock(return_value=FILES)) def test_build(self): """Verify a tree can be built.""" tree = build(FILES) self.assertEqual(4, len(tree)) @patch('doorstop.core.document.Document', MockDocumentSkip) @patch('doorstop.core.vcs.find_root', Mock(return_value=FILES)) d...
jchaffraix/ConfigMisc
install.py
Python
bsd-2-clause
1,293
0.022428
import os import subprocess import sys GITHUB="[email protected]:jchaffraix/ConfigMisc.git" # TODO: Allow customization. # This is hardcoded to match the bash_profile file for now. PATH="~/Tools/Scripts" def install_config(path, config, copy=False): # Check if the path exists. name = config.split("/")[-1] dst = pa...
GITHUB, path]) # Install the different configuration. install_c
onfig("~", "/".join([path, "config", ".bash_profile"])) if __name__ == "__main__": install(PATH)
TRECVT/vigir_footstep_planning_basics
vigir_footstep_planning_lib/src/vigir_footstep_planning_lib/qt_helper.py
Python
gpl-3.0
2,044
0.009295
#!/usr/bin/env python import rospy from python_qt_binding.QtCore import Qt from python_qt_binding.QtGui import QHBoxLayout, QGroupBox, QTextEdit, QDoubleSpinBox, QColor # generic helper to generate quickly QDoubleSpinBox def generate_q_double_spin_box(default_val, range_min, range_max, decimals, single_step): sp...
spin_box) return spin_box # adds a layout with frame and text to parent widget def add_layout_with_frame(parent, layout, text = ""): box_layout = QHBoxLayout() box_layout.addLayout(layo
ut) group_box = QGroupBox() group_box.setStyleSheet("QGroupBox { border: 1px solid gray; border-radius: 4px; margin-top: 0.5em; } QGroupBox::title { subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px; }") group_box.setTitle(text) group_box.setLayout(box_layout) parent.addWidget(group...
LordSputnik/beets
beetsplug/types.py
Python
mit
1,775
0
# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2016, Thomas Scholtes. # # Permission is hereby granted, free of c
harge, 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, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit perso...
or substantial portions of the Software. from __future__ import (division, absolute_import, print_function, unicode_literals) from beets.plugins import BeetsPlugin from beets.dbcore import types from beets.util.confit import ConfigValueError from beets import library class TypesPlugin(Beets...
Brocade-OpenSource/OpenStack-DNRM-Nova
nova/tests/virt/baremetal/db/test_bm_node.py
Python
apache-2.0
6,918
0.000578
# Copyright (c) 2012 NTT DOCOMO, INC. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
r node's interface is not affected if_x = db.bm_interface_get(self.context, if_x_id) self.assertEqual(self.ids[1], if_x['bm_node_id']) self.assertRaises( exception.NodeNotFound, db.bm_node_get, self.context, self.ids[0]) r = db.bm_node_get_all(...
rtEqual(fn['pm_address'], '2') fn = db.bm_node_find_free(self.context, 'host2', memory_mb=500, cpus=2, local_gb=100) self.assertEqual(fn['pm_address'], '3') fn = db.bm_node_find_free(self.context, 'host2', memory_mb=1001, cpus...
klanestro/vortaro
words/tools.py
Python
gpl-3.0
1,001
0.005994
import random # generate a random bit order # you'll need to save this mapping permanently, perhaps just hardcode it # map how ever many bits you need to represent your integer space mapping = range(34) mapping.reverse() # alphabet for changing from base 10 chars
= '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' # shuffle the bits def encode(n): result = 0 for i, b in enumerate(mapping):
b1 = 1 << i b2 = 1 << b if n & b1: result |= b2 return enbase(result) # unshuffle the bits def decode(n): result = 0 for i, b in enumerate(mapping): b1 = 1 << i b2 = 1 << b if n & b2: result |= b1 return debase(result) # change the base...
vsajip/django
django/contrib/gis/db/backends/postgis/operations.py
Python
bsd-3-clause
25,275
0.003521
import re from decimal import Decimal from django.conf import settings from django.contrib.gis.db.backends.base import BaseSpatialOperations from django.contrib.gis.db.backends.util import SpatialOperation, SpatialFunction from django.contrib.gis.db.backends.postgis.adapter import PostGISAdapter from django.contrib.gi...
'overlaps_below' : PostGISOperator('&<|'), # The "|&>" operator returns true if A's bounding box overlaps or # is above B's bounding box. 'overlaps_above' : PostGISOperator('|&>'), # The "<<|" operator returns true if A's bounding box is strictly # below...
's bounding box. 'strictly_below' : PostGISOperator('<<|'), # The "|>>" operator returns true if A's bounding box is strictly # above B's bounding box. 'strictly_above' : PostGISOperator('|>>'), # The "~=" operator is the "same as" operator. It tests actual ...
eneasz/RasHeating-Control
custom.py
Python
gpl-3.0
2,070
0.016425
#!/usr/bin/python #This is where you can set up your own scheduled by providing hour and minute when you want to start your task and duration where you say how long do you want to run it for. This is devided by each day of the week so you can run differen scheduler each day. It is possi
ble to extend this with another column for example task and th
is way it can run different tasks for each setting. week={ 'Monday':[{'hour': 10, 'minute': 19, 'duration': 460}, {'hour': 12, 'minute': 20, 'duration': 2}, {'hour': 18, 'minute': 0, 'duration': 362}, {'hour': 20, 'minute': 30, 'duration': 20}, ...
makeralchemy/stop-action-movie-maker
delete_frame_set.py
Python
mit
4,978
0.003415
#!/usr/bin/env python # delete_frame_set.py """ deletes the frame files associated with a stop action movie """ import argparse import os FILE_TYPE = '.png' # images will be saved as .png files COUNT_TYPE = '.count' # file type for the file containing the image count READ_ONLY = 'r' # open ...
les = True # else: # delete_files = False if delete_files: _, return_message = delete_frame_set(args.target_movie_name, prog_name, print_dm) print return_message else: print "file...
exit(return_code) # command line execution starts here if __name__ == "__main__": main()
largetalk/tenbagger
capital/reactor/reactor/urls.py
Python
mit
861
0
"""reactor URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based...
terns: path('blog/', include('b
log.urls')) """ from django.contrib import admin from django.urls import path from django.urls import include urlpatterns = [ path('admin/', admin.site.urls), path('cc/', include('cc.urls')), path('quant/', include('quant.urls')), ]
odeke-em/restAssured
auth/urls.py
Python
mit
477
0.002096
from
django.conf.urls import patterns, include, url import views urlpatterns = patterns('', url(r'^logout', views.lo
gout, name='logout'), url(r'^newUser', views.newUser, name='newUser'), url(r'^appHandler', views.appHandler, name='appHandler'), url(r'^passToLogin', views.loginByPassword, name='passToLogin'), url(r'^signToLogin', views.loginBySignature, name='signToLogin'), url(r'^authUserHandler', views.authUserH...
caioariede/sorl-thumbnail
tests/thumbnail_tests/tests.py
Python
bsd-3-clause
29,267
0.001846
# coding=utf-8 from __future__ import unicode_literals, division import sys import logging from subprocess import Popen, PIPE import shutil import os import re from os.path import join as pjoin from PIL import Image
from django.utils.six import StringIO from django.core import management from django.core.files.storage import default_storage from django.template.loader import render_to_string from django.test.client import Client from django.test import TestCase from django.test.utils import override_settings from sorl.thumbnail ...
ail.engines.pil_engine import Engine as PILEngine from sorl.thumbnail.helpers import get_module_class, ThumbnailError from sorl.thumbnail.images import ImageFile from sorl.thumbnail.log import ThumbnailLogHandler from sorl.thumbnail.parsers import parse_crop, parse_geometry from sorl.thumbnail.templatetags.thumbnail im...
chromakey/django-salesforce
salesforce/backend/subselect.py
Python
mit
4,158
0.006013
import re from unittest import TestCase def mark_quoted_strings(sql): """Mark all quoted strings in the SOQL by '@' and get them as params, with respect to all escaped backslashes and quotes. """ pm_pattern = re.compile(r"'[^\\']*(?:\\[\\'][^\\']*)*'") bs_pattern = re.compile(r"\\([\\'])") out_...
re x=@", [''])) inner("a'bc'd", ("a@d", ['bc'])) inner(r"a'bc\\'d", ("a@d", ['bc\\'])) inner(r"a'\'\\'b''''", ("a@b@@", ['\'\\', '', ''])) self.assertRaises(AssertionError, mark_quoted_str
ings, r"a'bc'\\d") self.assertRaises(AssertionError, mark_quoted_strings, "a'bc''d")
mahabs/nitro
nssrc/com/citrix/netscaler/nitro/resource/config/appflow/appflowcollector.py
Python
apache-2.0
10,726
0.035614
# # Copyright (c) 2008-2015 Citrix Systems, Inc. # # Licensed under the Apache License, Version 2.0 (the "License") # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable l...
r except Exception as e : raise e def _get_object_name(self) : """ Returns the value of object identifier argument """ try
: if (self.name) : return str(self.name) return None except Exception as e : raise e @classmethod def add(cls, client, resource) : """ Use this API to add appflowcollector. """ try : if type(resource) is not list : addresource = appflowcollector() addresource.name = resource.name ...
ebt-hpc/cca
cca/scripts/outline_for_survey_fortran.py
Python
apache-2.0
29,483
0.005054
#!/usr/bin/env python3 ''' A script for outlining Fortran programs Copyright 2013-2018 RIKEN Copyright 2018-2020 Chiba Institute of Technology 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 Lice...
l = children_l[:-1] return children_l class Outline(OutlineBase):
def __init__(self, proj_id, commits=['HEAD'], method='odbc', pw=VIRTUOSO_PW, port=VIRTUOSO_PORT, gitrepo=GIT_REPO_BASE, proj_dir=PROJECTS_DIR, ver='unknown', simple_l...
bolozna/EDENetworks
netpython/dialogues.py
Python
gpl-2.0
64,787
0.029126
""" EDENetworks, a genetic network analyzer Copyright (C) 2011 Aalto University This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version...
stance measure has been used
?',bg='DarkOliveGreen2',anchor=W) self.c1.grid(row=0,column=0) r1=Radiobutton(masterwindow,text='Non-shared alleles',value='nsa',variable=masterclass.measuretype) r2=Radiobutton(masterwindow,text='Linear Manhattan',value='lm',variable=masterclass.measuretype) r3=Radiobutton(masterwindow...
figure002/pyrits
pyrits.py
Python
gpl-3.0
17,967
0.008404
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2011, De Verkeersonderneming <[email protected]> # # This file is part of PyRITS - A tool for processing and analyzing transport # management system data. # # PyRITS is free software: you can redistribute it and/or modify # it under the terms of...
dules: preprocess, drivetimes, delays and report. The usage information for each submodule can be viewed by running the command, ./pyrits.py <module> -h """ import sys import os import logging import argparse import psycopg2 import pyrits.config import pyrits.erniesoft.std import pyrits.erniesoft.report __auth...
onderneming" __credits__ = ["Serrano Pereira <[email protected]>"] __license__ = "GPL3" __version__ = "0.1.2" __maintainer__ = "Serrano Pereira" __email__ = "[email protected]" __status__ = "Production" __date__ = "2011/11/24" def get_connection(db): """Return a PostgreSQL database connection obje...
mpjoseca/ate
src/editor.py
Python
isc
5,579
0.032622
import wx import os.path class MainWindow( wx.Frame ): def __init__( self, filename = '*.txt' ): super( MainWindow, self ).__init__( None, size = ( 800,640 ) ) self.filename = filename self.dirname = '.' self.panel = wx.Panel( self, -1 ) self.CreateInteriorWindowComponents...
for id, label, helpText, handler in \ [( wx.ID_ABOUT, '&About', 'Information about this program', self.OnAbout )]: if id == None: aboutMenu.AppendSeparator() else: item = aboutMenu.Append( id, label, helpText ) self.Bi...
item ) menuBar = wx.MenuBar() menuBar.Append( fileMenu, '&File' ) # Add the fileMenu to the MenuBar menuBar.Append( editMenu, '&Edit' ) menuBar.Append( aboutMenu, '&About' ) self.SetMenuBar( menuBar ) # Add the menuBar to the Frame def SetTitle( self ): super( Mai...
hesseltuinhof/mxnet
python/mxnet/gluon/model_zoo/vision/inception.py
Python
apache-2.0
7,902
0.001519
# coding: utf-8 # pylint: disable= arguments-differ """Inception, implemented in Gluon.""" __all__ = ['Inception3', 'inception_v3'] from ....context import cpu from ...block import HybridBlock from ... import nn from ..custom_layers import HybridConcurrent # Helpers def _make_basic_conv(**kwargs): out = nn.Hybrid...
ion3(**kwargs) if pre
trained: from ..model_store import get_model_file net.load_params(get_model_file('inceptionv3'), ctx=ctx) return net
markuskont/kirka
algorithms/Frequent.py
Python
gpl-3.0
610
0.001639
#!/usr/bin/env python # coding: utf-8 class Frequent(): d
ef __init__(self): self.counters = {} def add(self, item, k, k2, t): if item in self.counters: counters[item] = counters[item] + 1 elif len(self.counters) <= k: self.counters[item] = 1 else: for key, value in self.counters.copy(
).items(): if value > 1: self.counters[key] = value - 1 else: del self.counters[key] return key def returnItems(self): return self.counters
WilliamDASILVA/TheMysteryOfSchweitzer
gameplay/behaviours/playerBehaviour.py
Python
mit
4,453
0.043342
from engine.Input import Keyboard; from engine import Update; from engine import Global; # --------------------------------------------------- *\ # Player behaviour # --------------------------------------------------- */ player = None; controlsEnabled = False; scale = Global.scale; # ------------------------------...
alking"); drawable = player.getAssignedDrawables()[0]; drawable.setFlip(False); else: isMoving = False; # change sprite state if(player): player.useSprite("static"); drawable = player.getAssignedDrawables()[0]; drawable.setFlip(False); # --------------------------------------------------...
# * Updating player's position * # Return : nil # --------------------------------------------------- */ def updatePosition(): if isMoving and player: if mouvementEnabled: position = player.getPosition(); size = player.getSize(); k = [position[0], position[1]]; # check for collisions with the scene b...
pangyemeng/myjob
pyspider/pyspider_mysql/pyspider/message_queue/kombu_queue.py
Python
gpl-2.0
3,271
0.000611
#!/usr/bin/env python # -*- encoding: utf-8 -*- # vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8: # Author: Binux<[email protected]> # http://binux.me # Created on 2015-05-22 20:54:01 import time import umsgpack from kombu import Connection, enable_insecure_serializers from kombu.serialization import register from k...
.Empty Full = BaseQueue.Full max_timeout = 0.3 def __init__(self, name, url="amqp://", maxsize=0, lazy_limit=True): """ Constructor for KombuQueue url: ht
tp://kombu.readthedocs.org/en/latest/userguide/connections.html#urls maxsize: an integer that sets the upperbound limit on the number of items that can be placed in the queue. """ self.name = name self.conn = Connection(url) self.queue = self.conn.SimpleQue...
mderomph-coolblue/dd-agent
checks.d/pgbouncer.py
Python
bsd-3-clause
7,003
0.002713
"""Pgbouncer check Collects metrics from the pgbouncer database. """ # 3p import psycopg2 as pg # project from checks import AgentCheck, CheckException class ShouldRestartException(Exception): pass class PgBouncer(AgentCheck): """Collects metrics from pgbouncer """ RATE = AgentCheck.rate GAUGE...
self.log.error("Connection error: %s" % str(e)) raise ShouldRestartExc
eption def _get_connection(self, key, host, port, user, password, use_cached=True): "Get and memoize connections to instances" if key in self.dbs and use_cached: return self.dbs[key] elif host != "" and user != "": try: if host == 'localhost' and pas...
trb/Multicache
backends/__init__.py
Python
bsd-2-clause
827
0.001209
import json class Cache(object): def __init__(self, backend): self.backend = backend def set(self, key, data): if type(data) is not str: data = ('json', json.dumps(data)) self.backend.store(key, data) def get(self, key): data = self.backend.retrieve(key) ...
if encoding != 'json': raise TypeError('No decoder found for encoding "{0}".' + ' Available decode
r: "json"'.format(encoding)) return json.loads(data) return data def has(self, key): return self.backend.check(key) def delete(self, key): self.backend.remove(key) def default(): import Local return Cache(Local.LocalBackend())
ryanpetrello/canary
canary/util.py
Python
bsd-3-clause
4,252
0
import os import re from wsgiref.util import guess_scheme import webob def cachedproperty(f): """returns a cached property that is calculated by function f""" def get(self): try: return self._property_cache[f] except AttributeError: self._property_cache = {} ...
y in ('wsgi.multiprocess', 'wsgi.multithread', 'wsgi.run_once')]) wsgi_vars['wsgi process'] = self.process_combos[proc_desc] return {'fields': data, 'filter_sensitive': self._filter_sensitive} @cachedpropert
y def sensitive_values(self): """ Returns a list of sensitive GET/POST values to filter from logs. """ values = set() params = webob.Request(self._environ).params for key in self._sensitive_keys: if key in params: values |= set([params[key]...
sysbot/pastedown
vendor/pygments/scripts/vim2pygments.py
Python
mit
26,283
0.00019
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Vim Colorscheme Converter ~~~~~~~~~~~~~~~~~~~~~~~~~ This script converts vim colorscheme files to valid pygments style classes meant for putting into modules. :copyright 2006 by Armin Ronacher. :license: BSD, see LICENSE for details. """ impor...
2': '#eed5b7', 'bisque3': '#cdb79e', 'bisque4': '#8b7d6b', 'black': '#000000', 'blanched': '#ffebcd', 'blanchedalmond': '#ffebcd', 'blue': '#8a2be2',
'blue1': '#0000ff', 'blue2': '#0000ee', 'blue3': '#0000cd', 'blue4': '#00008b', 'blueviolet': '#8a2be2', 'brown': '#a52a2a', 'brown1': '#ff4040', 'brown2': '#ee3b3b', 'brown3': '#cd3333', 'brown4': '#8b2323', 'burlywood': '#deb887', 'burlywood1': '#ffd39b', 'burlywoo...
remotesyssupport/cobbler-1
cobbler/config.py
Python
gpl-2.0
8,992
0.022464
""" Config.py is a repository of the Cobbler object model Copyright 2006-2009, Red Hat, Inc Michael DeHaan <[email protected]> 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 th...
pt: raise CX("serializer: error loading collection %s. Check /etc/cobbler/modules.conf" % item.collection_type()) return True def deserialize_raw(self,collection_type): """ Get obj
ect data from disk, not objects. """ return serializer.deserialize_raw(collection_type) def deserialize_item_raw(self,collection_type,obj_name): """ Get a raw single object. """ return serializer.de
Temesis/django-avatar
avatar/models.py
Python
bsd-3-clause
6,049
0.000331
import datetime import os from django.db import models from django.core.files.base import ContentFile from django.core.files.storage import get_storage_class from django.utils.translation import ugettext as _ from django.utils.hashcompat import md5_constructor from django.utils.encoding import smart_str from django.db...
atar.name, 'rb').read() image = Image.open(StringIO(orig)) quality = quality or AVATAR_THUMB_QUALITY (w, h) = image.size if w != siz
e or h != size: if w > h: diff = (w - h) / 2 image = image.crop((diff, 0, w - diff, h)) else: diff = (h - w) / 2 image = image.crop((0, diff, w, h - diff)) if image.mode != "RGB": ...
twaugh/docker-registry-client
tests/test_image.py
Python
apache-2.0
409
0
from __f
uture__ import absolute_import from docker_registry_client.Image import Image from docker_registry_client._BaseClient import BaseClientV1 from tests.mock_registry import mock_v1_registry class TestImage(object): def test_init(self): url = mock_v1_registry() image_id = 'test_image_id' imag...
googleapis/python-bigquery-datatransfer
samples/generated_samples/bigquerydatatransfer_v1_generated_data_transfer_service_get_data_source_sync.py
Python
apache-2.0
1,542
0.001946
# -*- 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...
tware # 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 GetDataSource # NOT...
dency, execute the following: # python3 -m pip install google-cloud-bigquery-datatransfer # [START bigquerydatatransfer_v1_generated_DataTransferService_GetDataSource_sync] from google.cloud import bigquery_datatransfer_v1 def sample_get_data_source(): # Create a client client = bigquery_datatransfer_v1.D...
MayankGo/ec2-api
ec2api/api/quota.py
Python
apache-2.0
2,313
0.003026
# Copyright 2014 # The Cloudscaling Group, 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...
f update_quota(context, account, resource, quota): account = account[4:] neutron = clients.neutron(context) with common.OnCrashCleaner() as cleaner: os_quota_body = { 'quota': { resource : quota, } ...
_format_quota_update(context, resource, os_quota)} def _format_quota_update(context, resource, os_quota): return { resource : os_quota[resource] } def show_quota(context, account): account = account[4:] neutron = clients.neutron(context) with common.OnCrashCleaner() as cleaner: ...
PaddlePaddle/Paddle
python/paddle/fluid/tests/unittests/seresnext_test_base.py
Python
apache-2.0
2,516
0
# Copyright (c) 2019 PaddlePaddle 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...
Type import numpy as np class TestResnetBase(Te
stParallelExecutorBase): def _compare_result_with_origin_model(self, check_func, use_device, delta2=1e-5, compare_seperately=True): if use_d...
zozo123/buildbot
master/contrib/coverage2text.py
Python
gpl-3.0
4,085
0.00049
#!/usr/bin/env python import sys from coverage import coverage from coverage.results import Numbers from coverage.summary import SummaryReporter from twisted.python import usage # this is an adaptation of the code behind "coverage report", modified to # display+sortby "lines uncovered", which (IMHO) is more importan...
+= "\n" if not outfile: outfile = sys.stdout # Write the header outfile.write(header1) outfile.write(header2) outfile.write(rule) total = Numbers()
total_uncovered = 0 lines = [] for cu in self.code_units: try: analysis = self.coverage._analyze(cu) nums = analysis.numbers uncovered = nums.n_statements - nums.n_executed total_uncovered += uncovered ar...
4thegr8just1ce/maze_py
main.py
Python
gpl-2.0
2,067
0.068347
import os import time maze = [[1,1,1,1,1,1,1,1,1,1,1], [1,0,0,0,0,0,1,0,0,0,1], [1,0,1,0,1,1,1,0,1,0,1], [1,0,1,0,1,0,0,0,1,0,1], [1,0,1,0,1,1,1,0,1,
1,1], [1,0,1,0,0,0,0,0,0,0,1], [1,0,1,0,1,1,1,0,1,0,1], [1,0,1,0,1,0,0,0,1,0,1], [1,1,1,0,1,0,1,1,1,0,1], [1,0,0,0,1,0,1,0,0,0,0,4], [1,1,1,1,1,1,1,1,1,1,1]] width = 11 height = 11 x = 1 y = 1 v = 0 def draw (maze): time.sleep(0.1) os.system('cls') for i in...
nue if (maze[i][j] == 0): print (" ", end="") elif (maze[i][j] == 1): print ("██", end="") elif (maze[i][j] == 4): print (" ", end="") print() step = 0 while maze[y][x]!= 4: draw(maze) if (v == 0)...
alandmoore/KiLauncher
kilauncher/__init__.py
Python
gpl-3.0
31
0
from
.app import KiLaunc
herApp
misaksen/umediaproxy
mediaproxy/headers.py
Python
gpl-2.0
3,161
0.002847
# Copyright (C) 2008 AG Projects # Author: Ruud K
laver <ruud@ag-projects
.com> # """Header encoding and decoding rules for communication between the dispatcher and relay components""" class EncodingError(Exception): pass class DecodingError(Exception): pass class MediaProxyHeaders(object): @classmethod def encode(cls, name, value): func_name = "encode_%s" % na...
caioserra/apiAdwords
examples/adspygoogle/adwords/v201309/reporting/get_report_fields.py
Python
apache-2.0
1,806
0.008306
#!/usr/bin/python # # Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
"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. """This example gets report fields. Tags: ReportDefinitionService.getReportFields """ __author__ = '[email protected] (K...
Winter)' import os import sys sys.path.insert(0, os.path.join('..', '..', '..', '..', '..')) # Import appropriate classes from the client library. from adspygoogle import AdWordsClient report_type = 'INSERT_REPORT_TYPE_HERE' def main(client, report_type): # Initialize appropriate service. report_definition_s...
TheWitchers/Team
TestingArea/Multithreading.py
Python
gpl-2.0
608
0
__author__ = 'dvir' import threading import random def Splitter(words): list = words.split() nlist = [] while (list): nlist.append(list.pop(random.randrange(0, len(list)))) print(' '.join(nlist)) if __name__ == '__main__': sen = 'Your god damn right.' numOfTreads = 5 threadList ...
args=(sen,)) t.start() threadList.append(t) print("\nTread Count: " + str(threading.activeCount())) print("EXIT
ING...\n")
bryansim/Python
piglow/clock.py
Python
gpl-2.0
3,562
0.011791
###################################### ## A binary clock using the PiGlow ## ## ## ## Example by Jason - @Boeeerb ## ###################################### from piglow import PiGlow from time import sleep from datetime import datetime piglow = PiGlow() ### You can customise th...
piglow.led(1,led01) led02 = ledbrightness if arm1[4] == "1" else 0 piglow.led(2,led02) led03 = ledbrightness if arm1[3] == "1" else 0 piglow.led(3,led03) led04 = ledbrightne
ss if arm1[2] == "1" else 0 piglow.led(4,led04) led05 = ledbrightness if arm1[1] == "1" else 0 piglow.led(5,led05) led06 = ledbrightness if arm1[0] == "1" else 0 piglow.led(6,led06) # Flash the white leds for the hour if hourcount != 0: sleep(0.5) if hourflash == 1: ...
qewerty/moto.old
tools/scons/engine/SCons/Node/Alias.py
Python
gpl-2.0
4,276
0.002105
"""scons.Node.Alias Alias nodes. This creates a hash of global Aliases (dummy targets). """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentat...
ublicense, 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 notic
e and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN N...
rjschwei/azure-sdk-for-python
azure-mgmt-servermanager/azure/mgmt/servermanager/models/prompt_message_response.py
Python
mit
856
0.001168
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
ior and will be lost if the code is # regenerated. # ---------------------------------------------------------------
----------- from msrest.serialization import Model class PromptMessageResponse(Model): """The response to a prompt message. :param response: The list of responses a cmdlet expects. :type response: list of str """ _attribute_map = { 'response': {'key': 'response', 'type': '[str]'}, ...
MBoustani/Geothon
Create Spatial File/Vector/create_shp_multipoint.py
Python
apache-2.0
1,696
0.008844
#!/usr/bin/env python ''' Project: Geothon (https://github.com/MBoustani/Geothon) File: Vector/create_shp_multipoint.py Description: This code creates points shapefile from some latitudes and longitues. Author: Maziyar Bous
tani (github.com/MBoustani) ''' import os try: import ogr except ImportError: from osgeo import ogr try: import osr except ImportError: from osgeo import osr latitudes = [30, 30, 30] longitudes = [10, 20, 30] shapefile = 'multipoints.shp' layer_name = 'multipoint_layer' #create ESRI shapefile dirve...
aSource(shapefile) #create spatial reference srs = osr.SpatialReference() #in this case wgs84 srs.ImportFromEPSG(4326) #create shapefile layer as points data with wgs84 as spatial reference layer = data_source.CreateLayer(layer_name, srs, ogr.wkbPoint) #create "Name" column for attribute table and set type as string...
XXMrHyde/android_external_chromium_org
build/android/pylib/instrumentation/test_jar.py
Python
bsd-3-clause
8,461
0.008037
# Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Helper class for instrumenation test jar.""" import collections import logging import os import pickle import re from pylib import cmd_helper from p...
ild it' % jar_path) sdk_root = os.getenv('ANDROID_SDK_ROOT', constants.ANDROID_SDK_ROOT) self._PROGUARD_PATH
= os.path.join(sdk_root, 'tools/proguard/bin/proguard.sh') if not os.path.exists(self._PROGUARD_PATH): self._PROGUARD_PATH = os.path.join(os.environ['ANDROID_BUILD_TOP'], 'external/proguard/bin/proguard.sh') self._jar_path = ...
garyphone/com_nets
visualization/enabled/_10010_project_visualization_panel.py
Python
mit
401
0.002494
# The slug of the panel to be added to HORIZON_CONFIG. Required. PANEL = 'visualization' # The slug of the dashboard the PANEL associated with. Required. PANEL_DASHBOARD = 'project'
# The slug of the panel group the PANEL is associated with. PANEL_GROUP = 'network' # Python panel class of the PANEL to be added. ADD_PANEL = 'openstack_dashboard
.dashboards.project.visualization.panel.Visualization'
Jc2k/libcloud
libcloud/storage/drivers/cloudfiles.py
Python
apache-2.0
35,768
0.00014
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use ...
ontent-Type' not in headers: headers.update({'Content-Type': 'application/json; charset=UTF-8'}) return super(CloudFilesConnection, self).request( action=action, params=params, data=data, method=method, headers=headers, raw=raw
) class CloudFilesSwiftConnection(CloudFilesConnection): """ Connection class for the Cloudfiles Swift endpoint. """ def __init__(self, *args, **kwargs): self.region_name = kwargs.pop('ex_region_name', None) super(CloudFilesSwiftConnection, self).__init__(*args, **kwargs) def get...
devs1991/test_edx_docmode
venv/lib/python2.7/site-packages/sklearn/decomposition/tests/test_dict_learning.py
Python
agpl-3.0
5,110
0.000587
import numpy as np from numpy.testing import assert_array_almost_equal, assert_array_equal, \ assert_equal from nose import SkipTest from nose.tools import assert_true from sklearn.utils.testing import assert_less from .. import DictionaryLearning, MiniBatchDictionaryLearning, SparseCoder, \...
2, axis=1)[:, np.newaxis] code = SparseCoder(dictionary=V,
transform_algorithm='lasso_lars', transform_alpha=0.001).transform(X) assert_true(not np.all(code == 0)) assert_less(np.sqrt(np.sum((np.dot(code, V) - X) ** 2)), 0.1)
ASMlover/study
python/py-interpreter/byterun/main.py
Python
bsd-2-clause
2,143
0.0014
#!/usr/bin/env python # -*- coding: UTF-8 -*- # # Copyright (c) 2016 ASMlover. 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...
h a bytecode interpreter.') parser.add_argument( '-m', dest='module', action='stroe_true', help='prog is a module name, not a file name') parser.add_argument( '-v', '--verbose', dest='verbose', action='stroe_true', help='trace the execution of the bytecode')
parser.add_argument('prog', help='the program to run') parser.add_argument( 'args', nargs=argparse.REMAINDER, help='arguments to pass to the program') return parser.parse_args() def main(): pass if __name__ == '__main__': main()
edx/edx-platform
common/lib/xmodule/xmodule/util/xmodule_django.py
Python
agpl-3.0
1,184
0.005068
""" Exposes Django utilities for consumption in the xmodule library NOTE: This file should only be im
ported into 'django-safe' code, i.e. known that this code runs int the Django runtime environment with the djangoapps in common configured to load """ import webpack_loader # NOTE: we are importing this method so that any module that imports us has access to get_current_request from crum import get_current_request ...
""" This method will return the hostname that was used in the current Django request """ hostname = None request = get_current_request() if request: hostname = request.META.get('HTTP_HOST') return hostname def add_webpack_to_fragment(fragment, bundle_name, extension=None, config='D...