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 |
|---|---|---|---|---|---|---|---|---|
nzufelt/theano_nn | min_work_ex.py | Python | mit | 757 | 0.029062 | import numpy as np
import numpy.random as rng
import theano
import theano.tensor as T
from theano.tensor.nnet import conv2d
minibatch = 3
image_height,image_width = 28,28
filter_height,filter_width = 3,3
n_filters = 1
n_channels = 1
n = 1/(np.sqrt(image_height*image_width))
X = T.tensor4(name='X')
X_shape = (minibat... | er_width)
W = theano.shared(n*rng.randn(*W_shape),name='W')
conv_out = conv2d(X,
W,
input_shape=X_shape,
filter_s | hape=W_shape,
border_mode='valid')
f = theano.function([X],[conv_out])
X_data = np.array(rng.randint(low=0,high=256,size=X_shape))
conv_out = f(X_data)
|
j2a/django-simprest | simprest/docs.py | Python | bsd-3-clause | 1,557 | 0.001927 | from django.core.urlresolvers import get_resolver
from django.http import HttpResponse
class HandlerRegistry(dict):
def __init__(self):
self.maxlength = 0
def __setitem__(self, name, v | alue):
self.maxlength = max(self.maxlength, len(str(value)))
super(HandlerRegistry, self).__setitem__(name, value)
def register( | self, handler):
self[handler] = None
def sync_urls(self):
resolver = get_resolver(None)
reverse = resolver.reverse_dict
for h in self:
if not self[h]:
# tied to current django url storage
urltuple = reverse[h][0][0]
args = ... |
letiangit/802.11ah-ns3 | src/energy/bindings/callbacks_list.py | Python | gpl-2.0 | 641 | 0.00624 | callback_classes = [
['void', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
['void', 'double', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
['void', 'int', 'ns... | , 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'n | s3::empty', 'ns3::empty', 'ns3::empty'],
['void', 'ns3::Ptr<ns3::NetDevice>', 'ns3::Ptr<ns3::Packet const>', 'unsigned short', 'ns3::Address const&', 'ns3::Address const&', 'ns3::NetDevice::PacketType', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
]
|
Ganapati/DjangoZik | infos_grabber/coverGrabber.py | Python | gpl-2.0 | 998 | 0.002004 | #!/usr/bin/python
import requests
from bs4 import BeautifulSoup
class CoverGrabber:
def __init__(self, url=None):
if url is None:
self.url = 'http://www.amazon.com/s/ref=nb_sb_noss_2?url=search-alias=aps&field-keywords=cd'
else:
self.url = url
def request_service(self... | nt "Grab CD Cover from Amazon"
cover_grabber = CoverGrabber()
cover = cover_grabber.grab('Blac | k ice')
if cover is None:
print "Error"
else:
print "Cover : %s" % cover
|
rananda/cfme_tests | cfme/services/catalogs/catalog_item.py | Python | gpl-2.0 | 16,459 | 0.001701 | # -*- coding: utf-8 -*-
from functools import partial
from types import NoneType
from navmazing import NavigateToSibling, NavigateToAttribute
from cfme.exceptions import DestinationNotFound
from cfme.fixtures import pytest_selenium as sel
from cfme.provisioning import provisioning_form as request_form
from cfme.web_u... | ric")
sel.click(basic_info_form.apply_btn)
if self.catalog_name is not None \
and self.provisioning_data is not None \
and not isinstance(self.provider, NoneType):
tabstrip.select_tab("Request Info")
tabstrip.select_tab("Catalog")
t... | te = template_select_form.template_table.find_row_by_cells({
'Name': self.catalog_name,
'Provider': self.provider.name
})
sel.click(template)
request_form.fill(self.provisioning_data)
sel.click(template_select_form.add_button)
def update(s... |
cinepost/Copperfield_FX | copper/core/utils/singleton.py | Python | unlicense | 849 | 0.003534 | # Taken from here: https://stackoverflow.com/questions/50566934/why-is-this-singleton-implementation-not-thread-safe
import functools
import threading
lock = threading.Lock()
def synchronized(lock):
""" Synchronization decorator """
def wrapper(f):
@functools.wraps(f)
def inner_wrapper(*args... | s SingletonOptimized(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._locked_call(*args, **kwargs)
return cls._instances[cls]
@synchronized(lock)
def _locked_call(cls, *args, **kwargs):
if cls not in cls._instances:
... | ized, cls).__call__(*args, **kwargs)
|
boar/boar | boar/accounts/urls.py | Python | bsd-3-clause | 562 | 0.010676 | from django.conf.urls.defaul | ts import *
urlpatterns = patterns('',
url(r'^$', 'boar.accounts.views.accounts', name='accounts'),
url(r'^signout/$', 'boar.accounts.views.signout', name='accounts_signout'),
url(r'^settings/$', 'boar.accounts.views.settings_form', name='accounts_settings'),
url(r'^mailing-lists/unsubscribe/(?P<user_i... | unsubscribe',
name='accounts_mailing_lists_unsubscribe'),
url(r'^user-data/$', 'boar.accounts.views.user_data'),
)
|
magnunleno/Rurouni | tests/test_basic_operations.py | Python | gpl-3.0 | 5,681 | 0.010033 | #!/usr/bin/env python
# encoding: utf-8
from conftests import *
from rurouni.exceptions import *
from rurouni.types import *
from rurouni import Database, Column, Table
def test_insert_errors(db):
class Client(Table):
__db__ = db
name = Column(String)
birthdate = Column(Date)
with pyt... | lient) == 3
db.destroy()
def test_empty(db):
class Client(Table):
__db__ = db
name = Column(String)
birthdate = Column(Date)
assert Client.isEmpty()
Client.insert(name='Joh | n', birthdate=randomDate())
assert not Client.isEmpty()
db.destroy()
|
Arnukk/TDS | wnaffect.py | Python | mit | 3,540 | 0.012994 | # -*- coding: utf-8 -*-
"""
Clement Michard (c) 2015
"""
import os
import sys
import nltk
from emotion import Emotion
from nltk.corpus import WordNetCorpusReader
import xml.etree.ElementTree as ET
class WNAffect:
"""WordNet-Affect ressource."""
def __init__(self, wordnet16_dir, wn_domains_dir):
"... | .path.append(cwd)
wn16_path = "{0}/dict".format(wordnet16_dir)
self.wn16 = WordNetCorpusReader(os.path.abspath("{0}/{1}".format(cwd, wn16_path)), nltk.data.find(wn16_path))
self.flat_pos = {'NN':'NN', 'NNS':'NN', 'JJ':'JJ', 'JJR':'JJ', 'JJS':'JJ', 'RB' | :'RB', 'RBR':'RB', 'RBS':'RB', 'VB':'VB', 'VBD':'VB', 'VGB':'VB', 'VBN':'VB', 'VBP':'VB', 'VBZ':'VB'}
self.wn_pos = {'NN':self.wn16.NOUN, 'JJ':self.wn16.ADJ, 'VB':self.wn16.VERB, 'RB':self.wn16.ADV}
self._load_emotions(wn_domains_dir)
self.synsets = self._load_synsets(wn_domains_dir)... |
SlicerRt/SlicerDebuggingTools | PyDevRemoteDebug/ptvsd-4.1.3/ptvsd/_vendored/pydevd/pydevd_concurrency_analyser/pydevd_thread_wrappers.py | Python | bsd-3-clause | 2,233 | 0.002239 | from _pydev_imps._pydev_saved_modules import threading
def wrapper(fun):
def pydev_after_run_call():
pass
def inner(*args, **kwargs):
fun(*args, **kwargs)
pydev_after_run_call()
return inner
def wrap_attr(obj, attr):
t_save_start = getattr(obj, attr)
setat... | _attr
else:
return orig_attr
def call_begin(self, attr):
pass
def call_end(self, attr):
pass
def __enter__(self):
self.call_begin("__enter__")
self.wrapped_object.__enter__()
self.call_end("__enter__")
def __exit__(self, exc_... | :
def inner(*args, **kwargs):
obj = fun(*args, **kwargs)
return ObjectWrapper(obj)
return inner
def wrap_threads():
# TODO: add wrappers for thread and _thread
# import _thread as mod
# print("Thread imported")
# mod.start_new_thread = wrapper(mod.start_new_thread)
... |
chimkentec/KodiMODo_rep | script.module.xbmcup/lib/xbmcup/cache.py | Python | gpl-3.0 | 7,268 | 0.004403 | # -*- coding: utf-8 -*-
__author__ = 'hal9000'
__all__ = ['Cache', 'CacheServer']
import socket
import time
import json
import hashlib
from sqlite3 import dbapi2 as sqlite
import xbmc
import log
import gui
import system
SOCKET = '127.0.0.1', 59999
CLEAR = 60*60*24 # 1 day
class SQL:
def __init__(self, name,... | elf.sql_set('create index dataindex on cache(expire)')
self.meta_load()
def health(self, version):
if self.meta['version'] != version:
self.meta_save('version', version)
self.clear()
elif self.meta['timeout'] < int(time.time()):
self.sq | l_set('delete from cache where expire<?', (int(time.time()), ))
self.meta_save('timeout', int(time.time()) + CLEAR)
def get(self, token):
return self.sql_get('select data from cache where token=? and expire>? limit 1', (hashlib.md5(str(token)).hexdigest(), int(time.time())))
def set(self... |
joshsamara/game-website | core/migrations/0014_auto_20150413_1639.py | Python | mit | 496 | 0.002016 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0013_merge'),
]
operations = [
migrations | .AlterField(
model_name='user',
name='public',
f | ield=models.BooleanField(default=True, help_text=b'Determines whether or not your profile is open to the public'),
preserve_default=True,
),
]
|
rudhir-upretee/Sumo17_With_Netsim | tools/assign/costFunctionChecker.py | Python | gpl-3.0 | 8,986 | 0.004118 | #!/usr/bin/env python
"""
@file costFunctionChecker.py
@author Michael Behrisch
@author Daniel Krajzewicz
@author Jakob Erdmann
@date 2009-08-31
@version $Id: costFunctionChecker.py 13811 2013-05-01 20:31:43Z behrisch $
Run duarouter repeatedly and simulate weight changes via a cost function.
SUMO, Simulatio... | for step in range(options.firstStep, options.lastStep):
btimeA = datetime.now()
print "> Executing step " + str(step)
# router
files = []
for tripFile in tripFiles:
file = tripFile
tripFile = os.path.basename(tripFile)
if step | >0:
file = tripFile[:tripFile.find(".")] + "_%s.rou.alt.xml" % (step-1)
output = tripFile[:tripFile.find(".")] + "_%s.rou.xml" % step
print ">> Running router with " + file
btime = datetime.now()
|
waterdotorg/power.Water | project/custom/management/commands/friend_joined_email.py | Python | gpl-3.0 | 2,527 | 0.004353 | import datetime
import logging
import time
from django.conf import settings
from django.contrib.sites.models import Site
from django.core.mail.message import EmailMultiAlternatives
from django.core.management.base import BaseCommand
from django.db.models import Q
from django.template.loader import render_to_string
fro... | if not profile.user_referrer.e | mail:
continue
try:
FriendJoinedEmailLog.objects.get(user=profile.user_referrer, user_referred=profile.user)
except FriendJoinedEmailLog.DoesNotExist:
dict_context = {
'site': self.site,
... |
matthijsvk/multimodalSR | code/Experiments/neon-master/tests/test_bleuscore.py | Python | mit | 1,914 | 0.001045 | # ----------------------------------------------------------------------------
# Copyright 2015-2016 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.apa... | "the rain in spain falls in the plains most of the time",
"it is raining today"]]
# reference scores for the given set of reference sentences
bleu_score_references = [92.9, 88.0, 81.5, 67.1] # bleu1, bleu2, bleu3, bleu4
# compute scores
bleu_metric = BLEUScore()
bleu_... | reference
if __name__ == '__main__':
test_bleuscore()
|
ryfeus/lambda-packs | pytorch/source/PIL/FtexImagePlugin.py | Python | mit | 3,322 | 0 | """
A Pillow loader for .ftc and .ftu files (FTEX)
Jerome Leclanche <jerome@leclan.ch>
The contents of this file are hereby released in the public domain (CC0)
Full text of the CC0 license:
https://creativecommons.org/publicdomain/zero/1.0/
Independence War 2: Edge Of Chaos - Texture File Format - 16 October 2001
... | texture) in this file.
{format_directory} = format_count * { u32:format, u32:where }
The format value is 0 for DX | T1 compressed textures and 1 for 24-bit RGB
uncompressed textures.
The texture data for a format starts at the position "where" in the file.
Each set of texture data in the file has the following structure:
{data} = format_count * { u32:mipmap_size, mipmap_size * { u8 } }
* "mipmap_size" is the number of bytes in that... |
Zyell/home-assistant | homeassistant/components/thermostat/__init__.py | Python | mit | 8,539 | 0 | """
Provides functionality to interact with thermostats.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/thermostat/
"""
import logging
import os
import voluptuous as vol
from homeassistant.helpers.entity_component import EntityComponent
from homeassi... | de_off()
thermostat.update_ha_state(True)
hass.services.register(
DOMAIN, SERVICE_SET_AWAY_MODE, away_mode_set_service,
descriptions.get(SERVICE_SET_AWAY_MODE),
schema=SET_AWAY_MODE_SCHEMA)
def temperature_set_service(service):
"""Set temperature on the target ther... | """
target_thermostats = component.extract_from_service(service)
temperature = service.data[ATTR_TEMPERATURE]
for thermostat in target_thermostats:
thermostat.set_temperature(convert(
temperature, hass.config.temperature_unit,
thermostat.unit_of_meas... |
mvendra/mvtools | detect_repo_type.py | Python | mit | 1,152 | 0.007813 | #!/usr/bin/env python3
import sys
import os
import path_utils
import git_lib
import svn_lib
REPO_TYPE_GIT_BARE="git/bare"
REPO_TYPE_GIT_STD="git/std"
REPO_TYPE_GIT_SUB="git/sub"
REPO_TYPE_SVN="svn"
REPO_TYPES = [REPO_TYPE_GIT_BARE, REPO_TYPE_GIT_STD, REPO_TYPE_GIT_SUB, REPO_TYPE_SVN]
def detect_repo_type(path):
... | )
if v and r:
return True, REPO_TYPE_GIT_SUB
v, r = svn_lib.is_svn_repo(path)
if v and r:
return True, REPO_TYPE_SVN
return True, None
def is_any_repo_type(repo_type):
return repo_type in REPO_TYPES
def puaq():
print("Usage | : %s path" % path_utils.basename_filtered(__file__))
sys.exit(1)
if __name__ == "__main__":
if len(sys.argv) < 2:
puaq()
path = sys.argv[1]
v, r = detect_repo_type(path)
print(r)
if not v:
sys.exit(1)
|
chris-hld/sfs-python | sfs/time/source.py | Python | mit | 3,359 | 0 | """Compute the sound field generated by a sound source.
The Green's function describes the spatial sound propagation over time.
.. include:: math-definitions.rst
"""
from __future__ import division
import numpy as np
from .. import util
from .. import defs
def point(xs, signal, observation_time, grid, c=None):
... | : (3,) array_like
Position of source in cartesian coordinates.
sign | al : (N,) array_like + float
Excitation signal consisting of (mono) audio data and a sampling
rate (in Hertz). A `DelayedSignal` object can also be used.
observation_time : float
Observed point in time.
grid : triple of array_like
The grid that is used for the sound field calcul... |
arangaraju/graph-stix | tests/conftest.py | Python | mit | 316 | 0 | #!/ | usr/bin/env python
# -*- coding: utf-8 -*-
"""
Dummy conftest.py for graph_stix.
If you don't know what this is for, just leave it empty.
Read more about conftest.py under:
https://pytest.org/l | atest/plugins.html
"""
from __future__ import print_function, absolute_import, division
import pytest
|
namhyung/uftrace | tests/t142_recv_multi.py | Python | gpl-2.0 | 1,783 | 0.001122 | #!/usr/bin/env python
import os.path
import random
import subprocess as sp
from runtest import TestBase
TDIR = 'xxx'
class TestCase(TestBase):
def __init__(self):
TestBase.__init__(self, 'abc', """
# DURATION TID FUNCTION
62.202 us [28141] | __cxa_atexit();
[28141] | main() {
... | rt)
self.exearg = 't-' + self.name
record_cmd = self.runcmd()
self.pr_debug('prerun command: ' + record_cmd)
| sp.call(record_cmd.split())
# use this
self.pr_debug('run another record')
self.dirname = 'dir-' + str(random.randint(100000, 999999))
self.pr_debug('after randint')
self.option += ' -d ' + self.dirname
record_cmd = self.runcmd()
self.pr_debug('prerun command: ... |
TaliesinSkye/evennia | wintersoasis-master/commands/unloggedin.py | Python | bsd-3-clause | 12,835 | 0.004441 | """
Commands that are available from the connect screen.
"""
import re
import traceback
from django.conf import settings
from src.players.models import PlayerDB
from src.objects.models import ObjectDB
from src.server.models import ServerConfig
from src.comms.models import Channel
from src.utils import create, logger, ... | string += "\nIf <name> or <password> contains spaces, enclose it in quotes."
session.msg(string)
return
playername, password = parts
print "playername '%s', password: '%s'" % (playername, password)
# sanity checks
if not re.findall('^[\w. @+-]+$', playername) or ... | ayername) <= 30):
# this echoes the restrictions made by django's auth module (except not
# allowing spaces, for convenience of logging in).
string = "\n\r Playername can max be 30 characters or fewer. Letters, spaces, digits and @/./+/-/_ only."
session.msg(string)
... |
CMU-Robotics-Club/roboticsclub.org | robocrm/migrations/0007_robouser_magnetic.py | Python | mit | 461 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals |
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('robocrm', '0006_auto_20141005_1800'),
]
operations = [
migrations.AddField(
model_name='robouser',
name='magnetic',
field=models.CharField(max_length=9... | ]
|
levibostian/myBlanky | googleAppEngine/google/appengine/tools/dev_appserver_apiserver.py | Python | mit | 53,339 | 0.00718 | #!/usr/bin/env python
#
# Copyright 2007 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... | after the domain.
Returns:
Tuple of (response, response_body):
response: HTTPResponse object.
response_body: Response body as string.
"""
connection = httplib.HTTPSConnection(self._STATIC_PROXY_HOST)
try:
connection.request('GET', path, None, { | })
response = con |
dob71/x2swn | skeinforge/fabmetheus_utilities/xml_simple_writer.py | Python | gpl-3.0 | 4,447 | 0.02586 | """
XML tag writer utilities.
"""
from __future__ import absolute_import
#Init has to be imported first because it has code to workaround the python bug where relative imports don't work if the module is imported as a main module.
import __init__
import cStringIO
__author__ = 'Enrique Perez (perez_enrique@yahoo.c... | if key == 'name':
return - 1
if otherKey == 'name':
return 1
if key < otherKey:
return - 1
return int(key > otherKey)
def getAttributesString(attributes):
'Add the closed xml tag.'
attributesString = ''
attributesKeys = attributes.keys()
attributesKeys.sort(compareAttributeKeyAscending)
for attributesKe... | r(attributes[attributesKey])
if "'" in valueString:
attributesString += ' %s="%s"' % (attributesKey, valueString)
else:
attributesString += " %s='%s'" % (attributesKey, valueString)
return attributesString
def getBeginGeometryXMLOutput(elementNode=None):
'Get the beginning of the string representation of t... |
phenoxim/cinder | cinder/tests/unit/volume/test_init_host.py | Python | apache-2.0 | 14,005 | 0 | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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 ... | nder.tests.unit import utils as tests_utils
from cinder.tests.unit import volume as base
from cinder.volume import driver
from cinder.volume import utils as volutils
CONF = cfg.CONF
class VolumeInit | HostTestCase(base.BaseVolumeTestCase):
def setUp(self):
super(VolumeInitHostTestCase, self).setUp()
self.service_id = 1
@mock.patch('cinder.manager.CleanableManager.init_host')
def test_init_host_count_allocated_capacity(self, init_host_mock):
vol0 = tests_utils.create_volume(
... |
ezequielpereira/Time-Line | libs/wx/tools/Editra/src/style_editor.py | Python | gpl-3.0 | 30,179 | 0.001922 | ###############################################################################
# Name: style_editor.py #
# Purpose: Syntax Highlighting configuration dialog #
# Author: Cody Precord <cprecord@editra.org> #
... | taining a choice control with all
available lexers listed in it.
@return: sizer item containing a choice control with all available
syntax test files available
"""
lex_sizer = wx.BoxSizer(wx.HORIZONTAL)
lexer_lbl = wx.StaticText(self.ctrl_pane, wx.ID_ANY,
... | ) + u": ")
lexer_lst = wx.Choice(self.ctrl_pane, ed_glob.ID_LEXER,
choices=syntax.GetLexerList())
lexer_lst.SetToolTip(wx.ToolTip(_("Set the preview file type")))
lexer_lst.SetStringSelection(u"CPP")
lex_sizer.AddMany([((10, 10)), (lexer_lbl, 0, wx.ALIGN_CEN... |
alvarolopez/pyocci | setup.py | Python | apache-2.0 | 171 | 0 | #!/usr/bin/env python
# THIS FILE IS MANAGED BY THE GLOBAL REQUIREMENTS REPO | - DO NOT EDIT
import setuptools
setuptools.setup(
setup_requires= | ['pbr'],
pbr=True)
|
dittaeva/ocitysmap | ocitysmap2/layoutlib/commons.py | Python | agpl-3.0 | 1,272 | 0.003943 | # -*- coding: utf-8 -*-
# ocitysmap, city map | and street index generator from OpenStreetMap data
# Copyright (C) 2010 David Decotigny
# Copyright (C) 2010 Frédéric Lehobey
# Copyright (C) 2010 Pierre Mauduit
# Copyright (C) 2010 David Mentré
# Copyright (C) 2010 Maxime Petazzoni
# Copyright (C) 2010 Thomas Petazzoni
# Copyright (C) 2010 Gaël Utard
# This ... | ftware Foundation, either version 3 of the
# License, or any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more det... |
rmcgurrin/PyQLab | instruments/AWGs.py | Python | apache-2.0 | 872 | 0 | """
AWGs
"""
from atom.api import Atom, List, Int, Float, Range, Enum, Bool, Constant, Str
from | Instrument import Instrument
import enaml
from enaml.qt.qt_application import QtApplication
from instruments.AWGBase import AWGChannel, AWG, AWGDriver
from plugins import find_plugins
AWGList = []
# local plugin registration to enable access by AWGs.plugin
plugins = find_plugins(AWG, verbose=False)
for plugin in ... | in not in AWGList:
AWGList.append(plugin)
if plugin.__name__ not in globals().keys():
globals().update({plugin.__name__: plugin})
print 'Registered Plugin {0}'.format(plugin.__name__)
if __name__ == "__main__":
with enaml.imports():
from AWGsViews import AWGView
... |
Jorge-Rodriguez/ansible | test/units/modules/network/ftd/test_ftd_configuration.py | Python | gpl-3.0 | 5,145 | 0.002527 | # Copyright (c) 2018 Cisco and/or its affiliates.
#
# 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 later v... | resource_mock.side_effect = FtdConfigurationError(msg)
result = self._run_module_with_fail_json({'operation': operation_name})
assert result['fai | led']
assert 'Failed to execute %s operation because of the configuration error: %s' % (operation_name, msg) == \
result['msg']
def test_module_should_fail_when_ftd_server_error(self, resource_mock):
operation_name = 'test name'
code = 500
response = {'error': 'foo'}
... |
capturePointer/or-tools | examples/python/nontransitive_dice.py | Python | apache-2.0 | 5,680 | 0.011972 | # Copyright 2010 Hakan Kjellerstrand hakank@bonetmail.com
#
# 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 ... | ither express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Nontransitive dice in Goog | le CP Solver.
From
http://en.wikipedia.org/wiki/Nontransitive_dice
'''
A set of nontransitive dice is a set of dice for which the relation
'is more likely to roll a higher number' is not transitive. See also
intransitivity.
This situation is similar to that in the game Rock, Paper, Scissors,
in which ... |
victorywang80/Maintenance | saltstack/src/salt/modules/xapi.py | Python | apache-2.0 | 24,954 | 0.000761 | # -*- coding: utf-8 -*-
'''
This module (mostly) uses the XenAPI to manage Xen virtual machines.
Big fat warning: the XenAPI used in this file is the one bundled with
Xen Source, NOT XenServer nor Xen Cloud Platform. As a matter of fact it
*will* fail under those platforms. From what I've read, little work is needed
t... | trix.com/XenServer/6.0.0/1.0/en_gb/api/
. https://github.com/xen-org/xen-api/tree/master/scripts/examples/python
. http://xenbits.xen.org/gitweb/?p=xen.git;a=tree;f=tools/python/xen/xm;hb=HEAD
'''
# Import pytho | n libs
import sys
import contextlib
import os
try:
import importlib
HAS_IMPORTLIB = True
except ImportError:
# Python < 2.7 does not have importlib
HAS_IMPORTLIB = False
# Import salt libs
from salt.exceptions import CommandExecutionError
import salt.utils
# Define the module's virtual name
__virtual... |
frreiss/tensorflow-fred | tensorflow/python/tpu/tpu.py | Python | apache-2.0 | 97,112 | 0.006683 | # 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 required by applica... | ion:
"""Initializes a distributed TPU Embedding system for use with TensorFlow.
The following two are equivalent:
1. initialize_system() with embedding_config.
2. initialize_system() without embedding_config, then
initialize_system_for_tpu_embedding().
initialize_system() should not be called with embed... | f
initialize_system_for_tpu_embedding() is meant to be called later.
Args:
embedding_config: a `TPUEmbeddingConfiguration` proto describing the desired
configuration of the hardware embedding lookup tables.
job: The job (the XXX in TensorFlow device specification /job:XXX) that
contains the TPU... |
vjFaLk/frappe | frappe/core/doctype/view_log/test_view_log.py | Python | mit | 850 | 0.031765 | # -*- coding: utf-8 -*-
# Copyright (c) 2018, Frappe Technologies and Contributors
# See license.txt
from __future__ import unicode_literals
import frappe
import unittest
class TestViewLog(unittest.TestCase):
def tearDown(self):
frappe.set_user('Administrator')
def test_if_user_is_added(self):
ev | = frappe.get_doc({
'doctype': 'Event',
'subject': 'test event for view logs',
'starts_on': '2018-06-04 14:11:00',
'event_type': 'Public'
}).ins | ert()
frappe.set_user('test@example.com')
from frappe.desk.form.load import getdoc
# load the form
getdoc('Event', ev.name)
a = frappe.get_value(
doctype="View Log",
filters={
"reference_doctype": "Event",
"reference_name": ev.name
},
fieldname=['viewed_by']
)
self.assertEqual('t... |
evildmp/arkestra-publications | publications/migrations/0003_auto__chg_field_student_student_id.py | Python | bsd-2-clause | 40,862 | 0.007905 | # -*- 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):
# Changing field 'Student.student_id'
db.alter_column('publications_stud... | eld', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
| 'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_... |
mdworks2016/work_development | Python/20_Third_Certification/venv/lib/python3.7/site-packages/celery/canvas.py | Python | apache-2.0 | 55,734 | 0.000036 | # -*- coding: utf-8 -*-
"""Composing task work-flows.
.. seealso:
You should import these from :mod:`celery` and not this module.
"""
from __future__ import absolute_import, unicode_literals
import itertools
import operator
from collections import deque
from copy import deepcopy
from functools import partial as ... | izers with a strict type subset.
Signa | tures can also be created from tasks:
- Using the ``.signature()`` method that has the same signature
as ``Task.apply_async``:
.. code-block:: pycon
>>> add.signature(args=(1,), kwargs={'kw': 2}, options={})
- or the ``.s()`` shortcut that works for star arguments:
.. code... |
popazerty/e2-dmm | lib/python/Screens/AudioSelectionExtended.py | Python | gpl-2.0 | 9,756 | 0.031673 | from Screen import Screen
from Components.ServiceEventTracker import ServiceEventTracker
from Components | .ActionMap import ActionMap
from Components.ConfigList import ConfigListScreen
from Components.ChoiceList import ChoiceList, ChoiceEntryComponent
from Components.config import config, ConfigSubsection, getConfigListEntry, ConfigNothing, ConfigSelection, ConfigOnOff
from Components.Mu | ltiContent import MultiContentEntryText
from Components.Sources.List import List
from Components.Sources.Boolean import Boolean
from Components.SystemInfo import SystemInfo
from enigma import iPlayableService
from Tools.ISO639 import LanguageCodes
from Tools.BoundFunction import boundFunction
FOCUS_CONFIG, FOCUS_STRE... |
softak/webfaction_demo | apps/stores/views.py | Python | bsd-3-clause | 11,025 | 0.004535 | import commonware.log
from datetime import datetime, timedelta
import re
from session_csrf import anonymous_csrf
from django.shortcuts import redirect, render, get_object_or_404
from django.contrib import messages
from django.utils.translation import ugettext_lazy as _
from django.views.generic.edit import CreateView, ... | *kwargs)
@login_required
@csrf_protect
def store_image(request):
if not hasattr(request.user, 'store'):
raise Http404()
store = request.user.store
if request.method == 'POST':
form = StoreImageUploadForm(request.POST,
| request.FILES,
instance=store)
if form.is_valid():
form.save()
return redirect(store_image)
else:
form = StoreImageUploadForm(instance=store)
return render(request, 'stores/manage/image.j.html', {
'image': request.user.store.window... |
cyphactor/lifecyclemanager | extra/plugins/docs/docs/__init__.py | Python | gpl-3.0 | 20 | 0 |
f | rom docs import * | |
googleapis/python-resource-manager | samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_get_tag_key_async.py | Python | apache-2.0 | 1,477 | 0.000677 | # -*- coding: utf-8 -*-
# Copyright 2022 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... | S IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Generated code. DO NOT EDIT!
#
# Snippet for GetTagKey
# NOTE: This snippet has been automatically gen | erated for illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-cloud-resourcemanager
# [START cloudresourcemanager_v3_generated_TagKeys_GetTagKey_async]
from google.cloud... |
hakanardo/pyvx | old/test/test_truediv.py | Python | mit | 494 | 0.002024 | from __future__ import | division
from pyvx import *
| from array import array
class TestDiv(object):
def test_div(self):
g = Graph()
with g:
img = Image(3, 4, DF_IMAGE_U8, array('B', range(12)))
sa1 = img / 2
sa2 = img // 2
sa1.force()
sa2.force()
g.process()
assert [sa1.data[... |
i404ed/portfolio-dir | portfolio/apps/core/tests.py | Python | gpl-3.0 | 697 | 0.002869 | from django.core.exceptions import ObjectDoesNotExist
from django.http import Http404
from django.shortcuts import get_object_or_404
from django.test import TestCase
# Create your tests here.
from portfolio.apps.core.models import User
class UserModelTests(TestCase):
def test_admin_user_exist(self):
sel... | with self.assertRaises(Http404) as e:
get_object_or_404(User, phone="3124795074")
self.assertRaises(ObjectDoesNotExist, lambda: User.objects.get(phone="3124795074"))
with self.assertRaises(O | bjectDoesNotExist) as e:
User.objects.get(phone="3124795074")
|
ucolesanti/tinyos-wrappers | support/sdk/python/pynopath.py | Python | bsd-3-clause | 296 | 0.037162 | import sys
import | string
import re
import os
input_file = open(sys.argv[1])
prev_value = int(0)
true = 1
while true:
input_line = input_file.readline()
if input_line == "":
break
input_line = r | e.sub('#line.*','',input_line)
input_line = re.sub('# [0-9].*','',input_line)
print input_line
|
0ps/reprocks | client/reprocks_client.py | Python | mit | 9,685 | 0.010532 | #! /usr/bin/python
import threading
import socket
import sys,time
import SocketServer,struct,select
global bufLen
global endflag
global socksPort
###################
socksPort = 50000 #Default socks5 proxy port
###################
endflag = []
bufLen = 4*1024
class startThreadSoket(threading.Thread):
def __init_... | self.socksPort)
class control(threading.Thread):
def __init__(self,server_Conn,client_Conn,serverAddr,clientAddr,clientNum):
threading.Thread.__init__(self)
self.server_Conn = server_Conn
self.client_Conn = client_Conn
self.server_Ad | dr = serverAddr
self.client_Addr = clientAddr
self.clientNum = clientNum
def run(self):
global endflag
transferDataThreads = []
thread = 2
flag = self.clientNum
endflag.append(False)
y = transfer2Server(self.server_Conn,self.client_Conn,self.server_A... |
pawpro/spa | spa/static/hashed.py | Python | bsd-3-clause | 8,271 | 0.000484 | import hashlib
import mimetypes
import os
import posixpath
import re
from time import time
from urlparse import urlsplit, urlunsplit
from werkzeug.exceptions import NotFound
from werkzeug.http import is_resource_modified, http_date
from spa.static.handlers import StaticHandler
from spa.utils import clean_path
class... | x(self):
"""
R | eturn the mount point for this handler. So if you had a route like
this:
('/foo/bar/static/<path:filepath>', 'foo', Handler)
Then this function should return '/foo/bar/static/'
"""
env = self.request.environ
filepath = self.params['filepath']
prefix, _, _ = (en... |
openstack/tap-as-a-service | neutron_taas/tests/unit/taas_client/osc/test_osc_tap_flow.py | Python | apache-2.0 | 9,088 | 0 | # All Rights Reserved 2020
#
# 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 t... | ource_port',
'tap_service_id',
)
def setUp(self):
super(TestCreateTapService, self).setUp()
self.cmd = osc_tap_flow.CreateTapFlow(self.app, self.namespace)
def test_create_tap_flow(self):
"""Test Create Tap Flow."""
fake_tap_flow = fakes.FakeTapFlow.create_tap_flow(... | attrs={
'source_port': uuidutils.generate_uuid(),
'tap_service_id': uuidutils.generate_uuid()
}
)
self.neutronclient.post = mock.Mock(
return_value={osc_tap_flow.TAP_FLOW: fake_tap_flow})
arg_list = [
'--name', fake_ta... |
saketkc/bio-tricks | meme_parser/meme_processory.py | Python | mit | 2,759 | 0.007249 | #!/usr/bin/env python
"""
Process meme.txt files to
generate conservation plots
"""
import argparse
import csv
import sys
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats.stats import pearsonr
from Bio import motifs
def plot_meme_against_phylo(meme_record, phylo):
sns.set(s... | mat(pr[0],pr[1]));
fig.savefig('{}_motif{}_scatter.png'.format(parsed.phylo, parsed.motif))
x = np.linspace(1,len(phylo_scores)+1,num=len(phylo_scores), endpoint=False)
f, (ax1, ax2) = plt.subplots(2, 1)
x1 = sns.barplot(x,y=np.array(motif_scores), ax=ax1)
x2 = sns.barplot(x | ,y=np.array(phylo_scores), ax=ax2)
x1.set(ylabel='Counts of most freq nucleotide', xlabel='Position in motif')
x2.set(ylabel='Phylop Score', xlabel='Position in motif')
f.tight_layout()
f.savefig('{}_motif{}_trend.png'.format(parsed.phylo, parsed.motif))
if __name__ == "__main__":
main(sys.argv[1:])... |
cateee/fosdem-volunteers | volunteers/urls.py | Python | agpl-3.0 | 403 | 0.027295 | from django.conf.urls import patterns, include, url
from volunteers import views
urlpatterns = patterns('',
#url(r'^$', views.index, name='volunteer_index'),
#url(r'^(?P<volunteer_id>\d+)/$', views.volunteer_deta | il, name='volunteer_detail'),
#url(r'^AddTasks/$', views.add_tasks, name='add_tasks'),
#url(r'^(?P<volunteer_id>\d+)/edit/$', views.volunteer_edit, name='volunteer_edit' | ),
)
|
mjg2203/edx-platform-seas | common/test/bok_choy/edxapp_pages/lms/open_response.py | Python | agpl-3.0 | 7,752 | 0.001806 | from bok_choy.page_object import PageObject
from bok_choy.promise import EmptyPromise, fulfill_after, fulfill_before
class OpenResponsePage(PageObject):
"""
Open-ended response in the courseware.
"""
@property
def name(self):
return "lms.open_response"
@property
def requirejs(sel... | ['disabled'])),
"Submit | button enabled"
)
# Submit the assessment
with fulfill_before(button_enabled):
self.css_click(button_css)
def _submitted_promise(self, assessment_type):
"""
Return a `Promise` that the next step is visible after submitting.
This will vary based on the ty... |
rockyzhengwu/mlpractice | algorithm/perceptron.py | Python | mit | 44 | 0.045455 | #!/usr/bin/env python
#-*-codi | ng=utf-8-*-
| |
sstjohn/pox | tests/topology/topology.py | Python | gpl-3.0 | 423 | 0.014184 | # TODO: use a unit-testing library for asserts
# invoke with:
# | ./pox.py --script=tests.topology.topology topology
#
# Maybe there is a less awkward way to invoke tests...
from pox.core import core
from pox.lib.revent import *
topology = core.components['topology']
def autobinds_correctly():
topology.listenTo(core)
return True
if not autobi | nds_correctly():
raise AssertionError("Did no autobind correctly")
|
btrent/knave | pychess/__init__.py | Python | gpl-3.0 | 49 | 0 | VERSION = "0.12beta4"
VERSION_NAME = | "Anderssen"
| |
sokolowskik/Tutorials | ThinkPython/chap11/ex10.py | Python | mit | 980 | 0.006122 | f = raw_input('filename: ')
def make_word_dict(f):
"""
Read the file f and, store each word as dictionary key.
Values are not important.
Return the dictioonary.
"""
c = open(f)
d = dict()
i = | 0
for word in c:
w = word.strip('\n\r')
d[w] = i
i += 1
#l.append(w)
c.close()
return d
def rotate_word(s, n):
"""
Rotate each char in | a string by the given amount.
Wrap around to the beginning (if necessary).
"""
rotate = ''
for c in s:
start = ord('a')
num = ord(c) - start
r_num = (num + n) % 26 + start
r_c = chr(r_num)
rotate += r_c
return rotate
if __name__ == '__main__':
word_dict =... |
PrismTech/opensplice | src/api/dcps/python/test/TestSequence.py | Python | gpl-3.0 | 2,566 | 0.005456 | #
# Vortex OpenSplice
#
# This software and documentation are Copyright 2006 to TO_YEAR ADLINK
# Technology Limited, its affiliated companies and licensors. All rights
# reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in ... | )
print('data: ' + str(data))
print('data._get_packing_fmt(): ', data._get_p | acking_fmt())
print('data._get_packing_args(): ', data._get_packing_args())
buffer = data._serialize()
print('buffer: ', buffer)
values = struct.unpack(data._get_packing_fmt(), buffer)
data1 = Sequence.basic.module_Sequence.Sequence_struct()
data1._deserialize(li... |
ulif/pulp | server/test/unit/server/webservices/views/test_consumer_groups.py | Python | gpl-2.0 | 24,673 | 0.003364 | import json
import unittest
import mock
from django.http import HttpResponseBadRequest
from base import (assert_auth_CREATE, assert_auth_READ, assert_auth_UPDATE, assert_auth_DELETE,
assert_auth_EXECUTE)
from pulp.server.exceptions import InvalidValue, MissingResource, MissingValue, OperationPostpon... | = json.dumps({'display_name': 'bar'})
consumer_group = ConsumerGroupView()
try:
response = consumer_group.post(request)
except MissingValue, response:
pass
| else:
raise AssertionError("MissingValue should be raised with missing options")
self.assertEqual(response.http_status_code, 400)
self.assertEqual(response.error_data['property_names'], ['id'])
class TestconsumerGroupResourceView(unittest.TestCase):
"""
Test consumer groups resourc... |
tfgraph/tfgraph | setup.py | Python | apache-2.0 | 1,296 | 0 | #!/usr/bin/env python3
# coding: utf-8
import io
from setuptools import setup, find_packages
# http://blog.ionelmc.ro/2014/05/25/python-packaging/
setup(
name="tfgraph",
version="0.2",
description="Python's Tensorflow Graph Library",
author="garciparedes",
author_email="sergio@garciparedes.me",
url="http... |
install_requires=[
"numpy>=1.11",
"pandas>=0.20",
"tensorflow>=1.0",
],
tests_require=[
"pytest"
],
package | s=find_packages(),
classifiers=[
"Development Status :: 2 - Pre-Alpha",
"Intended Audience :: Education",
"Intended Audience :: Science/Research",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python ... |
Akagi201/learning-python | pyglet/mygame/game/physicalobject.py | Python | mit | 2,456 | 0.000814 | import pyglet
import util
class PhysicalObject(pyglet.sprite.Sprite):
"""A sprite with physical properties such as velocity"""
def __init__(self, *args, **kwargs):
super(PhysicalObject, self).__init__(*args, **kwargs)
# Velocity
self.velocity_x, self.velocity_y = 0.0, 0.0
# ... | )
return (actual_distance <= collision_distance)
def handle_collision_wi | th(self, other_object):
if other_object.__class__ is not self.__class__:
self.dead = True
|
andrefarzat/django-styleguide | styleguide/views.py | Python | mit | 897 | 0 | # -*- coding: utf-8 -*-
from django.core.cache import cache
from django.shortcuts import render
from django.http import Http404
from styleguide.utils import (Styleguide, STYLEGUIDE_DIR_NAME,
STYLEGUIDE_DEBUG, STYLEGUIDE_CACHE_NAME,
| STYLEGUIDE_ACCESS)
def index(request, module_name=None, component_name=No | ne):
if not STYLEGUIDE_ACCESS(request.user):
raise Http404()
styleguide = None
if not STYLEGUIDE_DEBUG:
styleguide = cache.get(STYLEGUIDE_CACHE_NAME)
if styleguide is None:
styleguide = Styleguide()
cache.set(STYLEGUIDE_CACHE_NAME, styleguide, None)
if module_name ... |
aifeiasdf/Template-tookit | t/macro_test.py | Python | artistic-2.0 | 2,554 | 0.002741 | from template.test import TestCase, main
class MacroTest(TestCase):
def testMacro(self):
config = { "INCLUDE_PATH": "test/src",
"TRIM": 1,
"EVAL_PYTHON": True }
self.Expect(DATA, config, self._callsign())
DATA = r"""
-- test --
[% MACRO foo INCLUDE foo -%]
foo: [% foo %]
foo(... | oo(a) INCLUDE foo -%]
foo: [% foo %]
foo(c): [% foo(c) %]
-- expect --
foo: This is the foo file, a is
foo(c): This is the foo file, a is charlie
-- test --
[% BLOCK mypage %]
Header
[% content %]
Footer
[% END %]
[%- MACRO content BLOCK -%]
This is a macro which encapsulates a template block.
a: [% a -%]
[% END -%]... | Footer
mid
Header
This is a macro which encapsulates a template block.
a: New Alpha
Footer
end
-- test --
[% BLOCK table %]
<table>
[% rows %]
</table>
[% END -%]
[% # define some dummy data
udata = [
{ id => 'foo', name => 'Fubar' },
{ id => 'bar', name => 'Babar' }
]
-%]
[% # define a macro to p... |
CityofPittsburgh/pittsburgh-purchasing-suite | migrations/versions/29562eda8fbc_add_vendor_opportunity_category_models.py | Python | bsd-3-clause | 3,927 | 0.012478 | """add vendor, opportunity, category models
Revision ID: 29562eda8fbc
Revises: 3473ff14af7e
Create Date: 2015-05-28 02:31:47.039725
"""
# revision identifiers, used by Alembic.
revision = '29562eda8fbc'
down_revision = '3473ff14af7e'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands a... | sa.PrimaryKeyConstraint('id')
)
op.add_column('app_status', sa.Column('county_max_deadline', sa.DateTime(), nullable=True))
op.add_column('line_item', sa.Column('percentage', sa.Boolean(), nullable=True))
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - pleas... | or_association_vendor_id'), table_name='category_vendor_association')
op.drop_index(op.f('ix_category_vendor_association_category_id'), table_name='category_vendor_association')
op.drop_table('category_vendor_association')
op.drop_index(op.f('ix_vendor_id'), table_name='vendor')
op.drop_table('vendor')
... |
mhkyg/OrangePIStuff | lcd/lcd_update.py | Python | mit | 1,190 | 0.012605 | #!/usr/bin/python3
# Example using a character LCD connected to a Raspberry Pi or BeagleBone Black.
import time
import datetime
import Adafruit_CharLCD as LCD
def file_get_contents(filename):
with open(filename) as f:
return f.read()
# Raspberry Pi pin configuration:
lcd_rs = 24 # Note this might ... | lcd_columns, lcd_rows, lcd_backlight)
datestring = datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
lcd.clear()
lcd.message(file_get_contents | ("../data/lcd.txt") ); |
shirk3y/cyclone | demos/helloworld/helloworld.py | Python | apache-2.0 | 1,114 | 0 | #!/usr/bin/env python
# coding: utf-8
#
# Copyright 2010 Alexandre Fiori
# based on the original Tornado by Facebook
#
# 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.... | TIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import cyclone.web
import sys
from twisted.internet import reactor
from twisted.python import log
class MainHandler(cyclone.web.RequestHandler):
def ge... | istenTCP(8888, application, interface="127.0.0.1")
reactor.run()
if __name__ == "__main__":
main()
|
0x0mar/RATDecoders | Xtreme.py | Python | gpl-3.0 | 10,565 | 0.030951 | #!/usr/bin/env python
'''
xtreme Rat Config Decoder
'''
__description__ = 'xtreme Rat Config Extractor'
__author__ = 'Kevin Breen http://techanarchy.net http://malwareconfig.com'
__version__ = '0.1'
__date__ = '2014/04/10'
#Standard Imports Go Here
import os
import sys
import string
from struct import unpack
from op... | "] = getUnicodeString(rawConfig, 0x380)
dict["FTP UserName"] = getUnicodeString(rawConfig, 0x422)
dict["FTP Password"] = getUnicodeString(rawConfig, 0x476)
dict["FTP Folder"] = getUnicodeString(rawCon | fig, 0x3d2)
dict["Domain1"] = str(getUnicodeString(rawConfig, 0x14)+":"+str(unpack("<I",rawConfig[0:4])[0]))
dict["Domain2"] = str(getUnicodeString(rawConfig, 0x66)+":"+str(unpack("<I",rawConfig[4:8])[0]))
dict["Domain3"] = str(getUnicodeString(rawConfig, 0xb8)+":"+str(unpack("<I",rawConfig[8:12])[0]))
dict["Domain... |
ABcDexter/cython | Cython/Compiler/Optimize.py | Python | apache-2.0 | 169,504 | 0.004501 | from __future__ import absolute_import
from . import TypeSlots
from .ExprNodes import not_a_constant
import cython
cython.declare(UtilityCode=object, EncodedString=object, BytesLiteral=object,
Nodes=object, ExprNodes=object, PyrexTypes=object, Builtin=object,
UtilNodes=object)
from . imp... | ResultRefNode):
node = node.expression
return node
def is_common_value(a, b):
a = unwrap_node(a)
b = unwrap_node(b)
if isinstance(a, ExprNodes.NameNode) and isinstance(b, ExprNodes.NameNo | de):
return a.name == b.name
if isinstance(a, ExprNodes.AttributeNode) and isinstance(b, ExprNodes.AttributeNode):
return not a.is_py_attr and is_common_value(a.obj, b.obj) and a.attribute == b.attribute
return False
def filter_none_node(node):
if node is not None and node.constant_result i... |
bitmazk/django-event-rsvp | event_rsvp/views.py | Python | mit | 8,144 | 0.000491 | """Views for the ``event_rsvp`` app."""
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.http import Http404, HttpResponseRedirect
from django.utils import timezone
from django.utils.decorators import method_decorator
from django.views.generic import (
... | self.kwargs = kwargs
self.object = self.get_object()
if not self.object.is_published and not request.user.is_staff:
raise Http404
return super(EventDetailView, self).dispatch(request, *args, **kwargs)
class EventCreateView(StaffMixin, EventViewMixin, CreateVi | ew):
"""Create view to handle information of an event."""
pass
class EventUpdateView(StaffMixin, EventSecurityMixin, EventViewMixin,
UpdateView):
"""Update view to handle information of an event."""
url_mode = 'update'
class EventDeleteView(StaffMixin, EventSecurityMixin, Event... |
elliotpeele/pyramid_oauth2_provider | pyramid_oauth2_provider/models.py | Python | mit | 6,539 | 0 | #
# Copyright (c) Elliot Peele <elliot@bentlogic.net>
#
# This program is distributed under the terms of the MIT License as found
# in a file called LICENSE. If it is not present, the license
# is always available at http://www.opensource.org/licenses/mit-license.php.
#
# This program is distributed in the hope that it... | peError:
pass
self._client_secret = kdf.derive(client_secret)
client_secret = synonym('_client_secret', descriptor=property(
_get_client_secret, _set_client_secret))
def revoke(self):
self.revoked = True
self.revocation_date = datetime.utcnow()
def isRevoked(se... | Oauth2RedirectUri(Base):
__tablename__ = 'oauth2_provider_redirect_uris'
id = Column(Integer, primary_key=True)
uri = Column(Unicode(256), unique=True, nullable=False)
client_id = Column(Integer, ForeignKey(Oauth2Client.id))
client = relationship(Oauth2Client, backref=backref('redirect_uris'))
... |
dustinvtran/bayesrl | bayesrl/environments/chainworld.py | Python | mit | 1,441 | 0.002082 | import numpy as np
from ..utils import check_random_state
class ChainWorld(object):
def __init__(self, left_length, left_reward, right_length, right_reward, on_chain_reward, p_return_to_start, random_state=None):
self.left_length = left_length
self.left_reward = left_reward
self.right_lengt... | d = right_reward
self.on_chain_reward = on_chain_reward
self.p_return_to_start = p_return_to_start
self.num_states = self.left_length + self.right_length + 1
self.num_actions = 2
self.random_state = check_random_state(random_state)
self.reset()
def reset(self):
... | def is_terminal(self, state):
return state == 0 or state == self.num_states - 1
def perform_action(self, action):
if self.p_return_to_start and self.random_state.rand() < self.p_return_to_start:
self.reset()
elif action == 0:
self.state -= 1
else:
... |
obi-two/Rebelion | data/scripts/templates/object/building/poi/shared_tatooine_hutt_assassin_camp_large1.py | Python | mit | 465 | 0.047312 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE L | OST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Building()
result.template = "object/building/poi/shared_tatooine_hutt_assassin_camp_large1.iff"
result.attribute_template_id = -1
result.stfName("poi_n","base_poi_building")
... | MODIFICATIONS ####
return result |
wmvanvliet/mne-python | mne/preprocessing/__init__.py | Python | bsd-3-clause | 1,572 | 0 | """Preprocessing with artifact detection, SSP, and ICA."""
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Matti Hämäläinen <msh@nmr.mgh.harvard.edu>
# Martin Luessi <mluessi@nmr.mgh.harvard.edu>
# Denis Engemann <denis.engemann@gmail.com>
#
# License: BSD-3-Clause
from .annot... | orrmap, read_ica_eeglab)
from .otp import oversampled_temp | oral_projection
from ._peak_finder import peak_finder
from .infomax_ import infomax
from .stim import fix_stim_artifact
from .maxwell import (maxwell_filter, find_bad_channels_maxwell,
compute_maxwell_basis)
from .realign import realign_raw
from .xdawn import Xdawn
from ._csd import compute_curren... |
fancl20/pili-python | pili/client.py | Python | mit | 163 | 0.006135 | from .hub import H | ub
class Client(object):
| def __init__(self, mac):
self.__mac__ = mac
def hub(self, hub):
return Hub(self.__mac__, hub)
|
Sanji-IO/sanji-firmware | tests/test_e2e/view_firmware.py | Python | gpl-2.0 | 4,216 | 0 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import logging
from time import sleep
from sanji.core import Sanji
from sanji.connection.mqtt import Mqtt
REQ_RESOURCE = "/system/firmware"
class View(Sanji):
# This function will be executed after registered.
def run(self):
for count in xrange(0, 10... | data={"server": "test.server"})
if res.code != 200:
print "data.reset=0 should reply code 200"
print res.to_json()
self.stop()
print "GET %s" % REQ_RESOURCE
res = self.publish.get(REQ_RESOURCE)
... | self.stop()
elif "test.server" != res.data["server"]:
print "PUT failed, server (%s) should be \"test.server\"" \
% res.data["server"]
self.stop()
# case 7: test PUT with upgrade=0
sleep(2)
print "PUT %s... |
chemelnucfin/tensorflow | tensorflow/python/autograph/impl/api_test.py | Python | apache-2.0 | 30,339 | 0.008141 | # 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 required by applica... | "
from __future__ import absolute_import
from __future__ import division
from __future_ | _ import print_function
import collections
import functools
import gc
import imp
import os
import re
import textwrap
import types
import numpy as np
from tensorflow.python.autograph import utils
from tensorflow.python.autograph.core import ag_ctx
from tensorflow.python.autograph.core import converter
from tensorflow... |
conan-io/conan | conans/test/unittests/tools/gnu/autotools_test.py | Python | mit | 857 | 0.002334 | import os
from conan.tools.files.files import save_toolchain_args
from conan.tools.gnu import Autotools
from conans.test.utils.mocks import ConanFileMock
from conans.test.utils.test_files import temp_folder
def test_source_folder_works():
folder = temp_folder()
os.chdir(folder)
save_toolchain_args({
... | ools(conanfile)
autotools.configure(build_script_folder="subfolder")
assert conanfile.com | mand.replace("\\", "/") == '"/path/to/sources/subfolder/configure" -foo bar'
autotools.configure()
assert conanfile.command.replace("\\", "/") == '"/path/to/sources/configure" -foo bar'
|
remybaranx/qtaste | Testbeds/ControlScripts/do_nothing.py | Python | gpl-3.0 | 507 | 0.027613 | from controlscript import *
print "This is a simple control script. It just does nothing and exits successfully."
print "Start parameter is %s, additional parameters are %s" % (star | t, arguments)
class DoNothing(ControlAction):
""" Control script action for exiting with error 1 on stop """
def __init__(self):
ControlAction.__init__(self, "Do nothing")
def start(self):
print "Do nothing on start"
print
|
def stop(self):
print "Do nothing on stop"
print
ControlScript([
DoNothing()
]) |
kuzeko/Twitter-Importer | twitter_helper/twitter_data.py | Python | mit | 8,560 | 0.002921 | import re
import Queue
import HTMLParser
import dateutil.parser as parser
class TwitterData:
#Twitter Datum properties
tweet_fields_list = ['id', 'user_id', 'in_reply_to_status_id', 'in_reply_to_user_id', 'favorited', 'retweeted', 'retweet_count', 'lang', 'created_at']
tweet_text_fields_list = ['tweet_id... | weet['coordinates']['coordinates'][1])
elif field == 'place_full_name':
if not tweet['place']:
value = ''
else:
value = tweet['place']['full_name'].strip()
value = self.highpoints.sub(u'', value)
... | tweet_text_record.append(value)
elif field == 'place_id':
# http://api.twitter.com/1/geo/id/6b9ed4869788d40e.json
if not tweet['place']:
tweet_text_record.append('')
else:
tweet_text_record.append(tweet['place'... |
pydicom/sendit | sendit/celery.py | Python | mit | 512 | 0.001953 | from __future__ import absolute_import
import os
from celery import Celery
from django.conf import settings
from celery.schedules import crontab
from sendit.settings import (
INSTALLED_APPS,
BROKER_URL
)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sendit.settings')
app = | Celery('sendit',broker=BROKER_URL)
# Using a string here means the worker will not have to
# pickle the object when using Windows.
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: I | NSTALLED_APPS)
|
jammon/gemeinde | gottesdienste/models.py | Python | mit | 2,564 | 0.007419 | # encoding: utf-8
from django.db import models
from gemeinde import settings
from mezzanine.generic.fields import KeywordsField
from mezzanine.pages.models import Page
from pytz import timezone
# from django.utils.timezone import activate
# activate()
class Gottesdienst(models.Model):
u"""Repräsentiert einen Gott... | t',
self.datum.astimezone(timezone(settings.TIME_ZONE))))
def save(self, *args, **kwargs):
if self.prediger_key:
self.prediger = unicode(self.prediger_key)
super(Gottesdienst, self).save(*args, **kwargs)
def prediger_name(self):
return (self.prediger_ke... | key
else self.prediger)
class Prediger(models.Model):
"""Ein Prediger, der Gottesdienste feiert"""
nachname = models.CharField(max_length=50)
vorname = models.CharField(max_length=50, blank=True)
titel = models.CharField(max_length=10, blank=True)
class Meta:
verbose_name =... |
bfirsh/pytest_django | tests/views.py | Python | bsd-3-clause | 270 | 0.003704 | from django.http import HttpResponse
from django.template import Template
d | ef admin_required_view(request):
if request.user.is_staff:
return HttpResponse(Template('You are an admin').render({}))
return HttpResponse(Template('Access denied').render( | {}))
|
NeoBelerophon/Arietta.GPIO | test/test.py | Python | mit | 18,250 | 0.003671 | #!/usr/bin/env python
"""
Copyright (c) 2013-2014 Ben Croston
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, mer... | setup(LED_PIN, GPIO.IN)
# Test setup(..., pull_up_down=GPIO.HIGH) raises exception
with self.assertRaises(ValueError):
GPIO.setup(LED_PIN, GPIO.IN, pull_up_down=GPIO.HIGH)
# Test 'already in use' warning
GPIO.cleanup()
with open('/sys/class/gpio/export','wb') as f:
... | with open('/sys/class/gpio/gpio%s/direction'%LED_PIN_BCM,'wb') as f:
f.write(b'out')
with open('/sys/class/gpio/gpio%s/value'%LED_PIN_BCM,'wb') as f:
f.write(b'1')
with warnings.catch_warnings(record=True) as w:
GPIO.setup(LED_PIN, GPIO.OUT) # generate 'already in... |
mjumbewu/django-model-blocks | setup.py | Python | bsd-3-clause | 1,497 | 0.008684 | from setuptools import setup, find_packages
model_blocks = __import__('model_blocks')
readme_file = 'README.rst'
try:
long_description = open(readme_file).read()
except IOError, err:
sys.stderr.write("[ERROR] Cannot find file specified as "
"``long_description`` (%s)\n" % readme_file)
sys.exit(1)
... | 'Intended Audience :: Developers',
'License :: OSI Approved :: BSD | License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Utilities'],
)
|
svenfraeys/sftoolbox | sftoolboxqt/editor.py | Python | mit | 4,569 | 0 | """gui systems to manage actions
"""
import os
from sftoolbox.content import ActionContent, PanelContent
from sftoolboxqt import qtgui, qtcore
from sftoolboxqt.tree import PanelsModel, PanelsTreeWidget
class ActionsTreeWidget(qtgui.QTreeWidget):
"""tree widget holding actions
"""
def startDrag(self, dro... | self._project = value
self._refresh_content()
def _handle_item_double_clicked(self, item):
"""handle doubleclicking item
"""
item.action.run()
def _refresh_content(self):
"""refresh the content
"""
| self._tree_widget.clear()
self._tree_widget.itemDoubleClicked.connect(
self._handle_item_double_clicked)
if not self.project:
return
for action in self.project.actions:
item = qtgui.QTreeWidgetItem()
icon_filepath = action.absolute_icon_filepath
... |
OniOni/ril | wsgi.py | Python | apache-2.0 | 37 | 0 | from | app im | port setup
app = setup()
|
kkris/wheatley | strategies.py | Python | bsd-3-clause | 10,513 | 0.003044 | """
strategies
~~~~~~~~~~
Various strategies.
:copyright: (c) 2013 by Matthias Hummel and Kristoffer Kleine.
:license: BSD, see LICENSE for more details.
"""
from graph import (State, make_walkable, split_into_extended_islands,
split_into_subgraphs, make_flooded)
def get_direction(current, targe... | continue
next_node = min(current_node.neighbors, key=lambda n: n.distance_to_flooded)
direction = get_direction(current_node, next_node)
self.do('GO', direction)
current_node = next_node
return self.commit()
class MetaStrategy(Strategy):
"""
... | uates the current situation and chooses the right strategy
"""
def evaluate_mode(self, walkable, position):
current_node = walkable.get_node(*position)
target_island = None
for island in self.extended_islands:
other_node = walkable.get_node(island.nodes[0].x, island.nodes[... |
jrcapriles/armSimulator | ButtonTest.py | Python | mit | 1,443 | 0.028413 | # -*- coding: utf-8 -*-
"""
Created on Sat Jul 26 23:01:44 2014
@author: Jose Capriles
"""
import pygame, Buttons
from pygame.locals import *
#Initialize pygame
pygame.init()
class Button_Test:
def __init__(self):
self.loopFlag = True
self.main()
#Create a display
... | #Run the loop
def main(self):
self.display()
self.Button1 = Buttons.Button(self.screen, color = (107,142,35), x = 225, y = 135, length = 200, height = 100, width = 0, text ="Button Test", t | ext_color = (255,255,255), font_size=25, fade_on = False)
while self.loopFlag:
self.update_display()
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.loopFlag = False
if event.type == KEYDOWN:
... |
MOA-2011/enigma2-plugin-extensions-openwebif | plugin/controllers/models/config.py | Python | gpl-2.0 | 7,243 | 0.034102 | # -*- coding: utf-8 -*-
from enigma import eEnv
from Components.SystemInfo import SystemInfo
from Components.config import config
from os import path, listdir
import xml.etree.cElementTree
from Plugins.Extensions.OpenWebif.__init__ import _
def addCollapsedMenu(name):
tags = config.OpenWebif.webcache.collapsedmenus... | cache.remotegrabscreenshot.value = value
config.OpenWebif.webcache.remotegrabscreenshot.save()
return {
"result": True
}
def getRemoteGrabScreenshot():
return {
"result": True,
"remotegrabscreenshot": config.OpenWebif.webcache.remotegrabscreenshot.value
}
def setZapStream(value):
config.OpenWebif.webcache... | eam.value = value
config.OpenWebif.webcache.zapstream.save()
return {
"result": True
}
def getZapStream():
return {
"result": True,
"zapstream": config.OpenWebif.webcache.zapstream.value
}
def getJsonFromConfig(cnf):
if cnf.__class__.__name__ == "ConfigSelection" or cnf.__class__.__name__ == "ConfigSelect... |
Zex0n/django-simple-cms | news/urls.py | Python | mit | 286 | 0 | from django.conf.urls import url
from . import views
urlpat | terns = [
# url(r'^news/([\w-]+)$', views.ListView.as_view(), name='list'),
url(r'^news/$', views.ListV | iew.as_view(), name='list_all'),
url(r'^news/(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
]
|
bwhite/picarus | server/jobs.py | Python | apache-2.0 | 9,515 | 0.002207 | #!/usr/bin/env python
if __name__ == '__main__':
from gevent import monkey
monkey.patch_all()
import redis
import json
import pprint
import argparse
import mturk_vision
import base64
import uuid
import pickle
import time
import databases
from hadoop_parse import scrape_hadoop_jobs
class UnauthorizedException(... | RAVEN.captureException()
raise
parser = argparse.ArgumentParser(description=' | Picarus job operations')
parser.add_argument('--redis_host', help='Redis Host', default='localhost')
parser.add_argument('--redis_port', type=int, help='Redis Port', default=6379)
parser.add_argument('--raven', help='URL to the Raven/Sentry logging server')
parser.add_argument('--annotations_redis_host'... |
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/shapely/geometry/point.py | Python | agpl-3.0 | 6,390 | 0.002817 | """Points and related utilities
"""
from ctypes import c_double
from ctypes import cast, POINTER
from shapely.coords import required
from shapely.geos import lgeos, DimensionError
from | shapely.geometry.base import BaseGeometry
from shapely.geometry.proxy import CachingGeometryProxy
__all__ = ['Point', 'asPoint']
class Point(BaseGeometry):
"""
A zero dimensional feature
A point has zero length and zero area.
Attributes
----------
x, y | , z : float
Coordinate values
Example
-------
>>> p = Point(1.0, -1.0)
>>> print p
POINT (1.0000000000000000 -1.0000000000000000)
>>> p.y
-1.0
>>> p.x
1.0
"""
def __init__(self, *args):
"""
Parameters
----------
The... |
blab/nextstrain-db | download_all.py | Python | agpl-3.0 | 7,407 | 0.006615 | # Simple script to run required operations to
# 1. Download FASTAs from database
# 2. Copy FASTAs to nextflu directory
# 3. Download titer tables from database
# 4. Copy titer tables to nextflu directory
# Run from base fauna directory with python flu/download_all.py
# Assumes that nextflu/, nextflu-cdc/ and nextflu-cd... | = str, help ="seasonal flu lineages to download, options are h3n2, h1n1pdm, vic and yam")
parser.add_argument('--segments', type=str, default=['ha', 'na'], nargs='+', help="specify segment(s) to download")
parser.add_argument('--sequences', default=False, action="store_true", help="download sequences from vdb")
parser... | ources', default=["base", "crick", "cdc", "niid", "vidrl"], nargs='+', type = str, help ="titer sources to download, options are base, cdc, crick, niid and vidrl")
parser.add_argument('--titers_passages', default=["egg", "cell"], nargs='+', type = str, help ="titer passage types to download, options are egg and cell"... |
tweemeterjop/thug | thug/ActiveX/modules/Kingsoft.py | Python | gpl-2.0 | 350 | 0 | # Kingsoft An | tivirus
# CVE-NOMATCH
import logging
log = logging.getLogger("Thug")
def SetUninstallName(self, arg):
if len(arg) > 900:
log.ThugLogging.log_exploit_event(self._window.url,
"Kingsoft AntiVirus ActiveX",
"SetUninstallName... | erflow")
|
suhe/odoo | addons/payroll_cancel/controllers/controllers.py | Python | gpl-3.0 | 806 | 0.003722 | # -*- coding: utf-8 -*-
from openerp import http
# class PayrollCancel(http.Controller):
# @http.route('/payroll_cancel/payroll_cancel/', auth='publ | ic')
# def index(self, **kw):
# return "Hello, world"
# @http.route('/payroll_cancel/payroll_cancel/objects/', auth='public')
# def list(self, **kw) | :
# return http.request.render('payroll_cancel.listing', {
# 'root': '/payroll_cancel/payroll_cancel',
# 'objects': http.request.env['payroll_cancel.payroll_cancel'].search([]),
# })
# @http.route('/payroll_cancel/payroll_cancel/objects/<model("payroll_cancel.payroll_cancel"... |
diogocs1/comps | web/addons/note/note.py | Python | apache-2.0 | 8,900 | 0.01 | # -*- 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... | azy)
#upgrade config setting page to configure pad, fancy and tags mode
class note_base_config_settings(osv.osv_memory):
_inherit = 'base.config.settings'
_columns = {
| 'module_note_pad': fields.boolean('Use collaborative pads (etherpad)'),
'group_note_fancy': fields.boolean('Use fancy layouts for notes', implied_group='note.group_note_fancy'),
}
class res_users(osv.Model):
_name = 'res.users'
_inherit = [' |
macarthur-lab/seqr | reference_data/migrations/0008_geneexpression.py | Python | agpl-3.0 | 724 | 0.002762 | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-09-17 15:22
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.M | igration):
dependencies = [
('reference_data', '0007_auto_20180809_2053'),
]
operations = [
migrations.CreateModel(
name='GeneExpression',
fields=[
('id', models.AutoField(aut | o_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('expression_values', models.TextField(blank=True, null=True)),
('gene', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='reference_data.GeneInfo')),
],
),
]
|
enthought/traitsgui | enthought/pyface/dock/dock_sizer.py | Python | bsd-3-clause | 155,245 | 0.020265 | #-------------------------------------------------------------------------------
#
# Copyright (c) 2005, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in enthought/LICENSE.txt and may be redistributed only
# under the conditions ... | -------------------------------------------------------------------------------
# Imports:
| #-------------------------------------------------------------------------------
import wx, sys
from enthought.traits.api \
import HasPrivateTraits, Instance, Str, Int, List, Enum, Tuple, Any, \
Range, Property, Callable, Constant, Event, Undefined, Bool, \
cached_property
from enthought.tr... |
Uberlearner/uberlearner | uberlearner/courses/admin.py | Python | mit | 848 | 0.008255 | from django.contrib import admin
from courses.models import Course, Instructor, Page, Enrollment
class CourseAdmin(admin.ModelAdmin):
list_display = ['title', 'instructor', 'language', 'popularity', 'is_public', 'deleted']
prepopulated_fields = {
'slug': ('title', )
}
def queryset(self, request... | # the following is needed from the superclass
ordering = self.get_ordering(request)
if ordering:
qs = qs.order_by(*ordering)
return qs
class InstructorAdmin(admin.ModelAdmin):
list_display = ['user', 'popularity']
class PageAdmin(admin.ModelAdmin):
pass
admin.s... | ent)
|
hamperbot/factoids2 | hamper_factoids/parser.py | Python | mpl-2.0 | 1,049 | 0.000953 | import parsley
_grammar = r"""
parse = pair:head (' '+ pair)*:tail -> dict([head] + tail)
pair = ident:i '=' value:v -> (i, v)
ident = <letter letterOrDigit*>
value = string | regex | number | word
string = '"' (escapedChar | ~'"' anything)*:c '"' -> ''.join(c)
| "'" (escapedChar | ~"'" anything)*:c "'" -> ''.... | -> '/' + ''.join(c) + '/'
word = <(~' ' anything)+>
# A number is optionally a negative sign, followed by an intPart, and then
# maybe a floatPart.
number = ('-' | -> ''):sign
( (intPart:i floatPart:f -> float(sign + i + f ))
| (intPart:i -> int(sign + i))
| (floatPart:f -> float(sign + '0'... | first + rest)
| digit
floatPart = <'.' digit+>
# This matches a *single* backslash, followed by something else, which it returns.
escapedChar = "\\\\" anything
"""
learn_grammar = parsley.makeGrammar(_grammar, {})
|
mattew/mattew.github.io-src | publishconf.py | Python | mit | 531 | 0.00565 | #!/usr/bin/en | v python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
# This file is only used if you use `make publish` or
# explicitly specify it as your config file.
import os
import sys
sys.path.append(os.curdir)
from pelicanconf import *
SITEURL = 'http://mpdev.mattew.se'
RELATIVE_URLS = False
FEED_ALL_AT... | M = 'feeds/all.atom.xml'
CATEGORY_FEED_ATOM = 'feeds/%s.atom.xml'
DELETE_OUTPUT_DIRECTORY = False
# Following items are often useful when publishing
#DISQUS_SITENAME = ""
#GOOGLE_ANALYTICS = ""
|
cs-au-dk/Artemis | WebKit/Tools/Scripts/webkitpy/layout_tests/layout_package/json_layout_results_generator.py | Python | gpl-3.0 | 7,573 | 0.002377 | # Copyright (C) 2010 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the ... | ITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTA | L,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE... |
antoinecarme/pyaf | tests/model_control/detailed/transf_Logit/model_control_one_enabled_Logit_LinearTrend_Seasonal_DayOfMonth_SVR.py | Python | bsd-3-clause | 160 | 0.05 | import tests.model_control.test_ozone_custom_models_enabled as testmod
testmod.build_model( ['Logit'] , ['LinearTrend' | ] , ['Seasonal_DayOfMonth'] | , ['SVR'] ); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.