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 |
|---|---|---|---|---|---|---|---|---|
tableau/TabPy | tests/integration/test_custom_evaluate_timeout.py | Python | mit | 1,223 | 0.000818 | from . import integ_test_base
class TestCustomEvaluateTimeout(integ_test_base.IntegTestBase):
def _get_evaluate_timeout(self) -> str:
return "3"
def test_custom_evaluate_timeout_with_script(self):
# Uncomment the following line to preserve
# test case output and other files (config, s... |
"""
headers = {
"Content-Type": "application/json",
"TabPy-Client": "Integration test for testing custom eva | luate timeouts "
"with scripts.",
}
conn = self._get_connection()
conn.request("POST", "/evaluate", payload, headers)
res = conn.getresponse()
actual_error_message = res.read().decode("utf-8")
self.assertEqual(408, res.status)
self.assertEqual(
... |
saikrishnarallabandi/clustergen_steroids | building_blocks/falcon_models.py | Python | apache-2.0 | 7,925 | 0.029653 | import dynet_config
dynet_config.set_gpu()
import dynet as dy
import os
import pickle
import numpy as np
import numpy as np
import os,sys
from sklearn import preprocessing
import pickle, logging
import argparse
debug = 0
class falcon_heavy(object):
def __init__(self, model, args):
self.pc = model.add_su... | .act_generic):
weigh | t_matrix_array.append(dy.parameter(W))
biases_array.append(dy.parameter(b))
acts.append(a)
# Specific layers
length = len(self.postspecificlayers)
start_index = (tgtspk -1)*length
idx = 0
if debug:
print "The number of specific biases: ... |
pashinin-com/pashinin.com | src/pashinin/admin.py | Python | gpl-3.0 | 1,211 | 0 | from django.contrib import admin
from .models import Lesson, Course, CourseLead, QA
# from django.utils.translation import ugettext_lazy as _
from ordered_model.admin import OrderedModelAdmin
from core.models import User
# from adminfilters.models import Species, Breed
class UserAdminInline(admin.TabularInline):
... | filter = ('student', )
list_display = ('start', 'student')
save_as = True
# raw_id_fields = ("student",)
# inlines = [UserAdminInline]
@admin.register(Course)
class CourseAdmin(admin.ModelAdmin):
list_display = ('name', 'slug', 'published', )
ordering = ['id']
@admin.regis | ter(CourseLead)
class CourseLeadAdmin(admin.ModelAdmin):
list_display = (
'name',
'contact',
'course',
'status',
'student',
)
list_filter = ('status', )
ordering = ['status']
@admin.register(QA)
class QAAdmin(OrderedModelAdmin):
list_display = (
'ord... |
RadonX/iScript | leetcode_problems.py | Python | mit | 4,146 | 0.002894 | #!/usr/bin/env python
# -*- coding=utf-8 -*-
import sys
import re
import os
import argparse
import requests
from lxml import html as lxml_html
try:
import html
except ImportError:
import HTMLParser
html = HTMLParser.HTMLParser()
try:
import cPickle as pk
except ImportError:
import pickle as pk
c... | sys.exit()
tree = lxml_html.fromstring(res.text)
title = tree.xpath('//meta[@property="og:title"]/@content')[0]
description = tree.xpath('//meta[@property="description"]/@content')
if not description:
| description = tree.xpath('//meta[@property="og:description"]/@content')[0]
else:
description = description[0]
description = html.unescape(description.strip())
tags = tree.xpath('//div[@id="tags"]/following::a[@class="btn btn-xs btn-primary"]/text()')
... |
whiplash01/pyCycle | src/pycycle/heat_exchanger.py | Python | apache-2.0 | 4,907 | 0.01773 | """
preHeatEx.py - (Run this before heatExchanger2.py)
Performs inital energy balance for a basic heat exchanger design
Originally built by Scott Jones in NPSS, ported and augmented by Jeff Chin
NTU (effectiveness) Method
Determine the heat transfer rate and outlet temperatures when the type ... | Cp_cold = self.Cp_cold
W_coldCpMin = W_cold*Cp_cold;
if ( Wh*Cp_hot < W_cold*Cp_cold ):
W_coldCpMin = Wh*Cp_hot
self.Qmax = W_coldCpMin*(T_hot_in - T_cold_in)*1.4148532; #BTU/s to hp
self.Qreleased = Wh*Cp_hot*(T_hot_in - T_hot_out)*1 | .4148532;
self.Qabsorbed = W_cold*Cp_cold*(T_cold_out - T_cold_in)*1.4148532;
try:
self.LMTD = ((T_hot_out-T_hot_in)+(T_cold_out-T_cold_in))/log((T_hot_out-T_cold_in)/(T_hot_in-T_cold_out))
except ZeroDivisionError:
self.LMTD = 0
self.residual_qmax = self.Qre... |
PyBossa/pybossa | pybossa/flickr_client.py | Python | agpl-3.0 | 2,464 | 0.000406 | # -*- coding: utf8 -*-
# This file is part of PYBOSSA.
#
# Copyright (C) 2015 Scifabric LTD.
#
# PYBOSSA 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 op... | __init__(self, api_key, logger=None):
self.api_key = api_key
self.logger = logger
def get_user_albums(self, session):
"""Get user albums from Flickr."""
if session.get('flickr_user') is not None:
url = 'https://api.flickr.com/servi | ces/rest/'
payload = {'method': 'flickr.photosets.getList',
'api_key': self.api_key,
'user_id': self._get_user_nsid(session),
'format': 'json',
'primary_photo_extras':'url_q',
'nojsoncallback':... |
saltstack/salt | tests/pytests/unit/beacons/test_bonjour_announce.py | Python | apache-2.0 | 801 | 0.003745 | """
tests.pytests.unit.beacons.test_bonjour_announce
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Bonjour announce beacon test cases
"""
import pytest
import salt.beacons.bonjour_announce as bonjour_announce
@pytest.fixture
def configure_loader_modules():
return {
bonjour_announce: {"last... | {"no_devices": False}}
}
def test_non_list_config():
config = {}
ret = bonjour_announce.validate(config)
assert ret == (False, "Configuration for bonjour_announce beacon must be a list.")
def test_empty_config():
config = [{}]
ret = bonjour_announce.validate(config)
assert ret == (
... | njour_announce beacon must contain servicetype, port and"
" txt items.",
)
|
ActiveState/code | recipes/Python/576816_Interval/recipe-576816.py | Python | mit | 3,064 | 0.014034 | class Interval(object):
"""
Represents an interval.
Defined as half-open interval [start,end), which includes the start position but not the end.
Start and end do not have to be numeric types.
"""
def __init__(self, start, end):
"Construct, start must be <= end."
if s... | if self > other:
other, self = self, other
i | f self.end > other.start:
return 0
else:
return other.start - self.end
|
DLR-SC/DataFinder | test/unittest/datafinder_test/gui/user/dialogs/datastore_dialog/__init__.py | Python | bsd-3-clause | 1,798 | 0.017798 | #
# $Filename$$
# $Authors$
# Last Changed: $Date$ $Committer$ $Revision-Id$
#
# Copyright (c) 2003-2011, German Aerospace Center (DLR)
# All rights reserved.
#
#
#Redistribution and use in source and binar | y forms, with or without
#modification, are permitted provided that the following conditions are
#met:
#
# * Redistributions of source code must reta | in 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
# distribution.... |
eagle-knights-ITAM/ssl-refbox-ros | scripts/refbox.py | Python | gpl-2.0 | 1,934 | 0.023785 | """
Publishes the Referee Box's messages as a ROS topic named "refbox" with type "referee"
"""
from referee_pb2 import SSL_Referee
import rospy
# Substitute "ekbots" here with your ROS package name
from ekbots.msg import referee, team_info
from socket import socket, inet_aton, IPPROTO_IP, IP_ADD_MEMBERSHIP
from soc... | g(data)
# Instance the ROS msg types to fill them out
yellow, blue, trama = team_info(), team_info(), referee()
# Translate the team info
for team, buf in ((yellow, proto.yellow), (blue, proto.blue)):
team.name = buf.name
team.score = buf.score
team.red_cards = buf.red_cards
team.yellow_card_times = bu... | uf.goalie
trama.yellow = yellow
trama.blue = blue
# Translate the rest
trama.packet_timestamp = proto.packet_timestamp
trama.stage = proto.stage
trama.stage_time_left = proto.stage_time_left
trama.command = proto.command
trama.command_counter = proto.command_counter
trama.command_timestamp = proto.command_... |
tchellomello/home-assistant | homeassistant/components/ambient_station/__init__.py | Python | apache-2.0 | 20,729 | 0.001495 | """Support for Ambient Weather Station Service."""
import asyncio
import logging
from aioambient import Client
from aioambient.errors import WebsocketError
import voluptuous as vol
from homeassistant.components.binary_sensor import DEVICE_CLASS_CONNECTIVITY
from homeassistant.config_entries import SOURCE_IMPORT
from ... | = "batt10"
TYPE_BATT2 = "batt2"
TYPE_BATT3 = "batt3"
TYPE_BATT4 = "batt4"
TYPE_BATT5 = "batt5"
TYPE_BATT6 = "batt6"
TYPE_BATT7 = "batt7"
TYPE_BATT8 = "batt8"
TYPE_BATT9 = "batt9"
TYPE_BATTOUT = "battout"
TYPE_CO2 = "co2"
TYPE_DAILYRAININ = "dailyrainin"
TYPE_DEWPOINT = "dewPoint"
TYPE_EVENTRAININ = "eventrain | in"
TYPE_FEELSLIKE = "feelsLike"
TYPE_HOURLYRAININ = "hourlyrainin"
TYPE_HUMIDITY = "humidity"
TYPE_HUMIDITY1 = "humidity1"
TYPE_HUMIDITY10 = "humidity10"
TYPE_HUMIDITY2 = "humidity2"
TYPE_HUMIDITY3 = "humidity3"
TYPE_HUMIDITY4 = "humidity4"
TYPE_HUMIDITY5 = "humidity5"
TYPE_HUMIDITY6 = "humidity6"
TYPE_HUMIDITY7 = "hu... |
knadir/Flask-Images | flask_images/size.py | Python | bsd-3-clause | 3,727 | 0.00322 | from __future__ import division
from PIL import Image
from . import modes
from .transform import Transform
class ImageSize(object):
@property
def image(self):
if not self._image and self.path:
self._image = Image.open(self.path)
return self._image
def __init__(self, path=No... | if not self.width:
self.needs_enlarge = self.height > self.image_height
if not self.enlarge:
self.height = min(self.height, self.image_height)
self.width = self.image_width * self.height // self.image_height
return
# Don't maintain aspect ra | tio; enlarging is sloppy here.
if self.mode in (modes.RESHAPE, None):
self.needs_enlarge = self.width > self.image_width or self.height > self.image_height
if not self.enlarge:
self.width = min(self.width, self.image_width)
self.height = min(self.height, s... |
nrempel/rucksack-api | app/web_components/models.py | Python | mit | 1,563 | 0 | # -*- coding: utf-8 -*-
from datetime import datetime
from app import db
from app.models import components_tags
from app.users.models import User
from app.tags.models import Tag
from app.util import unix_time
clas | s WebComponent(db.Model):
__tablename__ = 'web_component'
id = db.Column(db.Integer, primary_key=True)
created = db.Column(db.DateTime)
name = db.Column(
db.String,
index=True,
unique=True)
description = db.Column(db.String)
owner_id = db.Column(db.Integer, db.ForeignKey(... | ser, backref=db.backref('web_components', lazy='dynamic'))
repository_url = db.Column(db.String(256))
tags = db.relationship(
Tag,
secondary=components_tags,
backref=db.backref('web_components', lazy='dynamic'))
def __init__(
self,
name,
descripti... |
TeamEOS/external_chromium_org | tools/telemetry/telemetry/core/backends/chrome/inspector_timeline.py | Python | bsd-3-clause | 3,318 | 0.005425 | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.core.backends.chrome import timeline_recorder
from telemetry.timeline import inspector_timeline_data
class TabBackendException(Exception):
... | usage:
with inspector_timeline.InspectorTimeline.Recorder(tab):
# Something to run while the timeline is recording.
This is an alternative to directly calling the Start and Stop methods below.
"""
def __init__(self, tab):
self._tab = tab
def __enter__(self):
self._tab.St... | :
super(InspectorTimeline, self).__init__()
self._inspector_backend = inspector_backend
self._is_recording = False
@property
def is_timeline_recording_running(self):
return self._is_recording
def Start(self):
"""Starts recording."""
assert not self._is_recording, 'Start should only be ca... |
raisfathin/chipsec | source/tool/chipsec/hal/spi_uefi.py | Python | gpl-2.0 | 26,618 | 0.018859 | #!/usr/local/bin/python
#CHIPSEC: Platform Security Assessment Framework
#Copyright (c) 2010-2016, Intel Corporation
#
#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; Version 2.
#
#This pr... | ttributes, State, Checksum, Size, FileImage, HeaderSize, UD, fCalcSum = NextFwFile(FvImage, FvLength, next_offset, polarity)
if FvLengthChange >= 0:
data = data[:FvEndOffset] + data[FvEndOffset + FvLengthChange:]
else:
data = data[:FvEndOffset] + (abs(FvLeng... | "Rebuilding Firmware Volume with GUID=%s at offset=%08X" % (FsGuid, FvOffset) )
# FvHeader = data[FvOffset: FvOffset + FvHeaderLength]
# FvHeader = FvHeader[:0x20] + struct.pack('<Q', FvLength) + FvHeader[0x28:]
# NewChecksum = FvChecksum16(FvHeader[:0x32] + '\x00\x00' + ... |
willu47/SALib | src/SALib/sample/latin.py | Python | mit | 1,859 | 0 | from __future__ import division
import numpy as np
from . import common_args
from ..util import scale_samples, read_param_file
def sample(problem, N, seed=None):
"""Generate model inputs using Latin hypercube sampling (LHS).
Returns a NumPy matrix containing the model inputs generated by Latin
... | (D):
for j in range(N):
temp[j] = np.random.uniform(
low=j * d, high=(j + 1) * d, size=1)[0]
np.random.shuffle(temp)
for j in range(N):
result[j, i] = temp[j]
scale_samples(result, problem['bounds'])
return result
def cli_parse... | o CLI parser.
Parameters
----------
parser : argparse object
Returns
----------
Updated argparse object
"""
parser.add_argument('-n', '--samples', type=int, required=True,
help='Number of Samples')
return parser
def cli_action(args):
""... |
gpittarelli/reddit-twitch-bot | lib/twitchtv.py | Python | mit | 1,061 | 0 | #!/usr/bin/env python
'''
Define functions to query the twitch.tv streaming
websites.
More info on the Twitch.tv REST api here:
https://github.com/justintv/twitch-api
'''
import sys
import logging
import requests
'''
Twitch.tv API stream listing r | equest. This API call takes a comma
separated list of channel names and returns an array of JSON objects,
one per channel that is currently streaming (so nothing is returned
for channels that were queried but aren't streaming)
'''
STREAM_URL = "https://api.twitch.tv/kraken/streams?channel=%s"
# Takes an array of ch... | ",".join(channel_names)))
try:
message = response.json()["streams"]
except ValueError:
# JSON Decode failed
sys.exit("Invalid message from twitch.tv: %s" % (response.text))
if not isinstance(message, list):
sys.exit("Unexpected JSON from twitch.tv: %s" % (message))
ret... |
ahmedhosnycs/linkedin-search | fab.py | Python | gpl-2.0 | 575 | 0.003478 | from __future__ import with_sta | tement
from fabric.contrib.console import confirm
from fabric.api import local
import fileinput
def server(port=""):
replace_for_local()
if port:
local("python manage.py runserver 0.0.0.0:" + port + " --settings=linkedin_search.local")
else:
local("python manage.py runserver 0.0.0.0:8888... | age.py " + setting + " --settings=linkedin_search.local")
|
AutorestCI/azure-sdk-for-python | azure-mgmt-web/azure/mgmt/web/models/backup_request.py | Python | mit | 3,146 | 0.001589 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | nType'},
}
def __init__(self, kind=None, backup_request_name=None, enabled=None, storage_account_url=None, backup_schedule=None, databases=None, backup_request_type=None):
super(BackupRequest, self).__init__(kind=kind)
self.backup_request_name = backup_request_name
self.enabled = enable... | self.backup_request_type = backup_request_type
|
perimosocordiae/pyhrm | extract_images.py | Python | mit | 2,304 | 0.009549 | from __future__ import print_function
import numpy as np
import turtle
from argparse import ArgumentParser
from base64 import decodestring
from zlib import de | compress
# Python 2/3 compat
try:
_input = raw_input
except NameError:
_input = input
'''TODO:
* add a matplotlib-based plotter
* add a path export function (for pasting back into HRM)
* path cleanup (length reduction)
* handwriting -> ascii conversion?
'''
def parse_images(filepath):
lines = open(filepat... | artswith(b'DEFINE '):
continue
_, kind, number = line.split()
kind = kind.decode('ascii')
number = int(number)
raw_data = b''
while not line.endswith(b';'):
line = next(lines).strip()
raw_data += line
# strip ; terminator
raw_data = raw_data[:-1]
# add base64 padding
... |
carlos-ferras/Sequence-ToolKit | view/genrep/dialogs/ui_apply_this_to.py | Python | gpl-3.0 | 11,221 | 0.000891 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/home/krl1to5/Work/FULL/Sequence-ToolKit/2016/resources/ui/genrep/dialogs/apply_this_to.ui'
#
# Created by: PyQt5 UI code generator 5.5.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
c... | self.gridLayout.addWidget(self.condition_2, 2, 1, 1, 1)
self.criterion_2 = QtWidgets.QComboBox(self.form_area)
self.criterion_2.setEnabled(False)
self.criterion_2.setMinimumSize(QtCore.QSize(160, 28))
self.criterion_2.setObjectName("criterion_2")
self.criterion_2.addItem("")
... | self.criterion_2.addItem("")
self.criterion_2.addItem("")
self.criterion_2.addItem("")
self.gridLayout.addWidget(self.criterion_2, 2, 0, 1, 1)
self.value_1 = QtWidgets.QLineEdit(self.form_area)
self.value_1.setEnabled(False)
self.value_1.setMinimumSize(QtCore.QSize(160, 2... |
nke001/attention-lvcsr | libs/Theano/theano/sandbox/gpuarray/opt_util.py | Python | mit | 4,761 | 0 | from functools import wraps
import numpy
from theano import scalar as scal, Constant
from theano.gof import local_optimizer
from theano.tensor import (DimShuffle, get_scalar_constant_value,
NotScalarConstantError)
from .basic_ops import GpuFromHost, HostFromGpu
from .elemwise import GpuDim... | cpu_scalar(node.inputs[0], nd=nd)
else:
lr = grab_cpu_scalar(node.inputs[1], nd=nd)
if lr is None or targ | is None:
return None
inputs = list(targ.inputs)
try:
c = get_scalar_constant_value(lr)
if c == 0:
inputs[alpha_in] = lr
inputs[beta_in] = lr
elif c == 1:
... |
hassaanm/stock-trading | src/pybrain/datasets/dataset.py | Python | apache-2.0 | 13,198 | 0.001743 | from __future__ import with_statement
__author__ = 'Thomas Rueckstiess, ruecksti@in.tum.de'
import random
import pickle
from itertools import chain
from scipy import zeros, resize, ravel, asarray
import scipy
from pybrain.utilities import Serializable
class OutOfSyncError(Exception): pass
class VectorFormatError(E... | pendLinked(self, *args):
"""Add rows to all linked fields at once."""
assert len(args) == len(self.link)
for i, l in enumerate(self.link):
self._appendUnlinked(l, args[i])
def getLinked(self, index=None):
"""Access the dataset randomly or sequential.
| If called with `index`, the appropriate line consisting of all linked
fields is returned and the internal marker is set to the next line.
Otherwise the marked line is returned and the marker is moved to the
next line."""
if self.link == []:
raise NoLinkedFieldsError('The da... |
shyba/cryptosync | cryptosync/resources/__init__.py | Python | agpl-3.0 | 300 | 0 | from twisted.web.server import Site
from .root import RootResource
from .auth import Aut | hResource
def make_site(**kwargs | ):
root_resource = RootResource()
auth_resource = AuthResource(kwargs['authenticator'])
root_resource.putChild('auth', auth_resource)
return Site(root_resource)
|
skearnes/pylearn2 | pylearn2/datasets/svhn.py | Python | bsd-3-clause | 18,086 | 0.007796 | """
.. todo::
WRITEME
"""
import os
import gc
import warnings
try:
import tables
except ImportError:
warnings.warn("Couldn't import tables, so far SVHN is "
"only supported with PyTables")
import numpy
from theano import config
from pylearn2.datasets import dense_design_matrix
from pylearn2.uti... | PATH "
"be aware that data might have been "
"modified or pre-processed | .")
if mode == 'r' and (scale or center or (start != None) or
(stop != None)):
raise ValueError("Only for speed there is a copy of hdf5 " +\
"file in PYLEARN2_DATA_PATH but it meant to be only " +\
"readable. If you wish to modify the ... |
peddie/conftron | settings.py | Python | gpl-2.0 | 8,250 | 0.00897 | ## This file is part of conftron.
##
## Copyright (C) 2011 Matt Peddie <peddie@jobyenergy.com>
##
## 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 (a... | "max":self['max'],
"min":self['min'],
"val":self['default']}
die += 1
if float(self['step']) > (float(self['max']) - float(self['min'])):
print parse_settings_badval % {"sp":'default',
... | |
CodeCatz/litterbox | ajda/complicajda.py | Python | mit | 5,477 | 0.023553 | # 1. del: funkcije
#gender: female = 2, male = 0
def calculate_score_for_gender(gender):
if gender == "male":
return 0
else: return 2
#age: 0-100 if age < 10 --> 0, 11 < age < 20 --> 5, 21 < age < 35 --> 2, 36 < age < 50 --> 4, 50+ --> 1
def calculate_score_for_age(age):
if (age > 11 and age <= 20) or (age >... | (raw_input(">> "))
while not money_have:
money_have = float(raw_input("We aren't tax collectors, so be honest: "))
# PRED RAW INPUT MORAS DAT FLOAT, CE NI CELA STEVILKA IN ODSTRANI .ISDIGIT, KER .ISDIGIT JE LE ZA CELE STEVILKE!
#money_want
print "In addition to the mone | y you've got, how much money do you want to have?"
money_want = float(raw_input(">> "))
while money_want < 0: #---->zato, da je pozitivno stevilo!
money_want = float(raw_input("I didn't ask for apples and peaches. So, how much money do you want? "))
#rl_friends
print "How many real friends have you got?"
rl_friends =... |
anselmobd/mb2e | mb2e.py | Python | mit | 8,171 | 0.000122 | #!/usr/bin/env python3
# -*- coding: utf8 -*-
import os
import sys
import re
import gettext
from oxy.arg import parse as argparse
from oxy.verbose import VerboseOutput
class Mbox():
NONE = 0
READ = 1
HEADERCANDIDATE = 2
COPY = 3
END = 4
vOut = None
state = NONE
nLine = 0
header... | '-': '_'}
mailFileName = "".join(transCharacters[c]
if c in transCharacters
else c
for c in mailName
).rstrip()
mailFileName = os.path.join(sel... | n as e:
self.vOut.prnt('Can not open mail file to write "{}"'.format(
mailFileName), 0)
def endEml(self):
self.vOut.prnt('->endEml', 4)
self.eml.close()
self.eml = None
def cleanLine(self):
return self.line.strip('\n')
def extract(self):... |
SGover/monopoly | test1.py | Python | unlicense | 84 | 0 | fr | om gui import playerDialog
n | ame = "haha"
name = playerDialog().show()
print(name)
|
couchbase/couchbase-python-client | acouchbase/tests/cases/transcoder_t.py | Python | apache-2.0 | 31,512 | 0.001111 | import json
import platform
from datetime import timedelta
from unittest import SkipTest
from nose.tools import nottest
from functools import wraps
from acouchbase.cluster import (Cluster, get_event_loop,
close_event_loop)
from couchbase_tests.async_base import AsyncioTestCase
from couc... | a": "b"}}
KEY = "imakey"
async def initialize(self):
try:
await self.collection.remove(self.KEY)
except DocumentNotFoundException:
pass
@async_test
async def test_default_tc_json_upsert(self):
await self.collection.upsert(self.KEY, self.CONTENT)
... | it self.collection.get(self.KEY)
result = resp.content_as[dict]
self.assertIsNotNone(result)
self.assertIsInstance(result, dict)
self.assertEqual(self.CONTENT, result)
@async_test
async def test_default_tc_json_insert(self):
await self.collection.insert(self.KEY, self.CO... |
baspijhor/paparazzi | sw/ground_segment/python/dashboard/radiowatchframe.py | Python | gpl-2.0 | 2,290 | 0.00131 | import wx
import sys
import os
import time
import threading
import math
import pynotify
import pygame.mixer
sys.path.append(os.getenv("PAPARAZZI_HOME") + "/sw/ext/pprzlink/lib/v1.0/python")
from pprzlink.ivy import IvyMessagesInterface
WIDTH = 150
HEIGHT = 40
UPDATE_INTERVAL = 250
class RadioWa | tchFrame(wx.Frame):
def message_recv(self, ac_id, msg):
if msg.name == "ROTORCRAFT_STATUS" | :
self.rc_status = int(msg['rc_status'])
if self.rc_status != 0 and not self.alertChannel.get_busy():
self.warn_timer = wx.CallLater(5, self.rclink_alert)
# else:
# self.notification.close()
def gui_update(self):
self.rc_statusText.SetLabel(["OK", "LO... |
envhyf/wrftools | wrftools/__init__.py | Python | gpl-3.0 | 148 | 0.033784 | #import wrftools
#from exceptions import ConfigError, Domain | Error, ConversionError
#import tools
#import io
#__all__ = ['wrftools', 't | ools', 'io']
|
pythongssapi/python-gssapi | gssapi/_utils.py | Python | isc | 5,004 | 0 | import sys
import types
import typing as t
import decorator as deco
from gssapi.raw.misc import GSSError
if t.TYPE_CHECKING:
from gssapi.sec_contexts import SecurityContext
def import_gssapi_extension(
name: str,
) -> t.Optional[types.ModuleType]:
"""Import a GSSAPI extension module
This method im... | *args, **kwargs)
class CheckLastError(type):
"""Check for a deferred error on all methods
This metaclass applies the :python:`check_last_err` decorator
to all methods not prefixed by '_'.
Additionally, it enabled `__DEFER_STEP_ERRORS__` by default.
"""
def __new__(
cls,
name... | ue
for attr_name in attrs:
attr = attrs[attr_name]
# wrap only methods
if not isinstance(attr, types.FunctionType):
continue
if attr_name[0] != '_':
attrs[attr_name] = check_last_err(attr)
return super(CheckLastError, cl... |
prologic/mio | mio/types/string.py | Python | mit | 3,962 | 0.000252 | from mio import runtime
from mio.utils import method
from mio.object import Object
from mio.lexer import encoding
from mio.core.message import Message
from mio.errors import AttributeError
class String(Object):
def __init__(self, value=u""):
super(String, self).__init__(value=value)
self.create_... | ds
@method("__getitem__")
def getItem(self, receiver, context, m, i):
i = int(i.eval(context))
return receiver.value[i]
@method("__len__")
def getLen(self, receiver, context, m):
return runtime.find("Number").clone(len(receiver.value))
# General Operations
@method("+"... | m, other):
return self.clone(receiver * int(other.eval(context)))
@method()
def find(self, receiver, context, m, sub, start=None, end=None):
sub = str(sub.eval(context))
start = int(start.eval(context)) if start is not None else None
end = int(end.eval(context)) if end is not No... |
stephenl6705/fluentPy | registration_param.py | Python | mit | 451 | 0.017738 | registry = set()
def register(active=True):
def decorate(func):
print('running register(active=%s)->decorate(%s)' % (active, func))
if active:
registry.add(func)
else:
registry.discard(func)
return func
return decorate
@r | egister(active=False)
def f1() | :
print('running f1()')
@register()
def f2():
print('running f2()')
def f3():
print('running f3()') |
tuxite/ovh-dynhost-updater | updater.py | Python | apache-2.0 | 4,677 | 0.002138 | #!/usr/bin/python
# -*- encoding: utf-8 -*-
"""OVH DynHost IP Updater.
Updates at least every 15 minutes the DynHost Record IP of the server.
Uses the OVH API.
Requires:
* ovh - https://github.com/ovh/python-ovh
* ipgetter - https://github.com/phoemur/ipgetter
"""
import re
import time
import os.path
import ConfigPar... | ch
ch.setFormatter(formatter)
# add ch to logger
logger.addHandler(ch)
# The paths in the OVH API (api.ovh.com)
UPDATE_PATH = "/domain/zone/{zonename}/dynHost/record/{id} | "
REFRESH_PATH = "/domain/zone/{zonename}/refresh"
# The file where the IP will be stored
# As the script doesn't run continuosly, we need to retreive the IP somewhere...
IP_FILE = "stored_ip.txt"
# The period between two forced updates of the IP on the OVH server.
# If you launch the script every minute, this reduce... |
uppsaladatavetare/foobar-api | src/wallet/migrations/0010_auto_20170218_2322.py | Python | mit | 640 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-18 23:22
from __future__ import unicode_literals
from django.db import migrations
import enumfields.fields
import wallet.enums
import enum
class TrxType(enum.Enum):
FINALIZED = 0 |
PENDING = 1
CANCELLATION = 2
class Migration(migrations.Migration):
dependencies = [
('wallet', '000 | 9_remove_wallettransaction_trx_status'),
]
operations = [
migrations.AlterField(
model_name='wallettransaction',
name='trx_type',
field=enumfields.fields.EnumIntegerField(default=0, enum=TrxType),
),
]
|
yl565/statsmodels | statsmodels/tsa/statespace/tests/test_models.py | Python | bsd-3-clause | 6,374 | 0.000157 | """
Tests for miscellaneous models
Author: Chad Fulton
License: Simplified-BSD
"""
from __future__ import division, absolute_import, print_function
import numpy as np
import pandas as pd
import os
import re
import warnings
from statsmodels.tsa.statespace import mlemodel
from statsmodels import datasets
from numpy.te... | def test_predicted_states_cov(self):
assert_allclose(
self.results.det_predicted_state_cov. | T,
self.desired[['detP']]
)
def test_smoothed_states(self):
assert_allclose(
self.results.smoothed_state.T,
self.desired[['alphahat1', 'alphahat2', 'alphahat3']]
)
def test_smoothed_states_cov(self):
assert_allclose(
self.results.... |
GiorgioAresu/backuppc-pi-display | settings.py | Python | mit | 1,278 | 0.000782 | BACKUPPC_DIR = "/usr/share/backuppc"
TARGET_HOST = "192.168.1.65"
BACKUPPC_USER_UID = 110
BACKUPPC_USER_GID = 116
DEBUG = False
TRANSLATIONS = {
'Status_idle': 'inattivo',
'Status_backup_starting': 'avvio backup',
'Status_backup_in_progress': 'backup in esecuzione',
'Status_restore_starting': 'avvio ri... | nothing_to_do': 'nulla da fare',
'Reason_backup_failed': 'backup fallito',
'Reason_restore_failed': 'restore fallito',
'Reason_archive_failed': 'archivio fallito',
'Reason_no_ping': 'no ping',
'Reason_backup_canceled_by_user': 'backup annullato dall\'utente',
'Reason_restore_canceled_by_user': '... | ': 'archivio annullato dall\'utente',
'Disabled_OnlyManualBackups': 'auto disabilitato',
'Disabled_AllBackupsDisabled': 'disabilitato',
'full': 'completo',
'incr': 'incrementale',
'backupType_partial': 'parziale',
} |
pombredanne/lizard-progress | hdsr_controle/realtech_hdsr/data_loader.py | Python | gpl-3.0 | 11,413 | 0.013669 | '''
Created on Aug 1, 2012
@author: ouayed
'''
import logging,os
import hdsr_controle.realtech_hdsr.models as model
from django.contrib.gis.utils import LayerMapping,LayerMapError
from django.db import transaction,IntegrityError
from django.utils.datetime_safe import datetime
from hdsr_controle.realtech_hdsr import e... | le, model.realtech_hdsr_Hydrovakken_mapping, verbose, project, beginTime)
for shapefile in project.profielenShapes:
saveShapeFile(model.HdsrDWPProfielen, shapefile, model.realtech_hdsr_DWPProfielen_mapping, verbose, project, beginTime)
def exportHydrovakken(gebruikersdata):
for gebruik... | :
for shapefile in project.hydrovakkenShapes:
export.ShpResponder(queryset=model.hdsrHydrovakken.objects.filter(project=project.project), file_name= shapefile,geo_field=None, proj_transform=None)
def loadmetfiles(gebruikersdata):
for gebruiker in gebruikersdata:
for project in g... |
PaddlePaddle/Paddle | python/paddle/fluid/tests/book/test_recommender_system.py | Python | apache-2.0 | 12,089 | 0.000662 | # 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... | p[0])
break # test only 1 segment for speeding up CI
# get test avg_cost
test_avg_cost = np.array(avg_cost_set).mean()
if test_avg_cost < 6.0:
# if avg_cost less than 6.0, we think our code is good.
... | dirname, [
"user_id", "gender_id", "age_id", "job_id",
"movie_id", "category_id", "movie_title"
], [scale_infer], exe)
return
if math.isnan(float(out[0])):
sys.exit("g... |
dask/distributed | distributed/tests/test_asyncprocess.py | Python | bsd-3-clause | 11,851 | 0.000506 | import asyncio
import gc
import os
import signal
import sys
import threading
import weakref
from datetime import timedelta
from time import sleep
import psutil
import pytest
from tornado import gen
from tornado.locks import Event
from distributed.compatibility import WINDOWS
from distributed.metrics import time
from ... | xitcode == 5
@pytest.mark.skipif(WINDOWS, reason="POSIX only")
@gen_test()
async def test_signal():
proc = AsyncProcess(target=exit_with_signal, args=(signal.SIGINT,))
proc.daemon = True
assert not proc.is_alive()
assert proc.exitcode is None
await proc.start()
await proc.join(timeout=30)
... | ssert not proc.is_alive()
# Can be 255 with forkserver, see https://bugs.python.org/issue30589
assert proc.exitcode in (-signal.SIGINT, 255)
proc = AsyncProcess(target=wait)
await proc.start()
os.kill(proc.pid, signal.SIGTERM)
await proc.join(timeout=30)
assert not proc.is_alive()
asse... |
isabellewei/deephealth | data/network.py | Python | mit | 3,768 | 0.004777 | '''
A Multilayer Perceptron implementation example using TensorFlow library.
This example is using the MNIST database of handwritten digits
(http://yann.lecun.com/exdb/mnist/)
Author: Aymeric Damien
Project: https://github.com/aymericdamien/TensorFlow-Examples/
'''
from __future__ import print_function
import tensorf... | 1': tf.Variable(tf.random_normal([n_hidden_1])),
'b2': tf.Variable(tf.random_normal([n_hidden_2])),
'out': tf.Variable(tf.random_normal([n_classes]))
}
# Construct model
pred = multilayer_perceptron(x, weights, biases)
# Define loss and optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(l... |
with tf.Session() as sess:
sess.run(init)
# Training cycle
for epoch in range(training_epochs):
avg_cost = 0.
total_batch = int(csv_size/batch_size)
# Loop over all batches
for i in range(total_batch):
batch_x, batch_y = mnist.train.next_batch(batch_size)
... |
michaelconnor00/gbdxtools | tests/unit/test_idaho.py | Python | mit | 2,604 | 0.003072 | '''
Authors: Donnie Marino, Kostas Stamatiou
Contact: dmarino@digitalglobe.com
Unit tests for the gbdxtools.Idaho class
'''
from gbdxtools import Interface
from gbdxtools.idaho import Idaho
from auth_mock import get_mock_gbdx_session
import vcr
from os.path import join, isfile, dirname, realpath
import tempfile
impor... | 182839))"
results = i.get_images_by_catid_and_aoi(catid=catid, aoi_wkt=aoi_wkt)
assert len(results['results']) == 2
@vcr.use_cassette('tests/unit/cassettes/test_idaho_get_images_by_catid.yaml', filter_headers=['authorization'])
def test_idaho_get_images_by_catid(self):
i = Idaho(self.gb | dx)
catid = '10400100203F1300'
results = i.get_images_by_catid(catid=catid)
assert len(results['results']) == 12
@vcr.use_cassette('tests/unit/cassettes/test_idaho_describe_images.yaml', filter_headers=['authorization'])
def test_idaho_describe_images(self):
i = Idaho(self.gbdx)... |
dochang/ansible | lib/ansible/constants.py | Python | gpl-3.0 | 20,345 | 0.01332 | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) an... | None, ispath=True)
DEFAULT_ROLES_PATH = ge | t_config(p, DEFAULTS, 'roles_path', 'ANSIBLE_ROLES_PATH', '/etc/ansible/roles', ispath=True)
DEFAULT_REMOTE_TMP = get_config(p, DEFAULTS, 'remote_tmp', 'ANSIBLE_REMOTE_TEMP', '$HOME/.ansible/tmp')
DEFAULT_MODULE_NAME = get_config(p, DEFAULTS, 'module_name', None, ... |
sirk390/coinpy | coinpy-lib/src/coinpy/lib/transactions/tx_checks.py | Python | lgpl-3.0 | 2,364 | 0.004653 | from | coinpy.lib.serialization.structures.s11n_tx import TxSerializer
from coinpy.model.constants.bitcoin import MAX_BLOCK_SIZE, is_money_range
from coinpy.lib.serialization.scripts.serialize import ScriptSerializer
class TxVerifier():
def __init__(self, runmode):
self.runmode = runmode
self.tx_seriali... | context.
"""
def basic_checks(self, tx):
self.check_size_limit(tx)
self.check_vin_empty(tx)
self.check_vout_empty(tx)
self.check_money_range(tx)
self.check_dupplicate_inputs(tx)
self.check_coinbase_script_size(tx)
self.check_null_inputs(tx)
def c... |
zloidemon/aiohttp_jrpc | aiohttp_jrpc/__init__.py | Python | bsd-2-clause | 6,064 | 0 | """ Simple JSON-RPC 2.0 protocol for aiohttp"""
from .exc import (ParseError, InvalidRequest, InvalidParams,
InternalError, InvalidResponse)
from .errors import JError, JResponse
from validictory import validate, ValidationError, SchemaError
from functools import wraps
from uuid import uuid4
from aio... | except ValidationError:
# Passing data to validate response.
# Good if does not valid to ERR_JSONRPC20 object.
pass
except Exception as err:
raise InvalidResponse(err)
try:
validate(data, RSP_JSONRPC20)
| if id != data['id']:
raise InvalidResponse(
"Rsponse id {local} not equal {remote}".format(
local=id, remote=data['id']))
except Exception as err:
raise InvalidResponse(err)
if schem:
try:
v... |
wizgrav/protobot | server.py | Python | bsd-3-clause | 861 | 0.020906 | import SocketServer
class ProtoHandler(SocketServer.BaseRequestHandler):
def handle(self):
msg = self.request.recv(1024)
a = msg.split(" ",2)
if len(a) >1 and a[0] == "GET":
a = a[1].split("/")
a =[i for i in a if i != '']
if len(a) == 0:
... | llow_reuse_address = True
SocketServer.TCPServer.__init__(self,hostport, ProtoHandler)
with open (default, "r") as myfile:
self.ret=myfile.read()
if __name__ == "__main__":
s = ProtoServer(("192.168. | 1.253", 6661),"index.html")
s.serve_forever()
|
manassolanki/frappe | frappe/database.py | Python | mit | 30,790 | 0.02897 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
# Database Module
# --------------------
from __future__ import unicode_literals
import warnings
import datetime
import frappe
import frappe.defaults
import frappe.async
import re
import frappe.model.meta
from frappe.u... |
"""
Open a database connection with the given parmeters, if use_default is True, use the
login details from `conf.py`. This is called by the request handler and is accessible using
the `db` global variable. the `sql` method is also global to run queries
"""
def __init__(self, host=None, user=None, passw... | lt = 0, local_infile = 0):
self.host = host or frappe.conf.db_host or 'localhost'
self.user = user or frappe.conf.db_name
self._conn = None
if ac_name:
self.user = self.get_db_login(ac_name) or frappe.conf.db_name
if use_default:
self.user = frappe.conf.db_name
self.transaction_writes = 0
self.au... |
wojtask/CormenPy | test/queue_util.py | Python | gpl-3.0 | 279 | 0.003584 | def get_stack_elements(stack):
return stack[1:stack.top].elements
def get_queue | _elements(queue):
if queue.head <= queue.tail:
retu | rn queue[queue.head:queue.tail - 1].elements
return queue[queue.head:queue.length].elements + queue[1:queue.tail - 1].elements
|
marios-zindilis/musicbrainz-django-models | musicbrainz_django_models/models/editor_subscribe_label_deleted.py | Python | gpl-2.0 | 1,251 | 0.000799 | """
.. module:: editor_subscribe_label_deleted
The **Editor Subscribe Label Deleted** Model.
PostgreSQL Definition
---------------------
The :code:`editor_subscribe_label_deleted` table is defined in the MusicBrainz Server as:
.. code-block:: sql
CREATE TABLE editor_subscribe_label_deleted
(
editor... | :class:`.edit`
"""
editor = models.OneToOneField('editor', primary_key=True)
gid = models.OneToOneField('deleted_entity')
deleted_by = models.ForeignKey('edit')
def __str__(self):
return 'Editor Subscribe Label Deleted'
class Meta:
db_table | = 'editor_subscribe_label_deleted'
|
programmdesign/blitzdb | setup.py | Python | mit | 3,033 | 0.008243 | from distutils.core import setup
from setuptools import find_packages
setup(name='blitzdb',
version='0.2.12',
author='Andreas Dewes - 7scientists',
author_email='andreas@7scientists.com',
license='MIT',
entry_points={
},
url='https://github.com/adewes/blitzdb',
packages=find_packages(),
zip_safe=False,
description... | fix-Release: Fix serialization problem with file backend.
* 0.2.8: Added `get`, `has_key` and `clear` methods to `Document` class
* 0.2.7: Fixed problem with __unicode__ function in Python 3.
* 0.2.6: Bugfix-Relea | se: Fixed an issue with the $exists operator for the file backend.
* 0.2.5: Bugfix-Release
* 0.2.4: Added support for projections and update operations to the MongoDB backend.
* 0.2.3: Bugfix-Release: Fixed bug in transaction data caching in MongoDB backend.
* 0.2.2: Fix for slice operators in MongoDB backend.
* 0.2.1:... |
JazzeYoung/VeryDeepAutoEncoder | pylearn2/pylearn2/expr/information_theory.py | Python | bsd-3-clause | 1,193 | 0 | """
.. todo::
WRITEME
"""
import theano.tensor as T
from | theano.gof.op import get_debug_values
from theano.gof.op import debug_assert
import numpy as np
from theano.tensor.xlogx import xl | ogx
from pylearn2.utils import contains_nan, isfinite
def entropy_binary_vector(P):
"""
.. todo::
WRITEME properly
If P[i,j] represents the probability of some binary random variable X[i,j]
being 1, then rval[i] gives the entropy of the random vector X[i,:]
"""
for Pv in get_debug_v... |
scm-spain/slippin-jimmy | src/slippinj/databases/drivers/oracle.py | Python | apache-2.0 | 7,437 | 0.004303 | import re
import unicodedata
from injector import inject, AssistedBuilder
import cx_Oracle as pyoracle
class Oracle(object):
"""Wrapper to connect to Oracle Servers and get all the metastore information"""
@inject(oracle=AssistedBuilder(callable=pyoracle.connect), logger='logger')
def __init__(self, orac... | b_schema = "= '{schema}'".format(schema=self.__db_schema)
query = "SELECT DISTINCT | table_name " \
"FROM all_tables WHERE OWNER " \
"{owner} {table_list_query}".format(owner=query_with_db_schema if self.__db_schema else "NOT LIKE '%SYS%' AND OWNER NOT LIKE 'APEX%'AND OWNER NOT LIKE 'XDB'" ,table_list_query=' AND ' + table_list_query if table_list_query else '')
... |
dickloraine/EmbedComicMetadata | comicbookinfo.py | Python | gpl-3.0 | 4,500 | 0.001778 | """
A python class to encapsulate the ComicBookInfo data
"""
"""
Copyright 2012-2014 Anthony Beville
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... | _container = json.loads(string)
except:
return False
return ('ComicBookInfo/1.0' in cbi_container)
def createJSONDictionary(self, metadata):
# Create the dictionary that we will convert to JSON text
cbi = dict()
cbi_container = {'appID': 'ComicTagger/',
... | ied': str(datetime.now()),
'ComicBookInfo/1.0': cbi}
# helper func
def assign(cbi_entry, md_entry):
if md_entry is not None:
cbi[cbi_entry] = md_entry
# helper func
def toInt(s):
i = None
if type(s) in [str, u... |
illfelder/libcloud | libcloud/compute/drivers/ec2.py | Python | apache-2.0 | 256,785 | 0.000008 | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... | }
},
'm3.medium': {
'id': 'm3.medium',
'name': 'Medium Instance', |
'ram': GiB(3.75),
'disk': 4, # GB
'bandwidth': None,
'extra': {
'cpu': 1
}
},
'm3.large': {
'id': 'm3.large',
'name': 'Large Instance',
'ram': GiB(7.5),
'disk': 32, # GB
'bandwidth': None,
'extra': {
... |
dudanogueira/microerp | microerp/comercial/migrations/0062_dadovariavel_tipo.py | Python | lgpl-3.0 | 549 | 0.001821 | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-02-09 22:21
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations | .Migration):
dependencies = [
('comercial', '0061_auto_20160206_2052'),
]
operations = [
migrations.Ad | dField(
model_name='dadovariavel',
name='tipo',
field=models.CharField(blank=True, choices=[(b'texto', b'Texto'), (b'inteiro', b'Inteiro'), (b'decimal', b'Decimal')], max_length=100),
),
]
|
pombredanne/drf-toolbox | tests/test_serializers.py | Python | bsd-3-clause | 23,089 | 0.00078 | from __future__ import absolute_import, unicode_literals
from collections import namedtuple
from django.core.exceptions import ValidationError, ObjectDoesNotExist
from django.db.models.fields import FieldDoesNotExist
from django.test.client import RequestFactory
from drf_toolbox.compat import django_pgfields_installed,... | 'api_endpoints', s.opts.fields)
self.assertNotIn('api_endpoint', s.opts.fields)
def test_direct_relationship(self):
"""Test that a direct relationship retrieval works
as expected.
"""
# Get the related field from a direct relationship.
s = test_serializers.ChildSeria... | d_field(
model_field=test_models.ChildModel._meta.\
get_field_by_name('normal')[0],
related_model=test_models.NormalModel,
to_many=False,
)
self.assertIsInstance(rel_field, RelatedField)
# Verify the label.
self.assertEqual(
... |
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractChuunihimeWordpressCom.py | Python | bsd-3-clause | 560 | 0.033929 |
def extractChuunihimeWordpressCom(item):
'''
Parser for 'chuunihime.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPos | tfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
| return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False
|
joeydong/endless-lake-player | player.py | Python | mit | 4,891 | 0.002045 | import functools
import itertools
import json
import multiprocessing
import os
import shutil
import sys
import time
import cv2
import numpy
import utility.config
import utility.cv
import utility.geometry
import utility.gui
import utility.image
import utility.log
# Explicitly disable OpenCL. Querying for OpenCL suppo... | utility.log.info("double click")
utility.gui.mouse_double_click()
break
elif action["action"] == "single" and action["distance"] <= utility.config.single_jump_action_distance:
# Single jump
utility.log.info("single click")
utility.gui.mouse_c... | ts
composite_image = utility.image.highlight_regions(screenshot, matches)
utility.log.performance("highlight_regions", start)
# Present composite image
# utility.image.show(composite_image)
# utility.log.performance("show", start)
# Log trace
utility.log.trace(trace_directory, screenshot_o... |
ep1cman/workload-automation | wlauto/instrumentation/energy_model/__init__.py | Python | apache-2.0 | 42,085 | 0.00354 | # Copyright 2015 ARM Limited
#
# 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 writin... | all_idle_power[first_cluster_idle_state - 1])
# CLUSTER idle states
# We want the absolute value of each idle state
idle_cluster_power = low_filter(all_idle_power[first_cluster_idle_state - 1:])
em.add_cluster_idle(cluster, idle_cluster_power)
em.add... | g_core, little_core, em_template_file, outfile):
with open(em_template_file) as fh:
em_template = jinja2.Template(fh.read())
em_text = em_template.render(
big_core=big_core,
little_core=little_core,
em=em,
)
with open(outfile, 'w') as wfh:
wfh.write(em_text)
r... |
cgwalters/imagefactory | imagefactory_plugins/Rackspace/__init__.py | Python | apache-2.0 | 667 | 0 | # encoding: | utf-8
# Copyright 2012 Red Hat, 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
#
# Un | less required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
... |
cederstrom/natet-sos-generator | generator/integration/dryg.py | Python | mit | 327 | 0.003058 | import requests
class DrygDAO:
def __init__(self):
pass
def get_days_for_year(self, year):
response = requests.get("http://api.dryg.net/dagar/v2.1/%s" % year)
data = response.json()
workdays = [x["datum" | ] for x in data["dagar"] i | f x["arbetsfri dag"] == "Nej"]
return workdays
|
ethankennerly/hotel-vs-gozilla | user/h4.news.py | Python | mit | 126 | 0.007937 | { | 'level_mc': {'_txt': {'text': '6'},
'currentLabel': 'up',
'progress_mc': {'currentLabel': '_0'} | }} |
jpedroan/megua | megua/csection.py | Python | gpl-3.0 | 10,442 | 0.009289 | # coding=utf8
r"""
csection.py -- Create a tree of contents, organized by sections and inside
sections the exercises unique_name.
AUTHOR:
- Pedro Cruz (2012-01): initial version
- Pedro Cruz (2016-03): improvment for smc
An exercise could contain um its %summary tag line a description of section
in form:... | $, for $C in \mathbb{R}$.
....:
....: class E28E28_pimtrig_002(ExerciseBase):
....: pass
....: '''
sage: meg.save(txt)
-------------------------------
Instance of: E28E28_pimtrig_002
-------------------------------
==> Summary:
Here, is a summar... | r instance
The answer is $prim+C$, for $C in \mathbb{R}$.
sage: txt=r'''
....: %Summary Primitives; Imediate primitives; Polynomial
....:
....: Here, is a summary.
....:
....: %Problem Some Problem 1
....: What is the primitive of $a x + b@()$ ?
.... |
opencord/xos | xos/core/migrations/0012_backupoperation_decl_uuid.py | Python | apache-2.0 | 1,124 | 0.00089 | # Copyright 2017-present Open Networking Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | ('core', '0011_auto_20190430_1254'),
]
operations = [
migrations.AddField(
model_name='backupoperation_decl',
name='uuid',
field=models.CharField(blank=True, help_text=b'unique identifer of this request', ma | x_length=80, null=True),
),
]
|
klim-iv/phantomjs-qt5 | src/webkit/Tools/efl/common.py | Python | bsd-3-clause | 1,100 | 0.000909 | #!/usr/bin/env python
# Copyright (C) 2011 Igalia S.L.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2 of the Lice | nse, or (at your option) any later version.
#
# This libr | ary 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License alo... |
alexgarciac/scrapi | tasks.py | Python | apache-2.0 | 6,604 | 0.002574 | import base64
import logging
import platform
from datetime import date, timedelta
from invoke import run, task
from elasticsearch import helpers
from dateutil.parser import parse
from six.moves.urllib import parse as urllib_parse
import scrapi.harvesters # noqa
from scrapi import linter
from scrapi import registry
f... | (start).date() if | start else end - timedelta(settings.DAYS_BACK)
run_harvester.delay(harvester_name, start_date=start, end_date=end)
@task
def harvesters(async=False, start=None, end=None):
settings.CELERY_ALWAYS_EAGER = not async
from scrapi.tasks import run_harvester
start = parse(start).date() if start else date.... |
audiohacked/pyBusPirate | tests/test_buspirate_onewire.py | Python | gpl-2.0 | 3,002 | 0.000333 | # Created by Sean Nelson on 2018-08-19.
# Copyright 2018 Sean Nelson <audiohacked@gmail.com>
#
# This file is part of pyBusPirate.
#
# pyBusPirate 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... | write.assert_called_with(0 | x00)
def test_mode(self):
self.bus_pirate.serial.read.return_value = "1W01"
self.assertEqual(self.bus_pirate.mode, "1W01")
self.bus_pirate.serial.write.assert_called_with(0x01)
def test_enter(self):
self.bus_pirate.serial.read.return_value = "1W01"
self.assertEqual(self... |
amitu/gitology | src/gitology/d/templatetags/clevercsstag.py | Python | bsd-3-clause | 480 | 0.008333 | from django import template
import cle | vercss
register = template.Library()
@register.tag(name="clevercss")
def do_clevercss(parser, token):
nodelist = parser.parse(('endclevercss',))
parser.delete_first_token()
return CleverCSSNode(nodelist)
class CleverCSSNode(template.Node):
def __init__(self, nodelist):
self.nodelist = nodelis... | elf.nodelist.render(context)
return clevercss.convert(output)
|
lesavoie/nagiosservice | controlserver/servicelevelinterface/serializers.py | Python | gpl-2.0 | 816 | 0.015931 | from django.contrib.auth.models import User
from rest_framework import serializers
from servicelevelinterface.models import Monitor, Contact, Command
class MonitorSerializer(serializers.ModelSerializer):
owner = serializers.CharField(source='ow | ner.username', read_only=True)
class Meta:
model = Monitor
class ContactSerializer(serializers.ModelSerializer):
owner = serializers.CharField(source='owner.username', read_only=True)
class Meta:
model = Contact
class CommandSerializer(serializers.ModelSerializer):
class Meta:
model ... | a subset of the
# fields.
class CreateUserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('username', 'password', 'email')
|
none-da/zeshare | debug_toolbar/panels/logger.py | Python | bsd-3-clause | 2,377 | 0.002945 | import datetime
import logging
try:
import threading
except ImportError:
threading = None
from django.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _
from debug_toolbar.panels import DebugPanel
class ThreadTrackingHandler(logging.Handler):
def __init__(self):... | ds()
return records
def nav_title(self):
return _("Logging")
def nav_subtitle(self):
return "%s message%s" % (len(handler.get_records()), (len(handler.get_records()) == 1) and '' or 's')
def title(self):
return 'Log Messages'
def url(self):
return '' |
def content(self):
records = []
for record in self.get_and_delete():
records.append({
'message': record.getMessage(),
'time': datetime.datetime.fromtimestamp(record.created),
'level': record.levelname,
'file': record.pathn... |
informatics-isi-edu/webauthn | webauthn2/scripts/globus_oauth_client.py | Python | apache-2.0 | 1,011 | 0.004946 | import globus_sdk
CLIENT_ID = 'f7cfb4d6-8f20-4983-a9c0-be3f0e2681fd'
client = globus_sdk.Nati | veAppAuthClient(CLIENT_ID)
#client.oauth2_start_flow(requested_scopes="https://auth.globus.org/scopes/0fb084ec-401d-41f4-990e-e236f325010a/deriva_all")
client.oauth2_start_flow(requested_scopes="https://auth.globus.org/scopes/nih-commo | ns.derivacloud.org/deriva_all")
authorize_url = client.oauth2_get_authorize_url(additional_params={"access_type" : "offline"})
print('Please go to this URL and login: {0}'.format(authorize_url))
# this is to work on Python2 and Python3 -- you can just use raw_input() or
# input() for your specific version
get_input ... |
dominjune/LeetCode | 074 Search a 2D Matrix.py | Python | mit | 1,679 | 0.011316 | """
Write an efficient algorithm that searches for a | value in an m x n matrix. This matrix has the follow | ing properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
For example,
Consider the following matrix:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Given target = 3, return true.
"""
__author... |
openstax/openstax-cms | openstax/api.py | Python | agpl-3.0 | 2,453 | 0.003675 | from django.core.exceptions import MultipleObjectsReturned
from django.shortcuts import redirect
from django.urls import reverse, path
from wagtail.api.v2.router import WagtailAPIRouter
from wagtail.api.v2.views import PagesAPIViewSet, BaseAPIViewSet
from wagtail.images.api.v2.views import ImagesAPIViewSet
from wagtai... | BaseAPIViewSet.nested_default_fields + ['title', 'download_url', 'hei | ght', 'width']
# Create the router. “wagtailapi” is the URL namespace
api_router = WagtailAPIRouter('wagtailapi')
# Add the three endpoints using the "register_endpoint" method.
# The first parameter is the name of the endpoint (eg. pages, images). This
# is used in the URL of the endpoint
# The second parameter is t... |
OCA/connector-telephony | sms_no_automatic_delete/__manifest__.py | Python | agpl-3.0 | 543 | 0 | # Copyright 2021 Akretion (http://www.akretion.com).
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "No automatic deletion of SMS",
"summary": "Avoid automatic delete of sended sms",
"author": "Akretion,Odoo Community Association (OCA)",
"website": "https://github.com/OCA/conn... | on_data.xml",
| ],
"application": False,
"installable": True,
}
|
appleseedhq/cortex | test/IECore/ops/presetParsing/presetParsing-1.py | Python | bsd-3-clause | 3,526 | 0.047646 | ##########################################################################
#
# Copyright (c) 2007-2010, Image Engine Design 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:
#
# * Redis... | e.V2dData( imath.V2d( 0 ) ),
),
IECore.CompoundParameter(
name = "compound",
description = "a compound parameter",
members = [
IECore.V3dParameter(
name = "j",
description = "a v3d",
defaultValue = IECore.V3dData(),
presets = (
( "one", imath.V3d( 1 )... | ata(),
presets = (
( "one", imath.M44f( 1 ) ),
( "two", imath.M44f( 2 ) )
)
),
]
)
]
)
def doOperation( self, operands ) :
assert operands["h"] == IECore.V3fData( imath.V3f( 1, 0, 0 ) )
assert operands["i"] == IECore.V2dData( imath.V2d( 0 ) )
compoundPrese... |
intel-analytics/analytics-zoo | pyzoo/test/zoo/chronos/detector/anomaly/test_ae_detector.py | Python | apache-2.0 | 2,541 | 0 | #
# Copyright 2018 Analytics Zoo Authors.
#
# 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... | sert len(anomaly_indexes) == int(ad.ratio * len(y))
def test_ae_fit_score_unrolled(self):
y = self.create_data()
ad = AEDetector(roll_len=0)
ad.fit(y)
anomaly_scores = ad.score()
assert len(anomaly_scores) == len(y)
anomaly_indexes = ad.anomaly_indexes()
asse... |
ad = AEDetector(roll_len=314, backend="dummy")
with pytest.raises(ValueError):
ad.fit(y)
ad = AEDetector(roll_len=314)
with pytest.raises(RuntimeError):
ad.score()
y = np.array([1])
with pytest.raises(ValueError):
ad.fit(y)
y =... |
vidartf/hyperspy | hyperspy/io_plugins/__init__.py | Python | gpl-3.0 | 2,279 | 0.000439 | # -*- coding: utf-8 -*-
# Copyright 2007-2016 The HyperSpy developers
#
# This file is part of HyperSpy.
#
# HyperSpy 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... |
try:
from hyperspy.io_plugins import netcdf
io_plugins.append(netcdf)
except ImportError:
pass
# NetCDF is obsolate and is only provided for users who have
# old EELSLab files. Therefore, we silenly ignore if missing.
try:
from hype | rspy.io_plugins import hdf5
io_plugins.append(hdf5)
from hyperspy.io_plugins import emd
io_plugins.append(emd)
except ImportError:
_logger.warning('The HDF5 IO features are not available. '
'It is highly reccomended to install h5py')
try:
from hyperspy.io_plugins import image
... |
aweisberg/cassandra-dtest | thrift_bindings/thrift010/Cassandra.py | Python | apache-2.0 | 403,615 | 0.002118 | #
# Autogenerated by Thrift Compiler (0.10.0)
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
# options string: py
#
from thrift.Thrift import TType, TMessageType, TFrozenDict, TException, TApplicationException
from thrift.protocol.TProtocol import TProtocolException
import sys
import logging
f... | l. The first one, serial_consistency_level, simply indicates the
level of serialization required. This can be either ConsistencyLevel.SERIAL or ConsistencyLevel.LOCAL_SERIAL.
The second one, commit_consistency_level, defines the consistency level for the commit phase of the cas. This
is a more t... | e CL than for traditional writes are accepted) that impact
the visibility for reads of the operation. For instance, if commit_consistency_level is QUORUM, then it is
guaranteed that a followup QUORUM read will see the cas write (if that one was successful obviously). If
commit_consistency_level ... |
mattduan/proof | adapter/NoneAdapter.py | Python | bsd-3-clause | 653 | 0.009188 | """
This DatabaseHandler is used when you do not have a database installed.
"""
import proof.ProofConstants as ProofConstants
import proof.adapter.Adapter as Adapter
class NoneAdapter(Adapter.Adapter):
def __init__(self):
pass
def getResourceType(self):
return ProofConstants.NONE
def ge... | ef ignoreCase(self, s):
return self.toUpperCase(s)
def getIDMethodSQL(self, obj):
return None
def lockTable(self, con | , table):
pass
def unlockTable(self, con, table):
pass
|
ModestoCabrera/is210-week-12-synthesizing | task_02.py | Python | mpl-2.0 | 616 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Contains Custom | Exception Class"""
class CustomError(Exception):
"""
Attributes:
None
"""
def __init__(self, message, cause):
"""Custom Error that stores error reason.
Args:
cause (str): Reason for error.
message (str): User input.
Returns:
None
... | "
self.cause = cause
self.message = message
Exception.__init__(self)
|
aronsky/home-assistant | homeassistant/components/pioneer/__init__.py | Python | apache-2.0 | 29 | 0 | """Th | e pioneer component."""
| |
demorest/mark5access | python/examples/m5subband.py | Python | gpl-3.0 | 8,051 | 0.033288 | #!/usr/bin/python
"""
m5subband.py ver. 1.1 Jan Wagner 20150603
Extracts a narrow subband via filtering raw VLBI data.
Reads formats supported by the mark5access library.
Usage : m5subband.py <infile> <dataformat> <outfile>
<if_nr> <factor> <Ldft>
<start_bin> <stop_bi... | pening or decoding %s\n' % (fn))
return 1
# Safety checks
if (if_nr<0) or (if_nr>=dms.nchan) or (factor<0) or (factor>32) or (Ldft<2) or (start_bin>stop_bin) or (stop_bin>=Ldft):
print ('Error: invalid command line arguments')
return 1
if (Ldft % factor)>0:
print ('Error: length of DFT (Ldft=%u) must be div... | ut=%u) does not divide the overlap-add factor (factor=%u)' % (Lout,factor))
return 1
# Get storage for raw sample data from m5lib.mark5_stream_decode()
pdata = m5lib.helpers.make_decoder_array(ms, nin, dtype=ctypes.c_float)
if_data = ctypes.cast(pdata[if_nr], ctypes.POINTER(ctypes.c_float*nin))
# Numpy 2D array... |
googleads/google-ads-python | google/ads/googleads/v9/services/services/bidding_seasonality_adjustment_service/transports/grpc.py | Python | apache-2.0 | 12,389 | 0.001291 | # -*- 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... | OPES)
| # create a new channel. The provided one is ignored.
self._grpc_channel = type(self).create_channel(
host,
credentials=credentials,
ssl_credentials=ssl_channel_credentials,
scopes=self.AUTH_SCOPES,
options=[
... |
Zashas/segway | structs.py | Python | gpl-3.0 | 5,933 | 0.008933 | #coding: utf-8
from scapy.all import *
class WILDCARD:
""" Used to indicate that some fields in a scapy packet should be ignored when comparing """
pass
class NO_PKT:
""" Indicate that a sent packet should have no reply """
pass
def pkt_match(expected, actual):
""" Check if all fields described i... | gTLVIngressNode): |
tlvs.append('{{Ingr: {}}}'.format(tlv.ingress_node))
elif isinstance(tlv,IPv6ExtHdrSegmentRoutingTLVEgressNode):
tlvs.append('{{Egr: {}}}'.format(tlv.egress_node))
elif isinstance(tlv,IPv6ExtHdrSegmentRoutingTLVOpaque):
tlvs.append('{{Opaq: {}}}'.... |
Gustry/inasafe | safe/metadata/property/boolean_property.py | Python | gpl-3.0 | 1,696 | 0 | # -*- coding: utf-8 -*-
"""
InaSAFE Disaster risk assessment tool developed by AusAid -
**metadata module.**
Contact : ole.moller.nielsen@gmail.com
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Sof... | wed_python_types)
@classmethod
def is_valid(cls, value):
return True
def cast_from_str(self, value):
try:
return bool( | int(value))
except ValueError as e:
raise MetadataCastError(e)
@property
def xml_value(self):
if self.python_type is bool:
return str(int(self.value))
elif self.python_type is NoneType:
return ''
else:
raise RuntimeError('self._all... |
guschmue/tensorflow | tensorflow/contrib/framework/python/ops/variables.py | Python | apache-2.0 | 29,690 | 0.005322 | # Copyright 2015 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... | types
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import gen_state_ops
from tensorflow.python.platform | import tf_logging as logging
from tensorflow.python.platform import resource_loader
from tensorflow.python.training import saver as tf_saver
from tensorflow.python.training import training_util
from tensorflow.python.util.deprecation import deprecated
__all__ = ['add_model_variable',
'assert_global_step',... |
pipcat/kobo | translation-tools/qm2ts.py | Python | gpl-3.0 | 3,181 | 0.033008 | #!/usr/bin/python2
# -- coding: utf-8 --
# Converts a .qm file to a .ts file.
# More info: http://www.mobileread.com/forums/showthread.php?t=261771
# By pipcat & surquizu. Thanks to: tshering, axaRu, davidfor, mobileread.com
import codecs, cgi
def clean_text(txt, is_utf) :
if is_utf == False:
txt = txt.decode('u... | :
l1 = (ord(data[pos+3]) * 256) + ord(data[pos+4])
t1 = data[pos+5:pos+5+l1]
t1b = ''
t1c = ''
if data[pos+5+l1:pos+5+l1 | +3] == '\x03\x00\x00': #optional, when exists singular/plural
l1b = (ord(data[pos+5+l1+3]) * 256) + ord(data[pos+5+l1+4])
t1b = data[pos+5+l1+5:pos+5+l1+5+l1b]
pos = pos+l1b+5
if data[pos+5+l1:pos+5+l1+3] == '\x03\x00\x00': #optional, when exists singular/undecal/plural
l1c = (ord(data[pos+5+l1+3]) ... |
SirEdvin/Pandas-Pipe | pandaspipe/pipeline.py | Python | apache-2.0 | 10,315 | 0.002714 | # -*- coding:utf-8 -*-
import abc
import sys
import inspect
import types
import itertools
import networkx as nx
from pandaspipe.util import patch_list, isSubset
from pandaspipe.base import PipelineEntity
import logging
_log = logging.getLogger(__name__)
_log.addHandler(logging.StreamHandler(stream=sys.stdout))
class... | nnels, outchannel)
| elif obj.type == 'source':
obj.input_channels = []
patch_list(obj.output_channels, outchannel)
elif obj.type == 'outlet':
patch_list(obj.input_channels, channel)
obj.output_channels = []
else:
raise Exception('Well,... |
zlsun/ProjectEuler | 091.py | Python | mit | 484 | 0.008421 | #-*- encoding: utf-8 -*-
"""
Right triangles with integer coordinates
The points P (x1, y1) and Q (x2, y2) a | re plotted at integer co-ordinates and are joined to the origin, O(0,0), to form ΔOPQ.
There are exactly fourteen triangles containing a right angle that can be formed when each co-ordinate l | ies between 0 and 2 inclusive; that is,0 ≤ x1, y1, x2, y2 ≤ 2.
Given that 0 ≤ x1, y1, x2, y2 ≤ 50, how many right triangles can be formed?
"""
from utils import *
#
|
d-plaindoux/fluent-rest | tests/verb_test.py | Python | lgpl-2.1 | 1,943 | 0 | # Copyright (C)2016 D. Plaindoux.
#
# This program | is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2, or (at your option) any
# later version.
import unittest
from fluent_rest.spec.rest import *
from fluent_rest.exceptions import Overloa... |
@GET
def test():
pass
self.assertTrue(specification(test).hasGivenVerb(u'GET'))
def test_should_have_PUT(self):
@PUT
def test():
pass
self.assertTrue(specification(test).hasGivenVerb(u'PUT'))
def test_should_have_POST(self):
@P... |
skoolkid/skoolkit | skoolkit/skoolctl.py | Python | gpl-3.0 | 29,525 | 0.001897 | # Copyright 2010-2021 Richard Dymond (rjdymond@gmail.com)
#
# This file is part of SkoolKit.
#
# SkoolKit 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) an... | tems = self.op_evaluator.split_operands(operation[5:])
if self.preserve_base:
byte_fmt = FORMAT_PRESERVE_BASE
full_length = 0
lengths = []
length = 0
prev_base = N | one
for item in items + ['""']:
c_data = self._parse_string(item)
if c_data is not None:
if length:
lengths.append(byte_fmt[prev_base].format(length))
full_length += length
prev_base = None
length... |
chop-dbhi/django-dicom-review | dicom_review/prioritizers.py | Python | bsd-2-clause | 1,748 | 0.014302 | from django.db.models import Count
from django.conf import settings
from solo.models import SingletonModel
import loader
MAX_REVIEWERS = settings.MAX_REVIEWERS
# Simple algorithm that checks to see the number of years the studies span and
# returns one study per year
def one_per_year(candidate_studies, user, annotatio... | diologystudyreview"))\
.filter(study_date__year=period.year, num_reviews__lt=MAX_REVIEWERS)\
.exclude(radiologystudyreview__user_id=user.id).order_by("?")[:1]
for study in this_year:
studies.append(study)
return studies
# Whether the list method is the global default or set on... | see if there is a global list object setup, if so use that one
# Otherwise just pull from the candidate_studies
def lists(candidate_studies, user, annotation_class = None):
from models import Config
study_list = (hasattr(user, 'study_list') and user.study_list) or Config.get_solo().default_study_list
# if... |
TheTimmy/spack | var/spack/repos/builtin/packages/quinoa/package.py | Python | lgpl-2.1 | 2,175 | 0.00092 | ##############################################################################
# Copyright (c) 2017, Los Alamos National Security, LLC
# Produced at the Los Alamos National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, ... | )
depends_on("netlib-lapack+lapacke")
depends_on("mad-numdiff")
depend | s_on("h5part")
depends_on("boostmplcartesianproduct")
depends_on("tut")
depends_on("pugixml")
depends_on("pstreams")
depends_on("pegtl")
root_cmakelists_dir = 'src'
|
ekesken/istatistikciadamlazim | allauth/socialaccount/helpers.py | Python | gpl-3.0 | 7,010 | 0.00271 | from django.conf import settings
from django.contrib import messages
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.contrib.auth i... | t_field('first_name').max_length])
u.set_unusable_password()
u.is_active = not account_settings.EMAIL_VERIFI | CATION
u.save()
accountbase = SocialAccount()
accountbase.user = u
accountbase.save()
account.base = accountbase
account.sync(data)
send_email_confirmation(u, request=request)
ret = complete_social_signup(request, u, account)
return ret
def ... |
xlcteam/py-soccersim | soccersim/env.py | Python | apache-2.0 | 1,133 | 0 | import pygame
import sys
import os
class Env:
def __init__(self, teamA, teamB, field_size, display, robots=None,
debug=False):
self.teamA = teamA
self.teamB = teamB
self.width = field_size[0]
self.height = field_size[1]
self.display = display
self.b... | ': [False, False]}
self.debug | = debug
self.dir = os.path.dirname(os.path.realpath(__file__)) + os.sep
self.field = pygame.image.load(self.dir + 'img/field.png')
self.halftime = 1
self.teamAscore = 0
self.teamBscore = 0
def teamA_add_goal(self):
self.teamAscore += 1
def teamB_add_goal(self... |
dsweet04/rekall | rekall-gui/manuskript/plugin.py | Python | gpl-2.0 | 836 | 0 | import StringIO
class Plugin(object):
ANGULAR_MODULE = None
JS_FILES = []
CSS_FILES = []
@classmethod
def PlugIntoApp(cls, app):
pass
@classmethod
def GenerateHTML(cls, root_url="/"):
out = StringIO.StringIO()
for js_file in cls.JS_FILES:
js_file = js... | js_file))
for css_file in cls.CSS_FILES:
css_file = css_file.lstrip("/")
out.write('<link rel="stylesheet" href="%s%s"></link>\n' % (
root_url, css_file))
if cls.ANGULAR_MODULE:
out.write("""
<script>var manuskriptPluginsList = manuskriptPluginsList ... | R_MODULE)
return out.getvalue()
|
DigitalSkills-fr/Docs | docs/conf.py | Python | apache-2.0 | 8,474 | 0.006136 | # -*- coding: utf-8 -*-
#
# Read the Docs Template documentation build configuration file, created by
# sphinx-quickstart on Tue Aug 26 14:19:49 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenera... | dd any Sphinx extension | module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = []
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
## Add parser for Makdown
source_parsers = {
'.md': CommonMarkParser,
}... |
steffenschroeder/tarnow | tests/conftest.py | Python | mit | 290 | 0 | import pytest
import os
@pytest.fixture(autouse=True)
def change_tempory_direc | tory(tmpdir):
tmpdir.chdir()
yield
if os.path.exists("tarnow.tmp"):
os.r | emove("tarnow.tmp")
@pytest.fixture(autouse=True)
def patch_subprocess(mocker):
mocker.patch("subprocess.call")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.