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 |
|---|---|---|---|---|---|---|---|---|
alexisbellido/dockerize-django | python-click/example.py | Python | bsd-3-clause | 1,458 | 0.005487 | # -- coding: utf-8 --
import click
import yaml
import json
@click.command()
@click.option('-n', '--accession_number', help='Accession number')
@click.option('-e', '--environment', default='local', help='Environment.')
@click.option('--input', type=click.File('r'), required=False)
@click.option('--dryrun', is_flag=Tru... | ession_numbers:
count += 1
click.echo('===========================================================\n')
click.echo('{count} - Running for {accession_number} on {environment}\n'.format(
count=count,
accession_number=accession_number,
environment=environment |
))
if dryrun:
click.echo("\nDry run...\n")
else:
click.echo("\nActual run...\n")
if __name__ == '__main__':
process()
|
jeremiahyan/odoo | addons/gamification/models/gamification_badge.py | Python | gpl-3.0 | 9,182 | 0.002941 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from datetime import date
from odoo import api, fields, models, _, exceptions
_logger = logging.getLogger(__name__)
class GamificationBadge(models.Model):
"""Badge object that users can send and re... | get_badge_user_stats',
help="The number of time the current user has received this badge this month.")
stat_my_monthly_sending = fields.Integer(
'My Monthly Sending Total',
compute='_get_badge_user_stats',
help="The number of time the current user has sent this badge this month. | ")
remaining_sending = fields.Integer(
"Remaining Sending Allowed", compute='_remaining_sending_calc',
help="If a maximum is set")
@api.depends('owner_ids')
def _get_owners_info(self):
"""Return:
the list of unique res.users ids having received this badge
th... |
sharad/calibre | src/calibre/customize/builtins.py | Python | gpl-3.0 | 66,256 | 0.007274 | # -*- coding: utf-8 -*-
__license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
import os, glob, functools, re
from calibre import guess_type
from calibre.customize import (FileTypePlugin, MetadataReaderPlugin,
MetadataWriterPlugin, PreferencesPlugin, InterfaceActionBase, StoreBase)... | ept:
pass
if ret is not None:
path, data = ret
ext = os.path.splitext(path)[1][1:]
mi.cover_data = (ext.lower(), data)
return mi
class CHMMeta | dataReader(MetadataReaderPlugin):
name = 'Read CHM metadata'
file_types = set(['chm'])
description = _('Read metadata from %s files') % 'CHM'
def get_metadata(self, stream, ftype):
from calibre.ebooks.chm.metadata import get_metadata
return get_metadata(stream)
class EPUBMeta... |
etamponi/taxonomy-generator | deltaphi/test_category_group.py | Python | gpl-2.0 | 3,675 | 0.001905 | import unittest
import numpy
from deltaphi.category_info import RawCategoryInfo, CategoryGroup, CategoryInfoFactory
from deltaphi.fake_entities import FakeCategoryInfo
__author__ = 'Emanuele Tamponi'
class TestCategoryGroup(unittest.TestCase):
def setUp(self):
self.builder = CategoryInfoFactory({"a", ... | .testing.assert_array_equal([50, 40, 10 | 0], merged.frequencies)
self.assertEqual("(C1+C2)", merged.category)
self.assertEqual(180, merged.documents)
self.assertEqual(CategoryGroup([ci1, ci2]), merged.child_group)
def test_build_parent_multiple(self):
ci1 = self.builder.build(RawCategoryInfo("C1", 100, {"a": 50, "c": 80}))... |
morgenst/pyfluka | pyfluka/utils/OrderedYAMLExtension.py | Python | mit | 460 | 0 | import yaml
from collecti | ons import OrderedDict
def dump(data, stream=None, dumper=yaml.SafeDumper, **kwds):
class OrderedDumper(dumper):
pass
def _dict_representer(dumper, data):
return dumper.represent_mapping(
yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
data.items()
)
Order... | )
|
xupingmao/xnote | tests/test_base.py | Python | gpl-3.0 | 4,620 | 0.007193 | # encoding=utf-8
import sys
sys.path.insert(1, "lib")
sys.path.insert(1, "core")
import os
import time
import unittest
import xconfig
import xutils
import xtables
import xmanager
import xtemplate
import web
import six
import json
import xauth
from xutils import dbutil
from handlers.fs.fs_upload import get_upload_file_p... | gs, **kw):
response = APP.request(*args, **kw)
self.assertEqual("200 OK", response.status)
def check_200_debug(self, *args, **kw):
response = APP.request(*args, **kw)
print(args, kw, response)
print(APP.mapping)
se | lf.assertEqual("200 OK", response.status)
def check_303(self, *args, **kw):
response = APP.request(*args, **kw)
self.assertEqual("303 See Other", response.status)
def check_404(self, url):
response = APP.request(url)
self.assertEqual("404 Not Found", response.status)
def c... |
ploggingdev/practice | algos/tests/mergesort_tests.py | Python | gpl-3.0 | 437 | 0.011442 | from unittest import TestCase
from random import random
from algos.mergesort import merge, mergesort
class MergeSortTest(TestCase): |
def test_merge_sort(self):
seq = [random() for _ in range(4000)]
sorted_seq = sorted(seq)
self.assertEqual(mergesort(seq), sorted_seq)
def test_merge_sort_2(self):
| self.assertEqual(mergesort(list()), list())
if __name__ == '__main__':
unittest.main() |
qiime2/qiime2 | qiime2/sdk/tests/test_actiongraph.py | Python | bsd-3-clause | 5,365 | 0 | # ----------------------------------------------------------------------------
# Copyright (c) 2016-2022, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... | ------------------------
import unittest
from qiime2.core.testing.type import (Mapping, IntSequence1, IntSequence2)
from qiime2.core.type.primitive import (Int, Str, Metadata)
from qiime2.core.type.visualization import (Visualization)
from qiime2.core.testing.util import get_dummy_plugin
from qiime2.sdk.actiongraph im... | get_dummy_plugin()
self.g = None
def test_simple_graph(self):
methods = [self.plugin.actions['no_input_method']]
self.g = build_graph(methods)
obs = list(self.g.nodes)
exp_node = str({
'inputs': {},
'outputs': {
'out': Mapping
... |
fbradyirl/home-assistant | tests/components/alert/__init__.py | Python | apache-2.0 | 37 | 0 | "" | "Tests for the alert compo | nent."""
|
nkgilley/home-assistant | homeassistant/components/transport_nsw/sensor.py | Python | apache-2.0 | 4,543 | 0 | """Support for Transport NSW (AU) to query next leave event."""
from datetime import timedelta
import logging
from TransportNSW import TransportNSW
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
ATTR_ATTRIBUTION,
ATTR_MODE,
CONF_API_K... | def device_state_attributes(self):
"""Return the state attributes."""
if self._times is not None:
return {
ATTR_DUE_IN: self._times[ATTR_DUE_IN],
ATTR_STOP_ID: self._stop_id,
ATTR_ROUTE: self._times[ATTR_ROUTE],
ATTR_DELAY: se... | ATTR_MODE: self._times[ATTR_MODE],
ATTR_ATTRIBUTION: ATTRIBUTION,
}
@property
def unit_of_measurement(self):
"""Return the unit this state is expressed in."""
return TIME_MINUTES
@property
def icon(self):
"""Icon to use in the fronten... |
zhang0137/chromite | lib/table_unittest.py | Python | bsd-3-clause | 12,584 | 0.00739 | #!/usr/bin/python
# Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Unit tests for the table module."""
import cStringIO
import os
import sys
import tempfile
sys.path.insert(0, os.path.dirname(os... | L1: 'Walk', COL2: 'The', COL3: 'Line'}
ROW0a = {COL0: 'Xyz', COL1: 'Bcd', COL2: 'Cde', COL3: 'Yay'}
ROW0b = {COL0: 'Xyz', COL1: 'Bcd', COL2: 'Cde', COL3: 'Boo'}
ROW1a = {COL0: 'Abc', COL1: 'Bcd', COL2: 'Opq', COL3: 'B | lu'}
EXTRACOL = 'ExtraCol'
EXTRACOLUMNS = [COL0, EXTRACOL, COL1, COL2]
EROW0 = {COL0: 'Xyz', EXTRACOL: 'Yay', COL1: 'Bcd', COL2: 'Cde'}
EROW1 = {COL0: 'Abc', EXTRACOL: 'Hip', COL1: 'Bcd', COL2: 'Opq'}
EROW2 = {COL0: 'Abc', EXTRACOL: 'Yay', COL1: 'Nop', COL2: 'Wxy'}
def _GetRowValsInOrder(self, row):
... |
tmetsch/python-dtrace | examples/ctypes/syscall_by_zone.py | Python | mit | 925 | 0 | #!/usr/bin/env python
"""
Use the Python DTrace consumer and count syscalls by zone.
Created on Oct 10, 2011
@author: tmetsch
"""
from __future__ import print_function
import time
from ctypes import cast, c_char_p, c_int
from dtrace_ctypes import consumer
SCRIPT = 'syscall:::entry { @num[zonename] = count(); }'
... | Run DTrace...
"""
dtrace = consumer.DTraceConsumerThread(SCRIPT, walk_func=walk)
dtrace.start()
# we will stop t | he thread after some time...
time.sleep(5)
# stop and wait for join...
dtrace.stop()
dtrace.join()
if __name__ == '__main__':
main()
|
3dfxsoftware/cbss-addons | price_structure/model/sale.py | Python | gpl-2.0 | 10,026 | 0.005286 | #!/usr/bin/python
# -*- encoding: utf-8 -*-
###########################################################################
# Module Writen to OpenERP, Open Source Management Solution
# Copyright (C) OpenERP Venezuela (<http://openerp.com.ve>).
# All Rights Reserved
# Credits#######################################... | s if at least one product is being sold in the price range set out in its cost structure
'''
if context is None:
| |
willowtreeapps/tango-core | tests/errors/importerror.py | Python | bsd-3-clause | 77 | 0 | """
site: importerror
routes:
exports:
""" |
impo | rt doesnotexist
doesnotexist
|
larsks/muxdemux | muxdemux/writer.py | Python | gpl-3.0 | 4,581 | 0 | import cbor
import hashlib
import logging
import zlib
from .common import * # NOQA
LOG = logging.getLogger(__name__)
default_hashalgo = 'sha256'
state_bos = 0
state_metadata = 1
state_data = 2
state_eos = 3
class MuxError(Exception):
pass
class InvalidState(MuxError):
pass
class StreamWriter(object):... | LOG.debug('writing block: type=%s, content=%s',
blktype, repr(kwargs))
cbor.dump(dict(blktype=blktype, **kwargs), s | elf.fh)
def _get_hash_context(self):
return getattr(hashlib, self.hashalgo)()
def add_metadata(self, k, v):
self.metadata[k] = v
def write(self, data):
'''Write a data block to the mux stream.'''
# Write out the header if we haven't already.
if self.state == state... |
JSLBen/KnowledgeTracing | codes/AssistmentsProperties.py | Python | mit | 8,942 | 0.006263 | # datapath config
# data folder location
data_folder = '/home/data/jleeae/ML/e_learning/KnowledgeTracing/data/'
csv_original_folder = data_folder + 'csv_original/'
csv_rnn_data_folder = data_folder + 'csv_rnn_data/'
pkl_rnn_data_folder = data_folder + 'pkl_rnn_data/'
# csv_original
Assistments2009_csv_original = csv_o... | l'
self.correct = 'correct'
self.attempt_count = 'attempt_count'
self.ms_first_response = 'ms_first_response'
self.tutor_mode = 'tutor_mode'
| self.answer_type = 'answer_type'
self.sequence_id = 'sequence_id'
self.student_class_id = 'student_class_id'
self.position = 'position'
self.type = 'type'
self.base_sequence_id = 'base_sequence_id'
self.skill_id = 'skill_id'
self.skill_name = 'skill_name'
... |
Nzbuu/SensorMonitor | SensorMonitor/sensor.py | Python | mit | 1,304 | 0 | import SensorMonitor
class SensorFactory:
def __init__(self, sensor_cls, factory_if):
self.sensor_cls = sen | sor_cls
self.facto | ry_if = factory_if
def create(self, **kwargs):
sensor_if = self.factory_if.create(**kwargs)
return self.sensor_cls(sensor_if)
class Sensor:
def __init__(self, sensor_if):
self.sensor_if = sensor_if
def get_measurement(self):
return self.sensor_if.read_data()
class Senso... |
jinzekid/codehub | python/py3_6venv/encryption/rsa_generate_keypair.py | Python | gpl-3.0 | 1,156 | 0.012911 | # Author: Jason Lu
# RSA 是 Ron Rivest、Adi Shamir、Len Adleman 于 1977 年发明的加密算法。
# 公钥加密系统在加密和解密时分别使用不同的密钥。RSA 等就是公钥加密算法
# 在公钥加密系 | 统中,加密使用公钥(Public key),解密使用私钥(Private ke | y)。
# 这两种密钥 都需要通过算法生成。
# 公钥和私钥的密钥对可以通过 ssh-keygen 命令或 openssl 命令来创 建,
# 不过我们这里要学习的是用 PyCrypto 生成密钥的方法。
from Crypto.PublicKey import RSA
from Crypto import Random
INPUT_SIZE = 1024
def main():
random_func = Random.new().read #产生随机数的函数
key_pair = RSA.generate(INPUT_SIZE, random_func) #生成密钥对
private_pem = k... |
partp/gtg-services | GTG/plugins/export/templates.py | Python | gpl-3.0 | 6,174 | 0 | # -*- coding: utf-8 -*-
# Copyright (c) 2010 - Luca Invernizzi <[email protected]>
# 2012 - Izidor Matušov <[email protected]>
#
# 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
# Fou... | import glob
import os.path
import subprocess
import sys
import tempfile
import threading
from Cheetah.Template import Template as CheetahTemplate
from xdg.BaseDirectory import xdg_config_home
from gi.repository import GObject
TEMPLATE_PATHS = [
os.path.join(xdg_config_home, "gtg/plugins/export/export_templates"),... | or all the
available templates. """
template_list = []
for a_dir in TEMPLATE_PATHS:
template_list += glob(os.path.join(a_dir, "template_*"))
return template_list
class Template:
""" Representation of a template """
def __init__(self, path):
self._template = path
self._... |
Vvucinic/Wander | venv_2_7/lib/python2.7/site-packages/Django-1.9-py2.7.egg/django/core/cache/backends/base.py | Python | artistic-2.0 | 9,677 | 0.00155 | "Base Cache class."
from __future__ import unicode_literals
import time
import warnings
from django.core.exceptions import DjangoRuntimeWarning, ImproperlyConfigured
from django.utils.module_loading import import_string
class InvalidCacheBackendError(ImproperlyConfigured):
pass
class CacheKeyWarning(DjangoRun... | f the key is i | n the cache and has not expired.
"""
return self.get(key, version=version) is not None
def incr(self, key, delta=1, version=None):
"""
Add delta to value in the cache. If the key does not exist, raise a
ValueError exception.
"""
value = self.get(key, version=... |
kingland/go-v8 | v8-3.28/tools/testrunner/local/testsuite.py | Python | mit | 7,417 | 0.010382 | # Copyright 2012 the V8 project authors. All rights reserved.
# 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 conditi... | elf, args):
filtered = []
filtered_args = []
for a in args:
argpath = a.split(os.path.sep)
if argpath[0] != self.name:
continue
if len(argpath) == 1 or (len(argpath) == 2 and argpath[1] == '*'):
return # Don't filter, run all tests in this suite.
path = os.path.sep.j... | h(a):
filtered.append(t)
break
self.tests = filtered
def GetFlagsForTestCase(self, testcase, context):
raise NotImplementedError
def GetSourceForTest(self, testcase):
return "(no source available)"
def IsFailureOutput(self, output, testpath):
return output.exit_code != 0
... |
woobe/h2o | py/testdir_single_jvm/test_frame_split_iris.py | Python | apache-2.0 | 1,612 | 0.007444 | import unittest, time, sys, random
sys.path.extend(['.','..','py'])
import h2o, h2o_cmd, h2o_glm, h2o_hosts, h2o_import as h2i, h2o_jobs, h2o_exec as h2e
DO_POLL = False
class Basic(unittest.TestCase):
def tearDown(self):
h2o.check_sandbox_for_errors()
@classmethod
def setUpClass(cls):
lo... | 23)
@classmethod
def tearDownClass(cls):
h2o.tear_down_cloud()
def test_frame_split(self):
h2o.beta_features = True
csvFilename = 'iris22.csv'
csvPathname = 'iris/' + csvFilename
hex_key = "iris.hex"
parseResult = h2i.import_parse(bucket='smalldata', path=... | , schema='local', timeoutSecs=10)
print "Just split away and see if anything blows up"
splitMe = hex_key
# don't split
for s in range(10):
fs = h2o.nodes[0].frame_split(source=splitMe, ratios=0.5)
split0_key = fs['split_keys'][0]
split1_key = fs['spl... |
ThreatConnect-Inc/tcex | tcex/pleb/env_path.py | Python | apache-2.0 | 1,603 | 0.000624 | """ENV Str"""
# standard library
import os
import re
from pathlib import Path
from typing import Any, Dict, Union
class _EnvPath(type(Path()), Path): # pylint: disable=E0241
"""A stub of Path with additional attribute."""
# store for the original value passed to EnvPath
original_value = None
class Env... | env_value = os.getenv(env_key)
if env_value is not None:
string = string.replace(full_match, env_value)
except IndexError:
return string
# convert value to Path and return original value
p = _EnvPath(os.path.expanduser(string))
| p.original_value = value
return p
|
liquidkarma/pyneat | examples/xor/xor_neat.py | Python | gpl-2.0 | 1,835 | 0.016894 | #!/usr/bin/python
"""
pyNEAT
Copyright (C) 2007-2008 Brian Greer
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program... | ')
self.inputs = [[1.0, 0.0, 0.0], [1.0, 0.0, 1.0], [1.0, 1.0, 0.0], [1.0, 1.0, 1.0]]
self.targets = [0.0, 1.0, 1.0, 0 | .0]
def evaluate(self, network):
outputs = network.activate(inputs=self.inputs)
errorSum = 0
winner = True
for i in range(len(self.targets)):
target = self.targets[i]
output = outputs[i][0]
errorSum += math.fabs(output - target)
if (target > 0.5 and o... |
snapcore/snapcraft | tests/unit/build_providers/test_base_provider.py | Python | gpl-3.0 | 25,876 | 0.000966 | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2018-2020 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in ... | ]
),
call(["chown", "root:root", "/etc/apt/sources.list"]),
call(["chmod", "0644", "/etc/apt/sources.list"]),
call(
[
"mv",
"/var/tmp/L2V0Yy9hcHQvc291cm... | 2Vz",
"/etc/apt/sources.list.d/default.sources",
]
),
call(
[
"chown",
"root:root",
"/etc/apt/sources.list.d/default.sou... |
Mariaanisimova/pythonintask | INBa/2015/Sarocvashin_M/task_8_23.py | Python | apache-2.0 | 1,816 | 0.02439 | #Задача 8. Вариант 23.
#1-50. Доработайте игру "Анаграммы" (см. М.Доусон Программируем на Python. Гл.4) так, чтобы к каждому слову полагалась подсказка. Игрок должен получать право на подсказку в том случае, если у него нет никаких предположений. Разработайте систему начисления очков, по которой бы игроки, отгадавшие с... | али больше тех, кто запросил подсказку.#Чинкиров Валентин Владимирович
#20.05.2016
#Сароквашин Максим
import random
score = 10
words = ("Девятка ", "Шаха", "Семерка", "Москвич")
wor | d = random.choice(words)
letters = len(word)
print ("Я загадал некоторое слово связаное с машинами русского автопрома. В нём ", letters, " букв(/-ы)." )
ls = list(word)
random.shuffle(ls)
anagram = ls
i = 0
print(anagram)
answer = ""
while(answer!=word):
print("Назовёте слово сразу?(да/нет)")
answer = str(input())
i... |
pedesen/pyligadb | pyligadb.py | Python | mit | 11,013 | 0.003632 | #!/usr/bin/env python
"""
The pyligadb module is a small python wrapper for the OpenLigaDB webservice.
The pyligadb module has been released as open source under the MIT License.
Copyright (c) 2014 Patrick Dehn
Due to suds, the wrapper is very thin, but the docstrings may be helpful.
Most of the methods of pyligadb ... | etMatchdataByGroupLeagueSaison(groupOrderID,
leagueShortcut, leagueSaison)[0]
def getMatchdataByGroupLeagueSaisonJSON(self, groupOrderID, leagueShortcut,
leagueSaison):
"""
@param groupOrderID: The ID of a specific group.
Use i.e. getCurrentGroupOrderID() to obtain a... | Shortcut for a specific league.
Use getAvailLeagues() to get all shortcuts.
@param leagueSaison: A specific season (i.e. the date 2011 as integer).
@return: A JSON-Object containing detailed information about the
specified group/round.
"""
return |
dimagi/commcare-hq | corehq/form_processor/migrations/0020_rename_index_relationship.py | Python | bsd-3-clause | 352 | 0 | from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('form_processor', '0019_allow_closed_by_null'),
]
operations = [
migrations.RenameField(
| model_name='commcarecaseindexsql',
ol | d_name='relationship',
new_name='relationship_id',
),
]
|
Kagami/shitsu | shitsu/modules/animecal.py | Python | gpl-3.0 | 3,252 | 0.001538 | ##################################################
# shitsu - tiny and flexible xmpp bot framework
# Copyright (C) 2008-2012 Kagami Hiiragi <[email protected]>
#
# 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 So... | _list.append("%s (%s)" % (anime, ep))
line = "%s <span style='font-style: italic;'>(%s)</span>" % (
anime, ep)
if not day:
(h, m) = re.search("at (\d{2}):(\d{2})", ep).groups()
| start_time = now.replace(hour=int(h), minute=int(m))
delta = (now - start_time).seconds / 60
if delta > 0 and delta < 30:
line = "<span style='font-weight: bold;'>%s</span>" % line
anime_list_xhtml.append(line)
if len(anime_list) == 1:
... |
acerlawson/my-shadowsocks-manage | ssexe.py | Python | mit | 3,352 | 0.062649 | #!/usr/bin/env python
__author__='acerlawson'
__email_ | _='[email protected]'
import sslib
import os
import time
from datetime import datetime,timedelta
import commands
import json
import ssmail
def TurnOn(usrd):
#send TurnOnMsg mail to the usrd
ssmail.SendMail(usrd,ssmail.TurnOnMsg(usrd))
def TurnOff(usrd):
#send TurnOffMsg mail to the usrd
ssmail.SendMail(usrd,... | Routine check')
#Read the usrlist
usrlist=sslib.GetUsrList()
#Get now time to check
nowdate=sslib.nowdate()
for usrname in usrlist:
#change 'dict' to 'MyUsr'
usr = sslib.MyUsr(usrlist[usrname])
#Check the usr
Result = usr.check()
print Result
if Result == 'turnon':
#Write the result in history
... |
AdaHeads/Hosted-Telephone-Reception-System | use-cases/.patterns/callee_phone_rings/test.py | Python | gpl-3.0 | 56 | 0.071429 | self.Step (Message = "Callee phone rings.")
| ||
nkgilley/home-assistant | homeassistant/components/mycroft/notify.py | Python | apache-2.0 | 908 | 0 | """Mycroft AI notification platform."""
import logging
from mycroftapi import MycroftAPI
from homeassistant.components.notify import BaseNotificationService
_LOGGER = logging.getLogger(__name__)
def get_service(hass, config, discovery_info=None):
"""Get the Mycroft notification service."""
return MycroftNo... | on Service."""
def __init__(self, mycroft_ip):
"""Initialize the servic | e."""
self.mycroft_ip = mycroft_ip
def send_message(self, message="", **kwargs):
"""Send a message mycroft to speak on instance."""
text = message
mycroft = MycroftAPI(self.mycroft_ip)
if mycroft is not None:
mycroft.speak_text(text)
else:
_L... |
lhillber/qops | figure2.py | Python | mit | 5,048 | 0.002181 | import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import os
from figure3 import select, ket, exp
from matrix import ops
from measures import local_entropies_from_rhos, local_exp_vals_from_rhos
from mpl_toolkits.axes_grid1 import ImageGrid
from matplotlib import rc
rc("text", usetex=True)
fon... | ow",
axes_pad=0.1,
add_all=True,
cbar_mode="single",
cbar_location="right",
cbar_size="20%",
cbar_pad=0.05,
)
for col, (S, lett, cl) in enumerate(zip(Skey, letti, cli)):
N, S = map(int, S.split("."))
ax = gri... |
print("No sim!")
continue
S = sim["S"]
L = sim["L"]
IC = sim["IC"]
h5file = sim["h5file"]
if meas[0] == "e":
ticks = [-1, 1]
ticklabels = ["↑", "↓"]
... |
miketheprogrammer/dkxyz14 | hello-python/web.py | Python | mit | 296 | 0.013514 | import cherrypy
cherrypy.config.update({'server.socket_port': 9090})
cherrypy.config.update({'server.so | cket_host': '0.0.0.0'})
class Root(object):
@cherrypy.expose
def index(se | lf):
return "Hello World! From Python"
if __name__ == '__main__':
cherrypy.quickstart(Root(), '/') |
percolate/redset | redset/locks.py | Python | bsd-2-clause | 2,908 | 0 | """
Locks used to synchronize mutations on queues.
"""
import time
from redset.exceptions import LockTimeout
__all__ = (
'Lock',
)
# redis or redis-py truncates timestamps to the hundredth
REDIS_TIME_PRECISION = 0.01
class Lock(object):
"""
Context manager that implements a distributed lock with red... | r a recently acquired lock as expired
(float(current_value) + REDIS_TIME_PRECISION) < time.time() and
self.redis.getset(self.key, expires) == current_value
)
if has_expired:
retur | n
timeout -= self.poll_interval
time.sleep(self.poll_interval)
raise LockTimeout("Timeout while waiting for lock '%s'" % self.key)
def __exit__(self, exc_type, exc_value, traceback):
self.redis.delete(self.key)
|
puttarajubr/commcare-hq | custom/ilsgateway/tanzania/test/delivered.py | Python | bsd-3-clause | 3,569 | 0.005043 | from corehq.apps.commtrack.models import StockState
from custom.ilsgateway.models import SupplyPointStatus, SupplyPointStatusValues, SupplyPointStatusTypes
from custom.ilsgateway.tanzania.reminders import DELIVERY_PARTIAL_CONFIRM, NOT_DELIVERED_CONFIRM, \
DELIVERY_CONFIRM_DISTRICT, DELIVERY_CONFIRM_CHILDREN
from cu... | s.filter(location_id=self.dis.get_id,
status_type="del_dist").order_by("-status_date")[0]
self.assertEqual(SupplyPointStatusValues.RECEIVED, sps.status_value)
self.assertEqual(SupplyPointStatusTypes.DELIVERY_DISTRICT, sps.status_type)
def test_deliver... | (self):
script = """
555 > sijapokea
555 < {0}
""".format(NOT_DELIVERED_CONFIRM)
self.run_script(script)
sps = SupplyPointStatus.objects.filter(location_id=self.dis.get_id,
status_type="del_dist").order_by("-status_date... |
Apreche/Presentoh | utils/jinja2/debug.py | Python | mit | 9,931 | 0.000302 | # -*- coding: utf-8 -*-
"""
jinja2.debug
~~~~~~~~~~~~
Implements the debug interface for Jinja. This module does some pretty
ugly stuff with the Python traceback system in order to achieve tracebacks
with correct line numbers, locals and contents.
:copyright: (c) 2010 by the Jinja Team.
:... | eno(tb.tb_lineno)
tb = fake_exc_info(exc_info[:2] + (tb,), template.filename,
lineno)[2]
frames.append(TracebackFrameProxy(tb))
tb = next
# if we don't have any exceptions in the frames left, we have to
# | reraise it unchanged.
# XXX: can we backup here? when could this happen?
if not frames:
raise exc_info[0], exc_info[1], exc_info[2]
traceback = ProcessedTraceback(exc_info[0], exc_info[1], frames)
if tb_set_next is not None:
traceback.chain_frames()
return traceback
def fake_exc... |
opendoor/django-comlink | comlink/tests/__init__.py | Python | agpl-3.0 | 25 | 0.04 | from list_tests import | * | |
zakandrewking/cobrapy | cobra/manipulation/modify.py | Python | lgpl-2.1 | 9,924 | 0 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from ast import NodeTransformer
from itertools import chain
from six import iteritems
from warnings import warn
from cobra.core import Gene, Metabolite, Reaction
from cobra.core.gene import ast2str
from cobra.manipulation.delete import get_compiled_gene... | obra_model.genes._dict.pop(gene.id) # ugh
gene.id = new_name
cobra_model.genes[gene_index] = gene
elif not old_gene_present and new_gene_present:
pass
else: # not old gene_p | resent and not new_gene_present
# the new gene's _model will be set by repair
cobra_model.genes.append(Gene(new_name))
cobra_model.repair()
class Renamer(NodeTransformer):
def visit_Name(self, node):
node.id = rename_dict.get(node.id, node.id)
return node... |
MathieuDuponchelle/meson | mesonbuild/mesonlib.py | Python | apache-2.0 | 42,764 | 0.003648 | # Copyright 2012-2015 The Meson development team
# 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 agree... | arn if the locale is not UTF-8. This can cause various unfixable issues
# such as os.stat not being able to decode filenames with unicode in them.
# There is no way to reset both the preferred encoding and the filesystem
# encoding, so we can just warn about it.
e = locale.getpreferredencoding()
if ... | ows():
if not isinstance(direntry_array, list):
direntry_array = [direntry_array]
for de in direntry_array:
if is_ascii_string(de):
continue
mlog.warning('''You are using {!r} which is not a Unicode-compatible '
locale but you are trying to access a fi... |
insertnamehere1/maraschino | mobile.py | Python | mit | 32,117 | 0.008562 | # -*- coding: utf-8 -*-
"""Ressources to use Maraschino on mobile devices"""
import jsonrpclib
from flask import render_template
from maraschino import app, logger
from maraschino.tools import *
from maraschino.noneditable import *
global sabnzbd_history_slots
sabnzbd_history_slots = None
@app.route('/mobile/')
@... | ile=True)
return render_template('mobile/xbmc/recent_albums.html',
recently_added_albums=recently_added_albums[0],
using_db=recently_added_albums[1],
)
@app.route('/mobile/xbmc/')
@requires_auth
def xbmc():
servers = XbmcServer.query.order_by(XbmcServer.position)
active_server = int(g... | e('/mobile/movie_library/')
@requires_auth
def movie_library():
try:
xbmc = jsonrpclib.Server(server_api_address())
sort = {'method': 'label', 'ignorearticle': True}
movies = xbmc.VideoLibrary.GetMovies(sort=sort, properties=['title', 'rating', 'year', 'thumbnail', 'tagline', 'playcount'])['... |
fjcaetano/pelican_admin | pelican_admin/modules.py | Python | bsd-3-clause | 757 | 0.002642 | __author__ = 'flaviocaetano'
from django.utils.translation import ugettext_lazy as _
from admin_tools.dashboar | d import modules
import psutil
class PelicanAdmin(modules.DashboardModule):
"""Dashboard module for Pelican service administration.
"""
title = 'Pelican Admin'
template = 'pelican_admin.html'
def __init__(self, *args, **kwargs):
super(PelicanAdmin, self).__init__(*args, **kwargs)
... | .pelican_status = True
break
except psutil.AccessDenied, e:
pass
def is_empty(self):
return False |
n-witt/EconstorCorpus | Han_the_Converter/processingPdfFiles/processingPdfFiles.py | Python | gpl-3.0 | 4,598 | 0.005437 | import time
import os
from pdfLib import PdfLib
import langdetect
from filter import Filter
import json
class ProcessWorker():
def __init__(self, filename, wd, od, logger, uq, fileExtension = u'.json'):
"""
wd -> working dir
od -> output dir
uq -> update queue
"""
... | me()
self.logger.info(u"Took {:.2f}s.".format(stop-start))
i += 1
'''
gets plaintext from file at path "self.filename", does some normalization
and saves it into "outfile".
'''
def __getPlaintext(self):
# extract plaintext from pdf
paper = PdfLib(self.wd + os.sep... | nning, "max")
# normalize text
f = Filter(asString=plaintext)
plaintext = f.substitutions() \
.oneCharPerLine() \
.normalizeCaracters() \
.lower() \
.uselessCharacters() \
.multipleDots() \
.listEnum() \
... |
alexland/levenshtein-in-cython | levpy/levenshtein.py | Python | mit | 791 | 0.025284 | #!/usr/local/bin/python3.4
# encoding: utf-8
import os
import sys
import string
import warnings
import numpy as NP
from functools import partial
warnings.filterwarnings('ignore')
def levenshtein_dist(w1, w2, LuT):
'''
returns: levenshtein distance as int
| pass in: two words as python strings;
this fn for the easy case in which word lengths are equal;
'''
lw1, lw2 = len(w1), len(w2)
if lw1 != lw2:
return 'the two words do not have equal length'
w1, w2 = w1.lower(), w2.lower()
t1 = NP.array([LuT[chr] for chr in w1])
t2 = NP.array( | [LuT[chr] for chr in w2])
tdiff = t2 - t1
return NP.where(tdiff==0, 0, 1).sum()
p_levenshtein_dist = partial(levenshtein_dist,
LuT = {k:v for v, k in enumerate(string.ascii_lowercase)})
print(p_levenshtein_dist('pistol', 'piston'))
|
Titan-C/learn-dmft | examples/twosite/plot_dop_A.py | Python | gpl-3.0 | 1,345 | 0 | # -*- coding: utf-8 -*-
"""
================================================
Following the Metal to Mott insulator Transition
================================================
Sequence of plots showing the transfer of spectral weight for a Hubbard
Model in the Bethe Lattice as the local dopping is increased.
"""
# Cod... | , n in zip(axes, dop):
ind = np.abs(res[:, 0] - n).argmin()
sim = res[ind, 1]
w = sim.omega
s = sim.GF[r'$\Sigma$']
ra = w + sim.mu - s
rho = dos.bethe_lattice(ra, sim.t)
ax.plot(w, rho,
label='n={:.2f}'.format(sim.ocupations().sum()))
ax | .set_xlim([-6, 6])
ax.set_ylim([0, 0.36])
ax.set_yticks([])
ax.set_ylabel('n={:.2f}'.format(sim.ocupations().sum()))
ax.legend(loc=0, handlelength=0)
|
antoinecarme/pyaf | tests/model_control/detailed/transf_BoxCox/model_control_one_enabled_BoxCox_LinearTrend_BestCycle_MLP.py | Python | bsd-3-clause | 151 | 0.046358 | import tests.model_control.test_ozone_custom_models_enabled as testmod
testmod.build_m | odel( ['BoxCox'] , ['LinearTrend'] , ['BestCycle'] , ['MLP'] | ); |
flexi-framework/hopr | tools/blockgridgenerator/main.py | Python | gpl-3.0 | 603 | 0.023217 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys,os
from PyQt5 import QtCore, QtGui, QtWidgets, uic
from model import MainModel
from view import MainView
class App(QtWidgets.QApplication):
def __init__(self, scriptpath, sys_a | rgv):
super(App, self).__init__(sys_argv)
self.model = MainModel()
self.main_view = MainView(self.model, scriptpath)
self.main_view.show() #Maximized()
self.model.gridChanged.emit()
|
if __name__ == '__main__':
scriptpath = os.path.dirname(os.path.abspath(sys.argv[0]))
app = App(scriptpath, sys.argv)
sys.exit(app.exec_())
|
geggo/pyface | pyface/wizard/i_wizard.py | Python | bsd-3-clause | 5,057 | 0.001186 | #------------------------------------------------------------------------------
# Copyright (c) 2005, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in enthought/LICENSE.txt and may be redistributed only
# under the conditions describe... | _show_page(self, page):
""" Show the specified page. """
# Set the current page in the controller.
#
# fixme: Shouldn't this interface be reversed? Maybe calling
# 'next_page' on the controller should cause it to set its own current
# page?
self.controller.curre... | date(self):
""" Enables/disables buttons depending on the state of the wizard. """
pass
###########################################################################
# Private interface.
###########################################################################
def _initialize_controll... |
CompMusic/essentia | src/examples/python/show_algo_dependencies.py | Python | agpl-3.0 | 2,198 | 0.00455 | #!/usr/bin/env python
# Copyright (C) 2006-2013 Music Technology Group - Universitat Pompeu Fabra
#
# This file is part of Essentia
#
# Essentia is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation (FSF), e... | ed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the Affero GNU General Public License
# version 3 along with this ... | subprocess
def find_dependencies(mode, algo):
code = """
import essentia.%s as es
import essentia
essentia.log.infoActive = True
essentia.log.debugLevels += essentia.EFactory
loader = es.%s()
""" % (mode, algo)
proc = subprocess.Popen(["python", "-c", code], stdout=subprocess.PIPE)
stdout = proc.commun... |
krishauser/Klampt | Python/klampt/math/symbolic_klampt.py | Python | bsd-3-clause | 38,043 | 0.016797 | """ Defines many functions of Klampt as symbolic Functions.
Currently implemented:
- so3, se3
- ik
- some collide functions
- RobotModel kinematics
TODO:
- RobotModel dynamics
- Trajectories
- Geometries
- support polygons
"""
from .symbolic import *
from .symbolic_linalg import *
from .. import *
from . import so3... | ule:
- identity, matrix, inv, mul, apply, rotation, err | or, distance
- from_matrix, from_rpy, rpy, from_quaternion, quaternion, from_rotation_vector, rotation_vector
- eq_constraint: equality constraint necessary for SO3 variables
- quaternion_constraint: equality constraint necessary for quaternion variables
Completeness table
================= =====... |
kumar303/addons-server | conftest.py | Python | bsd-3-clause | 7,121 | 0 | """
pytest hooks and fixtures used for our unittests.
Please note that there should not be any Django/Olympia related imports
on module-level, they should instead be added to hooks or fixtures directly.
"""
import os
import uuid
import warnings
import pytest
import responses
import six
@pytest.fixture(autouse=True)... | cks()
yield
stop_es_mocks()
@pytest.fixture(autouse=True)
def start_responses_mocking(request):
"""Enable ``responses`` this enforcing us to explicitly mark tests
that require internet usage.
"""
marker = request.node.get_closest_marker | ('allow_external_http_requests')
if not marker:
responses.start()
yield
try:
if not marker:
responses.stop()
responses.reset()
except RuntimeError:
# responses patcher was already uninstalled
pass
@pytest.fixture(autouse=True)
def mock_basket(... |
thisisshi/cloud-custodian | tests/test_sns.py | Python | apache-2.0 | 26,225 | 0.000801 | # Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
import json
from .common import BaseTest, functional
from c7n.resources.aws import shape_validate
from c7n.utils import yaml_load
class TestSNS(BaseTest):
@functional
def test_sns_remove_matched(self):
session_factory = s... | }
],
},
session_factory=session_factory,
)
resources = p.run()
self.assertEqual(len(resources), 1)
data = json.loads(
client.get_topic_attributes(TopicArn=resources[0]["TopicArn"])[
"Attrib | utes"
][
"Policy"
]
)
self.assertTrue(
"ReplaceWithMe" in [s["Sid"] for s in data.get("Statement", ())]
)
@functional
def test_sns_account_id_template(self):
session_factory = self.replay_flight_data("test_sns_account_id_templa... |
domino14/Webolith | scripts/gen_firewall.py | Python | gpl-3.0 | 2,398 | 0.001251 | template = """# Generated on {{dt}}
*filter
:INPUT DROP
:FORWARD ACCEPT
:OUTPUT ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -i eth0 -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -i eth1 -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
{{#rule}}... | ver in the security group in question
# add its private ip to the firewall
if server['name'] in securityGroups[subrule[0]]:
port = subrule[1]
context['rule']['tcprule'].append(
{'source': server['networks']['v4'][0]['ip_addr... | )
f.write(res)
f.close()
return res
|
pferreir/indico-backup | indico/MaKaC/plugins/Collaboration/Vidyo/pages.py | Python | gpl-3.0 | 11,041 | 0.003713 | # -*- coding: utf-8 -*-
##
##
## This file is part of Indico.
## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN).
##
## Indico 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... | tPin()]
else:
| pinSection['lines'] = [_('This Vidyo room is protected by a PIN')]
sections.append(pinSection)
sections.append({
"title": _('Moderator'),
'lines': [booking.getOwnerObject().getStraightFullName()],
})
if booking.getBookingParamByName("displayPhoneNumbers")... |
futurice/futurice-ldap-user-manager | fum/servers/views.py | Python | bsd-3-clause | 3,137 | 0.009882 | from django.shortcuts import redirect
from django.views.generic import TemplateView
from d | jango.views.generic import ListView, DetailView
from django.views.generic.edit import FormView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.core.urlresolvers import reverse_lazy
from django.http import HttpResponse
from fum.models import Users, Groups, Servers
from fum.util impo... | rversForm
import json
NAME = 'servers'
MODEL = Servers
class ListView(ListView):
model = MODEL
template_name = '%s/%s_list.html'%(NAME,NAME)
# Order by case-insensitive name (because Postgre)
def get_queryset(self):
return self.model.objects.all().extra(select={'lower_name': 'lower(name)'}).... |
skodapetr/lbvs-environment | methods/ecfc/ecfc2_tanimoto.py | Python | mit | 1,365 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import rdkit
from rdkit.Chem import AllChem
from rdkit import DataStructs
__license__ = "X11"
METADATA = {
"id": "method_rdkit_ecfc2_tanimoto",
"representation": "ecfc2",
"similarity": "tanimoto"
}
def _compute_fingerprint(molecule):
return AllChem.GetM... | t(molecule, 1)
def _compute_similarity(left, right):
return DataStructs.TanimotoSimilarity(left, right)
def create_model(train_ligands, train_decoys):
model = []
for molecule in train_ligands:
model.append({
"name": molecule.GetProp("_Name"),
"fingerprint": _compute_finge... | rint = _compute_fingerprint(molecule)
similarities = [_compute_similarity(fingerprint, item["fingerprint"])
for item in model]
max_score = max(similarities)
index_of_max_score = similarities.index(max_score)
closest_molecule = model[index_of_max_score]
return {
"value": m... |
berinhard/py-notify | notify/utils.py | Python | lgpl-2.1 | 11,952 | 0.011577 | # -*- coding: utf-8 -*-
#--------------------------------------------------------------------#
# This file is part of Py-notify. #
# #
# Copyright (C) 2006, 2007, 2008 Paul Pogonyshev. #
# ... | object: the object for which a non-implemented method is called.
@type object: C{object}
@param function_name: name of the unimplemented function or method (inferred
automatically for non-extension functions).
@type function_name: ... | ception
except Exception:
try:
traceback = sys.exc_info () [2]
function_name = traceback.tb_frame.f_back.f_code.co_name
except Exception:
# We can do nothing, ignore.
pass
if function_name is not None:
funct... |
rsdk/labaccess | laborzugang/settings.py | Python | bsd-2-clause | 2,131 | 0.000469 | """
Django settings for laborzugang project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...... | middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'laborzugang.urls | '
WSGI_APPLICATION = 'laborzugang.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangopro... |
google/ml-fairness-gym | core_test.py | Python | apache-2.0 | 4,658 | 0.005796 | # coding=utf-8
# Copyright 2022 The ML Fairness Gym Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | eturn x
self.assertIn('my_function',
core.to_json({'params': {
'function': my_function
}}))
def test_to_json_with_indent(self):
self.assertNotIn('\n', core.to_json({'a': 5, 'b': [1, 2, 3]}))
self.assertIn('\n', core.to_json({'a': 5, 'b': [1, 2, 3... | me__ == '__main__':
absltest.main()
|
stumped2/school | CS480/milestone3/myreglexer.py | Python | apache-2.0 | 2,134 | 0.009372 | #!/usr/bin/env python
import collections
import sys
import re
def tokenize(stream):
Token = collections.namedtuple('Token', ['typ', 'value', 'line', 'column'])
tokenSpec = [
('REAL', r'[-]?(?=\d*[.eE])(?=\.?\d)\d*\.?\d*(?:[eE][+-]?\d+)?'),
('I | NTEGER', r'[-]?[0-9]+'),
('MINUS', r'\-'),
('STRING', r'\"(\\.|[^"])*\"'),
('BINOP', r'[\+\^\*/%]|([<>!]=?|=)|or|and'),
('UNOP', r'not|sin|cos|tan'),
('ASSIGN', r':='),
('ST | ATEMENT', r'stdout|while|if|let'),
('TYPES', r'bool|int|float|string'),
('BOOL', r'true|false'),
('NAME', r'[a-zA-Z_]+?[a-zA-Z0-9_]+|[a-zA-Z]'),
('LBRACE', r'\['),
('RBRACE', r'\]'),
('NEWLINE', r'\n'),
('SKIP', r'[ \t]')... |
googleapis/python-container | samples/generated_samples/container_v1_generated_cluster_manager_set_labels_async.py | Python | apache-2.0 | 1,476 | 0.000678 | # -*- coding: utf-8 -*-
# Copyright 2022 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 a | t
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governin... | trative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-cloud-container
# [START container_v1_generated_ClusterManager_SetLabels_async]
from google.cloud import container_v1
asy... |
TeXitoi/navitia | source/sql/alembic/versions/2d86200bcb93_co2_emission_column_added.py | Python | agpl-3.0 | 527 | 0.00759 | """co2_emission column added
Revision ID: 2d86200bcb93
Revises | : 82749d34a18
Create Date: 2014-12-30 17:23:39.654559
"""
# revision identifiers, used by Alembic.
revision = '2d86200bcb93'
down_revision = '82749d34a18'
from alembic import op
import sqlalchemy as sa
import geoalchemy2 as ga
def upgrade():
op.add_column('physical_mode', sa.Column('co2_emission', sa.FLOAT(), ... | al_mode', 'co2_emission', schema='navitia')
|
anthill-services/anthill-store | anthill/store/server.py | Python | mit | 4,175 | 0.00024 |
from anthill.common.options import options
from . import handler as h
from . import options as _opts
from anthill.common import server, database, access, keyvalue
from anthill.common.social.steam import SteamAPI
from anthill.common.social.xsolla import XsollaAPI
from anthill.common.social.mailru import MailRuAPI
f... | pp Purchasing, with server validation",
"icon": "shopping-cart"
}
def get_handlers(self):
return [
(r"/store/(.*)", h.StoreHandler),
(r"/order/new", h.NewOrderHandler),
(r"/orders", h.OrdersHandler),
(r"/order/(.*)", h.OrderHandler),
... | h.WebHookHandler),
(r"/front/xsolla", h.XsollaFrontHandler),
]
if __name__ == "__main__":
stt = server.init()
access.AccessToken.init([access.public()])
server.start(StoreServer)
|
meymarce/overlord | overlord/templatetags/view_tag.py | Python | agpl-3.0 | 2,130 | 0.002817 | from django.template import Library, Node, TemplateSyntaxError, Variable
from django.conf import settings
from django.core import urlresolvers
import hashlib
import re
register = Library()
class ViewNode(Node):
def __init__(self, parser, token):
self.args = []
self.kwargs = {}
tokens = ... | ef render(self, context):
print('render view tag...')
if 'request' not in context:
return ""
request = context['request']
# get the url for the view
url = Variable(self.url_or_view).resolve(context)
if not settings.USE_AJAX_REQUESTS:
# do not load... | an ajax request
#request.is_ajax = True # not needed since the jQuery.get() is implying this
urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF)
resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
# get the view function
view, args, kwargs = res... |
Perlence/porcupy | tests/test_assign.py | Python | bsd-3-clause | 12,924 | 0.003018 | import pytest
from porcupy.compiler import compile as compile_
def test_consts():
assert compile_('X = 4') == ''
assert compile_('X = 4; y = X') == 'p1z 4'
assert compile_('X = 4; Y = X; z = Y') == 'p1z 4'
with pytest.raises(ValueError) as exc_info:
compile_('X = 4; X = 5')
assert 'cann... | y = -x') == 'p1z 4 p2z p1z*-1'
assert compile_('x = ~5') == 'p1z -6'
assert compile_('x = ~-6') == 'p1z | 5'
assert compile_('x = ~True') == 'p1z -2'
assert compile_('x = ~False') == 'p1z -1'
assert compile_('x = 5; y = ~x') == 'p1z 5 p3z p1z*-1 p2z p3z-1'
assert compile_('x = not 4') == 'p1z 0'
assert compile_('x = not 0') == 'p1z 1'
assert compile_('x = not True') == 'p1z 0'
assert compile_(... |
Widdershin/CodeEval | challenges/001-fizzbuzz.py | Python | mit | 379 | 0.047493 | import sys
file_name = sys.argv[1]
with open(file_name) as open_file:
for line in open_file. | readlines():
a, b, n = map(int, line | .split())
output = ""
for i in xrange(1, n + 1):
out = ""
spacing = " "
if i == 1:
spacing = ""
if i % a == 0:
out += "F"
if i % b == 0:
out += "B"
output += spacing + (out or str(i))
print output
|
pbmanis/acq4 | acq4/devices/MockClamp/devTemplate.py | Python | mit | 8,324 | 0.003123 | # -*- coding: utf-8 -*-
from __future__ import print_function
# Form implementation generated from reading ui file './acq4/devices/MockClamp/devTemplate.ui'
#
# Created: Thu May 29 10:20:36 2014
# by: PyQt4 UI code generator 4.9.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore,... | setObjectName(_fromUtf8("groupBox_2"))
self.gridLayout_3 = QtGui.QGridLayout(self.groupBox_2)
self.gridLayout_3.setObjectName(_fromUtf8("gridLayout_3"))
self.horizontalLayout = | QtGui.QHBoxLayout()
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.vcModeRadio = QtGui.QRadioButton(self.groupBox_2)
self.vcModeRadio.setObjectName(_fromUtf8("vcModeRadio"))
self.horizontalLayout.addWidget(self.vcModeRadio)
self.i0ModeRadio = QtGui.QRadi... |
google/it-cert-automation | Course2/areas.py | Python | apache-2.0 | 771 | 0.003891 | #!/usr/bin/env python3
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRAN | TIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import math
def triangle(base, height):
return base*height/2
def rectangle(base, height):
return base*height
def circle(radius):
return math.... |
cwalk/CapacitiveTouchLamp | setup.py | Python | mit | 1,311 | 0.026697 | try:
# Try using ez_setup to install setuptools if not already installed.
from ez_setup import use_setuptools
use_setuptools()
except ImportError:
# Ignore import error and assume Python 3 which already has setuptools.
pass
from setuptools import setup, find_packages
classifiers = ['Development St... | Developers',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Topic :: Software Development',
'Topic :: System :: Hardware']
setup(name = 'Adafruit_MPR121',
version = '1.1.2',
author ... | = '[email protected]',
description = 'Library for MPR121 capacitive touch sensor.',
license = 'MIT',
classifiers = classifiers,
url = 'https://github.com/adafruit/Adafruit_Python_MPR121/',
dependency_links = ['https://github.com/adafruit/Adafrui... |
ShuffleBox/django-rcsfield | rcs/wiki/admin.py | Python | bsd-3-clause | 152 | 0.006579 | fro | m django.contrib import admin
from rcs.wiki.m | odels import WikiPage, WikiAttachment
admin.site.register(WikiPage)
admin.site.register(WikiAttachment) |
hrishioa/Aviato | kartograph/kartograph/geometry/view.py | Python | gpl-2.0 | 3,541 | 0.001977 |
from shapely.geometry import Polygon, MultiPolygon, LineString, MultiLineString, MultiPoint, Point
from kartograph.errors import KartographError
# # View
# Simple 2D coordinate transformation.
class View(object):
"""
translates a point to a view
"""
def __init__(self, bbox=None, width=None, height=... | += self.project_linear_ring(interior)
return [Polygon(ext[0], pts_int)]
elif len(ext) == 0:
return []
else:
raise KartographError('unhandled case: exterior is split into multiple rings')
def project_linear_ring(self, ring):
| points = []
for pt in ring.coords:
x, y = self.project(pt)
points.append((x, y))
return [points]
def __str__(self):
return 'View(w=%f, h=%f, pad=%f, scale=%f, bbox=%s)' % (self.width, self.height, self.padding, self.scale, self.bbox)
|
ralphm/wokkel | doc/conf.py | Python | mit | 7,874 | 0.007112 | # -*- coding: utf-8 -*-
#
# Wokkel documentation build configuration file, created by
# sphinx-quickstart on Mon May 7 11:15:38 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
# autogenerated file.
#
# All ... | t '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypan | ts = True
# Custom sidebar templates, maps document names to template names.
html_sidebars = {
'index': ['localtoc.html', 'indexsidebar.html', 'searchbox.html']
}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module in... |
ojii/django-filer | filer/admin/fileadmin.py | Python | mit | 4,673 | 0.00856 | from django.core.urlresolvers import reverse
from django.contrib.admin.util import unquote
from django.utils.translation import ugettext as _
from django.http import HttpResponseRedirect
from django import forms
from filer.admin.permissions import PrimitivePermissionAwareModelAdmin
from filer.models import File
# for... | est, context=context, add=False, change=False, form_url=form_url, obj=obj)
def delete_view(self, request, object_id, extra_context=None):
'''
Overrides the default to enable redirecting to the directory view after
deletion of a image.
we need to fetch the object and fin... | he parent is
before super, because super will delete the object and make it impossible
to find out the parent folder to redirect to.
'''
parent_folder = None
try:
obj = self.queryset(request).get(pk=unquote(object_id))
parent_folder = obj.folder
ex... |
ANR-COMPASS/shesha | data/par/par4tests/test_sh_base.py | Python | gpl-3.0 | 2,260 | 0 | import shesha.config as conf
simul_name = "bench_scao_sh_16x16_8pix"
# loop
p_loop = conf.Param_loop()
p_loop.set_niter(100)
p_loop.set_ittime(0.002) # =1/500
# geom
p_geom = conf.Param_geom()
p_geom.set_zenithangle(0.)
# tel
p_tel = conf.Param_tel()
p_tel.set_diam(4.0)
p_tel.set_cobs(0.1 | 2)
# atmos
p_atmos = conf.Param_atmos()
p_atmos.set_r0(0.16)
p_atmos.set_nscreens(1)
p_atmos.set_frac([1.0])
p_atmos.set_alt([0.0])
p_atmos.set_windspeed([20.0])
p_atmos.set_winddir([45.])
p_atmos.set_L0([1.e5])
# target
p_target = conf.Param_target()
p_targets = [p_target]
# p_target.set_ntargets(1)
p_target.set_x... | target.set_ypos(0.)
p_target.set_Lambda(1.65)
p_target.set_mag(10.)
# wfs
p_wfs0 = conf.Param_wfs()
p_wfss = [p_wfs0]
p_wfs0.set_type("sh")
p_wfs0.set_nxsub(8)
p_wfs0.set_npix(8)
p_wfs0.set_pixsize(0.3)
p_wfs0.set_fracsub(0.8)
p_wfs0.set_xpos(0.)
p_wfs0.set_ypos(0.)
p_wfs0.set_Lambda(0.5)
p_wfs0.set_gsmag(8.)
p_wfs0.... |
luotao1/Paddle | python/paddle/jit/__init__.py | Python | apache-2.0 | 1,478 | 0 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
# Copyright (c) 2021 NVIDIA Corporation. 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://ww... | ns and
# limitations under the License.
from __future__ import print_function
from ..fluid.dygraph.jit import save # noqa: F401
from ..fluid.dygraph.jit import load # noqa: F401
from ..fluid.dygraph.jit import TracedLayer # noqa: F401
from ..fluid.dygraph.jit import set_code_level # noqa: F401
from ..fluid.dygrap... | uid.dygraph import ProgramTranslator # noqa: F401
from ..fluid.dygraph.io import TranslatedLayer # noqa: F401
from . import dy2static # noqa: F401
__all__ = [ # noqa
'save',
'load',
'TracedLayer',
'to_static',
'ProgramTranslator',
'TranslatedLayer',
'set_code_level',
'set_verbosity... |
tensorflow/tensorflow | tensorflow/python/keras/layers/rnn_cell_wrapper_v2_test.py | Python | apache-2.0 | 9,770 | 0.002764 | # Copyright 2019 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... | er()])
res_g, res_g_res, res_m_new, res_m_new_res = self.evaluate(
[g, g_res, m_new, m_new_res])
# Residual connections
self.assertAllClose(res_g_res, res_g + [1., 1., 1.])
| # States are left untouched
self.assertAllClose(res_m_new, res_m_new_res)
def testDeviceWrapper(self):
wrapper_type = rnn_cell_wrapper_v2.DeviceWrapper
x = array_ops.zeros([1, 3])
m = array_ops.zeros([1, 3])
cell = rnn_cell_impl.GRUCell(3)
wrapped_cell = wrapper_type(cell, "/cpu:0")
chi... |
qiyeboy/SpiderBook | ch01/1.4.1.py | Python | mit | 3,126 | 0.001764 | #coding:utf-8
'''
第一种方式:使用os模块中的fork方式实现多进程
import os
if __name__ == '__main__':
print 'current Process (%s) start ...'%(os.getpid())
pid = os.fork()
if pid < 0:
print 'error in fork'
elif pid == 0:
print 'I am child process(%s) and my parent process is (%s)',(os.getpid(),os.getppid())
... | url_3']))
proc_writer2 = Process(target=proc_write, args=(q,['url_4','url_5','url_6']))
proc_reader = Process(target=proc_read, args=(q,))
# 启动子进程proc_writer,写入:
proc_writer1.start()
proc_writer2.start()
# 启动子进程proc_reader,读取:
proc_reader.start()
# 等待proc_writer结束:
proc_writer1.join(... |
import time,os
def proc_send(pipe,urls):
for url in urls:
print "Process(%s) send: %s" %(os.getpid(),url)
pipe.send(url)
time.sleep(random.random())
def proc_recv(pipe):
while True:
print "Process(%s) rev:%s" %(os.getpid(),pipe.recv())
time.sleep(random.random())
'''
... |
mushkevych/scheduler | tests/test_state_machine_recomputing.py | Python | bsd-3-clause | 8,122 | 0.005541 | __author__ = 'Bohdan Mushkevych'
import unittest
try:
import mock
except ImportError:
from unittest import mock
from settings import enable_test_mode
enable_test_mode()
from constants import PROCESS_SITE_HOURLY
from synergy.db.dao.job_dao import JobDao
from synergy.db.dao.unit_of_work_dao import UnitOfWorkDa... | ESS state"""
self.time_table_mocked.is_job_record_finalizable = mock.MagicMock(return_value=True)
returns = [
create_unit_of_work(PROCESS_SITE_HOURLY, 1, 1, TEST_ACTUAL_TIMEPERIOD, unit_of_work.STATE_REQUESTED),
create_unit_of_work(PROCESS_SITE_HOURLY, 1, 1, TEST_ACTUAL_TIMEPERIO... | ffect=side_effects)
self.ds_mocked.highest_primary_key = mock.MagicMock(return_value=1)
self.ds_mocked.lowest_primary_key = mock.MagicMock(return_value=0)
self.sm_real.insert_and_publish_uow = then_return_duplicate_uow
job_record = get_job_record(job.STATE_IN_PROGRESS, TEST_PRESET_TIM... |
toly/pyrecense | recense.py | Python | mit | 3,217 | 0.001554 | #!/usr/bin/env python
# coding: utf-8
__author__ = 'toly'
import re
import os
import sys
import argparse
from collections import Counter
BAD_FUNCTIONS = ['__init__', '__unicode__', 'setUp', 'tearDown']
FUNCTION_DEFINE_REGEXP = re.compile(r'def (\w+)\(')
FUNCTION_CALL_REGEXP = re.compile(r'(\w+)\(')
def main():
... | thon_files(args.project_directory)
for file_index, filename in enume | rate(project_files):
for line in get_file_lines(filename):
# getting functions, classes and their calls
definitions = [function_name for function_name in FUNCTION_DEFINE_REGEXP.findall(line)]
if definitions:
has_bad_functions = False
for bad_f... |
kevincobain2000/jProcessing | src/jNlp/jCabocha.py | Python | bsd-2-clause | 1,326 | 0.017391 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import sys, subprocess, os
from subprocess import call
from tempfile import NamedTemporaryFile
def formdamage(sent):
rectify = []
for ch in sent:
try: rectify.append(ch.encode('utf-8'))
except... | ()[0]
os.unlink(temp.name)
return unicode(output, 'utf-8')
def main():
pass
if __name__ == '__main__':
input_sentence = u'私が五年前にこの団体を仲間たちと結成したのは | マルコス疑惑などで日本のODA(政府開発援助)が問題になり、国まかせでなく、民間による国際協力が必要だと痛感したのが大きな理由です。'
print cabocha(input_sentence).encode('utf-8')
|
ratnania/pigasus | python/fem/color.py | Python | mit | 6,761 | 0.004141 | # -*- coding: UTF-8 -*-
#! /usr/bin/python
__author__="ARA"
__all__ = ['color_operator', 'color_field', 'color', 'manager',
'manager_operators', 'manager_fields']
__date__ ="$Mai 08, 2014 10:50:00 PM$"
from numpy import asarray
class myList:
def __init__(self):
self._list = []
self._c... | poisson
from pigasus.gallery.bilaplacian import bilaplacian
from caid.cad_geometry import square
geo = square(n=[3,3], p=[2,2])
PDE_1 = bilaplacian(geometry=geo)
PDE_2 = poisson(geometry=geo, V=PDE_1.V)
PDE_3 = poisson(geometry=geo, V=PDE_1.V)
PDE_4 = poisson(geometry=geo)
# print id(PD... | _2.V), PDE_2.V.id
# print "---"
# print PDE_1.operators
# print PDE_2.operators
S_1 = PDE_1.D2
S_2 = PDE_2.stiffness
S_3 = PDE_3.stiffness
S_4 = PDE_4.stiffness
green = color_operator()
red = color_operator()
red.append(S_1)
green.append(S_2)
green.append(S_3)
green... |
feureau/Small-Scripts | Blender/Blender config/2.91/scripts/addons/bricksculpt_v1-2-0/functions/common/images/pixel_effects_numba.py | Python | gpl-3.0 | 4,588 | 0.000654 | # Author: Christopher Gearhart
# System imports
from numba import jit, prange
import numpy as np
# Blender imports
# NONE!
# Module imports
# NONE!
@jit(nopython=True, parallel=True)
def resize_pixels(size, channels, old_pixels, old_size):
new_pixels = np.empty(size[0] * size[1] * channels)
for col in pran... | xel_dist[0] > 0 else -1
new_pixels = np.empty(len(old_pixels))
# for i in prange(width * height):
# x = i / height
# row = round((x % 1) * height)
# col = round(x - (x % 1))
for col in prange(width):
for row in prange(height):
pixel_number = width * row + col
... | 1):
for r in range(-pixel_dist[1], pixel_dist[1] + 1):
if not (0 < col + c < width and 0 < row + r < height):
continue
width_amt = abs(c) / pixel_dist[0]
height_amt = abs(r) / pixel_dist[1]
ratio = (... |
wwood/graftM | graftm/run.py | Python | gpl-3.0 | 42,090 | 0.00575 | #!/usr/bin/env python3
import os
import logging
import tempfile
import shutil
from graftm.sequence_search_results import SequenceSearchResult
from graftm.graftm_output_paths import GraftMFiles
from graftm.search_table import SearchTableWriter
from graftm.sequence_searcher import SequenceSearcher
from graftm.hmmsearch... | orator import Decorator
from graftm.external_program_suite import ExternalProgramSuite
from graftm.archive import Archive
from graftm.decoy_filter import DecoyFilter
from biom.util import biom_open
T=Timer()
class UnrecognisedSuffixError(Exception):
pass
class Run:
PIPELINE_ | AA = "P"
PIPELINE_NT = "D"
_MIN_VERBOSITY_FOR_ART = 3 # with 2 then, only errors are printed
PPLACER_TAXONOMIC_ASSIGNMENT = 'pplacer'
DIAMOND_TAXONOMIC_ASSIGNMENT = 'diamond'
MIN_ALIGNED_FILTER_FOR_NUCLEOTIDE_PACKAGES = 95
MIN_ALIGNED_FILTER_FOR_AMINO_ACID_PACKAGES = 3... |
idmillington/layout | tests/test_managers_box.py | Python | mit | 1,665 | 0.016817 | import unittest
from layout.datatypes import *
from layout.managers.box import *
class DummyElement(object):
def __init__(self, size):
self.size = size
def get_minimum_size(self, data):
return self.size
def render(self, rect, data):
self.rect = rect
class BoxLMTest(unittest.TestCas... | f.assertEqual(b.get_minimum_size(None), Point(6,5))
def test_margin_minimum_size(self):
b = BoxLM()
b.top = DummyElement(Point(4,2))
b.center = DummyElement(Point(3,4))
b.bottom = DummyElement(Point(5,1))
b.margin = 1
self.ass | ertEqual(b.get_minimum_size(None), Point(5,9))
def test_all_minimum_size(self):
b = BoxLM()
b.left = DummyElement(Point(2,5))
b.top = DummyElement(Point(4,2))
b.center = DummyElement(Point(3,4))
b.bottom = DummyElement(Point(5,1))
b.right = DummyElement(Point(2,4))
... |
tlienart/script2gle | s2gf.py | Python | mit | 5,785 | 0.051167 | from re import search, sub, match
from os.path import join
#
import s2gc
import s2gd
#
###########################
# LAMBDA FUNCTIONS ########
###########################
# match a certain expression at start of string
match_start = lambda expr,line: match(r'\s*(%s)[^a-zA-Z0-9]'%expr,line)
# ----------
# RECONSIDER
# ... | # strip ends (-[-stuff-]- extract stuff)
core = match(r'(\s*\[?)([^\[^\]]+)(\]?\s*)',s).group(2)
# replace ',' by space
left = sub(',',' ',core)
# ATTEMPT - if sequence
nc = left.count(':')
if nc==1: # 1:5
spl = match(r'(^[^:]+):([^:]+$)',left);
first,last = float(spl.group(1)), float(spl.group(2))
s... | :
cur+=1
seq.append(str(cur))
array = seq
elif nc==2:
spl = match(r'(^[^:]+):([^:]+):([^:]+$)',left)
first,step,last = float(spl.group(1)), float(spl.group(2)), float(spl.group(3))
seq,cur = [str(first)],first
while cur<=last-step:
cur+=step
seq.append(str(cur))
array = seq
... |
jacobandreas/nmn2 | extra/vqa/parse.py | Python | apache-2.0 | 4,979 | 0.002008 | #!/usr/bin/env python2
from collections import namedtuple
import itertools
import re
import sys
Node = namedtuple("Node", ["word", "tag", "parent", "rel", "path"])
BE_FORMS="is|are|was|were|has|have|had|does|do|did|be"
WH_RES = [
r"^what (\w+) (is|are)",
r"^what (is|are) the (\w+) of",
r"^what (\w+) of"... | r pred_comb in comb:
if len(pred_comb) == 1:
out.append("(%s %s)" % (wh, pred_comb[0]))
else:
out.append("(%s (and %s))" % (wh, " ".join(pred_comb)))
return out
def parse_all(self, stream):
queries = | []
query_lines = []
got_question = False
question = None
for line in stream:
sline = line.strip()
if sline == "" and not got_question:
got_question = True
question = query_lines[0].lower()
query_lines = []
... |
BryceBesler/ENEL453-Assembler | testCases/TestCasesRan/14-03-14--21-39/assembly.py | Python | mit | 11,254 | 0.019904 | '''
Opcode d(11:8) Operand d(7:0) Operation
0 8 bits representing a constant Load constant to Reg0
1 8 bits representing a constant Load constant to Reg1
2 d7 selects register Reg0 or Reg1 Load value of selected register to the... | gned bits
CONSTANT_MIN = 0; # Only using unsigned bits
ADDRESS_MAX = 255; # Largest address
ADDRESS_MIN = 0; # Can't go lower than zero
INSTRUCTION_LENGTH_DICT = {
'load' : 3,
'move' : 2,
'add' : 2,
'sub' : 2,
'sr' : 1,
'sl' : 1,
'and' : 2,
'or' : 2,
... | : 2,
'jal' : 2,
'jr' : 1,
'wri' : 2,
'str' : 2
};
# Helper functions
def doExit(error):
print "ERROR: {}".format(error);
print "Exiting..."
os.sys.exit(1);
def printInstructions():
print """Instruction Set:
load [Constant] [Reg0, Reg1] {load constant to re... |
pbfy0/visvis | core/baseWibjects.py | Python | bsd-3-clause | 5,953 | 0.014782 | # -*- coding: utf-8 -*-
# Copyright (C) 2012, Almar Klein
#
# Visvis is distributed under the terms of the (new) BSD License.
# The full license can be found in 'license.txt'.
""" Module baseWibjects
Defines the Box class and the DraggableBox class.
"""
import OpenGL.GL as gl
from visvis.core import Wibject
from v... | def edgeWidth():
""" Get/Set the edge width of the wibject.
"""
| def fget(self):
return self._edgeWidth
def fset(self, value):
self._edgeWidth = float(value)
return locals()
def _GetBgcolorToDraw(self):
""" Can be overloaded to indicate mouse over in buttons.
"""
return self._bgcolor
... |
MarouenMechtri/CNG-Manager | pyocni/backends/linkcng_backend.py | Python | apache-2.0 | 16,778 | 0.009298 | # Copyright 2013 Institut Mines-Telecom - Telecom SudParis
#
# 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 applicab... | ense, Version | 2.0
"""
""" Note: entity represent the linkcng category.
-Attributes of this category are:
- name
- cngSRC //Path of the cng source category
- cngDST //Path of the cng destination category
- publicaddrCN... |
hzlf/openbroadcast | website/apps/spf/management/commands/spf_lookup.py | Python | gpl-3.0 | 5,465 | 0.003843 | #-*- coding: utf-8 -*-
import os
import sys
import time
import re
from django.core.files import File as DjangoFile
from django.core.management.base import BaseCommand, NoArgsCommand
from optparse import make_option
from obp_legacy.models import *
from spf.models import Request, Match
from spf.util.lookup import Medi... | items = Request.objects.filter(status=1, num_results__gte=1)[self.offset:(self.limit + self.offset)]
for item in items:
mm.match(item)
print '---------------------------------------------'
print 'swp_id: %s' % item.swp_id
print 'title: ... | print '############# SUMMARY ############'
print 'num queried: %s' % items.count()
print 'num matches: %s' % total_matches
if self.action == 'reset':
print 'legacy mode'
items = Request.objects.all()[self.offset:(self.limit + self.offset)]
... |
wandb/client | wandb/vendor/pygments/lexers/_cl_builtins.py | Python | mit | 14,053 | 0.000142 | # -*- coding: utf-8 -*-
"""
pygments.lexers._cl_builtins
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ANSI Common Lisp builtins.
:copyright: Copyright 2006-2017 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
BUILTIN_FUNCTIONS = set(( # 638 functions
'<', '<=', '=', '>', '>=',... | 'code-char', 'coerce', 'compile',
'compiled-function-p', 'compile-file', 'compile-file-pathname',
'compiler-macro-function', 'complement', 'complex', 'complexp',
'compute-applicable-methods', 'compute-restarts', 'concatenate',
'concatenated-stream-streams', 'conjugate', 'cons', 'consp',
'constantly... | 'cosh', 'count', 'count-if',
'count-if-not', 'decode-float', 'decode-universal-time', 'delete',
'delete-duplicates', 'delete-file', 'delete-if', 'delete-if-not',
'delete-package', 'denominator', 'deposit-field', 'describe',
'describe-object', 'digit-char', 'digit-char-p', 'directory',
'directory-na... |
jonatanSh/challenge-framework | challenge_framework/challenge_admin/views.py | Python | apache-2.0 | 2,353 | 0.001275 | from django.views.generic import TemplateView
from challenge_framework.mixins import ChallengeAdmin, CustomAdminSideBar
from challenge_framework.configs.urls import admin_configs, challenge_admin, group_under
from .models import ChallengeScore
class BaseViewMixin(CustomAdminSideBar):
@property
def side_bar_li... | engeScore.objects.get(challenge__pk=self.challenge.pk)
# print(score.score, score.team)
scores = ChallengeScore.objects.filter(challenge__pk=self.challenge.pk)
response_object = {
"total_users": 0,
"users_finished": 0,
"currently_playing": 0,
"nu... | "jonatan", "sub_information": "best player"},
{"title": "Jhonatan",
"image": "https://pbs.twimg.com/profile_images/907986314250813440/52Csownn_400x400.jpg",
"sub_information": ",".join([
"a",
"b",
"c"]) # ... |
emyarod/OSS | 1_intro/6.00.1x/Week 3/Problem Set 3/radiationExposure.py | Python | mit | 935 | 0.006417 | def f(x):
import math
return 10*math.e**(math.log(0.5)/5.27 * x)
def radiationExposure(start, stop, step):
'''
Computes and returns the amount of radiation exposed
to between the start and stop times. Calls the
function f (defined for you in the grading script)
to obtain the value of the f... | stop: integer, the time at which exposure ends
step: float, the width of each rectangle. You can assume that
the step size will always partition the space evenly.
returns: float, the amount of radiation exposed to
between start and stop times.
'''
def frange(start, stop, step):
... | tep
value = 0
for time in frange(start, stop, step):
value += (f(time) * step)
return value
print radiationExposure(40, 100, 1.5) |
psnj/petl | petl/util/materialise.py | Python | mit | 3,854 | 0.000259 | from __future__ import absolute_import, print_function, division
import operator
from collections import OrderedDict
from itertools import islice
from petl.compat import izip_longest, text_type, next
from petl.util.base import asindices, Table
def listoflists(tbl):
return [list(row) for row in tbl]
Table.li... | [1, 2, 3]
See also :func:`petl.util.materialise.facetcolumns`.
"""
cols = OrderedDict()
it = iter(table)
hdr = next(it)
flds = list(map(text_type, hdr))
for f in flds:
cols[f] = list()
for row in it:
for f, v in izip_longest(flds, row, fillvalue=missing):
... | g=None):
"""
Like :func:`petl.util.materialise.columns` but stratified by values of the
given key field. E.g.::
>>> import petl as etl
>>> table = [['foo', 'bar', 'baz'],
... ['a', 1, True],
... ['b', 2, True],
... ['b', 3]]
>>> fc ... |
Fafa87/EP | ep/evalplatform/plot_comparison.py | Python | mit | 27,171 | 0.005153 | from __future__ import division # so that a / b == float(a) / b
import fire
from ep.evalplatform import draw_details
from ep.evalplatform.compatibility import plot_comparison_legacy_parse
from ep.evalplatform.parsers import *
from ep.evalplatform.parsers_image import *
from ep.evalplatform.plotting import Plotter
fr... | e:
print (celllist)
def read_ground_truth(path, parser=None):
"""
Returns::
[Cell]
"""
parser = parser or ground_truth_parser
debug_center.show_in_console(None, "Progress", "Reading ground truth data...")
debug_center.show_in_console(None, "Tech", "".join([" | Uses ", parser.__class__.__name__, " parser..."]))
cells = parser.load_from_file(path)
debug_center.show_in_console(None, "Progress", "Done reading ground truth data...")
return cells
def make_all_cells_important(frame_cells):
for frame_cell in frame_cells:
frame_cell[1].colour = 0
def read_... |
arenadata/ambari | ambari-server/src/main/resources/stacks/BigInsights/4.0/services/KAFKA/package/scripts/kafka_broker.py | Python | apache-2.0 | 4,270 | 0.010304 | """
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this ... | ('source {params.conf_dir}/kafka-env.sh; {params.kafka_bin} stop')
Execute(daemon_cmd,
user=pa | rams.kafka_user,
)
File (params.kafka_pid_file,
action = "delete"
)
def status(self, env):
import status_params
env.set_params(status_params)
check_process_status(status_params.kafka_pid_file)
if __name__ == "__main__":
KafkaBroker().execute()
|
3drobotics/MAVProxy | MAVProxy/modules/mavproxy_log.py | Python | gpl-3.0 | 7,465 | 0.003751 | #!/usr/bin/env python
'''log command handling'''
import time, os
from MAVProxy.modules.lib import mp_module
class LogModule(mp_module.MPModule):
def __init__(self, mpstate):
super(LogModule, self).__init__(mpstate, "log", "log transfer")
self.add_command('log', self.cmd_log, "log file handling", ... | self.download_last_timestamp = None
self.download_ofs = 0
self.retries = 0
self.entries = {}
def mavlink_packet(self, m):
'''handle an incoming | mavlink packet'''
if m.get_type() == 'LOG_ENTRY':
self.handle_log_entry(m)
elif m.get_type() == 'LOG_DATA':
self.handle_log_data(m)
def handle_log_entry(self, m):
'''handling incoming log entry'''
if m.time_utc == 0:
tstring = ''
else:
... |
borntyping/python-riemann-client | riemann_client/riemann_pb2.py | Python | mit | 314 | 0 | """Wraps the riemann_pb2_py2 and riemann_pb2_py3 modules"""
import sys
__all__ = ['Event', 'Msg', 'Query', 'Attri | bute']
if sys.version_info >= (3,):
from rie | mann_client.riemann_py3_pb2 import (Event, Msg, Query, Attribute)
else:
from riemann_client.riemann_py2_pb2 import (Event, Msg, Query, Attribute)
|
Laodicean/pyGravSim | gravSim.py | Python | gpl-3.0 | 4,070 | 0.014742 | #gravSim.py
import pygame
import math
frame_count = -1
WIDTH=640
HEIGHT=480
Quit = False
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('Gr | avity Sim')
objects_group = pygame.sprite.Group()
clock = pygame.time.Clock()
class Object(): #where the magic happens. Ideally there need only be one class for all of the objects in the game; saves code and makes things MUCH more simple.
def __init__(self,location = [0,0]):
self.mass = 10
self.loc... | self.velocityY = 0.0
self.forceX = 0.0
self.forceY = 0.0
self.size = (10,10)
self.downward_gravity = 1
self.makeSprite()
def checkLocation(self):
if self.sprite.rect.left < 0 or self.sprite.rect.right > WIDTH:
self.velocityX *= -1
if self.spr... |
timcera/mettoolbox | src/mettoolbox/evaplib.py | Python | bsd-3-clause | 23,762 | 0.000926 | # -*- coding: utf-8 -*-
"""
Functions for calculation of potential and actual evaporation
from meteorological data.
Potential and actual evaporation functions
==========================================
- E0: Calculate Penman (1948, 1956) open water evaporation.
- Em: Calculate evaporation according to... | of) aerodynamic resistance [s m-1].
References
----------
A.S. Thom (1075), Momentum, mass and heat exchange of plant communities,
In: Monteith, J.L. Vegetation and the Atmosphere, Academic Press, London.
p. 57–109.
Examples
--------
>>> ra(3 | ,0.12,2.4,5.0)
3.2378629924752942
>>> u=([2,4,6])
>>> ra(3,0.12,2.4,u)
array([ 8.09465748, 4.04732874, 2.69821916])
"""
# Test input array/value
u = meteolib._arraytest(u)
# Calculate ra
ra = (scipy.log((z - d) / z0)) ** 2 / (0.16 * u)
return ra # aerodynami... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.