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
uart/scarphase
pyscarphase/plot/color.py
Python
bsd-3-clause
1,885
0.000531
# Copyright (c) 2011-2013 Andreas Sembrant # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modificatio
n, are permitted provided that the following conditions are # met: # # - Redistributions
of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # - Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the d...
nborwankar/open-budgets
openbudget/apps/accounts/factories.py
Python
bsd-3-clause
1,107
0
import datetime import factory from django.utils.timezone import utc from openbudget.apps.accounts.models import Account class AccountFactory(factory.DjangoModelFactory): FACTORY_FOR = Account password = 'letmein' email = factory.Sequence(lambda n: 'p{0}@here.com'.format(n)) first_name = factory.Seq...
datetime.datetime.utcnow().replace(tzinfo=utc) ) created_on = factory.Sequence( lambda n: datetime.datetime.utcnow().replace(tzinfo=utc) ) last_modified = factory.Sequence( lambda n: datetime.datetime.utcnow().replace(tzinfo=utc)
) @classmethod def _prepare(cls, create, **kwargs): password = kwargs.pop('password', None) account = super(AccountFactory, cls)._prepare(create, **kwargs) account.set_password(password) if create: account.save() return account
Patrick-and-Michael/trumptweets
config/settings/production.py
Python
mit
4,984
0.001605
# -*- coding: utf-8 -*- """ Production Configurations - Use Redis for cache """ from __future__ import absolute_import, unicode_literals from boto.s3.connection import OrdinaryCallingFormat from django.utils import six from .common import * # noqa # SECRET CONFIGURATION # ---------------------------------------...
r this site # See https://docs.djangoproject.com/en/1.6/ref/settings/#allowed-hosts ALLOWED_HOSTS = env.list('DJANGO_ALLOWED_HOSTS', default=['example.com']) # END SITE CONFIGURATION INSTALLED_APPS += ('gunicorn', ) # STORAGE CONFIGURATION # ---------------------------------------------------------------------------...
rages.readthedocs.io/en/latest/index.html INSTALLED_APPS += ( 'storages', ) # AWS cache settings, don't change unless you know what you're doing: AWS_EXPIRY = 60 * 60 * 24 * 7 # TODO See: https://github.com/jschneier/django-storages/issues/47 # Revert the following and use str after the above-mentioned bug is fix...
zhsso/ubunto-one
lib/config.py
Python
agpl-3.0
1,777
0
# Copyright 2008-2015 Canonical # # 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 # License, or (at your option) any later version. # # This program is distributed...
lse: return value def __setattr__(self, name, value): self[name] = value def __str__(self):
return "<Config at %d: %s>" % ( id(self), super(_Config, self).__str__()) # instantiate the config and dynamically load the active ports config = _Config() devconfig.development_ports(config)
ekohl/django-waffle
waffle/__init__.py
Python
bsd-3-clause
6,842
0.000438
from decimal import Decimal import random import hashlib from django.conf import settings from django.core.cache import cache from django.db.models.signals import post_save, post_delete, m2m_changed from waffle.models import Flag, Sample, Switch VERSION = (0, 9, 2) __version__ = '.'.join(map(str, VERSION)) CACHE_...
ag.languages: languages = flag.languages.split(',') if (hasattr(request, 'LANGUAGE_CODE') and request.LANGUAGE_CODE in languages): return True flag_users = cache.get(keyfmt(FLAG_USERS_CACHE_KEY, flag.name)) if flag_users is None: flag_users = f
lag.users.all() cache_flag(instance=flag) if user in flag_users: return True flag_groups = cache.get(keyfmt(FLAG_GROUPS_CACHE_KEY, flag.name)) if flag_groups is None: flag_groups = flag.groups.all() cache_flag(instance=flag) user_groups = user.groups.all() for group ...
ingadhoc/website
payment_todopago/todopago/test/SendAuthorizeRequestTest.py
Python
agpl-3.0
2,473
0.003235
# pylint: disable-all # flake8: noqa import sys sys.path.append("..") from todopagoconnector import TodoPagoConnector from SendAuthorizeRequestData import SendAuthorizeRequestData import unittest from unittest import TestCase if sys.version_info[0] >= 3: from unittest.mock import patch, Mock else: from mock imp...
r = MockTodoPagoConnector(j_header_http, "test") instanceSAR = SendAuthorizeRequestData() MTPConnector.sendAuthorize.return_value = instanceSAR.send_authorize_request_fail_response() responseSAR = MTPConnector.sendAuthorize( inst
anceSAR.get_options_SAR_comercio_params(), instanceSAR.get_options_SAR_operation_params()) self.assertNotEquals(responseSAR['StatusCode'], -1) @patch('todopagoconnector.TodoPagoConnector') def test_get_credentials_702(self, MockTodoPagoConnector): j_header_http = { 'Aut...
elopio/snapcraft
tests/integration/general/test_clean_prime_step.py
Python
gpl-3.0
3,431
0
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright (C) 2016-2018 Canonical Ltd # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in ...
self.assertThat(os.path.j
oin(bindir, 'file2'), FileExists())
debugger06/MiroX
tv/lib/frontends/widgets/watchedfolders.py
Python
gpl-2.0
3,503
0.000571
# Miro - an RSS based video player application # Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011 # Participatory Culture Foundation # # 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; eithe...
copyright holders give # permission to link the code of portions of this program with the OpenSSL # library. # # You must obey the GNU General Public License in all respects for all of # the code used other than OpenSSL. If you modify file(s) with this # exception, you may extend this exception to your version of the f...
so. If you do not wish to do so, delete # this exception statement from your version. If you delete this exception # statement from all source files in the program, then also delete it here. """watchedsfolders.py -- Manages tracking watched folders. """ from miro import messages from miro import signals from miro.pl...
datasciencebr/serenata-de-amor
jarbas/core/views.py
Python
mit
867
0
from django.db import connection from django.http import HttpResponse from django.shortcuts import get_object_or_404 from rest_framework.generics import RetrieveAPIView from jarbas.c
ore.models import Company from jarbas.core.serializers import CompanySerializer from jarbas.chamber_of_deputies.serializers import format_cnpj class CompanyDetailView(RetrieveAPIView): lookup_field = 'cnpj' queryset = Company.objects.all() serializer_class = CompanySerializer def get_object(self): ...
return get_object_or_404(Company, cnpj=format_cnpj(cnpj)) def healthcheck(request): """A simple view to run a health check in Django and in the database""" with connection.cursor() as cursor: cursor.execute('SELECT 1') cursor.fetchone() return HttpResponse()
pyhmsa/pyhmsa
pyhmsa/fileformat/xmlhandler/condition/elementalid.py
Python
mit
925
0.005405
""" XML handler for element id c
ondition """ # Standard library modules. # Third party modules. # Local modules. from pyhmsa.spec.condition.elementalid import ElementalID, ElementalIDXray from pyhmsa.fileformat.xmlhandler.condition.condition import _ConditionXMLHandler # Glo
bals and constants variables. class ElementalIDXMLHandler(_ConditionXMLHandler): def __init__(self, version): super().__init__(ElementalID, version) def convert(self, obj): element = super().convert(obj) element.find('Element').set('Symbol', obj.symbol) # manually add symbol r...
feigaochn/leetcode
p62_unique_paths.py
Python
mit
892
0
# author: Fei Gao # # Unique Paths # # A robot is located at the top-left corner of a m x n grid (marked 'Start' in # the diagram below). # The robot can only move either down or right at any point in time. The robot # i
s trying to reach the bottom-right corner of the grid (marked 'Finish' in # the diagram
below). # How many possible unique paths are there? # Above is a 3 x 7 grid. How many possible unique paths are there? # Note: m and n will be at most 100. class Solution: # @return an integer def uniquePaths(self, m, n): mm = m - 1 nn = n - 1 if mm > nn: mm, nn = nn, mm ...
DrSpaceMonkey/script.pseudotv.live
resources/lib/EPGWindow.py
Python
gpl-3.0
58,386
0.008512
# Copyright (C) 2013 Lunatixz # # # This file is part of PseudoTV. # # PseudoTV is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # P...
int(self.getControl(99).getLabel(), 16) if focusedcolor > 0: self.focusedcolor = hex(focusedcolor)[2:] self.logDebug("onInit.Self.focusedcolor = " + str(self.focusedcolor)) except: pass try: self.textfont = self.getControl(...
tLabel() self.logDebug("onInit.Self.textfont = " + str(self.textfont)) except: pass # try: # self.rowCount = self.getControl(106).getLabel() # self.logDebug("onInit, Self.rowCount = " + str(self.rowCount)) # except: # p...
cmvac/demagorgon.repository
plugin.video.irmaospiologo/default.py
Python
gpl-2.0
1,296
0.013117
# -*- coding: utf-8 -*- #------------------------------------------------------------ # http://www.youtube.com/user/irmaospiologo #------------------------------------------------------------ # License: GPL (http://www.gnu.org/licenses/gpl-3.0.html) # Based on code from youtube addon #----------------------------------...
epr(p
arams)) plugintools.add_item( #action="", title="Cuidado! Improprio para menores! Entrar para comecar a zueira! XD", url="plugin://plugin.video.youtube/user/"+YOUTUBE_CHANNEL_ID+"/", thumbnail=icon, folder=True ) run()
Mavrikant/WikiBots
deneme.py
Python
mit
826
0.007472
# -*- coding: utf-8 -*- # !/usr/bin/python # mavri kütüphanesi yükle import mavri # json kütüphanesi yükle import json wiki='tr.wikipedia' username= 'Mavrikant Bot' # Kullanıcı girişi yap xx = mavri.login(wiki, username) # Giriş denemesini sonucunu ekrana JSON ile düzenleyerek yazdır print json.dumps(json.loads(xx...
) # 2 bölümü birbirinden ayır print "\n-------------------------------------------------------------------------\n" # Deneme sayfasına mesaj ekle. sonuc = mavri.appendtext_on_page('tr.wikipedia', 'Vikipedi:Deneme tahtası', '\n== mavribot test ==\nDeneme deneme 123 --~~~~', 'mavribot ile test yapıldı.', xx) # Sonuc...
print json.dumps(json.loads(sonuc.text), sort_keys=True, indent=4) # Programı kapat exit(0)
fbradyirl/home-assistant
tests/components/litejet/test_scene.py
Python
apache-2.0
1,928
0.001037
"""The tests for the litejet component.""" import logging import unittest from unittest import mock from homeassistant import setup from homeassistant.components import litejet from tests.common import get_test_home_assistant from tests.components.scene import common _LOGGER = logging.getLogger(__name__) ENTITY_SCE...
n "Mock Scene #" + str(number) self.mock_lj = mock_pylitejet.return_value self.mock_lj.lo
ads.return_value = range(0) self.mock_lj.button_switches.return_value = range(0) self.mock_lj.all_switches.return_value = range(0) self.mock_lj.scenes.return_value = range(1, 3) self.mock_lj.get_scene_name.side_effect = get_scene_name assert setup.setup_component( se...
KamilSzot/365_programs
2017-01-27/input_data.py
Python
unlicense
6,497
0.000154
#!/usr/bin/env python # This file comes from here: https://github.com/llSourcell/tensorflow_demo/blob/master/input_data.py """Functions for downloading and reading MNIST data.""" import gzip import os from six.moves.urllib.request import urlretrieve import numpy SOURCE_URL = 'http://yann.lecun.com/exdb/mnist...
elf, images, labels, fake_da
ta=False): if fake_data: self._num_examples = 10000 else: assert images.shape[0] == labels.shape[0], ( "images.shape: %s labels.shape: %s" % (images.shape, labels.shape)) self._num_examples ...
nacc/autotest
client/net/net_utils_mock.py
Python
gpl-2.0
2,952
0.004743
"""Set of Mocks and stubs for network utilities unit tests. Implement a set of mocks and stubs use to implement unit tests for the network libraries. """ import socket from autotest.client.shared.test_utils import mock from autotest.client.net import net_utils def os_open(*args, **kwarg): return os_stub('open')...
urn os_stub.readval def netutils_netif(iface): return netif_stub(iface, 'net_utils', net_utils.netif) class netif_stub(mock.mock_class): def __init__(self, iface, cls, name, *
args, **kwargs): mock.mock_class.__init__(self, cls, name, args, *kwargs) def wait_for_carrier(self, timeout): return class socket_stub(mock.mock_class): """Class use to mock sockets.""" def __init__(self, iface, cls, name, *args, **kwargs): mock.mock_class.__init__(self, cls, na...
rvrheenen/OpenKattis
Python/conundrum/conundrum.py
Python
mit
128
0.023438
cypher = input() per = "PER
" count = 0 for i in range(len(cypher)): if cypher[i] != per[i%3]: count +=
1 print(count)
freevo/freevo1
src/tv/plugins/xawtv.py
Python
gpl-2.0
9,292
0.004305
# -*- coding: iso-8859-1 -*- # ----------------------------------------------------------------------- # xawtv.py - use xawtv for tv viewing # ----------------------------------------------------------------------- # $Id$ # # Notes: # Todo: # # ----------------------------------------------------------------------- # F...
ANNELS) def Play(self, mode, tuner_channel=None, channel_change=0): if tuner_channel != None: try: self.TunerSetChannel(tuner_channel) except ValueError: pass if not tuner_channel: tuner_channel = self.fc.getChannel() vg ...
eoGroup(tuner_channel, True) if not vg.group_type == 'normal': print 'Xawtv only supports normal. "%s" is not implemented' % vg.group_type return if mode == 'tv' or mode == 'vcr': w, h = config.TV_VIEW_SIZE cf_norm = vg.tuner_norm cf_input =...
mwaskom/seaborn
examples/anscombes_quartet.py
Python
bsd-3-clause
430
0
""" Anscombe's quartet ================== _thumb: .4, .4 """ import seaborn as sns sns.set_theme(style="ticks") # Load the example dataset for Anscombe's quartet df = sns.load_dataset("anscombe") # Show the results of a linea
r regression within each dataset sns.lmplot(x="x", y="y", col="da
taset", hue="dataset", data=df, col_wrap=2, ci=None, palette="muted", height=4, scatter_kws={"s": 50, "alpha": 1})
663project/fastica_lz
fastica_lz/fastica_lz.py
Python
mit
2,082
0.022574
# coding: utf-8 # In[ ]: import numpy as np import numexpr as ne def sym_decorrelation_ne(W): """ Symmetric decorrelation """ K = np.dot(W, W.T) s, u = np.linalg.eigh(K) return (u @ np.diag(1.0/np.sqrt(s)) @ u.T) @ W # logcosh def g_logcosh_ne(wx,alpha): """derivatives of logcosh""" return n...
mp,:] X1 = k @ X # initial random weght vector w_init = np.random.normal(size=(n_comp, n_comp)) W = sym_decorrelation_ne(w_init) lim = 1 it = 0 # The FastICA algorithm while lim > tol and it < maxit : wx = W @ X1 if f =="logcosh": gwx = g_logcosh_ne(...
elif f =="exp": gwx = g_exp_ne(wx,alpha) g_wx = gprimeg_exp_ne(wx,alpha) else: print("doesn't support this approximation negentropy function") W1 = np.dot(gwx,X1.T)/X1.shape[1] - np.dot(np.diag(g_wx.mean(axis=1)),W) W1 = sym_decorrelation_ne(W1) ...
Muges/audiotsm
examples/sine.py
Python
mit
957
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ sine ~~~~ Run a TSM procedure on a signal generated with numpy. """ # pylint: disable=invalid-name import numpy as np import sounddevice as sd from audiotsm import wsola from audiotsm.io.array import ArrayReader, ArrayWriter # The parameters of the input signal le...
# in seconds samplerate = 44100 # in Hz frequency = 440 # an A4 # Generate the input signal time
= np.linspace(0, length, int(length * samplerate)) input_signal = np.sin(np.pi * frequency * time).reshape((1, -1)) # Run the TSM procedure reader = ArrayReader(input_signal) writer = ArrayWriter(channels=1) tsm = wsola(channels=1, speed=0.5) tsm.run(reader, writer) # Play the output # This example was written to sh...
miniworld-project/miniworld_core
miniworld/concurrency/StopThread.py
Python
mit
883
0.001133
from threading import Event import threading # encoding: utf-8 __author__ = "Nils Tobias Schmidt" __email__ = "schmidt89 at informatik.uni-marburg.de" class StopThread(threading.Thread): """ Extends the `Thread` with an `Event` and the `terminate` method like the `multiprocessing` api offers it. Callin...
nt`. Just implement your cleanup code for this event. """
def __init__(self, *args, **kwargs): super(StopThread, self).__init__(*args, **kwargs) self.shall_terminate_event = Event() def terminate(self): """ Immitate the `processing` API and offer a way to do some clean up in the `Thread`. """ self.shall_terminate_event.set() def...
VeritasOS/cloud-custodian
c7n/resources/iot.py
Python
apache-2.0
1,009
0
# Copyright 2016 Capital One Services, 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 agreed to in...
erning permissions and
# limitations under the License. from c7n.query import QueryResourceManager from c7n.manager import resources @resources.register('iot') class IoT(QueryResourceManager): class resource_type(object): service = 'iot' enum_spec = ('list_things', 'things', None) name = "thingName" i...
BPI-SINOVOIP/BPI-Mainline-kernel
toolchains/gcc-linaro-7.3.1-2018.05-x86_64_arm-linux-gnueabihf/share/gdb/python/gdb/FrameDecorator.py
Python
gpl-2.0
10,392
0.00154
# Copyright (C) 2013-2018 Free Software Foundation, Inc. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This progr...
return self.sym class FrameVars(object): """Utility class to fetch and store frame local variables, or frame argu
ments.""" def __init__(self, frame): self.frame = frame self.symbol_class = { gdb.SYMBOL_LOC_STATIC: True, gdb.SYMBOL_LOC_REGISTER: True,
OCA/carrier-delivery
delivery_price_by_category/models/delivery_carrier.py
Python
agpl-3.0
2,275
0
# -*- coding: utf-8 -*- # Copyright 2018 Simone Rubino - Agile Business Group # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, models from odoo.tools import safe_eval class DeliveryCarrier(models.Model): _inherit = 'delivery.carrier' @api.multi def get_price_ava...
break else: test = safe_eval( line.variable + line.operator + str(line.max_value), price_dict) if test: break if category_price: return category_price # Note that thi...
e(order) def get_price_dict(self, order): weight = volume = quantity = 0 total_delivery = 0.0 for line in order.order_line: if line.state == 'cancel': continue if line.is_delivery: total_delivery += line.price_total if not ...
8l/beri
cheritest/trunk/tests/cp2/test_cp2_creturn_trap.py
Python
apache-2.0
2,300
0.003478
#- # Copyright (c) 2013 Michael Roe # All rights reserved. # # This software was developed by SRI International and the University of # Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-10-C-0237 # ("CTSRD"), as part of the DARPA CRASH research programme. # # @BERI_LICENSE_HEADER_START@ # # Licensed to BER...
return_trap(BaseBERITestCase): @attr('capabilities') def test_cp2_creturn1(self): '''Test that creturn causes a trap''' self.assertRegisterEqual(self.MIPS.a2, 2, "creturn did not cause the right trap handler to be run") @attr('capabilities') def test_cp_creturn2(self): ...
lities') def test_cp_creturn3(self): '''Test that $kcc is copied to $pcc when trap handler runs''' self.assertRegisterEqual(self.MIPS.a4, 0x7fffffff, "$pcc was not set to $kcc on entry to trap handler") @attr('capabilities') def test_cp_creturn4(self): '''Test that cretu...
AndyGrant/EtherealBenchmarking
EtherBench/views.py
Python
gpl-3.0
11,198
0.012413
from django.contrib.auth import authenticate from django.contrib.auth import login as loginUser from django.contrib.auth import logout as logoutUser from django.contrib.admin.views.decorators import staff_member_required from django.contrib.auth.models import User from django.http import HttpResponse, HttpResponseRedir...
est.POST["username"], request.POST["email"], request.POST["password"]) user.save() loginUser(request, user) # Send them back to the home page return index(request) except Exception as err: return index(request,
"Unable to Register (Missing Field / Name Taken)") def login(request): # User trying to view the login page if request.method == "GET": return render(request, "login.html", {}) # User made a post request to /login.html, process it try: # Attempt to login the user, and send the...
aagallag/nexmon
utilities/aircrack-ng/scripts/dcrack.py
Python
gpl-3.0
17,795
0.044338
#!/usr/bin/python import sys import os import subprocess import random import time import sqlite3 import threading import hashlib import gzip import json import datetime import re if sys.version_info[0] >= 3: from socketserver import ThreadingTCPServer from urllib.request import urlopen, URLError from urllib.parse...
_pass(n, qs['pass'][0]) wl = qs['wl'][0] c = con.cur
sor() c.execute("SELECT * from nets where bssid = ?", (n,)) r = c.fetchone() if r and r['state'] == 2: return "Already done" c.execute("""UPDATE work set state = 2 where net = ? and dict = ? and start = ? and end = ?""", (n, wl, qs['start'][0], qs['end'][0])) con.commit() if c.rowcount == 0: ...
intel/ipmctl
src/os/ini/ini_auto_gen_default_config.py
Python
bsd-3-clause
682
0.001466
# Copyright (c) 2018, Intel Corporation. # SPDX-License-Identifier: BSD-3-Clause # Create the ixp_default.conf file used by installer based on the ixp_default.h import argparse delete_list = ["\"", "\\n"] parser = argparse.ArgumentParser(description='The default ini conf file generator.') parser.add_argument('src_f...
args = parser.parse_args() infile = open(args.src_file, 'r') outfile = open(args.dest_file, 'w') for line in infile: if line.rstr
ip(): for word in delete_list: line = line.replace(word, "") outfile.write(line) infile.close() outfile.close()
tidalcycles/tidalcycles.github.io
bin/build_examples.py
Python
gpl-3.0
1,514
0.002642
#!/usr/bin/python import glob import os.path import re import hashlib from bs4 import BeautifulSoup from subprocess import call, Popen, PIPE, STDOUT root = "/home/alex/tidalcycles.github.io/_site/" dnmatcher = re.compile(r'^\s*d[0-9]\s*(\$\s*)?') crmatcherpre = re.compile(r'^[\s\n\r]*') crmatcherpost = re.compile(r'[...
= re.compile(r'\bsize\b') outpath = "../patterns/" for fn in glob.glob(os.path.join(root, "*.html")): soup = BeautifulSoup(open(fn), 'lxml') patterns = soup.find_all("div", "render") if len(patterns) > 0: print(fn + " (" + str(len(patterns)) +")") for pattern in patterns: cod...
tcherpost.sub('', code) digest = hashlib.md5(code).hexdigest() code = sizematcher.sub('Sound.Tidal.Context.size', code) outfn = outpath + digest + ".mp3" if (not os.path.exists(outfn)): print "building outfn: " + outfn print "digest:" + di...
cajal/pupil-tracking
setup.py
Python
mit
1,026
0.001949
#!/usr/bin/env python from setuptools import setup, find_packages from os import path here = path.abspath(path.dirname(__file__)) long_description = "Pupil tracking library for mouse pupil" setup( name='pupil_tracking', version='0.1.0.dev1', description="Pupil tracker library.", long_description=long...
='jugnu.ag.jsr@gmail.com sinz@bcm.edu', license="Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License", url='https://github.com/cajal/pupil-tracking', keywords='eyetracker', packages=find_packages(exclude=['contrib', 'docs', 'tests*']), install_requires=['numpy'
], classifiers=[ 'Development Status :: 1 - Beta', 'Intended Audience :: Science/Research', 'Programming Language :: Python :: 3 :: Only', 'License :: OSI Approved :: Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License', 'Topic :: Database :: Front-Ends...
mcalmer/spacewalk
spacecmd/src/lib/utils.py
Python
gpl-2.0
24,782
0.000726
# # Licensed under the GNU General Public License Version 3 # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This p...
re passed to the function, and if so, # declare that the function is non-interactive # note: because we do it this way, default options are not passed into # OptionParser, as it would make determining if any options were passed # too complex def is_
interactive(options): for key in options.__dict__: if options.__dict__[key]: return False return True def load_cache(cachefile): data = {} expire = datetime.now() logging.debug('Loading cache from %s', cachefile) if os.path.isfile(cachefile): try: inp...
pulinagrawal/nupic
examples/opf/experiments/opfrunexperiment_test/simpleOPF/hotgym/description.py
Python
agpl-3.0
16,183
0.003399
# ---------------------------------------------------------------------- # 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 terms and conditions apply: # # This progra...
ncoderFieldName2_W = 5, # dsEncoderSchema = [ # base=dict( # fieldname='Name2', type='ScalarEncoder', # name='Name2', minval=0, maxval=270, clipInput=True, # n=DeferredDictLookup('_dsEncoderFieldName2_N'), #
w=DeferredDictLookup('_dsEncoderFieldName2_W')), # ], # ) # updateConfigFromSubConfig(config) # applyValueGettersToContainer(config) config = { # Type of model that the rest of these parameters apply to. 'model': "CLA", # Version that specifies the format of the config. ...
596acres/django-livinglots-groundtruth
livinglots_groundtruth/forms.py
Python
bsd-3-clause
569
0
from django import forms fro
m django.utils.translation import ugettext_lazy as _ class GroundtruthRecordFormMixin(forms.ModelForm): def clean(self): cleaned_data = super(GroundtruthRecordFormMixin, self).clean() contact_email = cleaned_data.get('contact_email', None) contact_phone = cleaned_data.get('contact_phone',...
'phone number')) return cleaned_data
hiuwo/acq4
acq4/analysis/modules/MapCombiner/__init__.py
Python
mit
36
0
from Ma
pCombiner import MapCom
biner
tdavis/inboxtix
inboxtix/home/views.py
Python
mit
594
0.006734
from django.http import HttpResponse, HttpResponseForbidden from django.core.cache import cache from inboxtix.util import get_api_tree def autocom
plete_category(request): if not request.is_ajax(): return HttpResponseForbidden() name = request.GET.get('q',None) limit = request.GET.get('limit', 10) if not name: return HttpResponse('') tree =
get_api_tree('category', 'search', **{'name':name, 'limit':limit}) matches = [] for cat in tree.iter('category'): matches.append(cat.find('name').text) return HttpResponse('\n'.join(matches))
btbonval/DieStatistician
tests/testseries.py
Python
mit
1,440
0.000694
''' Bryan Bonvallet 2013 This file tests functionality of series.py (and PMF.py). ''' from testbase import FinitePMF from testbase import InfinitePMF from testbase import TestSeriesPMF class TestSeries(TestSeriesPMF): # Test functions in series.py def test_finite_str(self): # Test that a string is r...
) or isinstance(test, unicode)) def test_infinite_str(self): # Test that a string is returned. obj = self._build_infinite_obj() test = str(obj) self.assertTrue(isinstance(test, str) or isinstance(test, unicode)) def test_infinite_str_maxterms(self): # Test that maxterms...
t display them all. obj = self._build_infinite_obj(terms*3) test = str(obj) # This test makes strong assumptions about the string representation. # Assume terms are listed in rows # Grab the first row of terms between square brackets nums = test.split('[')[-1].split(']')...
edoburu/django-fluent-contents
fluent_contents/plugins/oembeditem/__init__.py
Python
apache-2.0
199
0
VERSION = (0, 1, 0) # Do some version check
ing try: import micawber except ImportError: raise ImportError(
"The 'micawber' package is required to use the 'oembeditem' plugin." )
Csega/PythonCAD3
Interface/cadscene.py
Python
gpl-2.0
15,874
0.006678
# # Copyright (c) 2010 Matteo Boscolo, Gertwin Groen # # This file is part of PythonCAD. # # PythonCAD is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any...
distance = self.getDistance(event) self.activeICommand.updateMauseEvent(point, distance, qtItem) # self.updatePreview(self,point, distance) # # path=QtGui.QPainterPath() # path.addRect(scenePos.x()-self.__grapWithd/2, scenePos.y()+self.__grapWithd/2, ...
, event): if event.button() == QtCore.Qt.MidButton: self.isInPan = True self.firePan(True, event.scenePos()) if not self.isInPan: qtItem = self.itemAt(event.scenePos(), QtGui.QTransform()) p = QtCore.QPointF(event.scenePos().x(), event.scenePos().y()) ...
GroestlCoin/electrum-grs
electrum_grs/gui/qt/exception_window.py
Python
gpl-3.0
7,308
0.001505
#!/usr/bin/env python # # Electrum - lightweight Bitcoin client # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, ...
E_CHECKING, Optional, Set from PyQt5.QtCore import QObject import PyQt5.QtCore as QtCore from PyQt5.QtWidgets import (QWidget, QLabel, QPushButton, QTextEdit, QMessageBox, QHBoxLayout, QVBoxLayout) from electrum_grs.i18n import _ from electrum_grs.base_crash_reporter import BaseCrashRepor...
twork from .util import MessageBoxMixin, read_QIcon, WaitingDialog if TYPE_CHECKING: from electrum_grs.simple_config import SimpleConfig from electrum_grs.wallet import Abstract_Wallet class Exception_Window(BaseCrashReporter, QWidget, MessageBoxMixin, Logger): _active_window = None def __init__(se...
Alshootfa/I.K.R.A
app.py
Python
mit
3,051
0.004916
from flask import Flask, url_for, redirect, request, render_template, send_from_directory from flask.ext.sqlalchemy import SQLAlchemy from model import * from werkzeug import secure_filename import os ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'mp4']) if not os.path.exists('data/media'): ...
e=course) def get_courses_dir(course_id): result = os.path.join('courses', course_id) try: os.makedirs(result) except OSError: pass return result @app.route('/
courses/<course_id>') def get_course(course_id): course = Course.query.filter_by(ID=course_id).first() media = Media.query.filter_by(course_id=course_id) return render_template('course.html', course=course, media=media) @app.route('/courses/<course_id>/media/<name>') def get_media(course_id, name): med...
gratefulfrog/ArduGuitar
Ardu2/design/POC-3_MAX395/pyboard/V1_WithHMI/PyHMI/oClasses.py
Python
gpl-2.0
5,003
0.017789
#oClasses.py import Classes class LCDMgr: display = 0 editing = 1 eoEdit = 2 error = 3 confirmAbortMode = 4 #modes = [display, editing, eoEdit, error,confirmAbortMode] cursorOff =-1 cursorStart = 0 eoLine = 15 lineLength = 16 letters = ['A','a','B','b','C','c','D','d'] ...
arPtr] self.updateEditDisplay() def confirmed(self): if self.validateFunc(self.lcd.getLn(0)): # put a real test here for the display Char list self.
stateString = ''.join([c for c in self.displayCharList if c != ' ']) self.lcd.setLn(0,self.stateString) self.lcd.setLn(1,self.stateName) self.setDisplayMode() else: self.setEditingMode(True) def onRightButton(self): #print('onRi...
artefactual/archivematica-storage-service
storage_service/locations/api/urls.py
Python
agpl-3.0
865
0
from __future__ import absolute_import from django.conf.urls import include, url from tastypie.api import Api from locations.api import v1, v2 from locations.api.sword import views v1_api = Api(api_name="v1") v1_api.register(v1.SpaceResource()) v1_api.register(v1.LocationResource()) v1_api.register(v1.PackageResource...
syncResource()) urlpatterns = [ url(r"", include(v1_api.urls)), url(r"v
1/sword/$", views.service_document, name="sword_service_document"), url(r"", include(v2_api.urls)), url(r"v2/sword/$", views.service_document, name="sword_service_document"), ]
dana-i2cat/felix
expedient/doc/plugins/samples/plugin/sample_resource/controller/GUIdispatcher.py
Python
apache-2.0
7,485
0.011089
""" Graphical user interface functionalities for the SampleResource Aggregate Manager. @date: Jun 12, 2013 @author: CarolinaFernandez """ from django.core.exceptions import ValidationError from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect, HttpResponse from django.shortcuts imp...
ates(slice) ui_context['nodes'], ui_context['links'] = get_nodes_links(slice) except Exception as e: print "[ERROR] Problem loading UI data for p
lugin 'sample_resource'. Details: %s" % str(e) return ui_context
DougFirErickson/neon
neon/backends/tests/test_tensor.py
Python
apache-2.0
4,727
0.000635
# ---------------------------------------------------------------------------- # Copyright 2015 Nervana Systems Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.o...
llclose(numpy_result, nervanaGPU_result, rtol=0, atol=1e-5) cpu = NervanaCPU(default_dtype=dtype) nervanaCPU_result = math_helper(cpu, op, inA, inB, dtype=dtype) nervanaCPU_result = nervanaCPU_result.get() np.allclose(numpy_result, nervanaCPU_result, rtol=0, atol=1e-5) def rand_unif(dtype, dims):
if np.dtype(dtype).kind == 'f': return np.random.uniform(-1, 1, dims).astype(dtype) else: iinfo = np.iinfo(dtype) return np.around(np.random.uniform(iinfo.min, iinfo.max, dims)).clip(iinfo.min, iinfo.max) def pytest_generate_tests(metafunc): """ Build a list of test arguments. ...
lucidlylogicole/monkey
monkey.py
Python
gpl-3.0
11,008
0.014353
from PyQt4 import QtGui, QtCore, QtWebKit, Qsci import os, sys, pickle from monkey_ui import Ui_Monkey sys.path.append('../') import settings class Monkey(QtGui.QWidget): def __init__(self,parent=None): QtGui.QWidget.__init__(self,parent) self.ui = Ui_Monkey() self.ui.setupUi(self) ...
out(layout) self.ui.le_project.setPlaceholderText('Pro
ject Name') self.ui.fr_proj.layout().addWidget(self.ui.b_new ,0,0,1,1) self.ui.fr_proj.layout().addWidget(self.ui.le_project ,0,1,1,1) self.ui.fr_proj.layout().addWidget(self.ui.b_save ,0,2,1,1) self.ui.tab_top.setCornerWidget(self.ui.fr_proj) self.ui.le_project.show() ...
rogerthat-platform/rogerthat-backend
src/rogerthat/service/api/app.py
Python
apache-2.0
17,482
0.002402
# -*- coding: utf-8 -*- # Copyright 2017 GIG Technology NV # # 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...
O) app_id (unicode) Returns: AppSettingsTO """ service_user = users.get_current_user() if not app_id: app_id = get_default_service_identity(service_user).app_id validate_app_admin(service_user, [app_id]) return AppSettingsTO.from_model(bizz_app.put_settings(app_id, setti...
e_api(function=u'app.put_loyalty_user') @returns(PutLoyaltyUserResultTO) @arguments(url=unicode, email=unicode) def put_lo
bwind/propeller
propeller/response.py
Python
bsd-2-clause
4,589
0.000436
from datetime import timedelta from propeller.cookie import Cookie from propeller.options import Options from propeller.template import Template from propeller.util.dict import MultiDict from urllib import quote import httplib import propeller class Response(object): def __init__(self, body='', status_code=200, ...
def _error_page(self, title, subtitle='', traceback=None):
t = Options.tpl_env.get_template('error.html') return t.render( title=title, subtitle=subtitle, traceback=traceback, version=propeller.__version__ ) def set_cookie(self, name, value, domain=None, expires=None, path=None, secure=Fals...
chengduoZH/Paddle
python/paddle/fluid/profiler.py
Python
apache-2.0
13,034
0.003683
# Copyright (c) 2018 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 app...
profiling config by `config` argument. After getting the profiling result file, users can use `NVIDIA Visual Profiler <https://developer.nvidia.com/nvidia-visual-profiler>`_ to load this output file to visualize results. Args: output_file (str) : The output file name, the result will be...
and Comma separated values format ('csv', default). config (list<str>, optional) : Nvidia profile config. Default config is ['gpustarttimestamp', 'gpuendtimestamp', 'gridsize3d', 'threadblocksize', 'streamid', 'enableonstart 0', 'conckerneltrace']. For more details, please ...
linefeedse/korjournal
www/korjournal/permissions.py
Python
gpl-2.0
2,170
0.003687
from rest_framework import permissions from korjournal.models import Driver class IsOwner(permissions.BasePermission): """ Custom permission to only allow owners of an object to see it """ def has_object_permission(self, request, view, obj): user = request.user
try: if (obj.owner == user): return True else: return False except AttributeError: try: if (obj.vehicle.owner == user): return True else:
return False except AttributeError: try: if (obj.odometersnap.vehicle.owner == user): return True else: return False except AttributeError: return ...
marev711/scripts
medlemsinput.py
Python
mit
2,300
0.006957
# Graphical paste and save GUI for adding members from Tkinter import * import os import pdb import datetime lday = 04 lmonth = 10 class myDate: def __init__(self, year, month, day): self.date = datetime.datetime(year, month, day) self.updateString() def getMonthDay(self): lday = for...
dd(SEL, "1.0", END) text.mark_set(INSERT, "1.0") text.see(INSERT) return 'break' def nextfname(prefix): first = 1 fstr = format(first, '02') while os.path.exists(prefix + "-" + fstr + ".txt"): f
irst = first + 1 fstr = format(first, '02') return fstr root = Tk() text = Text(root) text.insert(INSERT, "") text.bind("<Control-Key-a>", select_all) text.grid() bsave = Button(root, text="Save", command=lambda: save(date)) bsave.grid(columnspan=2, column=1, row=0) dplus = Button(root, text="d+", comma...
ElliottH/tvrename
tvrename.py
Python
mit
7,125
0.002105
#!/usr/bin/env python from __future__ import print_function import os import sys import argparse import re import shutil class Colour(object): """Utility class for colour printing messages""" RED = '\033[91m' WHITE = '\033[97m' END = '\033[0m' @staticmethod def print(colour, msg, end="\n"): ...
os.path.join(os.path.dirname(name), new_name) self.confirm_move(fname, new_path) def confirm_move(self, src, dest):
""" Move file from src to dest * If args.dry_run is True, then we don't actually do anythin. * If args.confirm is True, then we ask first. """ if os.path.isfile(dest): Colour.red("Not moving %s to %s as file already exists" % (src, dest)) elif os.path...
jacoboariza/BotIntendHub
yahooWeatherForecast.py
Python
apache-2.0
335
0.00597
#!/usr/bin/env python def makeYqlQuery(req): result = req.get("result") parameters = result.get("parameters") city = parameters.get("geo-city") if city is None: return None return "select * from weather.forecast where woeid in (select woeid fro
m geo.places(1) where text='" + city + "') and
u='c'"
mldbai/mldb
testing/plugin_delete_test.py
Python
apache-2.0
856
0.005841
# This file is part of MLDB. Copyright 201
5 mldb.ai inc. All rights reserved. pythonScript = { "type": "python", "params": { "address": "", "source": """ mldb.log("Constructing plugin!") def requestHandler(mldb, remaining, verb, resource, restParams, payload, contentType, contentLength, headers): mldb.log("waqlsajf;lasdf") ...
("hoho") mldb.log("ouin") mldb.log(str(mldb.perform("PUT", "/v1/plugins/plugToDel", [["sync", "true"]], pythonScript))) mldb.log(str(mldb.perform("GET", "/v1/plugins", [], {}))) rtn= mldb.perform("GET", "/v1/plugins/plugToDel/routes/miRoute", [], {}) print(rtn) request.set_return(rtn["response"])
noamelf/Open-Knesset
laws/management/commands/freeze_bills.py
Python
bsd-3-clause
1,347
0
from __future__ import print_function from django.core.management.base import BaseCommand from optparse import make_option from laws.models import Bill from laws.vote_choices import BILL_STAGE_CHOICES from mks.models import Knesset class Command(BaseCommand): help = "Freeze bills staged in previous knessets" ...
if options['dryrun']: print("Not updating the db, dry run was specified") else: print('Settings {0} bills stage to u"0"'.format(found)) bills.
update(stage=u'0')
alexeyshulzhenko/OBDZ_Project
OnlineAgecy/urls.py
Python
gpl-3.0
3,927
0.005348
#!python # log/urls.py from django.conf.urls import url from . import views # We are adding a URL called /home urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^clients/$', views.clients, name='clients'), url(r'^clients/(?P<id>\d+)/$', views.client_detail, name='client_detail'), url(r'^clie...
lients/(?P<id>\d+)/edit/$', views.client_edit, name='client_edit'), url(r'^clients/sevices/$', views.clients_services_count, name='clients_services_count'), url(r'^clients/bills/(?P<id>\d+)/$', views.all_clients_bills, name='all_clients_bil
ls'), url(r'^clients/bills/$', views.fresh_clients, name='fresh_clients'), url(r'^clients/del/(?P<id>\d+)/$', views.delete_client, name='delete_client'), url(r'^contracts/$', views.contracts, name='contracts'), url(r'^contracts/(?P<id>\d+)/$', views.contract_detail, name='contract_detail'), url(r'^...
apache/incubator-cotton
mysos/executor/shell_utils.py
Python
apache-2.0
3,152
0.011421
"""Set of utility functions for working with OS commands. Functions in this module return the command string. These commands are composed but not executed. """ import os from subprocess import call HADOOP_CONF_DIR = '/etc/hadoop/conf' def encrypt(key_file): """ Encrypt the data from stdin and write output t...
ip. """ if extension == "gz": cmd = "pigz -d" if exists("pigz") else "gzip -d"
elif extension == "bz" or extension == "bz2": cmd = "bzip2 -d" elif extension == 'lzo': cmd = "lzop -d" else: raise ValueError("Unknown compression format/file extension") return cmd def hdfs_cat(uri, conf=HADOOP_CONF_DIR): """ Fetch the data from the specified uri and write output to stdout...
qsnake/gpaw
gpaw/xc/hybridk.py
Python
gpl-3.0
14,413
0.002637
# Copyright (C) 2010 CAMd # Please see the accompanying LICENSE file for further information. """This module provides all the classes and functions associated with the evaluation of exact exchange with k-point sampling.""" from math import pi, sqrt import numpy as np from ase import Atoms from gpaw.xc import XC fr...
phase_cd = np.exp(2j * pi * self.gd.sdisp_cd * k_c[:, np.newaxis]) kpt2 = KPoint0(kpt.weight,
kpt.s, k, None, phase_cd) kpt2.psit_nG = np.empty_like(kpt.psit_nG) kpt2.f_n = kpt.f_n / kpt.weight / K * 2 for n, psit_G in enumerate(kpt2.psit_nG): psit_G[:] = kd.transform_wave_function(kpt.psit_nG[n], k1) kpt2.P_ani = self.pt.dict(len(kpt.psit_nG)) ...
skarllot/open-tran
lib/stem/snowball.py
Python
gpl-2.0
136,128
0.004988
# -*- coding: utf-8 -*- # # Natural Language Toolkit: Snowball Stemmer # # Copyright (C) 2001-2010 NLTK Project # Author: Peter Michael Stahl <pemistahl@gmail.com> # Algorithms: Dr Martin Porter <martin@tartarus.org> # URL: <http://www.nltk.org/> # For license information, see LICENSE.TXT u""" Snowball stemmers and ap...
uage in Uni
code format. @type stopwords: C{list} """ languages = ("danish", "dutch", "finnish", "french", "german", "hungarian", "italian", "norwegian", "portuguese", "romanian", "russian", "spanish", "swedish") def __new__(cls, language, **kwargs): u""" ...
hguemar/cinder
cinder/zonemanager/drivers/cisco/cisco_fc_zone_driver.py
Python
apache-2.0
23,043
0
# (c) Copyright 2014 Cisco Systems Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unl...
if len(base_san_opts) > 0: CONF.register_opts(base_san_opts) self.configuration.append_config_values(base_san_opts) fabric_names = [x.strip() for x in self. configuration.fc_fabric_names.split(',')] # There can be more than one...
self.fabric_configs = fabric_opts.load_fabric_configurations( fabric_names) @lockutils.synchronized('cisco', 'fcfabric-', True) def add_connection(self, fabric, initiator_target_map): """Concrete implementation of add_connection. Based on zoning policy and state of each I-...
wkmanire/StructuresAndAlgorithms
pythonpractice/bubblesort.py
Python
gpl-3.0
819
0
# -*- coding:utf-8; mod
e:python -*- """ A terrible sorting algorithm |----------------------+-----------------------+------------------| | Best Time Complexity | Worst Time Complexity | Space Complexity | |----------------------+--------------------
---+------------------| | O(n^2) | O(n) | O(n) | |----------------------+-----------------------+------------------| """ from random import randint from helpers import random_array, print_array, swap def bubble_sort(array): for i in range(len(array) - 1): for ...
Erethon/synnefo
snf-cyclades-app/synnefo/logic/rapi.py
Python
gpl-3.0
54,880
0.003243
# # # Copyright (C) 2010, 2011 Google Inc. # Copyright (C) 2013, GRNET S.A. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later ve...
de = code class CertificateError(GanetiApiError): """Raised when a problem is found with the SSL certificate. """ pass def _AppendIf(container, condition, value): """Appends to a list if a conditi
on evaluates to truth. """ if condition: container.append(value) return condition def _AppendDryRunIf(container, condition): """Appends a "dry-run" parameter if a condition evaluates to truth. """ return _AppendIf(container, condition, (_QPARAM_DRY_RUN, 1)) def _AppendForceIf(container, condition...
naphthalene/fabric-bolt
fabric_bolt/launch_window/migrations/0001_initial.py
Python
mit
1,427
0.006307
# -*- coding: utf-8 -*- from south.utils import datetime_utils as 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 'LaunchWindow' db.create_table(u'launch_window_launchwindo...
('description', self.gf('django.db.models.fields.TextField')()), ('cron_format', self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True)), ))
db.send_create_signal(u'launch_window', ['LaunchWindow']) def backwards(self, orm): # Deleting model 'LaunchWindow' db.delete_table(u'launch_window_launchwindow') models = { u'launch_window.launchwindow': { 'Meta': {'object_name': 'LaunchWindow'}, 'cron_forma...
OstapHEP/ostap
ostap/frames/tree_reduce.py
Python
bsd-3-clause
12,435
0.052352
#!/usr/bin/env python # -*- coding: utf-8 -*- # ============================================================================= ## @file ostap/frames/tree_reduce.py # Helper module to "Reduce" tree using frames # @see Ostap::DataFrame # @see ROOT::RDataFrame # @author Vanya BELYAEV Ivan.Belyaev@itep.ru # @date 201...
# tree = ... # r = ReduceTree ( tree , cuts , [ 'px', 'py', 'pz' ] , 'new_file.root' ) # reduced = t.tree # @endcode class ReduceTree(CleanUp): """Reduce ROOT.TTree object >>> tree = ... >>> r = ReduceTree ( tree , cuts
, [ 'px', 'py', 'pz' ] >>> reduced = r.tree """ def __init__ ( self , chain , ## input TChain/TTree selection = {} , ## selection/cuts save_vars = () , ## list of variables to save n...
luo2chun1lei2/AgileEditor
ve/src/VeUtils.py
Python
gpl-2.0
503
0.014458
#
-*- coding:utf-8 -*- # 各种方便的工具。 import os, logging, threading def is_empty(string): # 判断是否空字符串,如果是空格之类的,也是empty。 # return:Bool:True,空 False,非空 if string is None or len(string) == 0: return True elif string.isspace(): return True else: return False def is_not_empty(st...
_empty(string)
annarev/tensorflow
tensorflow/compiler/xla/python/xla_client.py
Python
apache-2.0
24,551
0.005539
# Lint as: python3 # Copyright 2017 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 ...
pe annotations. # pylint: disable=invalid-sequence-index ops = _xla.ops profiler = _xla.profiler # Just an internal arbitrary increasing number to help with backward-compatible # changes. _version = 5 xla_platform_names = { 'cpu': 'Host', 'gpu': 'CUDA', } def _interpreter_backend_factor
y(): return _xla.get_interpreter_client() def _cpu_backend_factory(): return _xla.get_cpu_client(asynchronous=True) def _gpu_backend_factory(distributed_client=None, node_id=0): """Returns a GPU backend. BFC allocator is used by default.""" allocator = os.getenv('XLA_PYTHON_CLIENT_ALLOCATOR', 'default').low...
AiAeGames/DaniBot
dispatcher.py
Python
gpl-3.0
4,840
0.000207
import re import asyncio import threading from collections import defaultdict def connector(bot, dispatcher, NICK, CHANNELS, PASSWORD=None): @bot.on('client_connect') async def connect(**kwargs): bot.send('USER', user=NICK, realname=NICK) if PASSWORD: bot.send('PASS', password=PAS...
leep(5, loop=bot.loop) # Schedule a connection when the loop's next available bot.loop.create_task(bot.connect())
# Wait until client_connect has triggered await bot.wait("client_connect") @bot.on('ping') def keepalive(message, **kwargs): bot.send('PONG', message=message) @bot.on('privmsg') def message(host, target, message, **kwargs): if host == NICK: # don't process me...
deepmind/rlax
rlax/_src/nonlinear_bellman.py
Python
apache-2.0
7,670
0.004824
# Copyright 2019 DeepMind Technologies Limited. 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 ...
1 def transformed_n_step_q_learning( q_tm1: Array, a_tm1: Array, target_q_t: Array, a_t: Array, r_t: Array, discount_t: Array, n: int, stop_target_gradients: bool = True, tx_pair: TxPair = IDENTITY_PAIR, ) -> Array: """Calculates transformed n-step TD errors. See "Recurrent Ex...
/pdf?id=r1lyTjAqYX). Args: q_tm1: Q-values at times [0, ..., T - 1]. a_tm1: action index at times [0, ..., T - 1]. target_q_t: target Q-values at time [1, ..., T]. a_t: action index at times [[1, ... , T]] used to select target q-values to bootstrap from; max(target_q_t) for normal Q-learning, ...
Pikecillo/genna
external/PyXML-0.8.4/demo/quotes/qtfmt.py
Python
gpl-2.0
13,896
0.008923
#!/usr/bin/env python # # qtfmt.py v1.10 # v1.10 : Updated to use Python 2.0 Unicode type. # # Read a document in the quotation DTD, converting it to a list of Quotation # objects. The list can then be output in several formats. __doc__ = """Usage: qtfmt.py [options] file1.xml file2.xml ... If no filenames are provid...
fy(str(self.text)) + '*' def as_html(self): return '<em>' + string.strip(cgi.escape(str(self.text))) + '</em>' class Break(Text): def as_text(self): return "" def as_html(self): return "<P>" #
The QuotationDocHandler class is a SAX handler class that will # convert a marked-up document using the quotations DTD into a list of # quotation objects. class QuotationDocHandler(saxlib.HandlerBase): def __init__(self, process_func): self.process_func = process_func self.newqt = None # Erro...
HellerCommaA/flask-angular
lib/python2.7/site-packages/flask_restless/search.py
Python
mit
19,670
0.000153
""" flask.ext.restless.search ~~~~~~~~~~~~~~~~~~~~~~~~~ Provides querying, searching, and function evaluation on SQLAlchemy models. The most important functions in this module are the :func:`create_query` and :func:`search` functions, which create a SQLAlchemy query object and execute that que...
search`. If `argument`
is specified, it is the value to place on the right side of the operator. If `otherfield` is specified, that field on the model will be placed on the right side of the operator. .. admonition:: About `argument` and `otherfield` Some operators don't need either argument and some nee...
witjoh/enigma2_dreambox_scanner
Scanners/Movies/Enigma2 Debug Scanner.py
Python
gpl-2.0
7,163
0.006003
import re, os, os.path import Media, VideoFiles, Stack, Utils import time # # this is a start to get to learn how to write scanners # debugfile = '/tmp/enigma2_movie_debug.log' debug = True def Scan(path, files, mediaList, subdirs, language=None, root=None, **kwargs): def strip_name_from_ts_file(tsfile): ...
ine_array) genre = line_array[0]
year = line_array[1] if elements >= 3: short_info = line_array[2] else: short_info = '' elif re.search(r'\(\d{4}\)', lines[2]): if debug: ...
J22Melody/VPS-Monitor
manage.py
Python
gpl-2.0
254
0
#!/usr/bin/env python import os import
sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "vps_monitor.settings") from d
jango.core.management import execute_from_command_line execute_from_command_line(sys.argv)
zejacobi/ProjectEuler
Solutions/0031.py
Python
unlicense
2,719
0.004433
""" # PROBLEM 31 In England the currency is made up of pound, £, and pence, p, and there are eight coins in general circulation: 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p). It is possible to make £2 in the following way: 1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p How many different ways can £2 be made using a...
ues[position:]): max_pieces = int((goal - value) / pence) + 1 for n in range(1, max_pieces): if (value + pence * n) < goal: new_array = current[:] new_array[values_to_index[pence]] += n build_arrays(new_array, value + pence * n, position + 1 + ...
# seriously, it cuts down the run time 100-fold elif (value + pence * n) == goal: final = current[:] final[values_to_index[pence]] += n if final not in final_arrays: final_arrays.append(final) for array in starting_arrays[:]: build_ar...
Maethorin/py-inspector
tests/unitarios/test_validacao_pep8.py
Python
mit
1,941
0.002061
# -*- coding: utf-8 -*- import unittest from mock import MagicMock, patch from py_inspector import verificadores class CustomReport(unittest.TestCase): def test_deve_retornar_quantidade_erros(self): options = MagicMock() report = verificadores.CustomReport(options) report._deferred_print ...
, '_'), (22, 3, 'code zas', 'text zas', '_ zas')] rep
ort.get_file_results() report.results.should.be.equal([{'path': 'filename', 'code': 'code zas', 'text': 'text zas', 'col': 4, 'row': 24}, {'path': 'filename', 'code': 'code', 'text': 'text', 'col': 3, 'row': 25}]) class ValidandoPep8(unittest.TestCase): @patch('py_inspector.verificadores.assert_true') ...
qusp/orange3
Orange/preprocess/preprocess.py
Python
bsd-2-clause
6,516
0.00046
""" Preprocess ---------- """ import numpy as np import sklearn.preprocessing as skl_preprocessing import bottlechest import Orange.data from . import impute, discretize from ..misc.enum import Enum __all__ = ["Continuize", "Discretize", "Impute", "SklImpute"] def is_continuous(var): return isinstance(var, Ora...
in.attributes] domain = Orange.data.Domain( newattrs, data.domain.class_vars, data.domain.metas) return data.from_table(domain, data)
class SklImpute(Preprocess): __wraps__ = skl_preprocessing.Imputer def __init__(self, strategy='mean', force=True): self.strategy = strategy self.force = force def __call__(self, data): if not self.force and not np.isnan(data.X).any(): return data self.impute...
googleads/google-ads-python
google/ads/googleads/v9/services/services/campaign_simulation_service/transports/base.py
Python
apache-2.0
3,952
0
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
__( self, *, host: str = "googleads.googleapis.com", credentials: ga_credentials.Credentials = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiate the transport. Args: host (Optional[str]): ...
credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credent...
palichis/elmolino
elmolino/wsgi.py
Python
gpl-2.0
391
0.002558
""" WSGI config for elmolino project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.dja
ngoproject.com/en/1.7/howto/deployment/ws
gi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "elmolino.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application()
mozilla/verbatim
vendor/lib/python/translate/storage/tiki.py
Python
gpl-2.0
6,875
0.002327
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2008 Mozilla Corporation, Zuza Software Foundation # # This file is part of translate. # # translate 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; ...
getlocations() == ["untranslated"]: _untranslated.append(unit) elif unit.getlocations() == ["possiblyuntranslated"]: _possiblyuntranslated.append(unit) else: _translated.append(unit) output += "// ### Start of unused words\n" for u...
output += unicode(unit) output += "// ### end of unused words\n\n" output += "// ### start of untranslated words\n" for unit in _untranslated: output += unicode(unit) output += "// ### end of untranslated words\n\n" output += "// ### start of possibly untransla...
bryongloden/cppcheck
tools/listErrorsWithoutCWE.py
Python
gpl-3.0
645
0.006202
#!/usr/bin/python import argparse import xml.etree.ElementTree as ET def main(): parser = argparse.ArgumentParser(description="List all error without a CWE assigned in CSV format") parser.add_argument("-F", metavar="filename", required=True, help="XML file containing output from
: ./cppcheck --errorlist --xml-version=2") parsed = parser.parse_args() tree = ET.parse(vars(parsed)["F"]) root = tree.getroot() for child in root.iter("error"): if "cwe" not in child.attrib: print child.attrib["id"], ",", child.attrib["severity"], ",
", child.attrib["verbose"] if __name__ == "__main__": main()
nordicpower/GameListPatch
interphase/util.py
Python
apache-2.0
17,408
0.003389
#Interphase - Copyright (C) 2009 James Garnon <http://gatc.ca/> #Released under the MIT License <http://opensource.org/licenses/MIT> from __future__ import division import os from env import engine __docformat__ = 'restructuredtext' class Text(object): """ Receives text to display on surface. Arguments ...
efault'): """Writes text to surface.""" if surface == 'default': self.surface = self.screen else: self.surface = surface self.update() return self.surface def add(self,*message_append): """Add to text.""" for item in message_append: ...
s.append(self.message) def set_position(self, position, center=False): """Set position to write text.""" x, y = position if x < self.dimension['x'] and y < self.dimension['y']: self.x = x self.y = y if center: self.center = True ...
ifcharming/original2.0
tests/scripts/xml2/xmlparser.py
Python
gpl-3.0
6,723
0.00119
# Copyright (C) 2009 by Ning Shi and Andy Pavlo # Brown University # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, cop...
from exceptions import * class ContentParser(ContentHandler): """XML handler class. This class is used by the SAX XML parser. """ __parallels = ("Statements",) __terminals = ("SQL", "Status", "Info", "Result", "Se
ed") def __init__(self, l): """Constructor. 'l': An empty dictionary to be filled with request pairs. """ ContentHandler.__init__(self) self.rp_list = l self.__current_key = [] self.__current = [self.rp_list] def startElement(self, name, attrs): ...
izevg/CryptoLabs
first_lab.py
Python
gpl-2.0
8,202
0.003447
# -*- encoding: utf-8 -*- from __future__ import division import itertools import operator import collections debug = True to_bin = lambda integer: zero_filler(bin(integer)[2:]) def zero_filler(filling_string): result = "" if len(filling_string) != 4: result = filling_string else: return ...
binary = to_bin(value) out_table["pretty_table"].append(binary) out_table["values_table"].append(value) elif t
able_type == "S3": arr1 = out_table; arr2 = out_table; arr = out_table for j in range(0, 4): for k in range(0, 2): value = table[k][j] binary = to_bin(value) arr1["pretty_table"].append(binary) arr1["values_table"].append(value)...
coreyoconnor/nixops
nixops/resources/azure_dns_zone.py
Python
lgpl-3.0
4,631
0.003239
# -*- coding: utf-8 -*- # Automatic provisioning of Azure DNS zones. import os import azure import json from requests import Request try: from urllib import quote except: from urllib.parse import quote from nixops.util import attr_property from nixops.azure_common import ResourceDefinition, ResourceState, R...
/Microsoft.Network" "/dnsZones/{2}?api-version=2015-05-04-preview" .format(quote(self.subscription_id), quote(self.resource_group), quote(self.dns_zone_name))) def mk_request(self, method): http_request = Request() http_req...
e(self): response = self.nrpc().send_request(self.mk_request('GET')) if response.status_code == 200: return json.loads(response.content.decode()) else: return None def destroy_resource(self): response = self.nrpc().send_request(self.mk_request('DELETE')) ...
VitalPet/c2c-rd-addons
product_price_property/__openerp__.py
Python
agpl-3.0
1,905
0.009449
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # Copyright (C) 2010-2012 ChriCar Beteiligungs- und Beratungs- GmbH (<http://www.camptocamp.at>) # # Thi...
{ 'sequence': 500, 'name': 'Product Price Property', 'version': '1.0', 'category': 'Accounting & Finance', 'description': """ Creates a poperty for list and standard price on product (not template). this allows different prices for variants and companies ATT - 6.1 has server bug - ir property can not defined on "_...
cause incompatibility in custom module because the data model change """, 'author': 'ChriCar Beteiligungs- und Beratungs- GmbH', 'depends': [ 'product'], 'data': [ ], #'data': ['product_view.xml'], 'demo_xml': [], 'installable': False, 'active': False, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth...
danielvdao/facebookMacBot
venv/lib/python2.7/site-packages/twilio/rest/resources/sip/domains.py
Python
mit
5,827
0
from .. import InstanceResource, ListResource class IpAccessControlListMapping(InstanceResource): def delete(self): """ Remove this mapping (disassociate the ACL from the Domain). """ return self.parent.delete_instance(self.name) class IpAccessControlListMappings(ListResource): ...
od: The HTTP method Twilio should use when requesting the above URL. """ kwargs['domain_name'] = domain_name return self.create_instance(kwargs) def update(self, sid, **kwargs): """ Update a :class:`Domain` Available attributes to update are described a...
d: String identifier for a Domain resource """ return self.update_instance(sid, kwargs) def delete(self, sid): """ Delete a :class:`Domain`. :param sid: String identifier for a Domain resource """ return self.delete_instance(sid)
neuropoly/spinalcordtoolbox
spinalcordtoolbox/resampling.py
Python
mit
7,336
0.003544
######################################################################################### # # Resample data using nibabel. # # --------------------------------------------------------------------------------------- # Copyright (c) 2014 Polytechnique Montreal <www.neuro.polymtl.ca> # Authors: Julien Cohen-Adad, Sara Dup...
to a resolution of 1x1x5 mm :param image_dest: Destination image to resample the input image to. In this case, new_size and new_size_type are ignored :param interpolation: {'nn', 'linear', 'spline'}. The interpolation type :param mode: Outside values are filled with 0 ('constant') or nearest value (...
resampled nibabel or Image image (depending on the input object type). """ # set interpolation method dict_interp = {'nn': 0, 'linear': 1, 'spline': 2} # If input is an Image object, create nibabel object from it if type(image) == nib.nifti1.Nifti1Image: img = image elif type(image) =...
JoseBlanca/franklin
test/gmod/read_source_test.py
Python
agpl-3.0
3,791
0.006858
''' Created on 2009 eka 22 @author: peio ''' # Copyright 2009 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia # This file is part of franklin. # franklin 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 Softwa...
self.fail() except Exception: pass class LibrarySourceFileTest(unittest.TestCase): 'It uses this test to check LibrarySourceFile' @staticmethod def test_basic_use(): '''It test the basic use of the class ReadSourceFile''' read = 'ESIE1234121' ...
one_read = StringIO(CLONE_READ_LIBRARY) read_source = ReadSourceFile(fhand_clone_read) library = read_source.get_library(read) clone = read_source.get_clone(read) assert library == 'a' assert clone == '121313132clone' class ReadSourcesTest(unittest.Test...
Majsvaffla/strecklista
strecklista/wsgi.py
Python
gpl-3.0
183
0.005464
import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE
", "strecklista.settings.production") application = get_wsgi_a
pplication()
yoeo/guesslang
guesslang/model.py
Python
mit
6,714
0
"""Machine learning model""" from copy import deepcopy import logging from operator import itemgetter from pathlib import Path import shutil from tempfile import TemporaryDirectory from typing import List, Tuple, Dict, Any, Callable import tensorflow as tf from tensorflow.estimator import ModeKeys, Estimator from ten...
train_spec = tf.estimator.TrainSpec( input_fn=_build_input_fn(data_root_dir, ModeKeys.TRAIN)
, max_steps=max_steps, ) if max_steps > Training.LONG_TRAINING_STEPS: throttle_secs = Training.LONG_DELAY else: throttle_secs = Training.SHORT_DELAY eval_spec = tf.estimator.EvalSpec( input_fn=_build_input_fn(data_root_dir, ModeKeys.EVAL), start_delay_secs=Train...
agry/NGECore2
scripts/mobiles/tatooine/bantha_matriarch.py
Python
lgpl-3.0
1,676
0.02685
import sys from services.spawn import MobileTemplate from services.spawn import WeaponTemplate from resources.datatables import WeaponType from resources.datatables import Difficulty from resources.datatables import Options from jav
a.util import Vector def addTemplate(core): mobileTemplate = MobileTemplate() mobileTemplate.setCreatureName('matriarch_bantha') mobileTemplate.setLevel(15) mobileTemplate.setDifficulty(Difficulty.NORMAL) mobileTemplate.setMinSpawnDistance(4) mobileTemplate.setMaxSpawnDistance(8) mobileTemplate.setDeathblow...
pe("Wooly Hide") mobileTemplate.setBoneAmount(365) mobileTemplate.setBoneType("Animal Bones") mobileTemplate.setHideAmount(320) mobileTemplate.setSocialGroup("bantha") mobileTemplate.setAssistRange(2) mobileTemplate.setStalker(False) mobileTemplate.setOptionsBitmask(Options.ATTACKABLE) templates = Vector() ...
theonion/django-bulbs
bulbs/infographics/data_serializers.py
Python
mit
1,619
0.000618
from rest_framework import serializers from bulbs.utils.fields import RichTextField from bulbs.utils.data_serializers import CopySerializer, EntrySerializer, BaseEntrySerializer from .fields import ColorField class XYEntrySerializer(BaseEntrySerializer): title = RichTextField(required=False, field_size="short") ...
class ProConSerializer(serializers.Serializer): body = RichTextField(required=False, field_size="long") pro = CopySerializer(required=False, many=True) con = CopySerializer(required=False, many=True) class StrongSideWeakSideSerializer(serializers.Serializer): body = RichTextField(required=False, f
ield_size="long") strong = CopySerializer(required=False, many=True) weak = CopySerializer(required=False, many=True) class TimelineSerializer(serializers.Serializer): entries = EntrySerializer(many=True, required=False, child_label="entry")
hzlf/openbroadcast.org
website/apps/alibrary/apiv2/serializers.py
Python
gpl-3.0
9,901
0.000707
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.core.urlresolvers import reverse_lazy from django.conf import settings from rest_framework import serializers from rest_flex_fields import FlexFieldsModelSerializer from rest_flex_fields.serializers import FlexFieldsSerializerMixin from easy...
ship. """ def to_representation(self, value): """ Serialize tagged objects to a simple textual representation. """ if isinstance(value, Media): # return 'Media: {}'.format(value.pk) serializer = MediaSerializer( value, context={"request": ...
Media): return "Jingle: {}".format(value.pk) else: raise Exception("Unexpected type of tagged object") return serializer.data class PlaylistItemSerializer(serializers.ModelSerializer): # http://www.django-rest-framework.org/api-guide/relations/#generic-relationships c...
Aiacos/DevPyLib
mayaLib/guiLib/__init__.py
Python
agpl-3.0
62
0
fro
m . import base from . import mainMenu from . import utils
seoester/Git-Deployment-Handler
gitdh/tests/configgit.py
Python
mit
2,693
0.022651
import unittest, tempfile, os.path from gitdh.config import Config from gitdh.git import Git from subprocess import check_output class GitdhConfigGitTestCase(unittest.TestCase): def setUp(self): self.cStr = """ [Git] RepositoryPath = /var/lib/gitolite/repositories/test.git [Database] Engine = sqlite DatabaseFile ...
with open(os.path.join(path, 'README'), 'w') as f: f.write('On master') gC._executeGitCommand('add', '.') gC._executeGitCommand
('commit', '-m "Initial Import"') gC._executeGitCommand('branch', 'development') gC._executeGitCommand('checkout', 'development', suppressStderr=True) with open(os.path.join(path, 'README'), 'w') as f: f.write('On development') gC._executeGitCommand('add', '.') gC._executeGitCommand('commit', '-m "Developm...
frishberg/django
tests/messages_tests/test_fallback.py
Python
bsd-3-clause
6,536
0.000459
from django.contrib.messages import constants from django.contrib.messages.storage.fallback import ( CookieStorage, FallbackStorage, ) from django.test import SimpleTestCase from .base import BaseTests from .test_cookie import set_cookie_data, stored_cookie_messages_count from .test_session import set_session_data...
cookie_storage = self.get_cookie_storage(storage) session_storage = self.get_session_storage(storage) # Set initial cookie and session data. example_me
ssages = [str(i) for i in range(5)] set_cookie_data(cookie_storage, example_messages[:4] + [CookieStorage.not_finished]) set_session_data(session_storage, example_messages[4:]) self.assertEqual(list(storage), example_messages) def test_get_fallback_only(self): request = self.get_re...
akretion/logistics-center
stef_logistics/data/flow_delivery.py
Python
agpl-3.0
1,924
0
delivery_head = [ { "seq": 1, "len": 5, "type": "A", "col": "codenr", "req": True, "def": "E", "allowed": ["E"], "comment": "Code enregistrement", }, { "seq": 2, "len": 20, "type": "A", "col": "cmdcli", "...
e, "comment": "N° de référence donneur d'ordre", }, { "seq": 3, "len": 10, "type": "A", "col": "nomdos", "req": True, "comment": "Nom du dossier", }, { "seq": 4, "le
n": 13, "type": "I", "col": "codgln", "req": True, "comment": "Code GLN (EAN/UCC-13) du site STEF-TFE", }, { "seq": 6, "len": 8, "type": "D1", "col": "datliv", "req": True, "comment": "Date livr", }, { "seq": 7, ...
thomazs/geraldo
site/newsite/site-geraldo/django/core/cache/backends/memcached.py
Python
lgpl-3.0
1,303
0.00307
"Memcached cache backend" from django.core.cache.backends.base import BaseCache, InvalidCacheBackendError from django.utils.encoding import smart_unicode, smart_str from google.appengine.api import memcache class CacheClass(BaseCache): def __init__(self, server, params): BaseCache.__init__(self, params) ...
ache.get(smart_str(key)) if val is None: return default else: if isinstance(val, basestring): return smart_unicode(val) else: return val def set(self, key, value, timeout=0): if isinstance(value, unicode): value...
value, timeout or self.default_timeout) def delete(self, key): self._cache.delete(smart_str(key)) def get_many(self, keys): return self._cache.get_multi(map(smart_str,keys)) def close(self, **kwargs): self._cache.disconnect_all()
CubicERP/odoo
addons/stock_landed_costs/stock_landed_costs.py
Python
agpl-3.0
20,934
0.004395
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
, 'valuation_adjustment_lines': fields.one2many('stock.valuation.adjustment.lines', 'cost_id', 'Valuation Adjustments', states={'done': [('readonly', True)]}), 'description': fields.text('Item Description', states={'done': [('readonly', True)]}), 'amount_total': fields.function(_total_amount, ty...
c={}: ids, ['cost_lines'], 20), 'stock.landed.cost.lines': (_get_cost_line, ['price_unit', 'quantity', 'cost_id'], 20), }, track_visibility='always' ), 'state': fields.selection([('draft', 'Draft'), ('done', 'Posted'), ('cancel', 'Cancelled')], 'State', readonly=True, track_v...
cstipkovic/spidermonkey-research
testing/mozharness/scripts/b2g_desktop_multilocale.py
Python
mpl-2.0
9,106
0.002745
#!/usr/bin/env python # ***** BEGIN LICENSE BLOCK ***** # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. # ***** END LICENSE BLOCK ***** import sys import os # load mod...
"dest": "gaia_l10n_vcs", "help": "vcs to use for gaia l10n", }], ] def __init__(self, require_config_file=False): LocalesMixin.__init__(self) BaseScript.__init__(self, config_options=self.config_options,
all_actions=[ 'pull', 'build', 'summary', ], require_config_file=require_config_file, # Default configuration ...