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 |
|---|---|---|---|---|---|---|---|---|
antb/TPT----My-old-mod | src/python/stdlib/test/test_shutil.py | Python | gpl-2.0 | 29,086 | 0.001341 | # Copyright (C) 2003 Python Software Foundation
import unittest
import shutil
import tempfile
import sys
import stat
import os
import os.path
from os.path import splitdrive
from distutils.spawn import find_executable, spawn
from shutil import (_make_tarball, _make_zipfile, make_archive,
register_ar... | ove
# a file in the directory, so the first time through
# func is os.remove.
# However, some Linux machines running ZFS on
# FUSE experienced a failure earlier in the process
# at os.listdir. The first failure may legally
# be either.
if self.errorState == 0:
... | f.assertEqual(arg, self.childpath)
else:
self.assertIs(func, os.listdir,
"func must be either os.remove or os.listdir")
self.assertEqual(arg, TESTFN)
self.assertTrue(issubclass(exc[0], OSError))
self.errorState = 1
... |
arrabito/DIRAC | Resources/LogBackends/MessageQueueBackend.py | Python | gpl-3.0 | 1,639 | 0.007322 | """
Message Queue wrapper
"""
__RCSID__ = "$Id$"
from DIRAC.FrameworkSystem.private.standardLogging.Handler.MessageQueueHandler import MessageQueueHandler
from DIRAC.Resources.LogBackends.AbstractBackend import AbstractBackend
f | rom DIRAC.FrameworkSystem.private.standardLogging.Formatter.JsonFormatter import JsonFormatter
class MessageQueueBackend(AbstractBackend):
"""
MessageQueueBackend is used to create an abstraction of the handler and the formatter concepts from logging.
Here, we have:
- MessageQueueHandler: which is a custom ... | ivate/standardlogging/Handler
- BaseFormatter: is a custom Formatter object, created for DIRAC in order to get the appropriate display.
You can find it in FrameworkSystem/private/standardLogging/Formatter
"""
def __init__(self):
"""
Initialization of the MessageQueueBackend
"""
super(Messag... |
ghwatson/SpanishAcquisitionIQC | spacq/devices/keithley/mock/mock_voltagesource230.py | Python | bsd-2-clause | 1,017 | 0.021632 | import random
from ...mock.mock_abstract_device import MockAbstractDevice
from ..voltagesource230 import voltageSource230
"""
Mock Sample ABC1234
"""
class Mockvoltag | eSource230(MockAbstractDevice, voltageSource230):
"""
Mock interface for the Sample ABC1234.
"""
def __init__(self, *args, **kwargs):
self.mocking = voltageSource230
MockAbstractDevice.__init__(self, *args, **kwargs)
def _reset(self):
self.mock_state['setting'] = 'default value'
def write(self, message,... | lt = self.mock_state['setting']
else:
self.mock_state['setting'] = args
done = True
elif cmd[0] == 'read' and query:
result = '-1.{0:04d}0000E-02'.format(random.randint(0, 9999))
done = True
MockAbstractDevice.write(self, message, result, done)
name = '230 Programmable Voltage Source'
im... |
SystemsGenetics/KINC | scripts/make-input-data.py | Python | mit | 1,349 | 0.021497 | import argparse
import pandas as pd
import sklearn.datasets
if __name__ == "__main__":
# parse command-line arguments
parser = argparse.ArgumentParser(description="Create a synthetic gene expression dataset")
parser.add_argument("--n-samples", help="number of samples", type=int, default=100)
parser.add_argument(... | = args.n_genes // 10
n_redundant = args.n_genes - n_informative
X, y = sklearn.datasets.make_classification(args.n_samples, args.n_genes, n_informative=n_informative, n_redundant=n_redundant, n_classes=args.n_classes)
| # initialize gene names, sample names
X_samples = ["sample-%08d" % i for i in range(args.n_samples)]
X_genes = ["gene-%06d" % i for i in range(args.n_genes)]
# initialize dataframe
X = pd.DataFrame(X, index=X_samples, columns=X_genes)
# transpose dataset if specified
if args.transpose:
X = X.T
# save datas... |
eschnett/SimulationIO | python-read-h5py.py | Python | lgpl-3.0 | 1,069 | 0.002806 | #! /usr/bin/env python
from __future__ import print_function
from math import *
import sys
import numpy as np
import h5py
# Read metadata and data directly
filename = "python-example.s5"
file = h5py.File(filename, 'r')
rsum = 0.0
rsum2 = 0.0
rmin = sys.float_info.max
rmax = -sys.float_info.max
rcount = 0.0
ngrid... | iscretefieldblocks'][discretefieldblockname]
discretefieldblockcom | ponent = discretefieldblock['discretefieldblockcomponents']['scalar']
data = discretefieldblockcomponent['data']
ngrids += 1
for val in np.nditer(data):
rsum += val
rsum2 += val*val
rmin = min(rmin, val)
rmax = max(rmax, val)
rcount += 1.0
ravg = rsum / rcount
rnorm... |
aws-samples/chalice-workshop | code/media-query/06-web-api/app.py | Python | apache-2.0 | 1,443 | 0 | import os
import boto3
from chalice import Chalice
from chalicelib import db
from chalicelib import rekognition
app = Chalice(app_name='media-query')
_MEDIA_DB = None
_REKOGNITION_CLIENT = None
_SUPPORTED_IMAGE_EXTENSIONS = (
'.jpg',
'.png',
)
def get_media_db():
global _MEDIA_DB
if _MEDIA_DB is No... | l _REKOGNITION_CLIENT
if _REKOGNITION_CLIENT is None:
_REKOGNITION_CLIENT = rekognition.RekognitonClient(
boto3.client('rekognition'))
return _REKOGNITION_CLIENT
@app.on_s3_event(bucket=os.environ['MEDIA_BUCKET_NAME'],
events=['s3:ObjectCreated: | *'])
def handle_object_created(event):
if _is_image(event.key):
_handle_created_image(bucket=event.bucket, key=event.key)
@app.on_s3_event(bucket=os.environ['MEDIA_BUCKET_NAME'],
events=['s3:ObjectRemoved:*'])
def handle_object_removed(event):
if _is_image(event.key):
get_medi... |
ksmit799/Toontown-Source | toontown/minigame/PatternGameGlobals.py | Python | mit | 242 | 0 | import MinigameGlobals
INITIAL_ROUND_LENGTH = 2
ROUND_LENGTH_INCREMENT = 2
NUM_ROUNDS = 4
TOONTOWN_WORK = 1
InputTime = 10
ClientsReadyTimeout = 5 + MinigameGlobals.latencyTolerance
InputTimeout = | InputTime + MinigameGlobals.laten | cyTolerance
|
intelligenia/django-cmsutils | cmsutils/management/commands/freshdb.py | Python | lgpl-3.0 | 553 | 0.001808 | """
put in your project's management/ | commands/freshdb.py
"""
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = "Drops and re-creates the database"
def handle(self, *args, **options):
from django.db import connection
from django.conf import settings
c = connection.cursor()
c.ex... | BASE_NAME)
c.execute("CREATE DATABASE " + settings.DATABASE_NAME)
print 'Created new database: %s' % settings.DATABASE_NAME
c.close()
|
kcsry/infotv | infotv_test/tests/test_datum.py | Python | mit | 1,746 | 0.002291 | import json
import uuid
import pytest
from django.test.utils import override_settings
from django.utils.encoding import force_str
from infotv.models import Datum
from infotv.views import InfoTvView
@pytest.mark.django_db
def test_create_ | and_retrieve_unparsed_datum(rf):
response = InfoTvView.as_view()(
request=rf.post("/", {"datum": | "hello", "value": "world"}),
event="dsfargeg"
)
assert not json.loads(force_str(response.content))["parsed"]
assert Datum.objects.get(event_slug="dsfargeg", key="hello").value == "world"
response = InfoTvView.as_view()(
event="dsfargeg",
request=rf.get("/", {"action": "get_deck"... |
statsmodels/statsmodels | statsmodels/tsa/tests/test_x13.py | Python | bsd-3-clause | 1,501 | 0 | import pandas as pd
import pytest
from statsmodels.datasets import co2, macrodata
from statsmodels.tsa.x13 import (
_find_x12,
x13_arima_analysis,
x13_arima_select_order,
)
x13path = _find_x12()
pytestmark = pytest.mark.skipif(x13path is False,
reason='X13/X12 not availabl... | e is deferred object
if not isinstance(monthly_data, (pd.DataFrame, pd.Series)):
monthly_data = monthly_data.mean()
monthly_start_data = dta.resample('MS')
if not isinstance(monthly_start_data, (pd.DataFrame, pd.Series)):
monthly_start_data = monthly_start_data.mean()
data = (monthly_data, monthly_start_data,... | ',
'series', 'dataframe')
@pytest.fixture(params=data, ids=ids)
def dataset(request):
return request.param
def test_x13_arima_select_order(dataset):
res = x13_arima_select_order(dataset)
assert isinstance(res.order, tuple)
assert isinstance(res.sorder, tuple)
@pytest.mark.matplotlib
def tes... |
nextalk/webim-for-django | django_webim/views.py | Python | mit | 172 | 0.011628 | #!/usr/bin/ | env python
#coding: utf-8
from django.shortcuts import render
from django.http import HttpResponse
def home(request):
return render(request, 'i | ndex.html')
|
laosunhust/saleor | saleor/product/utils.py | Python | bsd-3-clause | 424 | 0 | def get_attributes_display_map(variant, attributes):
display = {}
for attribute in attributes:
value = variant.get_attribute(attribute.pk)
if value:
choices = {a.pk: a for a in attribute.values.all()}
| attr = choices.get(value)
if attr:
displ | ay[attribute.pk] = attr
else:
display[attribute.pk] = value
return display
|
svohara/proximityforest | evaluation/WACV2013/plotResults.py | Python | gpl-3.0 | 2,576 | 0.012422 | '''
Created on Nov 29, 2012
@author: Stephen O'Hara
Module with plotting code
'''
import pylab as pl
import cPickle
import os
import math
def loadRes_varyingTrees(datadir=".", fn="SIFT_10K_5trials_VaryingTrees.p"):
'''
Loads pickle files which store the trial details for the varyingNumTrees() experiment.
... | d = loadRes_varyingTrees(datadir, fn)
plotRes_varyingTrees(d, titles[ | i], max_correct=3000, show=False)
pl.subplots_adjust(bottom=.15)
pl.show()
if __name__ == '__main__':
pass |
LucaClaessens/Analogy | Printer/Publication_Maker.py | Python | gpl-3.0 | 7,901 | 0.04202 | from __future__ import division
import socket, MySQLdb
from PIL import Image
from random import randint, randrange
from ConfigParser import SafeConfigParser
parser = SafeConfigParser()
parser.read('../analogy_config.ini')
db = MySQLdb.connect(
host = parser.get('database','host'),
user = parser.get('database... | e:{}\nItems in pool:{}\nBalance:{}\n'.format(self.FREE,self.PUB, self.POOL, CURRENT_BALANCE )
# in case of lot of free content, print premium
if CURRENT_ | BALANCE < BALANCE:
_s = "SELECT COUNT(sentence_data) FROM source_material WHERE score > {}".format(SBMAX);
self.pref_premium = True
#otherwise print free content
else :
_s = "SELECT COUNT(sentence_data) FROM source_material WHERE score < {}".format(SBMIN);
self.pref_premium = False
q... |
danpoland/pyramid-restful-framework | tests/test_decorartors.py | Python | bsd-2-clause | 768 | 0.002604 | from unittest import TestCase
from pyramid_restful.decorators import list_route, detail_route
class DecoratorTests(TestCase):
def test_list_route(self):
@list_route(methods=['GET'], url_path='my-list-route')
def my_list_route():
| pass
assert my_list_route.bind_to_methods == ['GET']
assert my_list_route.detail == False
assert my_list_route.kwargs == {'url_path': 'my-list-route'}
def test_detail_route(self):
@detail_route(methods=['PUT'], url_path='my-detail-route')
def my_detail_route():
... | _methods == ['PUT']
assert my_detail_route.detail == True
assert my_detail_route.kwargs == {'url_path': 'my-detail-route'}
|
phobson/seaborn | doc/sphinxext/gallery_generator.py | Python | bsd-3-clause | 10,385 | 0.000481 | """
Sphinx plugin to run example scripts and create a gallery page.
Lightly modified from the mpld3 project.
"""
from __future__ import division
import os
import os.path as op
import re
import glob
import token
import tokenize
import shutil
from seaborn.external import six
import matplotlib
matplotlib.use('Agg')
im... | ng()
with open(filename, "r") as fid:
self.filetext = fid.read()
ou | tfilename = op.join(target_dir, self.rstfilename)
# Only actually run it if the output RST file doesn't
# exist or it was modified less recently than the example
if (not op.exists(outfilename)
or (op.getmtime(outfilename) < op.getmtime(filename))):
self.exec_file()
... |
Doveps/bassist | tests/parser/test_processes_stdout.py | Python | mit | 5,195 | 0.006737 | # Copyright (c) 2015 Kurt Yoder
# See the file LICENSE for copying permission.
import pytest
import bassist.parser.log_file.processes_stdout
good_processes_text = ''' PID PPID UID GID CGROUP F NI PRI TT COMMAND
1 0 0 0 - 4 0 19 ? /s... | ord: " -u root /bin/sh -c 'echo SUDO-SUCCESS-auksipcc | nwlfnchfnplywdkzysxjlucb; LANG=C LC_CTYPE=C /usr/bin/python /home/vagrant/.ansible/tmp/ansible-tmp-1419040447.65-238273699227159/command; rm -rf /home/vagrant/.ansible/tmp/ansible-tmp-1419040447.65-238273699227159/ >/dev/null 2>&1'
1530 1528 0 900 2:name=systemd:/user/900.us 4 0 19 pts/2 sudo -H -S -p [su... |
ARTFL-Project/PhiloLogic5 | python/philologic/OHCOVector.py | Python | gpl-3.0 | 12,529 | 0.002155 | #!/usr/bin/env python3
import sys
from json import dumps
### CompoundStack is the class to use for all parsers.
class ParallelRecord(object):
"""ParallelRecord tracks objects that are parallel to a primary record stack. Used by CompoundStack."""
def __init__(self, type, name, id):
self.type = typ... | ck."""
def __init__(
self,
types,
page,
docid=0,
out=None,
ref="",
line="",
graphic="",
factory=CompoundRecord,
p_factory=ParallelRecord,
):
self.stack = NewStack(types[:], out, factory)
self.out = out
self.... | p = None
self.ref = ref
self.current_ref = None
self.line = line
self.current_line = None
self.graphic = graphic
self.current_graphic = None
self.p = 0
self.r = 0
self.l = 0
self.g = 0
self.p_factory = p_factory
def __getitem__... |
mmitre/conf-central | Lesson_2/00_Conference_Central/models.py | Python | gpl-3.0 | 3,715 | 0.007537 | #!/usr/bin/env python
"""models.py
Udacity conference server-side Python App Engine data & ProtoRPC models
$Id: models.py,v 1.1 2014/05/24 22:01:10 wesc Exp $
created/forked from conferences.py by wesc on 2014 may 24
"""
__author__ = 'wesc+api@google.com (Wesley C | hun)'
import httplib
import endpoints
from protorpc import messages
from google.appengine.ext import ndb
|
class StringMessage(messages.Message):
"""StringMessage-- outbound (single) string message"""
data = messages.StringField(1, required=True)
class Profile(ndb.Model):
"""Profile -- User profile object"""
displayName = ndb.StringProperty()
mainEmail = ndb.StringProperty()
teeShirtSize = ndb.Str... |
tatiana/invesalius | invesalius/gui/dicom_preview_panel.py | Python | gpl-2.0 | 27,079 | 0.003804 | #--------------------------------------------------------------------------
# Software: InVesalius - Software de Reconstrucao 3D de Imagens Medicas
# Copyright: (C) 2001 Centro de Pesquisas Renato Archer
# Homepage: http://www.softwarepublico.gov.br
# Contact: invesalius@cti.gov.br
# License: GNU ... | e)
#self.title.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeave)
#self.subtitle.Bind(wx.EVT_LEAVE_WINDOW, self | .OnLeave)
self.Bind(wx.EVT_LEFT_DOWN, self.OnSelect)
self.title.Bind(wx.EVT_LEFT_DOWN, self.OnSelect)
self.subtitle.Bind(wx.EVT_LEFT_DOWN, self.OnSelect)
self.image_viewer.Bind(wx.EVT_LEFT_DOWN, self.OnSelect)
#self.Bind(wx.EVT_SIZE, self.OnSize)
def SetDicomToPreview(self... |
iddqd1/django-cms | cms/test_utils/project/mti_pluginapp/models.py | Python | bsd-3-clause | 935 | 0.002139 | # -*- coding: utf-8 -*-
from django.db import models
from cms.models import CMSPlugin
class TestPluginAlphaModel(CMSPlugin):
"""
Nothing interesting here, move along.
"""
alpha = models.CharField('name', blank=False, default='test plugin alpha', max | _length=32)
def get_add_url(self):
return '/admin/custom/view/'
def get_edit_url(self):
return '/admin/custom/view/%s/' % self.pk |
def get_move_url(self):
return '/admin/custom/move/'
def get_delete_url(self):
return '/admin/custom/delete/%s/' % self.pk
def get_copy_url(self):
return '/admin/custom/copy/'
class TestPluginBetaModel(TestPluginAlphaModel):
"""
NOTE: This is the subject of our test. A ... |
adangtran87/gbf-weap | tests/test_magna_class.py | Python | mit | 1,941 | 0.008243 | import context
import unittest
from weapon import *
class TestMagnaClass(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def _create_weapon(self, name, damage, weapon_skill, skill_level):
return WeaponMagna(**{
'name':name,
... | .140, 0.145]
for skill_level in range(0,15):
weapon = self._create_weapon(skill_level, 1000, 'medium', skill_level+1)
| self.assertEqual(weapon.multiplier, pass_mult[skill_level])
def test_magna_large_multiplier(self):
pass_mult = [0.06, 0.07, 0.08, 0.09, 0.10,
0.11, 0.12, 0.13, 0.14, 0.15,
0.156, 0.162, 0.168, 0.174, 0.18]
for skill_level in range(0,15):
we... |
pedroma/python-feedly | tests/__init__.py | Python | lgpl-3.0 | 44 | 0.022727 | from test | _methods import | TestBaseFeedlyClass |
MartienLagerweij/aidu | aidu_gui/src/aidu_gui/add_delivery.py | Python | mit | 3,609 | 0.004156 | #!/usr/bin/env python
__author__ = 'Rolf Jagerman'
from PySide import QtGui
import os
from authentication import AuthenticationListener, AuthenticationClient
from loadui import loadUi
from config import UI_DIRECTORY
from drawers import Drawers
from users import User
from locations import Location
class AddDelivery(Q... | h.join(UI_DIRECTORY, 'add_delivery.ui'), self)
self.cancel_button.clicked.connect(self.cancel)
self.save_button.clicked.connect(self.place)
self.deliveries = {}
self.sender = None
self.drawer_id = '1'
for location in Location.get_locations():
self.location_co... | ySide.QtGui import QComboBox
#test = QComboBox()
#self.recipient_combobox.addItems(User.get_users())
#self.location_combobox.addItems(Location.get_locations())
AuthenticationClient.add_listener(self)
def show(self, *args, **kwargs):
super(AddDelivery, self).show()
s... |
kubaszostak/gdal-dragndrop | osgeo/apps/Python27/Lib/site-packages/numpy/polynomial/tests/test_classes.py | Python | mit | 20,056 | 0.000848 | """Test inter-conversion of different polynomial classes.
This tests the convert and cast methods of all the polynomial classes.
"""
from __future__ import division, absolute_import, print_function
import operator as op
from numbers import Number
import pytest
import numpy as np
from numpy.polynomial import (
P... | domain=[1, 2], window=[2, 3])
p4 = Poly([1, 2, 3], domain=[0, 1], window=[1 | , 2])
assert_(p1 == p1)
assert_(not p1 == p2)
assert_(not p1 == p3)
assert_(not p1 == p4)
def test_not_equal(Poly):
p1 = Poly([1, 2, 3], domain=[0, 1], window=[2, 3])
p2 = Poly([1, 1, 1], domain=[0, 1], window=[2, 3])
p3 = Poly([1, 2, 3], domain=[1, 2], window=[2, 3])
p4 = Poly([1, 2, ... |
edx/i18n-tools | tests/test_dummy.py | Python | apache-2.0 | 3,895 | 0.002301 | """Tests of i18n/dummy.py"""
import ddt
from polib import POEntry
from i18n import dummy
from . import I18nToolTestCase,MOCK_APPLICATION_DIR
@ddt.ddt
class TestDummy(I18nToolTestCase):
"""
Tests functionality of i18n/dummy.py
"""
def setUp(self):
| super().setUp()
self.converter = dummy.Dummy()
def assertUnicodeEquals(self, str1, str2):
"""Just like assertEquals, but doesn't put Unicode into the fail message.
E | ither nose, or rake, or something, deals very badly with unusual
Unicode characters in the assertions, so we use repr here to keep
things safe.
"""
self.assertEquals(
str1, str2,
"Mismatch: %r != %r" % (str1, str2),
)
@ddt.data(
("sign in",
... |
hellflame/qiniu_manager | qiniuManager/test/progress_test.py | Python | mit | 1,900 | 0.000556 | # coding=utf8
import time
import ra | ndom
import unittest
from qiniuManager.progress import *
class Pro(object):
def __init__(self):
self.progressed = 0
self.total = 100
self.title = 'test'
self.chunked = False
self.chunk_recv | ed = 0
self.start = time.time()
@bar(100, '=')
def loader(self):
self._normal_loader()
self.title = "固定长度"
@bar(fill='x')
def loader_x(self):
self._normal_loader()
self.title = "x"
@bar()
def auto_loader(self):
self._normal_loader()
self... |
brianwc/juriscraper | opinions/united_states/state/texapp_11.py | Python | bsd-2-clause | 360 | 0.013889 | # Scraper for Texas 11th Court of Appeals
#CourtID: texapp11
#Court Short | Name: TX
#Author: Andrei Chelaru
#Reviewer: mlr
#Date: 2014-07-10
from juriscraper.opinions.united_states.state import tex
class Site(tex.Site):
def __init__(self):
super(Site, self).__init__()
self.court_id = | self.__module__
self.court_name = 'capp_11'
|
dhh1128/own_fix | param.py | Python | apache-2.0 | 5,815 | 0.003439 | import re
array_spec_pat = re.compile('.*(\[^]]\])$')
const_prefix_pat = re.compile('^const ([a-zA-Z0-9_]+)(.*)$')
moab_type_pat = re.compile('.*\Wm[a-z_0-9]+_t$')
datatype_names = 'int|short|long|double|float|char|bool'.split('|')
moab_struct_naming_pat = re.compile(r'm([a-z_]+)_t(?=$|\W)')
moab_common_out_pat = re.c... | # Same | for **.
if i > -1 and i < dt.rfind('*'):
return False
return True
def is_const(self):
return 'const' in self.decl
def get_pivot_point(self):
i = self.data_type.find('*')
j = self.data_type.find('&')
if i > -1:
if j > -1:
... |
Johnetordoff/osf.io | api/draft_registrations/views.py | Python | apache-2.0 | 8,601 | 0.00186 | from rest_framework import permissions as drf_permissions, exceptions
from framework.auth.oauth_scopes import CoreScopes
from api.base import permissions as base_permissions
from api.base.pagination import DraftRegistrationContributorPagination
from api.draft_registrations.permissions import (
DraftContributorDet... | n checking on the draft registration.
"""
# Overrides DraftMixin
def check_branched_from(self, draft):
# We do not have to check the branched_from relationship. node_id is not a kwarg
return
# Overrides DraftMixin
def check_resource_permissions(self, resource):
| # Checks permissions on draft_registration, regardless of whether or not
# draft_registration is branched off of a node
return self.check_object_permissions(self.request, resource)
class DraftRegistrationList(NodeDraftRegistrationsList):
permission_classes = (
IsContributorOrAdminContr... |
wxgeo/geophar | wxgeometrie/modules/exercice_equations_droites/barre_outils_ex_eq_dte.py | Python | gpl-2.0 | 2,243 | 0.004027 | # -*- coding: utf-8 -*-
##--------------------------------------##
# Barre d'outils pour la géométrie #
##--------------------------------------##
# WxGeometrie
# Dynamic geometry, graph plotter, and more for french mathematic teachers.
# Copyright (C) 2005-2013 Nicolas Pourcelot
... | tils pour construire les droites (dans le bon ordre).<br>"
"<i>Remarque :</i> pour créer une droite, il vous faudra deux points à coordonnées <i>entières</i>."))
self.sizer.addStretch()
self.setLayou | t(self.sizer)
self.adjustSize()
def creer_boutons(self):
self.add("F1", ("Pointeur", "fleche4", "Déplacer ou modifier un objet.", self.curseur)).select()
self.add("F3", ("Droite", "droite2", "Créer une droite.", self.droite))
self.add("F4", ("Gommer", "gomme", "Supprimer des objets... |
grap/OpenUpgrade | openerp/addons/openupgrade_records/lib/apriori.py | Python | agpl-3.0 | 931 | 0 | """ Encode any known changes to the database here
to help the matching process
"""
renamed_modules = {
'base_calendar': 'calendar',
'mrp_jit': 'procurement_jit',
'project_mrp': 'sale_service',
# OCA/account-invoicing
'invoice_validation_wkfl': 'account_invoice_validation_workflow',
'account_inv... | CA/bank-statement-import
'account_banking': 'account_bank_statement_import',
'account_banking_camt': 'account_bank_statement_import_camt',
'account_banking_mt940':
'account_bank_statement_import_mt940_base',
'account_banking_nl_ing_mt940':
'account_bank_statement_import_mt940_nl_i | ng',
'account_banking_nl_rabo_mt940':
'account_bank_statement_import_mt940_nl_rabo',
# OCA/product-attribute
'product_images': 'product_multi_image',
}
renamed_models = {
}
|
unbit/davvy | davvy/models.py | Python | mit | 4,165 | 0.00024 | from django.db import models
from django.contrib.auth.models import User, Group
import uuid
import davvy
import davvy.exceptions
from lxml import etree
# Create your models here.
class Resource(models.Model):
def generate_uuid():
return str(uuid.uuid4())
user = models.ForeignKey(User)
groups = ... | (default=0)
protected = models.BooleanField(default=False)
# pretty ugly, but should help viewing the full names
def __unicode__(self):
parts = []
parent = self.parent
while True:
if not parent:
break
parts.insert(0, Resource.objects.get(pk=pa... | rn '/' + '/'.join(parts)
def del_prop(self, dav, request, name):
try:
model_prop = self.prop_set.get(name=name)
model_prop.delete()
except Prop.DoesNotExist:
# removing a non existent property is not an error
pass
def get_prop(self, dav, request,... |
FirstDraftGIS/firstdraft | projfd/appfd/generator/__init__.py | Python | apache-2.0 | 7,321 | 0.006693 | from appfd.models import Source
from appfd.extractor import extract_locations_from_tables, extract_locations_from_text, extract_locations_from_webpage
from appfd.finisher import finish_order
from appfd.styler import style_order
from appfd.resolver import resolve_locations
from location_extractor import extract_location... | g source object")
source_text = source_data.encode("utf-8") if len(source_data.encode("utf-8")) < max_source_text_length else None
Source.objects.create(order_id=order_id, source_text=source_text, source_type="text")
print("[generator] | created source object")
#save_text_to_file(source_data, toFileName(source_data, max_length=20))
locations.extend(extract_locations_from_text(source_data, case_insensitive=case_insensitive))
elif (isinstance(source_data, str) or isinstance(source_data, str)) and va... |
FrancoisRheaultUS/dipy | dipy/reconst/mcsd.py | Python | bsd-3-clause | 11,292 | 0 | import numpy as np
from dipy.core import geometry as geo
from dipy.core.gradients import GradientTable
from dipy.data import default_sphere
from dipy.reconst import shm
from dipy.reconst.multi_voxel import multi_voxel_fit
from dipy.utils.optpkg import optional_package
cvx, have_cvxpy, _ = optional_package("cvxpy")
SH... | nput to the MultiShellDeconvModel.
It will be used as deconvolution kernel, as described in [2]_.
Parameter | s
----------
gtab : GradientTable
response : tuple or AxSymShResponse object
A tuple with two elements. The first is the eigen-values as an (3,)
ndarray and the second is the signal value for the response
function without diffusion weighting. This is to be ab... |
loomchild/flask_babel_test | flask_babel_test_test.py | Python | mit | 591 | 0.005076 | #!/usr/bin/env python
import unittest
from flask_babel_test import app
class FlaskBabelTestTest(unittest.TestCase):
def test(self):
rv = app.test_client().get()
assert 'Hello' in str(rv.data)
def test_pl(self):
with app.t | est_request_context():
app.config['BABEL_DEFAULT_LOCALE'] = 'pl'
# flask.ext.babel.refresh()
rv = app.test_client().get('/')
# rv = app.test_client().get('/', headers=[("Accept-Language", "pl")])
assert 'Witaj' in str(rv.data)
if __name__ = | = '__main__':
unittest.main()
|
torhve/FrameworkBenchmarks | frameworks/Python/django/setup_py3.py | Python | bsd-3-clause | 430 | 0.002326 | import subprocess
def start(args, logfile, errfile):
subprocess.Popen(
"$PY3_GUNICORN --pid=gunicorn.pid hello.wsgi:application -c gunicorn_conf.py --env DJANGO_DB=mysql",
cwd="django", shell=True, stderr=errfile, stdout=logfile)
return 0
def stop(logfile, errfile):
subprocess.call(
... | .pid`",
cwd="django" | , shell=True, stderr=errfile, stdout=logfile)
return 0
|
akkana/scripts | wpnet.py | Python | gpl-2.0 | 17,033 | 0.00182 | #!/usr/bin/env python3
# A wrapper script to make it easier to use wpa_cli to connect.
# https://wiki.archlinux.org/index.php/WPA_supplicant#Connecting_with_wpa_cli
# was very helpful.
#
# For extending this to eth0, browse /etc/dhcpcd.conf
# and /usr/share/dhcpcd/hooks/10-wpa_supplicant on raspbian,
# where dhcpcd is... | a page and compare it to the expected value.
content_from_web = response.read().decode('utf-8')
# Lots of ways this can fail.
# e.g. ValueError, "unknown url type"
# or BadStatusLine: ''
except Exception as e:
print("Couldn't fetch test | URL %s: probably redirected." % testurl, e)
content_from_web = ''
if content_from_web == content_from_file:
print("Looks like we're really connected -- no redirect")
return
print("Couldn't make a test connection -- probably redirected.")
# Don't want to run a browser as root, so f... |
ndp-systemes/odoo-addons | base_delivery_tracking_colissimo/__openerp__.py | Python | agpl-3.0 | 1,395 | 0 | # -*- coding: utf8 -*-
#
# Copyright (C) 2015 NDP Systèmes (<http://www.ndp-systemes.fr>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# Licen... | fero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
{
'name': 'Base delivery tracking (Colissimo)',
'version': '0.1',
'author': 'NDP Systèmes',
'maintai... | '],
'description': """
Base delivery tracking (Colissimo)
==================================
This module adds data to track seliveries using Colissimo
""",
'website': 'http://www.ndp-systemes.fr',
'data': ['base_delivery_tracking_colissimo_data.xml'],
'demo': [],
'test': [],
'installable': True,... |
vistarmedia/fetcher | setup.py | Python | apache-2.0 | 165 | 0 | # | !/usr/bin/env python
from distutils.core import setup
setup(
name='fetcher',
version='0.4',
install_requires=['pycurl==7.19.0.2'],
packages=['fetcher' | ])
|
MungoRae/home-assistant | homeassistant/components/light/flux_led.py | Python | apache-2.0 | 7,798 | 0 | """
Support for Flux lights.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/light.flux_led/
"""
import logging
import socket
import random
import voluptuous as vol
from homeassistant.const import CONF_DEVICES, CONF_NAME, CONF_PROTOCOL
from homeassistan... | b_color(self):
"""Return the color property."""
return self._bulb.getRgb()
@property
def supported_features(self):
"""Flag supported features."""
return SUPPORT_FLUX_LED
@property
def effect_list(self):
"""Return the list of supported effects."""
return ... | ._bulb.turnOn()
rgb = kwargs.get(ATTR_RGB_COLOR)
brightness = kwargs.get(ATTR_BRIGHTNESS)
effect = kwargs.get(ATTR_EFFECT)
if rgb is not None and brightness is not None:
self._bulb.setRgb(*tuple(rgb), brightness=brightness)
elif rgb is not None:
self._bu... |
eblade/radiant | radiant/grid/item.py | Python | mit | 271 | 0 | #!/usr/bin/env python3
from .label import Label
from .table import Table
def ItemType(item_type):
if item_type == "Label":
return Label
elif item_ty | pe == "Table":
| return Table
else:
raise TypeError("No such item type " + item_type)
|
jasonwee/asus-rt-n14uhp-mrtg | src/lesson_application_building_blocks/cmd_attributes.py | Python | apache-2.0 | 438 | 0 | import cmd
class HelloWorld(cmd.Cmd):
prompt = 'prompt: '
intro = "Simple command processor example."
doc_header | = 'doc_header'
misc_header = 'misc_header'
undoc_header = 'undoc_header'
ruler = '-'
def do_prompt(self, line):
"Change the interactive prompt"
self.prompt = line + ': '
def do_EOF(self, line):
re | turn True
if __name__ == '__main__':
HelloWorld().cmdloop()
|
FunTimeCoding/virtual-box-tools | tests/test_command_process.py | Python | mit | 1,577 | 0 | from virtual_box_tools.command_process import CommandProcess, \
CommandFailed
def test_standard_output() -> None:
process = CommandProcess(['echo', 'example'])
assert process.get_standard_output() == 'example'
assert process.get_standard_error() == ''
assert process.get_return_code() == 0
def te... | t CommandFailed as exception:
assert exception.get_command() == 'tests/exit.sh'
assert exception.get_standard_output() == ''
assert exception.get_standard_error() == ''
assert exception.get_return_code() == 1
def test_standard_output_error_and_exit_code() -> None:
try:
Comm... | 'tests/standard-output-error-and-exit.sh'
assert exception.get_standard_output() == 'example'
assert exception.get_standard_error() == 'error'
assert exception.get_return_code() == 2
def test_long_process() -> None:
process = CommandProcess(['sleep', '1'])
assert process.get_standar... |
rolepoint/appengine-mapreduce | python/src/mapreduce/mapper_pipeline.py | Python | apache-2.0 | 5,046 | 0.004954 | #!/usr/bin/env python
#
# Copyright 2011 Google 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 o... | rds,
output_writer_spec=output_writer_spec,
)
self.fill(self.outputs.job_id, mapreduce_id)
self.set_status(console_url="%s/detail?job_id=%s" % (
(parameters.config.BASE_PATH, mapreduce_id)))
def tr | y_cancel(self):
"""Always allow mappers to be canceled and retried."""
return True
def callback(self):
"""Callback after this async pipeline finishes."""
mapreduce_id = self.outputs.job_id.value
mapreduce_state = model.MapreduceState.get_by_job_id(mapreduce_id)
if mapreduce_state.result_statu... |
julianwang/cinder | cinder/volume/drivers/ibm/storwize_svc/replication.py | Python | apache-2.0 | 7,275 | 0.000275 | # Copyright 2014 IBM Corp.
# 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 app... | if primary['status'] == 'online':
status = 'active'
extended1 = (_('Primary copy status: %(status)s'
' and synchronized: %(sync)s') %
{'status': primary['status'],
'sync': primary['sync']})
# Check status of se... | 'sync': 'no',
'sync_progress': '0'}
status = 'error'
else:
if secondary['status'] != 'online':
status = 'error'
else:
if secondary['sync'] == 'yes':
secondary['sync_progress'] = '100'
... |
getninjas/adwords-client | adwords_client/adwords_api/operations/ad.py | Python | apache-2.0 | 5,064 | 0.000987 | from .utils import _get_selector
def expanded_ad_operation(adgroup_id: 'Long' = None,
ad_id: 'Long' = None,
status: 'String' = 'PAUSED',
operator: 'String' = 'ADD',
headline_part_1: 'String' = '',
... | # one at customer, campaign, ad group, ad, criterion or feed item levels.
ad['trackingUrlTemplate'] = tracking_url_template
if url_customer_parameters:
# Values for the parameters in the tracking URL. This can be provided at
# campaign, ad group, ad, criterion, or feed item levels.
... | '] = {'parameters': parameters}
for k, v in url_customer_parameters.items():
parameters.append({'key': k, 'value': v})
return ad
def _abstract_ad(ad_id: 'Long' = None):
ad = {
'xsi_type': 'Ad',
# Abstract ad for set and remove operations
'id': ad_id,
}
retur... |
ollie314/kuma | kuma/dashboards/tests/test_views.py | Python | mpl-2.0 | 25,862 | 0.001237 | import datetime
import mock
import pytest
from pyquery import PyQuery as pq
from django.contrib.auth.models import Permission
from django.core.exceptions import ImproperlyConfigured
from waffle.models import Flag, Switch
from kuma.core.tests import eq_, ok_
from kuma.core.urlresolvers import reverse
from kuma.core.ut... | ission_buttons(self):
url = reverse('dashboards.revisions', locale='en-US')
response = self.client.get(url)
eq_(200, response.status_code)
page = pq(response.content)
spam_table_cell = page.find('td.dashboard-spam')
eq_(spam_table_cell, [])
flag = Flag.objects.c... | ass')
url = reverse('dashboards.revisions', locale='en-US')
response = self.client.get(url)
eq_(200, response.status_code)
page = pq(response.content)
ip_button = page.find('td.dashboard-spam')
# Revisions available, admin has privileges to see this
ok_(len(ip_bu... |
stephengroat/miasm | miasm2/arch/x86/arch.py | Python | gpl-2.0 | 136,563 | 0.001882 | #-*- coding:utf-8 -*-
import re
from miasm2.expression.expression import *
from pyparsing import *
from miasm2.core.cpu import *
from collections import defaultdict
import miasm2.arch.x86.regs as regs_module
from miasm2.arch.x86.regs import *
from miasm2.core.asmblock import AsmLabel
log = logging.getLogger("x86_arch... | )
def reg2exprid(r):
if not r.name in all_regs_ids_byname:
raise ValueError('unknown reg')
return all_regs_ids_byname[r.name]
def parse_deref_reg(s, l, t):
t = t[0][0]
return t[0]
def parse_deref_int(s, l, t):
t = t[0]
return t[0]
def parse_deref_regint(s, l, t):
t = t[0]
... | return r1 + i1
def parse_deref_regreg(s, l, t):
t = t[0]
return t[0][0] + t[1][0]
def parse_deref_regregint(s, l, t):
t = t[0]
r1 = reg2exprid(t[0][0])
r2 = reg2exprid(t[1][0])
i1 = ExprInt(t[2].arg, r1.size)
return r1 + r2 + i1
def parse_deref_reg_intmreg(s, l, t):
t = t[0]
... |
Featuretools/featuretools | featuretools/tests/wrappers/test_sklearn_wrapper.py | Python | bsd-3-clause | 3,577 | 0 | import numpy as np
import pandas as pd
import pytest
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.impute import SimpleImputer
from sklearn.model_selection import GridSearchCV, cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import FunctionTransformer, StandardScaler
f... | re(df['customer_id'].values, df.target.values)
# assert isinstance(result, (float))
def test_sklearn_cross_val_score(df, pipeline):
# Using with cross_val_score
res | ults = cross_val_score(pipeline,
X=df['customer_id'].values,
y=df.target.values,
cv=2,
scoring="accuracy")
assert isinstance(results[0], (float))
assert isinstance(results[1], (float))
def ... |
DrPaulBrewer/rtlsdr-automated-wxsat-capture | pypredict.py | Python | gpl-2.0 | 1,215 | 0.017284 | import subprocess
import sys
import time
class missingSatellitePredictionError(Exception):
def __init__(self):
self.description = "predict did not return data for the satellite"
def __str__(self):
return self.description
def aoslos(satname):
lines = subprocess.check_output(['... | result.extend([int(data[j]) for j in [0,6,7] ])
except:
pass
if len(result)==0:
raise missingSatellitePredictionError()
return resu | lt
|
duncanmmacleod/gwsumm | gwsumm/tests/test_data.py | Python | gpl-3.0 | 9,035 | 0 | # -*- coding: utf-8 -*-
# Copyright (C) Duncan Macleod (2013)
#
# This file is part of GWSumm.
#
# GWSumm 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) ... | '', # FFT scheme
])
de | f test_get_fftparams(self):
fftparams = utils.get_fftparams('L1:TEST-CHANNEL')
assert isinstance(fftparams, utils.FftParams)
for key in utils.FFT_PARAMS:
assert (getattr(fftparams, key) is
utils.DEFAULT_FFT_PARAMS.get(key, None))
fftparams = utils.get_ff... |
sysadminmatmoz/pmis | purchase_stock_analytic/models/__init__.py | Python | agpl-3.0 | 265 | 0 | # -*- coding: ut | f-8 -*-
# Copyright 2017 Eficent Business and IT Consulting Services S.L.
# - Jordi Ballester Alomar
# Copyright 2017 MATMOZ d.o.o.
# - Matjaž Mozetič
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from . import purchase
| |
ygol/odoo | odoo/addons/base/tests/test_mail_examples.py | Python | agpl-3.0 | 21,967 | 0.005329 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
MISC_HTML_SOURCE = u"""
<font size="2" style="color: rgb(31, 31, 31); font-family: monospace; font-variant: normal; line-height: normal; ">test1</font>
<div style="color: rgb(31, 31, 31); font-family: monospace; font-var... | LOCKQUOTE_OUT = [u"""--
Opener B.V. - Business solutions driven by open source collaboration
Stefan Rijnhart - Consultant/developer"""]
QUOTE_THUNDERBIRD_HTML = u"""<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
</head>
<body text="#000000" bgcolor="#FFFFFF">
<div cl... | Q0n0sy9XpGaCWRf1g@mail.gmail.com"
type="cite">
<div dir="ltr"><b><i>Test reply. The suite.</i></b><br clear="all">
<div><br>
</div>
-- <br>
<div class="gmail_signature">Raoul Poilvache</div>
</div>
</blockquote>
Top cool !!!<br>
<br>
<pre class="moz-sign... |
lapsed/whatbot | whatbase.py | Python | unlicense | 1,735 | 0.042651 | import re, urllib2
class WhatBase:
# Some utility functions and constants that I am very lazily bunging into a base class
_sitename = "what.cd"
def debugMessage(self, message, messagecallback = None):
if messagecal | lback:
messagecallback(message)
else:
print message
def downloadResource(self, url, path, fname, messagecallback = None):
# Remove char | acters Windoze doesn't allow in filenames
fname = re.sub("[\*\"\/\\\[\]\:\;\|\=\,\?]", "", fname)
try:
# Do an impression of Firefox to prevent 403 from some image hosts
opener = urllib2.build_opener()
opener.addheaders = [("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.2.3) Gecko/2... |
goozbach/ansible | lib/ansible/plugins/action/normal.py | Python | gpl-3.0 | 1,774 | 0.000564 | # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any lat... | odule_args']
results = merge_hash(results, self._execute_module(tmp=tmp, task_vars=task_vars))
# Remove special fields from the result, which can only be set
# internally by the executor engine. We do this only here in
# the 'normal' action, as other action plugins may set this.
... | # We don't want modules to determine that running the module fires
# notify handlers. That's for the playbook to decide.
for field in ('_ansible_notify',):
if field in results:
results.pop(field)
return results
|
gengwg/leetcode | 400_nth_digit.py | Python | apache-2.0 | 1,132 | 0.003883 | # 400 Nth Digit
# Find the nth digit of the infinite integer sequence 1, 2, 3, | 4, 5, 6, 7, 8, 9, 10, 11, ...
#
# Note:
# n is positive and will fit within the range of a 32-bit signed integer (n < 231).
#
# Example 1:
#
# Input:
# 3
#
# Output:
# 3
#
# Example 2:
#
# Input:
# 11
#
# Output:
# 0
#
# Explanation:
# The 11th digit of the seque | nce 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.
class Solution(object):
# https://www.hrwhisper.me/leetcode-contest-5-solution/
# 主要是求出该数字需要的位数,因为一位数有9*1,两位数有90*2,三位数有900*3以此类推。
# 剩下的直接看看是否整除啥的即可。
def findNthDigit(self, n):
"""
:type n: int
:rt... |
tgsmith61591/pyramid | examples/preprocessing/example_date_featurizer.py | Python | mit | 2,754 | 0.003268 | """
=================================================
Modeling quasi-seasonal trends with date features
=================================================
Some trends are common enough to appear seasonal, yet sporadic enough that
approaching them from a seasonal perspective may not be valid. An example of
this is the ... | plotlib import pyplot as plt
print(f"pmdarima version: {pm.__versio | n__}")
# Load the data and split it into separate pieces
y, X = load_date_example()
y_train, y_test, X_train, X_test = \
model_selection.train_test_split(y, X, test_size=20)
# We can examine traits about the time series:
pm.tsdisplay(y_train, lag_max=10)
# We can see the ACF increases and decreases rather rapidl... |
benjsto/ronquixote | manage.py | Python | mit | 252 | 0 | #!/usr/bin/env python
import | os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "quotoxic.settings")
from django.core.management import execute_from_command_line
| execute_from_command_line(sys.argv)
|
kaedroho/wagtail | wagtail/core/hooks.py | Python | bsd-3-clause | 2,294 | 0.000436 | from contextlib import ContextDecorator
from operator import itemgetter
from wagtail.utils.apps import get_app_submodules
_hooks = {}
def register(hook_name, fn=None, order=0):
"""
Register hook for ``hook_name``. Can be used as a decorator::
@register('hook_name')
def my_hook(...):
... | order))
class TemporaryHook(ContextDecorator):
def __init__(self, hook_name, fn, order):
self.hook_name = hook_name
self.fn = fn
self.o | rder = order
def __enter__(self):
if self.hook_name not in _hooks:
_hooks[self.hook_name] = []
_hooks[self.hook_name].append((self.fn, self.order))
def __exit__(self, exc_type, exc_value, traceback):
_hooks[self.hook_name].remove((self.fn, self.order))
def register_tempor... |
charmasaur/cw | appengine/manage.py | Python | gpl-2.0 | 227 | 0.004405 | from flask.cli import FlaskGroup
from app import app, db
cli = FlaskGroup(app)
@cli.command("create_ | db")
def create_db():
| db.drop_all()
db.create_all()
db.session.commit()
if __name__ == "__main__":
cli()
|
caw13/adventofcode | python/day_three_part2.py | Python | mit | 939 | 0.044728 | class PresentDeliverer:
present_locations = {}
def __init__(self, name):
self.name = name
self.x = 0
self.y = 0
self.present_locations[self.get_key()]=1
def get_key(self):
return str(self.x)+"-"+str(self.y)
def status(self):
print(self.name + " x: "+str(self.x)+" y: "+str(self.y))
def move(self... | = 1
self.present_locations[self.get_key()]=1
def unique_houses(self):
print("Unique houses: "+str(len(self.present_locations.keys())))
filename = "..\inputs\day_three_input.txt"
f = open(filename)
input_line = f.readline()
santa = PresentDeliverer("Santa")
robo = PresentDeliverer( | "RoboSanta")
instruction_count = 0
for c in input_line:
instruction_count += 1
if (instruction_count % 2):
santa.move(c)
else:
robo.move(c)
santa.unique_houses() |
DIRACGrid/DIRAC | src/DIRAC/Core/Security/test/x509TestUtilities.py | Python | gpl-3.0 | 17,182 | 0.000466 | """ Configuration and utilities for all the X509 unit tests """
import os
import sys
from datetime import datetime
from pytest import fixture
# We use certificates stored in the same folder as this test file
CERTDIR = os.path.join(os.path.dirname(__file__), "certs")
HOSTCERT = os.path.join(CERTDIR, "host/hostcert.pem... | oin(CERTDIR, "user/userkey.pem")
VOMSPROXY = os.path.join(CERTDIR, "voms/proxy.pem")
ENCRYPTEDKEY = os.path.join(CERTDIR, "key/encrypted_key_pass_0000.pem")
ENCRYPTEDKEYPASS = "0000"
CERTS = (HOSTCERT, USERCERT)
CERTKEYS = (HOSTKEY, USERKEY)
CERTCONTENTS = {
"HOSTCERTCONTENT": """-----BEGIN CERTIFICATE-----
MIIG... | Fw0zNzEwMjEw
OTE4MTdaMDkxGDAWBgNVBAoMD0RpcmFjIENvbXB1dGluZzENMAsGA1UECgwEQ0VS
TjEOMAwGA1UEAwwFVk9Cb3gwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoIC
AQDjV5Y6AQI61nZHy6hjr1MziFFeh/z1DdAgkPfiUnHQLxWtvXGcc4sX/tBcD6tv
NKTzJCwyFVAML0WNTD/w480TUmGILlRtg+17qfSWfeCvDygSbGNINX+la0auEqY7
u5oXtwhFAEnqBe+6pzvgfTpzh8eOtBSrqgJUwMtaI81P6LQ... |
gzc/gitstats | v1/DataDriver.py | Python | mit | 6,238 | 0.003847 | from datetime import datetime
import time
import json
from Commit import Commit;
import Constant;
import collections
from yattag import Doc
def generateHTML(commits, projectName, commitData, fileExtensionMap):
totalAuthors = len(commitData)
generateBestAuthors(projectName, commitData)
generateFileByExtensi... | fout.write(line.replace('$title', projectName))
elif '$time' in line:
fout.write(line.re | place('$time', time.strftime('%l:%M%p %Z on %b %d, %Y')))
elif '$files' in line:
fout.write(line.replace('$files', str(totalFiles)))
elif '$commits' in line:
fout.write(line.replace('$commits', str(totalCommits)))
elif '$totallines'... |
ascoderu/opwen-cloudserver | opwen_email_server/utils/email_parser.py | Python | apache-2.0 | 7,047 | 0.000284 | from copy import deepcopy
from datetime import datetime
from datetime import timezone
from email.utils import mktime_tz
from email.utils import parsedate_tz
from io import BytesIO
from itertools import chain
from mimetypes import guess_type
from typing import Callable
from typing import Iterable
from typing import List... | fc_822 = message.get_decoded_header('date')
if not rfc_822:
return None
date_tz = parsedate_tz(rfc_822)
if not date_tz:
return None
timestamp = mktime_tz(date_tz | )
# noinspection PyUnresolvedReferences
date_utc = datetime.fromtimestamp(timestamp, timezone.utc)
return date_utc.strftime('%Y-%m-%d %H:%M')
def parse_mime_email(mime_email: str) -> dict:
message = PyzMessage.factory(mime_email)
return {
'sent_at': _parse_sent_at(message),
'to': ... |
FlorianLudwig/rueckenwind | rw/__init__.py | Python | apache-2.0 | 89 | 0 | # -*- coding: u | tf-8 -*-
"""Top-level package for rueckenwind."""
__version | __ = '0.5.2'
|
mbayon/TFG-MachineLearning | venv/lib/python3.6/site-packages/scipy/io/harwell_boeing/tests/test_hb.py | Python | mit | 2,375 | 0.000842 | from __future__ import division, print_function, absolute_import
import os
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from StringIO import StringIO
import tempfile
import numpy as np
from numpy.testing import assert_equal, \
assert_array_almost_equal_nulp
from scipy.sparse imp... | -01 5.649603072111251e-01 9.934423887087086e- | 01
6.912334991524289e-01
"""
SIMPLE_MATRIX = coo_matrix(
(
(0.297124379969, 0.366236668288, 0.47869621747, 0.649006864799,
0.0661749042483, 0.887037034319, 0.419647859016,
0.564960307211, 0.993442388709, 0.691233499152,),
(np.array([[36, 70, 88, 17, 29, 44, 69,... |
sinhrks/expandas | pandas_ml/skaccessors/test/test_semi_supervised.py | Python | bsd-3-clause | 1,015 | 0 | #!/usr/bin/env python
import pytest
import sklearn.datasets as datasets
import sklearn.semi_supervised as ss
import pandas_ml as pdml
import pandas_ml.util.testing as tm
class TestSemiSupervised(tm.TestCase):
def test_objectmapper(self):
df = pdml.ModelFrame([])
self.assertIs(df.s... | ading, ss.LabelSpreading)
@pytest.mark.parametrize("algo", ['LabelPropagation', 'LabelSpreading'])
def test_Classifications(self, algo):
iris = datasets.load_iris()
df = pdml.ModelFrame(iris)
mod1 = getattr(df.semi_supervised, algo)()
mod2 = getattr(ss, algo)()
... | d2.predict(iris.data)
self.assertIsInstance(result, pdml.ModelSeries)
self.assert_numpy_array_almost_equal(result.values, expected)
|
SerpentCS/purchase-workflow | purchase_request/tests/test_purchase_request.py | Python | agpl-3.0 | 1,728 | 0 | # -*- coding: utf-8 -*-
# Copyright 2016 Eficent Business and IT Consulting Services S.L.
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl-3.0).
from openerp.tests import common
from openerp.tools import SUPERUSER_ID
class TestPurchaseRequest(common.TransactionCase):
def setUp(self):
super(... | purchase_request.id,
'product_id': self.env.ref('product.product_product_13').id,
'product_uom_id': self.env.ref('product.product_uom_unit').id,
| 'product_qty': 5.0,
}
self.purchase_request_line.create(vals)
self.assertEqual(
purchase_request.is_editable, True,
'Should be editable')
purchase_request.button_to_approve()
self.assertEqual(
purchase_request.state, 'to_approve',
... |
marinkaz/orange3 | Orange/projection/__init__.py | Python | bsd-2-clause | 82 | 0 | from .base import *
from .pca import *
fro | m .cur import *
from .manifold im | port *
|
badlogicmanpreet/nupic | tests/unit/nupic/research/spatial_pooler_cpp_api_test.py | Python | agpl-3.0 | 1,297 | 0.001542 | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following term | s and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU A | ffero Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero Public License for more details.... |
MatthewWilkes/mw4068-packaging | src/melange/src/soc/models/profile.py | Python | apache-2.0 | 173 | 0.034682 | from google.appengine.ext import db
class Profile(db.Model):
"""
"""
#:
profile = db.StringProperty(required=True | )
#:
path = db.Strin | gProperty(required=True)
|
laurenrevere/osf.io | admin_tests/utilities.py | Python | apache-2.0 | 1,197 | 0 | """
Utilities to help run Django tests
* setup_view - replaces as_view
"""
from osf_tests.factories import UserFactory
def setup_view(view, request, *args, **kwargs):
"""Mimic as_view() returned callable, but returns view instance
http://tech.novapost.f | r/django-unit-test-your-views-en.html
"""
view.request = request
view.args = args
view.kwargs = kwargs
return view
def setup_form_view(view, request, form, *args, **kwargs):
"""Mimic as_view and with forms to skip some of the context"""
view.request = request
try:
view.request.... | ef setup_user_view(view, request, user, *args, **kwargs):
view.request = request
view.request.user = user
view.args = args
view.kwargs = kwargs
return view
def setup_log_view(view, request, *args, **kwargs):
view.request = request
try:
view.request.user = request.user
except At... |
amonapp/amonagent-legacy | amonagent/runner.py | Python | mit | 1,374 | 0.037846 | from amonagent.modules.processes import processes_data_collector
from amonagent.modules.core import (
get_uptime,
get_memory_info,
get_cpu_utilization,
get_load_average,
disk_check,
get_network_traffic,
get_ip_address,
get_cpu_info
)
from amonagent.modules.distro import get_distro
from amonagent.mod | ules.plugins import discover_plugins
import logging
log = logging.getLogger(__name__)
class Runner(object):
def __init__(self):
self.plugins_list = discover_plugins()
def info(self):
system_info_dict = {
'processor': get_cpu_info(),
'ip_address': get_ip_address(),
'distro': get_distro(),
}
re... | ry_info(),
'cpu': get_cpu_utilization(),
'disk': disk_check.check(),
'network': get_network_traffic(),
'loadavg': get_load_average(),
'uptime': get_uptime(),
}
return system_data_dict
def processes(self):
return processes_data_collector.collect()
def plugins(self):
plugin_result_dict = ... |
shodimaggio/SaivDr | appendix/torch_nsolt/test_nsoltChannelConcatenation2dLayer.py | Python | bsd-2-clause | 7,477 | 0.02671 | import itertools
import unittest
from parameterized import parameterized
import torch
import torch.nn as nn
from nsoltChannelConcatenation2dLayer import NsoltChannelConcatenation2dLayer
nchs = [ [3, 3], [4, 4] ]
datatype = [ torch.float, torch.double ]
nrows = [ 4, 8, 16 ]
ncols = [ 4, 8, 16 ]
class NsoltChannelConca... | layer = NsoltChannelConcatenation2dLayer(
name='Cn'
)
# Actual values
Z = layer.forward(Xac=Xac,Xdc=Xdc)
Z.backward(dLdZ)
actualdLdXac = Xac.grad
actualdLdXdc = Xdc.grad
# Evaluation
self.assertEqual(actualdLdXdc.dtype,datatyp... | lf.assertTrue(torch.allclose(actualdLdXdc,expctddLdXdc,rtol=rtol,atol=atol))
self.assertTrue(torch.allclose(actualdLdXac,expctddLdXac,rtol=rtol,atol=atol))
self.assertTrue(Z.requires_grad)
if __name__ == '__main__':
unittest.main()
|
JMG1/FreeCAD_ExplodedAssemblyAnimationWorkbench | InitGui.py | Python | gpl-2.0 | 2,745 | 0.027727 | # -*- coding: utf-8 -*-
# FreeCAD Exploded Assembly Animation Workbench
# (c) 2014 Javier Martínez García
#***************************************************************************
#* (c) Javier Martínez García 2014 *
#* | *
#* This program is free software; you can redistribute it and/or modify *
#* it unde | r the terms of the GNU General Public License (GPL) *
#* as published by the Free Software Foundation; either version 2 of *
#* the License, or (at your option) any later version. *
#* for detail see the LICENCE text file. *
#* ... |
jonhadfield/acli | lib/acli/config.py | Python | mit | 1,321 | 0 | # -*- coding: utf-8 -*-
from __future__ import (absolute_import, print_function, unicode_literals)
try:
import configparser
except ImportError:
from external.six.moves import configparser
import os
class Config(object):
def __init__(self, cli_args):
self.access_key_id = None
self.secret_ac... | )
self.load_acli_config()
def from_cli(self, cli_args):
cli_aws_region = cli_args.get('--region')
cli_access_key_id = cli_args.get('--access_key_id')
cli_secret_access_key = cli_args.get('--secret_access_key')
if cli_aws_region:
self.region = cli_aws_region
... | staticmethod
def load_acli_config():
if os.path.isfile('acli.cfg'):
configparser.read('acli.cfg')
|
kagel/foobnix | foobnix/gui/controls/seekbar.py | Python | gpl-3.0 | 3,816 | 0.001574 | #-*- coding: utf-8 -*-
'''
Created on 28 сент. 2010
@author: ivan
'''
from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import Pango
from foobnix.util import idle_task
from foobnix.util.const import FTYPE_RADIO
from foobnix.gui.model.signal import FControl
from foobnix.util.time_utils im... | if self.seek_bar_movie:
self | .seek_bar_movie.clear()
@idle_task
def fill_seekbar(self):
self.progressbar.set_fraction(1)
@idle_task
def update_seek_status(self, position_sec, duration_sec):
if duration_sec == 0:
seek_text = "00:00 / 00:00"
seek_persent = 0.999
else:
dura... |
kratman/psi4public | tests/python/mints9/input.py | Python | gpl-2.0 | 8,970 | 0.011929 | from __future__ import print_function
import psi4
from psi4.driver import qcdb
#! A test of the basis specification. Various basis sets are specified outright and in blocks, both
#! orbital and auxiliary. Constructs libmints BasisSet objects through the constructor that calls
#! qcdb.BasisSet infrastructure. Checks th... | #TEST
psi4.compare_integers(51, wert.nbf(), 'nbf()' | ) #TEST
psi4.compare_integers(54, wert.nao(), 'nao()') #TEST
psi4.compare_strings('cs', mymol.schoenflies_symbol(), 'symm') #TEST
psi4.compare_strings('DZ_PLUSPLUS', wert.name(), 'callby') #TEST
psi4.compare_strings('AUG-CC-PVDZ + CC-PVDZ', wert.blend(), 'blend') #TEST
mymol.print_out()
print('[6] <<< RIFIT ... |
awsdocs/aws-doc-sdk-examples | python/example_code/greengrass/snippets/secret_resource_access_staging_label.py | Python | apache-2.0 | 796 | 0.001256 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to implement an AWS Lambda function that uses AWS IoT Greengrass Core SDK
to get the specific versio | n of a secret.
"""
# snippet-start:[greengrass.python.secret-resource-access-staging-label.complete]
impor | t greengrasssdk
secrets_client = greengrasssdk.client('secretsmanager')
secret_name = 'greengrass-TestSecret'
secret_version = 'MyTargetLabel'
# Get the value of a specific secret version
def function_handler(event, context):
response = secrets_client.get_secret_value(
SecretId=secret_name, VersionStage=... |
kyuupichan/electrumx | electrumx/lib/merkle.py | Python | mit | 9,500 | 0.000632 | # Copyright (c) 2018-2021, Neil Booth
#
# All rights reserved.
#
# This file is licensed under the Open BSV License version 3, see LICENCE for details.
'''Merkle trees, branches, proofs and roots.'''
from math import ceil, log
from aiorpcx import Event
from electrumx.lib.hash import double_sha256
class Merkle(obj... | c
branch = []
for _ in range(length):
if len(hashes) & 1:
hashes.append(hashes[-1])
# Asterix used in place of "dupli | cated" hashes in TSC format (derivable by client)
is_last_node_in_level = (index ^ 1 == len(hashes) - 1)
if tsc_format and is_last_node_in_level:
branch.append(b"*")
else:
branch.append(hashes[index ^ 1])
else:
... |
ProfessorX/Config | .PyCharm30/system/python_stubs/-1247971765/_codecs_kr.py | Python | gpl-2.0 | 517 | 0.017408 | # encoding: utf-8
# module _codecs_kr
# from /usr/lib/python3.4/lib-dynload/_codecs_kr.cpython-34m-x86_64-linux-gnu.so
# by generator 1.135
# no doc
# no imports
# functions
def getcodec(*args, **kwargs): # real signature unknown
""" """
pass
# no classes
# variables with complex values
__loader__ = None #... | __map_cp949ext = None # (!) real value is ''
__map_ks | x1001 = None # (!) real value is ''
__spec__ = None # (!) real value is ''
|
appium/python-client | test/unit/webdriver/app_test.py | Python | apache-2.0 | 4,887 | 0.003479 | #!/usr/bin/env python
# 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... | {'app': "com.app.id"}, get_httpretty_request_body(httpretty.last_request())
assert res | ult is True
@httpretty.activate
def test_terminate_app(self):
driver = android_w3c_driver()
httpretty.register_uri(
httpretty.POST, appium_command('/session/1234567890/appium/device/terminate_app'), body='{"value": true}'
)
result = driver.terminate_app("com.app.id")... |
apirakw/ev3 | demo/motorinfo.py | Python | gpl-3.0 | 1,212 | 0.018977 | #!/usr/bin/env python3
'''
Demonstrate different operations and info about motors
'''
import ev3dev.ev3 as ev3
import logging
from time import sleep
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(levelname)5s: %(message)s')
log = logging.getLogger(__name__)
def logMotor(motor, log... | un_timed()
logMotor(m | , log)
|
Diti24/python-ivi | ivi/agilent/agilentE4425B.py | Python | mit | 1,494 | 0.001339 | """
Python Interchangeable Virtual Instrument Library
Copyright (c) 2014-2016 Alex Forencich
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation f | iles (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above ... | sion notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR ... |
drxaero/calibre | src/calibre/gui2/tweak_book/diff/main.py | Python | gpl-3.0 | 18,741 | 0.004055 | #!/usr/bin/env python2
# vim:fileencoding=utf-8
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>'
import sys, os, re
from functools import partial
from PyQt5.Qt import (
... | setClipRect(br)
f = p.font()
f.setBold(True)
f.setPointSize(20)
p.setFont(f)
p.setPen(Qt.SolidLine)
r = QRect(0, self.dummy.geometry().top() + 10, self.geometry().width( | ), 150)
p.drawText(r, Qt.AlignHCenter | Qt.AlignTop | Qt.TextSingleLine, self.text)
p.end()
# }}}
class Cache(object):
def __init__(self):
self._left, self._right = {}, {}
self.left, self.right = self._left.get, self._right.get
self.set_left, self.set_right = self._left.__s... |
gltn/stdm | stdm/third_party/sqlalchemy/util/_preloaded.py | Python | gpl-2.0 | 5,765 | 0.000173 | # util/_preloaded.py
# Copyright (C) 2005-2020 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Legacy routines to resolve circular module imports at runtime.
These routines... | rgspec_plus(fn, grouped=True):
"""vendored version of langhelpers._format_argspec_plus.
not needed in the 1.4 version of preloaded.
"""
if com | pat.callable(fn):
spec = compat.inspect_getfullargspec(fn)
else:
spec = fn
args = compat.inspect_formatargspec(*spec)
if spec[0]:
self_arg = spec[0][0]
elif spec[1]:
self_arg = "%s[0]" % spec[1]
else:
self_arg = None
apply_pos = compat.inspect_formatargs... |
DavidTingley/ephys-processing-pipeline | installation/klustaviewa-0.3.0/klustaviewa/views/similaritymatrixview.py | Python | gpl-3.0 | 13,760 | 0.010102 | """Correlation matrix View: show correlation matrix."""
# -------------------------------------------------------- | ---------------------
# Imports
# -----------------------------------------------------------------------------
import numpy as np
import numpy.random as rdn
from galry import (Manager, DefaultPaintManager, PlotInteractionManager,
Visual, PlotPaintManager,
GalryWidget, QtGui, QtCore, QtOpenGL, enforce_dt... | array
from kwiklib.utils.colors import COLORMAP
from kwiklib.utils import logger as log
from klustaviewa.views.common import HighlightManager, KlustaViewaBindings, KlustaView
# -----------------------------------------------------------------------------
# Utility functions
# ---------------------------------... |
Gitweijie/first_project | networking_cisco/neutronclient/routerscheduler.py | Python | apache-2.0 | 7,544 | 0 | # Copyright 2015 Cisco Systems.
# 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... | lient.format = parsed_args.request_format
_id_hd = neutronV20.find_resourceid_by_name_or_id(
neutron_client, 'hosting_device', parsed_args.hosting_de | vice)
_id_r = neutronV20.find_resourceid_by_name_or_id(
neutron_client, 'router', parsed_args.router)
self.remove_router_from_hosting_device(neutron_client, _id_hd, _id_r)
print(_('Removed router \'%(router)s\' from hosting device \'%(hd)s\'')
% {'router': parsed_args.r... |
tonygalmiche/is_plastigray | report/is_pricelist_item.py | Python | mit | 5,365 | 0.009899 | # -*- coding: utf-8 -*-
from openerp import tools
from openerp import models,fields,api
from openerp.tools.translate import _
class is_pricelist_item(models.Model):
_name='is.pricelist.item'
_order='pricelist_name,price_version_id,sequence,product_id'
_auto = False
pricelist_name = f... | ir.actions.act_window',
# }
@api.multi
def corriger_anomalie_pricelist(self):
for obj in self:
base=False
if obj.pricelist_type== | 'purchase' and obj.base!=2:
base=2
if obj.pricelist_type=='sale' and obj.base!=1:
base=1
if base:
items=self.env['product.pricelist.item'].browse(obj.id)
for item in items:
item.base=base
|
kitsunde/django-pypi | pypi/admin.py | Python | mit | 394 | 0.005076 | from django.contrib import admin
f | rom pypi.models import Package
class PackageAdmin(admin.ModelAdmin):
search_fields = ('name',)
readonly_fields = Package._meta.get_all_field_names()
has_add_permission = lambda s, r: False
has_delete_permission = lambda s, r, o = None: False
list_display = ('name', 've | rsion', 'released_at')
admin.site.register(Package, PackageAdmin)
|
mailgun/talon | tests/text_quotations_test.py | Python | apache-2.0 | 21,510 | 0.002141 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from . import *
from . fixtures import *
import os
import email.iterators
from talon import quotations
import six
from six.moves import range
from six import StringIO
@patch.object(quotations, 'MAX_LINES_COUNT', 1)
def test_too_many_lines():
msg_bo... |
Gesendet: Dienstag, 25. November 2014 14:59
An: Somebody
Betreff: The manager has commented on your Loop
Blah-blah-blah
"""))
def test_french_multiline_from_block():
eq_('Lorem ipsum', quotations.extract_from_plain(
u"""Lorem ipsum
De : Brendan xxx [mailto:brendan.xxx@xxx | .com]
Envoyé : vendredi 23 janvier 2015 16:39
À : Camille XXX
Objet : Follow Up
Blah-blah-blah
"""))
def test_french_from_block():
eq_('Lorem |
KiMiralles/Python-Learning | Computational Physics Newman/Book Resources/bulirsch.py | Python | gpl-3.0 | 1,824 | 0.012061 | from math import sin,pi
from numpy import empty,array,arange
from pylab import plot,show
g = 9.81
l = 0.1
theta0 = 179*pi/180
a = 0.0
b = 10.0
N = 100 # Number of "big steps"
H = (b-a)/N # Size of "big steps"
delta = 1e-8 # Required position accuracy per unit time
def f(r):
theta = r[0]
ome... | ange(n-1):
r1 += h*f(r2)
r2 += h*f(r1)
# Calculate extrapolation estimates. Arrays R1 and R2
# hold the two most recent lines of the table
R2 = R1
R1 = empty([n,2],float)
R1[0] = 0.5*(r1 + r2 + 0.5*h*f(r2))
for m in range(1,n):
epsilo... | -1] + epsilon
error = abs(epsilon[0])
# Set r equal to the most accurate estimate we have,
# before moving on to the next big step
r = R1[n-1]
# Plot the results
plot(tpoints,thetapoints)
plot(tpoints,thetapoints,"b.")
show()
|
probml/pyprobml | scripts/huberLossPlot.py | Python | mit | 583 | 0.015464 | import superimport
import numpy as np
import matplotlib.pyplot as plt
import pyprobml_utils as pml
err = np.linspace(-3.0, 3.0, 60)
L1 = abs(err);
L2 = err**2;
delta = 1.5;
ind = abs(err) <= de | lta;
huber = np.multiply(0.5*ind, (err**2)) + np.multiply((1-ind) , (delta*(abs(err)-delta/2)))
vapnik = np.multiply(ind, 0) + np.multiply((1-ind), (abs(err) - delta))
plt.plot(err, L1, 'k-.')
plt.plot(err, L2, 'r-')
plt.plot(err, vapnik, 'b:')
plt.plot(err, huber, 'g-.')
plt.legend(['L1', 'L2','$ϵ$-insensitive', 'hu... | (-0.5, 5))
pml.savefig('Huber.pdf')
plt.show()
|
mediatum/mediatum | core/athana.py | Python | gpl-3.0 | 85,188 | 0.00135 | #!/usr/bin/python
"""
mediatum - a multimedia content repository
Copyright (C) 2007 Arne Seifert <seiferta@in.tum.de>
Copyright (C) 2007 Matthias Kramm <kramm@in.tum.de>
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 ... | ducers[0]
d = p.more()
if d:
return d
else:
self.producers.pop(0)
else:
return ''
class globbing_producer:
"""
'glob' the output from a producer into a particular buffer size.
helps reduce the number of calls to send(... | about 30% performance on requests to a single channel]
"""
def __init__(self, producer, buffer_size=1 << 16):
self.producer = producer
self.buffer = ''
self.buffer_size = buffer_size
def more(self):
while len(self.buffer) < self.buffer_size:
data = self.produce... |
PaddlePaddle/Paddle | python/paddle/fluid/tests/unittests/test_parallel_executor_seresnext_with_reduce_cpu.py | Python | apache-2.0 | 4,150 | 0.000723 | # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | s in zip(all_reduce_last_loss, all_reduce_last_loss_seq):
self.assertAlmostEquals(loss[0], loss[1], delta=loss[0] * delta2)
for loss in zip(reduce_first_loss, reduce_first_loss_seq):
self.assertAlmostEquals(loss[0], loss[1], delta=1e-5)
for loss in zip(reduce_last_loss, reduce_l... | self.assertAlmostEquals(loss[0], loss[1], delta=1e-5)
for loss in zip(all_reduce_last_loss_seq, reduce_last_loss_seq):
self.assertAlmostEquals(loss[0], loss[1], delta=loss[0] * delta2)
class TestResnetWithReduceCPU(TestResnetWithReduceBase):
def test_seresnext_with_reduce(self):
sel... |
jbonofre/beam | sdks/python/apache_beam/io/gcp/gcsio.py | Python | apache-2.0 | 31,218 | 0.007592 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | retry
__all__ = ['GcsIO']
# Issue a friendlier error message if the storage library is not available.
# TODO(silviuc): Remove this guard when storage is available everywhere.
try:
# pylint: disable=w | rong-import-order, wrong-import-position
# pylint: disable=ungrouped-imports
import apitools.base.py.transfer as transfer
from apitools.base.py.batch import BatchApiRequest
from apitools.base.py.exceptions import HttpError
from apache_beam.internal.gcp import auth
from apache_beam.io.gcp.internal.clients im... |
JuliusKunze/thalnet | util.py | Python | mit | 2,098 | 0.000953 | import functools
from time import strftime
import tensorflow as tf
# lazy_property: no need for if $ not None logic
def lazy_property(function):
attribute = '_cache_' + function.__name__
@property
@functools.wraps(function)
def decorator(self):
if not hasattr(self, attribute):
set... | *kwargs):
"""
A decorator for functions that define TensorFlow operations. The wrapped
function will only be executed once. Subsequent calls to it will directly
return the result so that operations are added to the graph only once.
The operations added by the function live within a tf.vari | able_scope(). If
this decorator is used with arguments, they will be forwarded to the
variable scope. The scope name defaults to the name of the wrapped
function.
"""
attribute = '_cache_' + function.__name__
name = scope or function.__name__
@property
@functools.wraps(function)
def... |
rodo/django-perf | foo/offset/management/commands/keypage_prepare_fields.py | Python | gpl-3.0 | 2,395 | 0.001671 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2013,2014 Rodolphe Quiédeville <rodolphe@quiedeville.org>
#
# 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 ver... | This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public ... | import BaseCommand
from optparse import make_option
from django.core.paginator import Paginator
from foo.offset.models import Log
from foo.july.models import BigBook
import logging
from datetime import datetime
from django.db import connection
class Command(BaseCommand):
help = 'Import datas'
def handle(self... |
Mickey32111/pogom | pogom/pgoapi/protos/POGOProtos/Networking/Responses/NicknamePokemonResponse_pb2.py | Python | mit | 3,789 | 0.005278 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: POGOProtos/Networking/Responses/NicknamePokemonResponse.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
... | 'POGOProtos.Ne | tworking.Responses.NicknamePokemonResponse.Result',
filename=None,
file=DESCRIPTOR,
values=[
_descriptor.EnumValueDescriptor(
name='UNSET', index=0, number=0,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='SUCCESS', index=1, number=1,
options=None,
typ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.