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
borevitzlab/timestreamlib
tests/test_pipeline_yml.py
Python
gpl-3.0
3,863
0
# Copyright 2015 Joel Granados joel.granados@gmail.com # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This progra...
line import maincli from tests import helpers from tests.
helpers import ( FILES, PIPELINES_DIR, TMPDIR, ) class PipelineRunTestcase(TestCase): """Tests all example pipeline YAMLs under ./pipelines with run_pipeline""" def setUp(self): self.tmp_in = FILES["timestream_good_images"] self.tmp_out = path.join(TMPDIR, 'out') def _run_pip...
davidxmoody/kata
project-euler/completed/euler16.py
Python
mit
69
0.028986
#!/usr/bin/env python3
print(sum( (int(i) for i in str(2**10
00)) ))
Udzu/pudzu
photosets/averageflags.py
Python
mit
3,300
0.010606
from pudzu.charts import * from pudzu.sandbox.bamboo import * flags = pd.read_csv("../dataviz/datasets/countries.csv").filter_rows("organisations >> un").split_columns('country', "|").split_rows('country').set_index('country').drop_duplicates(subset='flag', keep='first') def flag_image(c): return Image.from_url_w...
continents]], padding=5, bg="white") continent_area.save("output/averageflags/continents_area.png") continent_density = Image.from_array([continentlabels, [average_flag(flags[flags.co
ntinent == continent], (600, 400), lambda df: df.population / df.area) for continent in continents]], padding=5, bg="white") continent_density.save("output/averageflags/continents_density.png")
Microno95/DESolver
desolver/__init__.py
Python
mit
446
0.004484
from . import backend from . import exception_types from .differential_system import DiffRHS, rhs_prettifier, OdeSystem from . import utilities from . import integrators from .integrators i
mport available_methods from . import tests from .utilities import tests from .exception_types import tests try: # Pytest testing from numpy._pytesttester import PytestT
ester test = PytestTester(__name__) del PytestTester except: pass
grzes/djangae
djangae/tests/test_connector.py
Python
bsd-3-clause
94,756
0.004232
import datetime import decimal import re import random import logging from cStringIO import StringIO from string import letters from hashlib import md5 from unittest import skipIf # LIBRARIES import django from django.conf import settings from django.core.files.uploadhandler import StopFutureHandlers from django.core...
models.CharField(max_length=32) class Meta: app_label = "djangae" class MultiTableChildOne(MultiTableParent): child_one_field = models.CharField(max_length=32) class Meta: app_label = "djangae" class MultiTableChildTwo(MultiTableParent): child_two_field = models.CharField(max_lengt...
class Relation(models.Model): class Meta: app_label = "djangae" class Related(models.Model): headline = models.CharField(max_length=500) relation = models.ForeignKey(Relation) class Meta: app_label = "djangae" class NullDate(models.Model): date = models.DateField(null=True, def...
Saviq/nova-compute-lxd
nclxd/tests/test_driver_api.py
Python
apache-2.0
28,337
0
# Copyright 2015 Canonical Ltd # 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...
i.API', mock.Mock(return_value=self.ml)) lxd_patcher.start() self.addCleanup(lxd_patcher.stop) self.connection = driver.LXDDriver(fake.FakeVirtAPI()) def test_capabilities(self): self.assertFalse(self.connection.capabilities['has_imagecache'])
self.assertFalse(self.connection.capabilities['supports_recreate']) self.assertFalse( self.connection.capabilities['supports_migrate_to_same_host']) def test_init_host(self): self.assertEqual( True, self.connection.init_host(None) ) def test_init...
sklam/numba
numba/tests/test_np_functions.py
Python
bsd-2-clause
123,601
0.000235
# Tests numpy methods of <class 'function'> import itertools import math import platform from functools import partial import numpy as np from numba.core.compiler import Flags from numba import jit, njit, typeof from numba.core import types from numba.typed import List, Dict from numba.np.numpy_support import numpy_...
in
creasing=False): return np.vander(x, N, increasing) def partition(a, kth): return np.partition(a, kth) def cov(m, y=None, rowvar=True, bias=False, ddof=None): return np.cov(m, y, rowvar, bias, ddof) def corrcoef(x, y=None, rowvar=True): return np.corrcoef(x, y, rowvar) def ediff1d(ary, to_end=No...
adrfer/swift
utils/SwiftBuildSupport.py
Python
apache-2.0
6,845
0.001753
# utils/SwiftBuildSupport.py - Utilities for Swift build scripts -*- python -*- # # This source file is part of the Swift.org open source project # # Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library Exception # # See http://swift.org/LICENSE.tx...
one if o == "mixin-preset": # Split on newlines and filter out empty lines. mixins = filter(None, [m.strip() for m in a.splitlines()]) for mixin in mixins: (base_build_script_opts, base_build_script_impl_opts, base_missi...
g_opts) = \ _get_preset_options_impl(config, substitutions, mixin) build_script_opts += base_build_script_opts build_script_impl_opts += base_build_script_impl_opts missing_opts += base_missing_opts elif o == "dash-dash": dash_dash_...
fake-name/ReadableWebProxy
WebMirror/management/rss_parser_funcs/feed_parse_extractWwwComegatranslationsCom.py
Python
bsd-3-clause
381
0.034121
def extra
ctWwwComegatranslationsCom(item): ''' Parser for 'www.comegatranslations.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['ti
tle'].lower(): return None if "WATTT" in item['tags']: return buildReleaseMessageWithType(item, "WATTT", vol, chp, frag=frag, postfix=postfix) return False
ramnes/qtile
test/widgets/test_df.py
Python
mit
3,460
0
# Copyright (c) 2021 elParaguayo # # 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, publish, distrib...
oftware, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The abo
ve copyright notice 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 NONIN...
o0neup/ibis
ibis/sql/compiler.py
Python
apache-2.0
27,343
0
# Copyright 2014 Cloudera 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...
self, expr): ctx = self.context node = expr.op() if isinstance(node, ops.Join): for arg in node.args: if not isinstance(arg, ir.TableExpr): continue self._make_table_aliases(arg) else: if not ctx.is_extracted(exp...
-------------------------- # Expr analysis / rewrites def _analyze_select_exprs(self): new_select_set = [] for expr in self.select_set: new_expr = self._visit_select_expr(expr) new_select_set.append(new_expr) self.select_set = new_select_set def _visit_sel...
kivy/python-for-android
pythonforandroid/recipes/sqlite3/__init__.py
Python
mit
1,251
0.001599
from pythonforandroid.recipe import NDKRecipe from pythonforandroid.toolchain import shutil from os.path import join import sh class Sqlite3Recipe(NDKRecipe): version = '3.35.5' # Don't forget to change the URL when changing the version url = 'https://www.sqlite.org/2021/sqlite-amalgamation-3350500.zip' ...
oid.mk')) def build_arch(self, arch, *extra_args): super().build_arch(arch) #
Copy the shared library shutil.copyfile(join(self.get_build_dir(arch.arch), 'libs', arch.arch, 'libsqlite3.so'), join(self.ctx.get_libs_dir(arch.arch), 'libsqlite3.so')) def get_recipe_env(self, arch): env = super().get_recipe_env(arch) env['NDK_PROJECT_PATH'] = sel...
DrOctogon/appscake-rewrite
appscake/views.py
Python
bsd-3-clause
1,604
0.016209
import logging from appscake import helpers from django.shortcuts import render from django.shortcuts import render_to_response from appscake.forms import CommonFields from django.http import HttpResponse from django.http import HttpResponseRedirect # When deploying on virtual machines without IaaS support. CLUSTER_...
['ips_yaml'] if not form.is_valid(): return HttpResponseRedirect('/start/?error=badform') # Redirect after POST # Fire it off in a thread and then r
edirect to a page that polls. else: return render(request, 'base/start.html')
nilskingston/Hello-world
helloworld.py
Python
mit
170
0
""" helloworld.py Author: Nils Kingston Credit: none Assignment: Write and submit a Python program that prints the fo
llo
wing: Hello, world! """ print("Hello, world!")
bru32/magz
magz/umath.py
Python
mit
3,528
0.03288
""" Math Utils. Bruce Wernick 10 June 2021 """ import math import sys __all__ = ['showvec', 'makemat', 'makevec', 'MAX', 'MIN', 'SIGN', 'SQR', 'pythag', 'is_number', 'odd', 'sum_inv', 'is_close', 'max2', 'liststat', 'ave', 'sum_inv'] # --------------------------------------------------------------...
o, t, ave, a[n//2] def ave(a): "average of list" return sum(a) / float(len(a)) # --------------------------------------------------------------------- def minfunc(f,*a): "return inner function" def inner_func(x): return f(x,*a) return inner_func
def maxfunc(f,*a): "return inner function" def inner_func(x): return 0.0-f(x,*a) # negative for max return inner_func def golden(f, a, b, tol=1e-3): "golden section search for minimum" G = 0.5*(1.0 + math.sqrt(5.0)) e = (b-a)/G c, d = b-e, a+e while abs(c-d) > tol: if f(c) < f(d): ...
bertjwregeer/alexandria
alexandria/models/__init__.py
Python
isc
1,257
0.002387
from sqlalchemy.orm import sessionmaker as sqla_sessionmaker from sqlalchemy import engine_from_config import zope.sqlalchemy import transaction from .meta import Base from .user import ( User, UserTickets, ) from .domain import Domain from .record import Record from .types import ( ...
lambda
r: get_dbsession(r, sessionmaker), 'dbsession', reify=True, ) # Include the transaction manager if 'tm.manager_hook' not in settings: config.add_settings({ 'tm.manager_hook': lambda _: transaction.TransactionManager(), }) config.i...
whittlbc/jarvis
jarvis/learn/classify/data_prepper.py
Python
mit
960
0.039583
import numpy as np impo
rt jarvis.helpers.helpers as helpers from data_cleaner import DataCleaner def get_data(csv=None, sep='|'): dataset = create_dataset(csv, sep) inputs = DataCleaner().clean(dataset[:, 0:1]) outputs = format_targets(dataset[:, 1]) train_data, test_data = inputs[::2], inputs[1::2] train_targets, test_targets = o...
ta, train_targets), (test_data, test_targets)] def create_dataset(csv, sep): if csv: return helpers.read_csv(csv, sep=sep).values else: data = [] for f in helpers.csvs(): for row in helpers.read_csv(f, sep=sep).values: data.append(list(row)) return np.array(data) def format_targets(target_li...
gfunkmonk2/mate-games
glchess/src/lib/ggz/chess.py
Python
gpl-2.0
5,544
0.007937
# -*- coding: utf-8 -*- import struct class GGZChessFeedback: def onSeat(self, seatNum, version): pass def onPlayers(self, whiteType, whiteName, blackType, blackName): pass def onClockRequest(self): pass def onClock(self, mode, sec...
KeyError: self.decodeMethod = None print 'Unknown data received: %s' % repr(char) return self.command = '' self.command += char self.decodeMethod() def getGGZ
String(self, buffer): if len(buffer) < 4: return (None, 0) (length,) = struct.unpack("!I", buffer[:4]) if len(buffer) < length + 4: return (None, 0) string = buffer[4:length + 4] # Strip C null characters while string.endswith('\x...
romanchyla/pylucene-trunk
test/test_PerFieldAnalyzerWrapper.py
Python
apache-2.0
1,917
0.002087
# ==================================================================== # 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 re...
ting, software # distribut
ed 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. # ==================================================================== from un...
danjamker/DiffusionSimulation
LinearRegression.py
Python
mit
12,302
0.007316
from __future__ import division try: from BytesIO import BytesIO except ImportError: from io import BytesIO try: from urlparse import urlparse except ImportError: from urllib.parse import urlparse import pandas as pd from mrjob.job import MRJob from mrjob.protocol import JSONValueProtocol from mrjob...
), str(pval)]) def steps(self): return [MRStep( mapper=self.mapper, reducer=self.reducer )] def generate_tables(self, df): result_user = df.dr
op_duplicates(subset='number_activated_users', keep='first').set_index( ['number_activated_users'], verify_integrity=True, drop=False).sort_index() result_user["surface_mean"] = result_user["surface"].expanding(min_periods=1).mean() result_user["surface_cv"] = result_user["surface"].expandi...
accdias/dotfiles
vim/pythonx/lints/cpp.py
Python
artistic-2.0
611
0
# -*- coding: utf-8 -*- from validator import Validator class Cpp(Validato
r): __filetype__ = "cpp" checker = "clang-tidy" binary_option = "clang_tidy" args_file = ".clang-tidy-config" regex = r""" .+: (?P<lnum>\d+): (?P<col>\d+): .* \s
( (?P<error>error) | (?P<warning>warning) ): \s (?P<text>.*)""" def cmd(self, fname): return "{} {} -- {}".format( self.binary, fname, self.parse_arguments(self.args_file))
noplay/gns3-gui
gns3/modules/qemu/pages/qemu_vm_preferences_page.py
Python
gpl-3.0
13,713
0.002188
# -*- coding: utf-8 -*- # # Copyright (C) 2014 GNS3 Technologies Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. ...
em(section_item, ["Disk image (hdd):", qemu_vm["hdd_disk_image"]]) # fill out the Network section section_item = self._createSectionItem("Network") QtGui.QTreeWidgetItem(section_item, ["Adapters:", str(qemu_vm["adapters"])]) QtGui.QTreeWidgetItem(section_item, ["Type:", qemu_vm["adapter...
ctionItem("Linux boot") if qemu_vm["initrd"]: QtGui.QTreeWidgetItem(section_item, ["Initial RAM disk:", qemu_vm["initrd"]]) if qemu_vm["kernel_image"]: QtGui.QTreeWidgetItem(section_item, ["Kernel image:", qemu_vm["kernel_image"]]) if qemu_vm["kernel_c...
jckuester/droidtracer-module
src/main/jni/libnl-3.2.22/python/netlink/route/address.py
Python
gpl-2.0
11,028
0.000997
# # Copyright (c) 2011 Thomas Graf <tgraf@suug.ch> # """Module providing access to network addresses """ from __future__ import absolute_import __version__ = '1.0' __all__ = [ 'AddressCache', 'Address'] import datetime from .. import core as netlink from . import capi as capi from . import link as Link f...
type=int, fmt=util.num) def scope(self): """Address scope""" scope = capi.rtnl_addr_get_scope(self._rtnl_addr) return capi.rtnl_scope2str(scope, 32)[0] @scope.setter def scope(self, value): if type(value) is str: value = capi.rtnl_str2scope(value) capi.rt...
@property @netlink.nlattr(type=str, immutable=True, fmt=util.addr) def local(self): """Local address""" a = capi.rtnl_addr_get_local(self._rtnl_addr) return netlink.AbstractAddress(a) @local.setter def local(self, value): a = netlink.AbstractAddress(value) capi.r...
smallyear/linuxLearn
salt/salt/modules/stormpath.py
Python
apache-2.0
5,811
0.00086
# -*- coding: utf-8 -*- ''' Support for Stormpath .. versionadded:: 2015.8.0 ''' # Import python libs from __future__ import absolute_import, print_function import json import logging # Import salt libs import salt.utils.http log = logging.getLogger(__name__) def __virtual__(): ''' Only load the module if...
tmein Shemp Howard ''' items = { 'email': email, 'password': password, 'givenName': givenName, 'surname': surname, } items.update(**kwargs) status, result = _query( action='directories', command='{0}/accounts'.format(directory_id), data=json....
result['href'].split('/') return show_account(comps[-1]) def list_accounts(): ''' Show all accounts. CLI Example: salt myminion stormpath.list_accounts ''' status, result = _query(action='accounts', command='current') return result def show_account(account_id=None, ...
alexlo03/ansible
lib/ansible/plugins/action/nxos_config.py
Python
gpl-3.0
4,248
0.000706
# # Copyright 2015 Peter Sprygada <psprygada@ansible.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any...
hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://ww...
n.nxos import ActionModule as _ActionModule from ansible.module_utils._text import to_text from ansible.module_utils.six.moves.urllib.parse import urlsplit from ansible.utils.vars import merge_hash PRIVATE_KEYS_RE = re.compile('__.+__') class ActionModule(_ActionModule): def run(self, tmp=None, task_vars=None):...
wnavarre/email-dictator
web/run_on.py
Python
mit
1,802
0.00444
import sys import os import files.io from StringIO import StringIO from constants import * added_path = os.path.join(os.path.dirname(os.path.abspath(os.path.dirname(__file__))), "script") sys.path.append(added_path) import script import mess sys.path.pop() def full_file(pointer): pointer.seek(0) return pointe...
t" output_location = StringIO() kwargs = {} if send_default_confirmation: pass else: kwargs["send_confirmation_to"] = None if "constants" in input_files: kwargs["constants"] = StringIO(input_files["constants"]) success = script.run_script( StringIO(input_files["te...
output=output_location, actually_send=actually_send, **kwargs ) script_results = special_text + full_file(output_location) if confirmation_email and ((confirmation_email_on_success and success) or (confirmation_email_on_fail and not success)): send_confirmation_email(confirm...
jfunez/scielo-manager
scielomanager/accounts/urls.py
Python
bsd-2-clause
1,917
0.000522
# -*- encoding: utf-8 -*- from django.conf.urls.defaults import * from django.contrib.auth import views as auth_views from django.conf import settings from django.views.generic.base import TemplateView from . import views urlpatterns = patterns('', url(r'^logout/$', auth_views.logout, {'next_page...
count, name='journalmanager.my_account'), url(r'^myaccount/password/$', views.password_change, name='journalmanager.password_change'), url(r'^unauthorized/$', views.unauthorized, name='accounts.u
nauthorized'), )
michael-robbins/jobqueue_frontend
frontend/urls.py
Python
gpl-2.0
2,971
0.006059
from frontend import views from rest_framework import routers from django.conf.urls import patterns, url, include router = routers.DefaultRouter() router.register(r'categories', views.CategoryViewSet) router.register(r'packages', views.PackageViewSet) router.register(r'files', views.FileViewSet) router.register(r'clie...
jobs/add/$', views.job_add, name='job_add'),
url(r'^jobs/history/$', views.job_history, name='job_history'), url(r'^jobs/(?P<job_id>\d+)/$', views.job_view, name='job_view'), url(r'^jobs/(?P<job_id>\d+)/delete/$', views.job_delete, name='job_delete'), url(r'api/', include(router.urls...
pandastrail/InfoEng
scripting/exercises/p06_requests_web_files.py
Python
gpl-3.0
1,645
0.006079
# -*- coding: utf-8 -*- """ Created on Tue Sep 26 14:42:10 2017 @author: ksagilop Use requests modules to retrieve info from website and download files A nice tutorial: https://gist.github.com/phillipsm/0ed98b2585f0ada5a769 TODO: List of books available TODO: Merge this function with Gender Detection script TODO: A...
able.table tr'): cells = table_row.findAll('td') if len(cells) > 0: books = cells[1] #print(books) return lib.text def lease(book): '''Construct a list of available books to
download''' res = requests.get(book) # Requests a response from the url 'book' res.raise_for_status() # Check call success print(type(res)) print(len(res.text)) print(res.text[:300]) return res.text # Execute #lease(book_example) #library(url) lib = requests.get(url) lib.raise_for_stat...
theodesp/aspoonfulofhome
theoliveoilbakers/settings/base.py
Python
mit
6,232
0.001123
""" Django settings for theoliveoilbakers project. 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/ """ import sys from os.path import abspath, dirname, join from django...
locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'wagta...
lbakers.urls' WSGI_APPLICATION = 'theoliveoilbakers.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases if 'test' in sys.argv or 'test_coverage' in sys.argv: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3' } } else: DAT...
Paulloz/godot
core/make_binders.py
Python
mit
12,675
0.01641
# -*- coding: ibm850 -*- template_typed = """ #ifdef TYPED_METHOD_BIND template<class T $ifret ,class R$ $ifargs ,$ $arg, class P@$> class MethodBind$argc$$ifret R$$ifconst C$ : public MethodBind { public: $ifret R$ $ifnoret void$ (T::*method)($arg, P@$) $ifconst const$; #ifdef DEBUG_METHODS_ENABLED virtual Variant...
argument=get_argument_count(); return Variant(); } if (p_arg_count<(get_argument_count()-get_default_argument_count())) { r_error.error=Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; r_error.argument=get_argument_count()-get_default_argument_count(); return Variant()
; } $arg CHECK_ARG(@); $ #endif $ifret Variant ret = $(instance->*method)($arg, _VC(@)$); $ifret return Variant(ret);$ $ifnoret return Variant();$ } #ifdef PTRCALL_ENABLED virtual void ptrcall(Object*p_object,const void** p_args,void *r_ret) { __UnexistingClass *instance = (__UnexistingClass*)p_object;...
serl/topoblocktest
lib/topologies.py
Python
mit
8,613
0.00476
from .topology import Master, OVS, Netns, Link from collections import OrderedDict def direct_veth(disable_offloading=False, **settings): m = Master() ns1 = Netns('x-ns1').add_to(m) ns2 = Netns('x-ns2').add_to(m) Link.declare((ns1, '10.112.1.1'), (ns2, '10.112.1.2'), disable_offloading=disable_offlo...
n_qdisc_netem(disable_offl
oading=False, **settings): return ns_chain_qdisc('netem', False, disable_offloading, **settings) ns_chain_qdisc_netem.arguments = ns_chain.arguments.copy() def ns_chain_qdisc_htb(disable_offloading=False, **settings): return ns_chain_qdisc('htb', False, disable_offloading, **settings) ns_chain_qdisc_htb.argum
eduNEXT/edunext-platform
cms/djangoapps/contentstore/tests/test_tasks.py
Python
agpl-3.0
6,906
0.002317
""" Unit tests for course import and export Celery tasks """ import copy import json from unittest import mock from uuid import uuid4 from django.conf import settings from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user from django.test.utils import override_settings from o...
er = self.create_non_staff_authed_user_client() key = str(self.course.location.course_key) result = export_olx.delay(nonstaff_user.id, key, 'en') self._assert_failed(result, 'Permission denied') def _assert_failed(self, task_result, error_message): """ Ver
ify that a task failed with the specified error message """ status = UserTaskStatus.objects.get(task_id=task_result.id) self.assertEqual(status.state, UserTaskStatus.FAILED) artifacts = UserTaskArtifact.objects.filter(status=status) self.assertEqual(len(artifacts), 1) err...
Letractively/aha-gae
applications/aha.application.coreblog3/application/config.py
Python
bsd-3-clause
2,782
0.008267
# -*- coding: utf-8 -*- import logging import os def check_for_spartphone(request): """ A function to check if user agent is smartphone or not. """ ua = request.headers.get('User-Agent', '').lower() go = False for i in ['iphone', 'ipad', 'android']: if i in ua: return True return F...
from aha.controller.decorator import cache cache.set_namespace_func(cache_namespace) config = aha.Config() # initialize route and the installed plugins from aha.dispatch
.router import get_router, get_fallback_router # initialize router with default rule. r = get_router() # setting up well known config attributes config.initial_user = ['test@example.com', 'shib.ats@gmail.com', 'ats'] config.site_root = 'http://coreblog.org' config.error_template = '/common/erro...
aaruni96/misc
distance.py
Python
gpl-2.0
379
0.013193
import urllib.request import json origin = input("Origin\n") destination = input("Destination\n") urllib.request.urlretrieve("https://maps.googleapis.com/maps/api/distancemat
rix/json?units=imperial&origins="+origin+"&destinations="+destination,"abc.json") data=json.l
oad(open("abc.json")) distance=data["rows"][0]["elements"][0]["distance"]["value"]/1000.0 print(distance,'km')
eseidel/native_client_patches
tests/file/run.py
Python
bsd-3-clause
2,598
0.008083
#!/usr/bin/python #!/usr/bin/python # Copyright 2008, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notic...
istribution. # * Neither the name of Google Inc. nor the names o
f its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERC...
hdoria/HnTool
HnTool/core.py
Python
gpl-2.0
9,011
0.00688
#! /usr/bin/env python # -*- coding: utf-8 -*- # # HnTool - A hardening tool for Linux/BSD # Copyright (C) 2009-2010 Authors # Authors: # * Hugo Doria <mail at hugodoria dot org> # * Aurelio A. Heckert <aurium at gmail dot com> # # This program is free software; you can redistribute it and/or modify # it under ...
_)
- set(self.options.exclude_list.split(','))) elif self.options.modules_list: # if we just want to run specific modules modules_list = self.options.modules_list.split(',') else: # gets all the modules modules_list = HnTool.modules.__all__ ...
josuemontano/python_intro
tema_6/Leccion_6.py
Python
gpl-3.0
762
0.003953
# -*- coding: utf-8 -*- # C
onexión a bases de datos # Lección 6 # SQLAlchemy: Estados de una
entidad from Leccion_1 import Libro from Leccion_2 import session from sqlalchemy import inspect def mostrar_estado(objeto): estado = inspect(objeto) print('Transient: {0}; Pending: {1}; Persistent: {2}; Detached: {3}'.format(estado.transient, estado.pending, estado.persistent, estado.detached)) def main(...
JoshuaSkelly/lunch-break-rl
utils.py
Python
mit
1,404
0.000712
from math import sqrt def cp437(string): """Converts utf8 to codepage 437""" return ''.join([chr(ord(c.encode('cp437'))) for c in string]) def rect(x, y, width, height): result = [] for i in range(width):
for j in range(height): re
sult.append((i + x, j + y)) return result def is_next_to(e1, e2): """Returns true if the given entities are positioned next to each other. e1: An entity e2: An entity Returns True if they are orthogonally adjacent """ if not e1 or not e2: return False dx, dy = math.sub(e1....
jreback/pandas
asv_bench/benchmarks/tslibs/resolution.py
Python
bsd-3-clause
1,414
0.000707
""" ipython analogue: tr = TimeResolution() mi = pd.MultiIndex.from_product(tr.params[:-1] + ([str(x) for x in tr.params[-1]],)) df = pd.DataFrame(np.nan, index=mi, columns=["mean", "stdev"]) for unit in tr.params[0]: for size in tr.params[1]: for tz in tr.params[2]: tr.setup(unit, size, tz) ...
.tslibs import get_resolution except ImportError: from pandas._libs.tslibs.resolution import get_reso
lution class TimeResolution: params = ( ["D", "h", "m", "s", "us", "ns"], [1, 100, 10 ** 4, 10 ** 6], [ None, timezone.utc, timezone(timedelta(minutes=60)), pytz.timezone("US/Pacific"), gettz("Asia/Tokyo"), tzlocal(), ...
PyCQA/pylint
tests/functional/ext/docparams/yield/missing_yield_doc.py
Python
gpl-2.0
307
0.006515
"""Tests for missing-yield-doc and missing-yield-type-doc""" # pylint: disable=missing-function-docstring, unused-argument, function-redefined # Ignore no docstring def my_func(self): yield False # Ignore unrecognized style docstring def my_func(self): """This is a docstring.""" yield
False
dentaku65/plugin.video.pelisalacarta.it
servers/rapidvideo.py
Python
gpl-3.0
2,858
0.030102
# -*- coding: iso-8859-1 -*- #------------------------------------------------------------ # pelisalacarta - XBMC Plugin # Conector para rapidvideo # http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/ #------------------------------------------------------------ import urllib,re from core import scrapertools from...
rapertools.cache_page( url ).replace( 'TMPL_VAR|', '' ) data = scr
apertools.cache_page( url ) packed = scrapertools.get_match( data, "<script type='text/javascript'>eval.function.p,a,c,k,e,.*?</script>" ) unpacked = packer.unpack( packed ) media_url = scrapertools.get_match( unpacked, 'file:"([^"]+)"' ) video_urls = [] video_urls.append( [ scrapertools.get_filen...
Psybernetics/Synchrony
synchrony/resources/privs.py
Python
mit
871
0.002296
import flask_restful as restful from sqlalchemy import and_, desc from flask import request, session from synchrony import app, db, log from synchrony.models import Priv from synchrony.controllers.auth import auth from synchrony.controllers.utils import make_response class PrivCollection(restful.Resource): def get...
t("page", type=int, required=False, default=1) parser.add_argument("per_page", type=int, required=False, default=10) args = parser.parse_args() user = auth(session, required=True) if not user.can("see_all"): return {}, 403 query = Priv.query.order_by(desc(Priv....
eated)).paginate(args.page, args.per_page) return make_response(request.url, query)
hlzz/dotfiles
graphics/VTK-7.0.0/ThirdParty/Twisted/twisted/names/test/test_tap.py
Python
bsd-3-clause
3,955
0.00177
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for L{twisted.names.tap}. """ from twisted.trial.unittest import TestCase from twisted.python.usage import UsageError from twisted.names.tap import Options, _buildResolvers from twisted.names.dns import PORT from twisted.name...
rs(options) # Extra cleanup, necessary on POSIX because client.Resolver doesn't know # when to stop parsing resolv.conf. See #NNN for improving this. for x in cl: if isinstance(x, ResolverChain): recurser = x.resolvers[-1] if isinstance(recu
rser, Resolver): recurser._parseCall.cancel() self.assertIsInstance(cl[-1], ResolverChain)
hellohaptik/chatbot_ner
ner_v2/detectors/pattern/phone_number/phone_number_detection.py
Python
gpl-3.0
6,667
0.003678
# -*- coding: utf-8 -*- from __future__ import absolute_import import re try: import regex _regex_available = True except ImportError: _regex_available = False import phonenumbers from six.moves import zip from language_utilities.constant import ENGLISH_LANG from ner_v2.detectors.base_detector import B...
o send specific arguments in future. Returns: self.phone (list): list consisting the detected phone numbers and their country calling codes self.original_phone_text (list): list containing their corresponding substrings in the original message. Examples: text = 'call ...
de':'1', value':'4089126172'} ], [u'+1 (408) 912-6172']) text = '+९१ ९८१९९८३१३२ पर कॉल करें और संदेश ९८२०३३४४१६ पर कॉल करें' p = PhoneDetector(entity_name='phone_number', language='hi', locale='en-IN') p.detect_entity(text=text) ([{'country_calling_code':'91', value':'981998313...
adazey/Muzez
libs/nltk/tag/perceptron.py
Python
gpl-3.0
11,552
0.004761
# -*- coding: utf-8 -*- # This module is a port of the Textblob Averaged Perceptron Tagger # Author: Matthew Honnibal <honnibal+gh@gmail.com>, # Long Duong <longdt219@gmail.com> (NLTK port) # URL: <https://github.com/sloria/textblob-aptagger> # <http://nltk.org/> # Copyright 2013 Matthew Honnibal #...
er.pickle" class AveragedPerceptron(object): '''An averaged perceptron, as imp
lemented by Matthew Honnibal. See more implementation details here: http://spacy.io/blog/part-of-speech-POS-tagger-in-python/ ''' def __init__(self): # Each feature gets its own weight vector, so weights is a dict-of-dicts self.weights = {} self.classes = set() ...
dpm76/eaglebone
drone/flight/stabilization/state.py
Python
isc
315
0.009524
# -*- coding: utf-8 -*- ''' Created on 23 de feb. de 2016 @au
thor: david ''' class SensorState(object): ''' Sensor's state ''' def __init__(self): ''' Constructor
''' self.accels = [0.0]*3 self.angleSpeeds = [0.0]*3 self.angles = [0.0]*3
kiyukuta/chainer
chainer/functions/math/sum.py
Python
mit
2,814
0
from chainer import cuda from chainer import function from chainer.utils import type_check class Sum(function.Function): """Sum of array elements over a given axis.""" keepdims = False def __init__(self, axis=None, keepdims=False): if axis is None: self.axis = None elif isins...
n_shape = x[0].shape self._in_dtype = x[0].dtype self._xp = cuda.get_array_module(*x) return self._xp.asarray( x[0].sum(axis=self.axis, keepdims=self.keepdims)), def backward(self, x, gy): xp = self._xp gy = gy[0] if not (len(self._in_shape) == 0 or ...
xis += len(self._in_shape) actual_axis.append(axis) for axis in sorted(actual_axis): gy = xp.expand_dims(gy, axis=axis) if hasattr(xp, 'broadcast_to'): gx = xp.broadcast_to(gy, self._in_shape) else: # NumPy 1.9 does not support broadcas...
supervacuo/pinry
pinry/core/feeds.py
Python
bsd-2-clause
4,918
0.001017
from __future__ import unicode_literals from django.contrib.syndication.views import Feed from django.contrib.sites.models import get_current_site from django.shortcuts import get_object_or_404 from django.contrib.auth.models import User from django_images.models import Thumbnail from taggit.models import Tag from ....
pins from around the internet.' domain_name = None item_enclosure_mime_type = 'image/jpeg' def get_object(self, request, tag): """ Doing this as a fix for Django's not incl
uding the domain name in enclosure urls. """ request_type = 'http' if request.is_secure(): request_type = 'https' self.domain_name = ''.join([request_type, '://', get_current_site(request).domain]) return get_object_or_404(Tag, name=tag...
UNINETT/nav
python/nav/smsd/dispatcher.py
Python
gpl-2.0
10,103
0
# -*- coding: utf-8 -*- # # Copyright (C) 2006-2009 Uninett AS # # This file is part of Network Administration Visualized (NAV). # # NAV is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License version 3 as published by # the Free Software Foundation. # # This progr...
dule object. """ mod = __import__(name) components = name.split('.') for comp in components[1:]: mod = getattr(mod, comp) return mod def sendsms(self, phone, msgs): ""
" Formats and sends with help of the wanted dispatcher. :param phone: the phone number the messages are to be dispatched to. :param msgs: a list of messages ordered with the most severe first. Each message is a tuple with ID, text and severity of the me...
Jumpscale/jumpscale_core8
lib/JumpScale/tools/perftesttools/Disk.py
Python
apache-2.0
2,097
0.002384
from JumpScale import j class Disk: def __init__(self, devname, node=None, disknr=None, screenname=None): devname.replace("//", "/") self.devname = devname self.devnameshort = self.devname.split("/")[2] self.mounted = False self.mountpath = None self.node = node ...
Mount(): raise j.exceptions.RuntimeError("could not mount %s" % self) print("init %s:%s done" % (fs, self)) def initDi
skXFS(self): self.initDisk(fs='xfs') def initDiskBTRFS(self): self.initDisk(fs='btrfs') def mount(self): print("mount:%s mounting %s on %s " % (self, self.devname, self.disknr)) if self.mountpath is None: self.mountpath = '/storage/%s' % self.disknr self.nod...
allenm/sync-hosts
server/tools/install.py
Python
apache-2.0
955
0.020942
#!/usr/bin/env python # -*- coding: utf-8 -*- # author allenm < http://blog.allenm.me > # date 2012-5-23 # import os import sys import sqlite3 def createDB( clean ): path = os.path.dirname(__file__) dbfile = path + "/../libs/hosts.db" if( clean is True ): os.remove( dbfile ) conn = sq...
TEGER DEFAULT 1 )''') c.execute('''CREATE TABLE if not exists workspace( id INTEGER PRIMARY KEY AUTOINCREMENT , hosts TEXT, status INTEGER DEFAULT 1)''') conn.commit() c.close() conn.close() if __name__ == "__main
__": if len( sys.argv ) > 1 and sys.argv[1] == "--clean": createDB( True ) else: createDB( False )
wilsonkichoi/zipline
tests/test_benchmark.py
Python
apache-2.0
6,927
0
# # Copyright 2015 Quantopian, 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 wr...
)[2].pct_change() for idx, day in enumerate(days_to_use[1:]): self.assertEqual( source.get_value(day), manually
_calculated[idx + 1] ) def test_no_stock_dividends_allowed(self): # try to use sid(4) as benchmark, should blow up due to the presence # of a stock dividend with self.assertRaises(InvalidBenchmarkAsset) as exc: BenchmarkSource( 4, self.env, self....
PisiLinux-PyQt5Port/package-manager
src/packagedelegate.py
Python
gpl-2.0
17,880
0.00481
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2009-2010, TUBITAK/UEKAE # # 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 ...
nstalled Version:")} self._titleFM = {} for key, value in self._titles.items(): self._titleFM[key] = self.boldDetailFontFM.width(value) + ICON_SIZE + 3 self.baseWidth = self.boldFontFM.width(max(self._titles.values(), key=len)) + ICON_SIZE self.parent = parent.packageList ...
tant features # self.plastik = QStyleFactory.create('plastique') def paint(self, painter, option, index): if not index.isValid(): return super(PackageDelegate, self).paint(painter, option, index) if index.flags() & Qt.ItemIsUserCheckable: if index.column() == 0: ...
GhostTV/plugin.video.mykodibuildwizard
default.py
Python
gpl-3.0
8,951
0.025249
import xbmc, xbmcaddon, xbmcgui, xbmcplugin,os,sys import shutil import urllib2,urllib import re import extract import time import downloader import plugintools import zipfile import ntpath USER_AGENT = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3' base='' ADDON=xbmcaddo...
") print '=======================================' print addonfolder print '=======================================' extract.all(lib,addonfolder,dp) dialog = xbmcgui.Dialo
g() dialog.ok("DOWNLOAD COMPLETE", 'Unfortunately the only way to get the new changes to stick is', 'to force close kodi. Click ok to force Kodi to close,', 'DO NOT use the quit/exit options in Kodi., If the Force close does not close for some reason please Restart Device or kill task manaully') killxbmc() ...
ehua7365/RibbonOperators
TEBD/mpstest7.py
Python
mit
5,808
0.025654
""" mpstest7.py A test of manipulating matrix product states with numpy. 2014-08-25 """ import numpy as np import matplotlib.pyplot as plt from cmath import * from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm def main(): test3() def test3(): """ Test MPS conversion functions by computing fide...
p.tensordot(c,A[i],axes=(-1,0)) c = np.trace(c,axis1=0,axis2=-1) return np.reshape(c,d**N) def getMPS(state,chi): """ MPS of a state.""" d = 2 # Qubits have 2 states each N = int(np.log2(len(state)
)) # Number of qubits c = np.reshape(state,cShape(d,N)) # State amplitudes tensor c. A = [] # List of N matrices of MPS, each of shape (chi,d,chi) # Start left end with a vector of size (d,chi) c = np.reshape(c,(d,d**(N-1))) # Reshape c (ap,sv,c) = np.linalg.svd(c) # Apply SVD s = np.zeros((d,...
openhumanoids/exotica
exotica_python/test/test_sparse_costs.py
Python
bsd-3-clause
1,326
0
from __future__ import print_function, division import numpy as np import pyexotica as exo NUM_TESTS = 1000 def num_diff_1d(method, x, arg): eps = 1e-6 x_plus = method(x + eps/2.0, arg) x_minus = method(x - eps/2.0, arg) dx = (x_plus - x_minus) / eps return dx def check_derivative_1d(f, df, arg...
diff, rtol=1e-3) def test_huber(): for delta in [0.001, 0.01, 0.1, 1.0, 10.0]:
check_derivative_1d(exo.Tools.SparseCosts.huber_cost, exo.Tools.SparseCosts.huber_jacobian, delta) check_derivative_1d(exo.Tools.SparseCosts.huber_jacobian, exo.Tools.SparseCosts.huber_hessian, delta) def test_smooth_l1(): for alpha in [1.0, 1...
npuichigo/ttsflow
third_party/tensorflow/tensorflow/contrib/keras/python/keras/layers/noise.py
Python
apache-2.0
5,875
0.003574
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
wargs): super(GaussianDropout, self).__init__(**kwargs) self.supports_masking = True self.rate = rate def call(self, inputs, training=None): if 0 < self.rate < 1: def noised(): stddev = np.sqrt(self.rate / (1.0 - self.rate)) return inputs * K.random_normal( shape=K....
return inputs def get_config(self): config = {'rate': self.rate} base_config = super(GaussianDropout, self).get_config() return dict(list(base_config.items()) + list(config.items())) class AlphaDropout(Layer): """Applies Alpha Dropout to the input. Alpha Dropout is a `Dropout` that keeps mean...
nirs/vdsm
tests/network/functional/netrestore_test.py
Python
gpl-2.0
5,990
0
# Copyright 2016-2020 Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in...
bridged, 'switch': switch} } REMOVE_NET = {NETWORK_NAME: {'remove': True}} with adapter.reset_persistent_config(): with adapter.setupNetworks(
SETUP_NET, {}, NOCHK): adapter.setSafeNetworkConfig() adapter.setupNetworks(REMOVE_NET, {}, NOCHK) adapter.assertNoNetworkExists(NETWORK_NAME) adapter.restore_nets() adapter.assertNetworkExists(NETWORK_NAME) @parametrize_bridged ...
nacerix/xmind-sdk-python
xmind/core/__init__.py
Python
mit
9,331
0.000429
#!/usr/bin/env python #-*- coding: utf-8 -*- """ xmind.core ~~~~~~~~~~ :copyright: :license: """ __author__ = "aiqi@xmind.net <Woody Ai>" from xml.dom import minidom as DOM from .. import utils def create_document(): """:cls: ``xml.dom.Document`` object constructor """ return DOM.Do...
self._node.ownerDocument def setOwnerDocument(self, doc_imple): self._node.ownerDocument = doc_imple def setAttributeNS(self, name
space, attr): """ Set attributes with namespace to DOM implementation. Please notice that namespace must be a namespace name and namespace value. Attr composed by namespceURI, localName and value. """ namespace_name, namespace_value = namespace if not self._node.h...
mrcslws/nupic.research
projects/backprop_structure/runs/run_alexnet_binaryactivation_kwinners_gsc.py
Python
agpl-3.0
2,906
0.001032
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2019, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This progra...
periments.mixins as mixins import nupic.research.frameworks.backprop_structure.networks as networks from nupic.research.archive.dynamic_sparse.common.ray_custom_loggers import ( DEFAULT_LOGGERS, ) class SupervisedNoiseBoosting(mixins.UpdateBoostStrength, mixins.TestNoise, ...
.run( experiments.as_ray_trainable(SupervisedNoiseBoosting), name=os.path.basename(__file__).replace(".py", ""), config=dict( network_class=networks.gsc_alexnet_binaryactivation_kwinners, network_args=dict(), dataset_class=datasets.PreprocessedGSC, ...
bollwyvl/es6-widget-example
es6widgetexample/es6examplewidget.py
Python
bsd-3-clause
673
0
from ipywidgets.widgets import ( Button, Widget, widget_serialization, ) from traitlets import ( Unicode, Instance, ) class ES6Example(Button): """ An example widget that highlights issues
in implementing Backbone classes in ES6. """ _model_name = Unicode('ES6ExampleModel', sync=True) _model_module = Unicode( 'nbextensions/es6-widget-example/js/ES6ExampleModel', sync=True) _view_name = Unicode('ES6ExampleView', sync=True) _view_module = Unicode( 'nbextensions/es6-...
idget-example/js/ES6ExampleView', sync=True) foo = Instance(klass=Widget, sync=True, **widget_serialization)
pybel/pybel-notebooks
test.py
Python
apache-2.0
849
0.002356
import os import unittest import nbformat from nbconvert.preprocessors import ExecutePreprocessor import pytest import itertools as itt DIRECTORY = os.path.dirname(os.path.realpath(__file__)) # CHECK THIS http://stackoverflow.c
om/questions/1676269/writing-a-re-usable-parametrized-unittest-testcase-method def get_all_ipynb(directory): for root, directory, files in os.walk(directory): for file in files: if file.endswith('.ipynb') and 'checkpoints' not in root: yield os.path.join(root, file)
@pytest.mark.parametrize('path', get_all_ipynb(DIRECTORY)) def test_notebook(path): with open(os.path.join(DIRECTORY, path)) as f: nb = nbformat.read(f, as_version=4) ep = ExecutePreprocessor(timeout=600, kernel_name='python3') ep.preprocess(nb, {'metadata': {'path': DIRECTORY}})
YuxuanLing/trunk
trunk/code/study/python/core_python_appilication/ch09/parse_links.py
Python
gpl-3.0
2,016
0.006448
#!/usr/bin/env python from HTMLParser import HTMLParser from cStringIO import StringIO from urllib2 import urlopen from urlparse import urljoin from BeautifulSoup import BeautifulSoup, SoupStrainer from html5lib import parse, treebuilders URLS = ( 'http://python.org', 'http://google.com', ) d...
AnchorParser(HTMLParser): def handle_starttag(self, tag, attrs): if tag != 'a': return if not hasattr(self, 'data'): self.data = [] for attr in
attrs: if attr[0] == 'href': self.data.append(attr[1]) parser = AnchorParser() parser.feed(f.read()) output(urljoin(url, x) for x in parser.data) def html5libparse(url, f): 'html5libparse() - use html5lib to parse anchor tags' output(urljoin(url, x.attr...
balbinot/superharris
superharris/urls.py
Python
mit
828
0
"""superharris URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Clas...
om other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, ...
rl(r'^catalogue/', include('catalogue.urls')) ]
christabor/jinja2_template_pack
flask_extras/views/statuses.py
Python
mit
2,266
0
"""Static pages for various HTTP codes. Format must be `page_XXX` where XXX is the code in question. This allows proper dynamic injection into the Flask app
error handling mechanism. """ from inspect import isfunction from flask import render_template def page_400(error): """400 page.""" return render_template( 'status_codes/400.html', code=400, desc='bad request', error=error) def page_401(error): """401 page.""" return ren
der_template( 'status_codes/401.html', code=401, desc='unauthorized access', error=error) def page_403(error): """403 page.""" return render_template( 'status_codes/403.html', code=403, desc='forbidden', error=error) def page_404(error): """404 page.""" return render_...
Flavsditz/projects
eyeTracking/pupil/pupil_src/shared_modules/atb/__init__.py
Python
gpl-2.0
27,057
0.004324
#!/usr/bin/env python # -*- coding: utf-8 -*- #----------------------------------------------------------------------------- # Copyright (C) 2009-2010 Nicolas P. Rougier # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #---------------...
e label is the name used when the bar was created. :type: str ''') def _set_alpha(self, alpha): c = ctypes.c_int(alpha) TwSetParam(self._bar, "", "alpha", PARAM_INT32, 1, ctypes.byref(c)) def _get_alpha(self): c = ctypes.c_in
t(0) TwGetParam(self._bar, "", "alpha", PARAM_INT32, 1, ctypes.byref(c)) return c.value alpha = property(_get_alpha, _set_alpha, doc='''Bar opacity. Bar opacity can vary from 0 for fully transparent to 255 for fully opaque. See also the color and text parameters to chan...
pyranges/pyrle
tests/helpers.py
Python
mit
1,515
0
import pandas as pd def assert_df_equal(df1, df2): pd.options.mode.chained_assignment = None if "Strand" in df1 and "Strand" in df2: sort_on = "Chromosome Start End Strand".split() df1.Strand = df1.Strand.astype("object") df2.Strand = df2.Strand.astype("object") else: sor...
.Chromosome.astype("object") df2.Chromosome = df2.Chromosome.astype("object") print("Actual") print(df1.to_csv(sep=" ")) print("Expected") print(df2.to_csv(sep=" ")) print("Actual dtyp
es") print(df1.dtypes) print("Expected dtypes") print(df2.dtypes) # print("dtypes Strand\n", "1", df1.Strand.dtype, "2", df2.Strand.dtype) # print("dtypes Strand\n", df1.Strand.dtype == df2.Strand.dtype) # print("dtypes equal\n", df1.dtypes == df2.dtypes) print("Actual index") print(df...
p4lang/p4c-bm
p4c_bm/gen_json.py
Python
apache-2.0
61,832
0.000388
# Copyright 2013-present Barefoot Networks, 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 agre...
d_metadata_t": LOG_INFO("Header type '{}' is not byte-aligned, adding padding " "field '{}'".format(name, padding_name)) fields.append([padding_name, 8 - fixed_width % 8]) header_type_dict["fields"] = fields length_exp = None max_length = Non...
length_exp = header_length_exp_format(p4_header.length, zip(*fields)[0]) # bm expects a length in bits length_exp = p4.p4_expression(length_exp, "*", 8) length_exp = p4.p4_expression(length_exp, "-", fixed_width) length_ex...
kingdaa/LC-python
lintc/1417_Weighing_Problem.py
Python
mit
958
0
# 1417. Weighing Problem # Gives nn coins, each weighing 10g, but the weight of one coin is 11g. There # is now a balance that can be accurately weighed. Ask at least a few times # to be sure to find the 11g gold coin. # # Example # Given n = 3, return 1. # # Explanation: # Select two gold coins on the two ends of the...
gold coin is 11g, otherwise the heavy one # is
11g. # Given n = 4, return 2. # # Explanation: # Four gold coins can be divided into two groups and placed on both ends of # the scale. According to the weighing results, select the two heavy gold # coins and place them on the two ends of the balance for the second # weighing. The gold coin at the heavy end is 11g gold...
coursera/courseraresearchexports
courseraresearchexports/models/ExportRequest.py
Python
apache-2.0
8,795
0
# Copyright 2016 Coursera # # 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, sof...
anonymity_level=None, statement_of_purpose=None, schema_names=None, interval=None, ignore_existing=None, **kwargs): self._course_id = course_id if partner_id is not None: self._partner_id = int(partner_id) el
se: self._partner_id = partner_id self._group_id = group_id self._export_type = export_type self._anonymity_level = anonymity_level self._statement_of_purpose = statement_of_purpose self._schema_names = schema_names self._interval = interval self._igno...
ragupta-git/ImcSdk
imcsdk/methodmeta/ConfigConfMosMeta.py
Python
apache-2.0
828
0.007246
"""This module contains the meta information of ConfigConfMos ExternalMethod.""" from ..imccoremeta import MethodMeta, MethodPropertyMeta method_meta = MethodMeta("ConfigConfMos", "configConfMos", "Version142b") prop_meta = { "cookie": MethodPropertyMeta("Cookie", "cookie", "Xs:string", "Version142b", "InputOutp...
False), "in_configs": MethodPropertyMeta("InConfigs", "inConfigs", "ConfigMap", "Version142b", "Input", True), "in_hierarchical": MethodPropertyMeta("InHierarchical", "inHierarchical", "Xs:string", "Version142b", "InputOutput", False), "out_configs": MethodPropertyMeta("OutConfigs", "outConfigs", "ConfigMap...
igs": "out_configs", }
kwikadi/orange3
Orange/widgets/unsupervised/owdistancemap.py
Python
bsd-2-clause
26,035
0.000115
import sys import itertools from functools import reduce from operator import iadd import numpy from PyQt4.QtGui import ( QFormLayout, QGraphicsRectItem, QGraphicsGridLayout, QFontMetrics, QPen, QIcon, QPixmap, QLinearGradient, QPainter, QColor, QBrush, QTransform, QGraphicsWidget, QApplication ) from Py...
, self.Select) def mousePressEvent(self, event):
if event.button() == Qt.LeftButton: r, c = self._cellAt(event.pos()) if r != -1 and c != -1: # Clear existing selection # TODO: Fix extended selection. self.__select(QRect(), self.Clear) selrange = QRect(c, r, 1, 1) ...
mattclark/osf.io
api/files/views.py
Python
apache-2.0
9,504
0.00263
from django.http import FileResponse from django.core.files.base import ContentFile from rest_framework import generics from rest_framework import permissions as drf_permissions from rest_framework.exceptions import NotFound, PermissionDenied, ValidationError from framework.auth.oauth_scopes import CoreScopes from o...
developer.osf.io/#operation/files_version_detail). """ version_lookup_url_kwarg = 'version_id' permission_classes = ( drf_permissions.IsAuthenticatedOrReadOnly, base_permissions.TokenHasScope, PermissionWithGetter(ContributorOrPublic, node_from_version), ) required_read_scop...
NODE_FILE_READ] required_write_scopes = [CoreScopes.NODE_FILE_WRITE] serializer_class = FileVersionSerializer view_category = 'files' view_name = 'version-detail' # overrides RetrieveAPIView def get_object(self): self.file = self.get_file() maybe_version = self.file.get_version...
Maelstroms38/ecommerce
src/products/mixins.py
Python
mit
640
0.020313
from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.contrib.admin.views.decorators import staff_member_required from django.http import Http404 from django.shortcuts import get_object_or_404 from answers.mixins import SellerAccountMixin class Produ...
gs): # seller = self.get_account() obj = super(ProductManagerMixin,
self).get_object(*args, **kwargs) return obj # try: # obj.seller == seller # except: # raise Http404 # if obj.seller == seller: # return obj # else: # raise Http404
racker/python-service-registry-cli
service_registry_cli/commands/configuration/list.py
Python
apache-2.0
2,023
0
# Copyright 2012 Rackspace # # 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...
parser = super(ListCommand, self).get_parser(prog_name=prog_name) parser.add_argument('--namespace', dest='namespace') return parser def take_action(self, parsed_args): client = get_client(parse
d_args) marker = parsed_args.marker if parsed_args.marker else None limit = parsed_args.limit if parsed_args.limit else None kwargs = {'marker': marker, 'limit': limit} if parsed_args.namespace: kwargs['namespace'] = parsed_args.namespace result = client.config...
kevin-intel/scikit-learn
sklearn/utils/tests/test_estimator_checks.py
Python
bsd-3-clause
24,646
0
# We can not use pytest here, because we run # build_tools/azure/test_pytest_soft_dependency.sh on these # tests to make sure estimator_checks works without pytest. import unittest import sys import numpy as np import scipy.sparse as sp import joblib from sklearn.base import BaseEstimator, ClassifierMixin from sklea...
lass_weight += 1. # Simply assigning coef_ to the class_weight self.coef_ = class_weight return self class BadTransformerWit
houtMixin(BaseEstimator): def fit(self, X, y=None): X = self._validate_data(X) return self def transform(self, X): X = check_array(X) return X class NotInvariantPredict(BaseEstimator): def fit(self, X, y): # Convert data X, y = self._validate_data( ...
tecnovert/particl-core
test/functional/rpc_uptime.py
Python
mit
1,033
0.000968
#!/usr/bin/env python3 # Copyright (c) 2017-2021 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the RPC call related to the uptime command. Test corresponds to code in rpc/server.cpp. """ impo...
def run_test(self): self._test_negative_time() self._test_uptime() def _test_negative_time(self): assert_raises_rpc_error(-8, "Mocktime cannot be negative: -1.", self.nodes[0].setmocktime, -1) def _test_uptime(self): wait_time = 10 self.nodes[0].setmocktime(int(time.t...
'__main__': UptimeTest().main()
OCA/reporting-engine
kpi_dashboard/tests/__init__.py
Python
agpl-3.0
60
0
from . impor
t test_formula from . import test
_kpi_dashboard
park-bench/gpgmailer
test/__init__.py
Python
gpl-3.0
1,050
0.000952
#!/usr/bin/python3 # Copyright 2017-2021 Joel Allen Luellwitz and Emily Frost # # This program is free software: you can redistribute it and/or modif
y # it under t
he terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or F...
WeakGroup/twitter-rec
test/test_block.py
Python
gpl-2.0
304
0.016447
from twitter_rec import Api import time USERNAME = "liaoy
isheng89@sina.com"
PASSWD = "bigdata" s = Api.Session(USERNAME, PASSWD, debug=False) s.connect() counter = 0 while True: _ = s.read("/AllenboChina/followers") if "eason" in _: print counter counter += 1 else: assert False
anguoyang/SMQTK
python/smqtk/fusion/__init__.py
Python
bsd-3-clause
369
0.00271
# -*- coding: utf-8 -*-
""" LICENCE ------- Copyright 2015 by Kitware, Inc. All Rights Reserved. Please refer to KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. SMQTK subsystem providing the ability to manage and fuse index rankings from multiple descripto...
numenta/nupic.research
packages/backprop_structure/src/nupic/research/frameworks/backprop_structure/dataset_managers/imagenet.py
Python
agpl-3.0
3,774
0.00106
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2020, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This progra...
ersion 3 as # published by
the Free Software Foundation. # # 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. # See the GNU Affero Public License for more details. # # You should have received a copy of the GNU A...
ilendl2/chrisdev-cookiecutter
{{cookiecutter.repo_name}}/{{cookiecutter.project_name}}/news/views.py
Python
bsd-3-clause
2,060
0.000485
from django.shortcuts import render_to_response, get_object_or_404 from django.http import Http404 from django.views.generic.list import ListView from django.views.generic.detail import DetailView from django.views.generic.dates import YearArchiveView, MonthArchiveView,\ DateDetailView from .models import Article, ...
ist.html" class SectionDetailView(DetailView): queryset = Section.objects.all() template = "news/section_detail.html" class ArticleYearArchiveView(YearArchiveView): queryset = Article.objects.published() date_field = "published" make_object_list = True template = "news/post_archive_year.html...
st = True template = "news/post_archive_month.html"
anitagraser/processing_pysal
ext-libs/pysal/cg/tests/test_shapes.py
Python
gpl-2.0
27,046
0.002884
from pysal.cg import Point, LineSegment, Line, Ray, Chain, Rectangle, Polygon import doctest import unittest class test_Point(unittest.TestCase): def test___init__1(self): """ Tests whether points are created without issue. Test tag: <tc>#tests#Point.__init__</tc> """ for...
st tag: <tc>#tests#LineSegment.is_ccw</tc> """ ls = LineSegment(Point((0, 0)), Point((5, 0))) self.assertFalse(ls.is_ccw( Point((10, 0
)))) # At positive boundary beyond segment self.assertFalse(ls.is_ccw(Point((3, 0)))) # On segment self.assertFalse(ls.is_ccw( Point((-10, 0)))) # At negative boundary beyond segment self.assertFalse(ls.is_ccw(Point((0, 0)))) # Endpoint of segment self.assertFalse(ls.is_c...
kmod/icbd
icbd/type_analyzer/tests/multiple_inheritance.py
Python
mit
543
0.014733
def f1(): class A(ob
ject): pass class B(A): pass " Invalid mro:" class C(A,B): # e 4 pass def f2(): class A(object): w = '' x = '' y = '' z = '' class B(A): y = 1 z = 1 class C(A): x = True y = True z = True cl...
.x # 6 bool o.y # 6 int o.z # 6 None
lukas-linhart/pageobject
tests/unit/commands/test_get_value.py
Python
mit
297
0.006734
from tests.unit.fixtures import mock_commands_po as mock_po def test_get_value_method_delegates_to_webelement_with_correct_parameter(mock_po): correct_parameter = 'value' mock_po.webelement.get_attribute = lambda attr, log=True: attr assert mock_po.get_value() == correct_paramet
er
simbha/mAngE-Gin
lib/django/db/models/sql/constants.py
Python
mit
1,399
0
""" Constants specific to the SQL storage portion of the ORM. """ from collections import namedtuple import re # Valid query types (a set is used for speedy lookups). These are (currently) # considered SQL-specific; other storage systems may choose to use different # lookup types. QUERY_TERMS = { 'exact', 'iexact...
with', 'iendswith', 'range', 'year', 'month', 'day', 'week_day', 'hour', 'minute', 'second', 'isnull', 'search',
'regex', 'iregex', } # Size of each "chunk" for get_iterator calls. # Larger values are slightly faster at the expense of more storage space. GET_ITERATOR_CHUNK_SIZE = 100 # Namedtuples for sql.* internal use. # Join lists (indexes into the tuples that are values in the alias_map # dictionary in the Query class). ...
ChristopherHogan/cython
Cython/Compiler/Errors.py
Python
apache-2.0
7,307
0.0052
# # Errors # from __future__ import absolute_import try: from __builtin__ import basestring as any_string_type except ImportError: any_string_type = (bytes, str) import sys from ..Utils import open_new_file from . import DebugFlags from . import Options class PyrexError(Exception): pass class Pyre...
.write(line) return warn _warn_once_seen = {} def warn_once(position, message, level=0): if level < LEVEL or message in _warn_once_seen: return warn = CompileWarning(position, message) line = "warning: %s\n" % warn if listing_file: listing_file.write(line) if echo_file: ...
rror_stack = [] def hold_errors(): error_stack.append([]) def release_errors(ignore=False): held_errors = error_stack.pop() if not ignore: for err in held_errors: report_error(err) def held_errors(): return error_stack[-1] # this module needs a redesign to support parallel cytho...
shoubamzlibap/small_projects
auto_copy/auto_copy_daemon.py
Python
mit
798
0.005013
#!/usr/bin/env python # -*- coding: utf-8 -*- """ The daemon that calls auto_copy.py uppon optical d
isc insertion """ import signal import sys import time sys.path.append('/usr/local/bin') import auto_copy SIGNAL_RECEIVED = False def run_daemon(config): """ Run the damon config: configParser object """ signal.signal(signal.SIGUSR1, signal_handler) while True: time.sleep(1) ...
auto_copy.auto_copy(config) SIGNAL_RECEIVED = False def signal_handler(dump1, dump2): global SIGNAL_RECEIVED SIGNAL_RECEIVED = True if __name__ == "__main__": main_config = auto_copy.read_config('/etc/auto_copy.yml') auto_copy.setup_logging(main_config) run_daemon(main_config)
Alex-Zamora/cms-basico-django
website/settings.py
Python
gpl-3.0
2,835
0.001764
""" Django settings for website project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) im...
', ) ROOT_URLCONF = 'website.urls' WSGI_APPLICATION = 'website.wsgi.application' # Database # https://docs.djangoproject.com/en/1.7/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.7/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # htt...
neoslaw/django
contact/migrations/0001_initial.py
Python
mit
594
0.001684
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration)
: dependencies = [ ] operations = [ migrations.CreateModel( name='Message', fields=[ ('id', models.AutoField(serialize=False, auto_created=True, verbose_name='ID', primary_key=True)), ('name', models.CharField(max_length=250)), ...
EmailField(max_length=254)), ('message', models.TextField()), ], ), ]
wglass/zoonado
zoonado/recipes/sequential.py
Python
apache-2.0
2,484
0
from __future__ import unicode_literals import logging import re import uuid from tornado import gen from zoonado import exc, WatchEvent from .recipe import Recipe log = logging.getLogger(__name__) sequential_re = re.compile(r'.*[0-9]{10}$') class SequentialRecipe(Recipe): def __init__(self, base_path): ...
ta=data, ephemeral=True, sequential=True ) self.owned_paths[znode_label] = created_path @gen.coroutine def delete_unique_znode(self, znode_label): try: yield self.client.delete(self.owned_paths[znode_label]) except exc.NoNode: pass @ge
n.coroutine def analyze_siblings(self): siblings = yield self.client.get_children(self.base_path) siblings = [name for name in siblings if sequential_re.match(name)] siblings.sort(key=self.sequence_number) owned_positions = {} for index, path in enumerate(siblings): ...
IlyaDjurin/django-shop
cart/context_processors.py
Python
mit
80
0.0125
from .cart imp
ort Cart def cart(request): return {'cart':
Cart(request)}
juantascon/bollinger-bands
python/bolly.py
Python
gpl-3.0
1,507
0.00929
#! /usr/bin/env python3 from bollinger import bands, plot, strategies import argparse parser = argparse.ArgumentParser(description="plots bollinger bands or suggests investments", epilog="example: bolly.py plot AMZN FB") parser.add_argument("action", metavar="ACTION", choices=["plot", "suggest"], help="either plot o...
b = bands.Bands(symbol) b.fetch() try: if args.strategy == "uponce": s = strategies.UpOnce(b) elif args.strategy == "downonce": s = strategies.DownOnce(b) elif args.strategy == "moreup": s
= strategies.MoreUp(b) elif args.strategy == "moredown": s = strategies.MoreDown(b) print("YES" if s.invest() else "NO") except Exception as ex: print("FAIL: (%s)"%(ex))
Beomi/irkshop
goods/migrations/0012_auto_20170907_1720.py
Python
apache-2.0
2,556
0.002874
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-09-07 08:20 from __future__ import unicode_literals import ckeditor.fields from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('goods', '0011_order_uuid'), ] ...
lay_order'], 'verbose_name': '카테고리', 'verbose_name_plural': '카테고리'}, ), migrations.AlterModelOptions( name='goods', options={'ordering': ['display_order'], 'verbose_name': '상품', 'verbose_name_plural': '상품'}, ), migrations.AddField( model_name='category...
migrations.AddField( model_name='goods', name='display_order', field=models.PositiveSmallIntegerField(default=0, verbose_name='카테고리 내 순서(작은게 먼저)'), ), migrations.AddField( model_name='goods', name='stock', field=models.Positive...
gijs/inasafe
safe_qgis/test_keywords_dialog.py
Python
gpl-3.0
23,345
0.001671
""" InaSAFE Disaster risk assessment tool developed by AusAid and World Bank - **GUI Test Cases.** Contact : ole.moller.nielsen@gmail.com .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foun...
s in pylint #pylint: disable=W0101 raise SkipTest("This test hangs Jenkins.") myDialog = KeywordsDialog(PARENT, IFACE) myButton = myDialog.buttonBox.button(QtGui.QDialogButtonBox.Help) QTest.mouseClick(myButton, QtCore.Qt.LeftButton) myMessage = 'Hel
p dialog was not created when help button pressed' assert myDialog.helpDialog is not None, myMessage #pylint: enable=W0101 def test_on_pbnAdvanced_toggled(self): """Test advanced button toggle behaviour works""" makePadangLayer() myDialog = KeywordsDialog(PARENT, IFACE) ...
hesslink111/neuralnetworknibbles
domain/genepool.py
Python
mit
670
0.002985
from domain.snake import Snake from util.encoding import Encoder class GenePool: """Represents the highest evaluated snake encodings of all time. Stores a list of 100 snakes.""" def __init__(self): self.snakes = [] for i in range(100): self.snakes.append(Snake(Encoder.generate_enc...
_snake = self.snakes[0] self.average_score = 0 def add_snakes(self, snakes): self.snakes += snakes self.snakes = sorted(self.snakes, key=lambda x: x.score, reverse=True)[0:100] self.best_snake = self.snakes[0] self.average_score = sum(map(la
mbda x: x.score, self.snakes)) / 100
wisechengyi/pants
src/python/pants/pantsd/pants_daemon.py
Python
apache-2.0
22,406
0.002812
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import logging import os import sys import threading from contextlib import contextmanager from dataclasses import dataclass from setproctitle import setproctitle as set_process_title fr...
ionsBootstrapper from pants.option.options_fingerprinter import OptionsFingerprinter from pants.option.scope import GLOBAL_SCOPE from pants.pantsd.process_manager import FingerprintedProcessManager from pants.pantsd.service.fs_event_service import FSEventService from pants.pantsd.service.pailgun_service import PailgunS...
ce.scheduler_service import SchedulerService from pants.pantsd.service.store_gc_service import StoreGCService from pants.pantsd.watchman_launcher import WatchmanLauncher from pants.util.contextutil import stdio_as from pants.util.memo import memoized_property from pants.util.strutil import ensure_text class _LoggerSt...
zhangxd12/Lfw_face_recognition_svm_ensemble
face_recognition_other_ensemble.py
Python
gpl-3.0
8,462
0.004136
""" =================================================== Faces recognition example using other ensemble methods and pca pca is used to extract features Adapted from http://scikit-learn.org/stable/auto_examples/applications/face_recognition.html#sphx-glr-auto-examples-applications-face-recognition-py and http://scikit...
ensemble import BaggingClassifier from sklearn.neighbors import KNeighborsClassifier from itertools import product from sklearn.ensemble import VotingClassifier from sklearn.ensemble import GradientBoostingClassifier print(__doc__) # Display progress logs on stdout logging.basicConfig(level=
logging.INFO, format='%(asctime)s %(message)s') ############################################################################### # Download the data, if not already on disk and load it as numpy arrays lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4) # introspect the images arrays to find the shapes...