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
PUNCH-Cyber/stoq
stoq/cli.py
Python
apache-2.0
10,981
0.001002
#!/usr/bin/env python3 # Copyright 2014-2018 PUNCH Cyber Analytics Group # # 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 # # Un...
gin installation directory', ) install.add_argument( '--upgrade', action='store_true', help='Force the plugin to be upgraded if it already exists', ) install.add_argument( '--github', action='store_true', help='Install plugin from Github re
pository' ) subparsers.add_parser('test', help='Run stoQ tests') args = parser.parse_args() plugin_opts: Union[Dict, None] = None try: if args.plugin_opts: plugin_opts = {} for arg in args.plugin_opts: plugin_name, plugin_option = arg.split(':', 1) ...
introini/ourlist
users/urls.py
Python
bsd-2-clause
1,039
0.005775
from django.conf.urls import include, url # from django.urls import path, include from . import views # from django.contrib.auth import views as auth_views import search.views app_name = 'users' urlpatterns = [ url(r'^login/', views.Login.as_view(), name='login'), url(r'^register/', views.register_view, name...
', views.user_settings_fl, name='user-settings-fl'), url(r'^settings/fl=(?P<pk>[
0-9]+)&search=$', views.search_users, name='search-users'), url(r'^settings/fl=(?P<pk>[0-9]+)&add=(?P<add_pk>[0-9]+)$', views.add_friend, name='add-friend'), url(r'^settings/fl=(?P<pk>[0-9]+)&remove=(?P<remove_pk>[0-9]+)$', views.remove_friend, name='remove-friend'), ]
skodapetr/lbvs-environment
scripts/libs/data.py
Python
mit
6,451
0.00062
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Provide ways to loading molecules for the test instances. """ import os import re __license__ = 'X11' __DATA_DIRECTORY = os.path.dirname(os.path.realpath(__file__)) + '/../../data/' __DATASET_DIRECTORY = __DATA_DIRECTORY + 'datasets/' __MOLECULES_FILE_CACHE = {} cl...
default_selection=None): """ :param collection: :param default_selection: :return: Groups of datasets. """ collection_dir = __DATA_DIRECTORY + '/collections/' + collection + '/' result = {} for name in os.lis
tdir(collection_dir): datasets_in_collection = [] result[name] = datasets_in_collection with open(collection_dir + name) as stream: for line in stream: line = line.rstrip().split(',') datasets_in_collection.append([line[0], line[1], line[2]]) retur...
Silvia333/ASleep
my_importData_small.py
Python
apache-2.0
1,639
0.009152
import numpy as np import pandas as pd input_file = "3_floor.csv" # comma delimited is the default df = pd.read_csv(input_file, header = 0) # for space delimited use: # df = pd.read_csv(input_file, header = 0, delimiter = " ") # for tab delimited use: # df = pd.read_csv(input_file, header = 0, delimiter = "\t") # ...
RandomForestRegressor(100).fit(numpy_array[0:160, 0:2 ], t).predict(numpy_array[16
0:182, 0:2]) import matplotlib.pyplot as plt fig, ax = plt.subplots() #ax.errorbar(x, t, 0.3, fmt='*', label="Training traffic") ax.plot(xtest, tfit, '-r', label="Predicted traffic") ax.errorbar(xtest, numpy_array[160:182, 3], fmt='g-o', label="Test traffic") #ax.set_ylabel('Throughput (kbits/second)') #ax.set_xlabel...
hamish2014/optTune
optTune/paretoArchives/paretoArchive2D_multi_front.py
Python
gpl-3.0
11,121
0.012409
""" Multi-objective pareto Front archive, features: - stores current pareto front approximation. - check designs domaninance status - this version is designed for large pareto sets. * quick dominance calculting algorithms Only 2D Pareto Fronts values """ import numpy def dominates(a,b): "all(a <= b) and any(...
h_list = [] self.nod_inspected = 0 #nod = number of designs self.nod_dominance_check_only = 0 self.nod_rejected = 0 # recusively create pareto front layers. self.frontDominating = _frontDominating self.offset = _offset if _offset < fronts-1: self.front...
"binary search to locate comparison point." search_list = self.search_list lb, ub = 0, len(search_list)-1 while ub - lb > 1: mp = (ub + lb)/2 if search_list[mp] < fv_dim1: lb = mp #try make sure lb is always less than fv_dim1, and hence non dominat...
SuriyaaKudoIsc/olympia
apps/api/utils.py
Python
bsd-3-clause
5,273
0.000948
import re from django.conf import settings from django.utils.html import strip_tags import amo from amo.helpers import absolutify from amo.urlresolvers import reverse from amo.utils import urlparams, epoch from tags.models import Tag from versions.compare import version_int # For app version major.minor matching. m...
**kwargs: settings.SITE_URL + urlparams(u, **kwargs) if disco: learnmore = settings.SERVICES_URL + reverse('discovery.addons.detail', args=[addon.slug]) learnmore = urlparams(learnmore, src='discovery-personalrec') else: learnmore = ur...
'id': addon.id, 'name': unicode(addon.name) if addon.name else None, 'guid': addon.guid, 'status': amo.STATUS_CHOICES_API[addon.status], 'type': amo.ADDON_SLUGS_UPDATE[addon.type], 'authors': [{'id': a.id, 'name': unicode(a.name), 'link': absolutify(a....
micove/libdesktop-agnostic
wafadmin/Tools/ccroot.py
Python
lgpl-2.1
13,478
0.058391
#! /usr/bin/env python # encoding: utf-8 import os,sys,re import TaskGen,Task,Utils,preproc,Logs,Build,Options from Logs import error,debug,warn from Utils import md5 from TaskGen import taskgen,after,before,feature from Constants import* try: from cStringIO import StringIO except ImportError: from io import StringI...
t_name(self))) tsk.chmod=self.chmod self.link_task=tsk def apply_lib_vars(self): env=self.env uselib=self.to_list(self.uselib) seen=[] names=self.to_list(self.uselib_local)[:] while names
: x=names.pop(0) if x in seen: continue y=self.name_to_obj(x) if not y: raise Utils.WafError("object '%s' was not found in uselib_local (required by '%s')"%(x,self.name)) if getattr(y,'uselib_local',None): lst=y.to_list(y.uselib_local) for u in lst: if not u in seen: names.append(u) y.p...
Nekel-Seyew/Complex-3D-Vector-Fields
dlib-18.18/python_examples/max_cost_assignment.py
Python
apache-2.0
2,558
0.001955
#!/usr/bin/python # The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt # # This simple example shows how to call dlib's optimal linear assignment # problem solver. It is an implementation of the famous Hungarian algorithm # and is quite fast, operating in O(N^3) time. # # ...
d each column corresponds to a job. So for # example, below we are saying that person 0 will make $1 at
job 0, $2 at job 1, # and $6 at job 2. cost = dlib.matrix([[1, 2, 6], [5, 3, 6], [4, 5, 0]]) # To find out the best assignment of people to jobs we just need to call this # function. assignment = dlib.max_cost_assignment(cost) # This prints optimal assignments: [2, 0...
jtauber/graded-reader
code/vocab-coverage-arbitrary.py
Python
mit
3,511
0.002848
#!/usr/bin/env python """ Output a table showing what percentage of targets can be read assuming a certain percentage coverage (columns) and number of items learnt in arbitrary order (rows). The first input file should consist of lines of <target> <item> separated by whitespace. The second input file should consist ...
_future__ import print_function ## configurable settings # list of coverage ratios we want to calculate for # 0.001 is approximately "any" COVERAGE = [0.001, 0.50, 0.75, 0.90, 0.95, 1.00] # list of item counts we want to display for ITEM_COUNTS = [100, 200, 500, 1000, 2000, 5000, 8000, 12000, 16000, 20000] ## l...
ice target_item_list = [] for line in open(TARGET_ITEM_FILENAME): target_item_list.append(line.strip().split()) # items: map of item to learning order, as indicated by loaded learning # programme items = {} count = 1 for line in open(LEARNING_PROGRAMME_FILENAME): if line.startswith("learn"): item = l...
jigargandhi/UdemyMachineLearning
Machine Learning A-Z Template Folder/Part 2 - Regression/Section 4 - Simple Linear Regression/j_data_preprocessing_template.py
Python
mit
72
0.013889
import numpy as np import pandas as pd
import matplot
lib.pyplot as plt
openstack/rally
tests/unit/plugins/task/sla/test_iteration_time.py
Python
apache-2.0
3,060
0
# Copyright 2014: 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 b...
_iteration({"duration": 3.14}) sla_inst.add_iteration({"duration": 6.28}) self.assertTrue(sla1.result()["success"]) # 42 > 6.28 self.assertFalse(sla2.result()["success"]) # 3.62 < 6.28 self.assertEqual("Passed", sla1.status()) self.assertEqual("Failed", sla2
.status()) def test_result_no_iterations(self): sla_inst = iteration_time.IterationTime(42) self.assertTrue(sla_inst.result()["success"]) def test_add_iteration(self): sla_inst = iteration_time.IterationTime(4.0) self.assertTrue(sla_inst.add_iteration({"duration": 3.14})) ...
ksmit799/Toontown-Source
toontown/hood/MailboxInteractiveProp.py
Python
mit
10,805
0.00435
from direct.actor import Actor from direct.directnotify import DirectNotifyGlobal from direct.interval.IntervalGlobal import Sequence, Func from toontown.hood import InteractiveAnimatedProp from toontown.hood import GenericAnimatedProp from toontown.toonbase import ToontownGlobals, ToontownBattleGlobals, TTLocalizer c...
10), ('tt_a_ara_mml_mailbox_idleLook2', 1, 1,
None, 3, 10), ('tt_a_ara_mml_mailbox_idleAwesome3', 1, 1, ...
jawilson/home-assistant
homeassistant/components/aftership/const.py
Python
apache-2.0
1,116
0.000896
"""Constants for the Aftership integration.""" from __future__ import annotations from datetime import timedelta from typing import Final import voluptuous as vol import homeassistant.helpers.config_validation as cv DOMAIN: Final = "aftership" ATTRIBUTION: Final = "Information provided by AfterShip" ATTR_TRACKINGS...
(CONF_SLUG): cv.string, } ) REMOVE_TRACKING_SERVICE_SCHEMA: Final = vol.Schema( {vol.R
equired(CONF_SLUG): cv.string, vol.Required(CONF_TRACKING_NUMBER): cv.string} )
cor14095/probases1
Back-end/csvHandler.py
Python
mit
41,975
0.032281
import csv import json import random import os import re import itertools import shutil currentDatabase = '' def showDatabases(): return (next(os.walk('./db'))[1]) def createDatabase(databaseName): newDatabaseDirectory = (r'./db/') + databaseName if not os.path.exists(newDatabaseDirectory): #Create directory ...
], insertInfo['tableName'], metadata) == 'int'): if(type(insertInfo['values'][i]) != type(1)): print("TYPE ERROR") return False if(getType(insertInfo['columns'][i], insertInfo['tableNa
me'], metadata) == 'float'): if(type(insertInfo['values'][i]) != type(1.0)): print("TYPE ERROR") return False if(getType(insertInfo['columns'][i], insertInfo['tableName'], metadata) == 'date'): dateExpresion = re.compile('^\d\d-\d\d-\d\d\d\d$') if not dateExpresion.match(insertInfo['values'][i]): ...
scalyr/scalyr-agent-2
tests/image_builder/distributions/centos7/__init__.py
Python
apache-2.0
1,729
0.000578
# Copyright 2014-2020 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, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language g...
from scalyr_agent.__scalyr__ import get_install_root from tests.utils.compat import Path from tests.image_builder.distributions.fpm_package_builder import FpmPackageBuilder from tests.utils.image_builder import AgentImageBuilder from tests.image_builder.distributions.base import ( create_distribution_base_image_na...
shtrom/gtg
GTG/plugins/bugzilla/bugzilla.py
Python
gpl-3.0
4,140
0.000966
# -*- coding: utf-8 -*- # Copyright (c) 2009 - Guillaume Desmottes <[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 3 of the License, or (at your option) any...
scheme, hostname, queries = self.parseBugUr
l(bug_url) bug_id = queries.get('id', None) if bugIdPattern.match(bug_id) is None: # FIXME: make some sensable action instead of returning silently. return try: bugzillaService = BugzillaServiceFactory.create(scheme, hostname) except BugzillaServiceN...
samabhi/pstHealth
venv/lib/python2.7/site-packages/crispy_forms/tests/test_layout_objects.py
Python
mit
16,205
0.000309
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from django.template import Context from django.utils.translation import ugettext as _ from django.utils.translation import activate, deactivate from .compatibility import get_template_from_string from .conftest import only_boot...
) == 1 def test_field_type_hidden(): template = get_template_from_string(""" {% load crispy_forms_tags %} {% crispy test_form %} """) test_form = TestForm() test_form.helper = FormHelper()
test_form.helper.layout = Layout( Field('email', type="hidden", data_test=12), Field('datetime_field'), ) c = Context({ 'test_form': test_form, }) html = template.render(c) # Check form parameters assert html.count('data-test="12"') == 1 assert html.count('name=...
simo5/custodia
custodia/message/simple.py
Python
gpl-3.0
1,145
0
# Copyright (C) 2015 Custodia Project Contributors - see LICENSE file import json from six import string_types from custodia.message.common import InvalidMessage from custodia.message.common import MessageHandler class SimpleKey(MessageHandler): "
""Handles 'simple' messages""" def parse(self, msg, name): """Parses a simple message :param req: ignored :param msg: the json-decoded value
:raises UnknownMessageType: if the type is not 'simple' :raises InvalidMessage: if the message cannot be parsed or validated """ # On requests we imply 'simple' if there is no input message if msg is None: return if not isinstance(msg, string_types): rai...
cemc/cscircles-wp-content
lesson_files/lesson9/if.py
Python
gpl-3.0
225
0
x = int(input()) y = int(input(
)) print('In this test case x =', x, 'and y =', y) if x >= y: print('(The maximum is x)') theMax = x else: print('(The maximum is y)') theMax = y print('The maximum is', theMax)
oneman/xmms2-oneman-old
wafadmin/Tools/vala.py
Python
lgpl-2.1
8,888
0.02644
#!/usr/bin/env python # encoding: utf-8 # Ali Sabil, 2007 import os.path, shutil import Task, Runner, Utils, Logs, Build, Node from TaskGen import extension, after, before EXT_VALA = ['.vala', '.gs'] class valac_task(Task.Task): vars = ("VALAC", "VALAC_VERSION", "VALAFLAGS") before = ("cc", "cxx") def run(self)...
ectory: '%s'" % include) if hasattr(self, 'threading'): valatask.threading = self.threading self.use
lib = self.to_list(self.uselib) if not 'GTHREAD' in self.uselib: self.uselib.append('GTHREAD') if hasattr(self, 'target_glib'): valatask.target_glib = self.target_glib if hasattr(self, 'gir'): valatask.gir = self.gir env = valatask.env output_nodes = [] c_node = node.change_ext('.c') output_no...
uaprom-summer-2015/Meowth
project/utils.py
Python
bsd-3-clause
368
0
import re from project.models import PageChunk contacts_map_coordinates = \ re.compil
e( r".*" r"@(?P<latitude>\-?[\d\.]+)," r"(?P<longitude>\-?[\d\.]+)," r"(?P<zoom>[\d\.]+)z" r".*"
) def inject_pagechunks(): chunks = {chunk.name: chunk.text for chunk in PageChunk.query.all()} return {"pagechunks": chunks}
saebyn/django-classifieds
classifieds/__init__.py
Python
bsd-3-clause
17
0
"""
$Id$
"""
mu2019/heysqlware
demo/tables/atttb.py
Python
mit
1,087
0.053628
#!/usr/bin/env python #!coding=utf-8 from sqlalchemy.ext.declarative import declarative
_base from sqlalchemy import Table,Column,Integer,String,Numeric,MetaData,DateTime,Date from ._base import BaseInit,Base ''' 員工刷卡原始數據表 ''' class ATTTB(BaseInit,Base): __tablename__='ATTTB' TB001=Column(String(20),nullable=False,primary_key=True,doc='員工編號') TB002=Column(DateTime,nullable=False,primary_k...
B004=Column(String(30),default='',doc='員工姓名') TB005=Column(String(10),default='',doc='員工部門編號') TB006=Column(String(30),default='',doc='員工部門編號') TB007=Column(String(10),default='',doc='員工職務編號') TB008=Column(String(30),default='',doc='員工職務名稱') TB009=Column(String(10),default='',doc='卡鍾代號') TB010=C...
charlieRode/network_tools
test_socket_server1.py
Python
mit
573
0.013962
#!/usr/bin/env python import socket_server, pytest, socket address= ('127.0.0.1', 50000) tester_client= socket.socket( socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP) def test_bad_request_type(): request= "HEAD www.wombatlyfe.com HTTP/1.1\r\n" pass def test_good_request(): request= "GE...
tester_client.shutdown(socket.SH
UT_WR) tester_client.close() assert 'Bad Request' not in message
kivy/python-for-android
pythonforandroid/recipes/pyaml/__init__.py
Python
mit
321
0.003115
from pythonforandroid.recipe import P
ythonRecipe class PyamlRecipe(PythonRecipe): version = "15.8.2" url = 'https://pypi.python.org/packages/source/p/pyaml/py
aml-{version}.tar.gz' depends = ["setuptools"] site_packages_name = 'yaml' call_hostpython_via_targetpython = False recipe = PyamlRecipe()
twonds/punjab
punjab/httpb_client.py
Python
mit
12,339
0
import hashlib import random import urllib.parse import os from twisted.internet import defer, reactor, protocol from twisted.python import log, failure try: from twisted.words.xish import domish, utility except Exception: from twisted.xish import domish, utility # noqa from twisted.web import http from twis...
self.deferred =
defer.Deferred() self.client.sendBody(b) return self.deferred def parseResponse(self, contents, protocol): self.client = protocol hp = HttpbParse(True) try: body_tag, elements = hp.parse(contents) except Exception: raise else: ...
AliLozano/django-messages-extends
messages_extends/urls.py
Python
mit
358
0.005587
# -*- coding: utf-8 -*- """urls.py: messages extends""" fr
om django.conf.urls import url from messages_extends.views import message_ma
rk_all_read, message_mark_read urlpatterns = [ url(r'^mark_read/(?P<message_id>\d+)/$', message_mark_read, name='message_mark_read'), url(r'^mark_read/all/$', message_mark_all_read, name='message_mark_all_read'), ]
argonemyth/sentry
tests/sentry/api/endpoints/test_project_group_index.py
Python
bsd-3-clause
12,617
0.00103
from __future__ import absolute_import from datetime import timedelta from django.core.urlresolvers import reverse from django.utils import timezone from mock import patch from sentry.models import Group, GroupBookmark, GroupSeen, GroupStatus from sentry.testutils import APITestCase from sentry.testutils.helpers impo...
new_gr
oup4 = Group.objects.get(id=group4.id) assert new_group4.resolved_at is None assert new_group4.status == GroupStatus.UNRESOLVED def test_set_bookmarked(self): group1 = self.create_group(checksum='a' * 32, status=GroupStatus.RESOLVED) group2 = self.create_group(checksum='b' * 32, sta...
uranusjr/django
tests/m2m_through_regress/models.py
Python
bsd-3-clause
3,268
0.000612
from django.contrib.auth.models import User from django.db import models # Forward declared intermediate model class Membership(models.Model): person = models.ForeignKey('Person', models.CASCADE) group = models.ForeignKey('Group', models.CASCADE) price = models.IntegerField(default=100) def __str__(s...
reignKey(User, models.CASCADE) group = models.ForeignKey('Group', models.CASCADE) price = models.IntegerField(default=100) def __str__(self): return "%s is a user and member of %s" %
(self.user.username, self.group.name) class Person(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) # Membership object defined as a class members = models.ManyToManyField(Person...
wathsalav/xos
xos/core/models/role.py
Python
apache-2.0
815
0.009816
import os import datetime from django.db import models from core.models import PlCoreBase from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes
import generic class Role(PlCoreBase): role_type = models.CharField(max_length=80, verbose_name="Name") role = models.CharField(max_length=80, verbose_name="Keystone role id", null=True, blank=True) description = models.CharField(max_length=1
20, verbose_name="Description") content_type = models.ForeignKey(ContentType, verbose_name="Role Scope") def __unicode__(self): return u'%s:%s' % (self.content_type,self.role_type) def save(self, *args, **kwds): super(Role, self).save(*args, **kwds) def delete(self, *args, **kwds): ...
coala-analyzer/coala-bears
tests/general/LicenseHeaderBearTest.py
Python
agpl-3.0
2,350
0
imp
ort os from queue import Queue from bears.general.LicenseHeaderBear impo
rt LicenseHeaderBear from coalib.testing.LocalBearTestHelper import LocalBearTestHelper from coalib.results.Result import Result from coalib.settings.Section import Section from coalib.settings.Setting import Setting def get_testfile_path(name): return os.path.join(os.path.dirname(__file__), ...
wilbuick/django-ttdb
ttdb/__init__.py
Python
bsd-3-clause
194
0.005155
f
rom .decorators import use_template_database from .testcases import TemplateDBTestCase from .testcases import TemplateDBTransactionTestCase from .testcases import TemplateDBLiveServerTestCase
release-monitoring/anitya
anitya/tests/test_alembic.py
Python
gpl-2.0
1,640
0.00122
# (c) 2017 - Copyright 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 # version 2 as published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; with...
oc1 =
subprocess.Popen( ["alembic", "history"], cwd=REPO_PATH, stdout=subprocess.PIPE ) proc2 = subprocess.Popen( ["grep", " (head), "], stdin=proc1.stdout, stdout=subprocess.PIPE ) stdout = proc2.communicate()[0] stdout = stdout.strip().split(b"\n") s...
TNT-Samuel/Coding-Projects
DNS Server/Source/Lib/site-packages/dask/dataframe/__init__.py
Python
gpl-3.0
848
0
from __future__ import print_function, division, absolute_import from .core import (DataFrame, Series, Index, _Frame, map_partitions, repartition, to_delayed, to_datet
ime, to_timedelta) from .groupby import Aggregation from .io im
port (from_array, from_pandas, from_bcolz, from_dask_array, read_hdf, read_sql_table, from_delayed, read_csv, to_csv, read_table, demo, to_hdf, to_records, to_bag, read_json, to_json) from .optimize import optimize from .multi import merge, concat from . import rolling...
aljosa/django-tinymce
tests/manage.py
Python
mit
492
0.002033
#!/usr/bin/env python import o
s i
mport sys try: os.environ["DJANGO_SETTINGS_MODULE"] = "tests.settings" test_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, test_dir) except ImportError: pass else: from django.core.management import execute_from_command_line def main(): os.environ.setdefa...
MapQuest/mapquest-osm-server
src/python/dbmgr/dbm_stats.py
Python
mit
3,450
0.00029
# Copyright (c) 2011 AOL 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 use, copy, modify, merg...
s += _format('w', _wv, _w) s += _for
mat('r', _rv, _r) print s % locals() def _stats_timer(): "Invoke the actual display helper and re-arm the timer." _display_stats() global _timer if _is_active: _timer = threading.Timer(_timer_delay, _stats_timer) _timer.start() def init_statistics(config, options): "Initia...
odoousers2014/LibrERP
l10n_ch_payment_slip/wizard/bvr_import.py
Python
agpl-3.0
13,953
0.00258
# -*- coding: utf-8 -*- ############################################################################## # # Author: Nicolas Bessi. Copyright Camptocamp SA # Financial contributors: Hasa SA, Open Net SA, # Prisme Solutions Informatique SA, Quod SA # # This program is free software: you...
01: raise except_osv(_('Error'), _('Total record different from the computed!')) if int(line[51:63]) != len(records): raise except_osv(_('Error'), _('Number record different from the compute...
'reference': line[12:39], 'amount': float(line[39:47]) + (float(line[47:49]) / 100), 'date': time.strftime('%Y-%m-%d', time.strptime(line[65:71], '%y%m%d')), 'cost': float(line[96:98]) + (float(line[98:100]) / 100), } ...
ruibarreira/linuxtrail
usr/lib/python2.7/dist-packages/numpy/lib/stride_tricks.py
Python
gpl-3.0
4,203
0.001665
""" Utilities that manipulate strides to achieve desirable effects. An explanation of strides can be found in the "ndarray.rst" file in the NumPy reference guide. """ from __future__ import division, absolute_import, print_function import numpy as np __all__ = ['broadcast_arrays'] class DummyArray(object): """...
i] = [0] * diff + strides[i] # Chech each dimension for compatibility. A dimension length of 1 is # acc
epted as compatible with any other length. common_shape = [] for axis in range(biggest): lengths = [s[axis] for s in shapes] unique = set(lengths + [1]) if len(unique) > 2: # There must be at least two non-1 lengths for this axis. raise ValueError("shape mismatch:...
apikler/VideoStore
site/manage.py
Python
bsd-2-clause
254
0
#!/usr/bin/env python2 import os import sys if __name__ == "_
_main__": os.environ.setdefault("DJA
NGO_SETTINGS_MODULE", "videostore.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
cafecivet/django_girls_tutorial
Scripts/gunicorn_paster-script.py
Python
gpl-2.0
338
0.002959
#!C:\Users\mbradford\Documents\django_
projects\mysite\Scripts\python.exe # EASY-INSTALL-ENTRY-SCRIPT: 'gunicorn==19.1.1','console_scripts','gunicorn_paster' __requires__ =
'gunicorn==19.1.1' import sys from pkg_resources import load_entry_point sys.exit( load_entry_point('gunicorn==19.1.1', 'console_scripts', 'gunicorn_paster')() )
itsallvoodoo/csci-school
CSCI220/Week 13 - APR09-13/Board.py
Python
apache-2.0
4,833
0.046348
from graphics import * class Board: def __init__(self,w,h): self.win = GraphWin('Scrabble',w,h) self.win.setCoords(-30,-30,180,180) self.markers = [] tws_j = [0,0,0,7,7,14,14,14] tws_i = [0,7,14,0,14,0,7,14] dls_j = [0,0,2,2,3,3,3,6,6,6,6,7,7,8,8,8,8,11,11,1...
dl
s_i = [3,11,6,8,0,7,14,2,6,8,12,3,11,2,6,8,12,0,7,14,6,8,3,11] dws_j = [1,1,2,2,3,3,4,4,10,10,11,11,12,12,13,13] dws_i = [1,13,2,12,3,11,4,10,4,10,3,11,2,12,1,13] tls_j = [1,1,5,5,5,5,9,9,9,9,13,13] tls_i = [5,9,1,5,9,13,1,5,9,13,5,9] for i in range(15): for j i...
SuFizz/Dealer-Loves-Code
starter_first.py
Python
apache-2.0
14,255
0.023641
import urllib import twython def Crowd_twitter(query): consumer_key = '*****'; consumer_secret = '*****'; access_token = '******'; access_token_secret = '******'; client_args = {'proxies': {'https': 'http://10.93.0.37:3333'}} t = twython.Twython(app_key=consumer_key, app_secret=c...
names = []; for i in range(3): ind = product_image[i].index("alt")+len("alt=\""); names.append(product_image[i][ind:].split()[0]); # product_image[i][ind:indend]); return names; def link_fk(product_link): # print
"\n\n\n\n\nLINK FK"; # print product_link; beg_string = "www.flipkart.com"; links = []; for i in range(3): ind = product_link[i].index("a href=")+len("a href=\""); indend = product_link[i].index("class") - 2; links.append(beg_string+product_link[i][ind:indend]); return links;...
Hawaii-Smart-Energy-Project/Maui-Smart-Grid
test/test_msg_types.py
Python
bsd-3-clause
1,301
0
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Daniel Zhang (張道博)' __copyright__ = 'Copyright (c) 2014, University of Hawaii Smart Energy Project' __license__ = 'https://raw.github' \ '.com/Hawaii-Smart-Energy-Project/Maui-Smart-Grid/master/BSD' \ '-LICENSE.txt' import unittes...
mySuite
= unittest.TestSuite() for t in selected_tests: mySuite.addTest(MSGTypesTester(t)) unittest.TextTestRunner().run(mySuite) else: unittest.main()
apyrgio/synnefo
snf-admin-app/synnefo_admin/admin/resources/ips/actions.py
Python
gpl-3.0
2,190
0.000457
# Copyright (C) 2010-2014 GRNET S.A. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed i...
validate_ip_action` of the ips module, that handles the tupples returned by it. """ def check(ip, action): res, _ = ips.validate_ip_action(ip, action) return res return lambda ip: check(ip, action) def generate_actions(): """Create a list of actions on ips.""" actions = Ordere...
actions['destroy'] = IPAction(name='Destroy', c=check_ip_action("DELETE"), f=ips.delete_floating_ip, karma='bad', caution_level='dangerous',) actions['reassign'] = IPAction(name='Reassign to project', f=noop, ...
cortext/crawtextV2
~/venvs/crawler/lib/python2.7/site-packages/lxml/html/diff.py
Python
mit
30,500
0.003213
import difflib from lxml import etree from lxml.html import fragment_fromstring import re __all__ = ['html_annotate', 'htmldiff'] try: from html import escape as html_escape except ImportError: from cgi import escape as html_escape try: _unicode = unicode except NameError: # Python 3 _unicode = st...
sion1, 'version 1'), ... (version2, 'version 2')])) <span title="version 2">Goodbye</span> <span title="version 1">World</span> The documents must be *fragments* (str/UTF8 or unicode), not complete documents The markup argument is a
function to markup the spans of words. This function is called like markup('Hello', 'version 2'), and returns HTML. The first argument is text and never includes any markup. The default uses a span with a title: >>> print(default_markup('Some Text', 'by Joe')) <span title="by Joe">Some T...
WuPei/cv_reconstructor
Polygon.py
Python
mit
486
0.00823
# CS4243: Computer Vision and Pattern Recognition
# Zhou Bin # 29th, Oct, 2014 import numpy as np from Vertex import Vertex class Polygon: def __init__(self, newVertexList, newTexelList):
# Create list to store all vertex self.Vertex = [] for i in newVertexList: self.Vertex.append(i) # Create list to store all texel value self.Texel = [] for i in newTexelList: self.Texel.append(i)
Axilent/sharrock
sharrock_multiversion_example/descriptors/one.py
Python
bsd-3-clause
208
0.004808
""" 1.0 version of the API.
""" from sharrock.desc
riptors import Descriptor version = '1.0' class MultiversionExample(Descriptor): """ This is the first version of this particular function. """
tboyce021/home-assistant
homeassistant/components/switcher_kis/__init__.py
Python
apache-2.0
6,458
0.001858
"""Home Assistant Switcher Component.""" from asyncio import QueueEmpty, TimeoutError as Asyncio_TimeoutError, wait_for from datetime import datetime, timedelta import logging from typing import Dict, Optional from aioswitcher.api import SwitcherV2Api from aioswitcher.bridge import SwitcherV2Bridge from aioswitcher.co...
a=SERVICE_SET_AUTO_OFF_SCHEMA, ) hass.services.async_register( DOMAIN, SERVICE_TURN_ON_WITH_TIMER_NAME, async_turn_on_with_timer_service, schema=SERVICE_TURN_ON_WITH_TIMER_SCHEMA, ) async_listen_platform(hass, SWITCH_DOMAIN, async_switch_plat...
DOMAIN, {}, config)) @callback def device_updates(timestamp: Optional[datetime]) -> None: """Use for updating the device data from the queue.""" if v2bridge.running: try: device_new_data = v2bridge.queue.get_nowait() if device_new_data: ...
opendatakosovo/election-results-visualizer
runserver.py
Python
gpl-2.0
745
0
import argparse from erv import create_app # Create the flask app. app =
create_app() # Run the app if __name__ == '__main__': # Define the arguments. parser = argparse.ArgumentParser() parser.add_argument( '--host', default='0.0.0.0', help='Host to bind to: [%(default)s].') parser.add_argument( '--port', type=int, default=...
'--debug', action='store_true', default=False, help='Debug mode: [%(default)s].') # Parse arguemnts and run the app. args = parser.parse_args() app.run(debug=args.debug, host=args.host, port=args.port)
llou/panopticon
panopticon/core/util/comparer.py
Python
gpl-3.0
5,798
0.005347
# comparer.py is part of Panopticon. # Panopticon 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. # Panopticon is distributed in the ...
ame), self.first[name])) for name
in deleted: result.append((DELETED, self.get_path(name), self.second[name])) for name in changed: result.append((CHANGED, self.get_path(name), self.first[name])) cs = (self.compare(self.first[name], self.second[name], name=name, parent=self)) resul...
cubledesarrollo/django-cuble-project
project_name/project_name/settings/production.py
Python
mit
2,222
0.005851
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from os import environ from .base import * # Normally you should not import ANYTHING from Django directly # into your settings, but ImproperlyConfigured is an exception. from django.core.exceptions import ImproperlyConfigured def get_...
See: https://docs.djangoproject.com/en/dev/ref/settings/#email-backend EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # See: https://docs.djangoproject.com/en/dev/ref/settings/#email-host EMAIL_HOST = environ.get('EMAIL_HOST', 'smtp.gmail.com') # See: https://docs.djangoproject.com/en/dev/ref/settings/...
n.get('EMAIL_HOST_PASSWORD', '') # See: https://docs.djangoproject.com/en/dev/ref/settings/#email-host-user EMAIL_HOST_USER = environ.get('EMAIL_HOST_USER', '[email protected]') # See: https://docs.djangoproject.com/en/dev/ref/settings/#email-port EMAIL_PORT = environ.get('EMAIL_PORT', 587) # See: https://docs....
aldenjenkins/foobargamingwebsite
bans/apps.py
Python
bsd-3-clause
124
0
from __future__ import unicode
_literals from django.apps import AppConf
ig class BansConfig(AppConfig): name = 'bans'
MetaSUB/ModuleUltra
moduleultra/daemon/config.py
Python
mit
3,078
0.00065
from yaml import load from os import environ from os.path import join, isfile from ..module_ultra_repo import ModuleUltraRepo from ..module_ultra_config import ModuleUltraConfig class RepoDaemonConfig: """Represent a MU repo to the MU daemon.""" def __init__(self, **kwargs): self.repo_name = kwargs...
nes = kwargs['pipelines'] def get_repo(self): """Return the MU repo that this represents.""" return ModuleUltraRepo(self.repo_path) def get_pipeline_list(self): """Return a list of (pipe_name, version).""" return [(pipe['name'], pipe['version']) for pipe in self.pipelines] ...
"""Return tolerance for the pipeline.""" for pipe in self.pipelines: if pipe['name'] == pipe_name: return pipe.get('tolerance', 0) def get_pipeline_endpts(self, pipe_name): """Return a list of endpts or None.""" return None def get_pipeline_excluded_...
kato-masahiro/particle_filter_on_episode
PFoE_module/.test_particles_resampling.py
Python
mit
889
0.012739
#coding:utf-8 """ functionモジュールのparticle_resampling関数をテストする """ from functions import particles_resampling import pfoe robot1 = pfoe.Robot(sensor=4,choice=3,particle_num=100) #case1:パーティクルの分布・重みは等分 for i in range(100): robot1.particles.d
istribution[i] = i % 5 robot1.particles.weight[i] = 1.0 / 100.0 robot1.particles = particles_resampling(robot1.particles,5) print robot1.particles.weight print robot1.particles.distribution #case2:パーティクルの分布は等分、重みはイベント0に集中 for i in range(100): robot1.particles.distri
bution[i] = i % 5 if i % 5 == 0: robot1.particles.weight[i] = 1.0 / 20.0 else: robot1.particles.weight[i] = 0.0 robot1.particles = particles_resampling(robot1.particles,5) print robot1.particles.weight print robot1.particles.distribution
jjdmol/LOFAR
CEP/Imager/AWImager2/src/addImagingInfo.py
Python
gpl-3.0
16,822
0.01183
# addImagingInfo.py: Python function to add meta info to a CASA image # Copyright (C) 2012 # ASTRON (Netherlands Institute for Radio Astronomy) # P.O.Box 2, 7990 AA Dwingeloo, The Netherlands # # This file is part of the LOFAR software suite. # The LOFAR software suite is free software: you can redistribute it and/or #...
print "Added subtable", subNameOut, "containing", subtab.nrows(), "rows" subtab.close() sel.close() """ Create the empty LOFAR_QUALITY subtable """ def addQualityTable (image, usedCounts, visCounts): # Create the table using TaQL. tab = pt.taql ("create table '" +
image.name() + "/LOFAR_QUALITY' " + "QUALITY_MEASURE string, VALUE string, FLAG_ROW bool") # Get the rms noise of I,Q,U,V as list of tuples. noises = grn.get_rms_noise (image.name()) for noise in noises: row = tab.nrows() tab.addrows (2) tab.putcell ("QUALITY_MEA...
radiasoft/optics
code_drivers/shadow/driver/shadow_driver_setting.py
Python
apache-2.0
330
0
from optics.driver.abstract_driver_setting import AbstractDriverSetting class ShadowDriverSetting(AbstractDriverSetting): def __init__(self): from code_drivers.shadow.driver.shadow_driver imp
ort ShadowDri
ver AbstractDriverSetting.__init__(self, driver=ShadowDriver())
AAFC-MBB/galaxy-cloudman-playbook
roles/galaxyprojectdotorg.galaxy/files/makepyc.py
Python
mit
506
0
#!/usr/bin/en
v python import sys import compileall from os import walk, unlink from os.path import join, splitext, exists assert sys.argv[1], "usage: makepyc /path/to/lib" for root, dirs, files in walk(sys.argv[1]): for name in files: if name.endswith('.pyc'): pyc = join(root, name) py = sp...
k(pyc) compileall.compile_dir(sys.argv[1])
dsavoiu/kafe2
examples/004_constraints/generate_data.py
Python
gpl-3.0
1,268
0.003155
import numpy as np import matplotlib.pyplot as plt from kafe2 import XYContainer err_val_x = 0.001 err_val_y = 0.01 num_datapoints = 121 l, delta_l = 10.0, np.random.randn() * 0.001 r, delta_r = 0.052, np.random.randn() * 0.001 g_e = 9.780 # gravitational pull at the equator y_0, delta_y_0 = 0.6, np.random.randn() ...
* (np.cos(omega_d * x) + c / omega_d * np.sin(omega_d * x)) y = damped_harmonic_oscillator( x + delta_x, y_0 + delta_y_0, l + delta_l, r + delta_r, g_e, c + delta_c ) y += np.random.randn(num_datapoints) * err_val_y # Optional: plot the data #plt.plot(_x, _y, '+') #plt.show() data = XYContai...
l=err_val_y) data.to_file(filename='data.yml')
moodpulse/l2
users/management/commands/price_import.py
Python
mit
1,880
0.002307
from decimal import Decimal from django.core.management.base import BaseCommand from openpyxl import load_workbook from contracts.models import PriceName, PriceCoast from directory.models import Researches class Command(BaseCommand): def add_arguments(self, parser): """ :param path - файл с карт...
price_obj = PriceName.objects.filter(pk=int(cells[price_code])
).first() research_obj = Researches.objects.filter(pk=int(cells[identify])).first() if cells[coast]: coast_value = Decimal(cells[coast]) if price_obj and research_obj: PriceCoast.objects.update_or_create(price_name=price_obj...
c4goldsw/shogun
examples/undocumented/python_modular/kernel_comm_word_string_modular.py
Python
gpl-3.0
1,453
0.037853
#!/usr/bin/env python from tools.load import LoadMatrix lm=LoadMatrix() traindat = lm.load_dna('../data/fm_train_dna.dat') testdat = lm.load_dna('../data/fm_test_dna.dat') parameter_list = [[traindat,testdat,4,0,False, False],[t
raindat,testdat,4,0,False,False]] def kernel_comm_word_string_modular (fm_train_dna=traindat, fm_test_dna=testdat, order=3, gap=0, reverse = False, use_sign = False): from modshogun import CommWordStringKernel from modshogun import StringWordFeatures, StringCharFeatures, DNA from modshogun import SortWordString ...
s(DNA) charfeat.set_features(fm_train_dna) feats_train=StringWordFeatures(charfeat.get_alphabet()) feats_train.obtain_from_char(charfeat, order-1, order, gap, reverse) preproc=SortWordString() preproc.init(feats_train) feats_train.add_preprocessor(preproc) feats_train.apply_preprocessor() charfeat=StringCharFe...
tensorflow/tensorflow
tensorflow/compiler/mlir/tfr/define_op_template.py
Python
apache-2.0
1,903
0.003678
# Copyright 2020 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...
ense. """A template to define composite ops.""" # pylint: disable=g-direct-tensorflow-import import os import sys from absl import app from tensorflow.compiler.ml
ir.tfr.python.composite import Composite from tensorflow.compiler.mlir.tfr.python.op_reg_gen import gen_register_op from tensorflow.compiler.mlir.tfr.python.tfr_gen import tfr_gen_from_module from tensorflow.python.platform import flags FLAGS = flags.FLAGS flags.DEFINE_string( 'output', None, 'Path to write t...
CT-Data-Collaborative/ctdata-wagtail-cms
ctdata/migrations/0040_auto_20161129_1118.py
Python
mit
1,900
0.002105
# -*- coding: utf-8 -*- # Generated by Django 1.9.9 on 2016-11-29 11:18 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import modelcluster.contrib.taggit import modelcluster.fields class Migration(migrations.Migration): dependencies = [ ...
), migrations.AddField( model_name='dataacademyresource', name='tags', field=modelcluster.contrib.taggit.Clu
sterTaggableManager(blank=True, help_text='A comma-separated list of tags.', through='ctdata.AcademyResourceTag', to='taggit.Tag', verbose_name='Tags'), ), ]
yunity/foodsaving-backend
karrot/bootstrap/tests/test_api.py
Python
agpl-3.0
4,392
0.001138
from unittest.mock import ANY, patch from django.test import override_settings from geoip2.errors import AddressNotFoundError from rest_framework import status from rest_framework.test import APITestCase from karrot.groups.factories import GroupFactory from karrot.users.factories import UserFactory from karrot.utils....
def test_when_logged_in(self): self.client.force_login(user=self.user) with self.assertNumQueries(2): response = self.client.get(self.url)
self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data['user']['id'], self.user.id)
cihangxie/cleverhans
examples/nips17_adversarial_competition/validation_tool/validate_submission_lib.py
Python
mit
14,955
0.006286
"""Helper library which performs validation of the submission.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import csv import json import logging import os import re import subprocess import numpy as np from PIL import Image from six import iteritem...
open(filename) as f: for row in csv.reader(f): try: image_filename = row[0] if not image_filename.endswith('.png'): image_filename += '.png' label = int(row[1]) except (IndexError, ValueError): continue result[image_filename] = label return result cla...
ance of SubmissionValidator. Args: temp_dir: temporary working directory use_gpu: whether to use GPU """ self._temp_dir = temp_dir self._use_gpu = use_gpu self._tmp_extracted_dir = os.path.join(self._temp_dir, 'tmp_extracted') self._extracted_submission_dir = os.path.join(self._temp...
jmesteve/saas3
openerp/addons_extra/l10n_es_aeat/aeat_report.py
Python
agpl-3.0
6,565
0.005638
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2004-2011 # Pexego Sistemas Informáticos. (http://pexego.es) All Rights Reserved # Luis Manuel Angueira Blanco (Pexego) # Copyright (C) 2013 # Ignacio Ibeas - Acysos S.L. (...
id': fields.many2one('account.fiscalyear', 'Fiscal year', required=True, readonly=True, states={'draft': [('readonly', False)]})
, 'company_vat': fields.char('VAT number', size=9, required=True, readonly=True, states={'draft': [('readonly', False)]}), 'type': fields.selection([('N', 'Normal'), ('C', 'Complementary'), ('S', 'Substitutive')], '...
wrouesnel/ansible
lib/ansible/modules/cloud/amazon/elasticache.py
Python
gpl-3.0
20,816
0.001729
#!/usr/bin/python # # Copyright (c) 2017 Ansible Project # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = """ --- mod...
ult: None wait: description: - Wait for cache cluster result before returning required: false default: yes choices: [ "yes", "no" ] hard_
modify: description: - Whether to destroy and recreate an existing cache cluster if necessary in order to modify its state required: false default: no choices: [ "yes", "no" ] extends_documentation_fragment: - aws - ec2 """ EXAMPLES = """ # Note: None of these examples set aws_access_key,...
gnocchixyz/gnocchi
gnocchi/storage/__init__.py
Python
apache-2.0
29,952
0.000033
# -*- encoding: utf-8 -*- # # Copyright © 2016-2018 Red Hat, Inc. # Copyright © 2014-2015 eNovance # # 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/LICE...
ctions.defaultdict(list)) for metric, aggregation, split in self.MAP_METHOD( lambda m, k, a, v: (m, a, self._get_splits_unbatched(m, k, a, v)), # noqa ((metric, key, aggregation, version) for metric, aggregations_and_keys in six.iteritems(metric...
for aggregation, keys in six.iteritems(aggregations_and_keys) for key in keys)): results[metric][aggregation].append(split) return results @staticmethod def _get_splits_unbatched(metric, timestamp_key, aggregation, version=3): raise NotIm...
Bryukh-Checkio-Tasks/checkio-task-mono-captcha
verification/referee.py
Python
gpl-2.0
221
0
from checkio.sig
nals import ON_CONNECT from checkio import api from checkio.referees.io import CheckiOReferee from tests import TESTS api.add_liste
ner( ON_CONNECT, CheckiOReferee( tests=TESTS).on_ready)
neuroelectro/neuroelectro_org
article_text_mining/deprecated/db_add_full_text_wiley.py
Python
gpl-2.0
10,680
0.009551
# -*- coding: utf-8 -*- """ Created on Thu Feb 07 14:13:18 2013 @author: Shreejoy """ # -*- coding: utf-8 -*- """ Created on Tue Mar 20 09:54:11 2012 @author: Shreejoy """ import os import os.path import re import struct import gc from matplotlib.pylab import * from xml.etree.ElementTree i...
articleTitle.encode("iso-8859-15", "replace") #
save full text to a file fileName = make_html_filename(titleEncoded, pmid) if os.path.isfile(fileName): print 'found identical file' pass else: # file doesn't exist f = open(fileName, '...
rocketrip/django-jsonfield
jsonfield/fields.py
Python
mit
5,921
0.001351
import copy from django.db import models from django.utils.translation import ugettext_lazy as _ try: from django.utils import six except ImportError: import six try: import json except ImportError: from django.utils import simplejson as json from django.forms import fields try: from django.forms....
field
= super(JSONFieldBase, self).formfield(**kwargs) if isinstance(field, JSONFormFieldBase): field.load_kwargs = self.load_kwargs if not field.help_text: field.help_text = "Enter valid JSON" return field def get_default(self): """ Returns the default ...
openstack/trove
trove/tests/unittests/backup/test_backup_models.py
Python
apache-2.0
26,428
0
# Copyright 2013 Hewlett-Packard Development Company, L.P. # 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 o...
tance.datastore_version.id, db_record['datastore_version_id']) @patch.object(api.API, 'get_client', MagicMock(return_value=MagicMock())) def test
_create_incremental(self): instance = MagicMock() parent = MagicMock(spec=models.DBBackup) with patch.object(instance_models.BuiltInstance, 'load', return_value=instance): instance.validate_can_perform_action = MagicMock( return_value=None) ...
slaughterjames/etendard
shellplate.py
Python
gpl-3.0
3,659
0.006832
''' Etendard v0.4 - Copyright 2012 James Slaughter, This file is part of Etendard v0.4. Etendard v0.4 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...
e command line ''' class shellplate: ''' Constructor ''' def __init__(self):
''' Not used ''' ''' CreateTemplate() Function: - Creates a Python template that an exploit can be built from - Saves the template to disk for further modification - Returns to etendard ''' def CreateTemplate(self, target, protocol, port, filename)...
2e2a/l-rex
apps/item/migrations/0003_alter_itemfeedback_scale_values.py
Python
gpl-3.0
644
0.001553
# Generated by Django 3.2 on 2021-04-22 04:42 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [
('lrex_item', '0002_auto_20201210_0817'), ] operations = [ migrations.AlterField( model_name='itemfeedback',
name='scale_values', field=models.TextField(help_text='Scale values, separated by commas (e.g. "1,3"). If a label contains a comma itself, escape it with "\\" (e.g. "A,B,Can\'t decide\\, I like both"). The feedback will be shown to the participant if one of these ratings is selected.', max_lengt...
forslund/mycroft-core
mycroft/skills/mycroft_skill/event_container.py
Python
apache-2.0
6,352
0
from inspect import signature from mycroft.messagebus import Message from mycroft.metrics import Stopwatch, report_timing from mycroft.util.log import LOG from ..skill_data import to_alnum def unmunge_message(message, skill_id): """Restore message keywords by removing the Letterified skill ID. Args: ...
e + '.' + handler.__name__ else: return handler.__name__ def create_wrapper(handler, skill_id, on_start, on_end, on_error): """Create the default skill handler wrapper. This wrapper handles things like metrics, reporting handler start/stop and errors. handler (callable): method/functi...
_id: skill_id for associated skill on_start (function): function to call before executing the handler on_end (function): function to call after executing the handler on_error (function): function to call for error reporting """ def wrapper(message): stopwatch = Stopwatch() ...
jyeatman/dipy
dipy/viz/fvtk.py
Python
bsd-3-clause
53,175
0.000414
''' Fvtk module implements simple visualization functions using VTK. The main idea is the following: A window can have one or more renderers. A renderer can have none, one or more actors. Examples of actors are a sphere, line, point etc. You basically add actors in a renderer and in that way you can visualize the fore...
fvtk >>> import numpy as np >>> r=fvtk.ren() >>> lines=[np.random.rand(10,3)] >>> c=fvtk.line(lines, fvtk.colors.red) >>> fvtk.add(r,c) >>> #fvtk.show(r) ''' return vtk.vtkRenderer() def add(ren, a): ''' Add a specific actor ''' if isinstance(a, vtk.vtkVolume): ren...
.RemoveActor(a) def clear(ren): ''' Remove all actors from the renderer ''' ren.RemoveAllViewProps() def rm_all(ren): ''' Remove all actors from the renderer ''' clear(ren) def _arrow(pos=(0, 0, 0), color=(1, 0, 0), scale=(1, 1, 1), opacity=1): ''' Internal function for generating arro...
CCLab/Raw-Salad
scripts/db/budget/budgeutr.py
Python
bsd-3-clause
11,394
0.014785
#!/usr/bin/python # -*- coding: utf-8 -*- """ import: Budżet środków europejskich w układzie tradycyjnym flat structure (each data unit is a separate doc in the collection) parenting is archieved through 'parent' key bulk of files: - this file (budgeutr.py) - data file CSV, produced from XLS (for example, budgeutr.c...
0 else: dict_row[new_key] = int(field) elif new_type == "float": if ',' in field:
field= field.replace(',', '.') dict_row[new_key]= float(field) elif new_type == None: try: dict_row[new_key]= float(field) # then if it is a number if dict_row[new_key].is_integer(): # it can be integer ...
bradmontgomery/django-janitor
janitor/__init__.py
Python
mit
72
0
__version__ = '0.5.0' defaul
t_ap
p_config = 'janitor.apps.JanitorConfig'
CapstoneGrader/codeta
codeta/models/user.py
Python
mit
6,342
0.000946
from flask.ext.login import UserMixin, AnonymousUserMixin from codeta import app, auth, logger from codeta.models.course import Course class User(UserMixin): def __init__(self, user_id, username, password, email, fname, lname, active=True, courses=[]): self.user_id = user_id self.username = userna...
""") data = ( username, ) user = app.db.exec_query(sql, data, 'fetchall', 'return_dict') if user: user = user[0] if(auth.check_password(password, user['password'])): user = User( int(user['use
r_id']), user['username'], user['password'], user['email'], user['first_name'], user['last_name']) logger.debug("User: %s - auth success." % (username)) else: user = None ...
d0u9/examples
.ycm_extra_conf.py
Python
gpl-2.0
6,088
0.021025
# This file is NOT licensed under the GPLv3, which is the license for the rest # of YouCompleteMe. # # Here's the license text for this file: # # This is free and unencumbered software released into the public domain. # # Anyone is free to copy, modify, publish, use, compile, sell, or # distribute this software, either...
We intend this dedication to be an overt act of # relinquishment in perpetuity of all present and future rights to this # software under copyright law. # # THE SOFTW
ARE 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 NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TO...
mdlaskey/DeepLfD
src/deep_lfd/synthetic/synthetic_rope.py
Python
gpl-3.0
3,594
0.01419
import numpy as np import cv2 from scipy import interpolate from random import randint import IPython from alan.rgbd.basic_imaging import cos,sin from alan.synthetic.synthetic_util import rand_sign from alan.core.points import Point """ generates rope using non-holonomic car model dynamics (moves with turn radius) gen...
num_curves = int(rope_l_pixels/(steps_per_curve * pix_per_step * 1.0)) #point generation for c in range(num_curves): turn_delta = rand_sign() * randint(lo_turn_delta, hi_turn_delta) for s in range(steps_per_curve): curr_pos = all_positions[-1] ...
rr_pos + delta_pos], axis = 0) #center the points (avoid leaving image bounds) mid_x_points = (min(all_positions[:,0]) + max(all_positions[:,0]))/2.0 mid_y_points = (min(all_positions[:,1]) + max(all_positions[:,1]))/2.0 for pos in all_positions: pos[0] -= (mid_x_points - w...
kenshay/ImageScript
Script_Runner/PYTHON/Lib/ctypes/_aix.py
Python
gpl-3.0
12,565
0.002149
""" Lib/ctypes.util.find_library() support for AIX Similar approach as done for Darwin support by using separate files but unlike Darwin - no extension such as ctypes.macholib.* dlopen() is an interface to AIX initAndLoad() - primary documentation at: https://www.ibm.com/support/knowledgecenter/en/ssw_aix_61/com.ibm.a...
supported, or there are two directories, or there are different file names. The most common solution for multiple ABI is multiple directories. For the XCOFF (aka AIX) style - one directory (one archive file) is sufficient as multiple shared libraries ca
n be in the archive - even sharing the same name. In documentation the archive is also referred to as the "base" and the shared library object is referred to as the "member". For dlopen() on AIX (read initAndLoad()) the calls are similar. Default activity occurs when no path information is provided. When path informat...
Gustry/inasafe
safe/metadata/property/list_property.py
Python
gpl-3.0
1,695
0
# -*- coding: utf-8 -*- """ InaSAFE Disaster risk assessment tool developed by AusAid -
**metadata module.** Contact : [email protected] .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU
General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. """ __author__ = '[email protected]' __revision__ = '$Format:%H$' __date__ = '10/12/15' __copyright__ = ('Copyright 2012, Australia Indonesia Facility for ' ...
YosaiProject/yosai_dpcache
tests/cache/test_utils.py
Python
apache-2.0
905
0
from unittest import TestCase from dogpile.cache import util class UtilsTest(TestCase): """ Test the relevant utils functionality. """ def test_coerce_string_conf(self): settings = {'expiration_time': '-1'} coerced = util.coerce_string_conf(settings) self.assertEqual(coerced['ex...
settings = {'expiration_time': '+1'} coerced = util.coerce_string_conf(settings) self.assertEqual(coerced['expiration_time'], 1) self.assertEqu
al(type(coerced['expiration_time']), int) settings = {'arguments.lock_sleep': '0.1'} coerced = util.coerce_string_conf(settings) self.assertEqual(coerced['arguments.lock_sleep'], 0.1) settings = {'arguments.lock_sleep': '-3.14e-10'} coerced = util.coerce_string_conf(settings) ...
sebriois/biomart
biomart/attribute_page.py
Python
bsd-2-clause
703
0.004267
class BiomartAttributePage(object): def __init__(self, name, display_name=None, attributes=None, default_attributes=None, is_default=False): self.name = name self.display
_name = display_name or name self.attributes = attributes if attributes else {} self.default_attributes = default_attributes if default_attributes else [] self.is_default = is_default def add(self, attribute): attribute.is_default = attribute.name in self.default_attributes ...
"'%s': (attributes: %s, defaults: %s)" % (self.display_name, self.attributes, repr(self.default_attributes))
benkoo/nand2tetris
06/Python/FileManipulation/FileError.py
Python
cc0-1.0
635
0
# Copyright (C) 2011 Mark Armbrust. Permission granted for educational use. """ hasmError.py -- Er
ror handling for Hack Assembler See "The Elements of Computing Systems", by Noam Nisan and Shimon Schocken """ import sys def Error(message, lineNumber=0, line=''): """ Print an error message and continue. """ if lineNumber != 0: print('Line %d: %s' % (lineNumber, line)) print(' ...
') def FatalError(message, lineNumber=0, line=''): """ Print an error message and abort. """ Error(message, lineNumber, line) sys.exit(-1)
neale/CS-program
533-ReinforcementLearning/assignment1/mdp2.py
Python
unlicense
6,848
0.004965
import sys import operator import numpy as np import matplotlib.pyplot as plt import itertools, functools import re import argparse """ Grid Layout grid[0][0] = num_states grid[0][1] = num_actions """ def load_args(): parser = argparse.ArgumentParser(description='Description of your program') parser.add_ar...
^\x00-\x7f]',r'', line) for line in train] train[0] = [int(a) for a in train[0].split(' ')] num_states, num_actions = train[0] lines = num_actions * num_states + num_actions grid = [] for i in range(1, lines+(num_actions-1)): if (i-1) % (num_states+1) is not 0: ...
train[i] = [float(n) for n in train[i].split(' ')[::4]] actions = [] for i in range(num_actions): actions.append(grid[(i*num_states):((1+i)*num_states)]) train = np.array(train) return train, actions class MDP(object): def __init__(self, args, grid, actions): ...
iamsteadman/bambu-cron
bambu_cron/middleware.py
Python
apache-2.0
152
0.013158
import bambu_cron bambu_cron.autodiscover() class CronMiddleware(object): def process_reques
t(self, *args, **kwargs):
bambu_cron.site.run()
retr0h/maquina
test/unit/test_scenario.py
Python
mit
2,054
0
# Copyright (c) 2015-2017 Cisco Systems, Inc. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge...
RE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. import pytest from molecule import scenario @pytest.fixture def scenario_instance(config_instance): return scen
ario.Scenario(config_instance) def test_name_property(scenario_instance): assert 'default' == scenario_instance.name def test_directory_property(molecule_scenario_directory, scenario_instance): assert molecule_scenario_directory == scenario_instance.directory def test_check_sequence_property(scenario_inst...
c-amr/camr
model.py
Python
gpl-2.0
18,664
0.015216
#!/usr/bin/python from __future__ import absolute_import import bz2,contextlib import numpy as np import sys import json import cPickle as pickle #import simplejson as json from constants import * from common.util import Alphabet,ETag,ConstTag import importlib from collections import defaultdict _FEATURE_TEMPLATES_...
_node_tag(g) self.tag_codebook['ABTTag'].add(g_entity_tag) self.abttag_count[g_entity_tag] += 1 ''' elif g in state.gold_graph.abt_node_table and isinstance(state.gold_graph.abt_node_table[g],int): # post aligned
gnode = state.A.nodes[state.gold_graph.abt_node_table[g]] g_span_wds = [tok['lemma'] for tok in sent_tokens if tok['id'] in range(gnode.start,gnode.end)] g_span_ne = sent_tokens[state.gold_graph.abt_node_table[g]]['ne'] g_entity_tag = gold...
GbalsaC/bitnamiP
venv/src/django-oauth2-provider/tests/settings.py
Python
agpl-3.0
1,878
0.003195
# Django settings for example project. import os DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( ('Tester', '[email protected]'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'N...
d from MEDIA_ROOT. Make sure to use a
# trailing slash. # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = '' # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Exam...
unlessbamboo/grocery-shop
language/gcc/compile.py
Python
gpl-3.0
4,158
0.00051
#!/usr/bin/env python # coding:utf-8 """ 设置基础环境 """ import os import shutil import re import traceback import sys import subprocess def exception_catch(func, *args, **kw): """异常处理""" def inner_func(*args, **kw): """处理""" try: return func(*args, **kw) except BaseExceptio...
fobj.write(bo_value) # run ldconf rst = subprocess.check_call(['ldconfig']) if rst: print "Call ldconfig failed:{0}.".format( subprocess.CalledProcessError) def update_run_conf(log_dir, install_dir): """Update configure 运行时配置文件修改: 将日志配置文件,gcc运行配置文件中的路径更改...
onf/gcc-zlog.ini" new_log_conf = "build/conf/gcc-zlog.ini" src_run_conf = "conf/gcc.ini" new_run_conf = "build/conf/gcc.ini" conf_dir = install_dir + "/conf" # mkdir if not os.path.exists(log_dir): os.makedirs(log_dir) if not os.path.exists(conf_dir): os.makedirs(conf_dir) ...
andrewyoung1991/supriya
supriya/tools/requesttools/ErrorRequest.py
Python
mit
632
0.009494
# -*- encoding: utf-8 -*- from supriya.tools.requesttools.Request import Request class ErrorRequest(Request): ### CLASS VARIABLES ### __slots__ = ( ) ### INITIALIZER ### def __init__( self, ): Request.__init__(self) raise NotImplementedEr
ror ###
PUBLIC METHODS ### def to_osc_message(self): raise NotImplementedError ### PUBLIC PROPERTIES ### @property def response_specification(self): return None @property def request_id(self): from supriya.tools import requesttools return requesttools.RequestId.ERROR
berrange/nova
nova/tests/integrated/test_api_samples.py
Python
apache-2.0
173,795
0.000685
# Copyright 2012 Nebula, Inc. # Copyright 2013 IBM Corp. # # 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...
# Skip non-test classes if attr.extension_name is None: continue # Skip base tests cls = importutils.import_class(attr.extension_name) tests.append(cls.alias) return tests def _get_extensions(self): extensions = [] response = self._do_get...
extension in jsonutils.loads(response.content)['extensions']: extensions.append(str(extension['alias'])) return extensions def test_all_extensions_have_samples(self): # NOTE(danms): This is a list of extensions which are currently # in the tree but that don't (yet) have tests. T...
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/third_party/WebKit/Source/bindings/scripts/v8_attributes.py
Python
gpl-3.0
29,128
0.00206
# Copyright (C) 2013 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 # notice, this list of conditions and the ...
8/BindingSecurity.h') # [Constructor] # TODO(yukishiino): Constructors are much like methods although constructors # are not methods. Constructors must be data-type properties, and we can # support them as a kind of methods. constructor_type = idl_type.constructor_t
ype_name if is_constructor_attribute(attribute) else None # [CEReactions] is_ce_reactions = 'CEReactions' in extended_attributes if is_ce_reactions: includes.add('core/dom/custom/CEReactionsScope.h') # [CustomElementCallbacks], [Reflect] is_custom_element_callbacks = 'CustomElementCallbacks'...
openearth/delft3d-gt-server
delft3dworker/serializers.py
Python
gpl-3.0
5,793
0.000518
from django.contrib.auth.models import Group, User from rest_framework import serializers from delft3dworker.models import Scenario, Scene, SearchForm, Template, Version_Docker class VersionSerializer(serializers.ModelSerializer): """ A default REST Framework ModelSerializer for the Version_Docker model ...
sections", "templates", ) class TemplateSerializer(serializers.ModelSerializer): """ A default REST Framework ModelSerializer for the Template model source: http://www.django-rest-framework.org/api-guide/serializers/ """ # here we will write custom serialization and validation...
s Meta: model = Template fields = ( "id", "name", "meta", "sections", )
lordmos/blink
Tools/Scripts/webkitpy/layout_tests/servers/http_server_unittest.py
Python
mit
4,790
0.002505
# Copyright (C) 2012 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the ...
, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import re import sys import webkitpy.thi...
ghttpd from webkitpy.layout_tests.servers.http_server_base import ServerError class TestHttpServer(unittest.TestCase): def test_start_cmd(self): # Fails on win - see https://bugs.webkit.org/show_bug.cgi?id=84726 if sys.platform in ('cygwin', 'win32'): return host = MockHost() ...
wez/watchman
tests/integration/test_invalid_watchmanconfig.py
Python
apache-2.0
680
0
# vim:ts=4:sw=4:et: # Copyright
2012-present Facebook, Inc. # Licensed under the Apache License, Version 2.0 # no unicode literals from __future__ import absolute_import, division, print_function import os import WatchmanTestCase @WatchmanTestCase.expand_matrix class TestWatchmanConfigValid(WatchmanTestCase.WatchmanTestCase): def test_trail...
Raises(Exception) as ctx: self.watchmanCommand("watch", root) self.assertIn("failed to parse json", str(ctx.exception))
muchnoi/HPGe
bepc/ourweb.py
Python
gpl-3.0
5,626
0.026681
#!/usr/bin/env python # -*- coding: utf-8 -*- import ROOT, time toff = 0 # -8*3600 def Create_html(le,lp): htmlhead = '''<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="author" content="Nickolai Muchnoi"> <meta http-equiv="refresh" content="30"> <title>BEPC-...
= Get_Graph('E.results') PG1, PG2, tp, ep, lp = Get_Graph('P.results') MG = ROOT.TMultiGraph() if EG2: EG2.SetMarkerStyle(20); EG2.SetMarkerColor(ROOT.kGray+1); EG2.SetLineColor(ROOT.kGray+1); EG2.SetLineWidth(1); MG.Add(EG2) if PG2: PG2.SetMarkerStyle(20); PG2.SetMarkerColor(ROOT.kGray+1); PG2.SetLineCol...
) if PG1: PG1.SetMarkerStyle(20); PG1.SetMarkerColor(ROOT.kRed+2); PG1.SetLineColor(ROOT.kRed+2); PG1.SetLineWidth(2); MG.Add(PG1) cv = ROOT.TCanvas('cvt','Compton Beam Energy Monitor',0,0,1000,800); cv.cd(); cv.SetGrid() MG.Draw('AP'); MG.GetYaxis().SetDecimals(); MG.GetYaxis().SetTitle('beam energy, Me...
mogproject/calendar-cli
src/calendar_cli/operation/__init__.py
Python
apache-2.0
180
0
from .help_operation import HelpOperation from .setup_operation import Se
tupOperation from .summary_operation import Su
mmaryOperation from .create_operation import CreateOperation
gwq5210/python_learn
ctypes_test.py
Python
gpl-2.0
250
0.032
#!/usr/bin/env python # cod
ing=utf-8 from ctypes import *; import os; #libtest = CDLL(os.getcwd() + '/multiply.so') #print libtest.multiply(2, 3) lib = CDLL(".
/lib.so"); s = "nihao"; lib.display_sz(s); print "done!" lib.display(s); print "done!!"