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 |
|---|---|---|---|---|---|---|---|---|
jpoullet2000/cgs-data | cgsdatatools/cgs_generate_config.py | Python | apache-2.0 | 6,484 | 0.016965 | import yaml
import sys
import os
help = """
Converts two .csv files into YAML configuration files. This program requires three arguments:
-The path to the .csv table of VCF fields
-The path to the .csv table of the MySQL clinical database fields
-The destination path where YAML files will be generated
The... | l_file = sys.argv[2]
if os.path.isfile(mysql_file):
dest_path = sys.argv[3]
if os.path.isdir(dest_path):
cgs_make_mapping(vcf_in_db,dest_path)
cgs_make_MySQL(mysql_file,dest_path)
else:
print "The des... | else:
print "The path to the table of the MySQL clinical database fields is incorrect."
print arg_error
else:
print "The path to the table of VCF fields is incorrect."
print arg_error
|
ishan-marikar/hexchat-scripts | twitch-title.py | Python | mit | 3,820 | 0.001832 | #!/usr/bin/env python3
import requests
import sys
import threading
import hexchat
__module_name__ = "Twitch Title"
__module_author__ = "PDog"
__module_version__ = "0.1"
__module_description__ = "Display stream status and description for TwitchTV streams"
# TODO: Clean up thread handling <PDog>
# TODO: Figure out why ... |
def set_topic(self):
"""
Set the channel topic (no formatting) and print the topic locally with formatting
"""
msg = "\00318{0}\00399 - {1} | Now | playing: \00318{2}\00399 | {3}"\
.format(self.display_name, self.status, self.game, self.title)
hexchat.prnt(msg)
# HexChat doesn't support hiding characters in the topic bar (Windows), so strip the formatting until it's fixed
if sys.platform == "win32":
msg = hexchat.str... |
WhySoGeeky/DroidPot | venv/lib/python2.7/site-packages/sphinx/builders/qthelp.py | Python | mit | 10,789 | 0.000093 | # -*- coding: utf-8 -*-
"""
sphinx.builders.qthelp
~~~~~~~~~~~~~~~~~~~~~~
Build input files for the Qt collection generator.
:copyright: Copyright 2007-2015 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import os
import re
import codecs
import posixpath
from os impo... | nspace = re.sub('[^a-zA-Z0-9.]', '', nspace)
nspace = re.sub(r'\.+', '.', nspace).strip('.')
nspace = nspace.lower()
# write the project file
| f = codecs.open(path.join(outdir, outname+'.qhp'), 'w', 'utf-8')
try:
f.write(project_template % {
'outname': htmlescape(outname),
'title': htmlescape(self.config.html_title),
'version': htmlescape(self.config.version),
'project... |
Roasbeef/seneca | python-bitcoinlib/bitcoin/bloom.py | Python | unlicense | 5,793 | 0.002589 |
#
# bloom.py
#
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
"""Bloom filter support"""
from __future__ import absolute_import, division, print_function, unicode_literals
import struct
import sys
import math
import bit... | eed, vDataToHash):
"""MurmurHash3 (x86_32)
Used for bloom filters. See http://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp
"""
assert nHashSeed | <= 0xFFFFFFFF
h1 = nHashSeed
c1 = 0xcc9e2d51
c2 = 0x1b873593
# body
i = 0
while i < len(vDataToHash) - len(vDataToHash) % 4 \
and len(vDataToHash) - i >= 4:
k1 = struct.unpack(b"<L", vDataToHash[i:i+4])[0]
k1 = (k1 * c1) & 0xFFFFFFFF
k1 = ROTL32(k1, 15)
... |
RedHatInsights/insights-core | insights/parsers/tests/test_package_provides_java.py | Python | apache-2.0 | 1,183 | 0.002536 | from insights.parsers.package_provides_java import PackageProvidesJava
from insights.tests import context_wrap
from ...parsers import ParseException, SkipException
import pytest
PACKAGE_COMMAND_MATCH = """
/usr/lib/jvm/jre/bin/java java-1.8.0-openjdk-headless-1.8.0.141-3.b16.el6_9.x86_64
"""
PACKAGE_COMMAND_ERROR = "... | PackageProvidesJava(context_wrap(PACKAGE_COMMAND_ERROR))
assert "there is not java application running" in str(pe)
def test_package_provides_java_not_match():
with py | test.raises(SkipException) as pe:
PackageProvidesJava(context_wrap(PACKAGE_COMMAND_NOT_MATCH))
assert "current running java command is not provided by package installed through yum or rpm" in str(pe)
|
eliuha/pyIsraeliId | pyIsraeliId/checker.py | Python | apache-2.0 | 605 | 0 | __author__ = 'Ilya Chernyakov'
__alias__ = 'eliuha'
# Shalom everybody !
def validate_israeli_id_number(iID):
iID = str(iID)
| if len(iID) == 8:
iID = '0' + str(iID)
if len(iID) != 9:
return False
num_12_arr = [1, 2, 1, 2, 1, 2, 1, 2, 1]
dig = list(int(d) for d in str(iID))
sum_of_digits = 0
for i in range(0, 9):
temp = num_12_arr[i] * dig[i]
| if temp > 9:
t = list(int(d_1) for d_1 in str(temp))
temp = t[0] + t[1]
sum_of_digits += temp
if sum_of_digits % 10 != 0:
return False
return True
|
limscoder/amfast | tests/speed_test.py | Python | mit | 10,975 | 0.003827 | import optparse
from timeit import Timer
try:
import pyamf
from pyamf.util import BufferedByteStream
use_pyamf = True
except ImportError:
use_pyamf = False
from amfast.context import DecoderContext, EncoderContext
import amfast.encode as encode
import amfast.decode as decode
import amfast.class_def as... | tester = SpeedTestCase()
tests = [
{'test': tester.simple, 'label': 'AMF0 Encode Simple',
'args': [], 'kwargs': {'decode': False, 'amf3': False, 'pyamf': False}},
{'test': te | ster.simple, 'label': 'AMF0 Encode/Decode Simple',
'args': [], 'kwargs': {'decode': True, 'amf3': False, 'pyamf': |
bp-kelley/rdkit | rdkit/Chem/test_data/BuildDescrsTestSet.Crippen.py | Python | bsd-3-clause | 1,551 | 0.016119 |
from rdkit import RDConfig
import os.path
import pickle
from rdkit import Chem
from rdkit.Chem import Descriptors
descrs = ['SMR_VSA1', 'SMR_VSA10', 'SMR_VSA2', 'SMR_VSA3', 'SMR_VSA4', 'SMR_VSA5', 'SMR_VSA6',
'SMR_VSA7', 'SMR_VSA8', 'SMR_ | VSA9', 'SlogP_VSA1', 'SlogP_VSA10', 'SlogP_VSA11',
'SlogP_VSA12', 'SlogP_VSA2', 'SlogP_VSA3', 'SlogP_VSA5', 'SlogP_VSA6', 'SlogP_VSA7',
'SlogP_VSA8', 'SlogP_VSA9']
def runIt(inFileName, outFileName, smiCol=0, maxMols=-1, delim=','):
outF = | open(outFileName, 'w+')
outF.write('#' + ','.join(['SMILES'] + descrs))
outF.write('\n')
mols = []
nDone = 0
for line in inD:
if line[0] != '#':
splitL = line.strip().split(delim)
if not splitL:
continue
smi = splitL[smiCol].strip()
mol = Chem.MolFromSmiles(smi)
prin... |
btubbs/spa | spa/gzip_util.py | Python | bsd-3-clause | 2,754 | 0.001452 | import zlib
import struct
import time
def parse_encoding_header(header):
"""
Break up the `HTTP_ACCEPT_ENCODING` header into a dict of the form,
{'encoding-name':qvalue}.
"""
encodings = {'identity':1.0}
for encoding in header.split(","):
if(encoding.find(";") > -1):
encodi... | >= encodings['identity']
else:
return False
# After much Googling and gnashing of teeth, this function stolen from
# cherrypy.lib.encoding seems to be the most straightforward way to do gzip
# encoding of a stream withou | t loading the whole thing into memory at once.
def compress(chunks, compress_level, close=True):
"""
Compress 'chunks' at the given compress_level, where 'chunks' is an iterable
over chunks of bytes. If close=True, then look for .close() method on chunks
and call that when done iterating.
"""
t... |
SGenheden/Scripts | Gromacs/gmx_density_groups.py | Python | mit | 1,390 | 0.029496 | # Author: Samuel Genheden samuel.genheden | @gmail.com
"""
Program to make a Gromacs ndx-file from
a configuration file of atom groups and
snapshot
"""
import argparse
from sgenlib import | pdb
from sgenlib import groups
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Program make density group files")
parser.add_argument('-f','--file',help="the input gro-file")
parser.add_argument('-g','--groups',help="the group definitions")
parser.add_argument('-o','--out',help="the ... |
anhstudios/swganh | data/scripts/templates/object/tangible/deed/faction_perk/hq/shared_hq_s04_pvp.py | Python | mit | 449 | 0.046771 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPRO | PERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object impo | rt *
def create(kernel):
result = Tangible()
result.template = "object/tangible/deed/faction_perk/hq/shared_hq_s04_pvp.iff"
result.attribute_template_id = 2
result.stfName("deed","hq_s04_pvp")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
remind101/stacker | stacker/lookups/handlers/hook_data.py | Python | bsd-2-clause | 686 | 0 | from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from . import LookupHandler
TYPE_NAME = "hook_data"
class HookDataLookup(LookupHandler):
@classmethod
def handle(cls, | value, context, **kwargs):
"""Returns the value of a key for a given hook in hook_d | ata.
Format of value:
<hook_name>::<key>
"""
try:
hook_name, key = value.split("::")
except ValueError:
raise ValueError("Invalid value for hook_data: %s. Must be in "
"<hook_name>::<key> format." % value)
return... |
Cadasta/cadasta-test | cadasta/test/permission_tests/test_anonymous_user_permissions.py | Python | agpl-3.0 | 1,231 | 0 | import pytest
from ..base_test import SeleniumTestCase
from ..entities import Project, Organization
pytestmark = pytest.mark.skip
class AnonymousUserOrganizationView(SeleniumTestCase):
def test_anonymous_user_project_view(self):
self.open("")
self.wd.wait_for_css(".organizations")
self.... | self.open("")
self.wd.wait_for_css(".projects")
self.wd.find_element_by_link_text("Projects").click()
self.wd.wait_for_xpath("//h1[contains(text(), 'Projects')]")
self.wd.find_element_by_link_text(Project.get_test_proj_name()).click()
self.wd.wait_for_xpa | th("//h2[contains(text(), 'Project Overview')]")
assert self.wd.wait_for_xpath("//*[contains(text(), 'Sign in')]")
|
dims/neutron | neutron/db/migration/alembic_migrations/versions/mitaka/expand/32e5974ada25_add_neutron_resources_table.py | Python | apache-2.0 | 1,390 | 0.001439 | #
# 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
# ... | vision = '32e5974ada25'
down_revision = '13cfb89f881a'
from alembic import op
import sqlalchemy as sa
TABLES = ('ports', 'networks', 'subnets', 'subnetpools', 'securitygroups',
'floatingips', 'routers', 'securitygrouprules')
def upg | rade():
op.create_table(
'standardattributes',
sa.Column('id', sa.BigInteger(), autoincrement=True),
sa.Column('resource_type', sa.String(length=255), nullable=False),
sa.PrimaryKeyConstraint('id')
)
for table in TABLES:
op.add_column(table, sa.Column('standard_attr_i... |
TheRedFireFox/AnimeSubBot | src/worker.py | Python | gpl-2.0 | 14,016 | 0.014769 | #!/usr/bin/env python3.4
# -*- coding: utf-8 -*-
import time
import queue
import multiprocessing
import multiprocessing.managers
import sql
import gobjects
import telegram
import messages.save_sql
import messages.msg_processor
class MainWorker(multiprocessing.Process):
'''
This class is responsable for all th... | ct"] = telegram.InputTelegram | API(
ApiToken = self.Configuration["Security"]["TelegramToken"],
RequestTimer = self.Configuration["Telegram"]["RequestTimer"],
LoggingObject = self.Logging,
LanguageObject = self.LanguageObject,
ControllerQueue = self.InputAPI["Contro... |
LinuCC/sturo | src/car_attributes.py | Python | gpl-2.0 | 1,918 | 0.001043 | from servo_control.summit_pwm import SummitPWM
import servo_control.servos as servos
class CarAttributes(object):
def __init__(self):
self.pwm = SummitPWM()
# Servo-data
self.servo_transmission = servos.Transmission()
self.servo_rear_locker = servos.RearLocker()
self.servo... | self, val):
"""Sets the front locker
Arguments:
val -- True for activated, false for not activated
"""
if val:
self.pwm.servo_set(self.servo_front_locker, 0)
else:
self.pwm.servo_set(self.servo_front_locker, 1)
def set_rear_locker(self, val):... | elf.pwm.servo_set(self.servo_rear_locker, 0)
else:
self.pwm.servo_set(self.servo_rear_locker, 1)
|
sigrokproject/libsigrokdecode | decoders/eeprom24xx/lists.py | Python | gpl-3.0 | 5,965 | 0.004024 | ##
## This file is part of the libsigrokdecode project.
##
## Copyright (C) 2014 Uwe Hermann <uwe@hermann-uwe.de>
##
## 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 Li... | und': True,
'addr_bytes': 1,
'addr_pins': 3,
| 'max_speed': 400,
},
# Microchip
'microchip_24aa65': {
'vendor': 'Microchip',
'model': '24AA65',
'size': 8 * 1024,
'page_size': 64, # Actually 8, but there are 8 pages of "input cache"
'page_wraparound': True,
'addr_bytes': 2,
'addr_pins': 3,
... |
ChinaMassClouds/copenstack-server | openstack/src/ceilometer-2014.2.2/ceilometer/api/middleware.py | Python | gpl-2.0 | 5,417 | 0 | #
# Copyright 2013 IBM Corp.
# Copyright 2012 New Dream Network, LLC (DreamHost)
#
# Author: Doug Hellmann <doug.hellmann@dreamhost.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
#
# ... | ult = etree.fromstring('\n'.join(app_iter))
# Add the translated error to the xml data
if error is not None:
for fault_string in fault.findall('faultstring'):
fault_string.text = (
gettext | utils.translate(
error, user_locale))
body = ['<error_message>' + etree.tostring(fault)
+ '</error_message>']
except etree.XMLSyntaxError as err:
LOG.error(_('Error parsing HTTP response: %s') % err)
... |
rcbops/python-keystoneclient-buildpackage | keystoneclient/generic/client.py | Python | apache-2.0 | 8,106 | 0.000247 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 OpenStack LLC.
# 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/... | 0']['url'])
...
>>> user = keystone.users.get(USER_ID)
>>> user.delete()
"""
def __init__(self, endpoint=None, **kwargs):
""" Initialize a new client for the Keystone v2.0 API. """
super(Client, self).__init__(endpoint=endpoint, **kwargs)
self.endpoint = endpoin... | ional url to test (without version)
Returns::
{
'message': 'Keystone found at http://127.0.0.1:5000/',
'v2.0': {
'status': 'beta',
'url': 'http://127.0.0.1:5000/v2.0/',
'id': 'v2.0'
},
... |
ctrlaltdel/neutrinator | vendor/openstack/tests/unit/orchestration/v1/test_resource.py | Python | gpl-3.0 | 2,405 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | source()
self.assertEqual('resource', sot.resource_key)
self.assertEqual('resources', sot.resources_key)
self.assertEqual('/stacks/%(stack_name)s/%(stack_id)s/resources',
sot.base_path)
self.assertFalse(sot.allow_create)
self.assertFalse(sot.allow_retriev... | esource.Resource(**FAKE)
self.assertEqual(FAKE['links'], sot.links)
self.assertEqual(FAKE['logical_resource_id'], sot.logical_resource_id)
self.assertEqual(FAKE['name'], sot.name)
self.assertEqual(FAKE['physical_resource_id'],
sot.physical_resource_id)
se... |
mikedingjan/wagtail | wagtail/admin/templatetags/wagtailadmin_tags.py | Python | bsd-3-clause | 17,059 | 0.002638 | import itertools
import json
from urllib.parse import urljoin
from django import template
from django.conf import settings
from django.contrib.admin.utils import quote
from django.contrib.humanize.templatetags.humanize import intcomma
from django.contrib.messages.constants import DEFAULT_TAGS as MESSAGE_TAGS
from dja... | })
@register.inclusion_tag('wagtailadmin/shared/main_nav.html', takes_context=True)
def main_nav(context):
request = context['request']
return {
'menu_html': admin_menu.render_html(request),
'request': request,
}
@register.inclusion_tag('wagtailadmin/shared/breadcrumb.html', takes_con... | = context['request'].user
# find the closest common ancestor of the pages that this user has direct explore permission
# (i.e. add/edit/publish/lock) over; this will be the root of the breadcrumb
cca = get_explorable_root_page(user)
if not cca:
return {'pages': Page.objects.none()}
return ... |
Succeed-Together/bakfu | data/__init__.py | Python | bsd-3-clause | 502 | 0.001992 | # -*- coding: utf-8 -*-
'''
Data is expected to be of the form :
data = (
(id, data),
(id, data),
...
)
.. automodule:: bakfu.data.base |
.. automodule:: bakfu.data.simple
.. automodule:: bakfu.data.data_xml
.. automodule:: bakfu.data.data_redis |
.. automodule:: bakfu.data.data_mongo
.. automodule:: bakfu.data.data_rest
'''
from . import base
from . import simple
from . import data_redis
#from . import data_rest
from . import data_mongo
from . import data_xml
from . import save
|
wadobo/papersplease | papersplease/papers/migrations/0002_auto_20170415_1001.py | Python | agpl-3.0 | 555 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_li | terals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('papers', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='conference',
| options={'ordering': ['date']},
),
migrations.AddField(
model_name='paper',
name='url',
field=models.CharField(max_length=80, blank=True),
preserve_default=True,
),
]
|
progrium/skypipe | setup.py | Python | mit | 844 | 0.00237 | #!/usr/bin/env python
import os
from setuptools import setup, find_packages
import skypipe
setup(
name='skypipe',
version=skypipe.VERSION,
author='Jeff Lindsay',
author_email='progrium@gmail.com',
description='Magic pipe in the sky',
long_description=open(os.path.join(os.path.dirname(__file__)... | com/progrium/skypipe",
p | ackages=find_packages(),
install_requires=['pyzmq', 'dotcloud>=0.7', 'argparse'],
zip_safe=False,
package_data={
'skypipe': ['satellite/*']},
entry_points={
'console_scripts': [
'skypipe = skypipe.cli:run',]}
)
|
fokusov/moneyguru | core/gui/entry_table_base.py | Python | gpl-3.0 | 15,063 | 0.001859 | # Created By: Virgil Dupras
# Created On: 2010-09-11
# Copyright 2015 Hardcoded Software (http://www.hardcoded.net)
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/gpl-... | self._reconciled = entry.reconciled
self._recurrent = isinstance(entry.transaction, Spawn)
self._is_budget = getattr(entry.transaction, 'is_budget', False)
def save(self):
entry = self.entry
changed_fields = self._get_changed_fields(entry, self.FIELDS)
if len(entry.transfe... | splay if entry.transfer else ''
if self._transfer != oldvalue:
changed_fields['transfer'] = self._transfer
self.table.document.change_entry(entry, **changed_fields)
self.load()
def toggle_reconciled(self):
assert self.table.reconciliation_mode
self.table.... |
thylong/cabu | docs/conf.py | Python | bsd-3-clause | 9,963 | 0 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Cabu documentation build configuration file, created by
# sphinx-quickstart on Fri Jan 15 00:48:40 2016.
#
# 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
# autog... | source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General | information about the project.
project = 'Cabu'
copyright = '2016, Théotime Leveque'
author = 'Théotime Leveque'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
versi... |
Thortoise/Super-Snake | Blender/animation_nodes-master/nodes/object/object_transforms_input.py | Python | gpl-3.0 | 4,311 | 0.016933 | import bpy
from bpy.props import *
from ... events import executionCodeChanged
from ... base_types.node import AnimationNode
from ... utils.fcurve import getArrayValueAtFrame
frameTypeItems = [
("OFFSET", "Offset", ""),
("ABSOLUTE", "Absolute", "") ]
class ObjectTransformsInputNode(bpy.types.Node, AnimationNo... | Linked["scale"]:
customTriggers.new("MONITOR_PROPERTY", idType = "OBJECT", dataPath = "scale", idObjectName = objectName)
if isLinked["quaternion"]:
customTriggers.new("MONITOR_PROPERTY", idType = "OBJECT", dataP | ath = "rotation_quaternion", idObjectName = objectName)
|
ConsonanceNg/100_Days_of_code_submissions | submissions/deXbeulah/Day_1_ Guess My Number/guessMyNumber.py | Python | mit | 761 | 0.017083 | #python 3.6.2
import random
to_be_guess = random.randint (1, 30)
guess = 0
count = 0
guesses = []
print ("Hi, What is your name.")
name = input().capitalize()
print (name+", "+"I will be guessing between 1 and 3 | 0.")
while to_be_guess > 0:
print ("Enter a | guess")
guess = int(input())
count += 1
if guess < 0 or guess > 30:
print ("Note: the guess is between 1 and 30.")
elif guess < to_be_guess:
print ("Your guess is too small.")
elif guess > to_be_guess:
print ("Your guess is too large.")
elif type(guess) != 'int':
... |
Dezmonius/Deslium | Deslium Software/Deslium Hestia/master/libs/programclass/show_license.py | Python | gpl-3.0 | 1,705 | 0.002384 | # -*- coding: utf-8 -*-
#
# license.py
#
# Выводит окно с текстом лицензии.
#
import os
from kivy.clock import Clock
from kivy.uix.rst import RstDocument
from libs.uix.dialogs import dialog, card
class ShowLicense(object):
def show_license(self, *args):
def choice_language_license(on_language):
... | self.directory, self.data.dict_language[on_language]
)
if not os.path.exists(path_to_license):
dialog(text=self.data.string_lang_not_license, title=self.title)
dialog.dismiss()
return
text_license = open(path_to_license).read()
... | =self.data.alpha,
underline_color=self.data.underline_rst_color
)
card(widget_license, size=(.9, .8))
dialog.dismiss()
choice_dialog = dialog(
text=self.data.string_lang_prev_license, title=self.title,
buttons=[
[self.d... |
tux-00/ansible | test/units/inventory/test_inventory.py | Python | gpl-3.0 | 5,504 | 0.001272 | # Copyright 2015 Abhijit Menon-Sen <ams@2ndQuadrant.com>
#
# This file is part of Ansible
#
# Ansible 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 ... | sources=[__file__])
def _test_default_groups(self, inventory_content):
inventory = self._get_inventory(inventory_content)
| self.assertIn('all', inventory.groups)
self.assertIn('ungrouped', inventory.groups)
all_hosts = set(host.name for host in inventory.groups['all'].get_hosts())
self.assertEqual(set(['host1', 'host2', 'host3', 'host4', 'host5']), all_hosts)
ungrouped_hosts = set(host.name for host in i... |
xuleiboy1234/autoTitle | tensorflow/tensorflow/contrib/factorization/__init__.py | Python | mit | 1,602 | 0 | # Copyright 2016 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 applic | able law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and |
# limitations under the License.
# ==============================================================================
"""Ops and modules related to factorization."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# pylint: disable=wildcard-import
from tensorf... |
Prokuma/cafe-order-system | setup.py | Python | mit | 316 | 0.003165 | from distutils.core import setup
py_modules = [
'pymongo',
'Flask'
]
setup(
name='Cafe-Order-System',
license='MIT',
aut | hor='Prokuma',
| author_email='root@prokuma.kr',
version='1.0',
description='Robot Cafe Order System',
py_modules=py_modules,
) |
akatsoulas/snippets-service | snippets/base/migrations/0009_snippet_client_options.py | Python | mpl-2.0 | 448 | 0 | # -*- coding: | utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django_mysql.models
class Migration(migrations.Migration):
dependencies = [
('base', '0008_auto_20160331_1405'),
]
operations = [
migrations.AddField(
model_name='snippet',
... | ),
]
|
ff94315/hiwifi-openwrt-HC5661-HC5761 | staging_dir/host/lib64/scons-2.1.0/SCons/Tool/f03.py | Python | gpl-2.0 | 2,049 | 0.002928 | """engine.SCons.Tool.f03
Tool-specific initialization for the generic Posix f03 Fortran compiler.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2... | ed
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVI | DED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF C... |
ranger/ranger | ranger/gui/widgets/titlebar.py | Python | gpl-3.0 | 5,450 | 0.00055 | # This file is part of ranger, the console file manager.
# License: GNU GPL version 3, see the file "AUTHORS" for details.
"""The titlebar is the widget at the top, giving you broad overview.
It displays the current path among other things.
"""
from __future__ import (absolute_import, division, print_function)
from... | bar.add('~/', 'directory', fixed=True)
for path in pathway:
if path.is_link:
clr = 'link'
else:
clr = 'directory'
bidi_basename = self.bidi_transpose(path.basename)
bar.add(bidi_basename, clr, directory=path)
bar... | bidi_file_path = self.bidi_transpose(self.fm.thisfile.relative_path)
bar.add(bidi_file_path, 'file')
def _get_right_part(self, bar):
# TODO: fix that pressed keys are cut off when chaining CTRL keys
kbuf = str(self.fm.ui.keybuffer)
self.old_keybuffer = kbuf
bar.add... |
open-synergy/opnsynid-hr | hr_employee_identification_from_home_address/__openerp__.py | Python | agpl-3.0 | 655 | 0 | # -*- coding: utf-8 -*-
# Copyright 2018 OpenSynergy Indonesia
# Copyright 2022 PT. Simetri Sinergi Indonesia
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
# pylint: disable=locally-disabled, manifest-required-author
{
| "name": "Employee Identification From Home Address",
"version": "8.0.1 | .1.0",
"category": "Human Resource",
"website": "https://simetri-sinergi.id",
"author": "OpenSynergy Indonesia, PT. Simetri Sinergi Indonesia",
"license": "AGPL-3",
"installable": True,
"depends": [
"partner_identification",
"hr",
],
"data": [
"views/hr_employee_v... |
fengsp/flask-snippets | forms/render_wtform_without_syntaxerr.py | Python | bsd-3-clause | 1,222 | 0.006547 | # -*- coding: utf-8 -*-
"""
forms.render_wtform_without_syntaxerr
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Render WTForm fields with html attributes that cause TemplateSyntaxErrors
http://flask.pocoo.org/snippets/107/
"""
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(os.path.dir... | d', data-items='3', data-source='["x","y","z"]'>
After creating a WTForm in the view and passing it to your template, your first attempt would be to pass the additional keyword arguments:
{{ form.myfield(name='test', data-provide='typeahead', data-data-items='3', data-source='["x","y","z"]') }}
But this will lead to... | butes that contain invalid syntax as an ad-hoc dictionary:
{{ form.myfield(name='test', **{'data-provide':'typeahead','data-items':'3','data-source': '["x","y","z"]'}) }}
"""
|
googleapis/python-aiplatform | google/cloud/aiplatform_v1/types/specialist_pool.py | Python | apache-2.0 | 2,601 | 0.000384 | # -*- 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... | . The resource name of the pending
data labeling jobs.
specialist_worker_emails (Sequence[str]):
The email addresses of workers in the
SpecialistPool.
"""
name = proto.Field(proto.STRING, number=1,)
display_name = proto.Field(proto.STRING, number=2,)
speciali... | number=3,)
specialist_manager_emails = proto.RepeatedField(proto.STRING, number=4,)
pending_data_labeling_jobs = proto.RepeatedField(proto.STRING, number=5,)
specialist_worker_emails = proto.RepeatedField(proto.STRING, number=7,)
__all__ = tuple(sorted(__protobuf__.manifest))
|
adb-xkc85723/VELA-CLARA-Controllers | Controllers/VELA/INJECTOR/velaINJMagnets/bin/Release/test.py | Python | gpl-3.0 | 377 | 0.018568 | import sys,os
os.environ["EPICS_CA_ADDR_LIST"] = "192.168.82.10"
os. | environ["EPICS_CA_MAX_ARRAY_BYTES"] = "100000000"
import velaINJMagnetControl as VIMC
a = VIMC.velaINJMagnetController(True,False)
a.switchONpsu('SOL')
#print(a.isON('HVCOR'))
print(a.getRI('SOL'))
#print(a.getILockSta | tes('HVxhfjsfhk01'))
a.switchONpsu('SOL')
#print(a.isON('HVCOR'))
print(a.isON('SOL'))
|
Sbalbp/DIRAC | ConfigurationSystem/Client/Helpers/Registry.py | Python | gpl-3.0 | 9,778 | 0.054817 | # $HeadURL$
__RCSID__ = "$Id$"
import types
from DIRAC import S_OK, S_ERROR
from DIRAC.ConfigurationSystem.Client.Config import gConfig
from DIRAC.ConfigurationSystem.Client.Helpers.CSGlobals import getVO
gBaseRegistrySection = "/Registry"
def getUsernameForDN( dn, usersList = False ):
if not usersList:
retVal... | ( "%s/VO/%s/%s" % | ( gBaseRegistrySection, voName, optName ), defaultValue )
def getBannedIPs():
return gConfig.getValue( "%s/BannedIPs" % gBaseRegistrySection, [] )
def getVOForGroup( group ):
voName = getVO()
if voName:
return voName
return gConfig.getValue( "%s/Groups/%s/VO" % ( gBaseRegistrySection, group ), "" )
def... |
tonyseek/sqlalchemy-utils | tests/aggregate/test_simple_paths.py | Python | bsd-3-clause | 2,154 | 0 | import sqlalchemy as sa
from sqlalchemy_utils.aggregates import aggregated
from tests import TestCase
class TestAggregateValueGenerationForSimpleModelPaths(TestCase):
def create_models(self):
class Thread(self.Base):
__tablename__ = 'thread'
id = sa.Column(sa.Integer, primary_key=T... | @aggregated('comments', sa.Column(sa.Integer, default=0))
def comment_count(self):
return sa.func.count('1')
comments = sa.orm.relationship('Comment', backref='thread')
class Comment(self.Base):
__tablename__ = 'comment'
id = sa.Column(sa.Integ... | rue)
content = sa.Column(sa.Unicode(255))
thread_id = sa.Column(sa.Integer, sa.ForeignKey('thread.id'))
self.Thread = Thread
self.Comment = Comment
def test_assigns_aggregates_on_insert(self):
thread = self.Thread()
thread.name = u'some article name'
... |
benjamincongdon/adept | test_recipe.py | Python | mit | 308 | 0.025974 | from buffalo import utils
from recipeManager | import RecipeManager
from nose.tools import with_setup
import pygame
def init():
utils.init()
def teardown():
utils.end = True
pygame.quit()
@with_setup(init,teardown)
def | test_manager():
RecipeManager.loadRecipes()
assert len(RecipeManager.RECIPES) > 0
|
wq/django-data-wizard | data_wizard/backends/threading.py | Python | mit | 1,186 | 0 | from .base import DataWizardBackend
from django.core.cache import cache
import threading
import uuid
CACHE_P | REFIX = "data-wizard-"
def is_uuid(task_id):
if not task_id:
re | turn False
if len(task_id) != 36:
return False
return True
class Backend(DataWizardBackend):
current_state = None
current_result = None
def run_async(self, task_name, run_id, post):
task_id = uuid.uuid4()
thread = threading.Thread(
name=task_id,
tar... |
EQTPartners/k8s-snapshots | k8s_snapshots/backends/aws.py | Python | bsd-2-clause | 4,710 | 0.002123 | from typing import Dict, List, NamedTuple
import pykube.objects
import requests
import pendulum
from urllib.parse import urlparse
from boto import ec2
from ..context import Context
from k8s_snapshots.snapshot import Snapshot
from .abstract import NewSnapshotIdentifier, SnapshotStatus
from ..errors import SnapshotCreate... | return AWSDiskIdentifier(region=zone[:-1], volume_id=volume_id)
else:
# Older versions of kube just put the volume id in the volume id field.
volume_id = volume_url
region = volume.obj['metadata']['labels']['failure-domain.beta.kubernetes.io/region']
return AWSDiskIdentifier(reg... | _id=volume_id)
def parse_timestamp(date_str: str) -> pendulum.Pendulum:
return pendulum.parse(date_str).in_timezone('utc')
def validate_disk_identifier(disk_id: Dict):
try:
return AWSDiskIdentifier(
region=disk_id['region'],
volume_id=disk_id['volumeId']
)
except:
... |
bbiiggppiigg/PokemonGo-Bot | pokemongo_bot/sleep_schedule.py | Python | mit | 7,614 | 0.005253 | from datetime import datetime, timedelta
from time import sleep
from random import uniform
class SleepSchedule(object):
"""Pauses the execution of the bot every day for some time
Simulates the user going to sleep every day for some time, the sleep time
and the duration is changed every day by a random of... | t, config):
self.bot = bot
self._process_config(config)
self._schedule_next_sleep()
self._calculate_current_sleep()
def work(self):
if self._should_sleep_now():
self._sleep()
wake_up_at_location = self._wake_up_at_location
self._schedule_n... | self.bot.api.set_position(wake_up_at_location[0],wake_up_at_location[1],wake_up_at_location[2])
else:
self.bot.wake_location = wake_up_at_location
if hasattr(self.bot, 'api'): self.bot.login() # Same here
def _process_config(self, config):
self.e... |
Shrews/PyGerrit | webapp/django/core/servers/basehttp.py | Python | apache-2.0 | 24,277 | 0.004078 | """
BaseHTTPServer that implements the Python WSGI protocol (PEP 333, rev 1.21).
Adapted from wsgiref.simple_server: http://svn.eby-sarna.com/wsgiref/
This is a simple server for use in testing or debugging Django apps. It hasn't
been reviewed for security issues. Don't use it for production use.
"""
from BaseHTTPSe... | name='bud.gif')
Note that unlike the corresponding 'email.Message' method, this does
| *not* handle '(charset, language, value)' tuples: all values must be
strings or None.
"""
parts = []
if _value is not None:
parts.append(_value)
for k, v in _params.items():
if v is None:
parts.append(k.replace('_', '-'))
... |
holtwick/pyxer | tests/public/__init__.py | Python | mit | 279 | 0.014337 | # -*- coding: UTF-8 -*-
#############################################
## (C)opyright by Dirk Holtwick, 2008 ##
## All rights reserved | ##
#############################################
from pyxer.base import *
@controller
def index():
return "/index" | |
anonion0/nsec3map | n3map/tree/rbtree.py | Python | gpl-3.0 | 8,290 | 0.002051 | import bstree
RED = 0
BLACK = 1
class RBTreeNode(bstree.BSTreeNode):
"""A node of a Red-Black Tree"""
def __init__(self, k, v, nil=None):
super(RBTreeNode, self).__init__(k, v, nil)
self.color = BLACK
self.size = 0
def update_size(self):
"""Update the size attribute u... | ht_rotate(x.parent)
x = self.root
x.color = BLACK
def _update_size(self, node):
"""Updates the size attribute on all nodes from node to the root.
Time complexity: O(lg n)"""
while | node is not self.nil:
node.update_size()
node = node.parent
def deletekey(self, k):
node = self.find(k)
if node is not None:
node = self.delete(node)
return node
def delete(self, node):
"""Delete node from the tree, preserving all red-b... |
InQuest/ThreatKB | migrations/versions/af2de80654b6_add_default_compile_yara_rule_on_save_.py | Python | gpl-2.0 | 1,083 | 0.001847 | """Add default COMPILE_YARA_RULE_ON_SAVE setting
Revision ID: af2de80654b6
Revises: 2f0f6d26a505
Create Date: 2018-11-11 19:26:53.631142
"""
from alembic import op
import sqlalchemy as sa
from app.models import cfg_settings
import datetime
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic... | = datetime.datetime.now(). | isoformat()
date_modified = datetime.datetime.now().isoformat()
op.bulk_insert(
cfg_settings.Cfg_settings.__table__,
[
{"key": "COMPILE_YARA_RULE_ON_SAVE", "value": "1", "public": True, "date_created": date_created,
"date_modified": date_modified,
"descript... |
lingfliu/smart_tuwa | twrt/testbed/fan_test.py | Python | apache-2.0 | 951 | 0.007361 | import socket
import time
msg_header = 'AADD'
msg_stamp = '\x00\x00\x00\x00'
msg_id_gw = '00AA00DD'
msg_id_dev = '00000000'
msg_devtype = '\x33\x00'
msg_auth_key = '88888888'
msg_auth_datatype = '\x1c\x00'
msg_auth = msg_header+msg_stamp+msg_id_gw+msg_id_dev+msg_devtype+msg_ | auth_datatype+'\x00\x08'+msg_auth_key
msg_ctrl_datatype = '\x02\x00'
data_on = '\x64'
data_off = '\x00'
msg_ctrl_fan_on = msg_header+msg_stamp+msg_id_gw+msg_id_dev+msg_devtype+msg_ctrl_datatype+'\x00\x01'+data_on
msg_ctrl_fan_off = msg_header+msg_stamp+msg_id_gw+msg_id_dev+msg_devtype+msg_ctrl_datatype+'\x00\x01'+... | .AF_INET, socket.SOCK_STREAM)
skt.connect(serverAddress)
length = skt.send(msg_auth)
msg_bak = skt.recv(1024)
#print msg_bak
length = skt.send(msg_ctrl_fan_on)
time.sleep(10)
length = skt.send(msg_ctrl_fan_off)
#skt.close()
while(True):
pass
|
j00bar/ansible | lib/ansible/modules/cloud/packet/packet_device.py | Python | gpl-3.0 | 18,501 | 0.002324 | #!/usr/bin/python
# (c) 2016, Tomas Karasek <tom.to.the.k@gmail.com>
# (c) 2016, Matt Baldwin <baldwin@stackpointcloud.com>
# (c) 2016, Thibaud Morel l'Horset <teebes@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General P... | e your Packet api token in env var PACKET_API_TOKEN.
# You can a | lso pass it to the auth_token parameter of the module instead.
# Creating devices
- name: create 1 device
hosts: localhost
tasks:
- packet_device:
project_id: 89b497ee-5afc-420a-8fb5-56984898f4df
hostnames: myserver
operating_system: ubuntu_16_04
plan: baremetal_0
facility: sjc1
-... |
PyCQA/pylint | doc/conf.py | Python | gpl-2.0 | 7,748 | 0.001291 | #
# Pylint documentation build configuration file, created by
# sphinx-quickstart on Thu Apr 4 20:31:25 2013.
#
# 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 configuration values hav... | ' or '12pt').
# latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
(
"index",
"Pylint.tex",
"Pylint Documentation",
"Logilab, PyCQA and contributo... | ocuments, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False
# If true, show page references after internal links.
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
# latex_show_urls = False
# Additional stuff for the LaTeX preamble.
# latex_p... |
rkmaddox/expyfun | expyfun/io/_parse.py | Python | bsd-3-clause | 8,093 | 0.000247 | # -*- coding: utf-8 -*-
"""File parsing functions
"""
import numpy as np
import csv
import ast
import json
def read_tab_raw(fname):
"""Read .tab file from expyfun output without segmenting into trials.
Parameters
----------
fname : str
Input filename.
Returns
-------
data : list... |
b2 = b2 + 1 # include the end
assert lines[b2 - 1][1] == group_end
d = dict()
these_times = [float(line[0]) for line in lines[b1:b2]]
these_keys = [line[1] for line in lines[b1:b2]]
these_vals = [line[2] for line in lines[b1:b2]]
for ki, key in enumerate... | es[ii]) for ii in idx]
data.append(d)
return data
def reconstruct_tracker(fname):
"""Reconstruct TrackerUD and TrackerBinom objects from .tab files.
Parameters
----------
fname : str
Input filename.
Returns
-------
tr : list of TrackerUD or TrackerBinom
The tr... |
hillwoodroc/deepin-music-player | src/nls.py | Python | gpl-3.0 | 1,379 | 0.010877 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 ~ 2012 Deepin, Inc.
# 2011 ~ 2012 Hou Shaohui
#
# Author: Hou Shaohui <houshao55@gmail.com>
# Maintainer: Hou Shaohui <houshao55@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the ter... | ITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import gettext
import os
def get_parent_dir(filepath, level=1):
'''Get par... | dir.'''
parent_dir = os.path.realpath(filepath)
while(level > 0):
parent_dir = os.path.dirname(parent_dir)
level -= 1
return parent_dir
LOCALE_DIR=os.path.join(get_parent_dir(__file__, 2), "locale")
if not os.path.exists(LOCALE_DIR):
LOCALE_DIR="/usr/share/locale"
_ = Non... |
khchine5/book | lino_book/projects/gfktest/test_gfk.py | Python | bsd-2-clause | 4,261 | 0.002818 | # -*- coding: UTF-8 -*-
# Copyright 2015-2018 Rumma & Ko Ltd
# License: BSD (see file COPYING for details)
# go gfktest
# python manage.py test
from __future__ import unicode_literals
from builtins import str
# from lino.utils.test import DocTest
from lino.utils.djangotest import WebIndexTestCase
from django.db impo... | ate a member, and three GFK-related objects whose `owner`
fields point to that member. And then we try to delete that
member.
"""
| Member = rt.models.gfktest.Member
Note = rt.models.gfktest.Note
Memo = rt.models.gfktest.Memo
Comment = rt.models.gfktest.Comment
BrokenGFKs = rt.models.gfks.BrokenGFKs
def check_status(*args):
for i, m in enumerate((Member, Comment, Note, Memo)):
... |
Nizebulous/lighthouse | run.py | Python | mit | 119 | 0 | #!/usr/bin/env python
from | lighthouse import app
if __name__ == '__main__' | :
app.run(host='0.0.0.0', debug=True)
|
shubh24/casey-compile | compile.py | Python | mit | 3,001 | 0.016994 | from __future__ import division
import cv2
import sys, os
from pytube import YouTube
import upload_video
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
db = client.CaseyBot.urls
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
def cluster(data, maxgap):
... | groups = [[data[0]]]
for x in data[1:]:
if abs(x - groups[-1][0]) <= maxgap:
groups[-1].append(x)
else:
groups.append([x])
return groups
def detect_faces(frames):
selected_frames = []
counter = 0
for img in frames:
if counter%frames_count == 0:
... | t(counter/frames_count)) + " seconds done...")
faces = face_cascade.detectMultiScale(img, 1.3, 5)
if len(faces) > 0:
face_percentage = 0
for f in faces:
width = f[2]
height = f[3]
face_percentage += (widt... |
cysuncn/python | study/Socket/SocketClient.py | Python | gpl-3.0 | 1,102 | 0.002742 | # -*- coding: utf-8 -*-
import socket
import ibm_db
conn = ibm_db.connect("DATABASE=sample;HOSTNAME=66.3.44.37;PORT=60004;PROTOCOL=TCPIP;UID=cyrus;PWD=cyrus;", "", "")
sql = "SELECT PHONENO FROM EMPLOYEE"
def queryData(s):
result = []
if conn:
try:
stmt = ibm_db.exec_immediate(conn, s)
... | while dictionary != False:
for key in dictionary:
if key == 0:
result.append | (dictionary[key])
dictionary = ibm_db.fetch_both(stmt)
return result
except Exception as ex:
print(ex)
finally:
ibm_db.close(conn)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 9000))
print((s.recv(1024).decode()))
tu... |
McDermott-Group/Simulation | Mask Automation/main.py | Python | gpl-2.0 | 1,940 | 0.010825 | import sys
import os
import shlex
import argparse
def blockPrint():
sys.stdout = open(os.devnull, 'w')
# Restore
def enablePrint():
sys.stdout = sys.__stdout__
cap = raw_input("Enter parameters for the capacitor : (Enter blank for default values)\n")
XY = raw_input("Enter parameters for the XY Control : (Ent... | lank for default values)\n")
Qbus = raw_input("Enter parameters for the Quantum Bus : (Enter blank for default values)\n")
resonator = raw_input("Enter parameters for the Resonator : (E | nter blank for default values)\n")
parser = argparse.ArgumentParser(add_help=False,description='Generates the gds for the Capacitor.\nRefer to the pdf file for all the parametrizations')
parser.add_argument('-h', '--help', action='help', default=argparse.SUPPRESS,
help='Shows the default value of e... |
andela-angene/coursebuilder-core | coursebuilder/controllers/utils.py | Python | apache-2.0 | 61,721 | 0.000275 | # Copyright 2012 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | GET/POST parameter.
"""
def get(self):
"""Handles GET."""
action = self.request.get('action')
if not action:
action = self.default_action
if action not in self.get_actions:
self.error(404)
return
handler = getattr(self, 'get_%s' %... | equest.get('action')
if not action or action not in self.post_actions:
self.error(404)
return
handler = getattr(self, 'post_%s' % action)
if not handler:
self.error(404)
return
# Each POST request must have valid XSRF token.
xsrf_... |
qgis/QGIS-Django | qgis-app/base/tests/test_license.py | Python | gpl-2.0 | 541 | 0 | import os
from zipfile import ZipFile
from django.test import TestCase
from base.license import zipped_with_license
| TESTFILES_DIR = os.path.abspath(
os.path.join(os.path.dirname(__file__), 'testfiles'))
class TestZippedWithLicense(TestCase):
def setUp(self):
self.file = os.path.join(TESTFILES_DIR, "test.txt")
def test_zipped_with_license(self):
zipfile = zipped_with_license(self.file, "test")
... | |
olsonse/python-vxi11 | rpc/rpc.py | Python | gpl-2.0 | 36,998 | 0.002027 | from __future__ import with_statement
from __future__ import absolute_import
import socket, select
import struct
import threading
import logging
from collections import deque as Deque
from errno import EINPROGRESS, EWOULDBLOCK
from . import rpc_pack
from .rpc_const import *
from .rpc_type import *
from . import secu... | l message strings that we want to send through the
pipe. Records go in one end and come out the other. However, because
all that *really* goes through is a stream of bytes, just sending the
records as is wouldn't work, since there would be no way to | tell where
one record ends and another begins.
So record marking is used (rfc 1831 section 10), which breaks the
record into packets (called record fragments in the rfc), and precedes
each packet with a byte count and an end-of-record flag.
The raw byte stream sent is thus the packets with the in... |
dset0x/invenio-workflows | setup.py | Python | gpl-2.0 | 4,153 | 0.000241 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015 CERN.
#
# Invenio 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... | p(
name='invenio-workflows',
version=version,
description=__doc__,
long_description=readme + '\n\n' + history,
keywords='invenio workflows',
license='GPLv2',
author='CERN',
author_email='info@invenio-software.org',
url='https://github.com/inveniosoftware/invenio-workflows',
packa... | kflows',
],
zip_safe=False,
include_package_data=True,
platforms='any',
install_requires=requirements,
extras_require={
'docs': [
'Sphinx>=1.3',
'sphinx_rtd_theme>=0.1.7'
],
'tests': test_requirements
},
classifiers=[
'Environment :... |
Symmetry-Innovations-Pty-Ltd/Python-2.7-for-QNX6.5.0-x86 | usr/pkg/lib/python2.7/threading.py | Python | mit | 32,720 | 0.0011 | """Thread module emulating a subset of Java's threading model."""
import sys as _sys
try:
import thread
except ImportError:
del _sys.modules[__name__]
raise
import warnings
from time import time as _time, sleep as _sleep
from traceback import format_exc as _format_exc
from collections import deque
# No... | try:
self._is_owned = lock._is_owned
except AttributeError:
pass
self.__waiters = []
def __enter__(self):
return self.__lock.__enter__()
def __exit__(self, *args):
return self.__lock.__exit__(*args)
def __repr__(self):
return "<Condition... | _lock.release() # No state to save
def _acquire_restore(self, x):
self.__lock.acquire() # Ignore saved state
def _is_owned(self):
# Return True if lock is owned by current_thread.
# This method is called only if __lock doesn't have _is_owned().
if self.__loc... |
mcr/ietfdb | ietf/secr/console/views.py | Python | bsd-3-clause | 501 | 0.007984 | from django.http import HttpResponseRedirect, HttpResponse, HttpResponseForbidden
from djan | go.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from ietf.doc.models import *
def main(request):
'''
Main view for the Console
'''
latest_docevent = DocEvent.objects.all().order_by('-time')[0]
return | render_to_response('console/main.html', {
'latest_docevent': latest_docevent},
RequestContext(request, {}),
) |
ArcticaProject/vcxsrv | mesalib/src/glsl/nir/nir_opt_algebraic.py | Python | gpl-3.0 | 10,772 | 0.001578 | #! /usr/bin/env python
#
# Copyright (C) 2014 Intel Corporation
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, ... | eMorgan's Laws
(('iand', ('inot', a), ('inot', b)), ('inot', ('ior', a, b))),
(('ior', ('inot', a), ('inot', b)), ('inot', ('iand', a, b))),
# Shift optimizations
(('ishl', 0, a), 0),
(('ishl', a, 0), a),
(('ishr', 0, a), 0),
(('ishr', a, 0), a),
(('ushr', 0, a), 0),
(('ushr', a, 0), a),
... | a
(('flog2', ('fexp2', a)), a), # lg2(2^a) = a
(('flog', ('fexp', a)), a), # ln(e^a) = a
(('fpow', a, b), ('fexp2', ('fmul', ('flog2', a), b)), 'options->lower_fpow'), # a^b = 2^(lg2(a)*b)
(('fexp2', ('fmul', ('flog2', a), b)), ('fpow', a, b), '!options->lower_fpow'), # 2^(lg2(a)*b) = a^b
(('fexp', ... |
the-zebulan/CodeWars | tests/beta_tests/test_remove_duplicates_from_list.py | Python | mit | 612 | 0 | import unittest
from katas.beta.remove_duplicates_from_list import distinct
class DistinctTestCase(unittest.TestCa | se):
def test_equal_1(self):
self.assertEqual(distinct([1]), [1])
def test_equal_2(self):
| self.assertEqual(distinct([1, 2]), [1, 2])
def test_equal_3(self):
self.assertEqual(distinct([1, 1, 2]), [1, 2])
def test_equal_4(self):
self.assertEqual(distinct([1, 1, 1, 2, 3, 4, 5]), [1, 2, 3, 4, 5])
def test_equal_5(self):
self.assertEqual(distinct([1, 2, 2, 3, 3, 4, 4, 5, 6,... |
npuichigo/ttsflow | third_party/tensorflow/tensorflow/contrib/keras/python/keras/applications/vgg16.py | Python | apache-2.0 | 8,578 | 0.006179 | # Copyright 2015 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... | eturns:
A Keras model instance.
Raises:
ValueError: in case of invalid argument for `weights`,
or invalid input shape.
"""
if weights not in {'imagenet', None}:
raise ValueError('The `weights` argument should be either '
'`None` (random initialization) or `imagenet`... | '(pre-training on ImageNet).')
if weights == 'imagenet' and include_top and classes != 1000:
raise ValueError('If using `weights` as imagenet with `include_top`'
' as true, `classes` should be 1000')
# Determine proper input shape
input_shape = _obtain_input_shape(
... |
molobrakos/home-assistant | homeassistant/components/plex/media_player.py | Python | apache-2.0 | 33,328 | 0 | """Support to interface with the Plex API."""
from datetime import timedelta
import json
import logging
import requests
import voluptuous as vol
from homeassistant import util
from homeassistant.components.media_player import (
MediaPlayerDevice, PLATFORM_SCHEMA)
from homeassistant.components.media_player.const i... | plexserver.clients()
except plexapi.exceptions.BadRequest:
_LOGGER.exception("Error listing plex devices")
return
except requests.exceptions.RequestException as ex:
_LOGGER.warning(
"Could not connect to plex | server at http://%s (%s)", host, ex)
return
new_plex_clients = []
available_client_ids = []
for device in devices:
# For now, let's allow all deviceClass types
if device.deviceClass in ['badClient']:
continue
available_client_ids.... |
profitware/python-sandbox-algo | sandboxalgo/sets.py | Python | mit | 861 | 0.002323 | # -*- coding: utf-8 -*-
__author__ = 'Sergey Sobko'
class HashSet(object):
_set_dict = None
def __init__(self):
self._set_dict = dict()
def add(self, key, value):
self._set_dict[hash(key)] = value
def get(self, key):
return self._set_dict.get(hash(key))
def __repr__(se... |
class LexNode(object):
letter = None
data = None
next_letters = None
def __init__(self, letter):
self.letter = letter
self.next_letters = list()
class TreeSet(object):
root_letter = None
def __init__(self):
self.root_letter = LexNode(None)
def add(self, key, val... |
pass
# FIXME: Step into next letter's LexNode |
feroda/lessons-python4beginners | students/2016-09-04/pnatile/usodiz.py | Python | agpl-3.0 | 1,771 | 0.044068 | # uso dizionario come cache per evitare di calc | olare sempre
PEOPLE = []
def main():
"""
devo far inserire name, city, salary come input e salvarli nel dizionario
# 1.finche utente non smette.
# 2.l'utente inserisce il nome
usa raw_input per chiedere le info a | ll'utente
# 3.l'utente inserisce la città
# 4.l'utente inserisce lo stipendio
# 5.inserisci il dizionario con chiavi
'name','city','salary'
nella lista PEOPLE = []
PEOPLE.append(person_d)
# 6.STAMPA A VIDEO PEOPLE nel modo che ti piace
# 7.ri-inizia da Step 1
... |
bsmr-opengl/glad | glad/lang/d/loader/gl.py | Python | mit | 3,394 | 0.002357 | from glad.lang.common.loader import BaseLoader
from glad.lang.d.loader import LOAD_OPENGL_DLL
_OPENGL_LOADER = \
LOAD_OPENGL_DLL % {'pre':'private', 'init':'open_gl',
'proc':'get_proc', 'terminate':'close_gl'} + '''
bool gladLoadGL() {
bool status = false;
if(open_gl()) {
s... | = glversion[0] - \'0\';
int minor = glversion[2] - \'0\';
GLVersion.major = major; GLVersion.minor = minor;
'''
class OpenGLDLoader(BaseLoader):
def write_header_end(self, fobj):
pass
def write_header(self, fobj):
pass
def write(self, fobj):
fobj.write('alias Loader | = void* delegate(const(char)*);\n')
if not self.disabled and 'gl' in self.apis:
fobj.write(_OPENGL_LOADER)
def write_begin_load(self, fobj):
fobj.write('\tglGetString = cast(typeof(glGetString))load("glGetString");\n')
fobj.write('\tif(glGetString is null) { return false; }\n')
... |
JeffRoy/mi-dataset | mi/dataset/driver/vel3d_l/wfp/vel3d_l_wfp_recovered_driver.py | Python | bsd-2-clause | 2,021 | 0.003958 | #!/usr/bin/env python
"""
@package mi.dataset.driver.vel3d_l.wfp
@file marine-integrations/mi/dataset/driver/vel3d_l/wfp/vel3d_l_wfp_recovered_driver.py
@author Tapana Gupta
@brief Driver for the vel3d_l_wfp instrument
Release notes:
Initial Release
"""
from mi.core.log import get_logger
from mi.dataset.dataset_pa... | DataSetDriverConfigKeys.PAR | TICLE_MODULE: 'mi.dataset.parser.vel3d_l_wfp',
DataSetDriverConfigKeys.PARTICLE_CLASS: ['Vel3dLWfpInstrumentRecoveredParticle',
'Vel3dLWfpMetadataRecoveredParticle']
}
# The parser inherits from simple parser - other callbacks not needed ... |
plaid/plaid-python | plaid/model/payment_initiation_payment_create_request.py | Python | mit | 8,664 | 0.000693 | """
The Plaid API
The Plaid REST API. Please see https://plaid.com/docs/api for more details. # noqa: E501
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from plaid.model_utils import ( # noqa: F401
ApiTypeError,
ModelComposed,
ModelNormal... | A reference for the payment. This must be an alphanumeric string with at most 18 characters and must not contain any special characters (since not all institutions support them).
amount (PaymentAmount):
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
... | d if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_spec_property_nam... |
zerolab/wagtail | wagtail/users/utils.py | Python | bsd-3-clause | 1,289 | 0.002327 | import hashlib
from django.conf import settings
from django.utils.http import urlencode
from wagtail.core.compat import AUTH_USER_APP_LABEL, AUTH_USER_MODEL_NAME
delete_user_perm = "{0}.delete_{1}".format(AUTH_USER_APP_LABEL, AUTH_USER_MODEL_NAME.lower())
def user_can_delete_user(current_user, user_to_delete):
... | # users may not delete themselves
return False
if user_to_delete.is_superuser and not current_user.is_superuser:
| # ordinary users may not delete superusers
return False
return True
def get_gravatar_url(email, size=50):
default = "mm"
size = int(size) * 2 # requested at retina size by default and scaled down at point of use with css
gravatar_provider_url = getattr(settings, 'WAGTAIL_GRAVATAR_PROVI... |
idlesign/steampak | demo/steampak_demo.py | Python | bsd-3-clause | 2,653 | 0.002639 | #! /usr/bin/env python3
"""
Before you start:
* Demo application requires ``arcade`` packages to be installed: http://arcade.academy/installation_linux.html.
* Make sure `steampak` is available to your Pyth | on 3.
1. Set PATH_LIBSTEAM environment variable to a proper path or put `libsteam_api.so` into `demo` directory
near this very file.
2. Add `steampak_demo.py` into your game library:
Steam -> Library -> + ADD A GAME -> Add a Non-Steam Game ... -> BROWSE, ADD SELECTED PROGRAMS
3. Launch demo from Steam Library.... | d
Steam debug hint:
* Launch Steam with -console -debug_steamapi -dev
* Open Steam -> Console, run ``log_ipc 1``, ``log_callbacks``
* IPC log: tail-f ~/.steam/logs/ipc_SteamClient.log
"""
from os import environ, path
import arcade
class SteampakDemo(arcade.Window):
def __init__(self, width, height, title):
... |
guillaume-philippon/aquilon | lib/aquilon/worker/commands/add_application.py | Python | apache-2.0 | 1,378 | 0 | # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2009,2010,2011,2012,2013,2014,2015,2016 Contributor
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obt... | TIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains the logic for `aq add application`."""
from aquilon.aqdb.model import Application
from aquilon.worker.broker import BrokerCommand # pylint: disa... | lication(CommandAddResource):
required_parameters = ["application"]
resource_class = Application
resource_name = "application"
def setup_resource(self, session, logger, dbapp, eon_id, grn, **_):
dbgrn = lookup_grn(session, grn, eon_id, logger=logger,
config=self.conf... |
CheeseLord/warts | tests/smoketests/test_src_access.py | Python | mit | 92 | 0.01087 | fro | m src. | shared import config
def test_answer():
assert type(config.CHUNK_SIZE) == int
|
alehenaff/prodplanner | planner/translation.py | Python | mit | 303 | 0.006601 | from modeltranslation.translator import register, TranslationOptions
f | rom .models import DayTemplateRule, RuleSet
@register(DayTemplateRule)
class SimpleRuleTranslation(TranslationOptions):
fields = ('name',)
@reg | ister(RuleSet)
class RuleSetTranslation(TranslationOptions):
fields = ('name',)
|
sunu/oppia-test | controllers/feedback.py | Python | apache-2.0 | 1,415 | 0 | # Copyright 2012 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | : 'feedback',
})
self.render_template('feedback.html')
def post(self):
"""Handles POST requests."""
payload = json.loads(self.request.get('payload'))
feedback = payload.get('feedback')
u | rl = payload.get('url_params').get('url')
url = urllib.unquote_plus(url)
EventHandler.record_feedback_submitted(url, feedback)
|
silverbullet-dk/opentele-server | test/funkload/test_OpenteleWeb.py | Python | apache-2.0 | 9,083 | 0.003633 | # -*- coding: iso-8859-15 -*-
"""opentele_web FunkLoad test
$Id: $
"""
import unittest
from funkload.FunkLoadTestCase import FunkLoadTestCase
from webunit.utility import Upload
from funkload.utils import Data
#from funkload.utils import xmlrpc_get_credential
class OpenteleWeb(FunkLoadTestCase):
"""XXX
This t... | description="Get /opentele-server/")
# /var/folders/t3/32mqxjjs6pddb_yjpt_6clmr0000gn/T/tmp6eJa8l_funkload/watch0296.request
# /var/folders/t3/32mqxjjs6pddb_yjpt_6clmr0000gn/T/tmp6eJa8l_funkload/watch0297.request
self.get(server_url + "/opentele-server/patient/search",
description="... | ddb_yjpt_6clmr0000gn/T/tmp6eJa8l_funkload/watch0315.request
# /var/folders/t3/32mqxjjs6pddb_yjpt_6clmr0000gn/T/tmp6eJa8l_funkload/watch0316.request
self.post(server_url + "/opentele-server/patient/search", params=[
['ssn', ''],
['phone', ''],
['firstName', 'Linda'],
... |
kyleam/seaborn | seaborn/xkcd_rgb.py | Python | bsd-3-clause | 35,379 | 0 | xkcd_rgb = {'acid green': '#8ffe09',
'adobe': '#bd6c48',
'algae': '#54ac68',
'algae green': '#21c36f',
'almost black': '#070d0d',
'amber': '#feb308',
'amethyst': '#9b5fc0',
'apple': '#6ecb3c',
'apple green': '#76cd26',
... | 'coff | ee': '#a6814c',
'cool blue': '#4984b8',
'cool green': '#33b864',
'cool grey': '#95a3a6',
'copper': '#b66325',
'coral': '#fc5a50',
'coral pink': '#ff6163',
'cornflower': '#6a79f7',
'cornflower blue': '#5170d7',
'c... |
nyov/python-daemon | version.py | Python | gpl-3.0 | 18,554 | 0.000324 | # -*- coding: utf-8 -*-
# version.py
# Part of ‘python-daemon’, an implementation of PEP 3143.
#
# Copyright © 2008–2016 Ben Finney <ben+python@benfinney.id.au>
#
# This is free software: you may copy, modify, and/or distribute this work
# under the terms of the GNU General Public License as published by the
# Free So... | lue):
valid = True
if not valid:
raise ValueError(
"not a valid person specification {value!r}".format(
value=value))
else:
return None
@classmethod
def make_ordered_dict(cls, fields):
""" | Make an ordered dict of the fields. """
result = collections.OrderedDict(
(name, fields[name])
for name in cls.field_names)
return result
def as_version_info_entry(self):
""" Format the changelog entry as a version info entry. """
fields = vars(self)... |
TornikeNatsvlishvili/writing.skivri.ge | backend/backend/app.py | Python | mit | 502 | 0 | from flask import Flask, jsonify
from backend.settings import ProdConfig
from backend.api import api
from backend.extensions import mail, cors
def cre | ate_app(config_object=ProdConfig):
app = Flask(__name__)
app.config.from_object(config_object)
register_extensions(app)
register_blueprints(app)
return app
def regis | ter_blueprints(app):
app.register_blueprint(api)
return None
def register_extensions(app):
mail.init_app(app)
cors.init_app(app)
return None
|
hivesolutions/netius | src/netius/sh/base.py | Python | apache-2.0 | 1,533 | 0.003266 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Hive Netius System
# Copyright (c) 2008-2020 Hive Solutions Lda.
#
# This file is part of Hive Netius System.
#
# Hive Netius System is free software: you can redistribute it and/or modify
# it under the terms of the Apache License as published by the Apache
# Foun... | pyright (c) 2008-2020 Hive Solutions Lda."
""" The copyright for the module """
__license__ = "Apache License, Version 2.0"
""" The license for the module """
|
def sh_call(globals = {}, locals = {}):
import sys
if not len(sys.argv) > 1:
raise RuntimeError("invalid number of arguments (no method)")
name = sys.argv[1]
method = globals[name]
method(*sys.argv[2:])
|
robert-budde/smarthome | lib/module.py | Python | gpl-3.0 | 15,003 | 0.006265 | #!/usr/bin/env python3
# vim: set encoding=utf-8 tabstop=4 softtabstop=4 shiftwidth=4 expandtab
##################################### | ####################################
# Copyright 2017- Martin Sinn m.sinn@gmx.de
#########################################################################
# This file is part of SmartHomeNG
#
# SmartHomeNG is free software: you can redistribute it and/or modifyNode.js Design Patterns - S... | r option) any later version.
#
# SmartHomeNG 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 ... |
haakenlid/django-skeleton | settings/base.py | Python | mit | 5,649 | 0.000708 | # -*- coding: utf-8 -*-
"""
Django settings for skeleton 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/
"""
import os
# import django.conf.global_settings as... | LE = join_path(PROJECT_DIR, 'logs', 'django-debug.log')
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler'
},
'stream_to_console': {
'level': ... | ': DEBUG_LOG_FILE,
},
},
'loggers': {
'django.request': {
'handlers': ['mail_admins', 'stream_to_console', ],
'level': 'DEBUG',
'propagate': True,
},
'debug': {
'handlers': ['stream_to_console', 'write_to_logfile', ],
'l... |
abramhindle/UnnaturalCodeFork | python/testdata/launchpad/lib/lp/code/tests/test_directbranchcommit.py | Python | agpl-3.0 | 14,147 | 0 | # Copyright 2009-2012 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
"""Tests for `DirectBranchCommit`."""
__metaclass__ = type
from testtools.testcase import ExpectedException
from zope.security.proxy import removeSecurityProxy
from lp.code... | ns.
self.committer.writeFile('y.txt', 'aaa')
self.committer.commit('')
self._setUpCommitter()
self.committer.writeFile('y.txt', 'bbb')
self.committer.writeFile('y.txt', 'ccc')
self.committer.commit('')
self.assertEqual({'y.txt': 'bbb'}, self._getContents())
d... | ce it was last scanned,
# attempting to commit to it will raise Concurren |
michaelbrooks/uw-message-coding | message_coding/apps/base/views.py | Python | mit | 3,592 | 0.00167 | """ Views for the base application """
from django.shortcuts import render
from django.views.generic import DetailView
from django.contrib.auth import get_user_model
from django.core.exceptions import ObjectDoesNotExist, PermissionDenied
from django.http import Http404
from django.utils.translation import ugettext as... | initkwargs):
view = super(LoginRequiredMixin, cls).as_view(**initkwargs)
return login_r | equired(view)
class UserDashboard(LoginRequiredMixin, DetailView):
model = get_user_model()
template_name = 'base/dash_detail.html'
def get_object(self, queryset=None):
return self.request.user
def get_context_data(self, **kwargs):
context = super(UserDashboard, self).get_context_dat... |
javitonino/tosh | tosh/command.py | Python | bsd-3-clause | 2,434 | 0.002465 | """Base class and task for commands."""
import traceback
from .tasks import Task
class CommandFailedException(BaseException):
"""Class to represent a failure in a command. Used to avoid printing multiple tracebacks on nested commands."""
pass
class _CommandMeta(type):
"""
Metaclass (object that rep... | run`."""
self._status = Task.Status.Running
self._tosh.refresh()
try:
result = await self._run()
self._status = Task.Status.Succes | s
return result
except CommandFailedException:
self._status = Task.Status.Error
raise CommandFailedException()
except BaseException as e:
self._status = Task.Status.Error
self._set_output_text(traceback.format_exc())
raise CommandFa... |
assaron/pynlc | auth.py | Python | gpl-3.0 | 2,029 | 0.003943 | # -*- coding: utf-8 -*-
#
# Copyrigt 2010 Aleksey Sergushichev <alsergbox@gmail.com>
#
# This file is part of pynlc.
# Pynlc 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, ... | :
executable = "./encode"
else:
raise Exception("Unsupported OS")
args = [executable, config.NC_HASH, self._request_message]
p = Popen(args, stdout=PIPE)
reply = p.std | out.readline()[:-1] # without '\n'
p.wait()
self._sender("%s\t%s\t%s %s\t%s\n" % \
(config.NC_VERSION, reply, "CPU_INFO", "OS_INFO", gethostname()))
|
meteogrid/FTPRelayer | ftprelayer/util.py | Python | bsd-3-clause | 156 | 0.00641 | impo | rt pkg_resources
def import_string(s):
if isinstance(s, basestring):
return pkg_resources.EntryPoint.parse('x='+s).load(False)
ret | urn s
|
BillTheBest/Archipel-oVirt | scripts/kdump.py | Python | gpl-2.0 | 2,193 | 0.00228 | #!/usr/bin/env python
#
# kdump.py - Copyright (C) 2010 Red Hat, Inc.
# Written by Joey Boggs <jboggs@redhat.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# ... | te to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA. A copy of the GNU General Public License is
# also available at http://www.gnu.org/copyleft/gpl.html.
from ovirtnode.ovirtfunctions import *
def write_kdump_config(config):
kdump_config_file = open("/etc/k... | e.close()
ovirt_store_config("/etc/kdump.conf")
return True
def restore_kdump_config():
kdump_config_file = open("/etc/kdump.conf", "w")
kdump_config_file.write("default reboot\n")
kdump_config_file.write("ext4 /dev/HostVG/Data\n")
kdump_config_file.write("path /core\n")
kdump_config_file.c... |
wileeam/airflow | tests/providers/apache/spark/operators/test_spark_submit.py | Python | apache-2.0 | 7,170 | 0.001534 | #
# 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... | g',
'keytab': 'privileged_user.keytab',
'principal': 'user/spark@airflow.org',
'proxy_user': 'sample_user',
'name': '{{ task_instance.task_id }}',
'num_executors': 10,
| 'status_poll_interval': 30,
'verbose': True,
'application': 'test_application.py',
'driver_memory': '3g',
'java_class': 'com.foo.bar.AppMain',
'application_args': [
'-f', 'foo',
'--bar', 'bar',
'--start', '{{ macros.ds_add(ds, -1)}}',
... |
project-owner/Peppy | util/imageutil.py | Python | gpl-3.0 | 42,494 | 0.005224 | # Copyright 2020-2021 Peppy Player peppy.player@gmail.com
#
# This file is part of Peppy Player.
#
# Peppy Player 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 you... | th = int(wid | th * (min(k1, k2)))
height = int(height * (min(k1, k2)))
elif width > w and height < h:
k = w/width
width = int(width * k)
height = int(height * k)
elif width < w and height > h:
k = h/height
width = int(width * k)
h... |
evasilchenko/castle | start_castle.py | Python | mit | 121 | 0.008264 | from castle.main import CastleGameLoop
if __name__ == "__main_ | _":
castle = CastleGameLoop()
castle.start_g | ame() |
nimasmi/wagtail | wagtail/contrib/sitemaps/tests.py | Python | bsd-3-clause | 6,379 | 0.002351 | import datetime
import pytz
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.shortcuts import get_current_site
from django.test import RequestFactory, TestCase
from wagtail.core.models import Page, PageViewRestriction, Site
from wagtail.tests.testapp.models import EventIndex, Simpl... | ed_at=datetime.datetime(2017, 1, 1, 12, 0, 0, tzinfo=pytz.utc),
latest_revision_created_at=datetime.datetime(2017, 2, 1, 12, 0, 0, tzinfo=pytz.utc)
))
self.unpublished_child_page = self.home_page.add_child(instance=SimplePage(
title="Unpublished",
slug='unpublished',... | title="Protected",
slug='protected',
content="hello",
live=True,
))
PageViewRestriction.objects.create(page=self.protected_child_page, password='hello')
self.page_with_no_last_publish_date = self.home_page.add_child(instance=SimplePage(
title="I ... |
laurentb/weboob | modules/groupama/__init__.py | Python | lgpl-3.0 | 848 | 0 | # -*- coding: utf-8 -*-
# Copyright(C) 2012-2019 Budget Insight
#
# This file is part of a weboob module.
#
# This weboob module is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the... | f the GNU Lesser General Public License
# along with this weboob module. If | not, see <http://www.gnu.org/licenses/>.
from .module import GroupamaModule
__all__ = ['GroupamaModule']
|
aidin36/beneath-a-binary-sky | tests/test_database/test_get_robot.py | Python | gpl-3.0 | 2,548 | 0 | # This file is part of Beneath a Binary Sky.
# Copyright (C) 2016, Aidin Gharibnavaz <aidin@aidinhut.com>
#
# Beneath a Binary Sky 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
# Lice... | _alive(False)
# It shouldn't be changed yet.
new_robot_2 = database.get_robot(robot_id)
self.assertNotEqual(new_robot.get_alive(), n | ew_robot_2.get_alive())
# Actually committing changes.
database.commit()
new_robot_2 = database.get_robot(robot_id)
self.assertEqual(new_robot.get_alive(), new_robot_2.get_alive())
# Lock should be freed.
database.get_robot(robot_id, for_update=True)
database.ro... |
AutoDo/AutoDo | AutoDoApp/apps.py | Python | mit | 93 | 0 | from django. | apps import AppConfig
class AutodoappConfig(AppConfig):
name = 'AutoDoApp'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.