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 |
|---|---|---|---|---|---|---|---|---|
drfmunoz/PythonEncodingSample | test/__init__.py | Python | apache-2.0 | 22 | 0 | __author__ = 'fr | edd | y'
|
rsoutelino/pyeditmask | pyeditmask.py | Python | mit | 21,757 | 0.008549 | #!/usr/bin/env python
######################################################
## Edits ROMS masks using a GUI
## Nov 2014
## rsoutelino@gmail.com
######################################################
import os
import wx
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.bac... | f,filename):
self.filename = filename
self.ncfile = nc.Dataset(filename, mode='r+')
self.lonr = self.ncfile.variables['lon_rho'][:]
self.latr = self.ncfile.variables['lat_rho'][:]
self.lonu = self.ncfile.variables['lon_u'][:]
self.latu = self.ncfile.variables['lat... | _vert'][:]
self.latvert = self.ncfile.variables['lat_vert'][:]
self.h = self.ncfile.variables['h'][:]
self.maskr = self.ncfile.variables['mask_rho'][:]
self.masku = self.ncfile.variables['mask_u'][:]
self.maskv = self.ncfile.variables['mask_v'][:]
def uvp_mask(rfield):
... |
stevepiercy/cookiecutter | cookiecutter/generate.py | Python | bsd-3-clause | 13,178 | 0 | # -*- coding: utf-8 -*-
"""Functions for generating a project from a project template."""
from __future__ import unicode_literals
from collections import OrderedDict
import fnmatch
import io
import json
import logging
import os
import shutil
from jinja2 import FileSystemLoader
from cookiecutter.environment import Str... | format(infile))
# Render the path to the output file (not including the root project dir)
outfile_tmpl = env.from_string(infile)
outfile = os.path.join(project_dir, outfile_tmpl.render(**context))
file_name_is_empty = os.path.isdir(outfile)
if file_name_is_empty:
logger.debug('The resultin... | ile))
# Just copy over binary files. Don't render.
logger.debug("Check {} to see if it's a binary".format(infile))
if is_binary(infile):
logger.debug(
'Copying binary {} to {} without rendering'
''.format(infile, outfile)
)
shutil.copyfile(infile, outfile)
... |
tongxindao/Flask-micblog | Flask-MicroBlog/web/micblog/db_migrate.py | Python | apache-2.0 | 844 | 0.003695 | # coding: utf-8
import imp
from migrate.versioning import api
from app import db
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
|
migration = SQLALCHEMY_MIGRATE_REPO + '/versions/%03d_migration.py' % (api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO) + 1)
tmp_module = imp.new_module('old_model')
old_model = api.create_model(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
exec old_model in tmp_module.__dict__
script = api.make_... | |
google-research/dreamer | dreamer/control/dummy_env.py | Python | apache-2.0 | 1,560 | 0.004487 | # Copyright 2019 The Dreamer Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | {'image': gym.spaces.Box(low, high)}
return gym.spaces.Dict(spaces)
@property
def action_space(self):
low = -np.ones([5], dtype=np.float32)
high = np.ones([5], dtype=np.float32)
return gym.spaces.Box(low, high)
def reset(self):
self._step = 0
obs = self.observation_space.sample()
ret... | dom.uniform(0, 1)
self._step += 1
done = self._step >= 1000
info = {}
return obs, reward, done, info
|
nkmk/python-snippets | notebook/opencv_face_eye_detection.py | Python | mit | 1,633 | 0.001225 | import cv2
face_cascade_path = '/usr/local/opt/opencv/share/'\
'OpenCV/haarcascades/haarcascade_frontalface_default.xml'
eye_cascade_path = '/usr/local/opt/opencv/share/'\
'OpenCV/haarcascades/haarcascade_eye.xml'
face_cascade = cv2.CascadeClassifier(face_cascade_path)
eye_casca... | cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(src_gray)
for x, y, w, h in faces:
cv2.rectangle(src | , (x, y), (x + w, y + h), (255, 0, 0), 2)
face = src[y: y + h, x: x + w]
face_gray = src_gray[y: y + h, x: x + w]
eyes = eye_cascade.detectMultiScale(face_gray)
for (ex, ey, ew, eh) in eyes:
cv2.rectangle(face, (ex, ey), (ex + ew, ey + eh), (0, 255, 0), 2)
cv2.imwrite('data/dst/opencv_face_dete... |
mozilla-iam/cis | python-modules/cis_publisher/cis_publisher/auth0.py | Python | mpl-2.0 | 24,297 | 0.003992 | import cis_profile
import cis_publisher
import boto3
import botocore
import os
import logging
import json
import time
from auth0.v3.authentication import GetToken
from auth0.v3.management import Auth0
from auth0.v3.exceptions import Auth0Error
from datetime import datetime, timezone, timedelta
from traceback import for... | ublisher memory cache
publisher.known_cis_users = None
# XXX in case we got duplicates for some reason, we uniq | uify
self.all_cis_user_ids = list(set(self.all_cis_user_ids))
logger.info("Got {} known CIS users for all whitelisted login methods".format(len(self.all_cis_user_ids)))
return self.all_cis_user_ids
def get_az_user_ids(self):
"""
Extrac |
ESOedX/edx-platform | common/djangoapps/terrain/stubs/lti.py | Python | agpl-3.0 | 13,193 | 0.002653 | """
Stub implementation of LTI Provider.
What is supported:
------------------
1.) This LTI Provider can service only one Tool Consumer at the same time. It is
not possible to have this LTI multiple times on a single page in LMS.
"""
from __future__ import absolute_impor | t
import base64
import hashlib
import logging
import os
import textwrap
from uuid import uuid4
import mock
import oauthlib.oauth1
import requests
import six
import six.moves.urllib.error # pylint: disable=import-error
import six.moves.urllib.parse # pylint: disable=import-error
import six.moves.urllib.request # py... | mport StubHttpRequestHandler, StubHttpService
log = logging.getLogger(__name__)
class StubLtiHandler(StubHttpRequestHandler):
"""
A handler for LTI POST and GET requests.
"""
DEFAULT_CLIENT_KEY = 'test_client_key'
DEFAULT_CLIENT_SECRET = 'test_client_secret'
DEFAULT_LTI_ENDPOINT = 'correct_lt... |
chetan/cherokee | qa/137-Mime1.py | Python | gpl-2.0 | 797 | 0.012547 | from base import *
TYPE = "example/ejemplo"
EXTENSION = "mime_test_1"
MIME_TYPES = """
mime!application/java-archive!extensions = jar
mime!application/java-serialized-object!extensions = ser
mime!application/j | ava-vm!extensions = class
mime!%s!extensions = %s
mime!x-world/x-vrml!extensions = vrm vrml wrl
""" % (TYPE, EXTENSION)
class Test (TestBase):
def __init__ (self):
TestBase.__init__ (self, __file__)
self.name = "Mime type I"
se | lf.request = "GET /mime1/file.%s HTTP/1.0\r\n" % (EXTENSION)
self.expected_error = 200
self.expected_content = "Content-Type: %s" % (TYPE)
def Prepare (self, www):
d = self.Mkdir (www, "mime1")
f = self.WriteFile (d, "file.%s" % (EXTENSION))
self.conf = MIME_TYPE... |
JuliaSprenger/python-neo | neo/rawio/baserawio.py | Python | bsd-3-clause | 26,231 | 0.001792 | """
baserawio
======
Classes
-------
BaseRawIO
abstract class which should be overridden to write a RawIO.
RawIO is a new API in neo that is supposed to acces as fast as possible
raw data. All IO with theses characteristics should/could be rewritten:
* internally use of memmap (or hdf5)
* reading header is quite... | ame)
# create a logger fo | r 'neo' and add a handler to it if it doesn't
# have one already.
# (it will also not add one if the root logger has a handler)
corename = self.__class__.__module__.split('.')[0]
corelogger = logging.getLogger(corename)
rootlogger = logging.getLogger()
if not corelogger.h... |
Krissbro/LondonGaymers | antilink/antilink.py | Python | gpl-3.0 | 4,545 | 0.00154 | import discord
from discord.ext import commands
from .utils import checks
from __main__ import send_cmd_help, settings
from cogs.utils.dataIO import dataIO
import os
import re
import asyncio
class Antilink:
"""Blocks Discord invite links from users who don't have the permission 'Manage Messages'"""
def __ini... | await self.bot.say('Remember: Direct Messages on removal is disabled!\nEnable it with ``antilinkset toggledm``')
@antilinkset.command(pass_context=True, no_pm=True)
| @checks.admin_or_permissions(administrator=True)
async def toggledm(self, ctx):
serverid = ctx.message.server.id
if self.json[serverid]['dm'] is False:
self.json[serverid]['dm'] = True
await self.bot.say('Enabled DMs on removal of invite links')
elif self.json[ser... |
pombredanne/spaCy | spacy/tests/tokens/test_array.py | Python | mit | 1,141 | 0 | # coding: utf-8
from __future__ import unicode_literals
import pytest
from spacy import attrs
def test_attr_of_token(EN):
text = u'An example sentence.'
tokens = EN(text, tag=True, parse=False)
example = EN.vocab[u'example']
assert example.orth != example.shape
feats_array = tokens.to_array((att... | t = u'A nice sentence.'
tokens = EN(text)
assert tokens[0].tag != tokens[1].tag != tokens[2].tag != tokens[3].tag
feats_array = tokens.to_array((attrs.ORTH, attrs.TAG))
assert feats_array[0][1] == tokens[0].tag
assert feats_arr | ay[1][1] == tokens[1].tag
assert feats_array[2][1] == tokens[2].tag
assert feats_array[3][1] == tokens[3].tag
@pytest.mark.models
def test_dep(EN):
text = u'A nice sentence.'
tokens = EN(text)
feats_array = tokens.to_array((attrs.ORTH, attrs.DEP))
assert feats_array[0][1] == tokens[0].dep
... |
DavidBarishev/ClashOfClansBot | ClashOfClansBot/Plugins/Tasks/TrainTroops/_TrainTroopsTask.py | Python | mit | 131 | 0 | from ClashOfClansBot.Interfaces.BotAPI import ITask
class TrainTr | oopsTask(ITask | ):
def __init__(self, **troops):
pass
|
lmmsoft/LeetCode | LeetCode-Algorithm/1002. Find Common Characters/solution.py | Python | gpl-2.0 | 1,499 | 0 | class Solution(object):
def commonCha | rs(self, A):
"""
:type A: List[str]
:rtype: List[str]
"""
# 把每个字符串编程 char,count的dict放入数组
# 可以用直接用 str.count统计26个字母的个数
res: list = []
for a in A:
d = {}
for c in a:
d[c] = d.get(c, 0) + 1
res.append(d)
... | chars = []
for asi in range(ord('a'), ord('z') + 1):
c = chr(asi)
chars.append(c)
# print(c)
# 每个字母求个数最大值
ans = {}
for c in chars:
mmax = 99999999
for r in res:
mmax = min(mmax, r.get(c, 0))
ans[c]... |
jhbez/ProjectV | app/v/buy/rest/pendingRst.py | Python | apache-2.0 | 5,665 | 0.003001 | # -*- coding: utf-8 -*-
# Copyright 2017 ProjectV Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | status_code=201)
else:
raise ExceptionRest(status_code=500, message='No se ha podido registrar')
else:
raise ExceptionRest(status_code=400, errors=_errors)
e | xcept (Exception, ExceptionRest), e:
_post = processing_rest_exception(e)
return _post
class PendingRst(Resource, PendingMdl):
def get(self, id):
try:
_qrg = """
SELECT array_to_json(array_agg(row_to_json(t) )) as collection
FROM ( SE... |
heryii/snabb | src/program/lwaftr/tests/subcommands/monitor_test.py | Python | apache-2.0 | 2,186 | 0.00183 | """
Test the "snabb lwaftr monitor" subcommand. Needs a NIC name and a TAP interface.
1. Execute "snabb lwaftr run" in on-a-stick mode and with the mirror option set.
2. Run "snabb lwaftr monitor" to set the counter and check its output.
"""
from random import randint
from subprocess import call, check_call
import un... | )
self.assertIn(b'255.255.255.255', output,
b'\n'.join((b'OUTPUT', output)))
@classmethod
def tearDownClass(cls):
try:
super(TestMonitor, cls).tearDownClass()
finally:
# Clean up th | e TAP interface.
call(('ip', 'tuntap', 'delete', cls.tap_name, 'mode', 'tap'))
if __name__ == '__main__':
unittest.main()
|
dapengchen123/code_v1 | reid/datasets/market1501.py | Python | mit | 3,563 | 0.000561 | from __future__ import print_function, absolute_import
import os.path as osp
from ..utils.data import Da | taset
from ..utils.osutils import mkdir_if_missing
from ..utils.serialization import write_json
class Market1501(Dataset):
url = 'https://drive.google.com/file/d/0B8-rUzbwVRk0c054eEozWG9COHM/view'
md5 = '65005ab7d12ec1c44de4eeafe813e68a'
def __init__(self, root, split_id=0, num_val=0.3, download=False):
... | elf._check_integrity():
raise RuntimeError("Dataset not found or corrupted. " +
"You can use download=True to download it.")
self.load(num_val)
def download(self):
if self._check_integrity():
print("Files already downloaded and verified")
... |
DiscourseDB/discoursedb-core | composeddb/brat/config.py | Python | gpl-2.0 | 3,622 | 0.005246 | # This configuration was automatically generated by install.sh
from os.path import dirname, join as path_join
# This configuration file specifies the global setup of the brat
# server. It is recommended that you use the installation script
# instead of editing this file directly. To do this, run the following
# command... | g texts and annotations
# WORK_DIR: directory that the server uses for temporary files
#
BASE_DIR = dirname(__file__)
DATA_DIR = path_join(BASE_DIR, 'data' | )
WORK_DIR = path_join(BASE_DIR, 'work')
# If you have installed brat as suggested in the installation
# instructions, you can set up BASE_DIR, DATA_DIR and WORK_DIR by
# removing the three lines above and deleting the initial '#'
# character from the following four lines:
#from os.path import dirname, join
#BASE_DIR =... |
mph-/lcapy | doc/examples/networks/seriesparallelRL1.py | Python | lgpl-2.1 | 110 | 0.009091 | from lcapy import R, L
n = (R('R1') | L('L1')) + (R('R2') | L( | 'L2'))
n.draw(__file__.replace('.py', '.png'))
| |
seewindcn/tortoisehg | src/mercurial/demandimport.py | Python | gpl-2.0 | 9,674 | 0.001964 | # demandimport.py - global demand-loading of modules for Mercurial
#
# Copyright 2006, 2007 Matt Mackall <mpm@selenic.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
'''
demandimport - automatic demandloading of modules
To e... | rtfunc(hgextname, globals, *args, **kwargs)
class _demandmod(object):
"""module demand-loader and proxy"""
def __init__(self, name, globals, locals, level=level):
if '.' in name:
head, rest = name.split('.', 1)
after = [rest]
else:
head = name
aft... | (head, globals, locals, after, level, set()))
object.__setattr__(self, "_module", None)
def _extend(self, name):
"""add to the list of submodules to load"""
self._data[3].append(name)
def _addref(self, name):
"""Record that the named module ``name`` imports... |
danielsamuels/django-registration | registration/tests/test_views.py | Python | bsd-3-clause | 1,035 | 0 | from django.core.urlresolvers import reverse
from django.test import override_settings, TestCase
from ..models import RegistrationProfile
class ActivationViewTests(TestCase):
urls = 'registration.tests.urls'
@ove | rride_settings(ACCOUNT_ACTIVATION_DAYS=7)
def test_activation(self):
"""
Activation of an account functions properly when using a
simple string URL as the success redirect.
"""
resp = self.client.post(reverse('registration_register'),
| data={'username': 'bob',
'email': 'bob@example.com',
'password1': 'secret',
'password2': 'secret'})
profile = RegistrationProfile.objects.get(user__username='bob')
... |
ncdesouza/bookworm | env/lib/python2.7/site-packages/werkzeug/__init__.py | Python | gpl-3.0 | 7,216 | 0.00194 | # -*- coding: utf-8 -*-
"""
werkzeug
~~~~~~~~
Werkzeug is the Swiss Army knife of Python web development.
It provides useful classes and functions for any WSGI application to make
the life of a python web developer much easier. All of the provided
classes are independent from each other so yo... | rization',
'FileMultiDict', 'CallbackDict', 'FileStorage',
'OrderedMultiDict', 'ImmutableOrderedMultiDict'],
'werkzeug.useragents': ['UserAgent'],
'werkzeug.http': ['parse_etags', 'parse_date', 'http_date',
'cookie_da... | ote_etag',
'generate_etag', 'dump_header',
'parse_list_header', 'parse_dict_header',
'parse_authorization_header',
'parse_www_authenticate_header',
'remove_entity_headers', 'i... |
euhackathon/commission-today-api | backend/api/resources.py | Python | mit | 2,974 | 0.001345 | from tastypie.constants import ALL
from tastypie.fields import ToOneField
from tastypie.resources import ModelResource
from backend.models import Portofolio, Member, Meeting, Organization
import calendar
from haystack.query import SearchQuerySet
from django.core.paginator import Paginator, InvalidPage
from tastypie.uti... | (request.GET.get('q', ''))
paginator = Paginator(sqs, 20)
try:
page = paginator.page(int(request.GET.get('page', 1)))
except InvalidPage:
raise Http404("Sorry, no results on that page.")
objects = []
for result in page.object_list:
bundle = ... | object_list = {
'objects': objects,
}
return self.create_response(request, object_list)
|
norus/procstat-json | tornado/test/auth_test.py | Python | gpl-3.0 | 10,876 | 0.002023 | # These tests do not currently do much to verify the correct implementation
# of the openid/oauth protocols, they just exercise the major code paths
# and ensure that it doesn't blow up (e.g. with unicode/bytes issues in
# python 3)
from __future__ import absolute_import, division, with_statement
from tornado.auth im... | [
# test endpoints
('/openid/client/login', OpenIdClientLoginHandler, dict(test=self)),
('/oauth10/client/login', OAuth1ClientLoginHandler,
dict(test=self, version='1.0')),
('/oauth10/client/request_params',
OAuth1Clie... | n', OAuth1ClientLoginHandler,
dict(test=self, version='1.0a')),
('/oauth10a/client/request_params',
OAuth1ClientRequestParametersHandler,
dict(version='1.0a')),
('/oauth2/client/login', OAuth2ClientLoginHandler, dict(test=self)),
... |
kakRostropovich/EmmetOneLine | emmet_css_from_one_line.py | Python | mit | 908 | 0.007709 | import sublime, sublime_plugin, re
class EmmetCssFromOneLineCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
line_region = view.line(view.sel()[0])
line_str = view.substr(line_region)
left_padding = re.findall(r'^(\s+)', line_str)[0]
... | rray = re.findall(r'([a-zA-Z0-9:!;().,?/\-+#]+)', line_str)
# Delete long string
view.replace(edit, line_region, '')
def runEmmet():
view.run_command("expand_abbreviation_by_tab")
# Processing first element
view.insert(edit, view.sel()[0].end(), left_paddin... | view.insert(edit, view.sel()[0].end(), '\n' + left_padding + props_array[i])
runEmmet()
i += 1
|
hongliang5623/sentry | src/sentry/models/event.py | Python | bsd-3-clause | 7,063 | 0.001133 | """
sentry.models.event
~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import warnings
from collections import OrderedDict
from django.db import models
from django.utils import tim... | ered from several interfaces.
In order:
- User.id
- User.email
- User.username
- Http.env.REMOTE_ADDR
"""
user_data = self.data.get('sentry.interfaces.User', self.data.get('user'))
if user_data:
ident = user_data.get('id')
if ide... | t = user_data.get('username')
if ident:
return 'username:%s' % (ident,)
ident = self.ip_address
if ident:
return 'ip:%s' % (ident,)
return None
def get_interfaces(self):
result = []
for key, data in self.data.iteritems():
... |
aerospike/aerospike-client-python | test/new_tests/test_info_all.py | Python | apache-2.0 | 3,320 | 0.000602 | # -*- coding: utf-8 -*-
import pytest
import sys
from aerospike import exception as e
from .test_base_class import TestBaseClass
aerospike = pytest.importorskip("aerospike")
try:
import aerospike
except:
print("Please install aerospike python client.")
sys.exit(1)
@pytest.mark.usefixtures("as_connectio... | ts without connection
"""
client1 = aerospike.client(self.connection_config)
with pytest.raises(e.ClusterError) as err_info:
client1.info_all('sets')
def test_info_all_with_invalid_policy_type(self):
| '''
Test that sending a non dict/None as policy raises an error
'''
request = None
with pytest.raises(e.ParamError):
self.as_connection.info_all(None, [])
|
darkryder/django | tests/inspectdb/models.py | Python | bsd-3-clause | 3,075 | 0.000325 | # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
class People(models.Model):
name = models.CharField(max_length=255)
parent = models.ForeignKey('self', models.CASCADE)
class Message(models.Model):
from_field = models.ForeignKey(People, models.CASCADE, db_co... | dels.IntegerField(db_column='tamaño')
class Meta:
db_table = "inspectdb_special.table name"
class ColumnTypes(models.Model):
id = models.AutoField(primary_key=True)
big_int_field = models.BigIntegerField()
bool_field = models.BooleanField(default=False)
null_bool_field = models.NullBoolea... | SeparatedIntegerField(max_length=99)
date_field = models.DateField()
date_time_field = models.DateTimeField()
decimal_field = models.DecimalField(max_digits=6, decimal_places=1)
email_field = models.EmailField()
file_field = models.FileField(upload_to="unused")
file_path_field = models.FilePathF... |
gulopine/steel | examples/images/png.py | Python | bsd-3-clause | 6,898 | 0.00087 | import decimal
import sys
import steel
from steel import chunks
COMPRESSION_CHOICES = (
(0, 'zlib/deflate'),
)
RENDERING_INTENT_CHOICES = (
(0, 'Perceptual'),
(1, 'Relative Colorimetric'),
(2, 'Saturation'),
(3, 'Absolute Colorimetric'),
)
PHYSICAL_UNIT_CHOICES = (
| (0, '<Unknown Unit>'),
(1, 'Meters'),
)
FILTER_CHOICES = (
(0, 'Adaptive Filtering'),
)
INTERLACE_CHOICES = (
(0, '<No Interlacing>'),
(1, 'Adam7'),
)
class Chunk(chunks.Chunk, encoding='ascii'):
"""
A special chunk for PNG, which puts the size before the type
and includes ... | size = steel.Integer(size=4)
id = steel.String(size=4)
payload = chunks.Payload(size=size)
crc = steel.CRC32(first=id)
@property
def is_critical(self):
# Critical chunks will always have an uppercase letter for the
# first character in the type. Ancillary will always be ... |
ProfessorX/Config | .PyCharm30/system/python_stubs/-1247971765/PyKDE4/kdecore/KPtyProcess.py | Python | gpl-2.0 | 1,129 | 0.010629 | # encoding: utf-8
# module PyKDE4.kdecore
# from /usr/lib/python3/dist-packages/PyKDE4/kdecore.cpython-34m-x86_64-linux-gnu.so
# by generator 1.135
# no doc
# imports
import PyQt4.QtCore as __PyQt4_QtCore
import PyQt4.QtNetwork as __PyQt4_QtNetwork
from .KProcess import KProcess
class KPtyProcess(KProcess):
# n... | def __init__(self, *args, **kwargs): # real signature unknown
pass
AllChannels = 7
AllOutputChannels = 6
NoChannels = 0
| PtyChannelFlag = None # (!) real value is ''
PtyChannels = None # (!) real value is ''
StderrChannel = 4
StdinChannel = 1
StdoutChannel = 2
|
lukecwik/incubator-beam | sdks/python/apache_beam/runners/portability/fn_api_runner/__init__.py | Python | apache-2.0 | 865 | 0 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Ver | sion 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 writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or im... |
ragupta-git/ImcSdk | imcsdk/mometa/bios/BiosVfOSBootWatchdogTimer.py | Python | apache-2.0 | 3,929 | 0.009163 | """This module contains the general information for BiosVfOSBootWatchdogTimer ManagedObject."""
from ...imcmo import ManagedObject
from ...imccoremeta import MoPropertyMeta, MoMeta
from ...imcmeta import VersionMeta
class BiosVfOSBootWatchdogTimerConsts:
VP_OSBOOT_WATCHDOG_TIMER_DISABLED = "Disabled"
VP_OSBO... | E, 0x10, None, None, None, ["Disabled", "Enabled", "disabled", "enabled", "platform-default"], []),
"child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version151f, MoPropertyMeta.INTERNAL, None, None, None, None, [], []),
},
"modular": {
"dn": ... | , [], []),
"rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version2013e, MoPropertyMeta.READ_WRITE, 0x4, 0, 255, None, [], []),
"status": MoPropertyMeta("status", "status", "string", VersionMeta.Version2013e, MoPropertyMeta.READ_WRITE, 0x8, None, None, None, ["", "created", "deleted", "... |
Apkawa/simple-captcha-ocr-opencv | cap_extra/extras.py | Python | mit | 4,861 | 0.001646 | """
Copyright 2011 Dmitry Nikulin
This file is part of Captchure.
Captchure 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 ... | pt2 = (rect[0] + rect[2], rect[1] + rect[3])
cv.Rectangle(result, pt1, pt2, (0, 0, startcol + stepcol * index), 1)
return result
suffixes = {CAP_STAGE_PRE: | "pre", CAP_STAGE_SEG: "seg", CAP_STAGE_REC: "rec"}
titles = {CAP_STAGE_PRE: "Preprocessing", CAP_STAGE_SEG: "Segmentation", CAP_STAGE_REC: "Recognition"}
def getSuffix(stage):
try:
suffix = suffixes[stage]
except KeyError:
raise ValueError("Incorrect stage parameter")
return suffix
def g... |
tecnologiaenegocios/tn.plonemailing | src/tn/plonemailing/tests/base.py | Python | bsd-3-clause | 475 | 0.004211 | from Products.Five import zcml
from Products.Five import fiveconfigure
from Products.PloneTestCase import PloneTestCase as ptc
from Products.PloneTestCase.layer import onsetup
@onsetup
d | ef setup_product():
fiveconfigure.debug_mode = True
import tn.plonemailing
zcml.load_config('configure.zcml', tn.plonemailing)
fiveconfigure.debug_mode = False
setup_product()
ptc.setupPloneSite(product | s=['tn.plonemailing'])
class TestCase(ptc.PloneTestCase):
pass
|
scollis/iris | docs/iris/src/sphinxext/generate_package_rst.py | Python | gpl-3.0 | 7,563 | 0.006876 | # (C) British Crown Copyright 2010 - 2014, Met Office
#
# This file is part of Iris.
#
# Iris 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 l... | e
rootdir = os.path.dirname(module.__file__)
package_folder = []
module_folders = {}
for root, subFolders, files in os.walk(rootdir):
for fname in files:
name, ext = os.path.splitext(fname)
# skip some non-relevant files
if ( fname.startswith('.') or fname.... | rel_path = root_package + os.path.join(root, fname).split(rootdir)[-1]
mod_folder = root_package + os.path.join(root).split(rootdir)[-1].replace('/','.')
# only add to package folder list if it contains an __init__ script
if name == '__init__':
package_folder.append... |
CodeforLeipzig/luftqualitaet_sachsen | luftqualitaet_sachsen/tests/test_measuring_stations/test_models.py | Python | bsd-3-clause | 655 | 0 | from measuring_stations.models import MeasuringPoint
import pytest
def test_active_values():
mp = MeasuringPoint( | so2=True, o3=True)
assert mp.get_active_values() == ('so2', 'o3')
@pytest.fixture
def csv():
return "Datum Zeit; Leipzig-Mitte SO2\n" \
"; <B5>g/m<B3>\n" \
"01-07-14 11:00; 4,0\n" \
"01-07-14 10:00; 4,1"
@pytest.fixture
def params():
return []
@pytest.fixture
def stati... | rn "Leipzig-Mitte"
def test_import_values(csv, stationName, params):
pytest.mark.django_db(transaction=False)
mp = MeasuringPoint()
mp.put_csv(csv, stationName, params)
# assert
|
DemocracyClub/UK-Polling-Stations | polling_stations/apps/data_importers/management/commands/import_north_norfolk.py | Python | bsd-3-clause | 1,890 | 0.003704 | from data_importers.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = "NNO"
addresses_name = "2021-03-25T13:58:54.180597/Democracy_Club__06May2021.CSV"
stations_name = "2021-03-25T13:58:54.180597/Democracy_Club__06May2021.CSV"
... | [
"10034791449", # THE CEDARS, GRESHAM, NORWICH
"10023665747", # CHALET 4 MILL FARM AYLSHAM ROAD, FELMINGHAM
"10034812867", # BURROW COTTAGE AT WARREN BARN BREWERY ROAD, TRUNCH
"10034807115", # 6 SEAWARD CREST, LINKS ROAD, MUNDESLEY, NORWICH
"10034 | 818211", # GARDEN COTTAGE, HOVETON HALL ESTATE, HOVETON, NORWICH
"10034819670", # THE OLD GATEHOUSE, WALSINGHAM ROAD, EAST BARSHAM, FAKENHAM
"100091325096", # FLAT 6 7 NORWICH ROAD, CROMER
]:
return None
if record.addressline6 in ["NR12 0RX", "NR11 7PE", "NR12 8AH... |
ubccr/supremm | src/supremm/plugins/MemUsageTimeseries.py | Python | lgpl-3.0 | 3,532 | 0.003681 | #!/usr/bin/env python
""" Timeseries generator module """
from supremm.plugin import Plugin
from supremm.subsample import TimeseriesAccumulator
import numpy
from collections import Counter
class MemUsageTimeseries(Plugin):
""" Generate the CPU usage as a timeseries data """
name = property(lambda x: "memused... | self._hostdata[hostidx] = numpy.empty((TimeseriesAccumulator.MAX_DATAPOINTS, len(data[0])))
self._hostdevnames[hostidx] = dict((str(k), "numa " + v) for k, v in zip(description[0][0], description[0][1]))
nodemem_kb = numpy.sum(data[0]) - numpy.sum(data[1]) - numpy.sum(data[2])
insertat = se... | data[0] - data[1] - data[2]) / 1048576.0
return True
def results(self):
values = self._data.get()
if len(self._hostdata) > 64:
# Compute min, max & median data and only save the host data
# for these hosts
memdata = values[:, :, 1]
sortar... |
gregmarra/pxlart | layouts/couch_layout_gen.py | Python | mit | 1,417 | 0.018349 | ### NOTE NEED TO MANUALLY DELETE COMMA AFTER LAST POINT
LEDS_PER_METER = 30.0
# Dimensions from http://www.ikea.com/us/en/catalog/products/S99932597/
COUCH_WIDTH = 2.18
COUCH_DEPTH = 0.88
def layout_leds(width, depth, leds_per_meter):
led_coordinates = []
direction = ""
next_direction = "east"
x = -width/2
... | remainder = (y - depth/2)
y = depth/2
x = x - remainder
next_direction = "west"
if direction == "west":
x = x - 1/LEDS_PER_METER
if x < -depth/2:
remainder = (-depth/2) - x
x | = -depth/2
y = y - remainder
next_direction = "south"
if direction == "south":
y = y - 1/LEDS_PER_METER
if y < -depth/2:
break
direction = next_direction
led_coordinates.append((x, y))
return led_coordinates
def print_coordinates(led_coordinates):
print "["
for x... |
maui-packages/qt-creator | tests/system/suite_QMLS/tst_QMLS05/test.py | Python | lgpl-2.1 | 2,938 | 0.00919 | #############################################################################
##
## Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
## Contact: http://www.qt-project.org/legal
##
## This file is part of Qt Creator.
##
## Commercial License Usage
## Licensees holding valid commercial Qt licenses may use this f... | extMenuItem(editorArea, "Refactoring", "Split Initializer")
# wait until refactoring ended
waitFor("len(str(editorArea.plainText).splitlines()) == numLinesExpected", 5000)
# verify if refactoring was properly applied - each part on separate line
| verifyMessage = "Verifying split initializer functionality at element line."
for line in ["Item {", "x: 10;", "y: 20;", "width: 10", "}"]:
verifyCurrentLine(editorArea, line, verifyMessage)
type(editorArea, "<Down>")
#save and exit
invokeMenuItem("File", "Save All")
invokeMenuItem("File... |
JohanComparat/nbody-npt-functions | bin/bin_galform/plotLFs-color-mag-trends.py | Python | cc0-1.0 | 11,045 | 0.026075 | #! /usr/bin/env python
"""
This script produces quality plots to check that the LFs are fine compared to simumlations.
"""
import sys
import os
from os.path import join
data_dir = os.environ['DATA_DIR']
import glob
from lib_plot import *
#from lineListAir import *
SNlim = 5
# "D:\data\LF-O\LFmodels\data\trends_colo... | data[3] / dataRef[ | 3]
imin = n.argmax(dataRef[6])-1
p.figure(0,(6,6))
for jj in range(len(label)):
p.plot(dataRef[2][imin:],phiRatio[jj][imin:],label=label[jj])
p.xlabel(r'$log_{10}(L[O_{II}])$ [erg s$^{-1}$]')
p.ylabel(r'$\Phi/\Phi_{ref}$')
p.xscale('log')
p.xlim((7e40,5e43))
p.y |
siosio/intellij-community | python/testData/inspections/PyNonAsciiCharReferenceInspection/test.py | Python | apache-2.0 | 119 | 0.042735 | g = 2
i = 2
<warning descr="Non-ASCII c | haracter 'ɡ' in the file, but no encoding declared">ɡ</warning> = | 1
a = g + i
|
SeleniumHQ/selenium | py/selenium/webdriver/remote/file_detector.py | Python | apache-2.0 | 1,803 | 0 | # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | h 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 Li | cense 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 abc import ABCMeta, abstractmethod
import os
from typing import Optional
from selenium.type... |
freakboy3742/toga_web_demo | toga_django/widgets/list.py | Python | bsd-3-clause | 3,836 | 0.001564 | from django.core.urlresolvers import reverse, resolve
from | django.utils.html import escape
from .base import Widget
from ..libs import List as TogaList, SimpleListElement as TogaSimpleLis | tElement
class SimpleListElement(Widget):
def __init__(self, content, detail=None, **style):
super(SimpleListElement, self).__init__(**style)
self.content = content
self.detail = detail
self.startup()
def startup(self):
pass
def materialize(self):
return... |
rspavel/spack | lib/spack/spack/compilers/apple_clang.py | Python | lgpl-2.1 | 7,173 | 0.000279 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import os.path
import re
import shutil
import llnl.util.tty as tty
import llnl.util.lang
import spack.compiler
import spac... | os.symlink(
os.path.join(spack.paths.build_env_path, 'cc'),
os.path.join(dev_dir, fname) | )
os.symlink(developer_root, xcode_link)
env.set('DEVELOPER_DIR', xcode_link)
|
gustavofoa/pympm | scripts/locustfile.py | Python | apache-2.0 | 988 | 0.002024 | from locust import HttpLocust, TaskSet, task
class WebsiteTasks(TaskSet):
@task
def page1(self):
self.client.get("/sugestoes-para/6a-feira-da-quarta-semana-da-pascoa/")
@task
def page2(self):
self.client | .get( | "/sugestoes-para/5a-feira-da-quarta-semana-da-pascoa/")
@task
def page3(self):
self.client.get("/sugestoes-para/4a-feira-da-quarta-semana-da-pascoa/")
@task
def page4(self):
self.client.get("/sugestoes-para/3a-feira-da-quarta-semana-da-pascoa/")
@task
def musica1(self):
... |
cjmay/energyweb | graph/management/commands/energyfaker.py | Python | mit | 5,892 | 0.002206 | #!/usr/bin/env python
'''
Serve data on a TCP port (using the assumption that the machine can
listen on the specified address and port), imitating a Rhizome Systems
energy monitoring device. The imitation is accomplished by reading from
a "profile," i.e., a list of sample readings. Called with two
arguments: The ... | sor_id> start|stop|restart'
help = 'Imitat | e the specified Rhizome device.'
def handle(self, *args, **options):
if len(args) == 2:
try:
sensor_id = int(args[0])
except ValueError:
raise CommandError('Invalid sensor id: \'%s\'.' % args[0])
daemon = FakeRhizomeDaemon(
... |
hali4ka/robotframework-selenium2library | src/Selenium2Library/lib/selenium-2.8.1/py/selenium/webdriver/common/action_chains.py | Python | apache-2.0 | 7,157 | 0.002794 | # Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ap... | Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
| self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
s... |
krishna11888/ai | third_party/pattern/pattern/metrics.py | Python | gpl-2.0 | 42,773 | 0.008604 | #### PATTERN | METRICS #############################################################################
# coding: utf-8
# Copyright (c) 2010 University of Antwerp, Belgium
# Author: Tom De Smedt <tom@organisms.be>
# License: BSD (see LICENSE.txt for details).
# http://www.clips.ua.ac.be/pages/pattern
import sys
from tim... | urn Counter(self)
def __delitem__(self, k):
if k in self:
dict.__delitem__(self, k)
def __repr__(self):
return "Counter({%s})" % ", ".join("%r: %r" % e for e in | self.most_common())
try:
# Import Counter from Python 2.7+ if possible.
from collections import Counter
except:
pass
def cumsum(iterable):
""" Returns an iterator over the cumulative sum of values in the given list.
"""
n = 0
for x in iterable:
n += x
yield n
#### PROFIL... |
Plailect/PlaiCDN | PlaiCDN.py | Python | gpl-3.0 | 30,166 | 0.004575 | #!/usr/bin/env python3
#script is a replacement for https://github.com/Relys/3DS_Multi_Decryptor/blob/master/to3DS/CDNto3DS/CDNto3DS.py
#requires PyCrypto to be installed ("python3 -m ensurepip" then "pip3 install PyCrypto")
#requires makerom (https://github.com/profi200/Project_CTR/releases)
#this is a Python 3 script... | unhexlify
from Crypto.Cipher import AES
from hashlib import sha256
from imp import reload
import json
import platform
import os
import | struct
import errno
import shlex
import ssl
import sys
import urllib.request, urllib.error, urllib.parse
# from http://stackoverflow.com/questions/600268/
def pmkdir(path):
try:
os.makedirs(path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
... |
ugoertz/tippspiel | tippspiel/tools/vorrunde.py | Python | mit | 2,049 | 0.007809 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import datetime
import django
sys.path.append('/var/django/tippspiel')
django.setup()
from tipps.models import Spiel, Mannschaft, Runde
spiele = """
V1 | 2016-06-10, 21:00 | fra | rou
V1 | 2016-06-11, 15:00 | alb | sui
V1 | 2016-06-11, 18:00 | wal | svk
V1 | 2016... | | ukr | pol
V3 | 2016-06-21, 18:00 | nir | ger
V3 | 2016-06-21, 21:00 | cro | esp
V3 | 2016-06-21, 21:00 | cze | tur
V3 | 2 | 016-06-22, 21:00 | ita | irl
V3 | 2016-06-22, 21:00 | swe | bel
V3 | 2016-06-22, 18:00 | hun | por
V3 | 2016-06-22, 18:00 | isl | aut
"""
spielliste = [ l for l in spiele.split('\n') if l.strip() ]
for l in spielliste:
runde, datum, ms1, ms2 = l.split(' | ')
print datum, ms1, ms2
m1 = Mannschaft.objects.g... |
pettai/capirca | tools/cgrep.py | Python | apache-2.0 | 2,954 | 0.009479 | # Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | ' use
# $ cgrep.py -c FOO BAR
#
__author__ = "watson@google.com (Tony Watson)"
import sys
sys.path.append('../')
from lib import naming
from lib import nacaddr
from optparse import OptionParser
def main(argv):
parser = OptionParser()
parser.add_option("-d", "--def", dest="defs", action="store",
... | i", "--ip", dest="ip", action="store",
help="Return list of defintions containing this IP. "
"Multiple IPs permitted.")
parser.add_option("-t", "--token", dest="token", action="store",
help="See if an IP is contained within this token."
... |
vladan-m/ggrc-core | src/tests/ggrc/behave/factories.py | Python | apache-2.0 | 12,159 | 0.019163 | # Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: david@reciprocitylabs.com
# Maintained By: david@reciprocitylabs.com
import datetime
import factory
import random
from factory.base import BaseFact... | :
attr_name = attr
class_attr = getattr(model_class, attr_name)
#look | up the class method to use to generate the attribute
method = getattr(cls, class_attr.__class__.__name__)
value = method(attr_name, class_attr)
attrs[attr_name] = value
@classmethod
def InstrumentedAttribute(cls, attr_name, class_attr):
method = getattr(cls, class_attr.property.__class__.__nam... |
brain-research/conv-sv | conv2d_singular_values_test.py | Python | apache-2.0 | 7,125 | 0.006737 | """
Copyright 2018 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to... | d, one-channel filter and an input size, return the matrix
of the linear transformation corresponding to the | filter"""
transform_mat = np.zeros([n ** 2, n ** 2])
for i1 in range(n):
for i2 in range(n):
for j1 in range(filter.shape[0]):
for j2 in range(filter.shape[1]):
col = ((i1 + j1) % n) * n + (i2 + j2) % n
transform_mat[i1 * n + i2, col] = filter[j1, j2]
return ... |
kaiweifan/horizon | openstack_dashboard/dashboards/project/loadbalancers/workflows.py | Python | apache-2.0 | 29,119 | 0.000275 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013, Big Switch 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... | kwargs)
if api.neutron.is_extension_supported(request, 'service-router'):
router | _network_choices = self.populate_router_network_choices(
request, context)
self.fields.insert(
|
paveenju/mlat-sim | main/figure2_2a.py | Python | gpl-3.0 | 1,441 | 0.008328 | '''
Created on Dec 5, 2016
@author: paveenju
'''
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib2tikz.save as tikz_save
import utils.functions as fn
if __name__ == '__main__':
pass
def axes():
plt.axhline(0, alpha=.1)
plt.axvline(0, alpha=.1... | _p = np.meshgrid(x_p, y_p)
x, y, h, k = fn.linear_transformation(P1, P2, x_p, y_p)
# matplotlib
mpl.rcParams['lines.color'] = 'k'
mpl.rcParams['axes.prop_cycle'] = mpl.cycler('color', ['k'])
for a in A:
plt.contour(x_p, y_p,
((x**2/a**2) - (y**2/(c**2-a**2)) - 1),
[0]... | ate(r'$\tau_3$', xy=(0, 0), xytext=(1.2, 2.1), fontsize=20)
plt.text(1.75, 0.5, r'$\tau_1=0.4$' + '\n' + r'$\tau_2=0.6$' + '\n' + r'$\tau_2=0.9$',
bbox={'facecolor':'white', 'alpha':0.5, 'pad':10},
fontsize=20)
plt.plot(P1[0], P1[1], 'xr', mew=5, ms=15)
plt.plot(P2[0], P2[1], 'xr', mew=5, ms=15... |
jamielennox/python-kiteclient | kiteclient/common/meta_data.py | Python | apache-2.0 | 1,416 | 0 | # 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 writing, software
# distributed under t... | ck.common import jsonutils
from kiteclient.openstack.common import timeutils
class Metadata(object):
def __init__(self, source, destination, timestamp=None, nonce= | None):
self.source = source
self.destination = destination
self.timestamp = timestamp or timeutils.utcnow()
self.nonce = nonce or self.gen_nonce()
@classmethod
def gen_nonce(cls):
return struct.unpack('Q', Random.new().read(8))[0]
def get_data(self):
return ... |
benoitc/uzmq | docs/conf.py | Python | mit | 9,957 | 0.007231 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# uzmq documentation build configuration file, created by
# sphinx-quickstart on Wed Nov 7 00:32:37 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogen... | HTML footer. Default is True.
#html_show_sphinx = True
# If | true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_op... |
ulno/micropython-extra-ulno | examples/integriot_test/testnode1/files/autostart.py | Python | mit | 1,163 | 0.00258 | # user.py is the autostart code for a ulnoiot node.
# Configure your devices, sensors and local interaction here.
# Always start with this to make everything from ulnoiot available.
# Therefore, do not delete the following line.
from ulnoiot import *
# The following is just example code, adjust to your needs accordin... | ly, we assume for this example
# the following configuration.
# mqtt("ulnoiotgw", "myroom/test1")
## Use some shields
# The onboard-led is a | lways available.
# With this configuration it will report under myroom/test1/blue
# and can be set via sending off or on to myroom/test1/blue/test.
from ulnoiot.shield.onboardled import blue
blue.high() # make sure it's off (it's reversed)
## Add some other devices
# Add a button with a slightly higher debounce rate... |
ecreall/nova-ideo | novaideo/views/reports_management/restor.py | Python | agpl-3.0 | 2,013 | 0.000497 | # Copyright (c) 2014 by Ecreall under licence AGPL terms
# available on http://www.gnu.org/licenses/agpl.html
# licence: AGPL
# author: Amen Souissi
import deform
from pyramid.view import view_config
from dace.processinstance.core import DEFAULTMAPPING_ACTIONS_VIEWS
from pontus.default_behavior import Cancel
from p... | viewid = 'restorentity'
template = 'pontus:templates/views_templates/simple_multipleview.pt'
views = (RestorViewStudyRestor, RestorFormV | iew)
validators = [Restor.get_validator()]
DEFAULTMAPPING_ACTIONS_VIEWS.update(
{Restor: RestorView})
|
takeflight/wagtail | wagtail/tests/testapp/models.py | Python | bsd-3-clause | 43,462 | 0.001196 | import hashlib
import json
import os
import uuid
from django import forms
from django.conf import settings
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ValidationError
from django.core.paginator import Emp... | '),
FieldPanel('content'),
]
class PageWithOldStyleRouteMethod(Page):
"""
Prior to Wagtail 0.4, the route() method on Page returned an HttpResponse
rather than a Page instance. As subclasses of Page may override route,
we need to continue accepting this convention (albeit as a deprecated A... | serve(request)
# File page
class FilePage(Page):
file_field = models.FileField()
FilePage.content_panels = [
FieldPanel('title', classname="full title"),
FieldPanel('file_field'),
]
# Event page
class EventPageCarouselItem(Orderable, CarouselItem):
page = ParentalKey('tests.EventPage', related_na... |
gmarciani/ipath | model/linkedlist.py | Python | mit | 11,316 | 0.009544 | #Interface Import
from model.base.baselinkedlist import baselinkedlist
class SimpleLinkedList(baselinkedlist):
class Record:
def __init__(self, element):
self.element = element
self._next = None
def __repr__(self):
return str(sel... | (self):
self._first = None
self._last = None
self._num_elements = 0
def is_empty(self):
"""
Returns True if linked- | list is empty, otherwise False.
is_empty() -> True/False
@rtype: bool
@return: True if empty, False otherwise.
"""
return (self._first is None)
def add_as_first(self, element):
"""
Adds element as first into the linked-list.
... |
flandr/kerberos-keyutil | keyutil/keytab.py | Python | bsd-2-clause | 5,159 | 0.00252 | #!/usr/bin/env python
# Copyright (c) 2015, Nate Rosenblum
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the... | ()
parser.add_argument("principal", metavar='principal', type=str, nargs=1,
help='Principal name (name@realm)')
parser.add_argument("--kvno", dest="kvno", action="store", default=1,
help='Key version number (default 1)')
parser.add_argument("--password", dest="password", action="stor... | default=None, help='Password agument (default is to prompt)')
parser.add_argument("-o", "--output", dest="output", action="store",
default="keytab", help='Output keytab file name')
options = parser.parse_args()
if not options.password:
options.password = getpass.getpass("Password")
... |
ya-mouse/python-opcua | opcua/internal_server.py | Python | lgpl-3.0 | 8,403 | 0.002856 | """
Internal server implementing opcu-ua interface. can be used on server side or to implement binary/https opc-ua servers
"""
from datetime import datetime
from copy import copy
import logging
from threading import Lock
from enum import Enum
try:
from urllib.parse import urlparse
except ImportError:
from urlp... | rn self.iserver.attribute_service.write(params, self.user)
def browse(self, params):
return self.iserver.view_service.browse(params)
def translate_browsepaths_to_nodeids(self, params):
return self.iserver.view_service.translate_browsepaths_to_nodeids(params)
def add_nodes(self, params):
... | mgt_service.add_nodes(params, self.user)
def add_method_callback(self, methodid, callback):
return self.aspace.add_method_callback(methodid, callback)
def call(self, params):
return self.iserver.method_service.call(params)
def create_subscription(self, params, callback):
result = ... |
drpngx/tensorflow | tensorflow/contrib/data/python/kernel_tests/serialization/tf_record_dataset_serialization_test.py | Python | apache-2.0 | 3,947 | 0.006081 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | None):
filenames = self._createFiles()
if compression_type == "ZLIB":
zlib_files = []
for i, fn in enumerate(filenames):
with open(fn, "rb") as f:
cdata = zlib.compress(f.read())
zfn = os.path.join(self.get_temp_dir(), "tfrecord_%s.z" % i)
with open(zfn, "wb") a... | b_files.append(zfn)
filenames = zlib_files
elif compression_type == "GZIP":
gzip_files = []
for i, fn in enumerate(self.test_filenames):
with open(fn, "rb") as f:
gzfn = os.path.join(self.get_temp_dir(), "tfrecord_%s.gz" % i)
with gzip.GzipFile(gzfn, "wb") as gzf:
... |
ldolberg/the_port_ors_hdx | src/district_distance.py | Python | apache-2.0 | 1,973 | 0.014698 |
import math
import operator
import json
from geopy.distance import great_circle
class Order_districts():
def get_district_info():
# -- get names and coordinates from csv file
with open('coordinates.json') as coord_file:
district_dict = json.load(coord_file)
return dis... | Inputs: 'lat0' = latitude of point at center of map
'lon0' = longitude of point at cent | er of map
'district_dict' = dict of district names and (lat,lon) from function get_district_info()
Outputs: df with district names ordered by distance, coordinates of district (lat,lon)
'''
distance_dict={}
# -- loop thru entries in coord/name dictionary
for key, ... |
aricaldeira/pybrasil | pybrasil/inscricao/pis.py | Python | lgpl-2.1 | 2,760 | 0.000366 | # -*- coding: utf-8 -*-
#
# PyBrasil - Functions useful for most Brazil's ERPs
#
# Copyright (C) 2016-
# Copyright (C) Aristides Caldeira <aristides.caldeira at tauga.com.br>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Library General Public License as
# publ... | return pis
pis = LIMPA.sub('', pis)
p | is = str(int(pis))
digito = pis[-1]
numero = pis[:-1][::-1]
numero = numero[0:2] + '.' + numero[2:7] + '.' + numero[7:]
numero = numero[::-1]
return numero + '-' + digito
|
python-poetry/poetry-core | src/poetry/core/_vendor/lark/grammar.py | Python | mit | 2,918 | 0.00377 | from .utils import Serialize
###{standalone
class Symbol(Serialize):
__slots__ = ('name',)
is_term = NotImplemented
def __init__(self, name):
self.name = name
def __eq__(self, other):
assert isinstance(other, Symbol), other
return self.is_term == other.is_term and self.name ... | lse, expand1=False, priority=None, template_source=None, empty_indices=()):
self.keep_all_tokens = keep_all_tokens
self.expand1 = expand1
self.priority = priority
self.template_source = template_source
self.empty_indices = empty_indices
def __repr__(self):
return 'Ru... | self.priority,
self.template_source
)
class Rule(Serialize):
"""
origin : a symbol
expansion : a list of symbols
order : index of this expansion amongst all rules of the same name
"""
__slots__ = ('origin', 'expansion', 'alias', 'options', 'order', '_hash')
... |
pratapvardhan/pandas | pandas/tests/plotting/common.py | Python | bsd-3-clause | 19,374 | 0.000103 | #!/usr/bin/env python
# coding: utf-8
import pytest
import os
import warnings
from pandas import DataFrame, Series
from pandas.compat import zip, iteritems
from pandas.util._decorators import cache_readonly
from pandas.core.dtypes.api import is_list_like
import pandas.util.testing as tm
from pandas.util.testing impor... | Collection)):
result = tuple(patch.get_edgecolor()[0])
else:
result = patch.get_edgecolor()
expected = conv.to_rgba(color)
assert result == expected
if facecolors is not None:
if mapping is not None:
... | lors_mapped(mapping, facecolors)
facecolors = facecolors[:len(collections)]
assert len(collections) == len(facecolors)
for patch, color in zip(collections, facecolors):
if isinstance(patch, Collection):
# returned as list of np.array
... |
MrJohz/snooble | snooble/__init__.py | Python | mit | 4,756 | 0.002523 | import collections
import time
from urllib import parse as urlp
import requests
from . import oauth, errors, responses
from .ratelimit import RateLimiter
AUTH_DOMAIN = 'https://oauth.reddit.com/'
WWW_DOMAIN = 'https://www.reddit.com/'
Domain = collections.namedtuple('Domain', ['auth', 'www'])
class Snooble(objec... | url = urlp.urljoin(self.domain.auth, url)
response = self._limited_session.get(url, headers=headers, par | ams=kwargs)
return responses.create_response(response.json())
|
bruth/django-registration2 | registration/managers.py | Python | bsd-3-clause | 1,879 | 0.000532 | import re
import random
import hashlib
from django.db import models
SHA1_RE = re.compile('^[a-f0-9]{40}$')
class RegistrationManager(models.Manager):
"""Custom manager for the ``RegistrationProfile`` model.
The methods defined here provide shortcuts for account creation
and activation (including generati... | has expired, return ``False``.
If the key is valid but the ``User`` is already active,
return ``False``.
"""
# Make sure the key we're trying conforms to the pattern of a
# SHA1 hash; if it doesn't, no point trying to look it up in
# the database.
if SHA1_RE.sea... | profile = self.get(activation_key=activation_key)
except self.model.DoesNotExist:
return
return profile.activate()
def create_profile(self, user):
"""Create a ``RegistrationProfile`` for a given ``User``, and return
the ``RegistrationProfile``.
The ... |
Adoni/WeiboSpider | monitor/helper.py | Python | gpl-3.0 | 873 | 0.033219 | #coding:utf8
import re
import random
import time
import lxml.html
import json
def sleep(sleep_time):
sleep_time=sleep_time+random.randint(-2,2)
#print sleep_time
if sleep_time<=0:
sleep_time=0
#print('Sleeping for '+str(sleep_time)+' seconds')
time.sleep | (sleep_time)
#print('Wake up')
def get_target(html):
if(not 'location.replace' in html):
#print('No location.replace in html')
return None
pat="location.replace\('[^']*'\)"
a=re.findall(pat,html)
pat='location.replace\("[^"]*"\)'
b=re.findall(pat,html)
ans=[]
for url in ... |
for url in b:
ans.append(url[18:-2])
if(ans==[]):
return None
else:
return ans
if __name__=='__main__':
print 'Helper'
#print get_average_statuses_count()
#check()
#output_all_uids()
|
futurecolors/django-geoip | django_geoip/management/iso3166_1.py | Python | mit | 6,017 | 0 | # -*- coding: utf-8 -*-
ISO_CODES = {
"AF": "Afghanistan",
"AX": "Åland",
"AL": "Albania",
"DZ": "Algeria",
"AS": "American Samoa",
"AD": "Andorra",
"AO": "Angola",
"AI": "Anguilla",
"AQ": "Antarctica",
"AG": "Antigua and Barbuda",
"AR": "Argentina",
"AM": "Armenia",
... |
"SN": "Senegal",
"RS": "Serbia",
"SC": "Seychelles",
"SL": "Sierra Leone",
"SG": "Singapore",
"SX": "Sint Maarten",
"SK": "Slovakia",
"SI": "Slovenia",
"SB": "Solomon Islands",
"SO": "Somalia",
"ZA": "South Africa",
"GS": "South Georgia and South Sandwich Islands",
"... | "Svalbard and Jan Mayen Islands",
"SZ": "Swaziland",
"SE": "Sweden",
"CH": "Switzerland",
"SY": "Syria",
"TW": "Taiwan",
"TJ": "Tajikistan",
"TZ": "Tanzania",
"TH": "Thailand",
"TL": "Timor-Leste",
"TG": "Togo",
"TK": "Tokelau",
"TO": "Tonga",
"TT": "Trinidad and Toba... |
sahat/bokeh | examples/glyphs/daylight.py | Python | bsd-3-clause | 3,445 | 0.007837 | from __future__ import print_function
import numpy as np
import datetime as dt
from bokeh.browserlib import view
from bokeh.document import Document
from bokeh.embed import file_html
from bokeh.glyphs import Patch, Line, Text
from bokeh.objects import (
ColumnDataSource, DataRange1d, DatetimeAxis, DatetimeTickFor... | = df[df.Summer == 1]
patch2_source = ColumnDataSource(dict(
dates = np.concatenate((summer.Date, summer.Date[::-1])),
times = np.concatenate((summer.Sunrise, summer.Sunset[::-1]))
))
summer_start = df.Summer.tolist().index(1)
summer_end = df.Summer.tolist().index(0, summ | er_start)
calendar_start = df.Date.irow(0)
summer_start = df.Date.irow(summer_start)
summer_end = df.Date.irow(summer_end)
calendar_end = df.Date.irow(-1)
d1 = calendar_start + (summer_start - calendar_start)/2
d2 = summer_start + (summer_end - summer_start)/2
d3 = summer_end + (calendar_end - summer_end)/2
text_sou... |
inspoy/BounceArena | tools/protocol/protocol.py | Python | apache-2.0 | 13,731 | 0.001675 | #!/usr/local/bin/python3
# -*- coding: utf-8 -*-
import os.path
import shutil
import time
def get_protocol_data():
filename = "protocol.csv"
raw_data = []
try:
inp = open(filename, mode='r', encoding='utf-8')
lines = inp.readlines()
for line in lines:
fields = line.rstr... | str_default_value = "0"
str_fields += " this.%s = %s;\n" % (field["name"], str_default_value)
# end for
pass
res += " */\n" \
"class SFMsgData%s {\n" \
" constructor() {\n" \
| "%s" \
" }\n" \
"}\n" \
"exports.SFMsgData%s = SFMsgData%s;\n" \
"\n" % (name, str_fie |
the-zebulan/CodeWars | tests/kyu_5_tests/test_human_readable_time.py | Python | mit | 561 | 0 | import unittest
from katas.kyu_5.human_readable_time import make_readable
class HumanReadableTimeTestCase(unittest.TestCase):
def test_equals( | self):
self.assertEqual(make_readable(0), '00:00:00')
def test_equals_2(self):
self.assertEqual(make_readable(5), '00:00:05')
def test_equals_3(self):
self.assertEqual(make_readable(60), '00:01:00')
def test_equals_4(self):
self.assertEqual(make_readable(86399), '23:59:59'... |
def test_equals_5(self):
self.assertEqual(make_readable(359999), '99:59:59')
|
Koheron/lase | examples/spectrum_analyzer.py | Python | mit | 1,482 | 0.006073 | #!/usr/bin/env python
# -* | - coding: utf-8 -*-
import os
| import time
import numpy as np
import matplotlib
matplotlib.use('GTKAgg')
from matplotlib import pyplot as plt
from koheron import connect
from drivers import Spectrum
from drivers import Laser
host = os.getenv('HOST','192.168.1.100')
client = connect(host, name='spectrum')
driver = Spectrum(client)
laser = Laser(cli... |
runmyrobot/runmyrobot | telly.py | Python | apache-2.0 | 1,037 | 0.007715 |
import robot_util
de | f sendSettings(ser, args):
if args.right_wheel_forward_speed is not None:
robot_util.sendSerialCommand(ser, "rwfs " + str(args.right_wheel_forward_speed))
if args.right_wheel_backward_speed is not None:
robot_util.sendSerialCommand(ser, "rwbs " + str(args.right_wheel_backward_speed))
if a... | robot_util.sendSerialCommand(ser, "lwbs " + str(args.left_wheel_backward_speed))
if args.straight_delay is not None:
robot_util.sendSerialCommand(ser, "straight-distance " + str(int(args.straight_delay * 255)))
if args.turn_delay is not None:
robot_util.sendSerialCommand(ser, "turn-distance ... |
dcowden/cadquery-freecad-module | CadQuery/Examples/Ex011_Mirroring_Symmetric_Geometry.py | Python | lgpl-3.0 | 447 | 0.011186 | #This example is meant to be used from within t | he CadQuery module of FreeCAD.
import cadquery
import Part
#1.0 is the distance, not coordinate
r = cadquery.Workplane("front").hLine(1.0)
#hLineTo allows using xCoordinate not distance
r = r.vLine(0.5).hLine(-0.25).vLine(-0.25).hLineTo(0.0)
#Mirror the geometry and extrude
resu | lt = r.mirrorY().extrude(0.25)
#Boiler plate code to render our solid in FreeCAD's GUI
Part.show(result.toFreecad())
|
cansik/pg4nosql | pg4nosql/PostgresNoSQLTable.py | Python | mit | 4,608 | 0.00217 | import copy
import json
from psycopg2.extensions import AsIs
from psycopg2.extras import RealDictCursor
from pg4nosql import DEFAULT_JSON_COLUMN_NAME, DEFAULT_ROW_IDENTIFIER
from pg4nosql.PostgresNoSQLQueryStructure import PostgresNoSQLQueryStructure
from pg4nosql.PostgresNoSQLResultItem import PostgresNoSQLResultItem
... | AsIs(table_name),
AsIs(on_statement),
| AsIs(query)))
rows = [item for item in self.cursor.fetchall()]
items = map(lambda r: PostgresNoSQLResultItem(r, self), rows)
return items
def query_one(self, query='True', columns='*'):
result = self.query(query, columns)
if not result:
return None
retu... |
plotly/python-api | packages/python/plotly/plotly/validators/treemap/marker/colorbar/_ticklen.py | Python | mit | 515 | 0.001942 | import _plotly_utils.basevalidators
class TicklenValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self, plotly_name="ticklen", parent_name="treemap.marker.colorbar", **kwargs
):
super(Tickle | nValidator, self).__init__(
plot | ly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "colorbars"),
min=kwargs.pop("min", 0),
role=kwargs.pop("role", "style"),
**kwargs
)
|
Havate/havate-openstack | proto-build/gui/horizon/Horizon_GUI/openstack_dashboard/usage/views.py | Python | apache-2.0 | 2,020 | 0 | from horizon import tables
from openstack_dashboard.usage import base
class UsageView(tables.DataTableView):
usage_class = None
show_terminated = True
def __init__(self, *args, **kwargs):
super(UsageView, self).__init__(*args, **kwargs)
if not issubclass(self.usage | _class, base.BaseUsage):
raise AttributeError("You must specify a usage_class attribute "
"which is a subclass of BaseUsage.")
def get_template_names(self):
if self.request.GET.get('format', 'html') == 'csv':
return ".".join((self.template_name.rspli... | tent_type(self):
if self.request.GET.get('format', 'html') == 'csv':
return "text/csv"
return "text/html"
def get_data(self):
project_id = self.kwargs.get('project_id', self.request.user.tenant_id)
self.usage = self.usage_class(self.request, project_id)
self.usag... |
srowen/spark | python/pyspark/mllib/classification.py | Python | apache-2.0 | 33,064 | 0.001331 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | TYPE_CHECKING:
from pyspark.mllib._typing import VectorLike
__all__ = [
"LogisticRegressionModel",
"LogisticRegressionWithSGD",
"Log | isticRegressionWithLBFGS",
"SVMModel",
"SVMWithSGD",
"NaiveBayesModel",
"NaiveBayes",
"StreamingLogisticRegressionWithSGD",
]
class LinearClassificationModel(LinearModel):
"""
A private abstract class representing a multiclass classification
model. The categories are represented by int... |
cedricmenec/mysql-backup-service | main.py | Python | mit | 626 | 0.004792 | from app import app
from flask import jsonify
from backup.api import api as api_backup
from backup.api import api_restore
# Blueprints registration
app.register_blueprint(api_backup, url_prefix='/api/backup')
app.register_blueprint(api_restore, url_prefix='/api/restore')
@ap | p.route('/api/help', methods = ['GET'])
def help():
"""Print available functions."""
func_list = {}
for rule in app.url_map.iter_rules():
if rule.endpoint != 'static':
func_list[rule.rule] = app.view_functions[ru | le.endpoint].__doc__
return jsonify(func_list)
if __name__ == '__main__':
app.run('0.0.0.0') |
morepath/morepath | morepath/tests/fixtures/config/settings.py | Python | bsd-3-clause | 1,065 | 0 | """Example settings python dictionary for Morepath.
It contains also a helper function to create a JSON config file
from this dictionary.
"""
import json
settings = {
"chameleon": {"debug": True},
"jinja2": {
"auto_reload": False,
"autoescape": True,
"extensions": ["jinja2.ext.autoes... | : 2},
}
def create_json_config():
stream = open("settings.json", "w")
json.dump(
settings, stream, sort_keys=True, indent=4, separators=(",", ": ")
)
print(
json.dumps(settings, sort_ke | ys=True, indent=4, separators=(",", ": "))
)
|
douglaskastle/AcraNetwork | AcraNetwork/protocols/network/BaseAddress.py | Python | gpl-2.0 | 1,174 | 0.013629 | class BaseAddress():
_str = ''
@property
def str(self):
if None == self.int:
return None
else:
return self.intToAddr(self.int)
def __init__(self, i=None):
if None == i:
self.int = None
elif isinstance(i, int):
self... | if o == None and self.int == o:
return True
elif isinstance(o, int) and self.int == o:
return True
elif isinstance(o, str) and self.str == o:
return True
return False
def __ne__(self, o):
return not self.__eq__(o)
def __add__(self... | raise NotImplementedError
def addrToInt(self, i):
raise NotImplementedError
|
realer01/aiohttp-debugtoolbar | examples/simple.py | Python | apache-2.0 | 1,624 | 0 | import asyncio
import jinja2
import aiohttp_debugtoolbar
import aiohttp_jinja2
from aiohttp import web
@aiohttp_jinja2.template('index.html')
def basic_handler(request):
return {'title': 'example aiohttp_debugtoolbar!',
'text': 'Hello aiohttp_debugtoolbar!',
'app': request.app}
@asyncio... | dInter | rupt:
loop.run_until_complete(handler.finish_connections())
|
erudit/zenon | tests/unit/apps/public/book/test_views.py | Python | gpl-3.0 | 771 | 0.001297 | import pytest
from apps.public.book.test.factories import BookCollectionFactory, BookFactory
from apps.public.book.views import BookListView
@pytest.mark.django_db
class TestBookListView:
def test_books_order(self):
collection = BookCo | llectionFactory()
book_1 = BookFactory(collection=collection, year='2000', title='A')
book_2 = BookFactory(collection=collection, year='2000', title='B')
book_3 = BookFactory(collection=collec | tion, year='2002', title='D')
book_4 = BookFactory(collection=collection, year='2001', title='C')
view = BookListView()
view.object_list = None
context = view.get_context_data()
assert list(context['collections'][0].books.all()) == [book_3, book_4, book_1, book_2]
|
pierrejean-coudert/winlibre_pm | package_manager/smart/media.py | Python | gpl-2.0 | 12,238 | 0.001879 | #
# Copyright (c) 2005 Canonical
# Copyright (c) 2004 Conectiva, Inc.
#
# Written by Gustavo Niemeyer <niemeyer@conectiva.com>
#
# This file is part of Smart Package Manager.
#
# Smart Package Manager is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as publi... | s(path, comparepath)):
return True
return False
def __lt__(self, other):
return self.order < other.order
class MountMedia(Media):
def mount(self):
if self.isMounted():
return True
if self._device:
cmd = "mount %s %s" % (self._device, sel... | if self._options:
cmd += " -o %s" % self._options
status, output = commands.getstatusoutput(cmd)
if status != 0:
iface.debug(output)
return False
return True
class UmountMedia(Media):
def umount(self):
if not self.isMounted():
return ... |
JulyKikuAkita/PythonPrac | cs15211/Leaf-SimilarTrees.py | Python | apache-2.0 | 3,524 | 0.00454 | __source__ = 'https://leetcode.com/problems/leaf-similar-trees/'
# Time: O(N + M)
# Space: O(N + M)
#
# Description: Leetcode # 872. Leaf-Similar Trees
#
# Consider all the leaves of a binary tree.
# From left to right order, the values of those leaves form a leaf value sequence.
#
# For example, in the given tree abo... | public boolean leafSimilar(TreeNode root1, TreeNode root2) {
Queue<Inte | ger> q = new LinkedList<Integer>();
buildLeafNodeSeq(root1, q, true);
buildLeafNodeSeq(root2, q, false);
if (q.isEmpty()) return true;
return false;
}
private void buildLeafNodeSeq(TreeNode node, Queue<Integer> q, boolean add) {
if (node == null) {
return;
... |
marcb1/groupme_bot | src/groupme_bot.py | Python | gpl-2.0 | 891 | 0.042649 | import os
from flask import Flask
from flask import request
import requests
import ran | dom
import codecs
#API id
#move this to a config file
bot_id = ''
app = Flask(__name__)
#encode string as ASCII
def stripped(text):
text = text.lower()
return text.encode('ascii','replace_spc')
def send(text):
message = {
'text' : text,
'bot_id' : bot_id
}
r = requests.post("https://api.groupme.com/v3/bot... |
user_id = request.json['user_id']
nick = request.json['name'].lower()
message = request.json['text'].lower()
message = stripped(message).strip()
print 'Got message' + message
message_callback.got_message(message, nick);
return ''
if __name__ == "__main__":
app.run(port = 8080, host... |
flipcoder/bitplanes | sg.py | Python | mit | 80 | 0.0125 | # sgmake | script to use clang instead of gcc
makefile_params=["CXX=\'clang+ | +\'"]
|
jiaphuan/models | research/object_detection/utils/shape_utils_test.py | Python | apache-2.0 | 13,659 | 0.006003 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | pad_t2 = shape_utils.pad_tensor(t2, 2)
self.assertEqual(2, pad_t1.get_shape()[0])
self.assertEqual(2, pad_t2.get_shape()[0])
with self.test_session() as sess:
pad_t1_result, pad_ | t2_result = sess.run([pad_t1, pad_t2])
self.assertAllEqual([1, 0], pad_t1_result)
self.assertAllClose([[0.1, 0.2], [0, 0]], pad_t2_result)
def test_pad_tensor_using_tensor_input(self):
t1 = tf.constant([1], dtype=tf.int32)
pad_t1 = shape_utils.pad_tensor(t1, tf.constant(2))
t2 = tf.constant([... |
tonybeltramelli/Deep-Spying | server/analytics/modules/label/Label.py | Python | apache-2.0 | 725 | 0.002759 | __author__ = 'Tony Beltramelli www.tonybeltramelli.com - 06/09/2015'
import numpy as np
class Label:
def __init__(self, path):
file_path = "{}labels.csv".format(path)
try:
data = np.genfromtxt(file_ | path, delimiter=',', skip_header=1,
names=['timestamp', 'label'], dtype=[("timestamp", long), ('label', int)])
self.has_label = True
except IOError:
self.has_label = False
return
self.timestamp = data['timestamp']
label = data... | .append(chr(int(label[i])))
self.diff = np.diff(self.timestamp)
|
knoppo/tcprocd | tcprocd/client.py | Python | mit | 7,172 | 0.000697 | """tcprocd client."""
from __future__ import unicode_literals, print_function, absolute_import
from tcprocd.protocol import Protocol
import socket
import select
import sys
if sys.version_info[0] < 3:
str_types = (str, unicode) # noqa
else:
str_types = (str, bytes) # noqa
class SocketShell(object):
"""... | and port or the path to the socket file
"""
def __init__(self, server_address):
"""Initialize client."""
self.server_address = server_address
if isinstance(server_address, str_types):
self.is_unix_domain = True
sock_type = socket.AF_UNIX
else:
... | et.SOCK_STREAM)
self.protocol = Protocol(self.socket)
self.server_version = None
self.attached_to = None
def connect(self, username=None, password=None, username_callback=None, password_callback=None):
"""Connect to the server."""
if self.is_unix_domain:
try:
... |
jjst/rbpriority | setup.py | Python | mit | 601 | 0 | from reviewboard.extensions.packaging import setup
PACKAGE = "rbpriori | ty"
VERSION = "0.1"
setup(
name=PACKAGE,
version=VERSION,
description="Extension rbpriority",
author="Jeremie Jost",
packages=["r | bpriority"],
entry_points={
'reviewboard.extensions':
'%s = rbpriority.extension:PriorityExtension' % PACKAGE,
},
package_data={
'rbpriority': [
'templates/rbpriority/*.txt',
'templates/rbpriority/*.html',
],
},
scripts=['bin/rb-priority-al... |
irinabov/debian-qpid-cpp-1.35.0 | src/tests/acl_1.py | Python | apache-2.0 | 17,802 | 0.00573 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | ssn.receiver("amq.topic")
assert False, "anonymous | should not be allowed to create receiver from amq.topic"
except UnauthorizedAccess: pass
try:
self.bob.receiver("amq.topic")
assert False, "bob should not be allowed to create receiver to amq.topic"
except UnauthorizedAccess: pass
self.alice.receiver("amq.topic")... |
axbaretto/beam | sdks/python/.tox/lint/lib/python2.7/site-packages/pylint/test/functional/wrong_import_position9.py | Python | apache-2.0 | 202 | 0.00495 | """Checks | import position rule"""
# pylint: disable=unused-import,relative-import,ungrouped-imports,import-error,no-name-in-module
import y
try:
import x
except | ImportError:
pass
else:
pass
|
Geontech/docker-redhawk-ubuntu | Dockerfiles/files/build/ide-fetcher.py | Python | gpl-3.0 | 1,661 | 0.004816 | #!/usr/bin/python
# Author: Thomas Goodwin <btgoodwin@geontech.com>
import urllib2, json, os, sys, re
def download_asset(path, url):
asset_path = None
try:
file_name = os.path.basename(url)
asset_path = os.path.join(path, file_name)
if os.path.exists(asset_path):
# Skip do... | turn asset_path
def handle_release_assets(ass | ets):
assets = [ asset for asset in assets if re.match(r'redhawk-ide.+?(?=x86_64)', asset['name'])]
if not assets:
sys.exit('Failed to find the IDE asset')
elif len(assets) > 1:
sys.exit('Found too many IDE assets matching that description...?')
return download_asset('downloads', assets[... |
pacoqueen/ginn | extra/install/ipython2/ipython-5.10.0/setup.py | Python | gpl-2.0 | 10,245 | 0.007516 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Setup script for IPython.
Under Posix environments it works like a typical setup.py script.
Under Windows, the command sdist is not supported, since IPython
requires utilities which are not available under Windows."""
#--------------------------------------------------... | the terms of the Modified BSD License.
#
# The full license is in the file COPYING.rst, distributed with this software.
#--------- | --------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Minimal Python version sanity check
#-----------------------------------------------------------------------------
from __future__ import print_function
import sys
# T... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.