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
astroswego/plotypus
test/demo.py
Python
gpl-3.0
2,337
0.012409
from sys import exit import numpy as np np.random.seed(4) # chosen by fair dice roll. guaranteed to be random. from sklearn.linear_model import LinearRegression, LassoCV from sklearn.pipeline import Pipeline from plotypus.preprocessing import Fourier from plotypus.utils import colvec from plotypus.resources import matp...
lc(X_true) n_samples = 50 X_sample = np.random.uniform(size=n_samples) y_sample = lc(X_sample) + np.random.normal(0, 0.1, n_samples) predictor = Pipeline([('Fourier', Fourier(9)), ('OLS', LinearRegression())]) predictor = predictor.fit(colvec(X_sample), y_sample...
ec(X_true)) predictor = Pipeline([('Fourier', Fourier(9)), ('Lasso', LassoCV())]) predictor = predictor.fit(colvec(X_sample), y_sample) y_lasso = predictor.predict(colvec(X_true)) ax = plt.gca() signal, = plt.plot(np.hstack((X_true,1+X_true)), ...
kikinteractive/kik-python
kik/messages/attribution.py
Python
mit
1,812
0.001104
from kik.resource import Resource class Attribution(Resource): """ Parent class for all attribution types """ pass class CustomAttribution(Attribution): """ Att
ribution class for custom attributions, as documented at `<https://dev.kik.com/#/docs/messaging#attribution>`_ Usage: >>> from kik.messages import CustomAttribution, LinkMessage >>> message = LinkMessage() >>> message.attribution = CustomAttri
bution( >>> name='A Name', >>> icon_url='http://foo.bar/anicon' >>> ) """ def __init__(self, name=None, icon_url=None): self.name = name self.icon_url = icon_url @classmethod def property_mapping(cls): return { 'name': 'name', 'icon_ur...
nitely/Spirit
spirit/core/tests/models/__init__.py
Python
mit
341
0
# -*- cod
ing: utf-8 -*- from .auto_slug import ( AutoSlugPopulateFromModel, AutoSlugModel, AutoSlugDefaultModel, AutoSlugBadPopulateFromModel ) from .task_result import TaskResultModel __all__ = [ 'AutoSlugPopulateFromModel', 'AutoS
lugModel', 'AutoSlugDefaultModel', 'AutoSlugBadPopulateFromModel', 'TaskResultModel' ]
atul-bhouraskar/django
django/utils/dateformat.py
Python
bsd-3-clause
10,213
0.001175
""" PHP date() style date formatting See http://www.php.net/date for format strings Usage: >>> import datetime >>> d = datetime.datetime.now() >>> df = DateFormat(d) >>> print(df.format('jS F Y H:i')) 7th October 2003 11:39 >>> """ import calendar import datetime from email.utils import format_datetime as format_datet...
f._no_timezone_or_datetime_is_ambiguous_or_imaginary: return "" seconds = self.Z() sign = '-' if seconds < 0 else '+' seconds = abs(seconds) return "%s%02d%02d" % (sign, seconds // 3600, (seconds // 60) % 60) def P(self): """ Time, in 12-hour hours, minu...
'p.m.', with minutes left off if they're zero and the strings 'midnight' and 'noon' if appropriate. Examples: '1 a.m.', '1:30 p.m.', 'midnight', 'noon', '12:30 p.m.' Proprietary extension. """ if self.data.minute == 0 and self.data.hour == 0: return _('midnight') ...
rajagopal067/testrepo
karma/python/google.py
Python
apache-2.0
258
0.031008
def glTypesNice(types): """Make types into English words""" return typ
es.replace('_',' ').title() def getLatLong(latitude, longitude): """returns the comb
ination of latitude and longitude as required for ElasticSearch""" return latitude+", "+longitude
ging/keystone
keystone/contrib/oauth2/migrate_repo/versions/009_support_postgresql.py
Python
apache-2.0
3,936
0.002541
# Copyright (C) 2016 Universidad Politecnica de Madrid # # 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 la...
able.c.client_id], refcolumns=[consumer_oauth2.c.id], name='consumer_credentials_oauth2_client_id_fkey').drop() ForeignKeyConstraint( columns=[consumer_credentials_table.c.client_id], refcolumns=[consumer_oauth2.c.id], name='con
sumer_credentials_oauth2_client_id_fkey', ondelete='CASCADE').create() # MIGRATION 008 access_token_table = sql.Table('access_token_oauth2', meta, autoload=True) consumer_oauth2 = sql.Table('consumer_oauth2', meta, autoload=True) ForeignKeyConstraint( columns=[access_token_...
zqfan/leetcode
algorithms/74. Search a 2D Matrix/solution.py
Python
gpl-3.0
543
0.003683
class Solution(object): d
ef searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ m, n = len(matrix), len(matrix[0]) if matrix else 0 l, r = 0, m * n - 1 while l <= r: mid = (l + r) / 2 num = matrix[mid / n...
return True return False
NICTA/linearizedGP
linearizedGP/gputils.py
Python
gpl-3.0
4,822
0
# linearizedGP -- Implementation of extended and unscented Gaussian processes. # Copyright (C) 2014 National ICT Australia (NICTA) # # This file is part of linearizedGP. # # linearizedGP is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by...
raining input data Yr: [(k-1) * N / k] training output data Xs: [D x (N / k)] testing input data Ys: [N / k] testing output data All of these are randomly split (but non-overlapping per call) """ X = np.atleast_2d(X) random_indices = np.random.permutation(X....
X_s = X_groups[i] Y_s = Y_groups[i] X_r = np.hstack(X_groups[0:i] + X_groups[i + 1:]) Y_r = np.concatenate(Y_groups[0:i] + Y_groups[i + 1:]) yield (X_r, Y_r, X_s, Y_s) def k_fold_CV_ind(nsamples, k=5): """ Generator to return random test and training indeces for cross fold ...
kevin-coder/tensorflow-fork
tensorflow/python/keras/regularizers_test.py
Python
apache-2.0
3,702
0.005673
# Copyright 2016 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...
, ('l2_zero', keras.regularizers.l2(0.)), ]) @test_util.deprecated_graph_mode_only def test_activity_regularization(self, regularizer): with self.cached_session(): (x_train, y_train), _ = self.get_data() model = self.create_model(activity_regularizer=regularizer) model.compile(loss='ca...
as_parameterized.run_all_keras_modes @keras_parameterized.run_with_all_model_types def test_zero_regularization(self): # Verifies that training with zero regularization works. x, y = np.ones((10, 10)), np.ones((10, 3)) model = testing_utils.get_model_from_layers( [keras.layers.Dense(3, kernel_re...
speedyGonzales/RunTrainer
record/models.py
Python
gpl-3.0
244
0.02459
from django.db import
models # Create your models here. class Record(models.Model): description=mode
ls.TextField() distance=models.IntegerField() reg_date=models.DateTimeField('date published') reg_user=models.IntegerField()
arctelix/django-notification-automated
notification/migrations/0004_auto__add_noticequeuebatch.py
Python
mit
7,050
0.007801
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'NoticeQueueBatch' db.create_table('notification_noticequeuebatch', ( ('id', self...
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('d...
django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_le...
codeboy/coddy-sitetools
sitetools/coddy_api/api_resource.py
Python
bsd-3-clause
1,729
0.001157
# -*- coding: utf-8 -*- class ResourceOptions(object): """ A configuration class for ``Resource``. Provides sane defaults and the logic needed to augment these settings with the internal ``class Meta`` used on ``Resource`` subclasses. """ allowed_methods = ['get', 'post', 'put', 'delete', 'pat...
overrides[override_name] = getattr(meta, override_name) allowed_methods = overrides.get('allowed_methods', ['get', 'post', 'put', 'delete', 'patch']) if overrides.get('list_allowed_methods', None) is None: overrides['list_allowed_methods'] = allowed_methods if overrides...
labsland/labmanager
labmanager/views/proxy.py
Python
bsd-2-clause
7,224
0.007198
import re import time import urlparse import requests from flask import Blueprint, Response, abort, stream_with_context, request, url_for, jsonify, current_app from labmanager.db import db from labmanager.models import AllowedHost proxy_blueprint = Blueprint('proxy', __name__) WHITELIST_REQUEST_HEADERS = ["Accept-L...
SRC_RELATIVE_REGEXP.sub(r"\1%s" % relative_proxied_url, line) line = SRC_ABSOLUTE_REGEXP.sub(r"\1%s" % absolute_proxied_url, line) if '.css' in url: line = URL_ABSOLUTE_REGEXP.sub(r"\1%s/" % absolute_proxied_url, line) output = '\n'.join(output_lines) return output def replace_links...
block = inject_absolute_urls(block, url) return block def generate(req, url): pending_data = "" for chunk in req.iter_content(chunk_size=1024): current_block = pending_data + chunk unfinished = False for unfinished_regexp in unfinished_regexps: if unfinished_regex...
mattasmith/SCHEMA-RASPP
rasppcurve.py
Python
gpl-3.0
7,335
0.022904
#! /usr/local/bin/python """Script for producing a RASPP curve: the average disruption (energy) and average mutation of libraries that have the lowest average energy given constraints on fragment length. ****************************************************************** Copyright (C) 2005 Allan Drummond, Cali...
"sequence of length %d (with identities removed). Aborting..." print error_msg % (min_length, num_fragments, min_length, len(parents[0])) return contacts = schema.getSCHEMAContacts(pdb_contacts, parents) energies = raspp.make_4d_energies(contacts, parents) avg_energies = raspp.calc_average_energies(energies,...
%1.2f secs\n" % (time.clock()-tstart,)) output_file.write("# RASPP found %d results\n" % (len(res),)) tstart = time.clock() curve = raspp.curve(res, parents, bin_width) output_file.write("# RASPP found %d unique (<E>,<m>) points\n" % (len(curve),)) output_file.write("# RASPP curve took %1.2f secs\n" % (time.cloc...
aaxelb/osf.io
addons/dataverse/client.py
Python
apache-2.0
3,545
0.001975
import httplib as http from dataverse import Connection from dataverse.exceptions import ConnectionError, UnauthorizedError, OperationFailedError from framework.exceptions import HTTPError from addons.dataverse import settings from website.util.sanitize import strip_html def _connect(host, token): try: ...
e_long='This dataset cannot be connected due to forbidden ' 'characters in one or more of the file names.' )) def get_dataverses(connection): if connection is None: return [] return connection.get_dataverses() def get_dataverse(connection, alias): if connection i...
t_custom_publish_text(connection): if connection is None: return '' return strip_html(connection.get_custom_publish_text(), tags=['strong', 'li', 'ul'])
sahilshekhawat/ApkDecompiler
javadecompiler/Krakatau/ssa/excepttypes.py
Python
gpl-2.0
368
0.005435
#common exception types ArrayOOB = 'java/lang/ArrayIndexOutOfBoundsException', 0 ArrayStore = 'java/lang/ArrayStoreException', 0 ClassCast = 'java/lang/ClassCastException', 0 MonState = 'java/lang/IllegalMonitorStateException', 0 NegArrSize = 'java/lang/NegativeArraySizeException', 0 NullPtr = 'java/lang/Nu
llPointerException', 0
OOM = 'java/lang/OutOfMemoryError', 0
thoas/django-fairepart
fairepart/forms.py
Python
mit
787
0.002541
from django import forms from django.utils.translation import ugettext_lazy as _ from .models import Invitation class InvitationForm(forms.ModelForm): class Meta: model = Invitation fields = ('email', 'text') def __init__(self, *args,
**kwargs): self.user = kwargs.pop('user', None) super(InvitationForm, self).__init__(*args, **kwargs) def clean_email(self): email = self.cleaned_data['email'] if Invitation.objects.filter(from_user=self.user, email=email).exists(): raise forms.ValidationError(_('An in...
return email def save(self, *args, **kwargs): self.instance.from_user = self.user super(InvitationForm, self).save(*args, **kwargs)
roninio/gae-boilerplate
boilerplate/forms.py
Python
lgpl-3.0
5,505
0.00545
""" Created on June 10, 2012 @author: peta15 """ from wtforms import fields from wtforms import Form from wtforms import validators from lib import utils from webapp2_extras.i18n import lazy_gettext as _ from webapp2_extras.i18n import ngettext, gettext FIELD_MAXLENGTH = 50 # intended to stop maliciously long input ...
validators.regexp(utils.NAME_LASTNAME_REGEXP, message=_( "Last Name invalid. Use only letters and numbers."))]) class EmailMixin(BaseForm): email = fields.TextField(_('Email'), [validators.Required(), validators.Length(min=8, max=FIELD_MAXLENGTH, message=...
"Field must be between %(min)d and %(max)d characters long.")), validators.regexp(utils.EMAIL_REGEXP, message=_('Invalid email address.'))]) # ==== Forms ==== class PasswordResetCompleteForm(PasswordConfirmMixin): pass class Lo...
biddellns/litsl
season/migrations/0004_groupround_schedule_is_set.py
Python
gpl-3.0
464
0
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2016-12-06 02:31 from __future__ import unicode_
literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('season', '0003_auto_20161206_0216'), ] operations = [ migrations.AddField( model_name='groupround',
name='schedule_is_set', field=models.BooleanField(default=False), ), ]
kcompher/topik
topik/readers.py
Python
bsd-3-clause
15,758
0.004823
from __future__ import absolute_import, print_function import os import logging from topik.intermediaries.raw_data import output_formats # imports used only for doctests from topik.tests import test_data_path logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging....
lename): return next(_iter_document_json_stream(filename)) def _iter_large_json(filename, json_prefix='item'): # TODO: add the script to automatically find the json_prefix based on a key # Also should still have the option to manually specify a prefix for complex # json structures. """Iterate over...
prefix Parameters ---------- filename: string The filename of the large json file json_prefix: string The string representation of the hierarchical prefix where the items of interest may be located within the larger json object. Try the following script if you need h...
shaunsephton/holodeck
holodeck/django_settings.py
Python
bsd-3-clause
5,258
0.000761
from holodeck.settings import * import os import sys # Django settings for Holodeck project. PATH = os.path.split(os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]))))[0] DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS # Local time zone for t...
atic" or "C:/www/django/static". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', ...
ticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # Make this unique, and don't share it with anybody. SECRET_KEY = 'nj1p6t#2(fe(e=e_96o05fhti6p#@^mwaqioq=(f(ma_unqvt=' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS ...
jarble/EngScript
libraries/polishNotation.py
Python
mit
14,320
0.023673
#The new version is in polishNotation2.py. Use that version instead of using this version. #To do: #Find out how to split a string using matches of a regular expression as the separator. #Test everything in polyglotCodeGenerator.py #Use re.match(expr, stringToSplit).groups() to split a string with its paramet...
pe(current) == str) and (("'" in current) or ('"' in current))): theCounter +
= 1 toReturn += "<<" + str(theCounter) + ">>" else: toReturn += current return toReturn stringToTest = "(replace(?: each| every|)) <<foo>> (in|inside(?: of)|within) <<bar>> (with) <<baz>>" theRegex = getRegexFromString(stringToTest) print(splitParameterString(stringToTest)) print(splitStatement(theRegex, "rep...
t3dev/odoo
addons/event/__init__.py
Python
gpl-3.0
189
0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing detai
ls. from . import controllers from . import models from . import wizard from
. import report
miltonsarria/dsp-python
filters/ex2/ejemplo_window.py
Python
mit
1,773
0.038917
#procesamiento digital de senales #universidad santiago de cali from scipy import signal import matplotlib.pyplot as plt import numpy as np import sys sys.path.append('tools/') from fourierFunc import fourierAn from scipy.signal import get_window ########################################## #BLOQUE 1 #definir la frecue...
ar ventana M = n w = get_window(window, M) print(M) w=np.hstack((np.zeros(int((N-n)/2)),w,np.zeros(int((N-n)/2)))) print(w.shape) xw=x*w xw1=x1*w xw2=x2*w #usar fourier absX,Xdb,pX=fourierAn(x) f=np.linspace(-Fs/2,Fs/2,Xdb.size) absXw,Xdbw,pXw=fourierAn(xw) absXw1,Xdbw1,pXw2=fourierAn(xw1) absXw2,Xdbw2,pXw2=fourie...
lot(x2) plt.ylabel('x2[n]') plt.subplot(413) plt.plot(x) plt.ylabel('x[n]=x1[n]+x2[n]') plt.subplot(414) plt.plot(xw) plt.ylabel('x[n]*w[n]') plt.xlabel('tiempo - s') plt.figure(2) plt.subplot(311) plt.plot(f,Xdbw) plt.subplot(312) plt.plot(f,Xdbw1) plt.subplot(313) plt.plot(f,Xdbw2) plt.show...
vdrhtc/Measurement-automation
tests/test_keysight11713C.py
Python
gpl-3.0
249
0.004016
import pytest from drivers.keysight11713C import * @pytest.mark.skip def test_set_get(): attenuator = Keysight11713C("swc1", "Y") for i in range(82): attenuat
or.set_attenuation(i) assert i == att
enuator.get_attenuation()
Jorge-Rodriguez/ansible
lib/ansible/modules/cloud/ovirt/ovirt_disk.py
Python
gpl-3.0
29,884
0.002577
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (c) 2016 Red Hat, Inc. # 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'} DOCUME...
added: "2.3" size: description: - "Size of the disk. Size should be specified using IEC standard units. For example 10GiB, 1024MiB, etc." - "Size can be only increased, not decreased." interface: description: - "Driver of the storage interface."...
- "It's required parameter when creating the new disk." choices: ['virtio', 'ide', 'virtio_scsi'] default: 'virtio' format: description: - Specify format of the disk. - Note that this option isn't idempotent as it's not currently possible to change format o...
tcalmant/ipopo
pelix/shell/console.py
Python
apache-2.0
20,364
0.000049
#!/usr/bin/env python # -- Content-Encoding: UTF-8 -- """ Pelix interactive shell Provides a console interface for the Pelix shell, based on readline when available. :author: Thomas Calmant :copyright: Copyright 2020, Thomas Calmant :license: Apache License 2.0 :version: 1.0.1 .. Copyright 2020 Thomas Calmant ...
f script_file: self._run_script(self.__session, script_file) else: # No script: run the main loop (blocking) self._run_loop(self.__session) # Nothing more to do self._stop_event.set() sys.stdout.write("Bye !\n") sys.stdout.flush() if o...
ssion, file_path): """ Runs the given script file :param session: Current shell session :param file_path: Path to the file to execute :return: True if a file has been execute """ if file_path: # The 'run' command returns False in case of error ...
secnot/uva-onlinejudge-solutions
989 - Su Doku/main.py
Python
mit
2,568
0.005062
import sys from copy import deepcopy from math import sqrt def read_num(): return list(map(int, sys.stdin.readline().split())) def read_sudoku(): try: n = read_num() if not n: n = read_num() n = n[0] return [read_num() for _ in range(n*n)] except Exception: ...
self._board = deepcopy(board) def _undo_move(self): x, y = self._moves.pop() self._board[x][y] = 0 self._nfree += 1 def _make_move(self, x, y, value): self._moves.append((x, y)) self._board[x][y] = value self._nfree -= 1 def _possible_values(self, x, y): ...
# Square restrictions square_x, square_y = (x//self._dim)*self._dim, (y//self._dim)*self._dim s = [self._board[square_x+i][square_y+j] for i in range(self._dim) for j in range(self._dim)] # Return values not present in any restriction restrictions = set...
muthu-s/chef-repo
cookbooks/wsi/files/configurethreadpool.py
Python
apache-2.0
1,835
0.012534
import os; import sys; import traceback; ##################################################################### ## Update Thread Pool size ##################################################################### def configureThreadPool(clusterName, threadPoolName, minSize, maxSize): print "Cluster Name = " + ...
ame = AdminConfig.showAttribute(thread, "name") if (name == threadPoolName): AdminConfig.modify(thre
ad, [['minimumSize', minSize],['maximumSize', maxSize]]) print name + " thread pool updated with minSize:" + minSize + " and maxSize:" + maxSize AdminConfig.save() ##################################################################### ## Main #############...
ianmiell/shutit-distro
ruby/ruby.py
Python
gpl-2.0
863
0.040556
"""ShutIt module. See http://shutit.tk """ from shut
it_module import ShutItModule class ruby(ShutItModule): def build(self, shutit): shutit.send('mkdir -p /tmp/build/ruby') shutit.send('cd /tmp/build/ruby') shutit.send('wget -qO- http:/
/cache.ruby-lang.org/pub/ruby/2.2/ruby-2.2.0.tar.gz | tar -zxf -') shutit.send('cd ruby*') shutit.send('./configure --prefix=/usr') shutit.send('make') shutit.send('make install') return True #def get_config(self, shutit): # shutit.get_config(self.module_id,'item','default') # return True def finalize(s...
ntt-sic/nova
nova/virt/vmwareapi/network_util.py
Python
apache-2.0
7,362
0.002309
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2012 VMware, Inc. # Copyright (c) 2011 Citrix Systems, Inc. # Copyright 2011 OpenStack Foundation # # 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 # ...
_dynamic_property", props.distributedVirtualSwitch, "VmwareDistributedVirtualSwitch", "uuid") network_obj['dvsw'] = dvs_props else: props = session._call_method(vim_util, "get_dynamic_property", n...
== network_name: network_obj['type'] = 'Network' network_obj['name'] = network_name if (len(network_obj) > 0): return network_obj def get_vswitch_for_vlan_interface(session, vlan_interface, cluster=None): """ Gets the vswitch associated with the physical network ada...
Comunitea/CMNT_004_15
project-addons/product_outlet_loss/models/product.py
Python
agpl-3.0
1,853
0.00054
############################################################################## # # Copyright (C) 2014 Comunitea Servicios Tecnológicos All Rights Reserved # $Kiko Sánchez <kiko@comunitea.com>$ # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Gen...
d = fields.Many2one('product.product', 'Product') price_unit = fields.Float('Price') price_outlet = fields.Float('Outlet Price') total_lost = fields.Float("Outlet Loss", compute=_get_outlet_loss, store=True, readonly=True) date_move = fields.Date('Move to outlet on', defaul...
tetime.now()) outlet_ok = fields.Boolean('Outlet') order_line_id = fields.Many2one('sale.order.line', 'Order Line') qty = fields.Float('Quantity') percent = fields.Float('Outlet Percent')
ros2/launch
launch/launch/conditions/launch_configuration_equals.py
Python
apache-2.0
2,600
0.001923
# Copyright 2020 Open Source Robotics Foundation, 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...
itutions(expected_value) else: self.__expected_value = None super().__init__(predicate=self._predicate_func) def _predicate_func(self, context: LaunchContext) -> bool: expanded_expected_value = None if self.__expected_value is not None: expanded_expected_valu...
ons[self.__launch_configuration_name] return value == expanded_expected_value except KeyError: if expanded_expected_value is None: return True return False def describe(self) -> Text: """Return a description of this Condition.""" return self._...
Connexions/cnx-publishing
cnxpublishing/views/moderation.py
Python
agpl-3.0
3,154
0
# -*- coding: utf-8 -*- # ### # Copyright (c) 2013-2016, Rice University # This software is subject to the provisions of the GNU Affero General # Public License version 3 (AGPLv3). # See LICENCE.txt for details. # ### from pyramid import httpexceptions from pyramid.view import view_config from ..db import poke_publica...
GET', renderer="cnxpublishing.views:templates/moderations.rss", permission='view', http_cache=0) def admin_moderations(request): # pragma: no cover
return {'moderations': get_moderation(request)}
ofanoyi/scrapy
scrapy/tests/test_utils_python.py
Python
bsd-3-clause
6,570
0.001218
import functools import operator import unittest from itertools import count from scrapy.utils.python import str_to_unicode, unicode_to_str, \ memoizemethod_noargs, isbinarytext, equal_attributes, \ WeakKeyCache, stringify_dict, get_func_args __doctests__ = ['scrapy.utils.python'] class UtilsPythonTestCase(u...
'y'])) a.y = 2 # equal attributes self.failUnless(equal_attributes(a, b, ['x', 'y'])) a.y = 1 # differente attributes self.failIf(equal_attributes(a, b, ['x', 'y'])) # test callable a.meta = {} b.meta = {} se
lf.failUnless(equal_attributes(a, b, ['meta'])) # compare ['meta']['a'] a.meta['z'] = 1 b.meta['z'] = 1 get_z = operator.itemgetter('z') get_meta = operator.attrgetter('meta') compare_z = lambda obj: get_z(get_meta(obj)) self.failUnless(equal_attributes(a, b, [...
mcmartins/chaosproxy
setup.py
Python
mit
564
0.001773
from setuptools import setup from chaosproxy.chaosproxy import __version__ setup( name='ChaosProxy', version=__version__, description='ChaosProxy is an http 1.0 proxy / forward server that creates unstable connections.', url='http://github.com/mcmartins/chaosproxy',
author='Manuel Martins', author_email='manuelmachadomartins@gmail.com', license='MIT', packages=['chaosproxy'], package_
data={'chaosproxy': ['sample-conf.json']}, requires=['argparse'], install_requires=[ 'argparse' ], zip_safe=False )
BackupTheBerlios/espressopp
src/esutil/NormalVariate.py
Python
gpl-3.0
1,470
0.009524
# Copyright (C) 2012,2013 # Max Planck Institute for Polymer Research # Copyright (C) 2008,2009,2010,2011 # Max-Planck-Institute for Polymer Research & Fraunhofer SCAI # # This file is part of ESPResSo++. # # ESPResSo++ is free software: you can redistribute it and/or modify # it under the terms of t...
as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ESPResSo++ 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 PARTICUL
AR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ ********************************* **espresso.esutil.NormalVariate** ******************************...
UQ-UQx/edx-platform_lti
common/lib/xmodule/xmodule/modulestore/xml_importer.py
Python
agpl-3.0
40,861
0.002007
""" Each store has slightly different semantics wrt draft v published. XML doesn't officially recognize draft but does hold it in a subdir. Old mongo has a virtual but not physical draft for every unit in published state. Split mongo has a physical for every unit in every state. Given that, here's a table of semantics...
e more than one course loaded from data_dir/course_dirs & you supply this id, this method will raise an AssertException. static_content_store: the static asset store do_import
_static: if True, then import the course's static files into static_content_store This can be employed for courses which have substantial unchanging static content, which is too inefficient to import every time the course is loaded. Static content for some courses may also be ...
drufat/dec
doc/plot/cheb/basis_forms.py
Python
gpl-3.0
1,067
0.008435
from dec.grid1 import * import matplotlib.pyplot as plt N = 4 #g = Gri
d_1D.periodic(N) g = Grid_1D.regular(N) #g = Grid_1D.chebyshev(N) z = linspace(g.xmin, g.xmax, 100) #+ 1e-16 B0, B1, B0d, B1d = g.basis_fn() H0, H1, H0d, H1d = hodge_star_matrix(g.projection(), g.basis_fn()) H1d = linalg.inv(H0) #polynomial fit #def poly_coeff(basis): # A = array([polyfit(z, b(z), len(basis)-1)[::...
B0) #print poly_coeff(g.B1d) plt.figure() A = linalg.inv(H0).T U = array([b(z) for b in B1d]) V = dot(A, array([b(z) for b in B0])) for u, v in zip(U, V): plt.plot(z, u) plt.plot(z, v, color='k') plt.scatter(g.verts, 0*g.verts) plt.scatter(g.verts_dual, 0*g.verts_dual, color='r', marker='x') plt.fig...
thumbor-community/shortener
docs/conf.py
Python
mit
8,491
0.005889
# -*- coding: utf-8 -*- # # Thumbor documentation build configuration file, created by # sphinx-quickstart on Mon Sep 1 13:18:38 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # A...
: '', } # Grouping the document tree into LaTeX files. List
of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). # latex_documents = [ # ('index', 'Thumbor.tex', u'Thumbor Documentation', # u'Bernardo Heynemann', 'manual'), # ] # The name of an image file (relative to this directory) to place at the top of # the tit...
ssut/PushBank
pushbank/_singleton.py
Python
mit
330
0
class _Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances:
cls._instances[cls] = super(_Singleton, cls).__call__( *args, **kwargs) return cls._instances[cls] class Singleton(_Singleton('SingletonMeta', (obj
ect,), {})): pass
manxueitp/cozmo-test
object_recognition/04_exposure.py
Python
mit
4,967
0.001812
#!/usr/bin/env python3 # Copyright (c) 2017 Anki, 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 in the file LICENSE.txt or at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unles...
# Demo with default grayscale camera images robot.camera.color_image_enabled = False demo_camera_exposure(robot) # Demo with color camera images robot.camera.color_image_enabled = True demo_camera_exposure(robot) cozmo.robot.Robot.drive_off_charger_on_connect = False # Cozmo can stay on his ...
e_viewer=True, force_viewer_on_top=True)
enricoba/eems-box
configbus.py
Python
mit
2,756
0.003266
class __ConfigBus(object): def __init__(self): """Private object *_ConfigBus* provides private functions for various config classes. """ self.conf = 'eems.conf' def _read(self): """Private function *_read* reads the eems.conf file and returns all lines. :return: *l...
from *_ConfigBus* and provides functions to manipulate the monitoring flag. """ def read(self): """Public function *read* reads and returns the monitor
ing flag. :return: *bool* """ conf = self._read() value = [c for c in conf if c.strip('\n')[:10] == 'monitoring'][0].split(' ')[-1:][0].strip('\n') return bool(value) def write(self, value): """Public function *write* writes the monitoring flag into eems.conf file. ...
jorik041/shmoocon_2014_talk
caravan/caravan/dashboards/infrastructure/workers/tables.py
Python
bsd-2-clause
977
0
from horizon import tables from tasa.store import connection class RestartWorker(tables.Action): name = 'restart' verbose_name = 'Restart Worker' data_type_singular = 'Worker' action_present = 'restart' requires_input = False classes = ('btn-warning',) def handle(self, data_table, reques...
datum['add
r'] class Meta: name = 'workers' verbose_name = 'Connections' table_actions = (RestartWorker,) multi_select = False
lmazuel/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2016_12_01/models/flow_log_information_py3.py
Python
mit
2,020
0.00099
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
olicy: ~azure.mgmt.network.v20
16_12_01.models.RetentionPolicyParameters """ _validation = { 'target_resource_id': {'required': True}, 'storage_id': {'required': True}, 'enabled': {'required': True}, } _attribute_map = { 'target_resource_id': {'key': 'targetResourceId', 'type': 'str'}, 'stora...
stiletto/bnw
bnw_shell.py
Python
bsd-2-clause
122
0.016393
#!/usr
/bin/env python import os.path as path import sys root=path.abspath(path.dirname(__file__)) sy
s.path.insert(0,root)
mehulj94/Radium-Keylogger
Recoveries/chrome.py
Python
apache-2.0
2,142
0.010271
import sqlite3 import shutil import win32crypt import sys, os, platform class Chrome(): def __init__(self): pass def run(self): database_path = '' if 'HOMEDRIVE' in os.environ and 'HOMEPATH' in os.environ: # For Win7 path_Win7 = os.
environ.get('HOMEDRIVE') + os.environ.get( 'HOMEPATH') +
'\Local Settings\Application Data\Google\Chrome\User Data\Default\Login Data' # For XP path_XP = os.environ.get('HOMEDRIVE') + os.environ.get( 'HOMEPATH') + '\AppData\Local\Google\Chrome\User Data\Default\Login Data' if os.path.exists(path_XP): datab...
antoviaque/edx-platform
lms/djangoapps/course_api/blocks/tests/test_api.py
Python
agpl-3.0
2,533
0.003158
""" Tests for Blocks api.py """ from django.test.client import RequestFactory from course_blocks.tests.helpers import EnableTransformerRegistryMixin from student.tests.factories import UserFactory from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestC...
), len(self.store.get_items(self.course.id)) - 2) self.assertNotIn(unicode(self.html_block.location), blocks['blocks']) def test_no_user(self): blocks = get_blocks(self.request, self.course.location)
self.assertIn(unicode(self.html_block.location), blocks['blocks']) def test_access_before_api_transformer_order(self): """ Tests the order of transformers: access checks are made before the api transformer is applied. """ blocks = get_blocks(self.request, self.course.l...
feedhq/feedhq
feedhq/feeds/management/commands/sync_scheduler.py
Python
bsd-3-clause
1,310
0
import structlog from more_itertools import chunked from rache import delete_job, scheduled_jobs from . import SentryCommand from ...models import UniqueFeed from ....utils import get_redis_connection logger = structlog.get_logger(__name__) class Command(SentryCommand): """Syncs the UniqueFeeds and the schedule...
for job_id in
to_delete: delete_job(job_id, connection=connection) to_add = target - existing_jobs if to_add: logger.info("adding jobs to the scheduler", count=len(to_add)) for chunk in chunked(to_add, 10000): uniques = UniqueFeed.objects.filter(url__in=chunk) ...
autorealm/MayoiNeko
develop/apis.py
Python
apache-2.0
9,771
0.005366
# coding: utf-8 import re, time, hashlib, logging, json, functools from leancloud import Object from leancloud import User from leancloud import Query from leancloud import LeanCloudError from flask import request from flask import make_response from flask import session from develop.models import Blog, Comments, Pa...
mary': obj.get('summary'), 'content': obj.get('content'), #'user_name': obj.get('user').get('username'), 'created_at': str(obj.crea
ted_at) } if isinstance(obj, Comments): return { 'id': obj.id, #'user_name': obj.get('user').get('username'), 'content': obj.get('content'), 'created_at': str(obj.created_at) } if isinstance(obj, User): return { 'id': ob...
jminyu/PatternRecognition_library
Data_generation.py
Python
gpl-3.0
2,150
0.012093
__author__ = 'Schmidtz' import matplotlib import numpy as np import matplotlib.cm as cm import matplotlib.mlab as mlab import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np from numpy import matlib from numpy import * from numpy.random import * import pylab as p import math from scipy import sta...
c1)*(X-c1) + (Y-c1)*(Y-c1) < r1*r1]
Y1 = Y[(X-c1)*(X-c1) + (Y-c1)*(Y-c1) < r1*r1] X2 = X1[(X1-c1)*(X1-c1) + (Y1-c1)*(Y1-c1) > r2*r2] Y2 = Y1[(X1-c1)*(X1-c1) + (Y1-c1)*(Y1-c1) > r2*r2] X3 = X2[ abs(X2-Y2)>0.05 ] Y3 = Y2[ abs(X2-Y2)>0.05 ] #X3 = X2[ X2-Y2>0.15 ] #Y3 = Y2[ X2-Y2>0.15] X4=zeros(N...
KMPSUJ/lego_robot
pilot.py
Python
mit
4,781
0.001884
# -*- coding: utf-8 -*- from modules import Robot import time r = Robot.Robot() state = [0, 1000, 1500] (run, move, write) = range(3) i = run slowdown = 1 flag_A = 0 flag_C = 0 lock = [0, 0, 0, 0] while(True): a = r.Read() for it in range(len(lock)): if lock[it]: lock[it] = lock[it] - 1 ...
# lock = 30 elif not lock[2]: r.run(-r.S/slowdown, r.S/slowdown) flag_A = -1 flag_C = 1 elif a[3] == 4: if flag_A == -1 and flag_C == 1: r.stop() flag_A = 0
flag_C = 0 lock[3] = 30 # lock = 30 elif not lock[3]: r.run(r.S/slowdown, -r.S/slowdown) flag_A = 1 flag_C = -1 elif a[3] == 9: r.stop() flag_A = 0 flag_C = 0 ...
gviejo/ThalamusPhysio
python/figure_talk/main_talk_7_corr.py
Python
gpl-3.0
14,903
0.034825
import numpy as np import pandas as pd # from matplotlib.pyplot import plot,show,draw import scipy.io import sys sys.path.append("../") from functions import * from pylab import * from sklearn.decomposition import PCA import _pickle as cPickle import matplotlib.cm as cm import os #####################################...
ubplot(gs[0,:]) noaxis(axA) gsA = gridspec.GridSpecFromSubplotSpec(1,3,subplot_spec=gs[0,:],width_ratios=[0.6,0.6,0.6], hspace = 0.2, wspace = 0.2)#, height_ratios = [1,1,0.2,1]) new_path = data_directory+neuron_seed.split('-')[0]+'/'+neuron_seed.split("_")[0] meanWaveF = scipy.io.loadmat(new_path+'/Analysis/SpikeWav...
3 # WAWEFORMS gswave = gridspec.GridSpecFromSubplotSpec(1,3,subplot_spec = gsA[0,1])#, wspace = 0.3, hspace = 0.6) axmiddle = subplot(gswave[:,1]) noaxis(gca()) for c in range(8): plot(meanWaveF[int(neuron_seed.split('_')[1])][c]+c*200, color = color2, linewidth = lw) title("Mean waveforms (a.u.)", fontsize = 16) idx...
juposocial/jupo
src/lib/url.py
Python
agpl-3.0
2,529
0.016607
#! coding: utf-8 import re from urllib import quote from urlparse import urlsplit, urlunsplit TRAILING_PUNCTUATION = ['.', ',', ':', ';', '.)'] WRAPPING_PUNCTUATION = [('(', ')'), ('<', '>'), ('[', ']'), ('&lt;', '&gt;')] unquoted_percents_re = re.compile(r'%(?![0-9A-Fa-f]{2})') word_split_re = re.compile(r'(\s+)') ...
ECASE) simple_url_2_re = re.compile(r'^www\.|^(?!http)\w[^@]+\.(com|edu|gov|int|mil|net|org)$', re.IGNORECASE) def sm
art_urlquote(url): "Quotes a URL if it isn't already quoted." # Handle IDN before quoting. try: scheme, netloc, path, query, fragment = urlsplit(url) try: netloc = netloc.encode('idna').decode('ascii') # IDN -> ACE except UnicodeError: # invalid domain part pass else: url = urlun...
nhatbui/LebronCoin
lebroncoin/key_loader.py
Python
mit
654
0.001529
def load_keys(filepath): """ Loads the Twitter
API keys into a dict. :param filepath: file path to config file with Twitter API keys. :return: keys_dict :raise: IOError """ try: keys_file = open(filepath, 'rb') keys = {} for line in keys_
file: key, value = line.split('=') keys[key.strip()] = value.strip() except IOError: message = ('File {} cannot be opened.' ' Check that it exists and is binary.') print message.format(filepath) raise except: print "Error opening or unpi...
bjura/EPlatform
EMatch.py
Python
gpl-3.0
18,227
0.038094
#!/bin/env python2.7 # -*- coding: utf-8 -*- # This file is part of EPlatform. # # EPlatform 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 ...
hToEPlatform+'multimedia/voices/'+str(self.word)+'.ogg')
mixer.music.play() time.sleep(2) self.stoper.Start(self.timeGap) self.poczatek=False if self.flaga >= self.numberOfExtraWords+1: item = self.subSizer.GetChildren() ...
googleapis/python-speech
samples/snippets/transcribe_enhanced_model.py
Python
apache-2.0
2,170
0.000461
#!/usr/bin/env python # Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
erning permissions and # limitations under the License. """Google Cloud Speech API sample that demonstrates enhanced models and recognition me
tadata. Example usage: python transcribe_enhanced_model.py resources/commercial_mono.wav """ import argparse def transcribe_file_with_enhanced_model(path): """Transcribe the given audio file using an enhanced model.""" # [START speech_transcribe_enhanced_model] import io from google.cloud impor...
t3dev/odoo
addons/account_tax_python/models/account_tax.py
Python
gpl-3.0
4,229
0.010877
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields, api from odoo.tools.safe_eval import safe_eval class AccountTaxPython(models.Model): _inherit = "account.tax" amount_type = fields.Selection(selection_add=[('code', 'Python Cod...
float\n" ":param quantity: float\n" ":param company: res.company recordset singleton\n" ":param product: product.product recordset singleton or None\n" ":param partner: res.partner recordset singleton or None") def _compute_amount(self, base_amount, price_unit, quan...
: base_amount, 'price_unit':price_unit, 'quantity': quantity, 'product':product, 'partner':partner, 'company': company} safe_eval(self.python_compute, localdict, mode="exec", nocopy=True) return localdict['result'] return super(AccountTaxPython, self)._compute_amount(base_amount, price_u...
flavour/tldrmp
private/templates/IFRC/menus.py
Python
mit
31,780
0.005129
# -*- coding: utf-8 -*- from gluon import current from s3 import * from s3layouts import * try: from .layouts import * except ImportError: pass import s3menus as default red_cross_filter = {"organisation.organisation_type_id$name" : "Red Cross / Red Crescent"} # ==============================================...
MM("Received Shipments", c="inv", f="recv"), MM("Sent Shipments", c="inv", f="send"), MM("Items", c="supply", f="item"), MM("Item Catalogs", c="s
upply", f="catalog"), MM("Item Categories", c="supply", f="item_category"), M("Requests", c="req", f="req")(), #M("Commitments", f="commit")(), ), homepage("asset")( MM("Assets", c="asset", f="asset"), MM("Items", c=...
loogica/urlsh
test_views.py
Python
mit
2,651
0.002641
import os import shutil
import unittest from flask import json class NewsView(unittest.TestCase): def setUp(self): import web reload(web) self.app = web.app.test_client
() def tearDown(self): try: shutil.rmtree('urlshortner') except: pass def test_get_home(self): response = self.app.get('/', follow_redirects=True) assert 200 == response.status_code assert 'Loogi.ca' in response.data assert 'input' in res...
jaredlunde/cargo-orm
unit_tests/fields/Cidr.py
Python
mit
2,247
0.000445
#!/usr/bin/python3 -S # -*- coding: utf-8 -*- import netaddr from cargo.fields import Cidr from unit_tests.fields.Field import TestField from unit_tests import configure class TestCidr(configure.NetTestCase, TestField): @property def base(self): return self.orm.cidr def test___call__(self): ...
val.value)), arr) def test_array_select(self): arr = ['127.0.0.1/32', '127.0.0.2/32', '127.0.0.3/32'] self.base_array(arr) val = getattr(self.orm.new().insert(self.base_array), self.base_array.field_name) val_b = getattr(self.orm.new().desc(self.orm.uid).get()...
self.base_array.field_name) self.assertListEqual(list(map(str, val.value)), list(map(str, val_b.value))) def test_type_name(self): self.assertEqual(self.base.type_name, 'cidr') self.assertEqual(self.base_array.type_name, 'cidr[]') class TestEncCidr(TestCidr): @property def base(...
jmacmahon/invenio
modules/websearch/lib/websearch_external_collections_templates.py
Python
gpl-2.0
7,238
0.005388
# -*- coding: utf-8 -*- # This file is part of Invenio. # Copyright (C) 2006, 2007, 2008, 2010, 2011 CERN. # # Invenio 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...
rnal_engine_name_box + \ '</strong></big>') req.write('&nbsp;&nbsp;&nbsp;') req.write(html_external_engine_nb_results_box) req.write('</td><td class="externalcollectionsresultsboxheader" width="20%" align="right">') req.write('<small>' + \ html_external_engine_nb_seconds_box...
t info line for timeout.""" _ = gettext_set_language(lang) req.write('<a name="%s"></a>' % get_link_name(engine.name)) print_info_line(req, create_html_link(url, {}, name, {}, False, False), '', _('Search timed out.')) message = _("The external...
sysbot/pastedown
vendor/pygments/pygments/lexers/asm.py
Python
mit
12,130
0.001319
# -*- coding: utf-8 -*- """ pygments.lexers.asm ~~~~~~~~~~~~~~~~~~~ Lexers for assembly languages. :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re from pygments.lexer import RegexLexer, include, bygroups, using, DelegatingL...
[^\n]+\n', Other)
] } class DObjdumpLexer(DelegatingLexer): """ For the output of 'objdump -Sr on compiled D files' """ name = 'd-objdump' aliases = ['d-objdump'] filenames = ['*.d-objdump'] mimetypes = ['text/x-d-objdump'] def __init__(self, **options): super(DObjdumpLexer, self).__in...
stephenrauch/pydal
pydal/adapters/mssql.py
Python
bsd-3-clause
6,306
0.00111
import re from .._compat import PY2, iteritems, integer_types, to_unicode from .._globals import IDENTITY from .base import SQLAdapter from . import adapters, with_connection_or_raise long = integer_types[-1] class Slicer(object): def rowslice(self, rows, minimum=0, maximum=None): if maximum is None: ...
I.match(ruri) if not m: raise Syntax
Error( "Invalid URI string in DAL: %s" % self.uri) user = self.credential_decoder(m.group('user')) if not user: raise SyntaxError('User required') password = self.credential_decoder(m.group('password')) if not password: ...
syci/partner-contact
partner_contact_job_position/__manifest__.py
Python
agpl-3.0
823
0
# Copyright 2014 Pedro M. Baeza <pedro.baeza@tecnativa.com> # Copyright 2015 Antonio Espinosa <antonioea@antiun.com> # Copyright 2015 Jairo Llopis <jairo.llopis@tecnativa.com> # Copyright 2017 David Vidal <david.vidal@tecnativa.com> # License AGPL-3 - See http://www.gnu.org/lic
enses/agpl-3.0.html { "name": "Partner Job Position", "summary": "Categorize job positions for contacts", "version": "13.0.1.0.0", "category": "Customer Relationship Management", "website": "https://github.com/OCA/partner-con
tact", "author": "Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "installable": True, "depends": ["contacts"], "data": [ "security/ir.model.access.csv", "views/res_partner_job_position_view.xml", "views/res_partner_view.xml", ], }
dontnod/weblate
weblate/wladmin/migrations/0006_auto_20190926_1218.py
Python
gpl-3.0
1,322
0
# Generated by Django 2.2.5 on 2019-09-26 12:18 from django.db import migrations, models import weblate.utils.backup class Migration(migrations.Migration): dependencies = [("wladmin", "0005_auto_20190926_1332")] operations = [ migrations.AddField( model_name="backupservice", ...
model_name="backupservice", name="passphrase", field=models.CharField( default=weblate.utils.backup.make_password, max_length=100
), ), migrations.AlterField( model_name="backuplog", name="event", field=models.CharField( choices=[ ("backup", "Backup performed"), ("prune", "Deleted the oldest backups"), ("ini...
Winawer/exercism
python/house/house.py
Python
cc0-1.0
886
0.022573
parts = (('house', 'Jack built'), ('malt', 'lay in'), ('rat', 'ate'), ('cat', 'killed'), ('dog', 'worried'), ('cow with the crumpled horn', 'tossed'), ('maiden all forlorn', 'milked'), ('man all tattered and torn', 'kis...
('farmer sowing his corn', 'kept'), ('horse and the hound and the horn', 'belonged to')) def verse(n)
: return '{}\nthat {}'.format(parts[n][0],parts[n][1]) if n != 0 else '{} that {}'.format(parts[n][0],parts[n][1]) def rhymes(v = 11): if v == 0: return verse(v) else: return verse(v) + ' the ' + rhymes(v-1) def rhyme(): return '\n'.join([ 'This is the ' + rhymes(v) + '.\n' for v in range(12) ])[:-1]
krzyste/ud032
Lesson_2_Problem_Set/06-Processing_Patents/split_data.py
Python
agpl-3.0
1,803
0.004437
#!/usr/bin/env python # -*- coding: utf-8 -*- # So, the problem is that the gigantic file is actually not a valid XML, because # it has several root elements, and XML declarations. # It is, a matter of fact, a collection of a lot of concatenated XML documents. # So, one solution would be to split the file into separate...
ef split_file(filename): # we want you to split the input file into separate files # each containing a single patent. # As a hint - each patent declaration starts with the same line that was causing the error
# The new files should be saved with filename in the following format: # "{}-{}".format(filename, n) where n is a counter, starting from 0. indexes = [] with open(PATENTS, "r") as f: lines = f.readlines() for i, line in enumerate(lines): if "?xml" in line: indexes.append...
ismangil/pjproject
tests/pjsua/scripts-sipp/uas-answer-183-without-to-tag.py
Python
gpl-2.0
138
0
# $Id$ # import inc_const as const PJSUA = ["--null-audio --max-calls=1 --no-tcp $SIPP_URI"] PJSUA_EXPECT
S = [[0, "Audio updated"
, ""]]
hackerspace-silesia/cebulany-manager
setup.py
Python
mit
495
0
import os from setuptools import setup, find_packages here = os.path.abs
path(os.path.dirname(__file__)) with open(os.path.join(here, 'requirements.txt')) as fp: requires = fp.readlines() setup( name='cebulany manager', version='0.0.4', classifiers=[], author='Firem
ark', author_email='marpiechula@gmail.com', url='https://github.com/hackerspace-silesia/cebulany-manager', packages=find_packages(), install_requires=requires, tests_require=requires, )
wndias/bc.repository
plugin.video.superlistamilton/service.py
Python
gpl-2.0
837
0.001195
# -*- coding: utf-8 -*- ''' Genesis Add-on Copyright (C) 2015 lambda This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public Licen
se 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 FITNESS FOR A PARTICULAR PURPOSE...
e along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import xbmc xbmc.executebuiltin('RunPlugin(plugin://plugin.video.superlistamilton/?action=service)')
xhochy/arrow
python/pyarrow/tests/test_ipc.py
Python
apache-2.0
27,938
0
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional in
formation # regarding copyright ownership. The ASF licenses this file # to you under t
he 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 distri...
Azure/azure-linux-automation
remote-scripts/SETUP-INSTALL-PACKAGES.py
Python
apache-2.0
22,500
0.014622
#!/usr/bin/python from azuremodules import * import sys import shutil import time import re import os import linecache import imp import os.path import zipfile current_distro = "unknown" distro_version = "unknown" sudo_password = "" startup_file = "" rpm_links = {} tar_link = {} current_distro = ...
return True else: return False def zypper_package_install(package): if(ZypperPackageInstall(package) == True): return True elif(download_and_install_rpm(package) == True): return True elif(package == 'gcc'): retur...
on2.7" # create /etc/hosts ExecMultiCmdsLocalSudo(["touch /etc/hosts",\ "echo '127.0.0.1 localhost' > /etc/hosts",\ "echo '** modify /etc/hosts successfully **' >> PackageStatus.txt"]) # copy tools to bin folder Run("unzip -d CoreosPreparationTools ./Core...
Sauron754/SpaceScript
old/testEnvironments/SpaceScript/threadingFunctions.py
Python
gpl-3.0
1,480
0.031757
import SpaceScript import multiprocessing from multiprocessing import Process, Queue, Pipe, Lock from SpaceScript import frontEnd from SpaceScript import utility from SpaceScript.frontEnd import terminal from SpaceScript.utility import terminalUtility from SpaceScript.terminal import terminal as terminal from SpaceScri...
ng.Value() guiHold_v = multiprocessing.Value() guiHold_v.value = False termThreadHold_v.value = False subProcess = multiprocessing.Process(targe
t = terminal, args = (0, pullString_q, pushString_q, guiHold_v, termThreadHold_v)) subProcess.start() checkSequence_bool = True while checkSequence_bool: termThreadEventHandler(termThreadHold_v, pullString_q, commandPipe, holdValue_v) termThreadControlHandler(termThreadHold_v, contr...
nive/nive
nive/components/iface/tests/test_iface.py
Python
gpl-3.0
1,151
0.034752
# -*- coding: utf-8 -*- import time import unittest from nive.security import User """ #totest: templates/ definitions.py parts.py root.py search.py view.py """ class IfaceTest:#(unittest.TestCase): # TODO tests def setUp(self): app = App() app.SetConfiguration({"objects": [typedef]}) self.c = IFace(app) ...
rtTrue(self.
c.GetSearchConf("", container=container)) self.assertTrue(self.c.GetSearchConf("default", container=container)) def testF(self): object = Ob() self.assertTrue(self.c.GetTabs(object)) self.assertTrue(self.c.GetShortcuts(object)) def testRedirect(self): object = Ob() self.assertTrue(self.c.GetRedirect...
fidals/refarm-site
tests/ecommerce/tests_forms.py
Python
mit
1,163
0.00086
"""Tests for forms in eCommerce app.""" from django.test import TestCase from ecommerce.forms import OrderForm required_fields = { 'phone': '123456789', 'email': 'valid@email.ru', } invalid_form_email = { 'email': 'clearly!not_@_email', 'phone': '123456789' } no_phone = {'email': 'sss@sss.sss'} cla...
self.assertFalse(form.is_valid()) def test_filled_form_without_required_field(self): """Form is still not valid, if there are some required fiel
ds left unfilled.""" form = OrderForm(data=no_phone) self.assertFalse(form.is_valid()) def test_valid_form(self): """Form is valid, if there all required fields are filled.""" form = OrderForm(data=required_fields) self.assertTrue(form.is_valid()) def test_from_validati...
hgdeoro/pilas
pilasengine/fondos/__init__.py
Python
lgpl-3.0
2,302
0.000435
# -*- encoding: utf-8 -*- # pilas engine: un motor para hacer videojuegos # # Copyright 2010-2014 - Hugo Ruscitti # License: LGPLv3 (see http://www.gnu.org/licenses/lgpl.html) # # Website - http://www.pilas-engine.com.ar from pilasengine import colores from pilasengine.fondos.fondo import Fondo class Fondos(object): ...
f Blanco(self): import blanco return blanco.Blanco(self.pilas) def Fondo(self, imagen=None): import fondo return fondo.Fondo(self.pilas, imagen) def FondoMozaico(self, imagen=None): import fondo_mozaico return fondo_mozaico.FondoMozaico(self.pilas, imagen) ...
amiento_horizontal.DesplazamientoHorizontal(self.pilas)
Elico-Corp/openerp-7.0
sale_bom_split_anglo_saxon/__init__.py
Python
agpl-3.0
158
0
# -*- coding: utf-8
-*- # © 2014 Elico Corp (https://www.elico-corp.com) # Licence AGPL-3.0 or later(htt
p://www.gnu.org/licenses/agpl.html) import invoice
fahadkaleem/CodeWars
8 kyu/python/Dollars and Cents.py
Python
mit
151
0.006623
# https://www.c
odewars.com/kata/55902c5eaa8069a5b4000083 def format_money(amount): # your formatting code here return '${:.2f}'.format(am
ount)
goldhand/onegreek
onegreek/events/urls.py
Python
bsd-3-clause
1,273
0.011783
try: from django.conf.urls import * except ImportError: # django < 1.4 from django.conf.urls.defaults import * from .views import EventDetail, EventList, EventCreate, EventCreateJSON, EventDelete, EventUpdate urlpatterns = patterns("events.views", url(r"^$", EventList.as_view(template...
url(r"^(?P<pk>\d+)/delete/$", EventDelete.as_view(), name='delete'), url(r"^(?P<event_id>\d+)/rsvp/$", 'rsvp_event', name='rsvp'), url(r"^(?P<event_id>\d+)/attend/$", 'attend_event', name='attend'), #url(r"^calendar/(?P<year>\d+)/(?P<mont...
#url(r"^calendar/$", CalendarRedirectView.as_view(), name='calendar-redirect'), )
juanlumn/juanlumn
juanlumn/juanlumn/settings.py
Python
mit
2,719
0
""" Django settings for juanlumn project. Generated by 'django-admin startproject' using Django 1.8.5. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build pat...
) import os BASE_DIR = os.path.dirname(o
s.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '*943gs9_&tpl8nt4^24bk&(^g#9aa^h^z=zacbkn#qwot1v0ok' # SEC...
teoliphant/numba
numba/ad.py
Python
bsd-2-clause
7,869
0.002796
""" Example of how to use byte-code execution technique to trace accesses to numpy arrays. This file demonstrates two applications of this technique: * optimize numpy computations for repeated calling * provide automatic differentiation of procedural code """ import __builtin__ import os import sys import inspect im...
.append(r) if (id(arg1) in self.watcher.svars or id(arg2) in self.watcher.svars): s1 = self.watcher.svars.get(id(arg1), arg1) s2 = self.watcher.svars.get(id(arg2), arg2) self.watcher.svars[id(r)] = s1 + s2
#print 'added sym' def op_BINARY_SUBTRACT(self, i, op, arg): arg2 = self.stack.pop(-1) arg1 = self.stack.pop(-1) r = arg1 - arg2 self.stack.append(r) if (id(arg1) in self.watcher.svars or id(arg2) in self.watcher.svars): s1 = self.watcher.svar...
ChromiumWebApps/chromium
tools/telemetry/telemetry/core/timeline/model.py
Python
bsd-3-clause
7,997
0.009003
# Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. '''A container for timeline-based events and traces and can handle importing raw event data from different sources. This model closely resembles that in t...
empty_trace_importer.EmptyTraceImporter, ins
pector_importer.InspectorTimelineImporter, trace_event_importer.TraceEventTimelineImporter ] class MarkerMismatchError(Exception): def __init__(self): super(MarkerMismatchError, self).__init__( 'Number or order of timeline markers does not match provided labels') class MarkerOverlapError(Exception...
carlosb1/examples-python
architecture/chatserver.py
Python
gpl-2.0
3,299
0.007881
import socket import select import signal import sys from communication import send, receive class ChatServer(object): def sighandler(self,signum,frame): print('Shutting down server...') for o in self.outputs: o.close() self.server.close() def __init__(self, port=3490, back...
) for o in self.outputs: send(o,msg) self.outputs.append(client) elif s == sys.stdin:
junk = sys.stdin.readline() running = 0 else: try: data = receive(s) if data: msg = '\n#['+self.get_name(s)+']>>'+data ...
iamweilee/pylearn
traceback-example-1.py
Python
mit
285
0.014035
''' ÏÂÀý չʾÁË traceback Ä£¿éÔÊÐíÄãÔÚ
³ÌÐòÀï´òÓ¡Òì³£µÄ¸ú×Ù·µ»Ø(Traceback)ÐÅÏ¢, ÀàËÆÎ´²¶»ñÒ쳣ʱ½âÊÍ
Æ÷Ëù×öµÄ. ''' # ×¢Òâ! µ¼Èë traceback »áÇåÀíµôÒ쳣״̬, ËùÒÔ # ×îºÃ±ðÔÚÒì³£´¦Àí´úÂëÖе¼Èë¸ÃÄ£¿é import traceback try: raise SyntaxError, "example" except: traceback.print_exc()
bertptrs/adventofcode
2019/aoc2019/day13.py
Python
mit
1,338
0
import statistics from typing import TextIO, Tuple, Dict from aoc2019.intcode import Computer, read_program def render_screen(computer: Computer, screen: Dict[Tuple[int, int], int]): while computer.output: x = computer.output.popleft() y = computer.output.popleft() val = computer.output.p...
finished = True excep
t IndexError: # Waiting for input pass render_screen(computer, screen) ball_x = next(x for x, y in screen if screen[x, y] == 4) paddle_x = statistics.mean(x for x, y in screen if screen[x, y] == 3) if ball_x < paddle_x: computer.input.append(-1) ...
WarrenWeckesser/scipy
scipy/linalg/tests/test_lapack.py
Python
bsd-3-clause
116,267
0.000017
# # Created by: Pearu Peterson, September 2002 # import sys import subprocess import time from functools import reduce from numpy.testing import (assert_equal, assert_array_almost_equal, assert_, assert_allclose, assert_almost_equal, assert_array_equal) import pyt...
hs = b1.shape[1] else: nrhs = 1 # Request of sizes lwork = _compute_lwork(gels_lwork, m
, n, nrhs) lqr, x, info = gels(a1, b1, lwork=lwork) assert_allclose(x[:-1], np.array([-14.333333333333323, 14.999999999999991], dtype=dtype), rtol=25*np.finfo(dtype).eps) ...
uber-common/deck.gl
bindings/pydeck/pydeck/types/string.py
Python
mit
531
0
from functools import total_ordering
from .base import PydeckType @total_ordering class String(PydeckType): """Indicate a string value in pydeck Parameters --------
-- value : str Value of the string """ def __init__(self, s: str, quote_type: str = ""): self.value = f"{quote_type}{s}{quote_type}" def __lt__(self, other): return str(self) < str(other) def __eq__(self, other): return str(self) == str(other) def __repr__(se...
pantsbuild/pants
src/python/pants/backend/python/macros/poetry_requirements_caof.py
Python
apache-2.0
3,874
0.003098
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import os from typing import Iterable, Mapping from packaging.utils import canonicalize_name as canonicalize_project_name from pants.backend.python.ma...
quirement. This setting is important for Pants to know how to convert your import statements back into your dependencies. For example: poetry_requirements( module_mapping={ "ansicolors": ["colors"], "setuptools": ["pkg_resources"], } ) """
def __init__(self, parse_context): self._parse_context = parse_context def __call__( self, *, source: str = "pyproject.toml", module_mapping: Mapping[str, Iterable[str]] | None = None, type_stubs_module_mapping: Mapping[str, Iterable[str]] | None = None, over...
jamespcole/home-assistant
homeassistant/components/googlehome/__init__.py
Python
apache-2.0
3,612
0
"""Support Google Home units.""" import logging import asyncio import voluptuous as vol from homeassistant.const import CONF_DEVICES, CONF_HOST from homeassistant.helpers import discovery import homeassistant.helpers.config_validation as cv from homeassistant.helpers.aiohttp_client import async_get_clientsession _LOG...
hass.async_create_task( discovery.async_load_platform( hass, 'device_tracker', DOMAIN, device, config)) if device[CONF_TRACK_ALARMS]: hass.async_create_task( discovery.async_load_platform( hass, 'sensor', DOMAIN, devic...
Google Home Client.""" self.hass = hass self._connected = None async def update_info(self, host): """Update data from Google Home.""" from googledevices.api.connect import Cast _LOGGER.debug("Updating Google Home info for %s", host) session = async_get_clientsession...
Azure/azure-sdk-for-python
sdk/agfood/azure-mgmt-agfood/azure/mgmt/agfood/aio/__init__.py
Python
mit
588
0.003401
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
ncorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from ._azure_ag_food_platform_rp_service import AzureAgFoodP
latformRPService __all__ = ['AzureAgFoodPlatformRPService']
ocwc/ocwc-data
search/data/management/commands/courses.py
Python
apache-2.0
3,372
0.005635
# -*- coding: utf-8 -*- from optparse import make_option from django.core.management.base import BaseCommand from messytables import XLSTableSet, headers_guess, headers_processor, offset_processor from data.models import Source, Course, MerlotCategory class Command(BaseCommand): help = "Utilities to merge our da...
Health Science': 'Health Sciences', 'Management': 2248, 'Online Instruction': 'Hybrid and Online Course Development', 'Early Childhood': ['Career Counseling and Services', 'Childhood and Adolescence'], 'Law, Legal': 'Law', 'Psychology': 'Psychology', ...
', 'Professionalism': 'Personal Development' } source = Source.objects.get(pk=source_id) fh = open(filename, 'rb') table_set = XLSTableSet(fh) row_set = table_set.tables[0] offset, headers = headers_guess(row_set.sample) row_set.register_processor(h...
MBoustani/Geothon
Spatial Analyst Tools/zonal_statistics.py
Python
apache-2.0
2,677
0.007471
#!/usr/bin/env python ''' Project:
Geothon (https://github.com/MBoustani/Geothon) File: Vector/zonal_statistics.py Description: This code calculates statistics of GeoTIFF with polygon Shapefile Author: Maziyar Boustani (github.com/MBoustani) ''' import numpy as n
p try: import ogr except ImportError: from osgeo import ogr try: import gdal except ImportError: from osgeo import gdal from gdalconst import GA_ReadOnly gtif_file = "/path/to/tif" gtif_dataset = gdal.Open(gtif_file, GA_ReadOnly) shp_file = '/path/to/shp' driver = ogr.GetDriverByName('ESRI Shap...
HaseloffLab/PartsDB
partsdb/tools/CoordinateMapper/testCoordinateMapper.py
Python
mit
13,945
0.001004
#!/usr/bin/python from functools import wraps import unittest from CoordinateMapper import CoordinateMapper from MapPositions import GenomePositionError from MapPositions import ProteinPositionError from MapPositions import CDSPosition, CDSPositionError from SeqFeature import FeatureLocation, SeqFeature from Bio.SeqR...
actual, c) @two_dialects def testGoodOutside(self): """CDSPosition should match good outside-CDS values""" for c_args, c in zip(c_outside_tups, c_outside[self.dialect]): actual = CDSPosition.from_anchor(*c_args).to(self.dialect) self.assertEqual(actual, c) def testE...
f): """CDSPosition should test equal with same args""" for args in c_intron_tups: CPos = CDSPosition.from_anchor self.assertEqual(CPos(*args), CPos(*args)) self.assertEqual(str(CPos(*args)), str(CPos(*args))) #def testEqualDialects(self): #for c_pos in c_outs...
miquelramirez/lwaptk-v2
external/fd/pddl/conditions.py
Python
gpl-3.0
13,297
0.007596
from __future__ import print_function from . import pddl_types def parse_condition(alist): condition = parse_condition_aux(alist, False) # TODO: The next line doesn't appear to do anything good, # since uniquify_variables doesn't modify the condition in place. # Conditions in actions or axioms are uni...
ef negate(self):
return Truth() class Truth(ConstantCondition): def to_untyped_strips(self): return [] def instantiate(self, var_mapping, init_facts, fluent_facts, result): pass def negate(self): return Falsity() class JunctorCondition(Condition): # Defining __eq__ blocks inheritance of __h...
lmazuel/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2015_06_15/models/virtual_network_paged.py
Python
mit
962
0.00104
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under
the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # ------------------------------------------------------
-------------------- from msrest.paging import Paged class VirtualNetworkPaged(Paged): """ A paging container for iterating over a list of :class:`VirtualNetwork <azure.mgmt.network.v2015_06_15.models.VirtualNetwork>` object """ _attribute_map = { 'next_link': {'key': 'nextLink', 'type': 'st...
nimble0/plover
plover/oslayer/processlock.py
Python
gpl-2.0
2,400
0.002083
# Copyright (c) 2012 Hesky Fisher # See LICENSE.txt for details. # # processlock.py - Cross platform global lock to ensure plover only runs once. """Global lock to ensure plover only runs once.""" import sys class LockNotAcquiredException(Exception): pass if sys.platform.startswith('win32'): from ctypes ...
hostname = os.uname()[1] else: import socket hostname = socket.gethostname() lock_file_name = os.path.expanduser( '~/.plover-lock-%s-%s' % (hostname, display)) self.fd = open(lock_file_name, 'w') def acquire(sel...
ept IOError as e: raise LockNotAcquiredException(str(e)) def release(self): try: fcntl.flock(self.fd, fcntl.LOCK_UN) except: pass def __del__(self): self.release() try: self.fd.close() ...
sein-tao/trash-cli
unit_tests/test_storing_paths.py
Python
gpl-2.0
1,446
0.009682
from trashcli.put import TrashDirectoryForPut from nose.tools import assert_equals from mock import Mock class TestHowOriginalLocationIsStored: def test_for_absolute_paths(self): fs = Mock() self.dir = TrashDirectoryForPut('/volume/.Trash', '/volume', fs = fs) self.dir.store_absolute_paths(...
tore_relative_paths() self.assert_path_for_trashinfo_is('/file' , '/file') self.assert_path_for_trashinfo_is('/file' , '/d
ir/../file') self.assert_path_for_trashinfo_is('/outside/file' , '/outside/file') self.assert_path_for_trashinfo_is('file' , '/volume/file') self.assert_path_for_trashinfo_is('dir/file' , '/volume/dir/file') def assert_path_for_trashinfo_is(self, expected_value, file_to_be_tra...
drewokane/xray
xarray/backends/common.py
Python
apache-2.0
7,619
0.000263
import numpy as np import itertools import logging import time import traceback from collections import Mapping from ..conventions import cf_encoder from ..core.utils import FrozenOrderedDict from ..core.pycompat import iteritems, dask_array_type, OrderedDict # Create a logger object, but don't add any handlers. Leav...
self.sources.append(source) self.targets.append(target) else: target[...] = source def sync(self): if self.sources: import dask.array as da da.store(self.source
s, self.targets) self.sources = [] self.targets = [] class AbstractWritableDataStore(AbstractDataStore): def __init__(self, writer=None): if writer is None: writer = ArrayWriter() self.writer = writer def set_dimension(self, d, l): # pragma: no cover ...
jrdurrant/vision
torchvision/datasets/mnist.py
Python
bsd-3-clause
12,198
0.003771
from __future__ import print_function import torch.utils.data as data from PIL import Image import os import os.path import errno import numpy as np import torch import codecs class MNIST(data.Dataset): """`MNIST <http://yann.lecun.com/exdb/mnist/>`_ Dataset. Args: root (string): Root directory of da...
it is not downloaded again.
transform (callable, optional): A function/transform that takes in an PIL image and returns a transformed version. E.g, ``transforms.RandomCrop`` target_transform (callable, optional): A function/transform that takes in the target and transforms it. """ urls = [ 'http:...