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 |
|---|---|---|---|---|---|---|---|---|
algorithm-ninja/konig | legacy/legacy.py | Python | apache-2.0 | 21,057 | 0.010448 | #!/usr/bin/env pypy
# Libreria di funzioni sui grafi.
#
# classe astratta graph, derivate ugraph (grafo non diretto) e dgraph(grafo diretto).
#
# costruttore:
# graph(G[,w]) grafo copia di G
# graph(N[,w]) grafo vuoto con N nodi
# graph(N,E[,w]) grafo con lista di archi assegnata
# graph(N,[M=...],type=... | ameters specified.")
if len(E) > 0 and isinstance(E.__iter__().next(),list):
E = [self.cod(e) for e in E]
E = sortedset(E)
if len(E)==0 and N > 1:
if type == 'cycle':
for i in xrange(N):
E.add(self.cod([i,(i+1)%N]))
... | in xrange(1,N):
E.add(self.cod([randint(i),i]))
if type == 'forest':
if not (0 <= M < N):
raise StandardError("Parameter M out of bounds.")
for i in lsample(N-1,M):
E.add(self.cod([randint(i+1),i+1]))
if... |
MikrosAnim/vulture | vulture/__init__.py | Python | gpl-3.0 | 28 | 0 | f | rom vultu | re import Vulture
|
mikeh77/mi-instrument | mi/instrument/seabird/sbe16plus_v2/test/test_driver.py | Python | bsd-2-clause | 61,730 | 0.007112 | """
@package mi.instrument.seabird.sbe16plus_v2.test.test_driver
@file mi/instrument/seabird/sbe16plus_v2/test/test_driver.py
@author David Everett
@brief Test cases for InstrumentDriver
USAGE:
Make tests verbose and provide stdout
* From the IDK
$ bin/test_driver
$ bin/test_driver -u
$ bin/t... | VALID_SAMPLE2 = "0409DB0A738C81747A84AC0006000A2E541E18BE6ED9" + NEWLINE
VALID_DS_RESPONSE = 'SBE 16plus V 2.5 SERIAL NO. 6841 28 Feb 2013 16:39:31' + NEWLINE + \
'vbatt = 23.4, vlith = 8.0, ioper = 61.4 ma, ipump = 0.3 ma,' + NEWLINE + \
'status = not logging' + NEWLINE + \
's... | val = 10 seconds, number of measurements per sample = 4' + NEWLINE + \
'pump = run pump during sample, delay before sampling = 0.0 seconds, delay after sampling = 0.0 seconds' + NEWLINE + \
'transmit real-time = yes' + NEWLINE + \
'battery cutoff = 7.5 volts' + NEWLINE + \
'pressure sen... |
SureshMatsui/SaveCoin | contrib/linearize/linearize.py | Python | mit | 3,354 | 0.034287 | #!/usr/bin/python
#
# linearize.py: Construct a linear, no-fork, best version of the blockchain.
#
#
# Copyright (c) 2013 The SaveCoin developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
import json
import struct
imp... |
resp_obj = json.loads(body)
if resp_obj is None:
print "JSON-RPC: cannot JSON-decode body"
return None
if 'error' in resp_obj and resp_obj['error'] != None:
return resp_obj['error']
if 'result' not in resp_obj:
print "JSON-RPC: no result in object"
return None
return resp_obj['result']
def g... | , verbose])
def getblockhash(self, index):
return self.rpc('getblockhash', [index])
def getblock(rpc, settings, n):
hash = rpc.getblockhash(n)
hexdata = rpc.getblock(hash, False)
data = hexdata.decode('hex')
return data
def get_blocks(settings):
rpc = SaveCoinRPC(settings['host'], settings['port'],
setti... |
gewaltig/cython-neuron | topology/examples/grid_iaf_irr.py | Python | gpl-2.0 | 1,646 | 0.001823 | #! /usr/bin/env python
#
# grid_iaf_irr.py
#
# This file is part of NEST.
#
# Copyright (C) 2004 The NEST Initiative
#
# NEST 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... | ual', 'box')
pylab.axes().set_xticks((-0.75, -0.25, 0.25, 0.75))
pylab.axes().set_yticks((-0.5, 0, 0.5))
pylab.grid(True)
pylab.xlabel('4 Columns, Extent: 1.5')
pylab.ylabel('2 R | ows, Extent: 1.0')
# pylab.savefig('grid_iaf_irr.png')
|
maciejkula/glove-python | glove/corpus.py | Python | apache-2.0 | 2,667 | 0.000375 | # Cooccurrence matrix construction tools
# for fitting the GloVe model.
import numpy as np
try:
# Python 2 compat
import cPickle as pickle
except ImportError:
import pickle
from .corpus_cython import construct_cooccurrence_matrix
class Corpus(object):
"""
Class for constructing a cooccurrence mat... | y (if it was supplied).
| Context window distances will be preserved
even if out-of-vocabulary words are
ignored.
If False, a KeyError is raised.
"""
self.matrix = construct_cooccurrence_matrix(corpus,
... |
escapewindow/python-scriptharness | scriptharness/structures.py | Python | mpl-2.0 | 25,153 | 0.000398 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Data structures for configs.
There are two config dict models here:
* LoggingDict logs any changes to the dict or its children. When debugging,
config changes will be marked in the log. This is the default model.
* ReadOnlyDict recursively locks the dictionary. ... | """If child is a Logging* instance, set its parent and name.
Args:
child (Any): an object, which might be a Logging* instance
| child_name (str): the name to set in the child
"""
if is_logging_class(child):
child.recursively_set_parent(child_name, parent=self)
def ancestor_child_list(self, child_list=None):
"""Get the original ancestor of self, and the descending, linear list
of descendents... |
ctSkennerton/BioSQL-Extensions | scripts/add_annotation_to_protein.py | Python | mit | 9,369 | 0.004483 | #!/usr/bin/env python
from __future__ import print_function
import sys
from BioSQL import BioSeqDatabase
from BioSQL import Loader
from common import standard_options, get_seqfeature_id_from_qv
import csv
class CustomDBLoader(Loader.DatabaseLoader):
"""This is a slightly modified version of Loader.DatabaseLoader
... | be checked to make sure that there
is no collision between current annotations, if there | is the rank of the
new features will be changed to prevent collisions
"""
tag_ontology_id = self._get_ontology_id('Annotation Tags')
for qualifier_key in qualifiers:
# Treat db_xref qualifiers differently to sequence annotation
# qualif... |
richardcornish/django-itunespodcast | podcast/tests/__init__.py | Python | bsd-3-clause | 5,519 | 0.003443 | from __future__ import unicode_literals
import os
import datetime
from django.test import TestCase, Client, override_settings
from django.utils import timezone
from ..models import Show, Episode, Enclosure
try:
from django.urls import reverse
except ImportError:
from django.core.urlresolvers import reverse
... | re(datetime.datetime.strptime('2016-03-10T09:00:00', '%Y-%m-%dT%H:%M:%S')),
summary='Jane and Eric',
author_name='Jane Doe',
image='podcast/tests/static/everything/AllAboutEverything/Episode3.jpg',
explicit=False,
block=False,
)
# episode 4
... | objects.create(
show=show,
title='Red,Whine, & Blue',
slug='red-whine-blue',
description='This week we talk about surviving in a Red state if you are a Blue person. Or vice versa.',
pub_date=timezone.make_aware(datetime.datetime.strptime('2016-03-10T22:15:00',... |
shankari/e-mission-server | emission/core/wrapper/section.py | Python | bsd-3-clause | 2,128 | 0.012688 | from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
import logging
import emission.core.wrapper.wrapperbase as ecwb
import emissi... | #***** searchable datetime in local time of end location
"end_fmt_time": ecwb.WrapperBase.Access.WORM, # ******end formatted time (in timezone of point)
"start_stop": ecwb.WrapperBase.Access.WORM, # _id of place object before this one
"end_stop": ecwb.WrapperBase.Access.WORM, ... | "end_loc": ecwb.WrapperBase.Access.WORM, # location of end point in geojson format
"duration": ecwb.WrapperBase.Access.WORM, # duration of the trip in secs
"sensed_mode": ecwb.WrapperBase.Access.WORM, # the sensed mode used for the segmentation
"source": ecwb.Wrapp... |
postla/e2-gui | lib/python/Components/opkg.py | Python | gpl-2.0 | 1,535 | 0.033225 | import os
def enumFeeds():
for fn in os.listdir('/etc/opkg'):
if fn.endswith('-feed.conf'):
try:
for feed in open(os.path.join('/etc/opkg', fn)):
yield feed.split()[1]
except IndexError:
pass
except IOError:
pass
def enumPlugins(filter_start=''):
for feed in enumFeeds():
package = None... | if line.startswith('Version:'):
version = line.split(":",1)[1].strip()
elif line.startswith('Description:'):
description = line.split(":",1)[1].strip()
elif description and li | ne.startswith(' '):
description += line[:-1]
elif len(line) <= 1:
d = description.split(' ',3)
if len(d) > 3:
# Get rid of annoying "version" and package repeating strings
if d[1] == 'version':
description = d[3]
if description.startswith('gitAUTOINC'):
description = d... |
yank-team/yank-server | auth/models.py | Python | apache-2.0 | 248 | 0.012097 | from django.db | import models
class YankUser(models.Model):
username = models.CharField(max_length=98, unique=True)
password_digest = models.CharField(max_l | ength=128)
api_key = models.CharField(max_length=128, null=True)
|
sergeimoiseev/othodi_code | old/mpl_msk_spb.py | Python | mit | 1,018 | 0.034381 | # -*- coding: utf-8 -*-
# http://matplotlib.org/basemap/users/examples.html
from mpl_toolkits.basemap import Basemap
import numpy as np
import matplotlib.pyplot as plt
# create new figure, axes instances.
fig=plt.figure()
ax=fig.add_axes([0.1,0.1,0.8,0.8])
# setup mercator map projection.
m = Basemap(llcrnrlon=0.,llcrn... | ndon.
lonlat = 59.9386300; lonlon = 30.3141300
# draw great circle route between NY and London
m.drawgreatcircle(nylon,nylat,lonlon,lonlat,linewidth=2,color='b')
m.drawcoastlines()
m.fillcontinents()
# draw parallels
m.drawparallels(np.arange(-20 | ,0,20),labels=[1,1,0,1])
# draw meridians
m.drawmeridians(np.arange(-180,180,30),labels=[1,1,0,1])
ax.set_title('Great Circle from New York to London')
plt.show() |
izhan/Stream-Framework | stream_framework/serializers/aggregated_activity_serializer.py | Python | bsd-3-clause | 4,616 | 0.00065 | from stream_framework.activity import Activity
from stream_framework.exceptions import SerializationException
from stream_framework.serializers.activity_serializer import ActivitySerializer
from stream_framework.serializers.utils import check_reserved
from stream_framework.utils import epoch_to_datetime, datetime_to_ep... | d_activities = []
if self.dehydrate:
if no | t aggregated.dehydrated:
aggregated = aggregated.get_dehydrated()
serialized_activities = map(str, aggregated._activity_ids)
else:
for activity in aggregated.activities:
serialized = activity_serializer.dumps(activity)
# we use semicolons a... |
tuanquanghpvn/rest_exam | apps/category/mappers.py | Python | mit | 2,523 | 0.000793 | from marshmallow import (Schema, fields, post_load, validates_schema)
from contracts.category import (GetCategoryRequest, GetCategoryResponse,
DetailCategoryRequest, DetailCategoryResponse,
PostCategoryRequest, PutCategoryRequest, DeleteCategoryRequest)
fr... |
include_key = [CATEGORY_ID]
_check_include_fields(data, require_key, include_key)
class PostCategoryRequestSchema(CategorySchema) | :
@post_load
def make_contract(self, data):
return PostCategoryRequest(**data)
@validates_schema
def check_require_include_fields(self, data):
require_key = [NAME, SLUG]
include_key = [NAME, SLUG]
_check_include_fields(data, require_key, include_key)
class PutCategoryR... |
robin1885/algorithms-exercises-using-python | source-code-from-author-book/Listings-for-Second-Edition/listing_6_20.py | Python | mit | 488 | 0.006148 | def percDo | wn(self,i):
while (i * 2) <= self.currentSize:
mc = self.minChild(i)
if self.heapList[i] > self.heapList[mc]:
tmp = self.heapList[i]
self.heapList[i] = self.heapList[mc]
self.heapList[mc] = tmp
i = mc
def minChild(self,i):
if i * 2 + 1 > self.currentS... | 1
|
diana-hep/femtocode | lang/femtocode/thirdparty/meta/asttools/visitors/copy_tree.py | Python | apache-2.0 | 1,255 | 0.003984 | '''
Created on Dec 12, 2011
@author: sean
'''
from . import Visitor
import ast
#FIXME: add tests
class CopyVisitor(Visitor):
'''
Copy only ast nodes and lists
'''
def visitDefault(self, node):
Node = type(node)
new_node = Node()
for _field in Node._fields:
... |
setattr(new_node, _field, new_list)
elif isinstance(field, ast.AST):
setattr(new_node, _field, self.visit(field))
else:
setattr(new_node, _field, field)
for _at | tr in node._attributes:
if hasattr(node, _attr):
setattr(new_node, _attr, getattr(node, _attr))
return new_node
def copy_node(node):
return CopyVisitor().visit(node)
|
Geheimorganisation/sltv | sltv/effect/video_effect.py | Python | gpl-2.0 | 1,698 | 0.002357 | # -*- coding: utf-8 -*-
# Copyright (C) 2010 Holoscópio Tecnologia
# Author: Luciana Fujii Pontello <luciana@holoscopio.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... | ffect.__init__(self)
self.convertion1 = gst.element_factory_make(
"ffmpegcolorspace", "effect_colorspace1"
)
self.add(self.convertion1)
self.convertion2 = gst.element_factory_make(
"ffmpegcolorspace", "effect_colorspace2"
)
self.add(self.c... | = gst.element_factory_make(effect_name, effect_name)
self.add(self.effect_element)
gst.element_link_many(
self.convertion1, self.effect_element, self.convertion2
)
self.sink_pad.set_target(self.convertion1.sink_pads().next())
self.src_pad.set_target(self.conver... |
mLewisLogic/foursquare | foursquare/tests/test_oauth.py | Python | mit | 444 | 0.004505 | #!/usr/bin/env python
# -*- | coding: UTF-8 -*-
# (c) 2020 Mike Lewis
import logging
log = logging.getLogger(__name__)
from . import BaseAuthenticationTestCase
import six
class OAuthEndpointTestCase(BaseAuthenticationTestCase):
def test_auth_url(self):
url = self.api.oauth.auth_url()
assert isinstance(url, six.string_types)... | lf):
# Honestly, not much we can do to test here
pass
|
bitmovin/bitmovin-python | bitmovin/resources/enums/h264_b_pyramid.py | Python | unlicense | 107 | 0 | import enum
class H264BPyramid(enum.Enum):
NONE = 'NONE'
STR | ICT = 'STRIC | T'
NORMAL = 'NORMAL'
|
asyncee/cookiecutter-django | {{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/taskapp/celery.py | Python | bsd-3-clause | 1,701 | 0.01117 | {% if cookiecutter.use_celery == 'y' %}
import os
from celery import Celery
from django. | apps import apps, AppConfig
from django.conf import settings
if not settings.configured:
# set the | default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.local') # pragma: no cover
app = Celery('{{cookiecutter.project_slug}}')
class CeleryConfig(AppConfig):
name = '{{cookiecutter.project_slug}}.taskapp'
verbose_name = 'Celery Config... |
kitaro-tn/msgiver | msgiver/configure.py | Python | mit | 1,918 | 0.00365 | # -*- coding: utf-8 -*-
import os
import yaml
from six.moves import input
class Configure:
"""
msgiver configuration class
"""
CONF_FILE_PATH = os.path.join(os.environ.get("HOME"), ".msgiver.yml")
def __init__(self):
self.__conf = None
if os.path.exists(self.CONF_FILE_PATH):... | L"), | 'bot_icon': None}
else:
return self.__conf['slack']
def generate(self):
config_data = {}
config_data["slack"] = self.__input_slack()
with open(self.CONF_FILE_PATH, "w") as config_file:
yaml.dump(config_data, config_file, default_flow_style=False)
re... |
3D-e-Chem/rdkit-react | setup.py | Python | apache-2.0 | 639 | 0.001565 | from setuptools import setup, find_packages
exec(open('react/version.py').read())
setup(
name='reac | t',
description='Generate fragments of a molecule using smirks',
version=__version__,
packages=find_packages(),
url='https://github.com/3D-e-Chem/python-modified-tanimoto',
author='Stefan Verhoeven',
author_email='s.verhoeven@esciencecenter.nl',
install_requires=['nose', 'coverage', 'mock'],... | Software License'
]
) |
mahim97/zulip | zerver/tests/test_typing.py | Python | apache-2.0 | 11,021 | 0.002359 | # -*- coding: utf-8 -*-
import ujson
from typing import Any, Mapping, List
from zerver.lib.test_helpers import tornado_redirected_to_list, get_display_recipient
from zerver.lib.test_classes import (
ZulipTestCase,
)
from zerver.models import get_realm, get_user
class TypingNotificationOperatorTest(ZulipTestCase)... | set(user['email'] for user in event['recipients'])
event_user_ids = set(events[0]['users'])
event_recipient_user_ids = set(user['user_id'] for user in event['recipients'])
self.assertEqual(expected_recipient_ids, event_recipient_user_ids)
self.assertEqual(expected_recipient_ids, even | t_user_ids)
self.assertEqual(event_recipient_emails, expected_recipient_emails)
self.assertEqual(event['sender']['email'], sender.email)
self.assertEqual(event['type'], 'typing')
self.assertEqual(event['op'], 'start')
class StoppedTypingNotificationTest(ZulipTestCase):
def test_send... |
plotly/plotly.py | packages/python/plotly/plotly/validators/bar/hoverlabel/_alignsrc.py | Python | mit | 403 | 0.002481 | import _plotly_utils.basevalidators
class AlignsrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(s | elf, plotly_name="alignsrc", parent_name="bar.hoverlabel", **kwargs):
super(AlignsrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type | ", "none"),
**kwargs
)
|
jvictor0/TiaraBoom | tiara/data_gatherer.py | Python | mit | 46,191 | 0.00656 |
import database as db
import vocab as v
import conversation
import random
import time
import json
import datetime
import os
import math
import union_find
from twitter.status import Status
from twitter.user import User
from evidence import data_manager
from util import *
import threading
import tiara_ddl
impor... | not found, not allowed, suspended, not existing
self.InsertUngettable(tid, self.ApiHandler().errno)
return True
self.g_data.Trac | eWarn("Unhandled error in InsertTweetById %d" % self.ApiHandler().errno)
assert False
return None
def InsertUser(self, user):
uid = str(user.GetId())
sn = "'%s'" % user.GetScreenName().encode("utf8")
folls = str(user.GetFollowersCount())
friens = str... |
BorgERP/borg-erp-6of3 | verticals/garage61/acy_partner_vehicle/invoice.py | Python | agpl-3.0 | 1,362 | 0.002937 | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (c) 2010 Acysos S.L. (http://acysos.com) All Rights Reserved.
# Ignacio Ibeas <ignacio@acysos.com>
# $Id$
#
# This program i... | org/licenses/>.
#
##############################################################################
from osv import osv, fields
import tools
import os
| # Sale order
class account_invoice(osv.osv):
_inherit = 'account.invoice'
_columns = {
'vehicle_id': fields.many2one('res.partner.vehicle', 'Vehicle', readonly=True, states={'draft': [('readonly', False)]}, required=False),
}
account_invoice() |
josiahhardacre/Week-Four-Assignment | pigify.py | Python | mit | 562 | 0.019573 | #
# File Header
#
# Define vowels
vowels = "aeiouAEIOU" #I solved the case sensitivity by adding the vowels in both lowercase and uppercase.
# Ask for word
word = input("Please enter a word: ")
if (originalwo | rd[0] in vowels):
print((originalword + endofvowel).capitalize())
else:
print((originalword[1:] + originalword[0] + endofconsonant).capitalize())
# Loop through word, one letter at a time
for letter in word:
if letter in vowels:
pig = word + "yay"
else:
# False? | Consonant
pig = word[1:] + word[0] + "ay"
print(pig)
|
leosartaj/autosign | tests/test_removeSign.py | Python | mit | 1,228 | 0.004886 | #!/usr/bin/env python2
##
# autosign
# https://github.com/leosartaj/autosign.git
#
# copyright (c) 2014 sartaj singh
# licensed under the mit license.
##
import unittest
import os, shutil
import helper
from autosign.main import removeSign, isSign
from autosign.exce import UnsignedError
class TestremoveSign(unittest... | til.copyfile(self.signedfile, self.signed)
self.unsigned = os.path.join(self.dire, 'testData/test_unsignedfile.py')
helper.newFile(self.unsigned)
| helper.readrc(self)
def test_remove_from_unsigned_file(self):
self.assertRaises(UnsignedError, removeSign, self.unsigned, self.options_py)
def test_remove_from_signed_file(self):
self.assertTrue(isSign(self.signed, self.options_py))
removeSign(self.signed, self.options_py)
s... |
Gebesa-Dev/Addons-gebesa | mrp_segment/models/procurement_order.py | Python | agpl-3.0 | 327 | 0 | # -*- coding: utf-8 -*-
# © <YEAR(S)> <AUTHOR(S)>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import fields, models
class ProcurementOrder(models.Model):
_inherit = 'procurement.order'
related_segment = fields.Char(
strin | g='Rela | tad Segment',
default='',
)
|
open-rnd/ros3d-www | ros3dui/system/camera.py | Python | mit | 3,863 | 0.001812 | #
# Copyright (c) 2015 Open-RnD Sp. z o.o.
#
# 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, publ... | _log.debug('device state: %d', p | rops.State)
cam = dict(name=props.Id, value=props.State)
camera_data.append(cam)
except dbus.exceptions.DBusException, error:
_log.error('camera controller service unavaialble, error: %s', error)
raise CameraManagerError('Camera Controller service unavaila... |
zenoss/ZenPacks.community.Cfengine | ZenPacks/community/Cfengine/modeler/plugins/community/cfenginemodeler.py | Python | gpl-2.0 | 2,493 | 0.010429 | import re, os
from Products.ZenUtils.Utils import zenPath
from Products.DataCollector.plugins.DataMaps import MultiArgs
from Products.DataCollector.plugins.CollectorPlugin import PythonPlugin
class cfenginemodeler(PythonPlugin):
"""
Parse the zCfengineComplianceFile to get the compliance status for devices.
... | ts
#push the results into the model
def process(self, device, results, log):
log.info('Processing cfengine client list for device %s' % device.id)
self.modname = 'ZenPacks.community.Cfengine.CfengineClient'
self.relname = "cfengineclients"
serverId = device.getId()
rm = self.re... | f re.search(',', line):
om.cfcDisplayName, om.cfcDeviceClass, value = line.split(',')
if om.cfcDeviceClass == "any":
om.cfcDeviceClass == "/Discovered"
om.cfcCompliance = int(value)
log.debug('Collecting cfengine client list for device ... |
eta4ever/dimmer485 | host/test2.py | Python | gpl-3.0 | 523 | 0.022945 | from comm485 import Conn485
from device485 import Device
import time
conn = Conn485()
time | .sleep(0.1)
# led1 = Device("led1","pwm")
# led1.init_as_hardware(60, [0,0], conn)
enc1 = Device("enc1", "encoder", 1)
enc1.init_as_hardware(50, [0,0], conn)
# dummy = input(">")
try:
while True:
# time.sleep(0.1)
# print(led1.write_registers([100,1],conn))
# time | .sleep(0.1)
# print(led1.write_registers([200,0],conn))
time.sleep(0.1)
enc1.read_registers(conn)
print (enc1.get_registers())
finally:
del conn |
trigger-happy/conan-packages | libharu/conanfile.py | Python | mit | 1,457 | 0.002059 | from conans import ConanFile, AutoToolsBuildEnvironment, tools
import os
class LibHaruConn | (ConanFile):
name = "libharu"
version = "2.3.0"
license = "ZLIB https://github.com/libharu/libharu/bl | ob/master/LICENCE"
url = "https://github.com/trigger-happy/conan-packages"
description = "C library for generating PDF documents"
settings = "os", "compiler", "build_type", "arch"
options = {"shared": [True, False]}
default_options = "shared=False"
generators = "cmake"
def source(self):
... |
tadhg-ohiggins/regulations-parser | regparser/tree/depth/derive.py | Python | cc0-1.0 | 5,957 | 0 | from collections import namedtuple
from constraint import Problem
from regparser.tree.depth import markers, rules
from regparser.tree.depth.pair_rules import pair_rules
from regparser.tree.struct import Node
# A paragraph's type, index, depth assignment
ParAssignment = namedtuple('ParAssignment', ('typ', 'idx', 'dep... | gramming to derive the paragraph depths associated
with a list of paragraph markers. Additional constraints (e.g. expected
marker types, etc.) can also be added. Such constraints are functions of
tw | o parameters, the constraint function (problem.addConstraint) and a
list of all variables"""
if additional_constraints is None:
additional_constraints = []
if not original_markers:
return []
problem = Problem()
marker_list = _compress_markerless(original_markers)
# Depth in the ... |
david-ragazzi/nupic | examples/opf/clients/hotgym/simple/model_params.py | Python | gpl-3.0 | 8,905 | 0.002021 |
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the... | The number of cells (i.e., states), allocated per column.
'cellsPerColumn': 32,
'inputWidth': 2048,
'seed': 1960,
# Temporal Pooler implementation selecto | r (see _getTPClass in
# CLARegion.py).
'temporalImp': 'cpp',
# New Synapse formation count
# NOTE: If None, use spNumActivePerInhArea
#
# TODO: need better explanation
'newSynapseCount': 20,
# Maximum number of synapses pe... |
fcalo/bbqtv | bbqtv/services/db.py | Python | gpl-3.0 | 1,892 | 0.016913 | from pymongo import MongoClient
from datetime import datetime
class DB(object):
def __init__(self):
pass
def init_app(self, app):
self.db = MongoClient(host = app.config['DB_HOST'],
port = app.config['DB_PORT'])[app.config['DB_NAME']]
def get_channels(self, limi... | self.db.channels.find().sort("order", 1)
def get_grid(self):
grid = {}
for c in self.get_channels(limit = 7):
grid[c['name']] = self.get_channel_day(c['_id'], datetime.now())
return grid
def get_now(self):
grid = {}
for c in self.get_chann... | gramme = None
grid[c['name']] = {}
for programme in day['programmes']:
hour_pro, minute_pro = [int(a) for a in programme['time'].split(":")]
if hour < hour_pro or ( hour == hour_pro and minute <= minute_pro):
g... |
tommeagher/pycar14 | project4/step_3_complete.py | Python | mit | 1,081 | 0.002775 | #!/usr/bin/env python
import csv
import json
import requests
def main():
# We'll use a local version of this file from now on to save on
# bandwith.
with open('bills.json', 'r') as f:
data = json.load(f)
objects = data['objects']
# Create a csv file to output
with open('b... | ectly.
writer = csv.writer(o)
# Write out the header row
writer.writerow([
u'title',
u'label',
u'number',
u'current_status'
])
# Iterate through each dict in the array `objects`
for ... | bjects:
writer.writerow([
bill['title_without_number'].encode('utf-8'),
bill['bill_type_label'].encode('utf-8'),
bill['number'],
bill['current_status'].encode('utf-8')
])
if __name__ == '__main__':
main(... |
ilya-ilya/nikolayfs | fs.py | Python | gpl-2.0 | 3,194 | 0.038823 | """
Main module that use fuse to provide filesystem
"""
import os
import sys
import llfuse
import errno
import auth
import requests
import json
import re
import datetime
import time
FILES = "https://www.googleapis.com/drive/v2/files/"
def countMode(meta):
"""
count file mode
"""
mod | e = 0
if meta["mimeType"].split(".")[-1] == u"folder":
mode +=
def timeRFC3339(dateStr):
"""
Extract time from Epoch from date string
"""
mat = re.match(r"^(\d+)-(\d+)-$",\ |
dateStr)
return time.mktime(\
datetime.datetime(\
int(mat.group(1)),\
int(mat.group(2)),\
int(mat.group(3)),\
int(mat.group(4)),\
int(mat.group(5)),\
int(mat.group(6))\
).timetuple()\
)
def id2inode(sid):
"""
convert google id to inode number
"""
if sid == u"root":
return 1
else:
... |
lfasmpao/safecore-api | dashboard/forms.py | Python | agpl-3.0 | 4,140 | 0.007488 | from flask_wtf import FlaskForm
from . import app
from wtforms import StringField, PasswordField, SelectField, DateField, IntegerField
from wtforms.validators import DataRequired, Length, Email, EqualTo, Optional, NumberRange
from wtfrecaptcha.fields import RecaptchaField
from flask_wtf.file import FileField, FileAllow... | secure=True)
class LicenseKeyForm(FlaskForm):
category = SelectField('Category', choices=[(1, 'Premium'), (2, 'VIP')], coerce=int)
license_key = StringField('License Key', validators=[DataRequired(), Length(min=29, max=29)])
username = StringField('Sender Username', validators=[DataRequired(), L... | StringField('Sender Username', validators=[DataRequired(), Length(min=4, max=40)])
class ImageUpload(FlaskForm):
upload = FileField('Image Upload', validators=[FileRequired(), FileAllowed(['jpg', 'png'], 'Images only!')])
class BuyLicense(FlaskForm):
category = SelectField('Category', choices=[(1, 'VIP'), (... |
avkhadiev/bbtoDijet | bbtoDijetAnalyzer/test/crab_test_bbtoDijetAnalyzer_test/crab_bbtoDijetAnalyzer_test/inputs/PSet.py | Python | mit | 101 | 0 | import FWCo | re.ParameterSet.Config as cms
import pickle
proce | ss = pickle.load(open('PSet.pkl', 'rb'))
|
atwardowski/Dramiel | src/twisted/mod/tableflip.py | Python | mit | 320 | 0.009804 | # -*- coding: utf-8 -*-
f | rom modules.upsidedown.upsidedown import transform as upsidedown
def tableflip(tbot, user, channel, msg):
text = msg.replace('!tableflip', '').strip()
flipped = upsidedown(text)
tbot.msg(channel,u"%s: (╯°□°)╯︵ %s" % (user, flipped))
tableflip.rule = "!tableflip | (.*)"
|
magfest/ubersystem | alembic/versions/bba880ef5bbd_add_is_loud_and_pronouns_columns_to_.py | Python | agpl-3.0 | 2,103 | 0.005231 | """Add is_loud and pronouns columns to PanelApplicant
Revision ID: bba880ef5bbd
Revises: 8f8419ebcf27
Create Date: 2019-07-20 02:57:17.794469
"""
# revision identifiers, used by Alembic.
revision = 'bba880ef5bbd'
down_revision = '8f8419ebcf27'
branch_labels = None
depends_on = None
from alembic import op
import sq... | tch_op.alter_column('column_name', type_=sa.Unicode(), ser | ver_default='', nullable=False)
# else:
# op.alter_column('table_name', 'column_name', type_=sa.Unicode(), server_default='', nullable=False)
#
# ===========================================================================
def upgrade():
op.add_column('panel_applicant', sa.Column('other_pronouns', sa.U... |
jeromecc/doctoctocbot | src/bot/migrations/0005_auto_20200603_0508.py | Python | mpl-2.0 | 633 | 0 | # Generated by Django 2.2.12 on 2020-06-03 03:08
from django.db imp | ort migrations, models
class Migration(migrations.Migration):
dependencies = [
('bot', '0004_auto_20191013_2322'),
]
operations = [
migrations.AddField(
| model_name='account',
name='email',
field=models.CharField(default='', max_length=128),
preserve_default=False,
),
migrations.AddField(
model_name='account',
name='password',
field=models.CharField(default='', max_length=128... |
brainheart/dce_lti_py | dce_lti_py/tool_consumer.py | Python | mit | 2,381 | 0.0021 |
from requests import Request
from oauthlib.common import unquote
from requests_oauthlib import OAuth1
from requests_oauthlib.oauth1_auth import SIGNATURE_TYPE_BODY
from tool_base import ToolBase
from launch_params import LAUNCH_PARAMS_REQUIRED
from utils import parse_qs, InvalidLTIConfigError, generate_identifier
cl... | uper(ToolConsumer, self).__init__(consumer_key, consumer_secret,
params=params)
def has_required_params(self):
return all([
self.launch_params.get(x) for x in LAUNCH_PARAMS_REQUIRED
])
def generate_launch_request(self, **kwargs):
"... | LTIConfigError(
'Consumer\'s launch params missing one of ' \
+ str(LAUNCH_PARAMS_REQUIRED)
)
# if 'oauth_consumer_key' not in self.launch_params:
# self.launch_params['oauth_consumer_key'] = self.consumer_key
params = self.to_params()
r = ... |
wodo/django-ct | tests/settings.py | Python | bsd-2-clause | 5,129 | 0.002925 | # Django settings for tests project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'tests/da... | or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
#'django.contrib.auth',
#'django.contrib.contenttypes',
#'django.con | trib.sessions',
#'django.contrib.sites',
#'django.contrib.messages',
#'django.contrib.staticfiles',
#'django.contrib.admin',
'ct',
'tests',
)
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 ... |
Dawny33/Code | CodeChef/CDAV14/PND.py | Python | gpl-3.0 | 134 | 0 | T = | input()
while(T):
T -= 1
s = input()
| s = str(oct(s))
if s == s[::-1]:
print 1
else:
print -1
|
InUrSys/PescArt2.0 | GeneratedFiles/ui_addRulesToForm.py | Python | gpl-3.0 | 5,232 | 0.002867 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/Users/chernomirdinmacuvele/Documents/workspace/PescArt2.0/UserInt/ui_addRulesToForm.ui'
#
# Created by: PyQt5 UI code generator 5.8.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
clas... | addWidget(self.PBAdd, 1, 1, 1, 1)
self.PBEdit = QtWidgets.QPushButton(self.layoutWidget2)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(... | self.PBEdit.setText("")
icon1 = QtGui.QIcon()
icon1.addPixmap(QtGui.QPixmap(":/newPrefix/Icons/005-writer.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.PBEdit.setIcon(icon1)
self.PBEdit.setObjectName("PBEdit")
self.gridLayout_3.addWidget(self.PBEdit, 0, 1, 1, 1)
s... |
dahlstrom-g/intellij-community | python/testData/inspections/PyAbstractClassInspection/quickFix/AddABCToSuperclasses/main_import.py | Python | apache-2.0 | 85 | 0.023529 | import abc
class A1(abc.ABC):
| @abc.abstractmethod
def m1(self): |
pass |
ormnv/os_final_project | osfinalproject/migrations/0001_initial.py | Python | bsd-3-clause | 1,936 | 0.002066 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Answer',
fields=[
('id', models.AutoField(verbo... | ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('question_text', m | odels.TextField()),
('pub_date', models.DateTimeField(auto_now_add=True)),
('votes', models.IntegerField()),
],
options={
},
bases=(models.Model,),
),
migrations.CreateModel(
name='Vote',
fields=[
... |
lilida/teletraan | deploy-agent/tests/unit/deploy/staging/test_helper.py | Python | apache-2.0 | 4,299 | 0.001861 | # Copyright 2016 Pinterest, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | er_role)
if not os.path.exists(tarball_dir):
os | .mkdir(tarball_dir)
script_dir = os.path.join(tarball_dir, "teletraan")
if not os.path.exists(script_dir):
os.mkdir(script_dir)
self.assertTrue(Stager(config=self.config, transformer=self.transformer,
build="24714bc", target=self.target,
... |
brennie/reviewboard | reviewboard/scmtools/tests/test_svn.py | Python | mit | 22,242 | 0 | # coding=utf-8
from __future__ import unicode_literals
import os
from hashlib import md5
import nose
from django.conf import settings
from kgb import SpyAgency
from reviewboard.diffviewer.diffutils import patch
from reviewboard.scmtools.core import (Branch, Commit, Revision, HEAD,
... | lf.tool.parse_diff_revision('', '(版本 7)')[1],
'7')
def test_revision_parsing_with_nonexistent(self):
"""Testing SVN (<backend>) revision parsing with "(nonexistent)"
revision indicator
"""
# English
self.assertEqual(
self.tool.parse_diff_... | PRE_CREATION)
# Simplified Chinese
self.assertEqual(
self.tool.parse_diff_revision('', '(不存在的)')[1],
PRE_CREATION)
def test_revision_parsing_with_nonexistent_and_branches(self):
"""Testing SVN (<backend>) revision parsing with relocation
information and... |
lkhomenk/integration_tests | cfme/tests/configure/test_tag_category.py | Python | gpl-2.0 | 3,472 | 0.000864 | # -*- coding: utf-8 -*-
import fauxfactory
import pytest
from cfme.configure.configuration.region_settings import Category
from cfme.rest.gen_data import categories as _categories
from cfme.utils.rest import (
assert_response,
delete_resources_from_collection,
delete_resources_from_detail,
)
from cfme.util... | tegories.
Metadata:
test_flag: rest
"""
collection = appliance.rest_api.collections.categories
categories_len = len(categories)
new = []
for _ in range(categories_len):
new.append(
{'description': 'test_category_{}'.format(fauxfact... | date(categories[index]._ref_repr())
edited = collection.action.edit(*new)
assert_response(appliance)
else:
edited = []
for index in range(categories_len):
edited.append(categories[index].action.edit(**new[index]))
assert_response(ap... |
jaeminSon/V-GAN | codes/train.py | Python | mit | 6,553 | 0.020449 | import numpy as np
from model import GAN, discriminator_pixel, discriminator_image, discriminator_patch1, discriminator_patch2, generator, discriminator_dummy
import utils
import os
from PIL import Image
import argparse
from keras import backend as K
# arrange arguments
parser=argparse.ArgumentParser()
parser.add_arg... | n_round,FLAGS.discriminator,FLAGS.ratio_gan2seg)),'w') as f:
f.write(g.to_json())
g.save_weights(os.path.join(model_out_dir,"g_{}_{}_{}.h5".format(n_round,FLAGS.discriminator,FLAGS.ratio_gan2seg) | ))
# update step sizes, learning rates
scheduler.update_steps(n_round)
K.set_value(d.optimizer.lr, scheduler.get_lr())
K.set_value(gan.optimizer.lr, scheduler.get_lr())
# evaluate on test images
if n_round in rounds_for_evaluation:
generated=g.predict(test_imgs,b... |
dubrayn/dubrayn.github.io | examples/threading/example0.py | Python | mit | 143 | 0.048951 | #! | /usr/bin/env python3
import threading
def worker():
print('new worker')
for i in range(8):
threading.Thread( | target = worker).start()
|
AuthentiqID/examples-flask | example_dance.py | Python | mit | 2,000 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Flask-Dance example.
This example demonstrates how to integrate a server application with
Authentiq Connect. It uses the popular Flask-Dance package to make
this trivial in Flask.
"""
from __future__ import (
absolute_import,
division,
print_function,
u... | ort ProxyFix
class Config(object):
"""
Flask configuration container.
"""
DEBUG = True
TESTING = False
SECRET_KEY = "aicahquohzieRah5ZooLoo3a"
# The following app is registered at Authentiq Connect.
CLIENT_ID = | os.environ.get("CLIENT_ID", "examples-flask-basic")
CLIENT_SECRET = os.environ.get("CLIENT_SECRET", "ed25519")
# Personal details requested from the user. See the "scopes_supported" key in
# the following JSON document for an up to date list of supported scopes:
#
# https://connect.authentiq.io/.well-known/openid-c... |
openai/universe | universe/wrappers/experimental/action_space.py | Python | mit | 6,525 | 0.003525 | import logging
import gym
import numpy as np
from universe import spaces
from universe import vectorized
from universe.wrappers.gym_core import gym_core_action_space
logger = logging.getLogger(__name__)
def slither_vnc(space=False, left=False, right=False):
return [spaces.KeyEvent.by_name('space', down=space),
... | spaces.KeyEvent.by_name('right', down=right)]
def platfor | m_vnc(up=False, left=False, right=False, space=False):
return [spaces.KeyEvent.by_name('up', down=up),
spaces.KeyEvent.by_name('left', down=left),
spaces.KeyEvent.by_name('right', down=right),
spaces.KeyEvent.by_name('space', down=space)]
class SafeActionSpace(vectorized.Wrappe... |
mkaluza/python-enum | enum/__init__.py | Python | gpl-3.0 | 70 | 0 | from e | num import Enum, EnumFactory
__all | __ = ["Enum", "EnumFactory"]
|
igmhub/pyLyA | py/picca/fitter2/parser.py | Python | gpl-3.0 | 8,093 | 0.007167 | from functools import partial
import sys
import numpy as np
import os.path
from pkg_resources import resource_filename
if (sys.version_info > (3, 0)):
# Python 3 code in this block
import configparser as ConfigParser
else:
import ConfigPars | er
import fitsio
from picca.utils import userprint
from . import data, utils, priors
def parse_chi2(filename):
cp = ConfigParser.ConfigParser()
cp.optionxform=str
cp.read(filename)
dic_init = {}
dic_init['fiducial'] = {}
p = cp.get('fiducial','filename')
p = os.path.expandvars(p)
if... | rmat(p)
userprint('INFO: reading input Pk {}'.format(p))
h = fitsio.FITS(p)
zref = h[1].read_header()['ZREF']
dic_init['fiducial']['zref'] = zref
dic_init['fiducial']['Om'] = h[1].read_header()['OM']
dic_init['fiducial']['OL'] = h[1].read_header()['OL']
dic_init['fiducial']['k'] = h[1]['K']... |
hzlf/openbroadcast | website/apps/actstream/views.py | Python | gpl-3.0 | 6,439 | 0.004659 | from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.http import HttpResponseRedirect, HttpResponse
from django.views.generic import DetailView, ListView, FormView, UpdateView
from django.views.generic.detail import SingleObjectTemplateResponseMixin
... | lass ActionDetailView(DetailView):
context_object_name = "action"
model = Action
def render_to_response(self, context):
return super(ActionDe | tailView, self).render_to_response(context, mimetype="text/html")
def get_context_data(self, **kwargs):
context = super(ActionDetailView, self).get_context_data(**kwargs)
return context
def respond(request, code):
"""
Responds to the request with the given response code.
If `... |
catapult-project/catapult | trace_processor/trace_uploader/appengine_config.py | Python | bsd-3-clause | 1,441 | 0.004858 | # Copyright 2015 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.
"""App Engine config.
This module is loaded before others and can be used to set up the
App Engine environment. See:
https://cloud.google.com/appengine/do... | with vendor.add. The directories
added this way must be inside the App Engine project directory.
"""
# The deploy script is expected to add links to third party libraries
# before deploying. If the directories aren't there (e.g. when running tests)
# then just ignore it.
for library_dir in (THIRD_PARTY_LIB... | vendor.add(os.path.join(os.path.dirname(__file__), library_dir))
_AddThirdPartyLibraries()
|
google/yapf | yapftests/__init__.py | Python | apache-2.0 | 596 | 0 | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "Lice | nse");
# you may not use this file except in compliance with the License.
# You may o | btain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# 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 t... |
orangain/helloscrapy | helloscrapy/settings.py | Python | mit | 525 | 0.00381 | # Scrapy settings for helloscrapy project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http:// | doc.scrapy.org/en/latest/topics/settings.html
#
BOT_NAME = 'helloscr | apy'
SPIDER_MODULES = ['helloscrapy.spiders']
NEWSPIDER_MODULE = 'helloscrapy.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'helloscrapy (+http://www.yourdomain.com)'
DOWNLOAD_DELAY = 3
ROBOTSTXT_OBEY = True
|
coddingtonbear/jirafs | jirafs/commands/create.py | Python | mit | 2,936 | 0.001362 | from jirafs import utils
from jirafs.plugin import CommandPlugin
from jirafs.utils import run_command_method_with_kwargs
class Command(CommandPlugin):
"""Create a new Jira issue"""
MIN_VERSION = "2.0.0"
MAX_VERSION = "3.0.0"
AUTOMATICALLY_INSTANTIATE_FOLDER = False
FIELDS = (
{
... |
{"name": "summary", "prompt": "Summary", "required": True},
{"name": "description", "prompt": "Description", "required": False},
)
def set_field_value(self, data, field, value):
starting_reference = data
path = field.get("path", field["name"])
for part in path.split(".... | last_reference[path.split(".")[-1]] = value
return starting_reference
def prompt_for_input(self, field):
while True:
if field.get("default"):
value = input(
"%s (%s): "
% (
field.get("prompt"),
... |
drx/rom-info | handlers/dreamcast.py | Python | mit | 4,779 | 0.003139 | import mmap
import os.path
import re
from collections import OrderedDict
from .base_handler import BaseHandler
from .iso9660 import ISO9660Handler
from utils import MmappedFile, ConcatenatedFile
class GDIParseError(ValueError):
pass
class GDIHandler(BaseHandler):
def test(self):
if not re.match('^.*... | (self):
if not super().test():
return False
if self.read(0, 16) == b'SEGA SEGAKATANA ':
return True
else:
return False
def get_info(self):
header_info = OrderedDict()
header_info['Hardware ID'] = self.unpack('string' | , 0x00, 16, 0)
header_info['Maker ID'] = self.unpack('string', 0x10, 16, 0)
header_info['CRC'] = self.unpack('string', 0x20, 4, 0)
header_info['Device'] = self.unpack('string', 0x25, 6, 0)
header_info['Disc'] = self.unpack('string', 0x2b, 3, 0)
header_info['Region'] = self.unpack... |
floppp/programming_challenges | project_euler/001-050/25.py | Python | mit | 344 | 0.011628 | import time
start = time.time()
def fib():
a, b = 0, 1
while True:
yield a
| a, b = b, a + b
f = fib()
for i in range(10000):
d = next(f)
if len(str(d)) == 1000:
print(i)
break
print("t = {:.5f} seg".format(time.time() - start))
# 4782
# t = 0. | 03068 seg
10
print(len(str(10)))
# 2 |
isaac-philip/loolu | common/django/contrib/admin/views/decorators.py | Python | mit | 3,535 | 0.002263 | import base64
try:
from functools import wraps
except ImportError:
from django.utils.functional import wraps # Python 2.3, 2.4 fallback.
from django import http, template
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
from djang... | we cannot find the user, or if more than 1
# we cannot guess which user is the correct one.
message = _("Usernames cannot contain the '@' character.")
return _display_login_form(request, message)
# The user data is correct; log in the user in and continue.
... | esponseRedirect(request.get_full_path())
else:
return _display_login_form(request, ERROR_MESSAGE)
return wraps(view_func)(_checklogin)
|
Janhouse/usb-guard | usb-guard.py | Python | mit | 16,696 | 0.012578 | #!/usr/bin/env python2
#
# Copyright 2012 Janis Jansons (janis.jansons@janhouse.lv)
#
import gi
# make sure you use gtk+ 3
gi.require_version('Gtk', '3.0')
import sys, os
import struct
from gi.repository import GObject, Polkit, GLib, Notify, GUdev, Gio, Gtk
class UsbGuard:
def __init__(self):
print "Star... | +'authorized', '0')
self.devtree[dev]['enabled'] = False
def action_set(self, path, value):
f = open(path, 'w')
enabled=f.write(value)
f.close
def device_vendor_string(self, device):
if device.get_property("ID_VENDOR_FROM_DATABASE"):
return device.g... |
else:
return device.get_property("ID_VENDOR")
def device_model_string(self, device):
if device.get_property("ID_PRODUCT_FROM_DATABASE"):
return device.get_property("ID_PRODUCT_FROM_DATABASE")
elif device.get_property("ID_MODEL_ENC"):
... |
jrleeman/MetPy | metpy/plots/ctables.py | Python | bsd-3-clause | 8,974 | 0.002006 | # Copyright (c) 2014,2015,2017 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""Work with custom color tables.
Contains a tools for reading color tables from files, and creating instances based on a
specific set of constraints (e.g. step size) for ... | .write('({0:f}, {1:f}, {2:f})\n'.format(r / 255, g / 255, b / 255))
class ColortableRegistr | y(dict):
r"""Manages the collection of color tables.
Provides access to color tables, read collections of files, and generates
matplotlib's Normalize instances to go with the colortable.
"""
def scan_resource(self, pkg, path):
r"""Scan a resource directory for colortable files and add them... |
soarlab/FPTaylor | scripts/plot/gappa_data.py | Python | mit | 6,162 | 0.001623 | #!/usr/bin/env python
import sys
import os
import re
import glob
import shutil
import argparse
from fractions import *
import common
log = common.get_log()
# Global paths
base_path = os.path.dirname(os.path.normpath(sys.argv[0]))
tmp_base_path = os.path.join(base_path, "tmp")
tmp_path = os.path.join(tmp_base_path,... | a[n - 1][0][1]
f.write("[Gappa]{0}\n".format(self.name))
i = 1
for ((low, high), v) in data:
if args.error == 'abs':
abs_err = float(v)
rel_err = 0
else:
abs_err = 0
| rel_err = float(v)
if i == 1:
low = lo
if i == n:
high = hi
f.write("{0}, {1}, {2}, {3}, {4}, 0\n".format(i, low, high, abs_err, rel_err))
i += 1
# Export FPTaylor tasks to FPCore
out_file = os.path.... |
klmcwhirter/huntwords | manager/__main__.py | Python | mit | 1,563 | 0.003839 | '''
Usage:
manager puzzle_load (--file <filename>) [--url <url>]
manager puzzle_del (--name <name>) [--url <url>]
manager puzzles [--url <url>]
manager puzzleboards_clear [--url <url>]
manager puzzleboard_consume [--async-url <url>] (--name <name>) [--size <size>]
manager puzzleboard_pop (--name... | oc__, version='0.1')
comm | and = [v for k, v in verbs.items() if opts[k]][0]
command(**opts)
|
ForceBru/PyVM | test_memory.py | Python | mit | 3,339 | 0.001198 | import unittest
import os
import ctypes
from VM.Memory import Memory
class TestMemory(unittest.TestCase):
MEM_SIZE = 512
MAX_RANDOM_REPEAT = 10_000
def setUp(self):
self.mem = Memory(self.MEM_SIZE)
self.random_data = os.urandom(self.MEM_SIZE)
ctypes.memmove(self.mem.mem, self.ra... | e')
self.mem.set(offset, size, correct)
ret = self.mem.get(offset, size)
self.assertEqual(ret, correct)
if size == 4:
for offset in range(2, self.mem.size - size):
correct = int.from_bytes(os.urandom(size), 'little')
self.mem.set(... | elf.mem.get(offset, size)
self.assertEqual(ret, correct)
for offset in range(3, self.mem.size - size):
correct = int.from_bytes(os.urandom(size), 'little')
self.mem.set(offset, size, correct)
ret = self.mem.get(offset, size)
... |
acklabs/kytos | kytos/rest.py | Python | gpl-3.0 | 10,831 | 0.003324 | # This file is part of kytos.
#
# Copyright (c) 2014 by ACK Labs
#
# Authors:
# Beraldo Leal <beraldo AT acklabs DOT io>
# Gabriel von. Winckler <winckler AT acklabs DOT io>
# Gustavo Luiz Duarte <gustavo AT acklabs DOT io>
#
# kytos is free software: you can redistribute it and/or modify
# it under the terms ... | al Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Foobar. If not, see <http://www.gnu.org/licenses/>.
#
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# | -*- coding: utf-8 -*-
#!/usr/bin/env python
from kytos import models
from kytos.db import Session
from flask import Flask, redirect
from flask import url_for
from flask.ext.restful import abort, Resource, fields, reqparse, marshal_with, Api
from sqlalchemy.orm import subqueryload, scoped_session
from sqlalchemy.orm i... |
wonjunetai/pulse | features/uniprot_core.py | Python | mit | 2,151 | 0.003719 | # reads uniprot core file and generates core features
from features_helpers import score_differences
def build_uniprot_to_index_to_core(sable_db_obj):
uniprot_to_index_to_core = {}
for line in sable_db_obj:
tokens = line.split()
try:
# PARSING ID
prot = tokens[0]
... |
map_file_obj = open(map_file, 'r')
sable_db_obj = open(f_sable_db_location, 'r')
write_to = open(uniprot_core_output_location, 'w')
uniprot_to_index_to_core = build_uniprot_to_index_to_core(sable_db_obj)
for line in map_file_obj:
tokens = line.split()
asid = tokens[0].split("_")[... | ns[3])
end = int(tokens[4])
eend = int(tokens[5])
rough_a_length = int(int(tokens[0].split("_")[-1].split("=")[1]) / 3)
if asid[0] == "I":
rough_a_length = 0
c1_count = 0
a_count = 0
c2_count = 0
canonical_absolute = 0
if prot in uni... |
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2018_11_01/operations/_network_interfaces_operations.py | Python | mit | 64,353 | 0.005035 | # 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 may ... | olling strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(res | ponse)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType[None]
lro_delay = kwargs.pop(
'pol... |
tnewman/newmansound | server/newmansound/model.py | Python | gpl-3.0 | 1,028 | 0 | from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
Base = declarative_base()
class Artist(Base):
__tablename__ = 'artist'
id = Column(Inte... | umn(String)
artist_id = Column(Integer, ForeignKey('artist.id'))
artist = relationship('Artist')
class Song(Base):
__tablename__ = 'song'
id = Column(Integer, primary_key=True)
name = Column(String)
album_id = Column(Integer, ForeignKey('album.id'))
album = relationship('Album')
path ... | on = Column(Integer)
song = relationship('Song')
|
otsaloma/helsinki-transit-stops | hts/test/test_util.py | Python | gpl-3.0 | 1,528 | 0 | # -*- coding: utf-8 -*-
# Copyright (C) 2014 Osmo Salomaa
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This pr... | ing\ntesting\n"
handle, path = tempfile.mkstemp()
os.remove(path)
with hts.util.atomic_open(path, "w") as f:
f.write(text)
asser | t open(path, "r").read() == text
os.remove(path)
def test_calculate_distance(self):
# From Helsinki to Lissabon.
dist = hts.util.calculate_distance(24.94, 60.17, -9.14, 38.72)
assert round(dist/1000) == 3361
|
conda/kapsel | conda_kapsel/test/__init__.py | Python | bsd-3-clause | 331 | 0 | # -*- coding: utf-8 -*-
# ------------------------------------ | ----------------------------------------
# Copyright © 2016, Continuum Analytics, Inc. All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
# --------------------------- | -------------------------------------------------
|
tatigo/XBMC-BestRussianTVPlugin | archive.py | Python | gpl-3.0 | 9,702 | 0.004741 | # coding=utf-8
#
# <BestRussianTV plugin for XBMC>
# Copyright (C) <2011> <BestRussianTV>
#
# 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
# ... | ssword):
self.req = self.req.replace('{SiteId}', config1.siteId).replace('{AppName}', config1.appName) \
.replace('{Username}', Username).replace('{Password}', Password)
def Request(self):
conn = httplib.HTTPConnection('iptv-distribution.net')
conn.request('POST', config1.epgService... |
'SOAPAction': 'http://iptv-distribution.net/ds/epg/GetPVRChannels',
'Content-Type': 'text/xml; charset=utf-8'
})
response = conn.getresponse()
data = response.read()
p = xml.parsers.expat.ParserCreate()
p.StartElem... |
Teknologforeningen/teknologr.io | teknologr/registration/migrations/0004_auto_20190610_2250.py | Python | mit | 350 | 0 | # Generated by Django 2.2.1 on 2019-06-10 | 19:50
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('registration', '0003_limbomember_mother_tongue'),
]
operations = [
migrations.RenameModel(
old_name='LimboMember',
new_name='Ap | plicant',
),
]
|
tillraab/thunderfish | docs/pulseplots.py | Python | gpl-3.0 | 40,213 | 0.035635 | """
## Plot and save key steps in pulses.py for visualizing the alorithm.
"""
import pickle, glob
import numpy as np
from scipy import stats
from matplotlib import rcParams, gridspec, ticker
import matplotlib.pyplot as plt
try:
from matplotlib.colors import colorConverter as cc
except ImportError:
... | s is given in points (same unit as linewidth).
clw: int, float, None
Line width of the cap lines.
kwargs: key-word arguments
Passed on to `ax.text()` used to print the scale bar label.
"""
ax.autoscale(False)
# ax dimensions:
pixelx = np.abs(np.diff(ax.get_window_extent()... | x.get_xlim()
ymin, ymax = ax.get_ylim()
unitx = xmax - xmin
unity = ymax - ymin
dxu = np.abs(unitx)/pixelx
dyu = np.abs(unity)/pixely
# transform x, y from relative units to axis units:
x = xmin + x*unitx
y = ymin + y*unity
# bar length:
if wformat is None:
wfo... |
creasyw/IMTAphy | modules/phy/imtaphy/testConfigs/config.py | Python | gpl-2.0 | 29,929 | 0.021718 | ################################################################################
# This file is part of IMTAphy
# _____________________________________________________________________________
#
# Copyright (C) 2011
# Institute of Communication Networks (LKN)
# Department of Electrical Engineering and Information Techno... | s = 1 # tier of cell sites surrounding center site (0: 1 site, 1: 7 sites, 2: 19 sites)
random.seed(params.seed) # this fixes the seed for Python within this config.py
# simulator setup stuff
WNS = openwns.Simulator(si | mulationModel = openwns.node.NodeSimulationModel())
openwns.setSimulator(WNS)
WNS.maxSimTime = simTime
WNS.rng.seed = params.seed # this fixes the seed for the C++ simulator#
WNS.masterLogger.backtrace.enabled = False
WNS.masterLogger.enabled = True #False
WNS.outputStrategy = openwns.simulator.OutputStrategy.DELETE
W... |
jaywink/diaspora-hub | thefederation/migrations/0001_initial.py | Python | agpl-3.0 | 4,467 | 0.003582 | # Generated by Django 2.0.3 on 2018-03-25 19:18
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import django.db.models.deletion
import django_countries.fields
import enumfields.fields
import thefederation.enums
class Migration(migrations.Migration):
initial = True
depe... | ('uuid', models.UUIDField(auto_created=True, db_index=True, unique=True)),
('created', models.DateTimeField(auto_now_add=True)),
('updated', models.DateTimeField(auto_now=True)),
('latest_version', models.CharField(blank=True, max_length=128)),
('i... | .CharField(default='unknown', max_length=80)),
('name', models.CharField(max_length=80, unique=True)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Protocol',
fields=[
('id'... |
ihmeuw/vivarium | src/vivarium/examples/boids/visualization.py | Python | bsd-3-clause | 500 | 0 | import matplotlib.pyplot as plt
def plot_birds(simulation, plot_velocity=False):
width = simulation.configuration.location.width
height = simulation.configuration.location.height
pop = simulation.get_population()
plt.figure(figsize=[12, 12])
plt.scatter(pop.x, pop.y, color=pop.color)
if plot_... | y, color=pop.color, width=0.00 | 2)
plt.xlabel("x")
plt.ylabel("y")
plt.axis([0, width, 0, height])
plt.show()
|
jmp0xf/raven-python | setup.py | Python | bsd-3-clause | 3,611 | 0.000831 | #!/usr/bin/env python
"""
Raven
=====
Raven is a Python client for `Sentry <http://getsentry.com/>`_. It provides
full out-of-the-box support for many of the popular frameworks, including
`Django <djangoproject.com>`_, `Flask <http://flask.pocoo.org/>`_, and `Pylons
<http://www.pylonsproject.org/>`_. Raven also includ... | : 'NoneType' object is not callable" error
# in multiprocessing/util.py _exit_function whe | n running `python
# setup.py test` (see
# http://www.eby-sarna.com/pipermail/peak/2010-May/003357.html)
for m in ('multiprocessing', 'billiard'):
try:
__import__(m)
except ImportError:
pass
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
impor... |
ychen820/microblog | y/google-cloud-sdk/platform/google_appengine/lib/django-1.2/django/contrib/flatpages/admin.py | Python | bsd-3-clause | 1,072 | 0.00653 | from django import forms
from django.contrib import admin
from django.contrib. | flatpages.models import FlatPage
from django.utils.translation import ugettext_lazy as _
class FlatpageForm(forms.ModelForm):
url = forms.RegexField(label=_("URL"), max_length=100, regex=r'^[-\w/]+$',
help_text = _("Example: '/about/contact/'. Make sure to have leading"
" and trailin... | error_message = _("This value must contain only letters, numbers,"
" underscores, dashes or slashes."))
class Meta:
model = FlatPage
class FlatPageAdmin(admin.ModelAdmin):
form = FlatpageForm
fieldsets = (
(None, {'fields': ('url', 'title', 'content', 'si... |
wnereiz/pxeat | pxeat/views.py | Python | gpl-3.0 | 12,105 | 0.012557 | #!/usr/bin/python3
import sqlite3
import os, sys, time, datetime, random, string
import urllib.request, urllib.error
import configparser
from flask import Flask, request, session, redirect
from flask import render_template, g, flash, url_for
from contextlib import closing
from .modules import Pagi
from pxeat import ap... | her_page(page):
args = request.view_args.copy()
args['page'] = page
return url_for(request.endpoint, **args)
app.jinja_env.globals['url_for_other_page'] = url_for_other_page
@app.route('/confirm', methods | =['POST'])
def confirm_entry():
#Input checking
try:
for x,y in [[request.form['pxe_title'],'pxe_title'], \
[request.form['repo_url'], 'repo_url'], \
[request.form['repo_kernel'], 'file_path'], \
[request.form['repo_initrd'], 'file_path']]:
... |
youtube/cobalt | build/android/gyp/apkbuilder.py | Python | bsd-3-clause | 22,278 | 0.009202 | #!/usr/bin/env python3
#
# Copyright (c) 2015 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.
"""Adds the code parts to a resource APK."""
import argparse
import logging
import os
import shutil
import sys
import tempfile
... |
src_path, dest_path = _SplitAssetPath(path)
if os.path.isdir(src_path):
for f in build_utils.FindInDirectory(src_path, '*'):
ret.append((f, os.path.join(dest_path, f[len(src_path) + 1:])))
else:
ret.append((src_path, dest_path))
ret.sort(key=lambda t:t[1])
return ret
def _GetAsset... | ples,
|
msadegh97/IoT_first-project | server/server/urls.py | Python | mit | 326 | 0.01227 | from django.conf.urls import url,include
from django.contrib import admin
from cn_device import views
urlpatterns = [
url(r'^admin/', admin.site | .urls),
url(r'^send/(?P<id_ras>[0-9]+)/$',views.payam,name='send condition'),
url(r'^give/(?P<id_ras>[0-9]+)/(?P<bl>[0-1])/$', views.give_req | , name='give condition'),
]
|
F5Networks/f5-common-python | f5/bigip/tm/asm/policies/test/unit/test_character_sets.py | Python | apache-2.0 | 1,194 | 0 | # Copyright 2015 F5 Networks Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... | 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.
#
from f5.bigip.tm.asm.policies.character_sets import Character_Sets
from f5.sdk_except... | _e._meta_data['bigip'].tmos_version = '11.6.0'
return fake_e
class TestCharacterSets(object):
def test_create_raises(self, FakeChar):
with pytest.raises(UnsupportedOperation):
FakeChar.create()
def test_delete_raises(self, FakeChar):
with pytest.raises(UnsupportedOperation):
... |
ewheeler/rapidsms-core | lib/rapidsms/backends/email.py | Python | lgpl-3.0 | 4,516 | 0.007972 | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
from __future__ import absolute_import
from rapidsms.message import Message
from rapidsms.connection import Connection
from . import backend
from email import message_from_string
from django.core.mail import *
class Backend(backend.Backend):
'''Uses the django ... | essage[" | from"]
else:
from_string = self._username
# always use the identity in the message for "to",
# even if they specified one in the headers
to_string = message.connection.identity
if "," in to_string:
to_ple = to_string.split(",")
else:
... |
ajaygarg84/sugar | src/jarabe/model/session.py | Python | gpl-2.0 | 3,705 | 0.00081 | # Copyright (C) 2008, Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in... | elif self._logout_m | ode == self.MODE_REBOOT:
pm.Restart()
except:
logging.exception('Can not stop sugar')
self.session.cancel_shutdown()
return
session.SessionManager.shutdown_completed(self)
Gtk.main_quit()
def _close... |
adsorensen/girder | plugins/user_quota/server/__init__.py | Python | apache-2.0 | 1,930 | 0.002073 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright 2015 Kitware 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 cop... | ions under the Licens | e.
###############################################################################
from girder import events
from girder.models.model_base import ValidationException
from girder.utility import setting_utilities
from . import constants
from .quota import QuotaPolicy, ValidateSizeQuota
@setting_utilities.validator((
... |
LiquidCode/Leap | leap/static_pages.py | Python | mit | 585 | 0 | from pyramid.httpexceptions import HTTPFound
from pyramid.view import view_config
@view_config(
route_name='leap.projects',
renderer='projects.mako',
)
def blankPage(request): return {}
@view_config(route_name='leap.source')
def github(request):
return HTTPFound(location="https://github.com/LiquidCode")... | ute="leap.source", text="Sources")
config.add_route("leap.projects", "/projects") |
config.add_route("leap.source", "/sources")
|
rkhleics/wagtailmenus | wagtailmenus/__init__.py | Python | mit | 1,864 | 0 | from wagtailmenus.utils.version import get_version, get_stable_branch_name
# major.minor.patch.release.number
# release must be one of alpha, beta, rc, or final
VERSION = (3, 1, 0, "alpha", 0)
__version__ = get_version(VERSION)
stable_branch_name = get_stable_branch_name(VERSION)
default_app_config = "wagtailmenus.ap... | from wagtailmenus.conf import settings
return settings.MAIN_MENU_MODEL
def get_flat_menu_model_string():
"""
Get the dotted ``app.Model`` name for the flat menu model as a string.
| Useful for developers extending wagtailmenus, that need to refer to the
flat menu model (such as in foreign keys), but the model itself is not
required.
"""
from wagtailmenus.conf import settings
return settings.FLAT_MENU_MODEL
def get_main_menu_model():
"""
Get the model from the ``WA... |
vedujoshi/os_tempest | tempest/api_schema/compute/v3/keypairs.py | Python | apache-2.0 | 1,333 | 0 | # Copyright 2014 NEC Corporation. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in complianc | e with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# 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.
from tempest.api_schema.compute import keypairs
get_keypair = {
'status_code': [200],
'response_body': {
'type': 'object',
'properties': {
'keyp... |
AutorestCI/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_10_01/operations/virtual_network_gateway_connections_operations.py | Python | mit | 38,583 | 0.002514 | # 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 ... | udError
from msrest.exceptions import DeserializationError
from msrestazure.azure_operation import AzureOperationPoller
from .. import models
class VirtualNetworkGatewayConnectionsOperations(object):
"""VirtualNetworkGatewayConnectionsOperations operations.
:param client: Client for service requests.
:p... | zer: An objec model deserializer.
:ivar api_version: Client API version. Constant value: "2017-10-01".
"""
models = models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
... |
thomasem/nova | nova/scheduler/client/__init__.py | Python | apache-2.0 | 2,731 | 0 | # Copyright (c) 2014 Red Hat, 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 require... | te):
self.queryclient.delete_aggregate(context, aggregate)
def update_resource_stats(self, context, name, stats):
self.reportclient.update_resource_stats(context, name, stats)
def update_instance_info(self, context, host_name, instance_info):
self.queryclient.up | date_instance_info(context, host_name,
instance_info)
def delete_instance_info(self, context, host_name, instance_uuid):
self.queryclient.delete_instance_info(context, host_name,
instance_uuid)
def sync_instanc... |
jacksingleton/twitter-censorship | main.py | Python | mit | 623 | 0.009631 | #!/usr/bin/env python3
import os
import logging
import download_table_pages
i | mport download_notices
import parse_notice_tweets
import find_censored_tweets
#logging.basicConfig(level=logging.DEBUG)
for path in ['store/table_pages', 'store/notices', 'store/tweets']:
if not os.path.exists(path):
os.mkdirs(path)
withheld_tweets = (tweet
for table_page in download_table_page | s.fetch_table_pages()
for notice in download_notices.fetch_notices(table_page)
for tweet in parse_notice_tweets.parse_tweets_from(notice)
if find_censored_tweets.is_withheld(tweet))
for t in withheld_tweets: print(t)
|
PirateLearner/pi | PirateLearner/core/forms.py | Python | gpl-2.0 | 725 | 0.011034 | from djan | go import forms
from django.contrib.admin import widgets
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from crispy_forms.layout import Layout, Field, Fieldset, ButtonHolder
class PreviewForm(forms.Form):
object_list = forms.CharField(
label = "List of objects",
... | FormHelper()
self.helper.form_id = 'id-previewForm'
self.helper.form_class = 'blueForms'
self.helper.form_method = 'post'
self.helper.form_action = ''
self.helper.add_input(Submit('submit', 'Submit')) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.