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 |
|---|---|---|---|---|---|---|---|---|
looker/sentry | src/sentry/lang/native/systemsymbols.py | Python | bsd-3-clause | 1,526 | 0.000655 | from __future__ import absolute_import
import logging
from requests.exceptions import RequestException
from sentry import options
from sentry.http import Session
from sentry.lang.native.utils import sdk_info_to_sdk_id
MAX_ATTEMPTS = 3
logger = logging.getLogger(__name__)
def lookup_system_symbols(symbols, sdk_in... | r the server is disabled, `None` is
returned.
"""
if not options.get('symbolserver.enabled'):
return
url = '%s/lookup' % options.get('symbolserver.options')['url'].rstrip('/')
sess = Session()
symbol_query = {
'sdk_id': sdk_info_to_sdk_id(sdk_info), |
'cpu_name': cpu_name,
'symbols': symbols,
}
attempts = 0
with sess:
while 1:
try:
rv = sess.post(url, json=symbol_query)
# If the symbols server does not know about the SDK at all
# it will report a 404 here. In that cas... |
getodacu/eSENS-eDocument | profiles/e_confirmation/xb_request/_qdt.py | Python | mit | 3,119 | 0.003847 | # ./_qdt.py
# -*- coding: utf-8 -*-
# PyXB bindings for NM:763e66503f6e9797a3b5522270417bad82c9c82c
# Generated 2015-02-11 21:35:49.975995 by PyXB version 1.2.4 using Python 2.6.9.final.0
# Namespace urn:oasis:names:specification:ubl:schema:xsd:QualifiedDataTypes-2 [xmlns:qdt]
from __future__ import unicode_literals
i... | mDOM(dom.documentElement, default_namespace=default_namespace)
if default_namespace is None:
default_namespace = Namespace.fallbackNamespace()
saxer = pyxb.binding.saxer.make_parser(fallback_namespace=default_namespace, location_base=location_base)
handler = saxer.getContentHandler()
xmld = xml_... | ncode(pyxb._InputEncoding)
saxer.parse(io.BytesIO(xmld))
instance = handler.rootObject()
return instance
def CreateFromDOM (node, default_namespace=None):
"""Create a Python instance from the given DOM node.
The node tag must correspond to an element declaration in this module.
@deprecated: Fo... |
sswaner/twilio-aws | resources/lambda_functions/sms_message_handler.py | Python | gpl-3.0 | 671 | 0.011923 | import boto3
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def lambda_handler(event, context):
logger.info("RECEIVED EVENT: %s"%( str( event )) )
| params = event['params']
sid = params['MessageSid']
from_number = params['From']
to_number = params['To']
body = params['Body']
logger.info("RECEIVED MESSAGE SID: %s, FROM: %s, TO: %s, BODY: %s" % ( sid, from_number, to_number, body))
client = boto3.client('dynamodb')
client.put_item(Tab... | "to": {'S': to_number},
"body": {'S': body}})
return ""
|
paihu/moebox | admin.py | Python | mit | 124 | 0 | from django.contrib import admin
# Register your models here.
from .models import Uploade | r
admin.si | te.register(Uploader)
|
Julian/cardboard | cardboard/types.py | Python | mit | 4,144 | 0.001689 | artifact = u"Artifact"
creature = u"Creature"
enchantment = u"Enchantment"
land = u"Land"
planeswalker = u"Planeswalker"
instant = u"Instant"
sorcery = u"Sorcery"
permanents = frozenset({artifact, creature, enchantment, land, planeswalker})
nonpermanents = frozenset({instant, sorcery})
all = permanents | nonpermanen... | lver", u"Wall",
u"Warrior", u"Weird", u"Werewolf", u"Whale", u"Wizard", u"Wolf",
u"Wolverine", u"Wombat", u"Worm", u"Wraith", u"Wurm", u"Yeti",
u"Zombie", u"Zubera"
}) | ,
enchantment : frozenset({u"Aura", u"Curse", u"Shrine"}),
instant : frozenset({u"Arcane", u"Trap"}),
u"Basic Land" : frozenset({
u"Forest", u"Island", u"Mountain", u"Plains", u"Swamp"
}),
u"Non-Basic Land" : frozenset({
u"Desert", u"Lair", u"Locus", u"Mine",
u"Power-Plant"... |
rozap/arb | src/api/campbx.py | Python | mit | 3,615 | 0.00083 | import urllib2
import base64
import simplejson as json
import logging
from urllib import urlencode
from functools import partial
log = logging.getLogger(__name__)
log_formatter = logging.Formatter('%(name)s - %(message)s')
log_handler = logging.StreamHandler()
log_handler.setFormatter(log_formatter)
log.addHandler(lo... | ('myfunds', True),
| 'my_orders': ('myorders', True),
'my_margins': ('mymargins', True),
'get_btc_address': ('getbtcaddr', True),
'send_instant': ('sendinstant', True),
'send_btc': ('sendbtc', True),
'trade_cancel': ('tradecancel', True),
'trade_enter': ('tradeenter', True),
'trade... |
adriansnetlis/bgmc16minosaur | bgmc16minosaur/Assets/Scripts/LightLOD.py | Python | gpl-2.0 | 659 | 0.018209 | #This script is made by cotax
#cotax is blenderartists.org user's n | ickname.
#1. Place a lamp in the scene and put its energy to 0.0
#2. Connect this script to the lamp, always(true)- python
#- Add a property: energy(float) to the lamp
#- Add a property: distance(integer) to the lamp
#Set the energy and distance to your likings
from bge import logic
own = logic.getCurre... | ergy']
#check distance and set the energy
if own.getDistanceTo(cam) < distance:
own.energy = energy
else:
own.energy = 0.0 |
PaulMcMillan/2014_defcon_timing | hue/vis6.py | Python | bsd-2-clause | 1,918 | 0.001564 | import matplotlib.pyplot as plt
from collections import defaultdict
from itertools import combinations
from pprint import pprint
from scipy import stats
import random
from itertools import chain
import results
def choose_points(qr_list):
return [d.total_response() - getattr(d, 'median', 0) for d in qr_list]
de... |
return dict(data_roundup)
data = resul | ts.read_data(bucket=r'^/api/\w{3}(\w)\w{6}/config$',
data_dir='more_recent_data')
pprint(check_data(data))
exit()
correct = 0
incorrect = 0
unclear = 0
shortened = []
shorten_error = 0
ANSWER = '0'
for x in range(1000):
print "Iteration: ", x
res = check_data(data)
if not res:
... |
a5kin/evolife | evolife.py | Python | mit | 16,479 | 0.006554 | #!/usr/bin/env python
"""
EvoLife Cellular Automaton implementation using CUDA.
Rules are:
- Each living cell has its own birth/sustain ruleset and an energy level;
- Cell is loosing all energy if number of neighbours is not in its sustain rule;
- Cell is born with max energy if there are exactly N neighbours with N i... | if (gene > 0) genes_count--;
if (genes_count <= 0) break;
}
if (seed > 0) seed--;
if (seed == 0 && ff2 && gene_num < 17) {
gene = (1 << (gene_num + seed) % 17) & f2;
... | if (gene > 0) genes_count--;
if (genes_count <= 0) break;
}
if (seed > 0) seed--;
if (seed == 0 && ff3 && gene_num < 17) {
gene = (1 << (gene_num + seed) % 17) & f3;
f... |
xiangke/pycopia | mibs/pycopia/mibs/HP_SN_IGMP_MIB_OID.py | Python | lgpl-2.1 | 626 | 0.01278 | # python
# This file is generated by a program (mib2py).
import HP_SN_IGMP_MIB
OIDMAP = {
'1.3.6.1.4.1.11.2.3.7.11.12.2.6.1': HP_SN_IGMP_MIB.snIgmpMIBObjects,
'1.3.6.1.4.1.11.2.3.7.11.12.2.6.1.1': HP_SN_IGMP_MIB.snIgmpQueryInterval,
'1. | 3.6.1.4.1.11.2.3.7.11.12.2.6.1.2': HP_SN_IGMP_MIB.snIgmpGroupMembershipTime,
'1.3.6.1.4.1.11.2.3.7.11.12.2.6.1.3.1.1': HP_SN_IGMP_MIB.snIgmpIfEntryIndex,
'1.3.6.1.4.1.11.2.3.7.11. | 12.2.6.1.3.1.2': HP_SN_IGMP_MIB.snIgmpIfPortNumber,
'1.3.6.1.4.1.11.2.3.7.11.12.2.6.1.3.1.3': HP_SN_IGMP_MIB.snIgmpIfGroupAddress,
'1.3.6.1.4.1.11.2.3.7.11.12.2.6.1.3.1.4': HP_SN_IGMP_MIB.snIgmpIfGroupAge,
}
|
vollov/isda.ca | isda_backend/page/admin.py | Python | mit | 962 | 0.011435 | from django.contrib | import admin
from models import Page, TPage, Content, TContent
class PageAdmin(admin.Mo | delAdmin):
exclude = ['posted']
#fields = ['posted', 'title']
list_display = ('title', 'posted', 'slug')
prepopulated_fields = {'slug': ('title',)}
class TPageAdmin(admin.ModelAdmin):
list_display = ('title', 'language', 'page')
#prepopulated_fields = {'slug': ('title',)}
class ContentAdmin(ad... |
chrislit/usfm2osis | setup.py | Python | gpl-3.0 | 1,809 | 0 | from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
def readfile(fn):
"""Read fn and return the contents."""
with open(path.join(here, fn), "r", encoding="utf-8") as f:
return f.read()
setup(
name="usfm2osis",
... | osis', 'scripts/usfmtags'],
package_data={"usfm2osis": ["schemas/*.xsd"]},
entry_points={
"console_scripts": [
"usfm2osis = usfm2osis.scripts.usfm2osis:main",
"usfmtags = usfm2osis.scripts.us | fmtags:main",
]
},
)
|
Purg/SMQTK | python/smqtk/algorithms/nn_index/hash_index/linear.py | Python | bsd-3-clause | 3,373 | 0 | import heapq
import os
import numpy
from smqtk.algorithms.nn_index.hash_index import HashIndex
from smqtk.utils.bit_utils import (
bit_vector_to_int_large,
int_to_bit_vector_large,
)
from smqtk.utils.metrics import hamming_distance
__author__ = "paul.tunison@kitware.com"
class LinearHashIndex (HashIndex):... | nt = bit_vector_to_int_large(h)
bits = len(h)
#: :type: list[int|long]
near_codes = \
heapq.nsmallest(n, self.index,
lambda e: hamming_distance(h_int, e)
)
distances = map(hamming_distance, near_codes,
... | , bits) for c in near_codes], \
[d / float(bits) for d in distances]
|
alixedi/django_authstrap | authstrap/urls.py | Python | bsd-3-clause | 1,659 | 0.002411 | from django.conf.urls import patterns, url
from django.contrib.auth import views as auth_views
urlpatterns = patterns('',
url(r'^login/$',
auth_views.login,
{'template_name': 'authstrap/login.html'},
name='auth_login'),
url(r'^logout/$',
auth_views.logo... | password/reset/confirm/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$',
auth_views.password_reset_confirm,
{'template_name': 'authstrap/password_reset_confirm.html'},
name='auth_password_reset_confirm'),
url(r'^password/reset/complete/$',
auth_views.password_reset_comp... | iews.password_reset_done,
{'template_name': 'authstrap/password_change_done.html'},
name='auth_password_reset_done'),
) |
beeftornado/sentry | src/sentry/rules/__init__.py | Python | bsd-3-clause | 646 | 0.001548 | from __future__ import absolute_import
from .base import * # NOQA
from .registry impor | t RuleRegistry # NOQA
def init_registry():
from sentry.constants import _SENTRY_RULES
from sentry.plugins.base import plugins
from sentry.utils.imports import import_string
from sentry.utils.safe import safe_execute
registry = RuleRegistry()
for rule in _SENTRY_RULES:
| cls = import_string(rule)
registry.add(cls)
for plugin in plugins.all(version=2):
for cls in safe_execute(plugin.get_rules, _with_transaction=False) or ():
registry.add(cls)
return registry
rules = init_registry()
|
hufeiya/leetcode | python/88_Merge_Sorted_Array.py | Python | gpl-2.0 | 628 | 0.015924 | class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
last,i,j = m+n-1,m-1,n-1
while i >=... | 1
while j >= 0:
nums1[last] = nums2[j]
last,j = last-1, | j-1
|
caternuson/rpi-laser | mjpegger.py | Python | mit | 2,603 | 0.011909 | #===========================================================================
# mjpegger.py
#
# Runs a MJPG stream on provided port.
#
# 2016-07-25
# Carter Nelson
#===========================================================================
import threading
import SimpleHTTPServer
import SocketServer
import io
keepStre... | self.server.allow_reuse_address = True
self.server.timeout = 0.1
self.server.server_bind()
self.server.server_activate()
self.keepRunning = True
self.streamRunning = True
while | self.keepRunning:
self.server.handle_request()
self.streamRunning = False
camera.close()
self.server.server_close()
print "MJPEGThread done"
def stop(self, ):
global keepStreaming
keepStreaming = False
self.keepRunning = False
... |
Centre-Alt-Rendiment-Esportiu/att | src/python/test/classes/BallTracker.py | Python | gpl-3.0 | 2,078 | 0.001444 | from test.classes.ball_detector.BallDetector import BallDetector
from test.classes.ball_detector.BounceCalculator import BounceCalculator
from test.classes.ball_detector.Extrapolator import Extrapolator
from test.classes.utils.Ball import Ball
from test.classes.utils.BallHistory import BallHistory
VERTICAL_THRESHOLD ... | found_ball = self.ball_detector.detect(frame)
if found_ball.is_none():
found_ball = self.extrapolator.extrapolate(self.track_history)
# Remove vertical m | ovement logic
# If we have no one to compare to, cannot detect vertical movement
if len(self.track_history) == 0 or self.track_history[-1].is_none() or found_ball.is_none():
self.track_history.update_history(found_ball)
else:
# If we have someone to compare to, look if x... |
jeffmahoney/crash-python | crash/types/page.py | Python | gpl-2.0 | 10,946 | 0.001827 | #!/usr/bin/python3
# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:
from typing import Dict, Union, TypeVar, Iterable, Callable, Tuple,\
Optional
from math import log, ceil
import gdb
import crash
from crash.util import find_member_variant
from crash.util.symbols import Types, Symvals... | tup_pageflags_finish_done:
cls.setup_pageflags_finish()
@classmethod
def setup_mem_section(cls, gdbtype: gdb.Type) -> None:
# TODO | assumes SPARSEMEM_EXTREME
cls.SECTIONS_PER_ROOT = cls.PAGE_SIZE // gdbtype.sizeof
@classmethod
def pfn_to_page(cls, pfn: int) -> gdb.Value:
if cls.sparsemem:
section_nr = pfn >> (cls.SECTION_SIZE_BITS - cls.PAGE_SHIFT)
root_idx = section_nr // cls.SECTIONS_PER_ROOT
... |
arunhotra/tensorflow | tensorflow/python/kernel_tests/cholesky_op_test.py | Python | apache-2.0 | 2,904 | 0.006543 | """Tests for tensorflow.ops.tf.Cholesky."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.python.platform
import numpy as np
from six.moves import xrange # pylint: disable=redefined-builtin
import tensorflow as tf
class CholeskyOpTest... | (self):
self._verifyCholesky(np.array([[4., -1., 2.], [-1., 6., 0], [2., 0., 5.]]))
def testBatch(self):
simple_array = np.array([[[1., 0.], [0., 5.]]]) # shape (1, 2, 2)
self._verifyCholesky(simple_array)
self._verifyCholesky(np.vstack((simple_array, simple_array)))
odd_sized_array = np.array([... | = np.random.rand(10, 5, 5)
for i in xrange(10):
matrices[i] = np.dot(matrices[i].T, matrices[i])
self._verifyCholesky(matrices)
def testNonSquareMatrix(self):
with self.assertRaises(ValueError):
tf.cholesky(np.array([[1., 2., 3.], [3., 4., 5.]]))
def testWrongDimensions(self):
tensor3... |
chkarypidis/html2PraatMan | html2PraatMan.py | Python | gpl-3.0 | 7,854 | 0.026993 | # html2PraatMan - Version 1.0 - October 16, 2013
# Batch html-to-ManPages converter for Praat documentation
# Copyright (C) 2013 Charalampos Karypidis
# Email: ch.karypidis@gmail.com
# http://addictiveknowledge.blogspot.com/
##############################
##############################
# This program is free software... | pend(temp)
elif x.name == "i":
temp = italics(x.string)
listChildren.append(temp)
elif x.name == "kbd":
temp = monospace(x.string)
listChildren.append(temp)
elif x.name == "sub":
| temp = subscript(x.string)
listChildren.append(temp)
elif x.name == "sup":
temp = superscript(x.string)
listChildren.append(temp)
else:
listChildren.append(str(x))
output.write("<entry> " + doubleQuotes(string.join(listChildren, '')) + '\n')
elif child.name == "blockquote":
... |
ooici/coi-services | ion/services/dm/test/test_site_data_products.py | Python | bsd-2-clause | 20,250 | 0.007407 | from unittest import skip
from ion.services.dm.test.dm_test_case import DMTestCase
from pyon.public import PRED, OT, RT
from pyon.util.log import log
from ion.services.dm.test.test_dm_end_2_end import DatasetMonitor
from ion.services.dm.utility.granule import RecordDictionaryTool
from nose.plugins.attrib import attr... | ite_data_products:
self.assertEquals(sdp.category, DataProductTypeEnum.SITE)
| self.assertEquals(len(sdp.dataset_windows), 1)
stream_def = self.resource_registry.find_objects(sdp._id, PRED.hasStreamDefinition)[0][0]
assert sdp.dataset_windows[0].dataset_id == device_stream_names.get(stream_def.name)
assert sdp.dataset_windows[0].bounds.star... |
jdelacruz26/misccode | cad2xls.py | Python | bsd-3-clause | 2,955 | 0.004061 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
## @copyright
# Software License Agreement (BSD License)
#
# Copyright (c) 2017, Jorge De La Cruz, Carmen Castano.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the followi... | GetParameters:
def __init__(self):
self.filePath = '/home/jdelacruz/Downloads/KonzeptB_lang090715.st | p'
def loadCAD(self):
print('Starting to load the CAD file, please be patient!...')
Import.open(self.filePath)
self.handler = App.ActiveDocument
self.parts = self.handler.Objects
print('CAD model loaded!')
def writeTxt(self):
f = open('data.txt','a')
pri... |
sharoonthomas/nereid-project | user.py | Python | gpl-3.0 | 2,674 | 0 | # -*- coding: utf-8 -*-
"""
user
Add the employee relation ship to nereid user
:copyright: (c) 2012-2014 by Openlabs Technologies & Consulting (P) Limited
:license: GPLv3, see LICENSE for more details.
"""
from datetime import datetime
from nereid import request, jsonify, login_required, route
from t... | user is an employee and not a regular participant
employee = fields.Many2One('company.employee', 'Employee', select=True)
member_of_projects = fields.One2Many(
"project.work.member", "user", "Member of Projects"
)
def serialize(self, purpose=None):
'''
Serialize NereidUser and ... | er, self).serialize(purpose)
result['image'] = {
'url': self.get_profile_picture(size=20),
}
result['email'] = self.email
result['employee'] = self.employee and self.employee.id or None
result['permissions'] = [p.value for p in self.permissions]
return result
... |
mkhuthir/catkin_ws | src/chessbot/devel/lib/python2.7/dist-packages/nasa_r2_common_msgs/srv/_ResetTableScene.py | Python | gpl-3.0 | 6,933 | 0.016443 | # This Python file uses the following encoding: utf-8
"""autogenerated by genpy from nasa_r2_common_msgs/ResetTableSceneRequest.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
class ResetTableSceneRequest(genpy.Message):
_md5sum = "ba4b0b221fb425ac... | py(self, str, numpy):
"""
unpack serialized message in str into this message instance using numpy for array types
:param str: byte | array of serialized message, ``str``
:param numpy: numpy python module
"""
try:
end = 0
start = end
end += 1
(self.reset,) = _struct_B.unpack(str[start:end])
self.reset = bool(self.reset)
return self
except struct.error as e:
raise genpy.DeserializationError(e) ... |
sghai/robottelo | tests/foreman/ui/test_discoveredhost.py | Python | gpl-3.0 | 56,249 | 0.000018 | # -*- encoding: utf-8 -*-
"""Test class for Foreman Discovery
:Requirement: Discoveredhost
:CaseAutomation: Automated
:CaseLevel: Acceptance
:CaseComponent: UI
:TestType: Functional
:CaseImportance: High
:Upstream: No
"""
import subprocess
import time
from fauxfactory import gen_string
from nailgun import entit... | ls.loc = entities.Location(
name=gen_string('alpha'),
| organization=[cls.org],
).create()
# Update default org and location params to place discovered host
cls.discovery_loc = entities.Setting().search(
query={'search': 'name="discovery_location"'})[0]
cls.discovery_loc.value = cls.loc.name
cls.discovery_loc.update(... |
appcelerator/entourage | components/services/appengine/stub/beaker/ext/memcached.py | Python | apache-2.0 | 4,037 | 0.006688 | import sys
from beaker.container import NamespaceManager, Container
from beaker.exceptions import InvalidCacheBackendError, MissingCacheParameter
from beaker.synchronization import _threading, Synchronizer
from beaker.util import verify_directory, SyncDict
try:
import cmemcache as memcache
except ImportError:
... | _' + x for x in keys]
delete_keys.append(self.namespace + ':keys')
self.mc.delete_multi(delete_keys)
def keys(self):
keys = self.mc.get(self.namespace + ':keys')
if keys is None:
return []
else:
return [x.replace('\302\267', ' ') for | x in keys.keys()]
class MemcachedContainer(Container):
def do_init(self, data_dir=None, lock_dir=None, **params):
self.funclock = None
def create_namespace(self, namespace, url, **params):
return MemcachedNamespaceManager(namespace, url, **params)
create_namespace = classmethod(create_na... |
Gimpneek/jobseek | jobseekr/cv/forms/user.py | Python | agpl-3.0 | 1,096 | 0 | """ Forms for use with User objects """
from django import forms
from django.contrib.auth.models import User
class UserForm(forms.ModelForm):
"""
Form for django.contrib.auth.models.User
"""
class Meta:
"""
Meta data for User Form
"""
model = User
fields = ('us... | args)
self.fields['username'].required = True
self.fields['email'].required = True
self.fields['password'].required = True
def save(self, commit=True):
"""
Override save so creates a user using create_user method on User model
:param commit: Commit to DB or not
... | username=self.cleaned_data.get('username'),
password=self.cleaned_data.get('password'),
email=self.cleaned_data.get('email')
)
return instance
|
j-windsor/cs3240-f15-team21-v2 | post/forms.py | Python | mit | 640 | 0.015625 | from django import forms
from django.contrib.auth.models import User
from .models import Message
from tinymce.widgets import TinyMCE
class MessageForm(forms.Form):
recipient = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
subject = for | ms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
| content = forms.CharField(widget=TinyMCE(attrs={'cols': 80, 'rows': 30}))
encrypted = forms.BooleanField(required=False)
#class Meta:
# model = Message
# fields = ('recipient', 'subject', 'content', 'encrypted',)
class KeyForm(forms.Form):
pem_file = forms.FileField()
|
lokiteitor/ikol | test/DBtest.py | Python | gpl-2.0 | 589 | 0.018676 | #!/usr/bin/env python2.7
import os
import sys
thi | s_dir = os.path.dirname(os.path.abspath(__file__))
trunk_dir = os.path.split(this_dir)[0]
sys.path.insert(0,trunk_dir)
from ikol.dbregister import DataBase
from ikol import var
if os.path.exists(var.DB_PATH):
os.remove(var.DB_PATH)
D | B = DataBase(var.DB_PATH)
DB.insertPlaylist("loLWOCl7nlk","test")
DB.insertPlaylist("loLWO357nlk","testb")
DB.insertVideo("KDk2341oEQQ","loLWOCl7nlk","test")
DB.insertVideo("KDktIWeoE23","loLWOCl7nlk","testb")
print DB.getAllVideosByPlaylist("loLWOCl7nlk")
print DB.getVideoById("KDk2341oEQQ") |
klahnakoski/MySQL-to-S3 | vendor/pyLibrary/env/pulse.py | Python | mpl-2.0 | 7,554 | 0.00331 | # encoding: utf-8
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Author: Kyle Lahnakoski (kyle@lahnakoski.com)
#
from __future__ import unicode_literals
from __f... | self,
exchange, # name of the Pulse exchange
topic, # message name pattern to subscribe to ('#' is wildcard)
target=None, # WILL BE CALLED WITH PULSE PAYLOADS AND ack() IF COMPLETE$ED WITHOUT EXCEPTION
target_queue=None, # (aka self.queue) WILL BE FILLED WITH PULSE PAYLOADS
... | t=5671, # tcp port
user=None,
password=None,
vhost="/",
start=0, # USED AS STARTING POINT FOR ASSIGNING THE _meta.count ATTRIBUTE
ssl=True,
applabel=None,
heartbeat=False, # True to also get the Pulse heartbeat message
durable=False, # True to keep que... |
zbyna/plugin.video.sosac.ph | default.py | Python | gpl-2.0 | 2,056 | 0.000486 | # -*- coding: UTF-8 -*-
# /*
# * Copyright (C) 2013 Libor Zoubek + jondas
# *
# *
# * 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, or (at your option)
# * ... |
__scriptid__ = 'plugin.video.sosac.ph'
__scriptname__ = 'sosac.ph'
__addon__ = xbmcaddon.Addon | (id=__scriptid__)
__language__ = __addon__.getLocalizedString
__set__ = __addon__.getSetting
settings = {'downloads': __set__('downloads'),
'quality': __set__('quality'),
'subs': __set__('subs') == 'true',
'add_subscribe': __set__('add_subscribe'),
'force-ch': __set__('f... |
partp/gtg-services | GTG/gtk/backends_dialog/parameters_ui/passwordui.py | Python | gpl-3.0 | 3,286 | 0 | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Getting Things GNOME! - a personal organizer for the GNOME desktop
# Copyright (c) 2008-2013 - Lionel Dricot & Bertrand Rousseau
#
# This program is free software: you can redistribute it and/or modify it under
# t... | Public License along with
# this program. If not, see <http://www.gnu.org/licenses/>.
# -----------------------------------------------------------------------------
from gi.repository import Gtk
from GTG import _
class PasswordUI(Gtk.Box):
'''Widget displaying a gtk.Label and a textbox to input a password''' |
def __init__(self, req, backend, width):
'''Creates the gtk widgets and loads the current password in the text
field
@param req: a Requester
@param backend: a backend object
@param width: the width of the Gtk.Label object
'''
super(PasswordUI, self).__init_... |
rcosnita/fantastico | fantastico/samples/simple_component/simple_urls.py | Python | mit | 1,965 | 0.006107 | '''
Copyright 2013 Cosnita Radu Viorel
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, merge, publish, distribute... | antastico.samples.simple_component.simple_urls
'''
from fantastico.mvc.base_controller import BaseController
f | rom fantastico.mvc.controller_decorators import ControllerProvider, Controller
from webob.response import Response
@ControllerProvider()
class SampleUrlsController(BaseController):
'''This class provides some urls with limited functionality in order to enrich the samples from fantastico framework.'''
@Control... |
anhstudios/swganh | data/scripts/templates/object/intangible/pet/shared_3po_protocol_droid_silver.py | Python | mit | 438 | 0.047945 | #### NOTICE: THIS FILE IS AUTOGENERATED
### | # MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Intangible()
result.template = "object/intangible/pet/shared_3po_protocol_droid_silver.iff"
result.attribute_template_id = -1
result.stfName("","")
##... | NS ####
#### END MODIFICATIONS ####
return result |
DayGitH/Python-Challenges | DailyProgrammer/20120330B.py | Python | mit | 3,384 | 0.001773 | """
Write a program that will help you play poker by telling you what kind of hand you have.
|
Input:
The first line of input contains the number of test cases (no more than 20). Each test case consists of one line - five
space separated cards. Each card is represented by a two-letter (or digit) word. The first character is | the rank
(A,K,Q,J,T,9,8,7,6,5,4,3 or 2), the second character is the suit (S,H,D,C standing for spades, hearts, diamonds and
clubs). The cards can be in any order (but they will not repeat).
Output:
For each test case output one line describing the type of a hand, exactly like in the list above.
"""
rank = ['A', 'K'... |
joelfiddes/toposubv2 | topoMAPP/utils/copytree.py | Python | gpl-3.0 | 724 | 0.002762 | #!/usr/bin/env python
import os
import shutil
# def main(src, dst, symlinks=False, ignore=None):
# """Main entry point for the script."""
# copytree(src, dst, symlin | ks=False, ignore=None)
|
def copytree(src, dst, symlinks=False, ignore=None):
for item in os.listdir(src):
s = os.path.join(src, item)
d = os.path.join(dst, item)
if os.path.isdir(s):
shutil.copytree(s, d, symlinks, ignore)
else:
shutil.copy2(s, d)
# # calling main
# if... |
damngamerz/coala | coalib/settings/ConfigurationGathering.py | Python | agpl-3.0 | 17,309 | 0.000116 | import os
import re
import sys
import logging
from coalib.collecting.Collectors import (
collect_all_bears_from_sections, filter_section_bears_by_languages)
from coalib.misc import Constants
from coalib.output.ConfWriter import ConfWriter
from coalib.output.printers.LOG_LEVEL import LOG_LEVEL
from coalib.parsing.C... | :param log_printer: A log printer to emit the warning to.
:return: Returns a boolean True if the given argument
is present in the sections, else returns False.
"""
if all(argument not in section for section in sections.values()):
log_printer.warn('coala will no... | any analysis. Did you forget '
'to give the `--{}` argument?'.format(argument))
return True
return False
def load_configuration(arg_list, log_printer, arg_parser=None, args=None):
"""
Parses the CLI args and loads the config file accordingly, taking
default_coafile an... |
pineapplemachine/migrates | test/test_reindex.py | Python | gpl-3.0 | 1,758 | 0.006826 | import elasticsearch
import migrates
from .test_utils import callmigrates, iterate_test_data, remove_test_data
document_count = 1000
def insert_test_data(connection):
with migrates.Batch(connection, migrates.Logger()) as batch:
for i in range(0, document_count):
batch.add({
... | '_type': 'test_' + str(i % 3),
'_id': str(i),
'_source': {'x': i}
})
def validate_test_data(connection, index):
docs = set()
for document in | iterate_test_data(connection, index=index):
docs.add(document['_source']['x'])
assert len(docs) == document_count
def __main__():
logger = migrates.Logger()
connection = elasticsearch.Elasticsearch()
logger.log('Removing old test data.')
remove_test_data(connection)
try:
... |
anhstudios/swganh | data/scripts/templates/object/tangible/ship/crafted/droid_interface/shared_base_droid_interface_subcomponent_mk3.py | Python | mit | 523 | 0.042065 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTAT | ION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/ship/crafted/droid_interface/shared_base_droid_interface_subcomponent_mk3.iff"
result.attribute_template_id = 8
result.stfName("space_crafting_n","base_droid_interface_subcomponent_mk3")
#... | BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
miketung168/survey-dashboard | example_config.py | Python | mit | 130 | 0 | DB_CONFIG = | "postgresql://user:passwor | d@localhost/db"
ROOT_DIR = "/path/to/project"
ADMIN_USER = "username"
ADMIN_PW = "password"
|
lgarren/spack | var/spack/repos/builtin/packages/lua-luafilesystem/package.py | Python | lgpl-2.1 | 2,512 | 0.000398 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | ve/v1_6_3.tar.gz'
version('1_6_3', 'bed11874cfded8b4beed7dd054127b24')
# The version constraint here comes from this post:
#
# https://www.perforce.com/blog/git-beyond-basics-using-shallow-clones
#
# where it is claimed that full shallow clone support was added @1.9
depends_on | ('git@1.9.0:', type='build')
extends('lua')
def install(self, spec, prefix):
rockspec_fmt = join_path(self.stage.path,
'luafilesystem-{version.underscored}',
'rockspecs',
'luafilesystem-{version.dotted}-1... |
sniemi/SamPy | sandbox/src1/TCSE3-3rd-examples/src/py/regex/fdmgrid.py | Python | bsd-2-clause | 2,941 | 0.00136 | #!/usr/bin/env python
"""interpret a comapct grid specification using regex"""
import re
# use a compact regular expression with nested OR expressions,
# and hence many groups, but name the outer (main) groups:
real_short1 = \
r'\s*(?P<lower>-?(\d+(\.\d*)?|\d*\.\d+)([eE][+\-]?\d+)?)\s*'
real_short2 = \
r'\s*(?P<uppe... | s, ex)
# a nested list is returned; requires nested group counting
print re.findall(domain, ex)
print
# work with compiled expressio | ns and the groupindex dictionary to
# extract the named groups easily from the nested list that is
# returned from re.findall:
print 'work with groupindex:'
for ex in examples:
print re.findall(indices, ex)
c = re.compile(domain)
groups = c.findall(ex)
intervals = []
for i in range(len(groups)):
... |
rrmelcer/swissatest-analysis | gui/qt4/credits.py | Python | apache-2.0 | 19,884 | 0.004024 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# -----------------------------------------------
# ----> Computer Aided Optical Analysis <----
# -----------------------------------------------
# (c) 2015 by Swissatest Testmaterialien AG
# http://www.swissatest.ch
# -----------------------------------------------
# Devel... | True)
self.label_4.setTextInteractionFlags(QtCore.Qt.LinksAccessibleByKeyboard|QtCore.Qt.LinksAccessibleByMouse|QtCore.Qt.TextBrowserInteraction|Qt | Core.Qt.TextSelectableByKeyboard|QtCore.Qt.TextSelectableByMouse)
self.label_4.setObjectName(_fromUtf8("label_4"))
self.gridLayout.addWidget(self.label_4, 12, 1, 1, 1)
self.line_4 = QtGui.QFrame(dia_credits)
self.line_4.setFrameShape(QtGui.QFrame.HLine)
self.line_4.setFrameShadow... |
beppec56/core | uitest/writer_tests/tdf92611.py | Python | gpl-3.0 | 647 | 0.003091 | #
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
from uitest.framework import UITestCase
import time
class tdf92611(UITestCase):
def test_launch_and_close_bibl... | elf):
self.ui_test.create_doc_in_start_center("writer")
self.xUITest.executeCommand(".uno:BibliographyComponent")
time.sleep(2)
self.xUITest.executeCommand(".uno:CloseWin")
| time.sleep(2)
self.ui_test.close_doc()
# vim: set shiftwidth=4 softtabstop=4 expandtab:
|
piyush82/icclab-rcb-web | virtualenv/lib/python2.7/site-packages/pip/vendor/__init__.py | Python | apache-2.0 | 264 | 0 | """
pip.vendor is for vendoring | dependencies of pip to prevent n | eeding pip to
depend on something external.
Files inside of pip.vendor should be considered immutable and should only be
updated to versions from upstream.
"""
from __future__ import absolute_import
|
mjsir911/pymessage | client.py | Python | bsd-3-clause | 1,124 | 0.010676 | #!/usr/bin/e | nv python3
# -*- coding: utf-8 -*-
import uuid
import socket
import time
__appname__ = "pymessage"
__author__ = "Marco Sirabella, Owen Davies"
__copyright__ = ""
__credits__ = "Marco Sirabella, Owen Davies"
__license__ = "new BSD 3-Clause"
__version__ = "0.0.3"
__maintainers__ = "Marco Sirabell... | = "Prototype"
__module__ = ""
address = ('localhost', 5350)
lguid = '0'
def connect():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(address)
sock.send((hex(uuid.getnode()) + '\n').encode() + bytes(False)) # ik this is such BAD CODE
print("sent")
sock.send(lguid.e... |
HubSpot/tcollector | collectors/0/netstat.py | Python | gpl-3.0 | 17,157 | 0.001224 | #!/usr/bin/python
# This file is part of tcollector.
# Copyright (C) 2011 The tcollector Authors.
#
# This pr | ogram 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 3 of the License, or (at your
# option) any later version. This program is distributed in the hope that it
# will be useful, but WIT... | hout 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 along with this program. If not,
# see <http://www.gnu.org/licenses/>.
# Note: I spent man... |
getnamo/UnrealEnginePython | Content/Scripts/upycmd.py | Python | mit | 2,925 | 0.037949 | #ue.exec('pip2.py')
import subprocess
import sys
import os
import unreal_engine as ue
import _thread as thread
#ue.log(sys.path)
_problemPaths = ['']
def NormalizePaths():
problemPaths = _problemPaths
#replace '/' to '\\'
for i in range(len(sys.path)):
currentPath = sys.path[i]
sys.path[i] = currentPath.repl... | th(relativePath);
def AsAbsPath(path):
return os.path.abspath(path).replace('\\','/')
_PythonHomePath = PythonHomePath()
def FolderCommand(folder):
#replace backslashes
folder = folder.replace('/','\\')
changefolder = "cd /d \ | "" + folder + "\" & "
return changefolder
#main public function
def run(process, path=_PythonHomePath, verbose=True):
#todo: change folder
fullcommand = FolderCommand(path) + process
if verbose:
ue.log("Started cmd <" + fullcommand + ">")
stdoutdata = subprocess.getstatusoutput(fullcommand)
if verbose:
ue.lo... |
frasertweedale/drill | py/oldest_unique.py | Python | mit | 1,106 | 0 | class Node:
def __init__(self, val | ue):
self.value = value
self.next = None
self.prev = None
class OldestUnique:
def | __init__(self):
self.uniq = {}
self.seen = set()
self.head = None
self.tail = None
def feed(self, value):
if value in self.uniq:
# unlink from list but leave in uniq dict
node = self.uniq[value]
if node.prev is not None:
n... |
sdrogers/ms2ldaviz | ms2ldaviz/basicviz/migrations/0074_auto_20180831_1206.py | Python | mit | 670 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2018-08-31 12:06
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
| dependencies = [
('basicviz', '0073_auto_20180831_1203'),
]
operations = [
migrations.AddField(
model_name='experiment',
name='csv_id_column',
field=models.CharField(blank=True, max_length=128, null=True),
| ),
migrations.AddField(
model_name='experiment',
name='ms2_id_field',
field=models.CharField(blank=True, max_length=128, null=True),
),
]
|
indera/barebones-flask-app | tests/base_test.py | Python | bsd-3-clause | 1,403 | 0.000713 | """
Goal: set the environment for tests
Docs:
https://pythonhosted.org/Flask-SQLAlchemy/quickstart.html
The only things you need to know compared to plain SQLAlchemy are:
SQLAlchemy gives you access to the following things:
- all the functions and classes from sqlalchemy and sqlalchemy.orm
- a preconfigured scope... | l() methods to create and
drop tables according to the models
- a Model baseclass that is a configured declarative base
- The Model declarative base class behaves like a regular Python class but has
a query attribute attached that can be used to | query the model
- You have to commit the session, but you don't have to remove it at the end
of the request, Flask-SQLAlchemy does that for you.
"""
from flask_testing import TestCase
from app.main import app, db, mail
from app import initializer
from config import MODE_TEST
class BaseTestCase(TestCase):
""... |
m5w/matxin-lineariser | matxin_lineariser/utlgrammars/lrule.py | Python | gpl-3.0 | 2,392 | 0.000836 | from .lconfiguration import LocalConfiguration
from .printing import Printing
from .word import Word
from xml.etree import ElementTree
class LinearisationRule:
@classmethod
def deserialise(cls, grammars, def_rule_etree):
probability = float(def_rule_etree.get('p'))
head_node_etree = def_rule_... | tree.find('NODE')
linearisation_rule = {}
for node_etree in head_node_etree.findall('NODE'):
linearisation_rule[int(node_etree.get('ord'))] = (
node_etree.get('si'), Word.deserialise(node_etree))
head_node = (head_node_etr | ee.get('si'),
Word.deserialise(head_node_etree))
dependents = list(linearisation_rule.values())
dependents.sort()
local_configuration = LocalConfiguration(head_node[0], head_node[1],
tuple(dependents))
head_node_ord = ... |
RedhawkSDR/integration-gnuhawk | qa/gnuradio/gr/top_block.py | Python | gpl-3.0 | 4,399 | 0.006365 | #
# This file is protected by Copyright. Please refer to the COPYRIGHT file
# distributed with this source distribution.
#
# This file is part of GNUHAWK.
#
# GNUHAWK is free software: you can redistribute it and/or modify is under the
# terms of the GNU General Public License as published by the Free Software
# F... | en the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU General Public License for more details.
# You should have received a copy of the GNU General Public License along with
# this program. If not, see http:/ | /www.gnu.org/licenses/.
#
from ossie.utils import sb
from ossie.utils.sandbox import local
import gnuradioStubs
import sources
import commands
import time
def _uuidgen():
return commands.getoutput('uuidgen')
def _isStubClass(comp):
return (isinstance(comp, gnuradioStubs.stream_to_vector) or
isin... |
CZ-NIC/knot | tests-extra/tests/dnssec/single_type_signing/test.py | Python | gpl-3.0 | 1,348 | 0.003709 | #!/usr/bin/env python3
"""
DNSSEC Single-Type Signing Scheme, RFC 6781
"""
from dnstest.utils import *
from dnstest.test import Test
t = Test()
knot = t.server("knot")
zones = t.zone_rnd(5, dnssec=False, records=10)
t.link(zones, knot)
t.start()
# one KSK
knot.gen_key(zones[0], ksk=True, zsk=True, alg="ECDSAP256SHA2... | one in zones[:-1]:
knot.dnssec(zone).enable = True
knot.dnssec(zone).single_type_signing = True
# enable automatic Single-Type signing scheme with NSEC3 on the last zone
knot.dnssec(zones[-1]).enable = True
knot.dnssec(zones[-1]).nsec3 = True
knot.dnssec(zones[-1]).single_type_signing = | True
knot.gen_confile()
knot.reload()
t.sleep(7)
knot.flush(wait=True)
knot.stop()
for zone in zones:
knot.zone_verify(zone)
t.end()
|
team-xue/xue | xue/tutor/studentviews.py | Python | bsd-3-clause | 2,757 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, division
from django.shortcuts import redirect, get_object_or_404
from django.db import transaction
from xue.common.decorators import quickview, limit_role
from xue.tutor.forms import StudentApplicationForm, ProjectSelectionForm
from xue.tutor.models ... | = ProjectSelectionForm(year)
return {
'is_exceeded': False,
'projects': projs,
'form': frm,
}
# expiration
if PRELIMINARY_EXPIRED:
apply_view = apply_expi | red_view
if SECONDARY_EXPIRED:
selectproj_view = apply_expired_view
# vim:set ai et ts=4 sw=4 sts=4 fenc=utf-8:
|
kgblll/libresoft-gymkhana | commons/utils.py | Python | gpl-2.0 | 3,773 | 0.015119 | # -*- coding: utf-8 -*-
# MORFEO Project
# http://morfeo-project.org
#
# Component: EzForge
#
# (C) Copyright 2004 Telefónica Investigación y Desarrollo
# S.A.Unipersonal (Telefónica I+D)
#
# Info about members and contributors of the MORFEO project
# is available at:
#
# http://morfeo-project.org/
#
... | ensure_ascii=ensure_ascii)
def get_xml_error(value):
dom = getDOMImplementation()
doc = dom.createDocument(None, "e | rror", None)
rootelement = doc.documentElement
text = doc.createTextNode(value)
rootelement.appendChild(text)
errormsg = doc.toxml()
doc.unlink()
return errormsg
def getInnerText (domNode, tag=None):
try:
if tag ==None:
return domNode.childNodes[0].nodeValue
else:
... |
horazont/aioxmpp | tests/__init__.py | Python | lgpl-3.0 | 1,184 | 0 | ########################################################################
# File name: __init__.py
# This file is part of: aioxmpp
#
# LICENSE
#
# 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 Foundat... | s/>.
#
########################################################################
from aioxmpp.e2etest import ( # NOQA
setup_pac | kage as e2etest_setup_package,
teardown_package,
)
import warnings
def setup_package():
e2etest_setup_package()
warnings.filterwarnings(
"error",
message=".+(Stream)?ErrorCondition",
category=DeprecationWarning,
)
|
DEV3L/python-files-by-date | files_by_date/service/files_service.py | Python | mit | 4,825 | 0.003731 | import datetime
import os
import shutil
import time
from files_by_date.utils.logging_wrapper import get_logger, log_message
from files_by_date.validators.argument_validator import ArgumentValidator
logger = get_logger(name='files_service')
class FilesService:
def __init__(self):
raise NotImplementedErro... | count.copied}, skipped {group_count.skipped}') # 3.6
log_message('Copied {local_copied_count}, skipped {l | ocal_skipped_count}'.format(
local_copied_count=group_count.copied, local_skipped_count=group_count.skipped))
log_message(
# f'Total files count {total_count.files}, total copied {total_count.copied}, total skipped {total_count.skipped}') # 3.6
'Total files count {total_f... |
BigelowLab/genologics | genologics/descriptors.py | Python | mit | 18,060 | 0.000388 | """Python interface to GenoLogics LIMS via its REST API.
Entities and their descriptors for the LIMS interface.
Per Kraulis, Science for Life Laboratory, Stockholm, Sweden.
Copyright (C) 2012 Per Kraulis
"""
from genologics.constants import nsmap
try:
from urllib.parse import urlsplit, urlparse, parse_qs, urlun... |
return instance.root
class StringDescriptor(TagDescriptor):
"""An instance attribute containing a string value
represented by an XML element.
"""
def __get__(self, instance, cl | s):
instance.get()
node = self.get_node(instance)
if node is None:
return None
else:
return node.text
def __set__(self, instance, value):
instance.get()
node = self.get_node(instance)
if node is None:
# create the new tag
... |
scotartt/commentarius | decommentariis/decommentariis/signals.py | Python | gpl-2.0 | 1,210 | 0.015702 | from allauth.account.signals import email_confirmed, email_changed, email_added, email_removed, user_signed_up, user_logged_in
from django.contrib.auth.models import User, Group, Permission
from django.db.models import Q
from django.dispatch import receiver
"""intercept signals from allauth"""
@receiver(email_confir... | ly"""
# print(email_address.email + " confirmed email.")
query = {'email': email_address.email}
if email_address.primary:
user = User.objects.get(**query)
# print(str(user) + " confirmed primary email.")
group = Group.objects.get(name='AllowedCommentary')
user.groups.add(group)
@receiver(user_signed_up)
de... | llogin', None)
if social_login:
social_account = social_login.account
if social_account:
if 'verified_email' in social_account.extra_data:
if social_account.extra_data['verified_email']:
group = Group.objects.get(name='AllowedCommentary')
user.groups.add(group)
|
Pylvax/django | project/starter_app/admin.py | Python | mit | 92 | 0.01087 | from django.contri | b import admin
from .models import Message
admin.sit | e.register(Message)
|
fabiencro/knmt | tests/suite1/training_management_test.py | Python | gpl-3.0 | 3,928 | 0.001527 | #!/usr/bin/env python
"""macro_tests.py: Some macro tests"""
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Fabien Cromieres"
__license__ = "undecided"
__version__ = "1.0"
__email__ = "fabien.cromieres@gmail.com"
__status__ = "Development"
# import nmt_chainer.make_dat... | = str(train_dir.join("test1.train"))
data_src_file = os.path.join(test_data_dir, "src2.txt")
data_tgt_file = os.path.join(test_data_dir, "tgt2.txt")
args = 'make_data {0} {1} {2} --dev_src {0} --dev_tgt {1}'.format(
data_src_file, data_tgt_file, data_prefix).split(' ')
main(... | _iters 10 --mb_size 2 --Ei 10 --Eo 12 --Hi 30 --Ha 70 --Ho 15 --Hl 23 --save_ckpt_every 5".split(" ")
if gpu is not None:
args_train += ['--gpu', gpu]
main(arguments=args_train)
def test_config_saving(self, tmpdir, gpu):
"""
Test no error happens during checkpoint saving... |
jbernardis/repraptoolbox | src/Printer/printmon.py | Python | gpl-3.0 | 26,866 | 0.039902 | import wx
import re
import os
import time
import inspect
cmdFolder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0]))
gcRegex = re.compile("[-]?\d+[.]?\d*")
from cnc import CNC
from reprapenums import RepRapEventEnum
from gcframe import GcFrame
from properties import Pr... | .images.pngFileopen, size=BUTTONDIM)
self.bOpen.SetToolTip("Open a G Code file")
self.Bind(wx.EVT_BUTTON, self.onOpenFile, self.bOpen)
self.Bind(wx.EVT_CLOSE, self.onClose)
self.bPrint = PrintButton(self, self.images)
self.bPrint.Enable(False)
self.Bind(wx.EVT_BUTTON, self.onPrint, self.bPrint)
s... | lf.images.pngSdprintto, size=(BUTTONDIMWIDE))
self.bSdPrintTo.Enable(False)
self.Bind(wx.EVT_BUTTON, self.onSdPrintTo, self.bSdPrintTo)
self.bSdPrintFrom = wx.BitmapButton(self, wx.ID_ANY, self.images.pngSdprintfrom, size=(BUTTONDIMWIDE))
self.bSdPrintFrom.Enable(False)
self.Bind(wx.EVT_BUTTON, self.onSdPr... |
Achint08/open-event-orga-server | migrations/versions/8e7f7864cb60_.py | Python | gpl-3.0 | 374 | 0.008021 | """empty message
Revision ID: 8e7f7864cb60
Revises: ('80a704b880db', 'adf34c11b0df')
Create Da | te: 2016-06-19 15:43:23.027000
"""
# revision identifiers, used by Alembic.
revision = '8e7f7864cb60'
down_revision = ('80a704b880db', 'adf34c11b0df')
from alembic import op
import sqlalchemy as sa
import sqlalchemy_utils
def upgrade():
pass
def downgrade():
pass | |
mrknow/filmkodi | plugin.video.fanfilm/resources/lib/sources/segos_mv.py | Python | apache-2.0 | 5,195 | 0.009438 | # -*- coding: utf-8 -*-
'''
FanFilm Add-on
Copyright (C) 2016 mrknow
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any ... | trs = {'itemprop': 'copyrightYear'})) for i in result]
result = [i for i in result if len(i[2]) > 0]
result = [i for i | in result if tvshowtitle == cleantitle.tv(i[1])]
result = [i[0] for i in result if any(x in i[2][0] for x in years)][0]
try: url = re.compile('//.+?(/.+)').findall(result)[0]
except: url = result
url = client.replaceHTMLCodes(url)
url = url.encode('utf-8')
... |
SrNetoChan/QGIS | python/plugins/processing/algs/qgis/FindProjection.py | Python | gpl-2.0 | 6,023 | 0.00249 | # -*- coding: utf-8 -*-
"""
***************************************************************************
FindProjection.py
-----------------
Date : February 2017
Copyright : (C) 2017 by Nyall Dawson
Email : nyall dot dawson at gmail dot com
*****************... | 100.0 / len(crses_to_check)
found_results = 0
| transform_context = QgsCoordinateTransformContext()
for current, srs_id in enumerate(crses_to_check):
if feedback.isCanceled():
break
candidate_crs = QgsCoordinateReferenceSystem.fromSrsId(srs_id)
if not candidate_crs.isValid():
continue
... |
makerbot/ReplicatorG | skein_engines/skeinforge-35/skeinforge_application/skeinforge_plugins/craft_plugins/temperature.py | Python | gpl-2.0 | 9,647 | 0.017829 | """
This page is in the table of contents.
Temperature is a script to set the temperature for the object and raft.
==Operation==
The default 'Activate Temperature' checkbox is on. When it is on, the functions described below will work, when it is off, the functions will not be called.
==Settings==
===Rate===
The def... | r temperature of the first layer of the object.
====Object Next Layers Temperature====
Default for ABS is two hundred and thirty degrees Celcius.
Defines the temperature of the next layers of the object.
====Support Layers Temperature====
Default for ABS is two hundred degrees Celcius.
Defines the | support layers temperature.
====Supported Layers Temperature====
Default for ABS is two hundred and thirty degrees Celcius.
Defines the temperature of the supported layers of the object, those layers which are right above a support layer.
==Examples==
The following examples add temperature information to the file S... |
pygeek/PyInterstate | PyInterstate.py | Python | gpl-3.0 | 6,996 | 0.008719 | #PyInterstate by @pygeek
import urllib2
import json
class InterstateError(Exception):
"""Base class for Interstate App Exceptions."""
pass
class AuthError(InterstateError):
"""Exception raised upon authentication errors."""
pass
class IdError(InterstateError):
"""Raised when an operatio... | __version__ = "0.2.0"
def __init__(self):
self.protocol = "http://"
self.base_url = "interstateapp.com"
self.api_version = "v1"
public_key = "public-key"
private_key = "private-key"
"""Installing opener authentication for inevitable, \
subs... | nager
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_mgr.add_password(None, self.protocol + \
self.base_url, public_key, private_key)
handler = urllib2.HTTPBasicAuthHandler(password_mgr)
# create "opener" (OpenerDirector instance)
urlopener = urllib... |
deanwilson/yum-transaction-json | transaction-json.py | Python | gpl-3.0 | 1,282 | 0 | from yum.plugins import PluginYumExit, TYPE_CORE, TYPE_INTERACTIVE
try:
import json
except ImportError:
import simplejson as json
requires_api_version = '2.5'
plugin_type = (TYPE_INTERACTIVE,)
def config_hook(conduit):
parser = conduit.getOptParser()
parser.add_option('', '--json', dest='json', acti... | packages[transaction.name] = {}
version = {
"version": transaction.version,
"release": transaction.release,
"epoch": transaction.epoch,
"arch": transaction.arch,
"st | ate": transaction.ts_state,
"repo": getattr(transaction.po, 'repoid')
}
if transaction.ts_state:
packages[transaction.name]["pending"] = version
else:
packages[transaction.name]["current"] = version
print(json.dumps(packages))... |
jonmsawyer/site-tools | flgetpics/cookie.py | Python | mit | 97 | 0 | # Log into the site with your b | rowser, obtain the "Cookie" header, |
# and put it here
cookie = ''
|
orzubalsky/tradeschool | ts/apps/tradeschool/forms.py | Python | gpl-3.0 | 7,844 | 0.000382 | from django.forms import *
from django.forms.formsets import BaseFormSet
from django.utils.translation import ugettext_lazy as _
from django.contrib.sites.models import Site
from tradeschool.models import *
class DefaultBranchForm(Form):
def __init__(self, user, redirect_to, *args, **kwargs):
super(Defaul... | dentForm, self).__init__(*args, **kwargs)
self.fields['fullname'].error_messag | es['required'] = _(
"Please enter your name")
self.fields['email'].error_messages['required'] = _(
"Please enter your email")
self.fields['phone'].error_messages['required'] = _(
"Please enter your phone number")
class Meta:
model = Person
fields ... |
aspiers/crmsh | modules/ui_ra.py | Python | gpl-2.0 | 3,190 | 0.000627 | # Copyright (C) 2008-2011 Dejan Muhamedagic <dmuhamedagic@suse.de>
# Copyright (C) 2013 Kristoffer Gronlund <kgronlund@suse.com>
# See COPYING for license information.
from . import command
from . import completers as compl
from . import utils
from . import ra
from . import constants
from . import options
def comple... | a_type = ra.disambiguate_ra_type(args[0])
agent = ra | .RAInfo(ra_class, ra_type, ra_provider)
if agent.mk_ra_node() is None:
return False
try:
utils.page_string(agent.meta_pretty())
except Exception, msg:
context.fatal_error(msg)
|
datalogics/scons | src/engine/SCons/Tool/bcc32.py | Python | mit | 2,993 | 0.005012 | """SCons.Tool.bcc32
XXX
"""
#
# __COPYRIGHT__
#
# Permis | sion 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, merge, publish,
# di | stribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PR... |
Metaswitch/calico-nova | nova/tests/unit/api/openstack/compute/contrib/test_flavor_manage.py | Python | apache-2.0 | 17,379 | 0.000173 | # Copyright 2011 Andrew Bogott for the Wikimedia Foundation
# 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-... | %s" % flavorid)
if read_deleted != 'no':
raise test.TestingException("Should not be reading deleted")
return fake_db_flavor(flavorid=flavorid)
def fake_destroy(flavorname):
pass
def fake_create(context, kwargs, projects=None):
newflavor = fake_db_flavor()
flavorid = kwargs.get('flavori... | newflavor["name"] = kwargs.get('name')
newflavor["memory_mb"] = int(kwargs.get('memory_mb'))
newflavor["vcpus"] = int(kwargs.get('vcpus'))
newflavor["root_gb"] = int(kwargs.get('root_gb'))
newflavor["ephemeral_gb"] = int(kwargs.get('ephemeral_gb'))
newflavor["swap"] = kwargs.get('swap')
newflavo... |
throwable-one/teamcity-messages | tests/integration-tests/unittest_integration_test.py | Python | apache-2.0 | 27,766 | 0.00544 | # coding=utf-8
import os
import subprocess
import sys
import pytest
import virtual_environments
from diff_test_tools import expected_messages, SCRIPT
from service_messages import ServiceMessage, assert_service_messages, match
from test_util import run_command
@pytest.fixture(scope='module')
def venv(request):
"... | tput.find("stdout_test") < 0
assert output.find("stderr_test") < 0
def test_doctests(venv):
output = run_directly(venv, 'doctests.py')
test_name = '__main__.factorial'
assert_service_messages(
output,
[
ServiceMessage('testCount', {'count': "1"}),
ServiceMessage... | ServiceMessage('testFinished', {'name': test_name, 'flowId': test_name}),
])
def test_skip(venv):
if sys.version_info < (2, 7):
venv = virtual_environments.prepare_virtualenv(list(venv.packages) + ["unittest2==0.5.1"])
output = run_directly(venv, 'skip_test.py')
test_name = '_... |
Livefyre/protobuf-rpc | python/protobuf_rpc/connection.py | Python | mit | 3,673 | 0.001089 | from Queue import Queue, Empty
import contextlib
from logging import getLogger
import random
import time
from gevent.monkey import saved
LOG = getLogger(__name__)
if bool(saved):
LOG.info('using zmq.green...')
import zmq.green as zmq
else:
import zmq
class ZMQConnection(object):
def __init__(self... | f.maxage = maxage
self.timeout = timeout
self._zmq_init(hosts)
def _zmq_init(self, hosts):
context = zmq.Context()
random.shuffle(hosts)
self.socket = context.socket(zmq.REQ)
self.socket.setsockopt(zmq.LINGER, 0)
for (host, port) in hosts:
self.so... | self.poller.register(self.socket, zmq.POLLIN)
def send(self, req):
self.socket.send(req)
self._last_used = time.time()
def recv(self, timeout=None):
if self.poller.poll(timeout or self.timeout):
resp = self.socket.recv()
else:
self.close()
r... |
CSC591ADBI-TeamProjects/Product-Search-Relevance | build_tfidf.py | Python | mit | 1,752 | 0.021119 | import pandas as pd
import numpy as np
import re
from gensim import corpora, models, similarities
from gensim.parsing.preprocessing import STOPWORDS
def split(text):
'''
Split the input text into words/tokens; ignoring stopwords and empty strings
'''
delimiters = ".", ",", ";", ":", "-", "(", ")", " ", "\t"
... | exts = [[token for token in text if frequency[token] > 2] for text in texts]
# build dictionary
dictionary = corpora.Dictionary(texts)
dictionary.save('homedepot.dict')
print dictionary
# a | ctually build a bag-of-words corpus
corpus = [dictionary.doc2bow(text) for text in texts]
corpora.MmCorpus.serialize('homedepot.mm', corpus)
# build Tf-idf model
tfidf = models.TfidfModel(corpus)
tfidf.save('homedepot.tfidf')
if __name__ == "__main__":
main() |
holinnn/lupin | tests/lupin/validators/test_validator.py | Python | mit | 601 | 0 | # -*- coding: utf-8 -*-
import pytest
from lupin.validat | ors import Equal
from lupin.errors import ValidationError
@pytest.fixture
def invalid():
return Equal("sernine")
@pytest.fixture
def valid():
return Equal("lupin")
class TestAnd(object) | :
def test_returns_an_and_combination(self, valid, invalid):
combination = valid & invalid
with pytest.raises(ValidationError):
combination("andrésy", [])
class TestOr(object):
def test_returns_an_and_combination(self, valid, invalid):
combination = valid | invalid
... |
buxx/TextDataExtractor | sandbox/dalz/implode.py | Python | gpl-2.0 | 1,003 | 0.002991 | from sandbox.dalz.data import ArticleCommentCountFileData, ArticlePublicationDateFileData, ArticleAuthorFileData, \
ArticleWordCountFileData, CommentAuthorCommentCountFilesDatas, AuthorArticleCountFilesData, \
AuthorArticlesCommentsCountAverageFilesData, AuthorArticlesWordsCountAverageFilesData, \
ArticlePu... | de
class ArticleImplode(Implode):
_name = 'Articles'
_data_classes = [ArticleWordCountFileData,
ArticleCommentCountFileData,
ArticlePublicationDateFileData,
ArticlePublicationHourFileData,
ArticleAuthorFileData,
... | AuthorArticlesCommentsCountAverageFilesData,
AuthorArticlesWordsCountAverageFilesData]
|
nivbend/mock-open | src/mock_open/test/__init__.py | Python | mit | 161 | 0 | # pylint | : disable=missing-docstring
# pylint: disable=wildcard-import
from .test_mocks import *
from .cpython.testmock import *
from .cpython.testwith import | *
|
ecleya/project_cron | project_cron/utils/apputil.py | Python | mit | 424 | 0 | from project_cron.utils import processutil
def open(app_n | ame):
script = '''
if application "%s" is not running then
tell applicatio | n "%s" to activate
end if
''' % (app_name, app_name)
processutil.call(['/usr/bin/osascript', '-e', script])
def close(app_name):
script = 'tell application "%s" to quit' % app_name
processutil.call(['/usr/bin/osascript', '-e', script])
|
mokuso/scan-gspread-targets | scan-gspread-targets.py | Python | mit | 1,952 | 0.000512 | #!/usr/bin/env python
# A python script to take targets from a google spreadsheet and run a
# Nessus vulnerability scan.
import json
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from nessrest import ness6rest
import getpass
# Login with your Google account's API key
scopes = ['ht... | if i and i != 'IP':
# iterate through all rows and add to a temp array
temp_hosts.append(i)
print(temp_hosts)
# scan
# Scan Settings
# nessus_url = "https://nessus.example.com:8834"
nessus_url = "https://192.168.111.10:8834"
scan_policy = "Basic Network Scan"
scan_name = "My Scan"
# Scanner Cred... | login = "username"
# password = "password"
scan = ness6rest.Scanner(url=nessus_url, login=user,
password=password, insecure=True)
# Set scan policy that should be used
scan.policy_set(name=scan_policy)
# alt_targets on edit can take an array otherwise a new scan expects a string
hosts = ','... |
erh3cq/hyperspy | hyperspy/tests/test_non-uniform_not-implemented.py | Python | gpl-3.0 | 4,442 | 0.001576 | # -*- coding: utf-8 -*-
# Copyright 2007-2021 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... | ogram_image():
s = HologramImage([[10, 10], [10, 10]])
s.axes_manager[0].convert_to_non_uniform_axis()
s.axes_manager[1].convert_to_non_uniform_axis()
with pytest.raises(NotImplementedError):
s.estimate_sideband_position()
with pytest.raises | (NotImplementedError):
s.estimate_sideband_size(s)
with pytest.raises(NotImplementedError):
s.reconstruct_phase()
with pytest.raises(NotImplementedError):
s.statistics()
def test_lazy():
s = Signal1D([10, 10]).as_lazy()
s.axes_manager[0].convert_to_non_uniform_axis()
print(... |
vinegret/youtube-dl | youtube_dl/extractor/tf1.py | Python | unlicense | 3,611 | 0.002777 | # coding: utf-8
from | __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import comp | at_str
class TF1IE(InfoExtractor):
"""TF1 uses the wat.tv player."""
_VALID_URL = r'https?://(?:(?:videos|www|lci)\.tf1|(?:www\.)?(?:tfou|ushuaiatv|histoire|tvbreizh))\.fr/(?:[^/]+/)*(?P<id>[^/?#.]+)'
_TESTS = [{
'url': 'http://videos.tf1.fr/auto-moto/citroen-grand-c4-picasso-2013-presentation-off... |
carloderamo/mushroom | examples/atari_dqn.py | Python | mit | 19,062 | 0.00063 | import argparse
import datetime
import pathlib
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from mushroom_rl.algorithms.value import AveragedDQN, CategoricalDQN, DQN,\
DoubleDQN, MaxminDQN, DuelingDQN, NoisyDQN, Rainbow
from mushroom_rl.approxim... | 4,
help='Number of frames composing a state.')
arg_alg.add_argument("--target-update-frequency", type=int, default=10000,
help='Number of collected samples before each update'
'of the target network.')
arg_alg.ad | d_argument("--evaluation-frequency", type=int, default=250000,
help='Number of collected samples before each'
'evaluation. An epoch ends after this number of'
'steps')
arg_alg.add_argument("--train-frequency", type=int, default=4,
... |
josiah-wolf-oberholtzer/supriya | supriya/realtime/servers.py | Python | mit | 35,554 | 0.001041 | import asyncio
import logging
import re
import threading
from os import PathLike
from typing import Optional, Set, Union
from uqbar.objects import new
import supriya.exceptions
from supriya.commands import ( # type: ignore
FailResponse,
GroupNewRequest,
GroupQueryTreeRequest,
NotifyRequest,
QuitR... | SynthDef):
name = expr.actual_name
if name in self._synthdefs and self._synthdefs[name] == expr:
return True
return False
### PRIVATE METHODS ###
async def _connect(self):
self._osc_protocol = AsyncOscProtocol()
| await self._osc_protocol.connect(
ip_address=self._ip_address,
port=self._port,
healthcheck=HealthCheck(
request_pattern=["/status"],
response_pattern=["/status.reply"],
callback=self._shutdown,
max_attempts=5,
... |
hujiajie/chromium-crosswalk | third_party/WebKit/Tools/Scripts/webkitpy/style/checkers/png_unittest.py | Python | bsd-3-clause | 3,001 | 0.001666 | # Copyright (C) 2012 Balazs Ankes (bank@inf.u-szeged.hu) University of Szeged
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this lis... | TITUTE 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) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMA... | m webkitpy.common.system.systemhost_mock import MockSystemHost
class PNGCheckerTest(unittest.TestCase):
"""Tests PNGChecker class."""
def test_init(self):
"""Test __init__() method."""
def mock_handle_style_error(self):
pass
checker = PNGChecker("test/config", mock_handl... |
gerardroche/sublime-polyfill | ui.py | Python | bsd-3-clause | 8,584 | 0.000349 | import os
from sublime import active_window
from sublime import find_resources
from sublime import load_settings
from sublime import save_settings
import sublime_plugin
def _load_preferences():
return load_settings('Preferences.sublime-settings')
def _save_preferences():
return save_settings('Preferences.... | ting and interrupt flow
# because where the cursor focus has moved to is not always clear.
self.window.focus_group(active_group_before)
return
if len(self.window.views_in_group(active_group_before)) < 2:
# Only move the active view before | layout change to the new group
# if it doesn't leave the previous group without any views.
return
view = self.window.active_view_in_group(active_group_before)
self.window.set_view_index(view, self.window.active_group(), 0)
class ResetWindowCommand(sublime_plugin.WindowCommand)... |
icereval/osf.io | api/applications/urls.py | Python | apache-2.0 | 417 | 0.007194 | fro | m django.conf.urls import url
from api.applications import views
app_name = 'osf'
urlpatterns = [
url(r'^$', views.ApplicationList.as_view(), name=views.ApplicationList.view_name),
url(r'^(?P<client_id>\w+)/$', views.ApplicationDetail.as_view(), name=views.ApplicationDetail.view_name),
url(r'^(?P<client_... | Reset.view_name),
]
|
Fillll/reddit2telegram | reddit2telegram/channels/~inactive/r_ikeahacks/app.py | Python | mit | 141 | 0.007092 | #e | ncoding:utf-8
subreddit = 'ikeahacks'
t_channel = '@r_IKEAhacks'
def send_post(submission, r2t):
return | r2t.send_simple(submission)
|
FenrirUnbound/greg-ball | libraries/schedule.py | Python | gpl-2.0 | 262 | 0.003817 | from datetime import datetime
class Schedule(object):
WEEK | _ONE = dat | etime(2014, 9, 2, 9)
def week(self):
time_difference = datetime.now() - self.WEEK_ONE
return (time_difference.days/7)+1
def season_year(self):
return 2014
|
auready/django | django/core/cache/backends/filebased.py | Python | bsd-3-clause | 4,845 | 0.000413 | "File-based cache backend"
import glob
import hashlib
import os
import pickle
import random
import tempfile
import time
import zlib
from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache
from django.core.files.move import file_move_safe
from django.utils.encoding import force_bytes
class FileBasedCac... | e.time():
f.close() # On Windows a file has to be closed before deleting
self._delete(f.name)
return True
return False
def _list_cache_files(self):
"""
Get a list of paths to all the cache | files. These are all the files
in the root cache dir that end on the cache_suffix.
"""
if not os.path.exists(self._dir):
return []
filelist = [os.path.join(self._dir, fname) for fname
in glob.glob1(self._dir, '*%s' % self.cache_suffix)]
return fil... |
andreaso/ansible | lib/ansible/modules/cloud/amazon/ec2_vpc_subnet.py | Python | gpl-3.0 | 8,929 | 0.001568 | #!/usr/bin/python
#
# This is a free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This Ansible library is distributed in the hope that i... | uired=True),
state=dict(default='present', choices=['present', 'absent']),
tags=dict(default={}, required=False, type='dict', aliases=['resource_tags']),
vpc_id=dict(defau | lt=None, required=True)
)
)
module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
if not HAS_BOTO:
module.fail_json(msg='boto is required for this module')
region, ec2_url, aws_connect_params = get_aws_connection_info(module)
if region:
try:
... |
luci/luci-py | appengine/components/components/prpc/discovery/service_prpc_pb2.py | Python | apache-2.0 | 29,794 | 0.012016 | # Generated by the pRPC protocol buffer compiler plugin. DO NOT EDIT!
# source: service.proto
import base64
import zlib
from google.protobuf import descriptor_pb2
# Includes description of the service.proto and all of its transitive
# dependencies. Includes source code info.
FILE_DESCRIPTOR_SET = descriptor_pb2.Fil... | S15KV+Dm5cIQ1m5bl5t/QXGW/UuGk1y6'
'zTnhc0m1HbZVevKPe8V562L1UcBGMbnpc8uSjbaJ+SEyY+ptSOvadB8OcQflkJ1+pNiRvrHyb8'
'0mfDLyf+twx5bNFGN70nVFd0Ib | 4r87IXrdXb652VMrU/shY1guZacs7Kf1SnyJ+aWoucU9fbkj'
'9/kMm8M5s7efbEY9mxk7q7s4Y9lXC1EVYx5Lv//ImsN6gOqeeoXxlQGe+xkcIQ/yoe+9SQzy9U'
'o4Z/orO6iuP+KV+jOhT78Ch8VhjVdYSgfG1je6msixufLy/4881q2b9IwsV6u70ZHz9C4yA9GG'
'1SR4ZBGPumEDG1ook44nl+JazVsZRXOnxWj4P3ThwiuUISNgBZqTeD1jbTFU/6W8RNP2rxv1GH'
'6NyIaqSu9IKZ5HN06nmj3i... |
aslab/rct | higgs/trunk/code/ROS/metacontrol/master_monitor/src/master_monitor.py | Python | gpl-3.0 | 3,374 | 0.039123 | #!/usr/bin/env python
import roslib; roslib.load_manifest('master_monitor')
import rospy
from rosgraph_msgs.msg import Log
from syscall import runCmd, runCmdOutput
from move_base_msgs.msg import MoveBaseGoal, MoveBaseAction
from geometry_msgs.msg import PoseStamped
import actionlib
import numpy as np
class ControlMod... | aunched")
return
kinect_recov_launched = True
while not move_base_client.wait_for_server( | rospy.Duration(1.0)) and not rospy.is_shutdown():
rospy.loginfo("Waiting for the move_base action server to come up")
if rospy.is_shutdown():
return
rospy.loginfo("Canceling all active goals")
move_base_client.cancel_all_goals()
rospy.loginfo("Launching Kinect Reconfiguration!")
#Kill SICK laser no... |
com4/eventmq | eventmq/client/__init__.py | Python | lgpl-2.1 | 933 | 0 | # This file is part of eventmq.
#
# eventmq 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.1 of the License, or (at your option)
# any later | version.
#
# eventmq is distributed in the hope that it will be useful,
# but WITHOUT ANY WARR | ANTY; 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
# along with eventmq. If not, see <http://www.gnu.org/licenses/>.
"""
:mod:`clien... |
Logan213/is210-week-04-warmup | tests/test_task_05.py | Python | mpl-2.0 | 1,085 | 0.000922 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests lesson 04 task 05."""
# Import Python libs
import unittest
import mock
import random
class Lesson04Task05TestCase(unittest.TestCase):
"""
Test cases for lesson 04 task 05.
"""
def test_blood_pressure_status(self):
"""
Tests that... | 'ideal': [90, 119],
'warning': [120, 139],
'high': | [140, 159],
'emergency': [160, 256]
}
for key, value in levels.iteritems():
systolic = random.randint(value[0], value[1])
with mock.patch('__builtin__.raw_input', side_effect=[systolic]):
try:
task_05 = reload(task_05)
... |
bshaffer/google-api-php-client-services | generator/src/googleapis/codegen/api.py | Python | apache-2.0 | 37,026 | 0.005888 | #!/usr/bin/python2.7
# Copyright 2010 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | = None
self._surface_features = {}
self._schemas = {}
self._methods_by_name = {}
self._all_methods = []
self.SetTemplateValue('className', self._class_name)
| self.SetTemplateValue('versionNoDots',
self.values['version'].replace('.', '_'))
self.SetTemplateValue('versionNoDash',
self.values['version'].replace('-', '_'))
self.SetTemplateValue('dataWrapper',
'dataWrapper' in discovery_doc.get... |
josiah-wolf-oberholtzer/supriya | dev/etc/pending_ugens/XFadeRotate.py | Python | mit | 3,541 | 0.001977 | import collections
from supriya.enums import CalculationRate
from supriya.synthdefs import MultiOutUGen
class XFadeRotate(MultiOutUGen):
"""
::
>>> source = supriya.ugens.In.ar(bus=0)
>>> xfade_rotate = supriya.ugens.XFadeRotate.ar(
... n=0,
... source=source,
... |
index = self._ordered_input_names.index('n')
return self._inputs[index]
@property
def source(self):
"""
Gets `source` input of XFadeRotate.
::
>>> source = supriya.ugens.In.ar(bus=0)
>>> xfade_rotate = supriya. | ugens.XFadeRotate.ar(
... n=0,
... source=source,
... )
>>> xfade_rotate.source
OutputProxy(
source=In(
bus=0.0,
calculation_rate=CalculationRate.AUDIO,
channel_count=1
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.