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 |
|---|---|---|---|---|---|---|---|---|
ner0x652/RElief | dololi/dololi.py | Python | mit | 6,472 | 0.008189 | import lief
import sys
import os
import traceback
import configparser
import struct
from collections import OrderedDict
# Opcodes
X86_PUSH_BYTE = 0x6a
X86_32_PUSH_DWORD = 0x68
x86_32_CALL = [0xff, 0x15]
X86_64_CALL = [0xff, 0xd0]
X86_64_MOV_R9 = [0x49, 0xb9 | ]
X86_64_MOV_R8 = [0x49, 0xb8]
X86_64_MOV_RDX = [0x48, 0xba]
X86_64_MOV_RCX = [0x48, 0xb9]
X86_64_MOV_RAX = [0x48, 0xc7, 0xc0]
def get_config(conf_file="dololi.conf"):
assert os.path.isfile(conf_file)
conf = configparser.ConfigParser()
conf.read(conf_file)
return conf
def is_dll(pe_fi... | der.has_characteristic(lief.PE.HEADER_CHARACTERISTICS.DLL)
def get_pe_type(arch):
assert arch == "32" or arch == "64"
if arch == "32":
return lief.PE.PE_TYPE.PE32
else:
return lief.PE.PE_TYPE.PE32_PLUS
def is_64_bits(pe_type):
return pe_type == lief.PE.PE_TYPE.PE32_PLUS
def ge... |
N6UDP/cslbot | cslbot/commands/bard.py | Python | gpl-2.0 | 1,191 | 0.001679 | # Copyright (C) 2013-2015 Samuel Damashek, Peter Foley, James Forcier, Srijay Kasturi, Reed Koser, Christopher Reffett, and Fox Wilson
#
# 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 ve... | Syntax: {command} <something>
"""
if not msg:
send("Forsooth! What shalt I translate?")
| return
send(gen_shakespeare(msg))
|
kubow/HAC | Multimedia/Database/TkTableWrapper.py | Python | unlicense | 25,265 | 0.004235 | # Copyright (c) 2008, Guilherme Polo
# 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 conditions and ... | ll(self._w, 'bbox', first, last)) or ()
def clear(self, option, first=None, last=None):
"""This is a convenience routine to clear certain state information
managed by the table. first and last represent valid table indices.
If neither are specified, then the command operates on the whole
... | e specified section of the cache, if the table has been
keeping one."""
self.clear('cache', first, last)
def clear_sizes(self, first=None, last=None):
"""Clear the specified row and column areas of specific height/width
dimensions. When just one index is specified, for example 2,0,... |
Onyo/vtex-client | vtex_client/card.py | Python | gpl-3.0 | 424 | 0.002358 | # -*- | coding: utf-8 -*-
from __future__ import unicode_literals
from .base import BaseClient
class CardClient(BaseClient):
def get_information(self, numbers):
"""Get a card information from the first six numbers of the card.
:param numbers: first six numbers of the card
:returns: card inform... | rmat(numbers), 'get')
|
RenZ0/php-show-controller | engine/delta.py | Python | gpl-2.0 | 14,328 | 0.006003 | #!/usr/bin/python
# -*- coding:utf-8 -*-
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distr... | Universes
try:
prefs = self.base.requete_sql("SELECT * FROM dmx_preferences WHERE id=1") #setting
for p in range(len(prefs)):
self.univ_qty = prefs[p]['univ_qty']
except:
print "default | to 1 universe"
self.univ_qty = 1
print "univ_qty"
print self.univ_qty
# array to store full frame
self.WholeDmxFrame = [0] * 512 * self.univ_qty
# send the first one
self.SendDmxFrame()
self._wrapper.Run()
def BlackOut(self):
'''Reset a... |
ESOedX/edx-platform | openedx/core/djangoapps/video_pipeline/config/waffle.py | Python | agpl-3.0 | 720 | 0.002778 | """
This module contains configuration settings via waffle flags
for the Video Pipeline app.
"""
from __future__ import absolute_import
from openedx.core.djan | goapps.waffle_utils import WaffleFlagNamespace, CourseWaffleFlag
# Videos Namespace
WAFFLE_NAME | SPACE = 'videos'
# Waffle flag telling whether youtube is deprecated.
DEPRECATE_YOUTUBE = 'deprecate_youtube'
def waffle_flags():
"""
Returns the namespaced, cached, audited Waffle flags dictionary for Videos.
"""
namespace = WaffleFlagNamespace(name=WAFFLE_NAMESPACE, log_prefix=u'Videos: ')
retu... |
schmit/intro-python-course | lectures/code/classes_stocks.py | Python | mit | 351 | 0.002849 | class Stock():
| def __init__(self, name, symbol, prices=[]):
self.name = name
self.symbol = symbol
self.prices = prices
def high_price(self):
if len(self.prices) == 0:
return 'MISSING PRICES'
return max(self.prices)
ap | ple = Stock('Apple', 'APPL', [500.43, 570.60])
print apple.high_price()
|
sjorsng/osint-combiner | shodanfunctions.py | Python | mit | 6,072 | 0.002635 | from base import dict_add_source_prefix
from base import add_institution_field
from base import get_institutions
from base import dict_clean_empty
from base import convert_file
import configparser
import shodan
import json
import sys
import os
def get_new_shodan_api_object():
"""Returns initialised Shodan API obj... | ('\"' + query + '\"')
results = 0
with open(path_output_file, "a") as output_file:
try:
for banner in api.search_cursor(query):
| banner = dict_clean_empty(banner)
output_file.write(json.dumps(banner) + '\n')
results += 1
print('\r' + str(results) + ' results written...', end='')
print("")
except shodan.APIError as e:
print('E... |
mganeva/mantid | scripts/Muon/GUI/Common/load_run_widget/load_run_model.py | Python | gpl-3.0 | 2,348 | 0.001278 | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source
# & Institut Laue - Langevin
# SPDX - License - Identifier: GPL - 3.0 +
from __future__ import (absolute_import, divi... | ws, run, filename = load_utils.load_workspace_from_filename(filename)
except Exception as error:
failed_files += [(filename, error)]
continue
self._loade | d_data_store.remove_data(run=[run])
self._loaded_data_store.add_data(run=[run], workspace=ws, filename=filename, instrument=self._context.instrument)
if failed_files:
message = load_utils.exception_message_for_failed_files(failed_files)
raise ValueError(message)
# This i... |
RyanEggert/space-lander | rocket_control/printvals.py | Python | mit | 3,261 | 0.005826 | import time
from usb_vendor import PIC_USB
import traceback
# Product IDs: Master PIC is 0x0004, Rocket PIC is 0x0005, Barge PIC is 0x0006
comms = PIC_USB(0x0005)
def main():
print("START")
loop_time = .2 # How often to run the main loop, in seconds
while True:
start_time = time.clock()
# ... | ed {} | Tilt Angle {} | Tilt Direction {} | Rocket State {}".format(
info["tilt"],
info["speed"],
info["throttle"],
info["motor_speed"],
info["motor_thrust"],
info["stepper_speed"],
info["tilt_ang"],
| info["tilt_dir"],
info["rocket_state"],
)
def debug_uart_buffers():
info = comms.debug_uart_buffers()
rx = info["rx"]
tx = info["tx"]
print "TX_head {} | TX_tail {} | TX_count {} || RX_head {} | RX_tail {} | RX_count {}".format(
tx["head"],
tx["tail"],
tx["coun... |
iTeam-org/iteam-site | iTeam/events/forms.py | Python | agpl-3.0 | 3,827 | 0.001573 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: Adrien Chardon
# @Date: 2014-08-21 18:54:29
# @Last Modified by: Adrien Chardon
# @Last Modified time: 2014-12-04 19:41:49
# This file is part of iTeam.org.
# Copyright (C) 2014 Adrien Chardon (Nodraak).
#
# iTeam.org is free software: you can redistribute i... | e')
file = cleaned_data.get('file')
if img and img.size > | settings.SIZE_MAX_IMG:
msg = (
u'Fichier trop lourd (%d Ko / %d Ko max). Pour ne pas saturer le serveur, merci '
u'de réduire la résolution de l\'image.') % (img.size/1024, settings.SIZE_MAX_IMG/1024)
self._errors['image'] = self.error_class([msg])
if... |
maximumG/exscript | tests/Exscript/emulators/IOSEmulatorTest.py | Python | mit | 1,094 | 0.003656 | from __future__ import absolute_import
import sys
import unittest
import re
import os.path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', '..'))
from .VirtualDeviceTest import VirtualDeviceTest
from Exscript.emulators import IOSEmulator
from Exscript.emulators.iosemu import ios | banner
class IOSEmulatorTest(VirtualDeviceTest):
CORRELATE = IOSEmulator
cls = IOSEmulator
banner = iosbanner % ('myhost', 'myhost', 'myhost')
prompt = 'myhost#'
userprompt = 'Username: | '
passwdprompt = 'Password: '
def testAddCommand(self):
VirtualDeviceTest.testAddCommand(self)
cs = self.cls('myhost',
strict=True,
echo=False,
login_type=self.cls.LOGIN_TYPE_NONE)
response = cs.do('show version')
... |
kernelci/kernelci-backend | app/models/test_group.py | Python | lgpl-2.1 | 7,454 | 0 | # Copyright (C) Collabora Limited 2018,2019
# Author: Michal Galka <michal.galka@collabora.com>
# Author: Guillaume Tucker <guillaume.tucker@collabora.com>
# Author: Ana Guerrero Lopez <ana.guerrero@collabora.com>
#
# Copyright (C) Linaro Limited 2019
# Author: Matt Hart <matthew.hart@linaro.org>
#
# This program is fr... | ""The name of the test group."""
return self._name
@property
def lab_name(self):
"""The name of the test lab."""
return self._lab_name
@property
def build_id(self):
"""The ID of the build."""
return self._build_id
@build_id.setter
def build_id(self, val... | value
@property
def version(self):
"""The schema version of this test group."""
return self._version
@version.setter
def version(self, value):
"""Set the schema version of this test group."""
if self._version:
raise AttributeError("Schema version already set... |
RescueTime/cwmon-mysql | tests/test_cwmon_mysql.py | Python | bsd-2-clause | 1,999 | 0 | # -*- encoding: utf-8 -*-
"""Tests for the monitoring CLI.
.. danger:: Y | ou **must** pass the `--dry-run` flag in all tests. Failure to do
so will result in flooding AWS CloudWatch with bogus stats.
"""
from click.testing import CliRunner
from cwmon.cli import cwmon
def _run_mysql_metric(name, *args):
runner = CliRunner()
my_args = ['--dry-run', 'mysql']
if name:
... | voke(cwmon, my_args)
def test_mysql_registered_correctly():
"""Test the primary entrypoint of the CLI some more."""
result = _run_mysql_metric('')
assert result.output.startswith('Usage')
assert result.exit_code == 0
def test_deadlocks():
"""Test the happy path for deadlock detection."""
re... |
mansonul/events | events/contrib/plugins/form_elements/fields/select_multiple/apps.py | Python | mit | 516 | 0 | __title__ = 'fobi.contrib.plugins.form_elements.fields.select_multiple.apps'
__author_ | _ = 'Artur Barseghyan <artur.barseghyan@gmail.com>'
__copyright__ = '2014-2017 Artur Barseghyan'
__license__ = 'GPL 2.0/LGPL 2.1'
__all__ = ('Config',)
try:
from django.a | pps import AppConfig
class Config(AppConfig):
"""Config."""
name = 'fobi.contrib.plugins.form_elements.fields.select_multiple'
label = 'fobi_contrib_plugins_form_elements_fields_select_multiple'
except ImportError:
pass
|
craffel/librosa | tests/test_output.py | Python | isc | 3,760 | 0.000798 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''Tests for output functions'''
# Disable cache
import os
try:
os.environ.pop('LIBROSA_CACHE_DIR')
except:
pass
import librosa
import numpy as np
import tempfile
from nose.tools import raises, eq_
def test_write_wav():
def __test(mono, norm):
y,... | n(times):
yield __test_fail, times, annotation | s, sep
else:
yield __test, times, annotations, sep
|
privacyidea/privacyidea | tests/smtpmock.py | Python | agpl-3.0 | 7,934 | 0.000378 | # -*- coding: utf-8 -*-
"""
2016-01-20 Cornelius Kölbel <cornelius@privacyidea.org>
Support STARTTLS mock
2015-01-30 Cornelius Kölbel <cornelius@privacyidea.org>
Change responses.py to be able to run with SMTP
Original responses.py is:
Copyright 2013 Dropbox, Inc.
Licensed under the Apache Lic... | if self._request_data.get("authenticated"):
response = (235, "Authentication successful.")
else:
response = (535, "authentication failed (#5.7.1)")
return {self._request_data.get("recipient | "): response}
# def _on_init(self, SMTP_instance, host, port=25, timeout=3):
def _on_init(self, *args, **kwargs):
SMTP_instance = args[0]
host = args[1]
if isinstance(SMTP_instance, smtplib.SMTP_SSL):
# in case we need sth. to do with SMTL_SSL
self.smtp_ssl = True... |
sajuptpm/neutron-ipam | neutron/tests/unit/vmware/test_nsx_utils.py | Python | apache-2.0 | 15,554 | 0 | # Copyright (c) 2013 VMware.
#
# 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... | ='dbexts.db')).start()
mock.patch(nsx_method('delete_neutron_nsx_port_mapping',
module_name='dbexts.db')).start()
def _mock_network_mapping_db_calls(self, ret_value):
# Mock relevant db calls
# This will allow for avoiding settin | g up the plugin
# for creating db entries
mock.patch(nsx_method('get_nsx_switch_ids',
module_name='dbexts.db'),
return_value=ret_value).start()
mock.patch(nsx_method('add_neutron_nsx_network_mapping',
module_name='dbe... |
spreeker/democracygame | external_apps/docutils-snapshot/test/functional/tests/standalone_rst_s5_html_1.py | Python | bsd-3-clause | 2,406 | 0.001247 | exec(open('functional/tests/_standalone_rst_defaults.py').read())
# Source and destination file names:
test_source = 'standalone_rst_s5_html.txt'
test_destination = 'standalone_rst_s5_html_1.html'
# Keyword parameters passed to publish_file:
writer_name = 's5_html'
# Settings:
settings_overrides['theme'] = 'small-bl... | onal/output/', 'functional/expected/')
for path in differences]
parts.append('Please compare the expected and actual output files:' | )
parts.extend([' diff %s %s' % tup
for tup in zip(expected, differences)])
parts.append('If the actual output is correct, please replace the '
'expected output files:')
parts.extend([' mv %s %s' % tup
for tup in zip(differences,... |
itucsdb1517/itucsdb1517 | classes/operations/position_operations.py | Python | gpl-3.0 | 3,765 | 0.00425 | import psycopg2 as dbapi2
from classes.position import Position
from classes.model_config import dsn, connection
class position_operations:
def __init__(self):
self.last_key=None
def get_positions(self):
positions=[]
global connection
try:
connection = dbapi2.connect... | cursor.close()
result = 'success'
except dbapi2.IntegrityError:
result = 'integrityerror'
if connection:
connection.rollback()
e | xcept dbapi2.DatabaseError:
result = 'databaseerror'
if connection:
connection.rollback()
finally:
if connection:
connection.close()
return result
def delete_position(self,key):
global connection
try:
... |
burgerdev/hostload | visualization/xor2.py | Python | mit | 1,409 | 0.00071 | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 21 22:48:37 2016
@author: burger
"""
import numpy as np
from matplotlib import pyplot as plt
def sigma(x, a=1, b=0):
return 1/(1+np.exp(-(a*x+b)))
x = np.asarray([[0.0, .1], [0, 1], [.9, .05], [.9, .95]])
markers = 'v<>^'
a = .5*np.ones((2,))
proj = np.dot(x, a)... | lt.plot(proj_line, proj_line, 'k.', MarkerSize=dots)
plt.plot(proj_transformed_x, proj_transformed_y, 'r.', MarkerSize=dots)
plt.plot(X, Y, 'k')
for x in proj_line[::4]:
a, b = trafo(proj_line, x*np.ones_like(proj_line))
plt.plot(a, b, 'k')
a, b = trafo(x*np.ones_like(proj_line), proj_line)
plt.plot(a,... | ), 'k')
plt.xlim([-.05, 1.05])
plt.ylim([-.05, 1.05])
plt.show()
|
Tesora-Release/tesora-trove | trove/guestagent/strategies/restore/db2_impl.py | Python | apache-2.0 | 2,104 | 0 | # Copyright 2016 IBM Corp
# 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 agreed to in writing, software
# distributed under the License is distrib... | language governing permissions and limitations
# under the License.
from oslo_log import log as logging
from trove.common import cfg
from trove.common.i18n import _
from trove.common import utils
from trove.guestagent.common import operating_system
from trove.guestagent.datastore.db2 import service
from trove.guesta... |
jmeagher/playground | kubernetes/locust/tasks/tasks.py | Python | apache-2.0 | 5,021 | 0.009361 | import datetime
import glob
import os
import random
import requests
import sys
import time
import traceback
from locust import HttpLocust, TaskSet, task
timeout = (0.5, 1.0)
corpus_glob = os.environ["CORPUS_GLOB"]
all_files = glob.glob(corpus_glob)
test_index = os.environ.get("TEST_INDEX", "load_test")
simple_queri... | simple_search=None, post_search=None):
if simple_search:
url = "/%s/_search?q=%s" % (test_index, simple_search)
else:
url = "/%s/_search" % test_index
with self.client.get(url, name=name,
json=post_search, timeout=timeout, catch_response=True) as response:
... | e)
def _do_insert(self, id, name):
line = random.choice(self.corpus)
data = {
"timestamp": datetime.datetime.utcnow().isoformat(),
"line": line,
"my_id": id,
"random": random.randint(0,1000),
"data_type": name,
}
with self.... |
LABSN/expyfun | expyfun/io/_wav.py | Python | bsd-3-clause | 3,494 | 0 | # -*- coding: utf-8 -*-
"""WAV file IO functions
"""
import numpy as np
from scipy.io import wavfile
from os import path as op
import warnings
from .._utils import verbose_dec, logger, _has_scipy_version
@verbose_dec
def read_wav(fname, verbose=None):
"""Read in a WAV file
Parameters
----------
fna... | a.astype(np.float64) / max_val)
_print_wav_info('Read', data, orig_dtype)
return data, fs
@verbose_dec
def | write_wav(fname, data, fs, dtype=np.int16, overwrite=False, verbose=None):
"""Write a WAV file
Parameters
----------
fname : str
Filename to save as.
data : array
The data to save.
fs : int
The sample rate of the data.
dtype : numpy dtype
The output format to... |
inveniosoftware/invenio-records-rest | invenio_records_rest/schemas/fields/marshmallow_contrib.py | Python | mit | 4,465 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2018-2019 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Contributed Marshmallow fields."""
from __future__ import absolute_import, print_... | return func(value, self.parent.context, data)
elif func_args_len > 1:
return func(value, self.parent.context)
else:
return func(value)
class Method(fields.Method):
"""Enhanced marshmallow Method field.
The main difference between the original marshmallow.fields.Meth... | ent
method, with the second argument being the original data that was passed to
``Schema.load``. The following example better demonstrates how this works:
.. code-block:: python
class BarSchema(marshmallow.Schema):
bar = Method('serialize_bar', 'deserialize_bar')
# Exactl... |
theQRL/QRL | setup.py | Python | mit | 1,072 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file was generated with PyScaffold 3.0.2.
PyScaffold helps you to put up the scaffold of your new Python project.
Learn more under: http://pyscaffold.org/
"""
import sys
from setuptools import setup
import versioneer
# Add here console scripts and oth... | measure:main
qrl | _walletd = qrl.daemon.walletd:main
qrl_generate_genesis = qrl.tools.generate_genesis:main
"""
def setup_package():
needs_sphinx = {'build_sphinx', 'upload_docs'}.intersection(sys.argv)
sphinx = ['sphinx'] if needs_sphinx else []
setup(setup_requires=['pyscaffold>=3.0a0,<3.1a0'] + sphinx,
ent... |
rabipanda/tensorflow | tensorflow/contrib/kfac/python/ops/layer_collection_lib.py | Python | apache-2.0 | 1,738 | 0.000575 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
# |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | RANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Registry for layers and their parameters/variables.
This represents th... |
jawilson/home-assistant | homeassistant/components/nest/events.py | Python | apache-2.0 | 2,037 | 0 | """Library from Pub/sub messages, events and device triggers."""
from google_nest_sdm.camera_traits import (
CameraMotionTrait,
CameraPersonTrait,
CameraSoundTrait,
)
from google_nest_sdm.doorbell_traits import DoorbellChimeTrait
from google_nest_sdm.event import (
CameraMotionEvent,
CameraPersonEv... | ERA_SOUND = "camera_sound"
# Mapping of supported device traits to home assistant event types. Devices
# that support these traits will generate Pub/Sub event messages in
# the EVENT_NAME_ | MAP
DEVICE_TRAIT_TRIGGER_MAP = {
DoorbellChimeTrait.NAME: EVENT_DOORBELL_CHIME,
CameraMotionTrait.NAME: EVENT_CAMERA_MOTION,
CameraPersonTrait.NAME: EVENT_CAMERA_PERSON,
CameraSoundTrait.NAME: EVENT_CAMERA_SOUND,
}
# Mapping of incoming SDM Pub/Sub event message types to the home assistant
# event type... |
JKrehl/Electrons | Electrons/Tomography/Kernels/__init__.py | Python | isc | 157 | 0 | from . | Kernel import Kernel
from .RayKernel | import RayKernel
from .FresnelKernel import FresnelKernel
__all__ = [s for s in dir() if not s.startswith('_')]
|
Arelle/Arelle | arelle/ViewWinXml.py | Python | apache-2.0 | 1,337 | 0.004488 | '''
Created on Feb 6, 2011
@author: Mark V Systems Limited
(c) Copyright 2011 Mark V Systems Limited, All rights reserved.
'''
from tkinter import *
try:
from tkinter.ttk import *
except ImportError:
from ttk import *
from arelle.CntlrWinTooltip import ToolTip
import io
from arelle import (XmlUtil, ViewWinList... | ntextMenu()
view.menuAddSaveClipboard()
menu.add_command(label=_("Validate"), underline=0, command=view.validate)
class V | iewXml(ViewWinList.ViewList):
def __init__(self, modelXbrl, tabWin, tabTitle):
super(ViewXml, self).__init__(modelXbrl, tabWin, tabTitle, True)
def view(self, xmlDoc):
fh = io.StringIO()
XmlUtil.writexml(fh, xmlDoc, encoding="utf-8")
for line in fh.getvalue().split("\n"):
... |
all-of-us/raw-data-repository | tests/dao_tests/test_ghost_check_dao.py | Python | bsd-3-clause | 1,959 | 0.003063 | from datetime import datetime, timedelta
from rdr_service.dao.ghost_check_dao import GhostCheckDao
from tests.helpers.unittest_base import BaseTestCase
class GhostCheckDaoTest(BaseTestCase):
def test_loads_only_vibrent(self):
"""We might accidentally start flagging CE participants as ghosts if they're re... | ant(participantOrigin='vibrent')
self.data_generator.create_database_participant(participantOrigin='careevolution')
self.data_generator.create_database_participant(participantOrigin='anotherplatform')
participants = GhostCheckDao.get_participants_needing_checked(
session=self.data_g... | p_time=datetime.now() - timedelta(weeks=1)
)
self.assertEqual(1, len(participants), 'Should only be the Vibrent participant')
self.assertEqual(vibrent_participant.participantId, participants[0].participantId)
def test_ghost_flag_returned(self):
"""Ensure we get back the ghost data f... |
dennisguse/VoIP.py | Defines/SIGNALS.py | Python | gpl-3.0 | 1,227 | 0.008965 | from PyQt4.QtCore import *
import logging
#Call Signals
CALL_CONNECT = 'connectCall'
CALL_HANGUP = 'hangupCurrentCall'
CALL_NUMBER = 'callNumber'
CALL_INCOMING = 'inCallSig'
CALL_INCOMING_CANCELED = 'inCallCanceled'
CALL_OUTGOING_CANCELED = 'outCallCanceled'
CALL_SHOW_VIDEO = 'callShowVideo'
CALL_SIGNAL_LEVEL_CHANGE ... | = None):
logging.getLogger("SIGNALS").info(sender.__class__.__name__ + " " + signalName)
| if param2:
sender.emit(SIGNAL(signalName), param1, param2)
elif param1:
sender.emit(SIGNAL(signalName), param1)
else:
sender.emit(SIGNAL(signalName))
|
chosak/fdic-call-reports | bin/download_all_reports.py | Python | mit | 3,207 | 0.000624 | import logging, os, time
from contextlib import contextmanager
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.support.ui import Select
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
SELENIUM_SERVER =... | ds.select_by_index(count)
time.sleep(3)
submit_button = driver.find_element_by_id | ('Download_0')
submit_button.click()
time.sleep(3)
count += 1
logger.info('waiting for last download to finish')
time.sleep(30)
@contextmanager
def selenium_driver():
logger.info('connecting to local Selenium server at {}'.format(
SELENIUM_SERVER
)... |
djkonro/client-python | kubernetes/client/models/v1beta1_network_policy_ingress_rule.py | Python | apache-2.0 | 5,351 | 0.001121 | # coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.7.4
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
... | ld is present and contains at least on item, this rule allows traffic only if the traffic matches at least one item in the from list.
:return: The _from of this V1beta1NetworkPolicyIngressRule.
| :rtype: list[V1beta1NetworkPolicyPeer]
"""
return self.__from
@_from.setter
def _from(self, _from):
"""
Sets the _from of this V1beta1NetworkPolicyIngressRule.
List of sources which should be able to access the pods selected for this rule. Items in this list are c... |
prheenan/BioModel | EnergyLandscapes/Lifetime_Dudko2008/Python/TestExamples/Examples/Example_Dudko_Fit.py | Python | gpl-2.0 | 889 | 0.008999 | # force floating point division. Can still use integer with //
from __future__ import division
# This file is used for importing the common utilities classes.
import numpy as np
import matplotlib.pyplot as plt
import sys
sys.path.append("../../../../../")
from EnergyLand | scapes.Lifetime_Dudko2008.Python.TestExamples.Util import \
Example_Data
def PlotFit(data,BaseName):
fig = Example_Data.PlotHistograms(data)
fig.savefig(BaseName + "_Histogram.png")
fig = Example_Data.PlotLifetimesAndFit(data)
fig.savefig(BaseName + "_Lifetimes.png")
def run():
"""
""... | mple_Data.Dudko2008Fig1_Probabilities()
PlotFit(data,"../Out/Dudko2008_Fig1")
# figure 2 frm dudko 2008
data = Example_Data.Dudko2008Fig2_Probabilities()
PlotFit(data,"../Out/Dudko2008_Fig2")
if __name__ == "__main__":
run()
|
RealTimeWeb/wikisite | MoinMoin/i18n/tools/check_i18n.py | Python | apache-2.0 | 12,365 | 0.001617 | #! /usr/bin/env python
# -*- coding: iso-8859-1 -*-
"""check_i18n - compare texts in the source with the language files
Searches in the MoinMoin sources for calls of _() and tries to extract
the parameter. Then it checks the language modules if those parameters
are in the dictionary.
Usage: check_i18n.py [lang ...]
... | self.__unused[text] = self.__langDict[text]
| self.__ready = 1
def summary(self):
"""Return summary dict"""
summary = {
'name': i18n.languages[self.__lang][i18n.ENAME].encode(output_encoding),
'maintainer': i18n.languages[self.__lang][i18n.MAINTAINER],
'total': len(self.__langDict),
'missing... |
wazaahhh/patchwork | parseUserNames.py | Python | mit | 4,245 | 0.021673 | import numpy as np
import urllib
import simplejson
import time
from datetime import datetime
import pandas
from scipy import stats as S
'''
url = "http://reporobot.jlord.us/data"
urllib.urlretrieve(url, filename="usernames.json")
'''
rootdir = "/home/ubuntu/github/patchwork/"
dic = simplejson.loads(open(rootdir + "... | serList' : userList,
'timeList': timeList,
'prNumList' : prNumList,
'timestampList' : timestampList
}
if save:
outfile = open(rootdir + "userList.json | ", 'wb').write(simplejson.dumps(output))
return output
def exportUserNames(outdic,subsample=0.05):
users = np.array(outdic['userList'])
index = np.random.randint(0,len(users),int(subsample*len(users)))
f =open("users.txt",'wb')
for u in users[index]:
f.write("'" + u + "'")
... |
caktus/rapidpro-python | temba_client/utils.py | Python | bsd-3-clause | 935 | 0.00107 | from __future__ import absolute_import, unicode_literals
import datetime
import pytz
imp | ort six
ISO8601_DATE_FORMAT = '%Y-%m-%d'
ISO8601_DATETIME_FORMAT = ISO8601_DATE_FORMAT + 'T' + '%H:%M:%S'
def parse_i | so8601(value):
"""
Parses a datetime as a UTC ISO8601 date
"""
if not value:
return None
if 'T' in value: # has time
_format = ISO8601_DATETIME_FORMAT
if '.' in value: # has microseconds. Some values from RapidPro don't include this.
_format += '.%f'
i... |
TangentMicroServices/ProjectService | api/tests/tests.py | Python | gpl-2.0 | 6,753 | 0.025766 | from django.test import TestCase, Client
from django.conf import settings
from django.db import IntegrityError
from django.contrib.auth.models import User
from api.models import Project, Task, Resource
from tokenauth.authbackends import TokenAuthBackend
from datetime import date
import requests
import responses
imp... | elf.joe_admin.pk, project=p2)
@responses.activate
def test_get_projects_list_requires_auth(self):
mock_auth_failure()
response = self.c.get("/api/v1/projects/")
assert response.status_code == 403, 'Expect permission denied'
@responses.activate
def test_get_project_list(self):
mock_auth_success(self.... | e="joe", password="test")
response = self.c.get("/api/v1/projects/")
assert response.status_code == 200, 'Expect 200 OK'
assert len(json.loads(response.content)) == 2, 'Expect 2 projects back'
@responses.activate
def test_get_project_list_admin_gets_all_projects(self):
mock_auth_success(self.joe_admin)
... |
fgaudin/aemanager | core/views.py | Python | agpl-3.0 | 39,044 | 0.004175 | import logging
from decimal import Decimal
from django.shortcuts import render_to_response, redirect, get_object_or_404
from django.template.context import RequestContext, Context
from django.utils.translation import ugettext_lazy as _, ugettext
from core.forms import UserForm, PasswordForm, ResendActivationEmailForm, ... | invoiced(owner=user)
limit = profile.get_sales_limit()
remaining = limit - | paid - waiting - to_be_invoiced
sales_limit = profile.get_sales_limit()
sales_limit2 = profile.get_sales_limit2()
if user.get_profile().activity == AUTOENTREPRENEUR_ACTIVITY_PRODUCT_SALE_BIC:
service_waiting = Invoice.objects.get_waiting_service_payments(owner=user)
service_to_be_invoiced ... |
hs634/algorithms | python/strings/shortest_distance_between_words_1.py | Python | mit | 799 | 0.010013 | """
Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.
For example, Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
Given word1 = "coding", word2 = "practice", return 3. Given word1 = "makes", word2 = "coding", retu | rn 1
"""
class Solution():
def __init__(self):
pass
def shortest(self, lst, word1, word2):
m = len(lst)
a , b = -1, -1
for i in range(len(lst)):
if lst[i] == word1:
a = i
if lst[i] == word2:
b = i
if a != -1 a... | d b != -1:
m = min(m, abs(a-b))
return m
print Solution().shortest(["practice", "makes", "perfect", "coding", "makes"], "practice", "perfect") |
Kev/helhack | src/ability/Effect.py | Python | gpl-3.0 | 839 | 0.001192 | # Effect.py - Base class for all ability effects
# Copyright Stefan Brus 2007.
#
# This file is part of HelHack.
#
# HelHack 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.
#
# HelHack is distributed 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... |
TheCamusean/DLRCev3 | scripts/slam/mapping_BASE_10668.py | Python | mit | 5,371 | 0.059393 | import numpy as np
import cv2
from math import pi
def points2mapa(landmarks,pos_rob,mapa,P, delete_countdown): #mapa = (x,y, Px,Py, updt)
new_points2add = []
landmarks = np.array(landmarks)
for i in range(0,landmarks.shape[0]):
x_mapa = pos_rob[0] + landmarks[i,1]*np.cos((pos_rob[2])*pi/180+landmarks[i,0])
... |
if (distance > min_dist and distance< max_dist and angle > min_angle and angle< max_angle) and mapa_ar[j,4] == 0 :
pass
elif j not in eliminate_index:
eliminate_index.append(j)
print("j: ",eliminate_index)
eliminate_index = np.ar | ray(eliminate_index)
mapa = np.array(mapa)
if mapa.size:
mapa = mapa[eliminate_index,:]
mapa= mapa.tolist()
#mapa = mapa[eliminate_index]
return mapa
def add_points_in_mapa(landmarks,new_points2add,mapa, P ,pos_rob,index):
landmarks = np.array(landmarks)
for i in new_points2add:
x_mapa = pos_rob[0] +... |
grnet/synnefo | snf-astakos-app/astakos/im/settings.py | Python | gpl-3.0 | 11,849 | 0 | # Copyright (C) 2010-2017 GRNET S.A.
#
# 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 i... | es/>.
from logging import INFO
from django.conf import settings
from synnefo.lib import parse_base_url
from astakos.api.services import astakos_services as vanilla_astakos_services
from synnefo.lib import join_urls
from synnefo.lib.services import fill_endpoints
from copy import deepcopy
BASE_URL = getattr(settings... | 'https://accounts.example.synnefo.org')
BASE_HOST, BASE_PATH = parse_base_url(BASE_URL)
astakos_services = deepcopy(vanilla_astakos_services)
fill_endpoints(astakos_services, BASE_URL)
ACCOUNTS_PREFIX = astakos_services['astakos_account']['prefix']
VIEWS_PREFIX = astakos_services['astakos_ui']['prefix']... |
Xunius/txt2evernote | lib/geeknote/gnsync.py | Python | gpl-3.0 | 9,526 | 0.002729 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import argparse
import glob
import logging
import string
import unicodedata, re
from geeknote import GeekNote
from storage import Storage
from editor import Editor
import tools
# set default logger (write log to file)
def_logpath = os.path.join(os.getenv('USERP... | files = self._get_files()
notes = self._get_notes()
for f in files:
has_note = False
for n in notes:
if f['name'] == n.title:
has_note = True
if f['mtime'] > n.updated:
self._update_note(f, n)
... | for f in files:
if f['name'] == n.title:
has_file = True
if f['mtime'] < n.updated:
self._update_file(f, n)
break
if not has_file:
self._create_file(n)
... |
kickstandproject/sarlacc | sarlacc/tests/asterisk/agi/test_wait_for_digit.py | Python | apache-2.0 | 2,080 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2013 PolyBeacon, Inc.
#
# Author: Paul Belanger <paul.belanger@polybeacon.com>
#
# 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
#
#... | self.assertEqual(dtmf, '')
@mock.patch('sys.stdin', cStringIO.StringIO("200 result=51"))
def test_wait_for_digit_success(self):
with mock.patch(
'sys.stdout', new_callable=cStringIO.StringIO) as mock_stdout:
res, dtmf = self.agi.wait_for_digit(timeout='25000')
... | sertTrue(res)
self.assertEqual(dtmf, '3')
@mock.patch('sys.stdin', cStringIO.StringIO("200 result=0"))
def test_wait_for_digit_timeout(self):
with mock.patch(
'sys.stdout', new_callable=cStringIO.StringIO) as mock_stdout:
res, dtmf = self.agi.wait_for_digit(timeo... |
mattcongy/itshop | docker-images/taigav2/taiga-back/taiga/projects/api.py | Python | mit | 32,383 | 0.001328 | # -*- coding: utf-8 -*-
# Copyright (C) 2014-2016 Andrey Antukh <niwi@niwi.nz>
# Copyright (C) 2014-2016 Jesús Espino <jespinog@gmail.com>
# Copyright (C) 2014-2016 David Barragán <bameda@dbarragan.com>
# Copyright (C) 2014-2016 Alejandro Alonso <alejandro.alonso@kaleidos.net>
# This program is free software: you can r... | issions import | AllowAnyPermission
from taiga.base.api.utils import get_object_or_404
from taiga.base.decorators import list_route
from taiga.base.decorators import detail_route
from taiga.base.utils.slug import slugify_uniquely
from taiga.permissions import services as permissions_services
from taiga.projects.epics.models import Ep... |
jcarreiro/jmc-python | imp/dice.py | Python | mit | 1,405 | 0.0121 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import io
import string
import random
# Simple recursive descent parser for dice rolls, e.g. '3d6+1d8+4'.
#
# roll := die {('+' | '-') die} ('+' | '-') modifier
# di... | while c in string.digits:
literal += c
c = s.getc()
s.ungetc()
sym = (Symbol.NUMBER,
elif c == 'd':
# die indicator
pass
elif c == '+':
# plus sign
pass
elif c == '-':
# minus sign
pass
else:
# unrecogniz... | rror('Syntax error at position ' + s.tell())
return ()
|
LinuxCircle/tea5767 | wstester.py | Python | mit | 1,082 | 0.008318 | import websocket
try:
import thread
except ImportError: #T | ODO use Threading instead of _thread in python3
import _thread as thread
import time
import sys
def on_message(ws, message):
print(message)
def on_error(ws, error):
print(error)
def on_close(ws):
print("### closed ###")
def on_open(ws):
def run(*args):
for i in range(3):
| # send the message, then wait
# so thread doesnt exit and socket
# isnt closed
ws.send("Hello %d" % i)
time.sleep(1)
time.sleep(1)
ws.close()
print("Thread terminating...")
thread.start_new_thread(run, ())
if __name__ == "__main__":
... |
emacsmirror/stgit | stgit/lib/git/base.py | Python | gpl-2.0 | 852 | 0.00939 | class Immutable:
"""Base class for immutable objects.
Immutable objects cannot be modified once created. Any modification methods will
return a new object, leaving the original object as it was.
The reason for this is that we want to be able to represent git objects, which are
immutable, and want ... | o create new git objects that are just slight
modifications of other git | objects. (Such as, for example, modifying the commit
message of a commit object while leaving the rest of it intact. This involves
creating a whole new commit object that's exactly like the old one except for the
commit message.)
The ``Immutable`` class does not actually enforce immutability--subclasse... |
Kozea/Dyko | kalamar/site.py | Python | gpl-3.0 | 6,799 | 0.000441 | # -*- coding: utf-8 -*-
# This file is part of Dyko
# Copyright © 2008-2010 Kozea
#
# This library 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 lat... | equest.property.name = new_name
request.property.child_property = None
return request
def _delegate_to_ | acces_point(method_name, first_arg_is_a_request=False):
"""Create a function delegating ``method_name`` to an access point."""
if first_arg_is_a_request:
def wrapper(self, access_point_name, request=None, *args, **kwargs):
"""Call ``access_point.method_name(request, *args, **kwargs)``."""
... |
libo/Enigma2 | lib/python/Screens/NetworkSetup.py | Python | gpl-2.0 | 55,103 | 0.032648 | from Screen import Screen
from Screens.MessageBox import MessageBox
from Screens.InputBox import InputBox
from Screens.Standby import *
from Screens.VirtualKeyBoard import VirtualKeyBoard
from Screens.HelpMenu import HelpableScreen
from Components.Network import iNetwork
from Components.Sources.StaticText import Static... |
description = None
interfacepng = None
if iface in iNetwork.lan_interfaces:
if active is True:
interfacepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/network_wired-active.png"))
elif active is False:
interfacepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_def... | interfacepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/network_wired.png"))
elif iface in iNetwork.wlan_interfaces:
if active is True:
interfacepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/network_wireless-active.png"))
elif active is False:
interfa... |
Julian/clogs | clogs/tests/test_git.py | Python | mit | 559 | 0 | from __future__ import absolute_import |
import unittest
from git import Repo
import mock
from clogs import git
class TestGitClogger(unittest.TestCase):
def setUp(self):
super(TestGitClogger, self).setUp()
with mock.p | atch("clogs.git.git.Repo", mock.Mock(spec=Repo)):
self.g = git.GitClogger(directory="foo")
self.repo = self.g.repo
def test_init(self):
self.assertEqual(self.g.directory, "foo")
def test_commit_id(self):
self.assertEqual(self.g.commit_id, self.repo.head.commit.hexsha)
|
momm3/WelcomeBot | welcomebot/Lib/site-packages/requests/adapters.py | Python | mit | 20,601 | 0.001262 | # -*- coding: utf-8 -*-
"""
requests.adapters
~~~~~~~~~~~~~~~~~
This module contains the transport adapters that Requests uses to define
and maintain connections.
"""
import os.path
import socket
from urllib3.poolmanager import PoolManager, proxy_from_url
from urllib3.response import HTTPResponse
from urllib3.util ... | rusted.
:param proxies: (optional) The proxies dictionary to apply to the | request.
"""
raise NotImplementedError
def close(self):
"""Cleans up adapter specific items."""
raise NotImplementedError
class HTTPAdapter(BaseAdapter):
"""The built-in HTTP Adapter for urllib3.
Provides a general-case interface for Requests sessions to contact HTTP and
... |
AutorestCI/azure-sdk-for-python | azure-graphrbac/azure/graphrbac/models/domain.py | Python | mit | 1,683 | 0 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License | .txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
cl... | main(Model):
"""Active Directory Domain information.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar authentication_type: the type of the authentication into the domain.
:vartype authentication_type: str
:ivar is_default: if this is the default dom... |
richardcornish/smsweather | emojiweather/utils/utils.py | Python | bsd-3-clause | 596 | 0 | from django.contrib.gis.geoip2 import GeoIP2
from geoip2.errors impor | t GeoIP2Error
from ipware import get_client_ip
def get_location_from_ip(request):
client_ip, is_routable = get_client_ip(request)
if client_ip is not None:
g = GeoIP2()
try:
record = g.city(client_ip)
except GeoIP2Error:
return None
if record:
... | '
return None
|
malishevg/edugraph | common/djangoapps/lang_pref/views.py | Python | agpl-3.0 | 657 | 0 | """
Views for accessing language preferences
"""
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseBadRequest
from user_api.models import UserPreference
from lang_pref impo | rt LANGUAGE_KEY
@login_required
def set_language(request):
"""
This view is called when the user would like to set a language preference
"""
user = request.user
lang_pref = request. | POST.get('language', None)
if lang_pref:
UserPreference.set_preference(user, LANGUAGE_KEY, lang_pref)
return HttpResponse('{"success": true}')
return HttpResponseBadRequest('no language provided')
|
abalakh/robottelo | tests/foreman/cli/test_repository_set.py | Python | gpl-3.0 | 11,864 | 0 | # pylint: disable=invalid-name
"""Tests for cli repository set"""
from robottelo.cli.factory import make_org
from robottelo.cli.product import Product
from robottelo.cli.repository_set import RepositorySet
from robottelo.cli.subscription import Subscription
from robottelo import manifests
from robottelo.constants impor... | nization-id': org['id'],
u'product-id': product_id,
})
enabled = [
repo['enabled']
for repo
in result
if repo['arch'] == 'x86_64' and repo['release'] == '6Server'
][0]
self.assertEqual(enabled, 'true')
def test_repositoryse... | """@Test: Disable repo from reposet by names of reposet, org and
product
@Feature: Repository-set
@Assert: Repository was disabled
"""
org = make_org()
manifest = manifests.clone()
upload_file(manifest, remote_file=manifest)
Subscription.upload({
... |
nisse3000/pymatgen | pymatgen/io/qchem_io/sets.py | Python | mit | 7,003 | 0.000857 | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
import logging
from pymatgen.core import Molecule
from pymatgen.io.qchem_io.inputs import QCInput
from pymatgen.io.qchem_io.utils import lower_and_check_unique
# Classes for reading/manipulating/writing QChem ... | s.
__author__ = "Samuel Blau, Br | andon Wood, Shyam Dwaraknath"
__copyright__ = "Copyright 2018, The Materials Project"
__version__ = "0.1"
logger = logging.getLogger(__name__)
class QChemDictSet(QCInput):
"""
Build a QCInput given all the various input parameters. Can be extended by standard implementations below.
"""
def __init__(... |
tasleson/targetd | targetd/nfs.py | Python | gpl-3.0 | 10,459 | 0.000191 | # 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 hope that it will be useful,
# bu... | eturn "%s %s(%s)\n" % (Export._double_quote_space(self.path),
| self.host, self.options_string())
@staticmethod
def _chr_encode(s):
# Replace octal values, the export path can contain \nnn in the
# export name.
p = re.compile(Export.octal_nums_regex)
for m in re.finditer(p, s):
s = s.replace('\\' ... |
santisiri/popego | envs/ALPHA-POPEGO/lib/python2.5/site-packages/SQLAlchemy-0.4.0-py2.5.egg/sqlalchemy/__init__.py | Python | bsd-3-clause | 1,324 | 0.001511 | # __init__.py
# Copyright (C) 2005, 2006, 2007 Michael Bayer mike_mp@zzzcomputing.com
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
import inspect
from sqlalchemy.types import \
BLOB, BOOLEAN, CHAR, CLOB, DATE, DATETIME, DECIMAL, F... | SmallInteger, String, Time, Unicode
from sqlalchemy.sql import \
func, modifier, text, literal, literal_column, null, alias, | \
and_, or_, not_, \
select, subquery, union, union_all, insert, update, delete, \
join, outerjoin, \
bindparam, outparam, asc, desc, \
except_, except_all, exists, intersect, intersect_all, \
between, case, cast, distinct, extract
from sqlalchemy.schema import \
MetaData, ThreadLocalMetaDa... |
animesh0353/codelibrary | python/pow.py | Python | unlicense | 198 | 0.005051 | def pow(a, b, mod):
res = 1
while b > 0:
if b & 1 != 0:
| res = res * a % mod
a = | a * a % mod
b >>= 1
return res
print(1024 == pow(2, 10, 1000000007))
|
chengduoZH/Paddle | python/paddle/fluid/contrib/slim/nas/lock.py | Python | apache-2.0 | 1,215 | 0 | # Copyright (c) 2019 PaddlePaddle 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 appli... | istributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
__All__ = ['lock', 'unlock']
if os.name == 'nt':
def lock(fil | e):
raise NotImplementedError('Windows is not supported.')
def unlock(file):
raise NotImplementedError('Windows is not supported.')
elif os.name == 'posix':
from fcntl import flock, LOCK_EX, LOCK_UN
def lock(file):
"""Lock the file in local file system."""
flock(file.filen... |
prithvinambiar/tensor_network | tensor_network/__init__.py | Python | mit | 166 | 0 | # - | *- coding: utf-8 -*-
"""Top-level package for tensor_network."""
__author__ = """Prithvi Nambiar"""
__email__ = 'prithvinambiar@gmail.com'
__version__ = '0.1.0 | '
|
odlgroup/odl | examples/tomo/backends/astra_performance_cuda_parallel_2d_cg.py | Python | mpl-2.0 | 2,904 | 0 | """Performance example of running native ASTRA vs using ODL for reconstruction.
In this example, a 512x512 image is reconstructed using the Conjugate Gradient
Least Squares method on the GPU.
In general, ASTRA is faster than ODL since it does not need to perform any
copies and all arithmetic is performed on the GPU. ... | overhead is about 60 %, depending on | the
hardware used.
"""
import astra
import numpy as np
import matplotlib.pyplot as plt
import scipy.misc
import odl
from odl.util.testutils import timer
# Common geometry parameters
domain_size = np.array([512, 512])
n_angles = 180
det_size = 362
niter = 50
phantom = np.rot90(scipy.misc.ascent().astype('float'), -1... |
0atman/flask-admin | examples/quickstart/second.py | Python | bsd-3-clause | 272 | 0.003676 | from flask import Flas | k
from flask.ext.admin import Admin, BaseView, expose
class MyView(BaseView):
@expose('/')
def index(self):
return self.render('index.html')
app = Flask(__name__)
admin = Admin(app)
admin.add_view(MyView(name='Hello | '))
app.run()
|
whymirror/unholy | python/Kernel.py | Python | mit | 281 | 0.042705 | class Proc:
def __init__(self, code):
self.code = | code
def call(self, *args):
return eval(self.code, dict(zip(self.code.co_varnames, args)))
def proc(func):
return Proc(func)
def puts(*args):
for x in args: print x
if no | t args: print
class BasicObject:
pass
|
gammu/python-gammu | examples/batteryinfo.py | Python | gpl-2.0 | 1,237 | 0 | #!/usr/bin/env python
# vim: expandtab sw=4 ts=4 sts=4:
#
# Copyright © 2003 - 2018 Michal Čihař <michal@cihar.com>
#
# This file is part of python-gammu <https://wammu.eu/python-gammu/>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as pu... |
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
import sys
import gammu
state_machine = gammu.StateMachine()
if len(sys.argv) > 2:
state_machine.Re... | sys.argv[1])
del sys.argv[1]
else:
state_machine.ReadConfig()
state_machine.Init()
status = state_machine.GetBatteryCharge()
for x in status:
if status[x] != -1:
print(f"{x:20}: {status[x]}")
|
rodynnz/python-tfstate | src/tfstate/exceptions.py | Python | lgpl-3.0 | 144 | 0 | # -*- coding: utf-8 -*-
clas | s InvalidResource(E | xception):
"""
Raised when try to create a Resource with invalid data
"""
pass
|
dsweet04/rekall | rekall-core/rekall/plugins/darwin/networking.py | Python | gpl-2.0 | 13,974 | 0 | # Rekall Memory Forensics
#
# Copyright 2013 Google Inc. All Rights Reserved.
#
# 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 v... | nfo_arp_zone, Z_EXPAND, TRUE);
zone_change(llinfo_arp_zone, Z_CALLERACCT, FALSE);
arpinit_done = 1;
}
Disassembled, the first few instructions look like this:
0x0 55 | PUSH RBP
0x1 4889e5 MOV RBP, RSP
0x4 803d65e9400001 CMP BYTE [RIP+0x40e965], 0x1
0xb 7518 JNZ 0xff80090a7f95
0xd 488d3dee802900 LEA RDI, [RIP+0x2980ee]
0x14 488d35f5802900 LEA RSI, [RIP+0x2980f5]
0x1b baf3000000 MOV EDX, 0xf3
... |
django-cratis/cratis | tests/_markers.py | Python | bsd-2-clause | 131 | 0.007634 | import pytest
slow = pytest.mark.skipif(
no | t pytes | t.config.getoption("--runslow"),
reason="need --runslow option to run"
) |
TheTimmy/spack | var/spack/repos/builtin/packages/isl/package.py | Python | lgpl-2.1 | 1,805 | 0.000554 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | s and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Les | ser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class Isl(AutotoolsPackage):
"""isl (Integer Set Lib... |
lmr/avocado-vt | virttest/qemu_monitor.py | Python | gpl-2.0 | 92,751 | 0.000442 | """
Interfaces to the QEMU monitor.
:copyright: 2008-2010 Red Hat Inc.
"""
from __future__ import division
import socket
import time
import threading
import logging
import select
import re
import os
import six
try:
import json
except ImportError:
logging.warning("Could not import json module. "
... | '%s'" % self.monitor_name
class MonitorSocketError | (MonitorError):
def __init__(self, msg, e):
Exception.__init__(self, msg, e)
self.msg = msg
self.e = e
def __str__(self):
return "%s (%s)" % (self.msg, self.e)
class MonitorLockError(MonitorError):
pass
class MonitorProtocolError(MonitorError):
pass
class Monit... |
lukecwik/incubator-beam | learning/katas/python/test_helper.py | Python | apache-2.0 | 6,995 | 0.001287 | # 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"); y... | window_text = line[len(prefix):]
else:
window_text += line
if window_text:
windows.append(window_text.strip()) |
f.close()
return windows
def check_samples(samples=()):
"""
Check script output for all samples. Sample is a two element list, where the first is input and
the second is output.
"""
for sample in samples:
if len(sample) == 2:
output = get_file_output(arg_string=st... |
StephenPower/CollectorCity-Market-Place | stores/apps/store_admin/views.py | Python | apache-2.0 | 46,221 | 0.009281 | import logging
import datetime
import urllib
from django.core.mail import send_mail, EmailMessage
from django.core.urlresolvers import reverse
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.conf import settings
from django.db.models import Q
from django.http import HttpResponse, HttpRe... | esponse( | 'store_admin/customers/sold_items.html', params, RequestContext(request))
@shop_admin_required
def customers_payments(request):
return render_to_response('store_admin/customers/payments.html', {},
RequestContext(request))
@shop_admin_required
def customers_shipments(request):
... |
googleapis/python-binary-authorization | samples/generated_samples/binaryauthorization_v1beta1_generated_binauthz_management_service_v1_beta1_get_attestor_async.py | Python | apache-2.0 | 1,601 | 0.002498 | # -*- 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 at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under... | overning permissions and
# limitations under the License.
#
# Generated code. DO NOT EDIT!
#
# Snippet for GetAttestor
# NOTE: This snippet has been automatically generated for illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, ... |
Tatsh-ansible/ansible | lib/ansible/modules/messaging/rabbitmq_parameter.py | Python | gpl-3.0 | 4,458 | 0.002019 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2013, Chatham Financial <oss@chathamfinancial.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version'... | XAMPLES = """
# Set the federation parameter 'local_username' to a value o | f 'guest' (in quotes)
- rabbitmq_parameter:
component: federation
name: local-username
value: '"guest"'
state: present
"""
import json
from ansible.module_utils.basic import AnsibleModule
class RabbitMqParameter(object):
def __init__(self, module, component, name, value, vhost, node):
sel... |
mykonosbiennale/mykonosbiennale.github.io | filmfestival/models.py | Python | apache-2.0 | 13,267 | 0.011231 | from django.db import models
from django_countries.fields import CountryField
from django.utils.text import slugify
from django.core.urlresolvers import reverse
from phonenumber_field.modelfields import PhoneNumberField
import os,datetime
from uuid import uuid4
from imagekit.models import ImageSpecField
from imagekit.... | elta(minutes=previous_screening.film.runtime+previous_screening.pause)
else:
self.start_time = datetime.datetime.combine(self.day.date, self.day.start_time)
def save(self, *args, **kwargs):
self.slug = slugify(str(self))
if self.id is None:
self.schedule(self.day... | lm(models.Model):
class Meta:
ordering = ['ref']
DRAMATIC_NIGHTS = 'Dramatic Nights'
VIDEO_GRAFITTI = 'Video Grafitti'
DANCE = 'Dance'
DOCUMENTARY = 'Documentary'
FILM_TYPES_CHOICES = (
(DRAMATIC_NIGHTS, 'Dramatic Nights'),
(VIDEO_GRAFITTI, 'Video Graffiti'),
(DAN... |
ramusus/django-vkontakte-places | vkontakte_places/factories.py | Python | bsd-3-clause | 328 | 0 | from m | odels import City, Country
import factory
class CityFactory(factory.DjangoModelFactor | y):
remote_id = factory.Sequence(lambda n: n + 1)
class Meta:
model = City
class CountryFactory(factory.DjangoModelFactory):
remote_id = factory.Sequence(lambda n: n + 1)
class Meta:
model = Country
|
ohsu-computational-biology/server | ga4gh/datamodel/genotype_phenotype_featureset.py | Python | apache-2.0 | 12,563 | 0.00008 | """
Module responsible for translating g2p data into GA4GH native
objects.
"""
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import bisect
import rdflib
from rdflib import RDF
import ga4gh.protocol as protocol
import ga4gh.datamodel.sequenceAnnotations a... | tinue
feature = self._getFeatureById(featureId)
# get _getFeatureById returns native id, cast to compound
| feature.id = self.getCompoundIdForFeatureId(feature.id)
if nextPageToken < featuresCount - 1:
nextPageToken += 1
else:
nextPageToken = None
yield feature, (
str(nextPageToken)
if nextPageToken is not None else Non... |
JWageM/planet-wars | bots/smt/kb.py | Python | mit | 19,880 | 0.002968 | import sys
import numpy as np
import scipy.optimize as opt
class Symbol(object):
"""
A class representing a single unit in the boolean SAT problem. This can either refer to an atomic boolean, or a
constraint based on integer variables
"""
pass
class Boolean(Symbol):
def __init__(self, name):
... | lass Integer(IntSymbol):
def __init__(self, name, mult = 1):
"""
:rtype: object
"""
self.__name = name
self.__mult = mult
def name(self):
return self.__name
def mult(self):
return self.__mult
def __neg__(self):
return Integer(self.name... |
def __hash__(self):
return hash(self.name())
def __mul__(self, other):
if not isinstance(other, int):
raise ValueError('Can only multiply number symbol by int.')
return Integer(self.__name, other)
__rmul__ = __mul__
def __repr__(self):
if self.__mult == 1... |
LBatsoft/python3-webapp | www/coroweb.py | Python | gpl-3.0 | 6,284 | 0.003819 | # !/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "pwxc"
import asyncio, os, inspect, logging, functools
from urllib import parse
from aiohttp import web
from apis import APIError
def get(path):
"""
Define decorator @get('/path')
"""
def decorator(func):
@functools.wraps(func)
... | e, globals(), locals())
else:
name = module_name[n+1:]
mod = getattr(__import__(module_n | ame[:n], globals(), locals(), [name]), name)
for attr in dir(mod):
if attr.startswith('_'):
continue
fn = getattr(mod, attr)
if callable(fn):
method = getattr(fn, '__method__', None)
path = getattr(fn, '__route__', None)
if method and path:
... |
youtube/cobalt | third_party/llvm-project/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-advanced/TestDataFormatterAdv.py | Python | bsd-3-clause | 11,243 | 0.00169 | """
Test lldb data formatter subsystem.
"""
from __future__ import print_function
import os
import time
import lldb
from lldbsuite.test.lldbtest import *
import lldbsuite.test.lldbutil as lldbutil
class AdvDataFormatterTestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
def setUp(self):
... | Cmd(
'type summary add --summary-string "${var[].integer}" "i_am_cool[]')
self.expect("frame variable cool_array",
| substrs=['1,1,1,1,6'])
self.runCmd("type summary clear")
self.runCmd(
"type summary add --summary-string \"${var[1-0]%x}\" \"int\"")
self.expect("frame variable iAmInt",
substrs=['01'])
self.runCmd(
"type summary add --summary-string \... |
mila-udem/fuel | fuel/config_parser.py | Python | mit | 7,045 | 0 | """Module level configuration.
Fuel allows module-wide configuration values to be set using a YAML_
configuration file and `environment variables`_. Environment variables
override the configuration file which in its turn overrides the defaults.
The configuration is read from ``~/.fuelrc`` if it exists. A custom
confi... | set. By default none
is set and an error is raised instead.
env_var : str, optional
The environment variable name that holds this configuration
value. If not given, | this configuration can only be set in the
YAML configuration file.
"""
self.config[key] = {'type': type_}
if env_var is not None:
self.config[key]['env_var'] = env_var
if default is not NOT_SET:
self.config[key]['default'] = default
config = Configu... |
LICEF/edx-platform | common/lib/xmodule/xmodule/modulestore/tests/persistent_factories.py | Python | agpl-3.0 | 3,589 | 0.003622 | """Provides factories for Split."""
from xmodule.modulestore import ModuleStoreEnum
from xmodule.course_module import CourseDescriptor
from xmodule.x_module import XModuleDescriptor
import factory
from factory.helpers import lazy_attribute
from opaque_keys.edx.keys import UsageKey
# Factories don't have __init__ method... | = XModuleDescriptor
display_name = factory.LazyAttributeSequence(lambda o, n: "{} {}".format(o.category, n))
# pylint: disable=W0613
@classmethod
def _create(cls, target_class, parent_location, category='ch | apter',
user_id=ModuleStoreEnum.UserID.test, definition_locator=None, force=False,
continue_version=False, **kwargs):
"""
passes *kwargs* as the new item's field values:
:param parent_location: (required) the location of the course & possibly parent
:par... |
yaunj/hogments | hogments/hog.py | Python | bsd-2-clause | 4,940 | 0.001014 | #!/usr/bin/env python
# coding: utf-8
#
# License: BSD; see LICENSE for more details.
from pygments.lexer import RegexLexer, include, bygroups
import pygments.token as t
class SnortLexer(RegexLexer):
name = 'Snort'
aliases = ['snort', 'hog']
filenames = ['*.rules']
tokens = {
'root': [
... | p|udp|icmp|ip)', t.Keyword.Constant),
(r'\b(hex|dec|oct|string|type|output|any|engine|soid|service|'
r'norm|raw|relative|bytes|big|little|align|invalid-entry|'
r'enable|disable|client|server|both|either|printable|binary|'
r'all|session|host|packets|seconds|bytes|src|ds... | ode|bare_byte|ascii|iis_encode|bitstring_overflow|'
r'double_overflow|oversize_length|absolute_offset|'
r'relative_offset|rr|eol|nop|ts|sec|esec|lsrr|lsrre|'
r'ssrr|satid|to_client|to_server|from_client|from_server|'
r'established|not_established|stateless|no_stream|o... |
lzw120/django | django/core/files/base.py | Python | bsd-3-clause | 4,071 | 0.000737 | import os
from io import BytesIO
from django.utils.encoding import smart_str, smart_unicode
from django.core.files.utils import FileProxyMixin
class File(FileProxyMixin):
DEFAULT_CHUNK_SIZE = 64 * 2**10
def __init__(self, file, name=None):
self.file = file
if name is None:
name = ... | return "<%s: %s>" % (self.__class__.__name__, self or "None")
def __nonzero__(self):
return bool(self.name)
def __len__(self):
return self.size
def _get_size(self):
if not hasattr(self, '_size'):
if hasattr(self.file, 'size'):
self._size = self.file.... | f.file, 'tell') and hasattr(self.file, 'seek'):
pos = self.file.tell()
self.file.seek(0, os.SEEK_END)
self._size = self.file.tell()
self.file.seek(pos)
else:
raise AttributeError("Unable to determine the file's size.")
r... |
kaisero/fxosREST | fxos.py | Python | gpl-3.0 | 14,707 | 0.002108 | import json
import requests
import copy
from requests.exceptions import ConnectionError
from distutils.version import LooseVersion
requests.packages.urllib3.disable_warnings()
HEADERS = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'User-Agent': 'fxosREST'
}
class FXOSApiException... | self.timeout = timeout
self.headers = copy.copy(HEADERS)
se | lf.headers['token'] = self._login()
def _login(self):
try:
request_url = '{0}{1}'.format(self._url(), self.auth_url)
request_headers = copy.copy(HEADERS)
request_headers['USERNAME'] = self.username
request_headers['PASSWORD'] = self.password
respo... |
runn1ng/python-trezor | tests/test_msg_signtx.py | Python | lgpl-3.0 | 49,207 | 0.007153 | import unittest
import common
import binascii
import itertools
import trezorlib.messages_pb2 as proto
import trezorlib.types_pb2 as proto_types
from trezorlib.client import CallException
from trezorlib.tx_api import TXAPITestnet
class TestMsgSigntx(common.TrezorTest):
def test_one_one_fee(self):
self.setu... | ex=0)),
| proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)),
proto.TxRequest(request_type=proto_types.TXFINISHED),
])
(signatures, serialized_tx) = self.client.sign_tx('Bitcoin', [inp1, ], [out1, ])
# Accepted ... |
whip112/Whip112 | kuma/wiki/tests/test_models.py | Python | mpl-2.0 | 75,272 | 0.000292 | from cStringIO import StringIO
from datetime import date, datetime, timedelta
import json
import time
from xml.sax.saxutils import escape
import mo | ck
f | rom nose.tools import eq_, ok_
from nose.plugins.attrib import attr
from nose import SkipTest
from django.conf import settings
from django.core.exceptions import ValidationError
from constance import config
from waffle.models import Switch
from kuma.core.exceptions import ProgrammingError
from kuma.core.tests import... |
nimbusproject/epumgmt | src/python/tests/test_epumgmt_defaults_cloudinitd_load.py | Python | apache-2.0 | 3,064 | 0.001958 | import os
import types
import tempfile
import ConfigParser
from cloudinitd.user_api import CloudInitD
import epumgmt.defaults.cloudinitd_load
import epumgmt.main.em_args as em_args
from epumgmt.api.exceptions imp | ort ProgrammingError, IncompatibleEnvironment
from epumgmt.defaults.runlogs import DefaultRunlogs
from epumgmt.defaults.parameters import DefaultParameters
from mocks.common import FakeCommon
from mocks.modules import FakeModules
from mocks.modules import make_fake_scp_command_str
from mocks.remote_svc_adapter import ... | ers cloudinit.d plan.
We can grab all logged messages from c.log.transcript.
"""
self.test_run_name = "TESTRUN"
self.config = ConfigParser.RawConfigParser()
self.config.add_section("events")
self.runlogdir = tempfile.mkdtemp()
self.config.set("events", "runlogd... |
eunchong/build | scripts/slave/recipe_modules/commit_position/api.py | Python | bsd-3-clause | 2,897 | 0.009665 | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this so | urce code is governed by a BSD-style license that can be
# found in the LICENSE file.
import re
from recipe_engine import recipe_a | pi
class CommitPositionApi(recipe_api.RecipeApi):
"""Recipe module providing commit position parsing and manipulation."""
RE_COMMIT_POSITION = re.compile('(?P<branch>.+)@{#(?P<revision>\d+)}')
COMMIT_POS_STR = '^Cr-Commit-Position: refs/heads/master@{#%d}'
@classmethod
def parse(cls, value):
match = cl... |
glebkuznetsov/nucleic | nucleic/seq/__init__.py | Python | mit | 337 | 0.002967 | '''
nucleic.seq
Modules related to the creation and manupulation of DNA and RNA sequence
strings, including compact encoding schemes.
'''
from barcode import BarcodeGenerator
|
import binary
from manip | import reverse, complement, reverse_complement
# Space efficient abbreviations
r = reverse
c = complement
rc = reverse_complement
|
liuzzfnst/tp-libvirt | libguestfs/tests/guestmount.py | Python | gpl-2.0 | 2,688 | 0 | import logging
import os
from autotest.client.shared import error, utils
from virttest import data_dir, utils_test
def umount_fs(mountpoint):
if os.path.ismount(mountpoint):
result = utils.run("umount -l %s" % mountpoint, ignore_status=True)
if result.exit_status:
logging.debug("Umount... | et("gm_mount", "no")
vt = utils_test.libguestfs.VirtTools(vm, params)
vm_ref = params.get("gm_vm_ref")
is_disk = "yes" == params.get("gm_is_disk", "no")
# Automatically get disk if no disk specified.
if is_disk and vm_ref is None:
vm_ref = utils_test.libguestfs.get_primary_disk(vm)
if s... | ")
params['gf_inspector'] = True
gf = utils_test.libguestfs.GuestfishTools(params)
roots, rootfs = gf.get_root()
gf.close_session()
if roots is False:
raise error.TestError("Can not get root filesystem "
"in guestfish before test")
... |
dyf102/Gomoku-online | client/controller/chat_controller.py | Python | apache-2.0 | 3,149 | 0.000953 |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import logging
from PyQt4.QtCore import SIGNAL, QString
from basecontroller import BaseController, singleton
# from user_controller import UserController
# sys.path.append('../')
from util.util import print_trace_exception, log_callback
SEND_MSG_ID = 'SEND_... | # logging.debug('send_msg %s', data)
self.emit(SIGNAL("send_msg_callback(int)"), data['code'])
def get_msg(self, cid, uid):
logging.debug('Call get msg %d %d', cid, uid)
client = self.get_client()
req = {
'cid': cid,
'uid': uid
}
| client.send(service_name=SERVICE_NAME, method=GET_MSG_ID, msg=req)
@log_callback
def get_msg_cb(self, data):
if data and data.get('code') == 200:
token = data.get('token')
cid = data.get('cid')
if cid is None:
logging.debug("received %s", data)
... |
dashea/redhat-upgrade-tool | redhat_upgrade_tool/upgrade.py | Python | gpl-2.0 | 9,234 | 0.003357 | # upgrade.py - test the upgrade transaction using RPM
#
# Copyright (C) 2012 Red Hat Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option)... | )]
# If there is no handler for a type of problem, just return the
# rpmProblemString result for the problems
class GenericProblemSummary(ProblemSummary):
def format_details(self):
retur | n [str(p) for p in self.problems]
probsummary = { rpm.RPMPROB_DISKSPACE: DiskspaceProblemSummary,
rpm.RPMPROB_REQUIRES: DepProblemSummary,
}
def summarize_problems(problems):
summaries = []
for t in set(p.type for p in problems):
summarize = probsummary.get(t, GenericPr... |
eduNEXT/edunext-platform | cms/djangoapps/contentstore/tests/test_course_create_rerun.py | Python | agpl-3.0 | 8,047 | 0.001491 | """
Test view handler for rerun (and eventually create)
"""
import datetime
import ddt
from django.test import override_settings
from django.test.client import RequestFactory
from django.urls import reverse
from opaque_keys.edx.keys import CourseKey
from organizations.api import add_organization, get_course_organiza... | e_end - datetime.timedelta(days=14)
| source_course = CourseFactory.create(
org='origin',
number='the_beginning',
run='first',
display_name='the one and only',
start=self.course_start,
end=self.course_end,
enrollment_start=self.enrollment_start,
enrollment_end... |
Rondineli/django-sso | django_sso/accounts/migrations/0003_auto__add_field_user_is_admin.py | Python | gpl-2.0 | 5,064 | 0.008294 | # -*- 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):
# Adding field 'User.is_admin'
db.add_column(u'accounts_user', 'is_admin',
self.gf('dj... | ow': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'db_index': ' | True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'phone': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True'}),
'team': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True'})
},
... |
jparyani/pycapnp | examples/addressbook.py | Python | bsd-2-clause | 1,591 | 0 | #!/usr/bin/env python3
import capnp # noqa: F401
import addressbook_capnp
def writeAddressBook(file):
addresses = addressbook_capnp.AddressBook.new_message()
people = addresses.init("people", 2)
alice = people[0]
alice.id = 123
alice.name = "Alice"
alice.email = "alice@example.com"
ali... | :", phone.number)
which = person.employment.which()
print(which)
if which == "unemployed":
pri | nt("unemployed")
elif which == "employer":
print("employer:", person.employment.employer)
elif which == "school":
print("student at:", person.employment.school)
elif which == "selfEmployed":
print("self employed")
print()
if __name__ == "__main__":
... |
QISKit/qiskit-sdk-py | qiskit/transpiler/passes/depth.py | Python | apache-2.0 | 812 | 0 | # -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of | this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
""" An analysis pass for calculating the depth of a DAG c... | t AnalysisPass
class Depth(AnalysisPass):
""" An analysis pass for calculating the depth of a DAG circuit.
"""
def run(self, dag):
self.property_set['depth'] = dag.depth()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.