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 |
|---|---|---|---|---|---|---|---|---|
petrjasek/superdesk-core | superdesk/macros/imperial/length_feet_and_inches_to_metric.py | Python | agpl-3.0 | 4,093 | 0.002199 | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import re
fr... | bol_index = 7 # Index of feet symbol ', ft, feet, foot
inches_with_feet_value_index = 11 # When there is a feet and inch value matched together
inches_symbol_index = 5 # In | dex of inches symbol ", in, inch(es)
def convert(match):
match_item = match.group(match_index).strip()
from_value = match.group(value_index)
inches_from_value = "0"
feet_symbol = match.group(feet_symbol_index)
inches_symbol = match.group(inches_symbol_index)
multi_va... |
nickpascucci/AppDesign | download/download_test.py | Python | mit | 1,195 | 0.021757 | #! /usr/bin/env python
"""Unit tests for the image downloader."""
import unittest
import download
__author__ = "Nick Pascucci (npascut1@gmail.com)"
class DownloadTest(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_img_matcher(self):
html = """<html>
<bod... | download.m | atch_extension(filename)
filename = "abcdef.txt"
assert not download.match_extension(filename)
def test_sitename_matcher(self):
site = "http://www.xkcd.com/208/"
sitename = download.sitename(site)
assert "http://www.xkcd.com" == sitename
if __name__ == "__main__":
... |
florianholzapfel/home-assistant | tests/components/device_tracker/test_init.py | Python | mit | 24,131 | 0.000041 | """The tests for the device tracker component."""
# pylint: disable=protected-access
import asyncio
import json
import logging
import unittest
from unittest.mock import call, patch
from datetime import datetime, timedelta
import os
from homeassistant.core import callback
from homeassistant.bootstrap import setup_compo... | 'nodict.yaml': '100',
'badkey. | yaml': '@:\n name: Device',
'noname.yaml': 'my_device:\n',
'allok.yaml': 'My Device:\n name: Device',
'oneok.yaml': ('My Device!:\n name: Device\n'
'bad_device:\n nme: Device')}
args = {'hass': self.hass, 'consider_home': ... |
beobal/cassandra | pylib/cqlshlib/test/run_cqlsh.py | Python | apache-2.0 | 12,091 | 0.002316 | # 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 u... | return buf
def read_pipe(self, blksize, timeout=None):
buf = self.proc.stdout.read(blksize)
if isinstance(buf, bytes):
buf = buf.decode("utf-8")
return buf
def read_winpty(self, blksize, timeout=None):
buf = self.winpty.read(blksize, timeout)
if isinstance(... | flags=0, ptty_timeout=None, replace=[]):
if not isinstance(until, Pattern):
until = re.compile(until, flags)
cqlshlog.debug("Searching for %r" % (until.pattern,))
got = self.readbuf
self.readbuf = ''
with timing_out(timeout):
while True:
... |
jamespacileo/django-pure-pagination | example_project/core/names.py | Python | bsd-3-clause | 54,755 | 0 | names = [ # NOQA
'Aan',
'Aalia',
'Aaliah',
'Aaliyah',
'Aaron',
'Aaryanna',
'Aavree',
'Abbie',
'Abbott',
'Abbra',
'Abby',
'Abe',
'Abel',
'Abelardo',
'Abeni',
'Abia',
'Abiba',
'Abie',
'Abigail',
'Abner',
'Abraham',
'Abram',
'Abrial',
'Abrianna',
'Abrienda',
'Abril',
'Abryl',
'Absolom',
'Abu',
'Acacia',
'Acadia',
'Ace',
... | 'Bill',
'Billy',
'Bin',
'Bina',
'Bing',
'Bingham',
'Birch',
'Bisbee',
'Bishop',
'Biton',
'Bjorn',
'Blade',
'Blaine',
'Blair',
'Blaise',
'Blake',
'Blanche',
'Blaze',
'Blenda',
'Blinda',
'Bliss',
'Blithe',
'Blodwyn',
'Blossom',
'Blum',
'Bluma',
'Bly',
'Blythe',
'Bo',
'Boaz',
'Bob',
'Bodee',
'Bona',
'Bonaventure',
'Bond',... | Braden',
'Bradford',
'Bradley',
'Brady',
'Braeden',
'Braima',
'Bran',
'Brand',
'Brandee',
'Branden',
'Brandi',
'Brandie',
'Brandon',
'Brandy',
'Branellan',
'Brant',
'Braxton',
'Brayden',
'Brazil',
'Breanna',
'Breckin',
'Brede',
'Bree',
'Brein',
'Brend',
'Brenda',
'Brendan',
'Brenden',
'Brendon',
'Brenna',
'Brennan',
'B... |
openstreams/wflow | examples/wflow_rhine_hbv/staticmaps/shptoraster.py | Python | gpl-3.0 | 1,082 | 0.01756 |
import os
import os.path
import getopt
import ConfigParser
import sys
"""
rem rasterize needs to be done on tif file as .map files cannot be
rem handled direc | tby by gdal
"""
shpfile = "subbasins_rhein_wgs1984.shp"
nname = os.path.splitext(os.path.basename(shpfile))[0]
# In this dictionary the fiedl in the dbf is linked to the filename in the .map
pars = {"BETA": "BetaSeepage",
| "CFMAX": "Cfmax",
"ALPHA": "AlphaNL",
"TTI" : "TTI",
"TT" : "TT",
"PERC" : "PERC",
"K4" :"K4",
"FC" : "FC",
"KHQ" : "KHQ",
"LP": "LP",
"HQ" : "HQ",
"CFR" : "CFR",
"CEVPF" : "CEVPF"
}
os.system('pcrcalc "nilmap.map=s... |
KiChjang/servo | tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/tests/test_update.py | Python | mpl-2.0 | 64,506 | 0.000822 | import json
import mock
import os
import pytest
import sys
from io import BytesIO
from .. import metadata, manifestupdate
from ..update.update import WPTUpdate
from ..update.base import StepRunner, Step
from mozlog import structuredlog, handlers, formatters
here = os.path.dirname(__file__)
sys.path.insert(0, os.path.... | st.htm",
"status": "OK"})])
updated = update(tests, log)
assert len(updated) == 1
assert updated[0][1].is_empty
def test_update_1 | ():
tests = [("path/to/test.htm", [test_id], "testharness",
b"""[test.htm]
[test1]
expected: ERROR""")]
log = suite_log([("test_start", {"test": test_id}),
("test_status", {"test": test_id,
"subtest": "test1",
... |
bdh1011/wau | venv/lib/python2.7/site-packages/pandas/tools/plotting.py | Python | mit | 117,602 | 0.00091 | # being a bit too dynamic
# pylint: disable=E1101
import datetime
import warnings
import re
from math import ceil
from collections import namedtuple
from contextlib import contextmanager
from distutils.version import LooseVersion
import numpy as np
from pandas.util.decorators import cache_readonly, deprecate_kwarg
im... | lines.linewidth': 1.0,
'patch.antialiased': True,
'patch.edgecolor': '#EEEEEE',
'patch.facecolor': '#348ABD',
'patch.linewidth': 0.5,
'toolbar': 'toolbar2',
'xtick.color': '#555555',
'xtick.direction': 'in',
'xtick.major.pad': 6.0,
'xtick.major.size': 0.0,
'xtick.minor.... | ze': 0.0,
'ytick.color': '#555555',
'ytick.direction': 'in',
'ytick.major.pad': 6.0,
'ytick.major.size': 0.0,
'ytick.minor.pad': 6.0,
'ytick.minor.size': 0.0
}
def _get_standard_kind(kind):
return {'density': 'kde'}.get(kind, kind)
def _get_standard_colors(num_colors=None, colormap=N... |
adamcharnock/django-hordak | hordak/migrations/0006_auto_20161209_0108.py | Python | mit | 1,488 | 0.001344 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.1 o | n 2016-12-09 01:0 | 8
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("hordak", "0005_account_currencies")]
operations = [
migrations.RunSQL(
"""
CREATE OR REPLACE FUNCTION check_leg()
RETUR... |
tvtsoft/odoo8 | addons/delivery/models/stock_picking.py | Python | agpl-3.0 | 4,025 | 0.001491 | # -*- coding: utf-8 -*-
##############################################################################
#
# Odoo, Open Source Business Applications
# Copyright (c) 2015 Odoo S.A. <http://openerp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affe... | cancel_shipment(self)
msg = "Shipment %s cancelled" | % self.carrier_tracking_ref
self.message_post(body=msg)
self.carrier_tracking_ref = False
|
oscarbranson/latools | latools/filtering/classifier_obj.py | Python | mit | 8,422 | 0.000356 | import numpy as np
from sklearn import preprocessing
import sklearn.cluster as cl
from latools.helpers.stat_fns import nominal_values
class classifier(object):
def __init__(self, analytes, sort_by=0):
"""
Object to fit then apply a classifier.
Parameters
----------
analyte... | data : array-like
A dataset formatted by `classifier.fitting_data`.
n_clusters : int
The number of clusters in the data.
**kwargs
passed to `sklearn.cluster.KMeans`.
Returns
-------
Fitted `sklearn.cluster.KMeans` object.
"""
... | bin_seeding=False, **kwargs):
"""
Fit MeanShift clustering algorithm to data.
Parameters
----------
data : array-like
A dataset formatted by `classifier.fitting_data`.
bandwidth : float
The bandwidth value used during clustering.
If no... |
luciamc/projecttwo | funcion1.py | Python | apache-2.0 | 190 | 0.005263 | # -* | - coding: utf-8 -*-
"""
Created on Wed Dec 21 20:05:40 2016
@author: lucia
"""
def funcion1():
print('Primera funcion de mi projecttwo')
print( | 'Modifico la primera funcion 2')
|
msmbuilder/msmbuilder-legacy | MSMBuilder/project/__init__.py | Python | gpl-2.0 | 150 | 0 | from __future__ import print_f | unction, absolute_import, division
from .project import Project
from .builder import Proj | ectBuilder, FahProjectBuilder
|
tux-00/ansible | lib/ansible/module_utils/connection.py | Python | gpl-3.0 | 5,170 | 0.003868 | #
# This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own license
# to the complete ... | mport os
import uuid
from functools import partial
from ansible.module_utils.basic import get_exception
from ansible.module_utils._text import to_bytes, to_native, to_text
def send_data(s, data):
| packed_len = struct.pack('!Q', len(data))
return s.sendall(packed_len + data)
def recv_data(s):
header_len = 8 # size of a packed unsigned long long
data = to_bytes("")
while len(data) < header_len:
d = s.recv(header_len - len(data))
if not d:
return None
data += d... |
AllanYangZhou/oppia | core/domain/email_manager_test.py | Python | apache-2.0 | 78,772 | 0.000165 | # Copyright 2014 The Oppia 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 applicable ... | ': self.exploration.version,
'new_member_username': self.NEW_USER_USERNAME,
'new_member_role': rights_manager.ROLE_EDITOR,
}, csrf_token=csrf_token)
messages = self.mail_stub.get_sent_messages(to=se | lf.NEW_USER_EMAIL)
self.assertEqual(len(messages), 1)
def test_email_is_not_sent_if_recipient_has_declined_such_emails(self):
user_services.update_email_preferences(
self.new_user_id, True, False, False, False)
with self.can_send_emails_ctx, self.can_send_editor_role_email_... |
emsrc/daeso-framework | test/string/test_smith_waterman.py | Python | gpl-3.0 | 2,031 | 0.012309 | from daeso.string.smith_waterman import smith_waterman
from daeso.string.needleman_wunsch import print_scores, print_alignment
import unittest
class TestSmithWatermanExample(unittest.TestCase):
"""
reproduces the example in Figure1 from the Waterman & Eggert paper
"""
def sim_score(self, e1, e2):... | let's start with a really nice sentence".split()
scores, alignment = smith_waterman(seq1, seq2, self.sim_score, self.gap_cost)
print_scores(seq1, seq2, scores)
print_alignment(seq1, seq2, alignment)
self.assertEqual(alignment, [(6,1),(7,2)])
|
if __name__ == '__main__':
unittest.main() |
koneman/NGOpycrawl | NGOcrawler/spiders/spider_base.py | Python | mit | 5,932 | 0.013823 | import os
import sys
#import feedparser
#from bs4 import BeautifulStoneSoup
from bs4 import BeautifulSoup
#from nltk import clean_html
import urllib
import re
import json
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from scrapy.item import Item, Field
from ... | tact = response.css("div.contact")
print contact
parsedHTML = []
i = 0
for x in NGOSpider.start_urls:
parsedHTML.append(self.getHTMLtext(x))
i += 1
phoneNumber = []
email =[]
streetAddress = []
for x in parsedHTML:
ph... | getAddress(x))
projectProp = 'PROJECTPROPOSAL'
print(self.formatJSON(title,phoneNumber,email,streetAddress,projectProp))
print('_______________________________________________________________')
print('_______________________________________________________________')
#getting al... |
pllim/ginga | ginga/util/stages/base.py | Python | bsd-3-clause | 1,889 | 0.000529 | #
# stage.py -- Classes for pipeline stages
#
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
#
from ginga.misc import Bunch
#__all__ = ['Pipeline']
class StageError(Exception):
pass
class Stage(object):
"""Class to handle a pipeline stage."""
... | def export_as_dict(self):
| d = dict(name=self.name, type=self._stagename, bypass=self._bypass)
return d
def import_from_dict(self, d):
self.name = d['name']
self._bypass = d['bypass']
def __str__(self):
return self._stagename
|
hpparvi/PyTransit | pytransit/param/__init__.py | Python | gpl-2.0 | 996 | 0 | # PyTransit: fast and easy exoplanet transit modelling in Python.
# Copyright (C) 2010-2019 Hannu Parviainen
#
# 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 Licen... | R PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from .parameter import (ParameterSet, PParameter, LParameter, GParameter,
PParamet... | ive_qois
|
UPOLSearch/UPOL-Search-Engine | upol_search_engine/upol_crawler/core/validator.py | Python | mit | 1,618 | 0 | import urllib.parse
from upol_search_engine.upol_crawler.tools import blacklist, robots
def validate_regex(url, regex):
"""Check if url is validate with regex"""
return regex.match(url)
def validate_anchor(url):
"""Check if url include anchor"""
cheme, netloc, path, qs, anchor = urllib.parse.urlspl... | is valid or blacklisted"""
scheme, netloc, path, qs, anchor = urllib.parse.urlsplit(url)
path = path + qs + anchor
url_keywords = ['posting.php',
'ucp.php',
'view=print',
'memberlist.php',
'mark']
for url_keyword in url_ke... | rue
def validate_wiki(url):
"""Validate if url from wiki system is valid or blacklisted"""
scheme, netloc, path, qs, anchor = urllib.parse.urlsplit(url)
path = path + qs + anchor
url_keywords = ['&']
for url_keyword in url_keywords:
if url_keyword in path:
return False
r... |
Distrotech/reportlab | tests/test_platypus_lists.py | Python | bsd-3-clause | 7,526 | 0.014882 | from random import randint
from reportlab.lib.testutils import setOutDir,makeSuiteForClasses, outputfile, printLocation
setOutDir(__name__)
import os,unittest
from reportlab.platypus import Spacer, SimpleDocTemplate, Table, TableStyle, ListFlowable, ListItem, Paragraph, PageBreak
from reportlab.lib.styles import getSam... | e see that this
selectionally introduced contextual feature is rather different from a
parasitic gap construction.''',
'''
Blah blah blah blah blah blah discipline?... naked? ... With a melon!? blah blah blah blah blah Very silly indeed Mr. Nesbitt has learned the first lesson of 'Not Being Seen', not to stand up. blah... | h blah blah blah. Blah blah blah conceptualize blah contribution blah blah blah blah blah blah blah blah blah blah blah blah proactive. Blah blah blah blah blah blah proactive blah mastery learning blah blah blah blah blah projection Total Quality Management blah.
''',
'''
Blah Archer IV blah blah blah blah blah blah ... |
wmvanvliet/mne-python | mne/io/fiff/raw.py | Python | bsd-3-clause | 20,018 | 0 | # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Matti Hämäläinen <msh@nmr.mgh.harvard.edu>
# Martin Luessi <mluessi@nmr.mgh.harvard.edu>
# Denis Engemann <denis.engemann@gmail.com>
# Teon Brooks <teon.brooks@gmail.com>
#
# License: BSD-3-Clause
import copy
import os
im... | gnals that may also affect brain
activity. Can also be "yes" to load without eliciting a warning.
%(preload)s
%(on_split_missing)s
%(verbose)s
Attributes
----------
%(info_not_none)s
ch_names : list of string
List of channels' names.
n_times : int
Total number of... | rval between consecutive time samples is equal to the
inverse of the sampling frequency.
preload : bool
Indicates whether raw data are in memory.
%(verbose)s
"""
@verbose
def __init__(self, fname, allow_maxshield=False, preload=False,
on_split_missing='raise', verbo... |
suzlab/Autoware | ros/src/sensing/drivers/imu/packages/xsens/src/xsens_driver/src/mtdef.py | Python | bsd-3-clause | 6,714 | 0.051832 | """Constant and messages definition for MT communication."""
class MID:
"""Values for the message id (MID)"""
## Error message, 1 data byte
Error = 0x42
ErrorCodes = {
0x03: "Invalid period",
0x04: "Invalid message",
0x1E: "Timer overflow",
0x20: "Invalid baudrate",
0x21: "Invalid parameter"
}
# Stat... | s is a subset of the 100-series
class MTEx | ception(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return "MT error: " + self.message
|
billiob/papyon | papyon/service/description/AB/common.py | Python | gpl-2.0 | 1,752 | 0.003995 | # -*- coding: utf-8 -*-
#
# papyon - a python client library for Msn
#
# Copyright (C) 2005-2006 Ali Sabil <ali.sabil@gmail.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 ... | ww.msn.com/webse | rvices/AddressBook">false</IsMigration>
<PartnerScenario xmlns="http://www.msn.com/webservices/AddressBook">%s</PartnerScenario>
</ABApplicationHeader>
<ABAuthHeader xmlns="http://www.msn.com/webservices/AddressBook">
<ManagedGroupRequest xmlns="http://www.msn.com/webservices/Address... |
xyuanmu/XX-Net | python3.8.2/Lib/site-packages/pip/_internal/legacy_resolve.py | Python | bsd-2-clause | 17,303 | 0 | """Dependency Resolution
The dependency resolution in pip is performed as follows:
for top-level requirements:
a. only one spec allowed per project, regardless of conflicts or not.
otherwise a "double requirement" exception is raised
b. they override sub-dependency requirements.
for sub-dependencies
... | self.use_pep517 = use_pep517
self._discovered_dependencies = \
defaultdict(list) # type: DefaultDict[str, List]
def resol | ve(self, requirement_set):
# type: (RequirementSet) -> None
"""Resolve what operations need to be done
As a side-effect of this method, the packages (and their dependencies)
are downloaded, unpacked and prepared for installation. This
preparation is done by ``pip.operations.prep... |
sivakuna-aap/superdesk-core | superdesk/celery_task_utils.py | Python | agpl-3.0 | 3,230 | 0.000929 | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import os
im... | n(set_if_not_running, key)
return not is_set
def mark_task_as_not_running(name, id):
def remove_key(pipe):
| is_removed = pipe.delete(key)
return True if is_removed > 0 else False
key = __get_running_key(name, id)
removed = __redis_transaction(remove_key, key)
if not removed:
logger.error('Failed to set {}:{} as not running'.
format(name, id))
return removed
def __re... |
hodgesds/elasticsearch_tornado | tests/test_cluster.py | Python | apache-2.0 | 2,219 | 0.001803 | import tornado.ioloop
from functools import partial
from tornado.testing import AsyncTestCase
from elasticsearch_tornado import ClusterClient
try:
# python 2.6
from unittest2 import TestCase, SkipTest
except ImportError:
from unittest import TestCase, SkipTest
class ClusterClientTest(AsyncTestCase):... | get_settings(self):
c = ClusterClient()
c.cluster_get_settings(callback=self.handle_cb)
self.wait()
def test_put_settings(self):
c = ClusterClient()
body | = """
{
"persistent" : {
"discovery.zen.minimum_master_nodes" : 1
}
}
"""
c.cluster_put_settings(body, callback=self.handle_cb)
self.wait()
|
simbits/Lumiere | cabinet_test.py | Python | mit | 4,132 | 0.005808 | #!/usr/bin/env python
import random
import socket
import struct
import sys
import time
CABINET_VERSION='1.0b'
START_MSG='## Cabinet version %s ##' % (CABINET_VERSION)
MCAST_GRP = ('224.19.79.1', 9999)
DRAWERS = 9
USE_PULLUPS = 1
WAIT_DELAY = 0.5 #seconds
count = 0
if __name__ == '__main__':
c_state = [T... | nt ''
# print '-------'
# print ' i: drawer 1, 3 open'
# print ' e: open drawer 5'
# print ' p: [1,3,5]'
# print ' r: stop movie 3, | play movie 5'
# c_state = [ False, True, False, True, False, True, True, True, True ]
#if count == 150:
# print ''
# print '-------'
# print ' i: drawer 1, 3, 5 open'
# print ' e: close drawer 5'
# print ' p: [1, 3]'
... |
spacy-io/spaCy | spacy/lang/lb/tokenizer_exceptions.py | Python | mit | 1,168 | 0.000861 | from ..tokenizer_exceptions im | port BASE_EXCEPTIONS
from ...symbols import ORTH, NORM
from ...util import update_exc
# TODO
# treat other apostrophes within words as part of the word: [op d'mannst], [fir d'éischt] (= exceptions)
_exc = {}
# translate / delete what is not n | ecessary
for exc_data in [
{ORTH: "’t", NORM: "et"},
{ORTH: "’T", NORM: "et"},
{ORTH: "'t", NORM: "et"},
{ORTH: "'T", NORM: "et"},
{ORTH: "wgl.", NORM: "wannechgelift"},
{ORTH: "M.", NORM: "Monsieur"},
{ORTH: "Mme.", NORM: "Madame"},
{ORTH: "Dr.", NORM: "Dokter"},
{ORTH: "Tel.", NORM... |
matthewdeanmartin/kata-python | kata/descendents/test.py | Python | gpl-3.0 | 127 | 0.007874 | import unittest
import kata.descendents.main a | s cb
class Tests(unittest.TestCase | ):
def test_main(self):
cb.run()
|
Julian/home-assistant | homeassistant/components/sensor/vera.py | Python | mit | 2,662 | 0 | """
Support for Vera sensors.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.vera/
"""
import logging
from homeassistant.const import (
TEMP_CELSIUS, TEMP_FAHRENHEIT)
from homeassistant.helpers.entity import Entity
from homeassistant.componen... | e the sensor."""
self.current_value = None
self._temperature_units = None
VeraDevice.__init__(self, | vera_device, controller)
@property
def state(self):
"""Return the name of the sensor."""
return self.current_value
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
if self.vera_device.category == "Temperature Sensor"... |
SXKDZ/magic-mirror | backend/util/baidu.py | Python | gpl-3.0 | 1,267 | 0.000791 | import requests
import wave
CUID = '7519663'
APIKEY = 'Ll0c53MSac6GBOtpg22ZSGAU'
SECRET = '44c8af396038a24e34936227d4a19dc2'
def get_token():
api_key = APIKEY
secret_key = SECRET
auth_url = 'https://openapi.baidu.com/oauth/2.0/token'
payload = {
'grant_type': 'client_credentials',
'cl... | ent-Type': 'audio/pcm; rate=16000',
'Content-Length': str(f_len)
}
result = requests.post(url, params=payload, data=audio_data, headers=headers)
response = result.json()
if response['err_msg'] == 'success.':
text = ''.join(response['result'])
if text[-1] == ',':
text... | _msg']
}
|
eklitzke/mapserv | mapserv/lyric/table.py | Python | isc | 5,008 | 0.003794 | import threading
import weakref
from mapserv.interfaces.query import ttypes
import mapserv.query.util
class AndExpr(object):
"""Logically group a series of expressions by AND."""
def __init__(self, *terms):
self.terms = terms
class PseudoColumn(object):
def __init__(self, table, name, spatial):
... | e=self.table, name=self.name, spatial=self.spatial)
return ttypes.Target(col=col)
def make_orderby(self, ordering=None):
col = ttypes.Column(table=self.table, name=self.name, spatial=self.spatial)
return ttypes.OrderClause | (col=col, order=ordering)
def asc(self):
return self.make_orderby(ttypes.Order.ASC)
def desc(self):
return self.make_orderby(ttypes.Order.DESC)
def compare_to(self, other, eq):
lhs = self.make_target()
rhs = mapserv.query.util.make_target(other)
eqcomp = ttypes.EqC... |
mauriceyap/ccm-assistant | src/intents/intents.py | Python | mit | 7,176 | 0.003484 | import utils
import resources.bible as bible
import resources.passages as passages
import resources.sermons as sermons
import resources.events as events
import config
import cards
import speech
from .intents_utils import ensure_date_and_service_slots_filled, ensure_date_is_a_sunday, \
ensure_service_valid, ensure_d... | onse(
output=speech.get_next_event(event_name=next_event['name'],
event_datetime=next_event['datetime']),
reprompt_text=reprompt_text,
should_end_session=should_end_session,
card_text=cards.get_next_event_content(
event_description=next_ev... | ion'],
event_location_name=next_event['location_name']),
card_title=cards.get_next_event_title(
event_title=next_event['name'],
event_datetime=next_event['datetime']),
card_small_image_url=next_event['small_image_url'],
card_large_image_url=next_event['large_i... |
sn6uv/gmpy_cffi | tests/test_mpz.py | Python | bsd-3-clause | 13,559 | 0.000516 | from __future__ import division
import sys
import pytest
from gmpy_cffi import mpz, MAX_UI
PY3 = sys.version.startswith('3')
if PY3:
long = int
invalids = [(), [], set(), dict(), lambda x: x**2]
class TestInit(object):
small_ints = [-1, 0, 1, 123, -9876, sys.maxsize, -sys.maxsize - 1]
big_ints = [s... | ), b) == tuple(map(mpz, divmod(2, b)))
else:
with pytest.raises(ZeroDivisionError):
divmod(mpz(2), mpz(b))
with pytest.raises(ZeroDivisionError):
divmod(mpz(2), b)
@pytest.mark.parametrize('b', numbers)
def test_rdivmod(self, b):
assert di... | ) == tuple(map(mpz, divmod(b, 2)))
def test_rdivmod_by_zero(self):
with pytest.raises(ZeroDivisionError):
divmod(1, mpz(0))
@pytest.mark.parametrize('b', [0, 2, 1 << 16])
def test_shifts(self, b):
assert mpz(1) << mpz(b) == mpz(1 << b)
assert mpz(1) << b == mpz(1 << b)
... |
sixty-north/structurizr-python | test/core/test_workspace.py | Python | apache-2.0 | 413 | 0.004843 | import pytest
class TestWorkspace:
@pytest.mark.xfai | l(reason="Not yet implemented")
def test_set_source_does_not_throw_an_ex | ception_when_a_none_url_is_specified(self, workspace):
workspace.set_source(None)
@pytest.mark.xfail(reason="Not yet implemented")
def test_set_source_does_not_throw_an_exception_when_an_empty_url_is_specified(self, workspace):
workspace.set_source("")
|
maurov/xraysloth | sloth/io/rixs_esrf_bm23.py | Python | bsd-3-clause | 4,605 | 0.000651 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
RIXS data reader for beamline BM23 @ ESRF
=========================================
.. note: RIXS stands for Resonant Inelastic X-ray Scattering
"""
import os
import time
import numpy as np
from silx.io.dictdump import dicttoh5
from sloth.utils.bragg import ang2kev... | riter_name': str,
'writer_version': str,
'writer_timestamp': str,
'filename_all' : list,
'filename_root': str,
'n | ame_sample': str,
'name_scan': str,
'counter_all': str,
'counter_signal': str,
'counter_norm': str,
'ene_grid': float,
'ene_unit': str,
}
"""
_writer = "get_rixs_bm23"
_writer_version = "1.5" #: used for reading back in RixsData.load_from_h5()
_wr... |
mcruger/GooglePythonCourse | basic/list2.py | Python | apache-2.0 | 2,316 | 0.016408 | #!/usr/bin/python -tt
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
# Additional basic list exercises
# D. Given a list of numbers, return a list where
# al... | 2, 3]), [1, 2, 3])
test(remove_adjacent([2, 2, 3, 3, 3]), [2, 3])
test(remove_adjacent([]), [])
print
print 'linear_merge'
test(linear_merge(['aa', 'xx', | 'zz'], ['bb', 'cc']),
['aa', 'bb', 'cc', 'xx', 'zz'])
test(linear_merge(['aa', 'xx'], ['bb', 'cc', 'zz']),
['aa', 'bb', 'cc', 'xx', 'zz'])
test(linear_merge(['aa', 'aa'], ['aa', 'bb', 'bb']),
['aa', 'aa', 'aa', 'bb', 'bb'])
if __name__ == '__main__':
main()
|
popazerty/openhdf-enigma2 | keymapparser.py | Python | gpl-2.0 | 3,203 | 0.030596 | import enigma
import xml.etree.cElementTree
from keyids import KEYIDS
# these are only informational (for help)...
from Tools.KeyBindings import addKeyBinding
class KeymapError(Exception):
def __init__(self, message):
self.msg = message
def __str__(self):
return self.msg
def getKeyId(id):
if len(id) == 1:
... | p file " + filename | + " not found"
return
try:
dom = xml.etree.cElementTree.parse(source)
except:
raise KeymapError("[keymapparser] keymap %s not well-formed." % filename)
source.close()
keymap = dom.getroot()
for cmap in keymap.findall("map"):
context = cmap.attrib.get("context")
assert context, "[keymapparser] map must... |
ncdesouza/bookworm | env/lib/python2.7/site-packages/sqlalchemy/testing/runner.py | Python | gpl-3.0 | 1,626 | 0 | #!/usr/bin/env python
# testing/runner.py
# Copyright (C) 2005-2014 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""
Nose test runner module.
This script is a front-end to "... | work. The runner can
be invoked via::
python -m sqlalchemy.testing.runner
The script is then esse | ntially the same as the "nosetests" script, including
all of the usual Nose options. The test environment requires that a
setup.cfg is locally present including various required options.
Note that when using this runner, Nose's "coverage" plugin will not be
able to provide coverage for SQLAlchemy itself, since SQLAl... |
fairdk/lcrs2 | lcrs/master/dhcp/utils.py | Python | gpl-3.0 | 1,554 | 0.010296 | #
# LCRS Copyright (C) 2009-2011
# - Rene Jensen
# - Michael Wojciechowski
# - Benjamin Bach
#
# LCRS 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 ... | etails.
#
# You should have received a copy of the GNU General Public License
# along with LCRS. If not, see <http://www.gnu.org/licenses/>.
def octetsAsInts (s='10.20.20.1'):
'''
Converts a 4-octet represented as a string to an int-array representation
'''
if type(s) == str:
return [int(c... | n('octetsAsInts cannot deal with this thing: ' + repr(s))
def octetsAsString (c=[10,20,20,1]):
'''
Converts a 4-octet represented as an int-array representation to a string
'''
if type(c) == str:
return c
elif type(c) == list:
return ".".join (str(i) for i in c)
else:
... |
jamuelle/fotis | albums/views.py | Python | gpl-2.0 | 591 | 0.005076 | from django.http import HttpResponse
from django.http import Http404
from django.shortcuts import render_to_response
from fotis.albums.models import Album
def index(request):
year_list = Album.objects.all().order_by('-year')
r | eturn render_to_response('albums/index.html', {'year_list': year_list})
def year(request, year):
try:
y = Album.objects.get(year=year)
exce | pt Album.DoesNotExist:
raise Http404
return render_to_response('albums/year.html', {'year': y})
def event(request, year, event):
return HttpResponse("This is " + year + " " + event)
|
pascalc/narrative-roulette | src/db/__init__.py | Python | apache-2.0 | 1,164 | 0.002577 | import logging
import os
import sqlalchemy as sql
from config import db_credentials
# Localhost
HOST = db_credentials['host']
USERNAME = db_credentials['username']
PASSWORD = db_credentials['password']
DB_NAME = db_credentials['db_name']
connection_string = \
"mysql://{user}:{password}@{host}/{db}?charset=utf8".... | E
)
"""
Google App Engine
"""
# INSTANCE_NAME = db_credentials['instance_name']
# DB_NAME = db_credentials['db_name']
# USERNAME = db_credentials['username']
# PASSWORD = db_credentials['password']
# connection_string = None
# if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine'):
# connection_stri... | # username=USERNAME,
# password=PASSWORD,
# host=db_credentials['ip_address'],
# database=DB_NAME,
# )
# logging.info("SQLAlchemy connection string: %s" % connection_string)
engine = sql.create_engine(connection_string, pool_recycle=3600)
import db.reconnect
|
gasongjian/ttpy | tt/optimize/tt_min.py | Python | mit | 9,368 | 0.006939 | """This module contains a prototype implementation of the
TT-cross-based minimization procedure
"""
import numpy as np
import math
import tt
from ..maxvol import maxvol
from ..utils.rect_maxvol import rect_maxvol
def reshape(a, sz):
return np.reshape(a, sz, order = 'F')
def mkron(a, b):
return np.kron(a, b)
... | )
Jy[i + 1] = np.hstack((w1, w2))
Jy[i + 1] = reshape(Jy[i + 1], (ry[i] * n[i], -1))
Jy[i + 1] = Jy[i + 1][ind, :]
#Jy{i+1} = [kron(ones(n(i),1), Jy{i}), kron((1:n(i))', ones(ry(i),1))];
#Jy{i+1} = Jy | {i+1}(ind,:);
swp = 0
dirn = -1
i = d - 1
lm = 999999999999
while swp < nswp:
#Right-to-left sweep
#The idea: compute the current core; compute the function of it;
#Shift locally or globally? Local shift would be the first try
#Compute the current core
if np.... |
cchanrhiza/python-pptx | pptx/oxml/shapes/autoshape.py | Python | mit | 10,416 | 0.000096 | # encoding: utf-8
"""
lxml custom element classes for shape-related XML elements.
"""
from __future__ import absolute_impor | t
from .. import parse_xml
from ...enum.shapes import MSO_AUTO_SHAPE_TYPE, PP_PLACEHOLDER
from ..ns import nsdecls
from .shared import BaseShapeElement
from ..simpletypes import XsdBoolean, XsdString
from ..text import CT_TextBody
from ..xmlchemy import (
BaseOxmlElement, OneAndOnlyOne, OptionalAttribute, Required... | ``<a:gd>`` custom element class, defining a "guide", corresponding to
a yellow diamond-shaped handle on an autoshape.
"""
name = RequiredAttribute('name', XsdString)
fmla = RequiredAttribute('fmla', XsdString)
class CT_GeomGuideList(BaseOxmlElement):
"""
``<a:avLst>`` custom element class
... |
rolandgeider/OpenSlides | openslides/core/exceptions.py | Python | mit | 251 | 0 | from openslides.utils.exceptions import OpenSlidesError
class ProjectorException(OpenSlidesErro | r):
pass
class TagException(OpenSlidesError):
pass
class ConfigError(OpenSlidesError):
pass
class ConfigNotFound(ConfigError):
p | ass
|
KaranToor/MA450 | google-cloud-sdk/lib/surface/debug/logpoints/create.py | Python | apache-2.0 | 4,928 | 0.002029 | # Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | ndition=args.condition,
user_email=user_email)
# Wait a short time to see if the logpoint generates an error. Ideally,
# we'd want to wait until we get a response that the logpoint was set
# by at least one instance, but the API does not currently support that.
final_logpoint = debuggee.WaitForB... | args.location)
if args.location != final_logpoint.location:
log.status.write(
'The debugger adjusted the logpoint location to {0}'.format(
final_logpoint.location))
return final_logpoint or logpoint
def Collection(self):
retur... |
rcosnita/fantastico | fantastico/contrib/oauth2_idp/models/user_repository.py | Python | mit | 2,209 | 0.00679 | '''
Copyright 2013 Cosnita Radu Viorel
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute... | THER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
.. codeauthor:: Radu Viorel Cosnita <radu.cosnita@gmail.com>
.. py:module:: fantastico.contrib.oauth2 | _idp.models.user_repository
'''
from fantastico.contrib.oauth2_idp.models.users import User
from fantastico.mvc.model_facade import ModelFacade
from fantastico.mvc.models.model_filter import ModelFilter
from fantastico.exceptions import FantasticoDbNotFoundError
class UserRepository(object):
'''This class provides... |
ToonTownInfiniteRepo/ToontownInfinite | toontown/parties/DistributedPartyJukeboxActivityBaseAI.py | Python | mit | 4,954 | 0.010093 | from direct.directnotify import DirectNotifyGlobal
from toontown.parties.DistributedPartyActivityAI import DistributedPartyActivityAI
from direct.task import Task
import PartyGlobals
class DistributedPartyJukeboxActivityBaseAI(DistributedPartyActivityAI):
notify = DirectNotifyGlobal.directNotify.newCategory("Distr... | = 0
self.playing = False
def delete(self):
taskMgr.remove('playSong%d' % self.doId)
DistributedPartyActivityAI.delete(self)
def setNextSong(self, song):
avId = self.air.getAvatarIdFromSender()
phase = self.music.get(song[0])
if avId != self... | :
self.air.writeServerEvent('suspicious',avId,'Toon tried to set song without using the jukebox!')
if not phase:
self.air.writeServerEvent('suspicious',avId,'Toon supplied invalid phase for song!')
return
if not phase.has_key(song[1]):
self.air.writeServer... |
zookeepr/zookeepr | zkpylons/tests/functional/test_location.py | Python | gpl-2.0 | 568 | 0.003521 | from .crud_helper import CrudHelper
from .fixtures import LocationFactory
class TestLocation(CrudHelper):
def test_permissions(self, app, db_session):
# Special ical page has public permissions
CrudHelper.test_permissions(self, app, db_session)
CrudHelper.te | st_perm | issions(self, app, db_session, good_roles=['public'], bad_roles=[], get_pages=("ical",), post_pages=[])
def test_view(self, app, db_session):
resp = CrudHelper.test_view(self, app, db_session)
# TODO: parse resp to verify the schedule for the location
|
Jerad-M/ubfs | classes/custom/place/system.py | Python | apache-2.0 | 1,201 | 0.026644 | import datetime
from ...place import Place
from ...spec import Spec
from .planet import Planet
from .dwarfplanet import DwarfPlanet
class System(Place):
"""Systems exist within galaxies, and can contain planets...
Attributes
allowedChildEntities Enti | ty spec types that can be created from this context
spec Spec type of this Entity"""
# Things that child class SHOULDNT need to redeclare
# Things that a few child classes will need to redeclare
allowedChildEntities = [Spec.PLANET, Spec.DWARFPLANET]
# Things every child class will want to re... | the spec type.
Will likely redefine in Places.
Arguments
spec Spec type for new entity
key Key for new entity
path Path for new entity
Return
Entity"""
if (spec == spec.PLANET):
planet = Planet(key, path)
return planet
if (spec == spec.DWARFPLANET):
dwarfPlanet = DwarfPlanet(key,... |
oesteban/dipy | dipy/sims/tests/test_voxel.py | Python | bsd-3-clause | 12,904 | 0.000077 | import numpy as np
from nose.tools import (assert_true, assert_false, assert_equal,
assert_almost_equal)
from numpy.testing import (assert_array_equal, assert_array_almost_equal,
assert_)
from dipy.sims.voxel import (_check_directions, SingleTensor, MultiTensor,
... | r():
np.random.seed(1978)
s = single_tensor(gtab)
# For reasonably large SNR, var(signal) ~= sigma**2, where sigma = 1/SNR
for snr in [5, 10, 20]:
sigma = 1.0 / snr
for j in range(1000):
s_noise = add_noise(s, snr, 1, noise_type='rician')
asse | rt_array_almost_equal(np.var(s_noise - s), sigma ** 2, decimal=2)
def test_all_tensor_evecs():
e0 = np.array([1/np.sqrt(2), 1/np.sqrt(2), 0])
desired = np.array([[1/np.sqrt(2), 1/np.sqrt(2), 0],
[-1/np.sqrt(2), 1/np.sqrt(2), 0],
[0, 0, 1]]).T
assert_array_... |
rohitwaghchaure/frappe | frappe/build.py | Python | mit | 5,802 | 0.029128 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
from frappe.utils.minify import JavascriptMinify
"""
Build the `public` folders and setup languages
"""
import os, frappe, json, shutil, re
# from cssmin import cssmin
app_pat... | f + ' dirty'
return True
else:
return False
def compile_less():
from distutils.spawn import find_executable
if not find_executable("lessc"):
return
for path in app_paths:
less_path = os.path.join(path, "public", "less")
if os.path.exists(less_path):
for fname in os.listdir(less_path):
if fname.... | )
if fpath in timestamps and mtime == timestamps[fpath]:
continue
timestamps[fpath] = mtime
print "compiling {0}".format(fpath)
css_path = os.path.join(path, "public", "css", fname.rsplit(".", 1)[0] + ".css")
os.system("lessc {0} > {1}".format(fpath, css_path))
|
mdworks2016/work_development | Python/05_FirstPython/Chapter9_WebApp/fppython_develop/lib/python3.7/site-packages/bs4/tests/test_soup.py | Python | apache-2.0 | 28,802 | 0.002296 | # -*- coding: utf-8 -*-
"""Tests of Beautiful Soup as a whole."""
from pdb import set_trace
import logging
import unittest
import sys
import tempfile
from bs4 import (
BeautifulSoup,
BeautifulStoneSoup,
)
from bs4.builder import (
TreeBuilder,
ParserRejectedMarkup,
)
from bs4.element import (
Char... | e ignored.")
self.assertEqual(builder, soup.builder)
self.assertEqual(kwargs, builder.called_with)
def test_parser_markup_rejection(self):
# If | markup is completely rejected by the parser, an
# explanatory ParserRejectedMarkup exception is raised.
class Mock(TreeBuilder):
def feed(self, *args, **kwargs):
raise ParserRejectedMarkup("Nope.")
def prepare_markup(self, *args, **kwargs):
# We're going... |
klahnakoski/JsonSchemaToMarkdown | vendor/jx_sqlite/expressions.py | Python | mpl-2.0 | 30,120 | 0.002523 | # encoding: utf-8
#
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http:# mozilla.org/MPL/2.0/.
#
# Author: Kyle Lahnakoski (kyle@lahnakoski.com)
#
from __future__ import absolute_import
from __f... | empa = acc.setdefault(nested_path, {})
tempb = tempa.setdefault(get_property_name(cname), {})
tempb[json_type_to_sql_type[col.type]] = quote_column(col.es_column)
return wrap([
{"name": cname, "sql": types, "nested_path": nested_path}
for nested_path, pairs in acc.it... | ma, not_null=False, boolean=False):
value = self.value
v = quote_value(value)
if v == None:
return wrap([{"name": "."}])
elif isinstance(value, text_type):
return wrap([{"name": ".", "sql": {"s": quote_value(value)}}])
elif Math.is_number(v):
return wrap([{"name": ".", "sql":... |
chairco/vtdiscourse | setup.py | Python | mit | 1,822 | 0.002744 | # -*- coding: utf-8 -*-
"""
vtdiscourse
~~~~
This is g0v vTaiwan Project, it's can help develope easy create topic on talk vTaiwan
web site from gitbook
:copyright: (c) 2016 by chairco <chairco@gmail | .com>.
:license: MIT.
"""
import uuid
from pip.req import parse_requi | rements
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
import vtdiscourse
def requirements(path):
return [str(r.req) for r in parse_requirements(path, session=uuid.uuid1())]
class Tox(TestCommand):
def finalize_options(self):
TestCommand.fin... |
LabD/django-postcode-lookup | sandbox/urls.py | Python | mit | 132 | 0 | from django.conf.urls import url, include
| urlpatterns = [
url(r'^postcode-lookup/', include('django_p | ostcode_lookup.urls')),
]
|
cstein/neb | neb/interpolate/__init__.py | Python | mit | 120 | 0.008333 | """ | Different interpolation schemes to create ini | tial beads
"""
from restart import Restart
from linear import Linear
|
andymckay/zamboni | mkt/api/exceptions.py | Python | bsd-3-clause | 2,527 | 0.000396 | from django.conf import settings
from django.core.signals import got_request_exception
from rest_framework import status
from rest_framework.exceptions import APIException
from rest_framework.response import Response
from rest_framework.views import exception_handler
class Alread | yPurchased(Exception):
pass
class Conflict(APIException):
status_code = status.HTTP_409_CONFLICT
default_detail = 'Conflict detected.'
def __init__(self, detail=None):
| self.detail = detail or self.default_detail
class NotImplemented(APIException):
status_code = status.HTTP_501_NOT_IMPLEMENTED
default_detail = 'API not implemented.'
def __init__(self, detail=None):
self.detail = detail or self.default_detail
class ServiceUnavailable(APIException):
stat... |
wonkoderverstaendige/raspi_lepton | server/lepton_server.py | Python | mit | 972 | 0.013374 | #!/usr/bin/env python
import sys
import time
import zmq
import numpy as np
try:
import progressbar
except ImportError:
progressbar = None
try:
import pylepton
except ImportError:
print "Couldn't | import pylepton, using Dummy data!"
Lepton = None
# importing packages in parent folders is voodoo
from common.Frame import Frame
port = "5556"
context = zmq.Context()
socket = context.socket(zmq.PUB)
socket.bind("tcp://*:{}".format(port))
widgets = ['Got ', progressbar.Counter(), ' frames (', progressbar.Timer... | h pylepton.Lepton("/dev/spidev0.1") as lepton:
n = 0
while True:
arr, idx = lepton.capture()
frame = Frame(idx, np.squeeze(arr))
#frame = Frame(-1, np.random.random_integers(4095, size=(60.,80.)))
socket.send(frame.encode())
pbar.update(n)
n += 1
|
mitdbg/modeldb | client/verta/verta/_internal_utils/_config_utils.py | Python | mit | 6,135 | 0.00163 | # -*- coding: utf-8 -*-
impor | t contextlib
import json
import os
import yaml
from .._protos.public.client import Config_pb2 as _ConfigProtos
from . import _utils
# TODO: make this a named tuple, if it would help readability
CONFIG_YAML_FILENAME = "verta_config.yaml"
CONFIG_JSON_FILENAME = "verta_config.json"
CONFIG_FILENAMES = {
CONFIG_YAM... | nfig():
"""
Yields the merged contents of all accessible config files.
Even though this context does nothing on exit, it's still useful for scopes where
:func:`write_local_config` is also used, to visually clarify which contents are being
manipulated.
Yields
------
config : dict
... |
cveazey/ProjectEuler | 10/e10.py | Python | mit | 380 | 0.042105 | #!/usr/bin/env python -tt -Wall
def prime_sieve(upp | er):
marked = [False] * (upper-2)
def next_prime():
for i,v in enumerate(marked):
if not v:
yield i+2
next_prime_gen = next_prime()
for p in next_prime_gen:
for n in xrange(2*p - 2, len(marked), p):
marked[n] = True
yield p
def main():
print(sum(prime_sieve(2000000)))
if __name__ == '__main__':... | () |
vicnet/weboob | contrib/replace-backends-pass.py | Python | lgpl-3.0 | 2,065 | 0.00339 | #!/usr/bin/env python3
"""
This script edits your backends conf file by replacing stuff like:
[bnporc21]
_module = bnporc
website = pp
login = 123456
password = 78910
with:
[bnporc21]
_module = bnporc
website = pp
login = 123456
password = `pass show weboob/bnporc21`
"""
from __future__ import print_function
impo... | nd = mtc.group(1)
if backend in seen:
print('error: backend %r is present multiple times' % backend)
sys.exit(os.EX_DATAERR)
seen.add(backen | d)
print(line, file=outp)
os.rename(outp.name, FILE)
if errors:
print('%d errors were encountered when storing passwords securely' % errors)
sys.exit(2)
|
OliverWalter/amdtk | amdtk/models/normal_gamma.py | Python | bsd-2-clause | 2,962 | 0.000338 |
""" Normal-Gamma density."""
import numpy as np
from scipy.special import gammaln, psi
class NormalGamma(object):
"""Normal-Gamma density.
Attributes
----------
mu : numpy.ndarray
Mean of the Gaussian density.
kappa : float
Factor of the precision matrix.
alpha : float
... | s of the Gamma density.
Methods
-------
expLogPrecision()
Expected value of the logarithm of the precision.
expPrecision()
Expected value of the precision.
KL(self, pdf)
KL divergence between the current and the given densities.
newPosterior(self, stats)
Create a... | def __init__(self, mu, kappa, alpha, beta):
self.mu = mu
self.kappa = kappa
self.alpha = alpha
self.beta = beta
def expLogPrecision(self):
'''Expected value of the logarithm of the precision.
Returns
-------
E_log_prec : numpy.ndarray
... |
rjw57/streamkinect2 | scripts/depth_client.py | Python | bsd-2-clause | 5,772 | 0.003465 | #!/usr/bin/env python
"""
Simple benchmark of how fast depth frames are delivered.
"""
import logging
import struct
import threading
import time
from PIL import Image
import numpy as np
from tornado.ioloop import IOLoop, PeriodicCallback
from streamkinect2.server import ServerBrowser
from streamkinect2.client import ... | mpting connect to {0} which Zeroconf still advertises'.format(ep))
self.connect_to_server(ep)
def on_add_server(self, browser, server_info):
log.info('Discovered server "{0.name}" at "{0.endpoint}"'.format(server_info))
self.connect_to_server(server_info.endpoint)
def connect_to_se... | t_disconnect, sender=client)
self.clients[client] = (ClientWrapper(client), endpoint)
client.connect()
self.endpoints.add(endpoint)
def on_remove_server(self, browser, server_info):
log.info('Server "{0.name}" at "{0.endpoint}" went away'.format(server_info))
if server_info... |
djrlj694/Python-Demo | hello_world.py | Python | unlicense | 65 | 0 | #!/us | r/bin/python
# -*- coding: utf-8 -*-
print | ("Hello world!")
|
bitmazk/django-multilingual-news | multilingual_news/south_migrations/0007_auto.py | Python | mit | 13,164 | 0.007824 | # flake8: noqa
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Removing M2M table for field placeholders on 'NewsEntry'
db.delete_table('multilingual_news... | elated.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'cms.cmsplugin': {
'Meta': {'object_name': 'CMSPlugin'},
'changed... | ime.datetime.now'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'language': ('django.db.models.fields.CharField', [], {'max_length': '15', 'db_index': 'True'}),
'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
... |
gamaio/gama_api | core/migrations/0001_initial.py | Python | mit | 2,293 | 0.002617 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-06-01 07:08
from __future__ import unicode_literals
from django.conf import settings
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial =... | [
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('apikey', models.CharField(max_length=256, unique=True)),
('name', models.CharField(max_length=512, unique=True)),
('description', models.CharField(max_le... | gth=2048)),
('website', models.URLField(max_length=3000)),
('callback_uri', models.URLField(max_length=3000)),
('settings', django.contrib.postgres.fields.jsonb.JSONField()),
],
),
migrations.CreateModel(
name='api_heartbeat',
... |
antoinecarme/pyaf | tests/artificial/transf_BoxCox/trend_MovingAverage/cycle_5/ar_/test_artificial_1024_BoxCox_MovingAverage_5__20.py | Python | bsd-3-clause | 266 | 0.086466 | import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 1024 , FREQ = 'D | ', seed = 0, trendtype = "MovingAverage", cycle_length = 5, transform = "BoxCox", sigma = 0.0, exog_count = 20, ar_order = | 0); |
airbnb/kafka | tests/kafkatest/utils/util.py | Python | apache-2.0 | 2,970 | 0.006734 | # Copyright 2015 Confluent 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, s... | eturn __kafkatest_version__
def _kafka_jar_versions(proc_string):
"""Use a rough heuristic to find all kafka versions explicitly in the process classpath"""
vers | ions = re.findall("kafka-[a-z]+-([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)", proc_string)
versions.extend(re.findall("kafka-([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)", proc_string))
return set(versions)
def is_version(node, version_list, proc_grep_string="kafka", logger=None):
"""Heuristic to check that only the specified ... |
codefortulsa/punctuil | agendas/urls.py | Python | apache-2.0 | 178 | 0 | from django.conf.urls import url
from agendas import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^agend | as/alert$', views.alert, name='alert')
]
| |
chintak/scikit-image | skimage/segmentation/tests/test_slic.py | Python | bsd-3-clause | 5,821 | 0 | import itertools as it
import warnings
import numpy as np
from numpy.testing import assert_equal, assert_raises
from skimage.segmentation import slic
def test_color_2d():
rnd = np.random.RandomState(0)
img = np.zeros((20, 21, 3))
img[:10, :10, 0] = 1
img[10:, :10, 1] = 1
img[10:, 10:, 2] = 1
i... | mal(size=img.shape)
seg_non_spaced | = slic(img, n_segments=2, sigma=0, multichannel=False,
compactness=1.0)
seg_spaced = slic(img, n_segments=2, sigma=0, spacing=[1, 500, 1],
compactness=1.0, multichannel=False)
assert_equal(seg_non_spaced, result_non_spaced)
assert_equal(seg_spaced, result_spac... |
tanghaibao/goatools | tests/test_get_children.py | Python | bsd-2-clause | 1,701 | 0.002939 | #!/usr/bin/env python
"""Test get_all_children vs """
from __future__ import print_function
__copyright__ = "Copyright (C) 2010-2019, DV Klopfenstein, H Tang et al. All rights reserved."
import os
import sys
import timeit
from goatools.base import get_godag
from goatools.godag.go_tasks import get_id2children
from go... | go2children_orig[goobj.id] = children
else:
go2children_empty.add(goobj.id)
tic = prt_hms(tic, "Get all goobj's children using GOTerm.get_all_children()", prt)
# Get all children for all GO IDs using GOTerm get_all_children
go2children_fast = get_id2children(go2obj.values())
p... | id2children", prt)
# Compare children lists
CheckGOs('test_get_children', go2obj).chk_a2bset(go2children_orig, go2children_fast)
if __name__ == '__main__':
PRT = None if len(sys.argv) != 1 else sys.stdout
test_get_children(PRT)
# Copyright (C) 2010-2019, DV Klopfenstein, H Tang et al. All rights rese... |
rbruyere/appengine-mapreduce | python/test/mapreduce gcs/mapreduce/input_readers.py | Python | apache-2.0 | 128,812 | 0.00736 | #!/usr/bin/env python
# Copyright 2010 Google Inc. All Rights R | eserved.
#
# 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 the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either ... |
jmaas/cobbler | cobbler/remote.py | Python | gpl-2.0 | 89,579 | 0.001585 | """
Copyright 2007-2009, Red Hat, Inc and Others
Michael DeHaan <michael.dehaan AT gmail>
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 late... | toinstall_mgr = autoinstall_manager.AutoInstallationManager(api._collection_mgr)
def check(self, token):
"""
Returns a list of all the messages/warnings that are things
that admin may want to correct about the configuration of
the cobbler server. This has nothing to do with "check_... | PC API.
"""
self.check_access(token, "check")
return self.api.check(logger=self.logger)
def background_buildiso(self, options, token):
"""
Generates an ISO in /var/www/cobbler/pub that can be used to install
profiles without using PXE.
"""
# FIXME: be... |
trujunzhang/djzhang-targets | cwgooglelinkedin/cwgooglelinkedin/spiders/googlelinkedin_debug_spider.py | Python | mit | 1,547 | 0.004525 | # -*- coding: utf-8 -*-
from random import Random
import scrapy
from scrapy.selector import Selector, HtmlXPathSelector
from scrapy_webdriver.http import WebdriverRequest
# yield WebdriverRequest(_url, callback=self.parse_category_full_page)
from cwgooglelinkedin.items import GoogleLinkedIn
import urlparse
class Goo... | ugSpider, cls).from_crawler(crawler,
args,
mongo_uri=crawler.settings.get('MONGODB_SERVER')
)
def parse(self, response):
item = self._cr... | ield item
self._history_db.process_item(response.url)
|
kunz07/fyp2017 | GUI/final.py | Python | mit | 52,154 | 0.005772 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'final.ui'
#
# Created by: PyQt5 UI code generator 5.8.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
... | t Image
from PIL import ImageDraw
from PIL import ImageFont
PORT = '/dev/ttyUSB0'
BAUD_RATE = 9600
# Open serial port
ser = serial.Serial(PORT, BAUD_RATE)
class MovieSplashScreen(QSplashScreen):
def _ | _init__(self, movie, parent = None):
movie.jumpToFrame(0)
pixmap = QPixmap(movie.frameRect().size())
QSplashScreen.__init__(self, pixmap)
self.movie = movie
self.movie.frameChanged.connect(self.repaint)
def showEvent(self, event):
self.movie.sta... |
ezhuk/aws-tools | ec2/check_instance_status.py | Python | mit | 1,240 | 0.002419 | #!/usr/bin/env python
# Copyright (c) 2014 Eugene Zhuk.
# Use of this source code is governed by the MIT license that can be found
# in the LICENSE file.
"""Checks EC2 Instance status.
Displays the current status of one or more EC2 Instances.
Usage:
./check_instance_status.py <options>
"""
import boto.ec2
impor... | port sys
class Error(Exception):
pass
def main():
parser = optparse.OptionParser('Usage: %prog [options]')
parser.add_option('-i', '--instance', dest='instances', action='append',
help='One or more EC2 Instances to check the status for.')
(opts, args) = parser.parse_args()
if 0 != len(a... | e:
parser.print_help()
return 1
try:
c = boto.connect_ec2()
instances = list(itertools.chain.from_iterable(r.instances
for r in c.get_all_reservations()))
if not instances:
raise Error('could not find \'{0}\''.format(opts.instances))
for i in... |
pyaiot/pyaiot | pyaiot/gateway/common/node.py | Python | bsd-3-clause | 2,399 | 0 | # Copyright 2017 IoT-Lab Team
# Contributor(s) : see AUTHORS file
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions a... | utions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote prod... | FTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIREC... |
aboood40091/BFRES-Tool | structs.py | Python | gpl-3.0 | 1,321 | 0 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# BFRES Tool
# Version 5.1
# Copyright © 2017-2018 AboodXD
# This file is part of BFRES Tool.
# BFRES Tool 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, eith... | en the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import struct
class GX2Surface(struct.... | '>16I')
def data(self, data, pos):
(self.dim,
self.width,
self.height,
self.depth,
self.numMips,
self.format_,
self.aa,
self.use,
self.imageSize,
self.imagePtr,
self.mipSize,
self.mipPtr,
self.tileMo... |
sebrandon1/nova | nova/tests/unit/api/openstack/placement/test_util.py | Python | apache-2.0 | 10,993 | 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
# ... | on(
'{"name": "cow", '
'"uuid": "%s"}' % uuidsentinel.rp_uuid,
self.schema)
self.assertEqual('cow', data['name'])
self.assertEqual(uuidsentinel.r | p_uuid, data['uuid'])
class TestJSONErrorFormatter(test.NoDBTestCase):
def setUp(self):
super(TestJSONErrorFormatter, self).setUp()
self.environ = {}
# TODO(jaypipes): Remove this when we get more than a single version
# in the placement API. The fact that we only had a single ver... |
flavio-casacurta/File-FixedS | GerJobPdZds.py | Python | mit | 3,378 | 0.01421 | # -*- coding:utf-8
'''
Created on 22/05/2015
@author: C&C - HardSoft
'''
import os
import sys
import traceback
from util.change import change
from util.homogenize import Homogenize
from columns import Columns
from calc_length import calc_length
class GerJobPdZds(object):
def __init__(self, jobname, path, di... | col = Columns()
bookout = col.columns(self.book,fmt='cbl', signal=False)
book_zonado = os.path.join(self.path, '{}_ZD.cpy'.format(basename))
with open(book_zonado, 'w') as bkzd:
bkzd.writelines(bookout)
lengthout = str(c... | inrec,
self.start,
self.length,
content)
inrec = " "
buil... |
PX4/Firmware | src/modules/sensors/vehicle_magnetometer/mag_compensation/python/mag_compensation.py | Python | bsd-3-clause | 10,043 | 0.009858 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
File: mag_compensation.py
Author: Tanja Baumann
Email: tanja@auterion.com
Github: https://github.com/baumanta
Description:
Computes linear coefficients for mag compensation from thrust and current
Usage:
python mag_compensation.py /path/to/log/logfile.ulg curr... | e == "current":
power = get_data('battery_status', 'current_a', comp_instance)
power = np.t | rue_divide(power, 1000) #kA
power_t = ms2s_list(get_data('battery_status', 'timestamp', comp_instance))
comp_type_param = 2 + comp_instance
factor = -1
unit = "[G/kA]"
else:
print("unknown compensation type {}. Supported is either 'thrust' or 'current'.".format(comp_type))
sys.exit(1)
if len(power) == 0:
print(... |
ramnes/qtile | test/widgets/test_moc.py | Python | mit | 6,555 | 0.000765 | # Copyright (c) 2021 elParaguayo
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distrib... | return output
elif arg == "-p":
cls.info[cls.index]['State'] = "PLAY"
elif arg == "-G":
if cls.info[cls.index]['State'] == "PLAY":
cls.info[cls.index]['State'] = "PAUSE"
elif cls.info[cls.index]['State'] == "PAUSE":
| cls.info[cls.index]['State'] = "PLAY"
elif arg == "-f":
cls.index = (cls.index + 1) % len(cls.info)
elif arg == "-r":
cls.index = (cls.index - 1) % len(cls.info)
def no_op(*args, **kwargs):
pass
@pytest.fixture
def patched_moc(fake_qtile, monkeypatch, fak... |
billthefighter/sunrise | hzeller-test.py | Python | mit | 201 | 0.004975 | #!/us | r/bin/env python
from rgbmatrix import RGBMatrix
import time
rows = 32
chains = 2
parallel = 1
myMatrix = RGBMatrix(rows, chains, parallel)
myMatrix.Fill(255, 0, 0)
time.sleep(5)
myMatrix.Cl | ear() |
danielru/moose | python/TestHarness/RunParallel.py | Python | lgpl-2.1 | 9,808 | 0.015701 | from subprocess import *
from time import sleep
from timeit import default_timer as clock
from tempfile import TemporaryFile
#from Queue import Queue
from collections import deque
from Tester import Tester
from signal import SIGTERM
import os, sys
## This class provides an interface to run commands in parallel
#
# T... | on
tester.prepare()
job_index = self.jobs.index(None) # find an empty slot
log( 'Command %d started: %s' % (job_index, command) )
# It seems that using PIPE doesn't work very well when launching multiple jobs.
# It deadlocks rather easy. Instead we will use temporary files
# to hold the outpu... | tmp_command = command
command = "echo"
f = TemporaryFile()
# On Windows, there is an issue with path translation when the command is passed in
# as a list.
p = Popen(command,stdout=f,stderr=f,close_fds=False, shell=True)
if self.options.dry_run:
command = tmp_command... |
poussik/vcrpy | tests/unit/test_persist.py | Python | mit | 1,021 | 0 | import pytest
from vcr.persisters.filesystem import FilesystemPersister
from vcr.serializers import jsonserializer, yamlserializer
@pytest.mark.parametrize("cassette_path, serializer", [
('tests/fixtures/migration/old_cassette.json', jsonserializer),
('tests/fixtures/migration/old_cassette.yaml', yamlseriali... | rsister.load_cassette(cassette_path, serializer)
assert "run the migration script" in excinfo.exconly()
@pytest.mark.parametrize("cassette_path, serializer", [
('tests/fixtures/migration/not_cassette.txt', jsonserializer),
('tests/fixtures/migration/not_cassette.txt', yamlserializer),
])
def test_load_cas... | nfo:
FilesystemPersister.load_cassette(cassette_path, serializer)
assert "run the migration script" not in excinfo.exconly()
|
OpenDrift/opendrift | tests/readers/test_global_landmask.py | Python | gpl-2.0 | 4,005 | 0.001498 | import numpy as np
import pytest
from . import *
from opendrift.readers import reader_global_landmask
from opendrift.readers import reader_ROMS_native
from opendrift.models.oceandrift import OceanDrift
@pytest.mark.veryslow
def test_reader_landmask_generate():
import os, tempfile
tmpdir = os.path.join(tempfi... | Reader(extent=[4, 55, 11, 65])
assert reader_global.extent is not None or reader_glob | al.mask_type == 1
assert reader_global.__on_land__(np.array([10]), np.array([60])) == [True]
assert reader_global.__on_land__(np.array([5]), np.array([60])) == [False]
def test_global_array(test_data):
reader_global = reader_global_landmask.Reader()
assert reader_global.extent is None
reader_nor... |
iOSForensics/pymobiledevice | pymobiledevice/apis.py | Python | gpl-3.0 | 1,788 | 0 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# vim: fenc=utf-8
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
#
#
"""
File name: apis.py
Author: dhilipsiva <dhilipsiva@gmail.com>
Date created: 2016-06-19
"""
from os import path
# from pprint import pprint
def get_lockdown_and_service(udid):
from pymo... | ad())
cmd = {"Command": "Install", "PackagePath": path.basename(ipa_path)}
return run_command(service, uuid, cmd)
def uninstall_ipa(uuid, bundle_id):
lockdown, service = get_lockdown_and_service(uuid)
cmd = {"Command": "Uninstall", "ApplicationIdentifier": bundle_id}
return run_command(service, uu... | service, uuid, cmd)
apps_details = result.get("LookupResult")
apps = []
for app in apps_details:
if apps_details[app]['ApplicationType'] == 'User':
apps.append(app)
return apps
|
Kylskap/PloPo | skeletonWidget.py | Python | apache-2.0 | 728 | 0.023352 | # -*- coding: utf-8 -*-
"""
Created on Thu May 04 19:53:03 2017
@author: ZechT
"""
import sys
import numpy as np
from PyQt5.QtWidgets import *
class AbstractHandler(QWidget):
|
def __init__(self,parent=None):
QWidget.__init__(self)
self.parent=parent
| def main():
# Create an PyQT5 application object.
a = QApplication(sys.argv)
# The QWidget widget is the base class of all user interface objects in PyQt5.
c = QWidget()
w = AbstractHandler(c)
w.setFixedSize(395,395)
# Set window title
w.setWindowTitle("Widget")
... |
aESeguridad/GERE | venv/lib/python2.7/site-packages/cffi/model.py | Python | gpl-3.0 | 21,110 | 0.0009 | import types, sys
import weakref
from .lock import allocate_lock
# type qualifiers
Q_CONST = 0x01
Q_RESTRICT = 0x02
Q_VOLATILE = 0x04
def qualify(quals, replace_with):
if quals & Q_CONST:
replace_with = ' const ' + replace_with.lstrip()
if quals & Q_VOLATILE:
replace_with = ' volatile ' +... | def build_backend_type(self, ffi, finishlist):
result = self.result.get_cached_btype(ffi, finishlist)
args = []
for tp i | n self.args:
args.append(tp.get_cached_btype(ffi, finishlist))
abi_args = ()
if self.abi == "__stdcall":
if not self.ellipsis: # __stdcall ignored for variadic funcs
try:
abi_args = (ffi._backend.FFI_STDCALL,)
except Attribut... |
mvidalgarcia/indico | indico/modules/users/legacy.py | Python | mit | 10,195 | 0.002256 | # This file is part of Indico.
# Copyright (C) 2002 - 2019 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from flask_multipass import IdentityInfo
from indico.legacy.common.cache import GenericCache
from indico.... | )
# TODO: Once everything is in SQLAlchemy this whole thing needs to go away!
user = None
if data[0] == 'LDAP':
identifier = data[1]
email = data[2]
# You better have only one ldap provider or at least different identifiers ;)
identity = Identity.q... | user = identity.user
elif data[0] == 'Nice':
email = data[1]
else:
return None
if not user:
user = User.query.filter(User.all_emails == email).first()
if user:
self._old_id = self.id
self.id = str(user.id)
... |
konata39/chatbot-backend | chatbot.py | Python | gpl-3.0 | 4,400 | 0.006215 | # -*- coding: utf-8 -*-
import console
import task_modules.module_switch as module_switch
def main():
chatbot = Chatbot()
chatbot.waiting_loop()
class Chatbot(object):
def __init__(self, name="NCKU"):
self.name = name # The name of chatbot.
self.speech = '' # The... | - target : Optional. It is to define the user's input is in form of
a sentence or a given answer by pressing the bubble buttom.
If it is come from a button's text, target is the attribute name our
module want to confirm.
Return:
- response : Based on ... | - status : It would be the module's current status if the user has
been sent into any module and had not left it.
- target : Refer to get_query() in task_modules/task.py
- candiates: Refer to get_query() in task_modules/task.py
"""
status =... |
Cisco-Talos/pyrebox | volatility/volatility/plugins/hpakinfo.py | Python | gpl-2.0 | 2,123 | 0.006123 | # Volatility
# Copyright (C) 2007-2013 Volatility Foundation
#
# This file is part of Volatility.
#
# Volatility 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 o... | nder_text(self, outfd, data):
if not self._config.OUTPUT_FILE:
debug.error("You must supply --output-file")
data.convert_to_raw(outfd)
print "Compressed: {0}".format("Yes" if data.physmem.Compressed == 1 else "No")
print "Compressed Size: {0:#x}".fo... | x}".format(data.physmem.Length) |
ingadhoc/multi-company | account_multic_fix/models/__init__.py | Python | agpl-3.0 | 340 | 0 | ##############################################################################
# For copyright and license notices, see __manifest__.py file in module root
# directory
############################################ | ##################################
from . import account_move
from . import account_move_line
from . import acco | unt_master_port
|
anryko/ansible | test/units/modules/network/fortios/test_fortios_log_custom_field.py | Python | gpl-3.0 | 7,817 | 0.004094 | # Copyright 2019 Fortinet, 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 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the... | utils.network.fortios.fortios import FortiOSHandler
try:
fr | om ansible.modules.network.fortios import fortios_log_custom_field
except ImportError:
pytest.skip("Could not load required modules for testing", allow_module_level=True)
@pytest.fixture(autouse=True)
def connection_mock(mocker):
connection_class_mock = mocker.patch('ansible.modules.network.fortios.fortios_lo... |
tejaskhot/How-to-fit-an-elephant | elephant.py | Python | unlicense | 824 | 0.026699 | import numpy as np
import pylab
# elephant paramet | ers
p1, p2, p3, p4 = (50 - 30j, 18 + 8j, 12 - 10j, -14 - 60j )
p5 = 40 + 20j # eyepiece
def fourier(t, C):
f = np.zeros(t.shape)
A, B = C.real, C.imag
for k in range(len(C)):
f = f + A[k]*np.cos(k*t) + B[k]*np.sin(k*t)
return f
def elephant(t, p1, p2, p3, p4, p5):
npar = 6
Cx = np.z... | type='complex')
Cx[1] = p1.real*1j
Cx[2] = p2.real*1j
Cx[3] = p3.real
Cx[5] = p4.real
Cy[1] = p4.imag + p1.imag*1j
Cy[2] = p2.imag*1j
Cy[3] = p3.imag*1j
x = np.append(fourier(t,Cx), [-p5.imag])
y = np.append(fourier(t,Cy), [p5.imag])
return x,y
x, y = elephant(np.linspa... |
SKIRT/PTS | do/modeling/plot_with_reference_sed.py | Python | agpl-3.0 | 2,365 | 0.002115 | #!/usr/bin/env python
# -*- coding: utf8 -*-
# *****************************************************************
# ** PTS -- Python Toolkit for working with SKIRT **
# ** © Astronomical Observatory, Ghent University **
# *****************************************************************
##... | erence_seds Plot a certain simulated SED with the modeling reference SED.
# -----------------------------------------------------------------
# Ensure Python 3 compatibility
from __future__ import absolute_import, division, print_function
# Import the relevant PTS classes and modules
from pts.modeling.core.environme... | se_arguments
from pts.core.plot.sed import SEDPlotter
from pts.core.data.sed import SED, ObservedSED, is_from_skirt
from pts.core.basics.plot import mpl, plotting_libraries
# -----------------------------------------------------------------
environment = find_modeling_environment_up_cwd()
# -------------------------... |
iCHAIT/whats-fresh-api | whats_fresh/whats_fresh_api/tests/views/entry/test_inline_preparation.py | Python | apache-2.0 | 4,294 | 0 | from django.test import TestCase
from django.core.urlresolvers import reverse
from whats_fresh.whats_fresh_api.models import Preparation
from django.contrib.auth.models import User, Group
class InlinePreparationTestCase(TestCase):
"""
Test that the Inline Preparation form works as expected.
Things teste... | put'}
form = response.context['preparation_form']
for field in fields:
# for the Edit tests, you should be able to access
# form[field].value
self.assertIn(fields[field], str(form[field]))
def test_successful_preparation_creation_minimal(self):
"""
... | objects.all().delete()
# Data that we'll post to the server to get the new preparation created
inline_preparation = {
'name': 'Fried', 'description': '', 'additional_info': ''}
self.client.post(reverse('preparation_ajax'), inline_preparation)
preparation = Preparation.obje... |
agry/NGECore2 | scripts/equipment/bonus_sets/set_bonus_smuggler_utility_b.py | Python | lgpl-3.0 | 1,539 | 0.026641 | import sys
from services.equipment import BonusSetTemplate
from java.util import Vector
def addBonusSet(core):
bonusSet = BonusSetTemplate("set_bonus_smuggler_utility_b")
bonusSet.addRequiredItem("item_band_set_smuggler_utility_b_01_01")
bonusSet.addRequiredItem("item_ring_set_smuggler_utility_b_01_01")
bonusSet... | vice.addBonusSetTemplate(bonusSet)
def handleChange(core, creature, set):
wornItems = set.getWornTemplateCount(creature)
if wornItems == 3:
core.buffService.addBuffToCreature(creature, "set_bonus_smuggler_utility_b_1", creature)
creature.sendSystemMessage('@set_bonus:set_bonus_smuggler_utility_b_1_sys', 0)
e... | ('@set_bonus:set_bonus_smuggler_utility_b_2_sys', 0)
elif wornItems == 5:
core.buffService.addBuffToCreature(creature, "set_bonus_smuggler_utility_b_3", creature)
creature.sendSystemMessage('@set_bonus:set_bonus_smuggler_utility_b_3_sys', 0)
else:
core.buffService.removeBuffFromCreatureByName(creature, "set_bon... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.