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 |
|---|---|---|---|---|---|---|---|---|
alpha-beta-soup/errorgeopy | errorgeopy/address.py | Python | mit | 7,782 | 0.001028 | """Contains the :code:`Address` class, representing a collection of reverse
geocoding results. Primarily, this functions as a container for a set of
:code:`errorgeopy.Location` objects after a successful reverse geocode, and
exposes methods that operate on this set of results, including:
- de-duplication
- extracting ... | zy
under the hood for matching.
Args:
expectation (s | tr): The string indicating your expected result for a
reverse geocoding operation. It should probably look like an
address. Results are returned in the order that best meets this
expected address.
Kwargs:
limit (int): The maximum number of match candidates to ret... |
karllessard/tensorflow | tensorflow/python/tpu/tpu_outside_compilation_test.py | Python | apache-2.0 | 18,249 | 0.00822 | # Copyright 2020 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... | )
def testHostMultipleInputs(self):
strategy = get_tpu_strategy()
val0 = np.ara | nge(6).reshape((2, 3)).astype(np.float32)
val1 = np.arange(6).reshape((3, 2)).astype(np.float32)
def outside_fn(arg0, arg1):
tmp = array_ops.reshape(arg1, array_ops.shape(arg0))
ret0 = arg0 + tmp
ret1 = math_ops.matmul(arg0, arg1)
ret2 = array_ops.concat([arg0, tmp], 0)
return ret... |
threema-ch/threema-msgapi-sdk-python | examples/simple_blocking.py | Python | mit | 1,625 | 0 | """
You can modify and use one of the functions below to test the gateway
service with your account.
"""
import logbook
import logbook.more
from threema.gateway import (
Connection,
GatewayError,
util,
)
from threema.gateway.simple import TextMessage
def send_via_id(connection):
"""
Send a messag... | ction=connection,
to_id='ECHOECHO',
text='Hello from the world of Python!'
)
return message.send()
def send_via_email(connection):
"""
Send a message via an email address.
"""
message = TextMessage(
connection=connection,
email='test@threem | a.ch',
text='Hello from the world of Python!'
)
return message.send()
def send_via_phone(connection):
"""
Send a message via a phone number.
"""
message = TextMessage(
connection=connection,
phone='41791234567',
text='Hello from the world of Python!'
)
r... |
UndeadMastodon/Loltris | Draw.py | Python | gpl-3.0 | 1,695 | 0.00708 |
import Log
import pygame as Pygame
def fillJob(screen, color, job):
if hasattr(job, "fillArea"):
job.fillArea(color)
else:
padding = 0
if hasattr(job, "border_width"):
## Workaround
padding = job.border_width
Pygame.draw.rect(
screen,
... | (x + width - deepness, y + deepness), (x + deepness, y + deepness), ),
)
## Bottom
Pygame.draw.polygon(
screen,
colors[2],
((x, y + height), (x + width, y + height),
(x + width - deepness, y + height - deepness), ( | x + deepness, y + height - deepness), ),
)
## Left
Pygame.draw.polygon(
screen,
colors[3],
((x, y), (x + deepness, y + deepness),
(x + deepness, y + height - deepness), (x, y + height),),
)
## Right
Pygame.draw.polygon(
... |
nephila/djangocms-apphook-setup | tests/sample_app_2/urls.py | Python | bsd-3-clause | 137 | 0 | from django. | conf.urls import url
from .views import BaseView
urlpatterns = [
url(r"^$", BaseView.as_view(), name="base-view-2"),
| ]
|
wehkamp/ansible-modules-extras | network/nmcli.py | Python | gpl-3.0 | 40,826 | 0.006515 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2015, Chris Long <alcamie@gmail.com> <chlong@redhat.com>
#
# This file is a module for Ansible that interacts with Network Manager
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
#... | h bond - miimon
downdelay:
required: False
default: None
description:
- This is only used with bond - downdelay
updelay:
required: False
default: None
description:
- Thi | s is only used with bond - updelay
arp_interval:
required: False
default: None
description:
- This is only used with bond - ARP interval
arp_ip_target:
required: False
default: None
description:
- This is only used with bond - ARP IP target... |
sqlalchemy/sqlalchemy | lib/sqlalchemy/orm/descriptor_props.py | Python | mit | 25,542 | 0 | # orm/descriptor_props.py
# Copyright (C) 2005-2022 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: https://www.opensource.org/licenses/mit-license.php
"""Descriptor properties are more "auxiliary" properties
that exist as conf... | Any]], ...
]
def __init__(self, class_=None, *attrs, **kwargs):
super().__init__()
if isinstance(class_, (Mapped, str, sql.ColumnElement)):
self.attrs = (class_,) + attrs
# will initial | ize within declarative_scan
self.composite_class = None # type: ignore
else:
self.composite_class = class_
self.attrs = attrs
self.active_history = kwargs.get("active_history", False)
self.deferred = kwargs.get("deferred", False)
self.group = kwargs.... |
swipeat/back | query/dishsearcher.py | Python | bsd-3-clause | 729 | 0.005487 | #!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# @author: Pavel Korshunov <pavelkor@gmail.com>
# @date: Fri 10 F | eb 18:43:22 2017
import abc
import six
class DishSearcher(six.with_metaclass(abc.ABCMeta, object)):
"""
General class that provides API for querying recipes databases, APIs, or cached recipes.
"""
def __init__(self, constraints):
self.constraints = list(constraints)
@abc.abstractmethod
... | eturns JSON description of dishes
"""
raise NotImplementedError("Please implement this function in derived classes") |
hzruandd/AutobahnPython | examples/twisted/websocket/streaming/message_based_server.py | Python | mit | 2,143 | 0 | ###############################################################################
#
# The MIT License (MIT)
#
# Copyright (c) Tavendo GmbH
#
# Permission is hereby granted, fr | ee of charge, to any person obtaining a copy
# of this software and associat | ed documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the fol... |
nuSTORM/gnomon | tests/test_MagneticField.py | Python | gpl-3.0 | 1,406 | 0 | from unittest import TestCase
from gnomon import MagneticField
class MockG4ThreeVector():
x = 0
y = 0
z = 0
class TestWandsToroidField(TestCase):
def setUp(self): |
self.field_minus = MagneticField.WandsToroidField('-')
self.field_plus = MagneticField.WandsToroidField('+')
self.fields = [self.field_minus, self.field_plus]
def test_PhenomModel(self):
for field in self.fields:
with self.assertRaises(ValueError):
field... | for field in self.fields:
pos = MockG4ThreeVector()
vector = field.GetFieldValue(pos, 0)
self.assertEqual(vector.x, 0)
self.assertEqual(vector.y, 0)
self.assertEqual(vector.z, 0)
pos.x = 1
vector = field.GetFieldValue(pos, 0)
... |
SonyStone/pylib | Python_tutorial.py | Python | mit | 36,258 | 0.039167 | # PPPPPPPP
# PP PP t hh
# PP - PP tt hh
# PP PP yy - yy tttttttt hh hhhh ooooooo nn nnnnn -----------... | = """
aaaaaaaaaaaaa
bbb'''bbbbbbb""bbbbbb'bbb
ccccccccccc
"""
msg # => '\aaaaaaaaaaaaa\nbbb\'\'\'bbbbbbb""bbbbbb\'bbb\nccccccccccc\n'
# raw string literal
r'C:\text\new'
# | Unicode Strings
'sp\xc4m' # => 'spÄm' # normal str string are Unicode text
b'a\xo1c' # => b'a\x01c' # bytes string are byte-based data
u'sp\u00c4m' # => 'spÄm' # The 2.X Unicode literal works in 3.3+: just str
'spam'.encode('utf8') # => b'spam'
'spam'.encode('utf16') # => b'\xf... |
abramhindle/UnnaturalCodeFork | python/testdata/launchpad/scripts/process-one-mail.py | Python | agpl-3.0 | 2,007 | 0 | #!/usr/bin/python -S
#
# Copyright 2011 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
"""Process one email message, read from stdin."""
import _pythonpath
import sys
from lp.services.config import config
from lp.services.mail.helpers import... | x, which we're avoiding here.
if len(self.args) >= 1:
from_file = file(self.args[0], 'rb')
else:
from_file = sys.stdin
self.logger.debug("reading message from %r" % (from_file,))
raw_mail = from_file.read()
self.logger.debug("got %d bytes" % len(raw_mail))... | % (file_alias,))
parsed_mail = signed_message_from_string(raw_mail)
# Kinda kludgey way to cause sendmail to just print it.
config.sendmail_to_stdout = True
handle_one_mail(
self.logger, parsed_mail,
file_alias, file_alias.http_url,
signature_timestam... |
tiagoarasilva/django-boilerplate | project_name/accounts/migrations/0001_initial.py | Python | mit | 5,076 | 0.004137 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-09-04 17:41
from __future__ import unicode_literals
from django.conf import settings
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.db.models.deletion
import django.util... | ango.db.models.deletion.CASCADE, related_name='profile', to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='ProfileType',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
... | le_type', models.CharField(choices=[('admin', 'Admin'), ('user', 'User'), ('manager', 'Manager'), ('other', 'Other')], default='admin', max_length=255)),
('profile', models.ForeignKey(blank=True, on_delete=django.db.models.deletion.CASCADE, related_name='profile_types', to='accounts.Profile')),
... |
JohnDMcMaster/uvscada | ngc/lapsten/sten_virtex.py | Python | bsd-2-clause | 1,859 | 0.002152 | from uvscada.ngc import *
import math
'''
Need to account for endmill radius to make the die actualy fit
w=0.805, h=0.789
em=0.0413
Actual used w/h: cos(45) * 0.0413 = 0.02920351
Total w/h: 0.0413
Wasted w/h: 0.0413 - 0.0292 = 0.0121
each corner
Increase by
'''
cnc = init(
#em=0.0413,
em=0.0625,... | dw
dh = math.sin(theta) * cnc.em/2
fullh = dieh + 2 * dh
main_r = 1.063
line('(theta: %0.3f rad, %0.1f deg)' % (theta, theta * 180 / math.pi), verbo | se=True)
line('(die: %0.3fw x %0.3fh)' % (diew, dieh), verbose=True)
line('(em: %0.3f)' % (cnc.em), verbose=True)
line('(died: %0.3fw x %0.3fh)' % (dw, dh), verbose=True)
line('(dief: %0.3fw x %0.3fh)' % (fullw, fullh), verbose=True)
# Original diagram
if 0:
rect_in_ul(x=-0.403, y=-0.864, w=diew, h=dieh, finishe... |
CacaoMovil/guia-de-cacao-django | cacao_app/cacao/migrations/0007_auto_20150123_1600.py | Python | bsd-3-clause | 2,739 | 0.001825 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('cacao', '0006_auto_20150119_0946'),
]
operations = [
migrations.AddField(
model_name='section',
name... | ),
migrations.AlterField(
model_name='content',
name='title',
field=models.CharField(max_length=250, verbose_name=b'Titulo'),
preserve_default=True,
),
migrations.AlterField(
model_name='guide',
name='description',
... | d(
model_name='guide',
name='image',
field=models.ImageField(upload_to=b'cacao/', verbose_name=b'Imagen'),
preserve_default=True,
),
migrations.AlterField(
model_name='guide',
name='name',
field=models.CharField(max_leng... |
CityGenerator/Megacosm-Generator | tests/test_oneliners.py | Python | gpl-2.0 | 25,299 | 0.001976 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"Fully test this module's functionality through the use of fixtures."
#
import megacosm
from flask.ext.testing import TestCase
import fakeredis
import fixtures
from megacosm import oneliners
import re
class MegacosmFlaskTestCast(TestCase):
def create_app(self):
... | fixtures.misf | ire.import_fixtures(self)
fixtures.magicitem.import_fixtures(self)
fixtures.moon.import_fixtures(self)
fixtures.motivation.import_fixtures(self)
fixtures.mundaneitem.import_fixtures(self)
fixtures.npc.import_fixtures(self)
fixtures.organization.import_fixtures(self)
... |
dguglielmi/vmc-core | vmc/thirdparty/macgen.py | Python | gpl-3.0 | 343 | 0.03207 | # macgen.py script to generate a MAC address for Red Hat Virtualization guests
#
# from http://www.linux-kvm.com/sites/default/files/macgen.py
import random
def randomMAC():
mac = [ 0x00, 0x16, | 0x3e,
random.randint(0x00, 0x7f | ),
random.randint(0x00, 0xff),
random.randint(0x00, 0xff) ]
return ':'.join(map(lambda x: "%02x" % x, mac))
|
nss350/magPy | core/project.py | Python | apache-2.0 | 14,763 | 0.034749 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 24 08:18:04 2016
@author: npop
The project holds all the information about the project
And imposes the project structure
Time Data - any time data
Spec Data - this is the fourier data
Stat Data - statistic data
TF Data - transfer functions
Cal Data - the path to the cali... | ### SAVE AND LOAD PROJECT FILES
##################
def loadProjectFile(self, filepath):
f = open(filepath, "r")
lines = f.readlines()
f.close()
for l in lines:
split = l.strip().split("=")
if "Time data path" in l:
self.setTimeDataPath(split[1].strip())
if "Spect | ra data path" in l:
self.setSpecDataPath(split[1].strip())
if "Statistics data path" in l:
self.setStatDataPath(split[1].strip())
if "TransFunc data path" in l:
self.setTransDataPath(split[1].strip())
if "Calibration data path" in l:
self.setCalDataPath(split[1].strip())
if "Image data path... |
sphax3d/gedit-plugins | plugins/commander/commander/commands/__init__.py | Python | gpl-2.0 | 12,767 | 0.00188 | # -*- coding: utf-8 -*-
#
# __init__.py - commander
#
# Copyright (C) 2010 - Jesse van den Kieboom
#
# 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
# (... | te:
def __init__(self):
self.clear()
def clear(self):
self.stack = []
def top(self):
return self.stack[0]
def run(self, ret):
ct = self.top()
if ret:
ct.retval = ct.generator.send(ret)
else:
... | t.retval
def push(self, gen):
self.stack.insert(0, Commands.Continuated(gen))
def pop(self):
if not self.stack:
return
try:
self.stack[0].generator.close()
except GeneratorExit:
pass
del self.... |
kiwiheretic/logos-v2 | reddit/migrations/0005_auto_20160518_0031.py | Python | apache-2.0 | 471 | 0 | # -*- coding: utf-8 -*-
from __future__ import | unicode_literals
from django.db import migrations, models
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('reddit', '0004_auto_20160518_0017'),
]
operations = [
migrations.AlterField(
model_name='redditcredentials',
name... | odels.ForeignKey(to=settings.AUTH_USER_MODEL, unique=True),
),
]
|
ioflo/maze | maze/__init__.py | Python | mit | 162 | 0.018519 | """ maze behaviors modules"""
#pr | int "\nPackage at%s" % __path__[0]
__all__ = ['beha | ving',]
for m in __all__:
exec "from . import %s" % m #relative import
|
arannasousa/pagseguro_xml | pagseguro_xml/consultas/__init__.py | Python | gpl-2.0 | 474 | 0.006356 | # coding=utf-8
# ---------------------------------------------------------------
# Desenvolvedor: Arannã Sousa Santos
# Mês: 12
# Ano: 2015
# Projeto: | pagseguro_xml
# e-mail: asousas@live.com
# ---------------------------------------------------------------
from .v2 import ApiPagSeguroConsulta as ApiPagSeguroConsulta_v2, CONST as CONST_v2
from .v3 import ApiPagSeguroConsulta as ApiPagSeguroConsulta_v3, C | ONST as CONST_v3 |
Raynxxx/CUIT-ACM-Website | server/article_server.py | Python | mit | 6,348 | 0.008875 | # coding=utf-8
from __init__ import *
from dao.dbArticle import SolutionArticle
from dao.dbTag import Tag
def generate_tags(data):
tag_list = []
for tag in data:
if tag == '':
continue
has_tag = Tag.query.filter(Tag.name == tag).first()
if not has_tag:
new_tag = ... | st[0].strip() == "" :
has.md_shortcut = content_list[1]
has.md_conten | t = ""
else:
has.md_shortcut = content_list[0]
has.md_content = content_list[1]
oj = form.problem_oj_name.data
pid = form.problem_pid.data
has.is_top = form.is_top.data
has.is_draft = is_draft
has.problem_oj_name = oj
has.problem_pid = pid
has.tags = tags
has.save()
... |
kobtea/gof | chain_of_responsibility.py | Python | mit | 2,871 | 0 | #!/usr/bin/env python
class Trouble:
def __init__(self, number):
self.number = number
def __str__(self):
return '<Trouble: {}>'.format(self.number)
class Support:
def __init__(self, name):
self.name = name
self.next = None
def set_next(self, next):
self.next... | 31> is resolved by [ Elmo ].
<Trouble: 264> is resolved by [ Fred ].
<Trouble: 297> is resolved by [ Elmo | ].
<Trouble: 330> cannot be resolved.
<Trouble: 363> is resolved by [ Elmo ].
<Trouble: 396> cannot be resolved.
<Trouble: 429> is resolved by [ Charlie ].
<Trouble: 462> cannot be resolved.
<Trouble: 495> is resolved by [ Elmo ].
'''
|
jeremy-ma/gmmmc | gmmmc/tests/test_GMMPrior.py | Python | mit | 3,901 | 0.000513 | from unittest import TestCase
from gmmmc.priors.prior import *
class TestGMMPrior(TestCase):
def setUp(self):
self.covars = np.array([[3, 5], [2, 1]])
means = np.array([[1.0, 2], [3, 4]])
self.weights = np.array([0.3, 0.7])
prior_width = 1.0 * np.ones((2, 2))
self.prior = ... | (self.prior.log_prob(covars), 0.0)
self.assertEqual(self.prior.log_prob(covars * 4), -np.inf)
covars[3][2] = -10
self.assertEqual(self.prior.log_prob(covars), -np.inf)
def test_log_prob_single(self):
covar = np.ones((10))
self.assertEqua | l(self.prior.log_prob_single(covar, 3), 0.0)
self.assertEqual(self.prior.log_prob_single(covar * 2, 4), -np.inf)
covar[3] = -10
self.assertEqual(self.prior.log_prob_single(covar, 3), -np.inf)
def test_sample(self):
for i in xrange(100):
sample = self.prior.sample()
... |
lissyx/build-mozharness | configs/b2g_bumper/v2.2.py | Python | mpl-2.0 | 3,880 | 0.003093 | #!/usr/bin/env python
config = {
"exes": {
# Get around the https warnings
"hg": ['/usr/local/bin/hg', "--config", "web.cacerts=/etc/pki/tls/certs/ca-bundle.crt"],
"hgtool.py": ["/usr/local/bin/hgtool.py"],
"gittool.py": ["/usr/local/bin/gittool.py"],
},
'gecko_pull_url': 'ht... | tion/gaia-2_2',
'gaia_revision_file': 'b2g/config/gaia.json',
'gaia_max_revisions': 5,
# Which git branch this hg repo corresponds to
'gaia_git_branch': 'v2.2',
'gaia_git_repo': 'https://git.mozilla.org/releases/gaia.git',
'gaia_mapper_project': 'gaia',
'mapper_url': ' | http://cruncher.build.mozilla.org/mapper/{project}/{vcs}/{rev}',
'devices': {
'dolphin': {
'ignore_projects': ['gecko'],
'ignore_groups': ['darwin'],
},
'emulator-l': {
'ignore_projects': ['gecko'],
'ignore_groups': ['darwin'],
},
... |
ericsomdahl/compfiOne | HW2/hw2.py | Python | unlicense | 2,580 | 0.00155 | __author__ = 'eric'
import pandas as pd
import numpy as np
import math
import copy
import QSTK.qstkutil.qsdateutil as du
import datetime as dt
import QSTK.qstkutil.DataAccess as da
import QSTK.qstkutil.tsutil as tsu
import QSTK.qstkstudy.EventProfiler as ep
dataObj = da.DataAccess('Yahoo')
def find_events(ls_symbol... | 5.0 and f_symprice_today < 5.0:
df_events[s_sym].ix[ldt_timestamps[i]] = 1
return df_events
def create_study(ls_symbols, ldt_timestamps, s_study_name):
global dataObj
print "Grabbing data to perform {0}".format(s_study_name)
ls_keys = ['close', 'actual_close']
ldf_data = dataObj... | _key] = d_data[s_key].fillna(method='ffill')
d_data[s_key] = d_data[s_key].fillna(method='bfill')
d_data[s_key] = d_data[s_key].fillna(1.0)
df_events = find_events(ls_symbols, d_data)
print "Creating Study"
ep.eventprofiler(df_events, d_data, i_lookback=20, i_lookforward=20,
... |
stwunsch/volk-sha256 | gen/volk_sha256_compile_utils.py | Python | gpl-3.0 | 2,200 | 0.005455 | #!/usr/bin/env python
#
# Copyright 2012 Free Software Foundation, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version... | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://w | ww.gnu.org/licenses/>.
#
import optparse
import volk_sha256_arch_defs
import volk_sha256_machine_defs
def do_arch_flags_list(compiler):
output = list()
for arch in volk_sha256_arch_defs.archs:
if not arch.is_supported(compiler): continue
fields = [arch.name] + arch.get_flags(compiler)
... |
sinabahram/GrowTheTribe | GrowTheTribe/apps/talks/models.py | Python | gpl-3.0 | 2,914 | 0 | from django.db.models import Model, CharField, DateField, URLField, \
DateTimeField, TextField, ForeignKey, permalink, IntegerField
from taggit.managers import TaggableManager
from django.contrib.auth.models import User
class Conference(Model):
title = CharField(max_length=300)
start_date = DateField('con... | .pk])
class Resource(Model):
talk = ForeignKey(Talk)
title = CharField(max_length=300)
description = TextField()
url = URLField()
tags = TaggableManager()
created = DateTimeField(auto_now_add=True)
updated = | DateTimeField(auto_now=True)
@property
def name(self):
return self.title
def __unicode__(self):
return self.title
@permalink
def get_absolute_url(self):
return ('resource_detail', [self.pk])
|
sadanandb/pmt | src/tactic/ui/tools/custom_layout_edit_wdg.py | Python | epl-1.0 | 99,653 | 0.004837 | ###########################################################
#
# Copyright (c) 2005-2008, Southpaw Technology
# All Rights Reserved
#
# PROPRIETARY INFORMATION. This software is proprietary to
# Southpaw Technology, and is not to be reproduced, transmitted,
# or disclosed in any way without written ... | = DivWdg()
top.add(action_wdg)
action_wdg.add_gradient("background", "background", -10)
action_wdg.add_sty | le("margin: -10px -10px 10px -10px")
action_wdg.add_style("padding: 5px")
"""
delete = ActionButtonWdg(title='Remove', tip='Remove from Canvas')
action_wdg.add(delete)
delete.add_style("float: right")
delete.add_behavior( {
'type': 'click_up',
'cbjs_actio... |
jonasjberg/autonameow | autonameow/core/autonameow.py | Python | gpl-2.0 | 17,107 | 0.000877 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright(c) 2016-2020 Jonas Sjöberg <autonameow@jonasjberg.com>
# Source repository: https://github.com/jonasjberg/autonameow
#
# This file is part of autonameow.
#
# autonameow is free software: you can redistribute it and/or modify
# it under the terms of t... | enc.displayable_path(filepath_default_config)
),
'cache_directory_path': '"{!s}"'.format(
enc.displayable_path(filepath_config)
| )
}
self.ui.options.prettyprint_options(self.opts, include_opts)
def _dump_registered_meowuris(self):
if self.opts.get('verbose'):
cf_regi |
SUSE/azure-sdk-for-python | azure-mgmt-resource/azure/mgmt/resource/subscriptions/v2016_06_01/models/subscription.py | Python | mit | 2,737 | 0.000365 | # 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 ... | 'id': {'readonly': True},
'subscription_id': {'readonly': True},
'display_name': {'readonly': True},
'state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'subscription_id': {'key': 'subscriptionId', 'type': 'str'},
'display_name':... | 'key': 'subscriptionPolicies', 'type': 'SubscriptionPolicies'},
'authorization_source': {'key': 'authorizationSource', 'type': 'str'},
}
def __init__(self, subscription_policies=None, authorization_source=None):
self.id = None
self.subscription_id = None
self.display_name = None... |
AlanKuurstra/vidi3d | vidi3d/helpers.py | Python | gpl-3.0 | 623 | 0 | from collections import namedtuple
import numpy as np
from .definitions import ImageDisplayType
Event = na | medtuple('Event', ['x', 'y'])
def apply_display_type(complex_values, display_type):
if display_type == ImageDisplayType.mag:
data = np.abs(complex_values)
elif display_type == ImageDisplayType.phase:
data = np.angle(complex_values)
elif display_type == ImageDisplayType.real:
data =... | elif display_type == ImageDisplayType.imag:
data = np.imag(complex_values)
else:
raise ValueError("Display type not recognized")
return data
|
NumberZeroSoftware/PDFINVEST | pdfapp/migrations/0011_document_html_text_string.py | Python | mit | 468 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-25 01:59
from __future__ import uni | code_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pdfapp', '0010_auto_20170225_0034'),
]
operations = [
migrations.AddField(
model_name='document',
name='html_text_string',
field=models.Te... | ue),
),
]
|
offlinehacker/flumotion | flumotion/component/component.py | Python | gpl-2.0 | 31,473 | 0.000445 | # -*- Mode: Python; test-case-name: flumotion.test.test_component -*-
# vi:si:et:sw=4:sts=4:ts=4
#
# Flumotion - a streaming media server
# Copyright (C) 2004,2005,2006,2007,2008 Fluendo, S.L. (www.fluendo.com).
# All rights reserved.
# This file may be distributed and/or modified under the terms of
# the GNU General ... | erredLogin(self, d):
d | ef remoteDisconnected(remoteReference):
if reactor.killed:
self.log('Connection to manager lost due to shutdown')
else:
self.warning('Lost connection to manager, '
'will attempt to reconnect')
def loginCallback(reference):
... |
rvilalta/OFC_TAPI_SC | onos_api/onos_topology.py | Python | apache-2.0 | 586 | 0.011945 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import requests
from requests.auth import HTTPBasicAuth
import json
IP='127.0.0.1'
PORT='8181'
USER='onos'
PASSWORD='rocks'
def retrieveTopology(ip, port, user, pa | ssword):
http_json = 'http://' + ip + ':' + port + '/onos/v1/links'
response = requests.get(http_json, auth=HTTPBasicAuth(user, password))
topology = response.json()
return topology
if __name__ == "__main__":
print "Reading network-topology"
topo = retrieveTopology(IP, PORT, USER, PASSWORD)
... | |
lucienfostier/gaffer | python/GafferSceneUI/EncapsulateUI.py | Python | bsd-3-clause | 2,924 | 0.010944 | ##########################################################################
#
# Copyright (c) 2017, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistrib... |
# disclaimer in the documentation and/or other materia | ls provided with
# the distribution.
#
# * Neither the name of John Haddon nor the names of
# any other contributors to this software may be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY TH... |
yevgnenll/but | but/users/models/__init__.py | Python | mit | 71 | 0 | from .user import U | ser
f | rom .phone_certificate import PhoneCertificate
|
trnewman/VT-USRP-daughterboard-drivers_python | gr-atsc/src/python/fpll.py | Python | gpl-3.0 | 2,429 | 0.028407 | #!/usr/bin/env python
#
# Copyright 2004,2005 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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, or (at your opt... | * IF_freq / input_rate
t=[]
for i in range(len(tt)):
t += [tt[i] * 2. * math.cos(arg * i)]
rrc = gr.fir_filter_fff(1, t)
fpll = atsc.fpll()
pilot_freq = IF_freq - 3e6 + 0.31e6
lower_edge = 6e6 - 0.31e6
upper_edge = IF_freq - 3e6 + pilot_freq
transition_width = upper_edge - lower_edge
lp_coeffs = gr.firdes... | _edge) * 0.5,
transition_width,
gr.firdes.WIN_HAMMING);
lp_filter = gr.fir_filter_fff (1,lp_coeffs)
alpha = 1e-5
iir = gr.single_pole_iir_filter_ff(alpha)
remove_dc = gr.sub_ff()
out = gr.file_sink(gr.sizeof_float,"/tmp/atsc_pipe_3")
# out = gr.file_sink(gr... |
thempel/adaptivemd | adaptivemd/misc/archive.py | Python | lgpl-2.1 | 2,560 | 0.000391 | ##############################################################################
# adaptiveMD: A Python Framework to Run Adaptive Molecular Dynamics (MD)
# Simulations on HPC Resources
# Copyright 2017 FU Berlin and the Authors
#
# Authors: Jan-Hendrik Prinz
# Contributors:
#
# `adaptiveMD` is free software: ... | the | directory to dump all simulations to
"""
super(Archiver, self).__init__()
self.target = target
def to_dict(self):
return {
'target': self.target
}
def task_archive(self, files):
"""
Create a task that computes an msm using a given set of tr... |
neurodroid/gnoom | py/gnoominit.py | Python | gpl-2.0 | 15,471 | 0.006916 | import os
import sys
import time
import numpy as np
import bge.logic as GameLogic
import settings
import nicomedilib as ncl
import arduino_serial
import serial
import xinput
import random
import copy
from PIL import Image
import gnoomcomm as gc
import gnoomio as gio
import gnoomutils as gu
import chooseWalls
if sett... | igch, gDevrange)
outfrch = ncl.nichannel(devouttrigch, gOutfrchan, gOuttrigsubdev, fdouttrigch, gDevrange)
outleftch = ncl.nichannel(devouttrigch, gOutle | ftchan, gOuttrigsubdev, fdouttrigch, gDevrange)
outrightch = ncl.nichannel(devouttrigch, gOutrightchan, gOuttrigsubdev, fdouttrigch, gDevrange)
outexpch = ncl.nichannel(devouttrigch, gOutexpchan, gOuttrigsubdev, fdouttrigch, gDevrange) #MC2015
ncl.init_comedi_dig(intrigch, outtrigch, outf... |
watchdogpolska/feder | feder/institutions/migrations/0006_auto_20160907_2016.py | Python | mit | 828 | 0 | # Generated by Django 1.10.1 on 2016-09-07 20:16
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("institutions", "0005_auto_20160907_1814")]
operations = [
migrations.AlterModelOptions(
name="email",
options={
"ordering... | "verbose_name_plural": "Emails",
},
),
migrations.AlterModelOptions(
name="tag",
options={
"ordering": ["name"],
"verbose_name": "Tag",
"verbose_name_plural": "Tags",
},
),
migrations.Al... | ,
]
|
DeadSix27/python_cross_compile_script | packages/dependencies/python3_libs.py | Python | mpl-2.0 | 349 | 0.051576 | {
'repo_type' : 'git',
'url' : 'https://github.com/DeadSix27/p | ython_mingw_libs.git',
'needs_configure' : False,
'needs_make_install' : False,
'build_options' : 'PREFIX={targe | t_prefix} GENDEF={mingw_binpath}/gendef DLLTOOL={mingw_binpath}/{cross_prefix_bare}dlltool',
'_info' : { 'version' : '3.8.2', 'fancy_name' : 'Python (library-only)' },
} |
anhusa/pyfuzz | libfuzz/fuzzer.py | Python | bsd-3-clause | 6,407 | 0.001717 |
import sys
import copy
import time
import signal
import logging
import importlib
from libfuzz.process_management import ProcessManagement
class Fuzzer():
"""
The base fuzzer class provides a standard handler
interfaces to be used from external libraries like
ProcessManagement.
"""
def __ini... | = self._load_module("modules.fuzzing", module)
self.fuzzer = fuzzing_module.FuzzingModule(self.log)
def _load_instrumentation_module(self, module):
"""
See _load_module.
"""
instrumentation_module = self._load_module("modules.instrumentation", module)
self.instrument... | handler specifies how new processes are created.
Additional attributes for the Process object can be added
as needed in the _new_process_handler() function.
"""
if not hasattr(self, "_new_process_handler"):
self.log.error("_new_process_handler() does not exists")
... |
kumar303/rockit | vendor-local/boto/route53/connection.py | Python | bsd-3-clause | 12,631 | 0.001663 | # Copyright (c) 2006-2010 Mitch Garnaat http://garnaat.org/
# Copyright (c) 2010, Eucalyptus Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without | restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the | Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ... |
faun/django_test | tests/regressiontests/generic_views/views.py | Python | bsd-3-clause | 3,421 | 0.002923 | from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.utils.decorators import method_decorator
from django.views import generic
from regressiontests.generic_views.models import Artist, Author, Book, Page
from regressiontests.generic_views.forms import Author... | View):
queryset = Page.objects.all()
template_name_field = 'template'
class DictList(generic.ListView):
"""A ListView that doesn't use a model."""
queryset = [
{'first': 'John', 'last': 'Lennon'},
{'last': 'Yoko', 'last': 'Ono'}
]
template_name = 'generic_views/list.html'
cl... | = Author.objects.all()
class ArtistCreate(generic.CreateView):
model = Artist
class NaiveAuthorCreate(generic.CreateView):
queryset = Author.objects.all()
class AuthorCreate(generic.CreateView):
model = Author
success_url = '/list/authors/'
class SpecializedAuthorCreate(generic.CreateView):
... |
exseivier/scripts | ban-4.0/runsyl/joinCounts.py | Python | gpl-3.0 | 1,216 | 0.015625 | #!/usr/bin/env python
"""
Concatenates the mapped reads counts of all tratments obtained from analysis
with programms like HTSeq-count, Kallisto, etc for every gene name
Requieres a filename list with the counts or abundance text files, and the
OUTPUT path
Example:
./joinCounts.py <filelist.txt> <outputfile.txt> <colu... | strip()
for entry in PROCESSING_FILE:
entry = entry.strip()
fields = entry.split("\t")
if len(fields) < 2:
continue
try:
data_structure[fields[0]].append(round(float(fields[column-1])))
except Exception:
da | ta_structure[fields[0]] = [round(float(fields[column-1]))]
PROCESSING_FILE.close()
OUT = open(OUTPUT, "w+")
OUT.write("ID%s\n" % header)
for key, value in data_structure.iteritems():
OUT.write("%s" % key)
for item in value:
OUT.write("\t%.4f" % item)
OUT.write("\n")
OUT.close()
|
PwnArt1st/searx | tests/unit/engines/test_subtitleseeker.py | Python | agpl-3.0 | 7,429 | 0.001077 | from collections import defaultdict
import mock
from searx.engines import subtitleseeker
from searx.testing import SearxTestCase
class TestSubtitleseekerEngine(SearxTestCase):
def test_request(self):
query = 'test_query'
dicto = defaultdict(dict)
dicto['pageno'] = 1
params = subti... | ght:16px;" class="icon">
1039 Subs
</div>
<div class="boxRowsInner grey-web f10" style="width:130px;">
<img src="http://static.subtitleseeker.com/images/arrow_refresh_small.png"
style="width:16px; height:16px;" class="icon">
1 h... | iv class="clear"></div>
</div>
"""
subtitleseeker.language = 'English'
response = mock.Mock(text=html, search_params=dicto)
results = subtitleseeker.response(response)
self.assertEqual(type(results), list)
self.assertEqual(len(results), 1)
self.assertEqual... |
sdrogers/ms2ldaviz | ms2ldaviz/motifdb/migrations/0002_auto_20190218_1136.py | Python | mit | 1,323 | 0.002268 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2019-02-18 11:36
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('basicviz', '0088_auto_20190218_1136'),
('motifdb',... | rue, serialize=False, to='basicviz.Mass2Motif')),
],
bases=('basicviz.mass2motif',),
),
migrations.AddField(
model_name='mdbmotifset',
name='description',
field=models.TextField(null=True),
),
migrations.AddField(
mo... | reSet'),
),
migrations.AddField(
model_name='mdbmotif',
name='motif_set',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='motifdb.MDBMotifSet'),
),
]
|
GPNMilano/PyPRPImporter | PyPRPImport/uruprp_import.py | Python | gpl-2.0 | 5,276 | 0.018196 | #!BPY
#
# $Id: uruprp_import.py 861 2007-11-05 23:03:39Z trylon $
#
# Copyright (C) 2005-2008 Alcugs PyPRP Project Team and 2008 GoW PyPRP Project Team
# See the file AUTHORS for more info about the team
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GN... | tures = True
Blender.Window.FileSelector(open | _file,fname)
#Main code
do_main()
|
noamelf/Open-Knesset | video/management/commands/add_video.py | Python | bsd-3-clause | 1,246 | 0.016051 | # encoding: utf-8
from django.core.management.base import NoArgsCommand
from optparse import make_option
from video.management.commands.sub_commands.AddVideo import AddVideo
class Command(NoArgsCommand):
option_list = NoArgsCommand.option_list + (
make_option('--video-link',action='store',dest='video-lin... | s',
help="list supported video link types and form | ats"),
make_option('--object-type',action='store',dest='object-type',
help="set the object type, currently only member is supported"),
make_option('--object-id',action='store',dest='object-id',
help="set the object id that the video will be related to"),
make_option('--st... |
cesarpazguzman/The-Eternal-Sorrow | dependencies/luabind/boost-build/test/project_test1.py | Python | apache-2.0 | 1,956 | 0.005112 | #!/usr/bin/python
# Copyright 2002 Dave Abrahams
# Copyright 2002, 2003, 2004 Vladimir Prus
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
from BoostBuild import Tester
import os
t = Tester("--build-system=project-tes... | /include <threading>multi
* Default build:
* Source location: %(root-dir)s
* Projects to build: dir dir2
'/boost-build-test-project-1/dir':
* Parent project: %(root-dir)s
* Requirements: <include>/home/ghost/local/include <threading>multi
* Default build: <variant>release
* Source l | ocation: %(root-dir-prefix)sdir/src
* Projects to build:
"""
# Test that correct project structure is created when jam is invoked
# outside of the source tree.
expected = (expected_output1 + expected_output2 + expected_output3) % \
{"root-dir": "project-test1",
"root-dir-prefix": "project-test1/" }
t.run_bu... |
foursquare/commons-old | src/python/twitter/pants/targets/python_tests.py | Python | apache-2.0 | 1,972 | 0.002028 | # ==================================================================================================
# Copyright 2011 Twitter, Inc.
# --------------------------------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use thi... | ss PythonTests(PythonTarget):
def __init__(self | , name, sources, resources=None, dependencies=None,
timeout=Amount(2, Time.MINUTES),
soft_dependencies=False):
"""
name / sources / resources / dependencies: See PythonLibrary target
timeout: Amount of time before this test should be considered timed-out
[D... |
Kozea/WeasyPrint | weasyprint/layout/flex.py | Python | bsd-3-clause | 38,587 | 0 | """Layout for flex containers and flex-items."""
import sys
from math import inf, log10
from ..css.properties import Dimension
from ..formatting_structure import boxes
from .percent import resolve_one_percentage, resolve_percentages
from .preferred import max_content_width, min_content_width
from .table import find_i... | n_width == 'auto':
specified_size = child.width if child.width != 'auto' else inf
if isinstance(child, boxes.ParentBox):
new_child = child.copy_with_children(child.ch | ildren)
else:
new_child = child.copy()
new_child.style = child.style.copy()
new_child.style['width'] = 'auto'
new_child.style['min_width'] = Dimension(0, 'px')
new_child.style['max_width'] = Dimension(inf, 'px')
content_size = min_c... |
perfsonar/pscheduler | pscheduler-server/pscheduler-server/api-server/pschedulerapiserver/dbcursor.py | Python | apache-2.0 | 3,080 | 0.001623 | #
# Database Cursor
#
import pscheduler
import psycopg2
import sys
import threading
import time
from .log import log
module = sys.modules[__name__]
module.tries = 10
module.interval = 0.5
module.threadlocal = threading.local()
module.dsn = None # DSN for DB connection
def dbcursor_init(dsn):
"""Initialize... | ""
log.debug("QUERY: %s, %s", query, args)
while tries > 0:
cursor = dbcursor()
try:
cursor.execute(query, args)
except psycopg2.OperationalError as ex:
log.debug("Operational Error: %s", ex)
cursor.close()
tries -= 1
if tri... | text = str(ex)
location = text.find("\nCONTEXT: ")
if location > -1:
ex.args = (text[0:location],)
log.debug("EX: %s %s", type(ex), ex)
raise ex
break
rows = cursor.rowcount
if rows < 0:
raise psycopg2.Error("No resul... |
vigilo/vigiconf | src/vigilo/vigiconf/test/test_xsd_hosttemplate.py | Python | gpl-2.0 | 732 | 0.004098 | # vim: set fileencoding=utf-8 sw=4 ts=4 et :
# pylint: disable-msg=C0111,W0212,R0904
# Copyright (C) 2011-2020 CS GROUP - France
# License: GNU GPL v2 <http://www.gnu.org/licenses/gpl-2.0.html>
from __future__ import absolute_import
from .test_xsdutil import XSDTest
class HosttemplateXSD(XSDTes | t):
"""
Test du fichier hosttemplate.xsd.
The hosttemplate.xsd file is used to validate host te | mplates xml files
"""
xsd_file = "hosttemplate.xsd"
xml_ok_files = {
"hosttemplates/ok": [
"interleaved_tags.xml",
"passive_tags.xml",
],
"../../../conf.d/hosttemplates": ["*.xml"],
}
xml_ko_files = {"hosttemplates/ko":[
"linux.x... |
trzemecki/dicttools | doc/source/conf.py | Python | apache-2.0 | 9,599 | 0.000104 | # -*- coding: utf-8 -*-
#
# Dicttools documentation build configuration file, created by
# sphinx-quickstart on Sun Jul 03 11:45:55 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
# autogenerated file.
#
#... | ,
}
# Grouping the document tree into LaTeX files | . List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'Dicttools.tex', u'Dicttools Documentation',
u'Leszek Trzemecki', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# ... |
team-ferret/pip-in-toto | pip/toto/ssl_crypto/ed25519_keys.py | Python | mit | 14,560 | 0.009478 | """
<Program Name>
ed25519_keys.py
<Author>
Vladimir Diaz <vladimir.v.diaz@gmail.com>
<Started>
September 24, 2013.
<Copyright>
See LICENSE for licensing information.
<Purpose>
The goal of this module is to support ed25519 signatures. ed25519 is an
elliptic-curve public key signature scheme, its main s... | m(). The random bytes
# returned should be suitable for cryptographic use and is OS-specific.
# Raise 'NotImplementedError' if a randomness source is not found.
# ed25519 seed keys are fixed at 32 bytes (256-bit keys).
# http://blog.mozilla.org/warner/2011/11/29/ed25519-keys/
seed = os.urandom(32)
public ... | _key = nacl.signing.SigningKey(seed)
public = nacl_key.verify_key.encode(encoder=nacl.encoding.RawEncoder())
except NameError: # pragma: no cover
message = 'The PyNaCl library and/or its dependencies unavailable.'
raise ssl_commons__exceptions.UnsupportedLibraryError(message)
return public, seed
... |
dhp-denero/LibrERP | stock_picking_filter/__openerp__.py | Python | agpl-3.0 | 1,611 | 0 | # - | *- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
#
# Copyright (C) 2014 Didotech srl (<http://www.didotech.com>).
#
# All Rights Reserved
#
# This program is free software: you can redistribu... | n) any later version.
#
# This program 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 ... |
elfnor/sverchok | nodes/generators_extended/generative_art.py | Python | gpl-3.0 | 15,917 | 0.000565 | # ##### BEGIN GPL LICENSE BLOCK #####
#
# 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 distrib... | return shapes
def _evaluate(self, entry):
stack = [entry]
shapes = []
no | bjects = 0
while len(stack) > 0:
if nobjects > self._maxObjects:
print('max objects reached')
break
rule, depth, matrix = stack.pop()
local_max_depth = self._maxDepth
if "max_depth" in rule.attrib:
local_max_depth ... |
hlzz/dotfiles | graphics/VTK-7.0.0/Rendering/Core/Testing/Python/TestOutOfRangeDiscretizableColorTransferFunction.py | Python | bsd-3-clause | 1,475 | 0 | #!/usr/bin/env python
import sys
import vtk
from vtk.test import Testing
useBelowRangeColor = 0
if sys.argv.count("--useBelowRangeColor") > 0:
useBelowRangeColor = 1
useAboveRangeColor = 0
if sys.argv.count("--useAboveRangeColor") > 0:
useAboveRangeColor = 1
cmap = vtk.vtkDiscretizableColorTrans... | er.SelectColorArray("Normals")
mapper.ColorByArrayComponent("Normals", 0)
mapper.SetLookupTable(cmap)
mapper.UseLookupTableScalarRangeOn()
mapper.InterpolateScalarsBeforeMappingOn()
actor = vtk.vtkActor()
actor.SetMapper(mapper)
renderer = vtk.vtkRenderer()
renderer.AddActor(actor)
renderer.ResetCamera()
... | ()
renWin.AddRenderer(renderer)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
iren.Initialize()
renWin.Render()
|
torkelsson/meta-package-manager | meta_package_manager/tests/case.py | Python | gpl-2.0 | 3,430 | 0 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2016-2018 Kevin Deldycke <kevin@deldycke.com>
# and contributors.
# 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 F... | m command, print output and return results. """
code, output, error = run(*args)
| self.print_cli_output(args, output)
# Print some more debug info.
print("Return code: {}".format(code))
if error:
print(error)
return code, output, error
def invoke(self, *args):
""" Executes Click's CLI, print output and return results. """
resu... |
Winawer/CanIGo | CanIGoPee/wsgi.py | Python | mit | 393 | 0.002545 | """
WSGI config for CanIGoPee project.
It exposes the WSGI callable as a module-level variable named ``applica | tion``.
For more information on this file, see
https://docs.djangoproject.com/en/1. | 7/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CanIGoPee.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
|
albertz/music-player | mac/pyobjc-framework-Cocoa/Examples/OpenGL/OpenGLDemo/OpenGLDemo.py | Python | bsd-2-clause | 1,734 | 0.002884 | """OpenGLDemo.py -- A simple demo of using OpenGL with Cocoa
To build the demo program, run this line in Terminal.app:
$ python setup.py py2app -A
This creates a directory "dist" containing OpenGLDemo.app. (The
-A option causes the files to be symlinked to the .app bundle instead
of copied. This means you don't ... | or_(self, sender):
self.color_index = sender.tag()
self.setNeedsDisplay_(True)
def drawRect_(self, ((x, y), (w, h))):
glViewport(0, 0, w, h)
clear_color = [0.0]*4
clear_color[self.color_index] = 1.0
glClearColor(*clear_color)
glClear(GL_COLOR_BUFFER_BIT|GL_DE... | _BIT)
self.openGLContext().flushBuffer()
if __name__ == "__main__":
AppHelper.runEventLoop()
|
batousik/Python2-Diamond | setup.py | Python | mit | 1,233 | 0.001622 | from setuptools import setup, find_packages
from codecs import open # To use a consistent encoding
from os import path
from setuptools.command.test import test a | s test_command
import sys
class Tox(test_command):
# user_options = [('tox-args=', 'a', "Arguments to pass to tox")]
def initialize_options(self):
test_command.initialize_options(self)
self.tox_args = None
def finalize_options(self):
test_command.finalize_options(self)
se... | .test_suite = True
def run_tests(self):
import tox
errcode = tox.cmdline(self.test_args)
sys.exit(errcode)
here = path.abspath(path.dirname(__file__))
print(here)
with open(path.join(here, 'DESCRIPTION.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='Python2... |
ganeshgore/myremolab | server/src/test/unit/voodoo/gen/loader/APItype1.py | Python | bsd-2-clause | 422 | 0.002375 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2005 onwards University of Deusto
# All rights reserved.
#
# This software is licensed as described in the | file COPYING, which
# you should have received as part of this distribution.
#
# This software consists of contributions made by many individuals,
# listed below:
#
# Author: Pablo Ord | uña <pablo@ordunya.com>
#
methods = ['method_name_1','method_name_2']
|
Si-elegans/Web-based_GUI_Tools | cenet/migrations/0007_auto_20160806_1502.py | Python | apache-2.0 | 710 | 0.001408 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
class Migration(migrations.Migration):
dependencies = [
('cenet', '0006_auto_20160801_1939'),
| ]
operations = [
migrations.AddField(
model_name='cenetwork',
name='muscleModel',
field=models.IntegerField(default=1),
preserve_default=True,
),
migrations.AlterField(
model_name='cenetwor | k',
name='updated',
field=models.DateTimeField(default=datetime.datetime(2016, 8, 6, 15, 2, 45, 979000), auto_now=True),
preserve_default=True,
),
]
|
jasmine/jasmine-py | jasmine/result.py | Python | mit | 1,216 | 0 | class Result():
def __init__(
self,
status=None,
full_name=None,
failed_expectations=None,
deprecation_warnings=None,
runnable_id=None,
description=None,
pending_reason=None
):
if failed_expectations is None:... | :
return self._status
@property
def full_name(self):
return self._full_name
@property
def failed_expectations(self):
return self._failed_expectations
@property
def deprecation_warnings(self):
return self._deprecation_warnings
@property
def runnable_id(... | (self):
return self._description
@property
def pending_reason(self):
return self._pending_reason
|
dungvtdev/upsbayescpm | bayespy/inference/vmp/nodes/tests/test_categorical_markov_chain.py | Python | mit | 7,353 | 0.009656 | ################################################################################
# Copyright (C) 2014 Jaakko Luttinen
#
# This file is licensed under the MIT License.
################################################################################
"""
Unit tests for bayespy.inference.vmp.nodes.categorical_markov_chai... | age_to_child()
self.assertAllClose(u[0],
| [0.5, 0.5])
self.assertAllClose(u[1],
[ [[0.25, 0.25],
[0.25, 0.25]],
[[0.25, 0.25],
[0.25, 0.25]],
[[0.25, 0.25],
... |
jawrainey/sris | sris/manager.py | Python | mit | 7,789 | 0.000385 | from sris import db, models
from messenger import Messenger
from service import SMSService
from datetime import datetime
class Manager:
"""
The middle-man of interaction between messenger and the SMS service.
"""
def __init__(self):
self.config = self.__load_config_file()
self.messenge... | else:
print 'Message received was response t | o a RS. Sending OEQ.'
response = self.__select_question(number)
if response:
self.__save_message(number, patient_message, 'received')
self.__save_message(number, response, 'sent')
print 'The response (%s) has been saved to the database.' % response
... |
Alberto-Beralix/Beralix | i386-squashfs-root/usr/share/pyshared/orca/scripts/apps/packagemanager/__init__.py | Python | gpl-3.0 | 850 | 0.001176 | # Orca
#
# Copyright 2005-2009 Sun Microsystems Inc.
#
# This library 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 2.1 of the License, or (at your option) any later version.
#
# This... | NU Lesser General Public
# License along with this | library; if not, write to the
# Free Software Foundation, Inc., Franklin Street, Fifth Floor,
# Boston MA 02110-1301 USA.
"""Custom script for Packagemanager."""
from script import Script
|
jinankjain/zamboni | sites/altdev/settings_base.py | Python | bsd-3-clause | 5,851 | 0.000513 | """private_base will be populated from puppet and placed in this directory"""
import logging
import os
import dj_database_url
from lib.settings_base import (CACHE_PREFIX, ES_INDEXES,
KNOWN_PROXIES, LOGGING, HOSTNAME)
from .. import splitstrip
import private_base as private
ENGAGE_RO... | Backend'
EMAIL_HOST = private.EMAIL_HOST
DEBUG = False
TEMPLATE_DEBUG = DEBUG
DEBUG_PROPAGATE_EXCEPTIONS = False
SESSION_COOKIE_SECURE = True
REDIRECT_SECRET_KEY = private.REDIRECT_SECRET_KEY
ADMINS = ()
DATABASES = {}
DATABASES['default'] = dj_database_url.parse(private.DATABASES_DEFAULT_URL)
DATABASES['default']['... | d': 'SET storage_engine=InnoDB'}
DATABASES['slave'] = dj_database_url.parse(private.DATABASES_SLAVE_URL)
DATABASES['slave']['ENGINE'] = 'mysql_pool'
DATABASES['slave']['OPTIONS'] = {'init_command': 'SET storage_engine=InnoDB'}
DATABASES['slave']['sa_pool_key'] = 'slave'
DATABASE_POOL_ARGS = {
'max_overflow': 10,
... |
amylittleyang/OtraCAD | cadnano25/cadnano/gui/views/pathview/pathstyles.py | Python | mit | 4,318 | 0.007179 | from cadnano.gui.views.styles import *
from PyQt5.QtGui import QColor, QFont, QFontMetricsF
# Path Sizing
VIRTUALHELIXHANDLEITEM_RADIUS = 30
VIRTUALHELIXHANDLEITEM_STROKE_WIDTH = 2
PATH_BASE_WIDTH = 20 # used to size bases (grid squares, handles, etc)
PATH_HELIX_HEIGHT = 2 * PATH_BASE_WIDTH # staple + scaffold
PATH_... | f
SEQUENCEFONT = None
SEQUENCEFONTH = 15
SEQUENCEFONTCHARWIDTH = 12
SEQUENCEFONTCHARHEIGHT = 12
SEQUENCEFONTEXTRAWIDTH | = 3
SEQUENCETEXTXCENTERINGOFFSET = 0
def setFontMetrics():
""" Application must be running before you mess
too much with Fonts in Qt5
"""
global SEQUENCEFONT
global SEQUENCEFONTMETRICS
global SEQUENCEFONTCHARWIDTH
global SEQUENCEFONTCHARHEIGHT
global SEQUENCEFONTEXTRAWIDTH
global SEQ... |
plotly/plotly.py | packages/python/plotly/plotly/validators/heatmapgl/hoverlabel/font/_color.py | Python | mit | 472 | 0.002119 | import _plotly_utils.basevalidators
class ColorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self, plotly_name="colo | r", parent_name="heatmapgl.hoverlabel.font", **kwargs
):
super(ColorValidator, self).__init__ | (
plotly_name=plotly_name,
parent_name=parent_name,
array_ok=kwargs.pop("array_ok", True),
edit_type=kwargs.pop("edit_type", "none"),
**kwargs
)
|
Eksmo/calibre | src/calibre/gui2/convert/pdf_output.py | Python | gpl-3.0 | 1,003 | 0.002991 | # -*- coding: utf-8 -*-
__license__ = 'GPL 3'
__copyright__ = '2009, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
from calibre.gui2.convert.pdf_output_ui import Ui_Form
from calibre.gui2.convert import Widget
paper_size_model = None
orientation_model = None
class PluginWidget(Widget, ... | ption, get_help, db=None, book_id=None):
Widget.__init__(self, parent, ['paper_size', 'custom_size',
'orientation', 'preserve_cover_aspect_ratio'])
self.db, self.book_id = db, book_id
for x in get_option('paper_size').option.choices:
self.opt_paper_size.addItem(x)
... | ok_id)
|
SmokinCaterpillar/pypet | pypet/tests/integration/environment_scoop_test.py | Python | bsd-3-clause | 6,504 | 0.003536 | __author__ = 'Robert Meyer'
try:
import scoop
except ImportError:
scoop = None
def scoop_not_functional_check():
if scoop is not None and scoop.IS_RUNNING:
print('SCOOP mode functional!')
return False
else:
print('SCOOP NOT running!')
return True
from pypet.tests.in... | stutils.data import unittest
@unittest.skipIf(scoop_not_functional_check(), 'Only makes sense if scoop is installed and running')
class MultiprocSCOOPNetqueueTest(EnvironmentTest):
tags = 'integration', 'hdf5', 'environment', 'multiproc', 'netqueue', 'scoop'
def set_mode(self):
super(MultiprocSCOOPN... | ode = pypetconstants.WRAP_MODE_NETQUEUE
self.multiproc = True
self.freeze_input = False
self.ncores = 4
self.gc_interval = 3
self.niceness = check_nice(1)
self.use_pool = False
self.use_scoop = True
self.graceful_exit = False
@unittest.skip('Does not ... |
pengli09/Paddle | python/paddle/v2/framework/tests/test_recognize_digits_conv.py | Python | apache-2.0 | 2,759 | 0.000362 | import paddle.v2 as paddle
import paddle.v2.framework.layers as layers
import paddle.v2.framework.nets as nets
import paddle.v2.framework.core as core
import paddle.v2.framework.optimizer as optimizer
from paddle.v2.framework.framework import Program, g_program
from paddle.v2.framework.executor import Executor
import... | = 0
for data in train_reader():
img_data = np.array(map(lambda x: x[0].reshape([1, 28, 28]),
data)).astype("float32")
y_data = np.array(map(lambda x: x[1], data)).astype("int64")
y_da | ta = y_data.reshape([BATCH_SIZE, 1])
tensor_img = core.LoDTensor()
tensor_y = core.LoDTensor()
tensor_img.set(img_data, place)
tensor_y.set(y_data, place)
outs = exe.run(program,
feed={"pixel": tensor_img,
"label": tensor_y},
... |
gawel/panoramisk | tests/test_utils.py | Python | mit | 1,276 | 0 | from panoramisk import utils
from panoramisk.exceptions import AGIException
def test_parse_agi_valid_result():
res = try_parse_agi_result('200 result=0')
assert res == {'msg': '', 'result': ('0', ''), 'status_code': 200}
res = try_parse_agi_result('200 result=1')
assert res == {'msg': '', 'result': (... | t res == {'msg': '', 'result': ('1234', ''), 'status_code': 200}
res = try_parse_agi_result('200 result= (timeout)')
assert res == {'msg': '', 'result': ('', 'timeout'), 'status_code': 200}
def test_parse_agi_invalid_resul | t():
res = try_parse_agi_result('510 Invalid or unknown command')
assert res == {'msg': '510 Invalid or unknown command',
'error': 'AGIInvalidCommand',
'status_code': 510}
res = try_parse_agi_result('520 Use this')
assert res == {'msg': '520 Use this',
... |
ooblog/yonmoji_ge | LTsv/LTsv_file.py | Python | mit | 29,666 | 0.027343 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division,print_function,absolute_import,unicode_literals
import sys
import os
if sys.version_info.major == 2:
import urllib
if sys.version_info.major == 3:
import urllib.request
import zipfile
import datetime
import re
from LTsv_time import *... | Tsv_byte,LTsv_default,errors="xmlcharrefreplace")
if sys.version_info.major == 3:
with open(LTsv_path,mode="r",encoding=LTsv_default,errors="xmlcharrefreplace") as | LTsv_fobj:
LTsv_text=LTsv_fobj.read()
if not LTsv_text.endswith('\n'):
LTsv_text+='\n'
return LTsv_text
def LTsv_readlinepages(LTsv_text):
LTsv_line=""
for ltsv_tag in re.findall(re.compile("^\[(.+?)\|$",re.MULTILINE),LTsv_text):
LTsv_line+='\t'+ltsv_tag
LTs... |
jazzij/powertoken | data/models.py | Python | mit | 4,868 | 0.027732 | """
Contains the models to be used with the SQLAlchemy database interface.\n
Meant to be used by the background scripts, not the Flask app.\n
Created by Abigail Franz on 3/12/2018.\n
Last modified by Abigail Franz on 4/30/2018.
Update March 2019 - This is a really helpful guide:
https://stackoverflow.com/questions/41... | es = relationship("Activity", backref="user", lazy="dynamic")
errors = relationship("Error", backref="user", lazy="dynamic")
days = relationship("Day", backref="user", lazy="dynamic")
def thisday(self):
d = datetime.now()
today = datetime(d.year, d.month, d.day)
return self.days.filter(Day.date == today).firs... | ername = username
class Log(Base):
"""
Represents a PowerToken progress log, added whenever WEconnect progress is
detected and Fitbit step count is updated.
"""
__tablename__ = "log"
id = Column(Integer, primary_key=True)
timestamp = Column(DateTime, index=True, default=datetime.now())
wc_progress = Column(Flo... |
dati91/servo | tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/wptmanifest/tests/test_serializer.py | Python | mpl-2.0 | 4,547 | 0.00044 | import sys
import unittest
import pytest
from .. import parser, serializer
class TokenizerTest(unittest.TestCase):
def setUp(self):
self.serializer = serializer.ManifestSerializer()
self.parser = parser.Parser()
def serialize(self, input_str):
return self.serializer.serialize(self.p... | ctual = self.serialize(input_str)
self.assertEquals(actual, expected)
def test_0(self):
self.compare("""ke | y: value
[Heading 1]
other_key: other_value
""")
def test_1(self):
self.compare("""key: value
[Heading 1]
other_key:
if a or b: other_value
""")
def test_2(self):
self.compare("""key: value
[Heading 1]
other_key:
if a or b: other_value
fallback_value
""")
def test_3(self... |
transon/cassandra-shawn | test/system/test_avro_super.py | Python | apache-2.0 | 11,380 | 0.00703 |
# 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 ... | () < start + secs:
try:
fn(*args, **kwargs)
| success = True
except KeyboardInterrupt:
raise
except Exception, e:
last_exception = e
pass
if not success and last_exception:
raise last_exception
ZERO_WAIT = 5
_SUPER_COLUMNS = [_super_col('sc1', [Column(avro_utils.i64(4), 'value4', 0)]),
... |
audreyr/opencomparison | settings/base.py | Python | mit | 7,994 | 0.001876 | # -*- coding: utf-8 -*-
# Django settings
import os.path
from django.template.defaultfilters import slugify
PROJECT_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
DEBUG = True
TEMPLATE_DEBUG = DEBUG
# serve media through the staticfiles app.
SERVE_MEDIA = DEBUG
INTERNAL_IPS = [
"127.0.0.1"... | onment this must be set to the same as your
# system time zone.
TIME_ZONE = "US/Eastern"
|
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = "en-us"
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# Absolute path... |
globocom/database-as-a-service | dbaas/drivers/tests/test_driver_mysql.py | Python | bsd-3-clause | 7,183 | 0.001671 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from mock import MagicMock, patch
import logging
from django.conf import settings
from drivers import DriverFactory
from drivers.tests.base import (BaseMysqlDriverTestCase,
BaseSingleInstanceUpdateSizesTest... | _value=90))
class MySQLFOXHAUpdateUsedSizeTestCase(BaseMysqlDriverTestCase, BaseHAInstanceUpdateSizesTest):
| driver_class = MySQLFOXHA
instances_quantity = 2
class MySQLUsedAndTotalTestCase(BaseMysqlDriverTestCase):
"""
Tests MySQL total and used
"""
def test_masters_single_instance(self):
"""
Test validates return total and used size when has single instance
"""
s... |
Jajcus/pyxmpp2 | pyxmpp2/transport.py | Python | lgpl-2.1 | 33,073 | 0.001784 | #
# (C) Copyright 2011 Jacek Konieczny <jajcus@jajcus.net>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License Version
# 2.1 as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful... |
class ContinueConnect(WriteJob):
"""Object to signal (via the write queue) a pending connect request.
"""
# pylint: disable-msg=R0903
pass
class StartTLS(WriteJob):
"""StartTLS request for the `TCPTransport` write queue."""
# pylint: disable-msg=R0903
def __init__(self, **kwargs):
... | args = [ "{0}={1!r}".format(k, v) for (k, v) in self.kwargs.items() ]
return "<WriteJob: StartTLS: {0}>".format(" ".join(args))
class TLSHandshake(WriteJob):
"""Object to signal (via the write queue) a pending TLS handshake.
"""
# pylint: disable-msg=R0903
pass
class WriteData(WriteJob):
... |
gmimano/commcaretest | corehq/apps/receiverwrapper/fields.py | Python | bsd-3-clause | 2,703 | 0.005919 | from corehq.apps.reports.models import HQToggle
from corehq.apps.reports.fields import ReportField
from django.utils.translation import ugettext as _
from django.utils.translation import ugettext_noop
class SubmitToggle(HQToggle):
def __init__(self, type, show, name, doc_type):
super(SubmitToggle, se... | oc_types[i]) for i, name in enum | erate(cls.human_readable)]
class SubmissionTypeField(ReportField):
slug = "submitfilter"
template = "reports/fields/submit_error_types.html"
def update_context(self):
self.context['submission_types'] = self.get_filter_toggle(self.request)
@classmethod
def get_filter_toggle(cls, request):
... |
mikedingjan/wagtail | wagtail/contrib/redirects/apps.py | Python | bsd-3-clause | 248 | 0 | from django.apps import AppConfig |
from django.utils.translation import ugettext_lazy as _
class WagtailRedirectsAppConfig(AppConfig):
name = 'wagtail.contrib.redirects'
label = 'wagtailredirects'
verbose_name = _("Wagta | il redirects")
|
fboers/jumeg | jumeg/connectivity/cross_frequency_coupling.py | Python | bsd-3-clause | 11,555 | 0.000952 | #!/usr/bin/env python
# All the CFC relatd matlab code converted to python
# Translated from matlab code by Mark Kramer (math.bu.edu/people/mak/MA666/)
import numpy as np
from scipy.signal import hilbert
import mne
from mne.filter import filter_data
def filter_and_make_analytic_signal(data, sfreq, l_phase_freq, h_p... | n_samp - (n_samp / n_epochs)]
shifts = shifts.astype(np.int)
# construct the composite signal
z = amplitude_envelope * np.exp(1j * phase)
# mean of composite signal
mean_raw = np.mean(z)
surr_m | eans = np.zeros((n_surr, 1))
for i in range(0, n_surr):
# shift the amplitude for each surrogate
surr_amp = np.roll(amplitude_envelope, shifts[i])
# compute the mean |
jfterpstra/bluebottle | bluebottle/donations/migrations/0001_initial.py | Python | bsd-3-clause | 1,157 | 0.005186 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-05-23 13:25
from __future__ import unicode_literals
from django.db import migrations, models
import django_extensions.db.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Cre... | AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('amount', models | .DecimalField(decimal_places=2, max_digits=16, verbose_name='Amount')),
('created', django_extensions.db.fields.CreationDateTimeField(auto_now_add=True, verbose_name='Created')),
('updated', django_extensions.db.fields.ModificationDateTimeField(auto_now=True, verbose_name='Updated')),
... |
oVirt/releng-tools | check_virtsig_need_update.py | Python | gpl-3.0 | 8,232 | 0 | #!/usr/bin/python -O
# -*- coding: utf-8 -*-
# Copyright (C) 2015 Red Hat, Inc., Sandro Bonazzola <sbonazzo@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; either version 2 of th... | r != '-':
print(
'%s is ok, we have %s and %s is available\n' % (
| package_name, centos_nvr, fedora_nvr
)
)
for tag_to_check in (
'virt7-ovirt-common-candidate',
'virt7-ovirt-36-candidate',
'virt7-ovirt-35-candidate',
'virt7-kvm-co |
tlake/advent-of-code | 2016/day04_security_through_obscurity/python/src/part1.py | Python | mit | 1,245 | 0.001606 | #!/usr/bin/env python
"""Docstring."""
from collections import Counter
from functools import reduce
from common import (
get_input,
)
class RoomAnalyzer:
"""."""
def __init__(self, input_list=[]):
"""."""
self.input_list = input_list
def process_room_string(self, room_string):
... | or_id if self.room_is_real(name, checksum) else 0
def analyze_input(self):
"""."""
return reduce((lambda x, y: x + y), list(map(self.analyze_room, self.input_list)))
if __name__ == "__main__":
puzzle_inp | ut = get_input()
analyzer = RoomAnalyzer(get_input())
print(analyzer.analyze_input())
|
DRBarnum/Final-Project | DonkeyKong.py | Python | mit | 10,332 | 0.007646 | import ggame
from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame, CircleAsset, PolygonAsset, TextAsset
import random
SCREEN_WIDTH = 700
SCREEN_HEIGHT = 700
# THE WALLS
class wall(Sprite):
Red = Color(0xF44366, 1.0)
noline = LineStyle(0, Red)
def __init__(self, asset, po... | self.x += self.vx
self.a = self.collidingWithSprites(wall)
if len(self.a) != 0:
self.x -= self.vx
self.vx = 0
se | lf.YourDad = False
else:
self.YourDad = True
if len(self.d) != 0:
self.won = True
if len(self.c) != 0:
self.lives = self.lives - 1
if self.lives == 0 or self.won == True:
self.visible = False
else:
... |
tago-io/tago-python | tago/run_user/__init__.py | Python | mit | 3,335 | 0.008996 | import requests
import json
import os
API_TAGO = os.environ.get('TAGO_API') or 'https://api.tago.io'
REALTIME = os.environ.get('TAGO_REALTIME') or 'https://realtime.tago.io'
class RunUser:
def __init__(self, token):
self.token = token
self.default_headers = {
'content-type': 'application/json', 'Devi... | o'.format(api_endpoint=API_TAGO, tagoRunURL=tagoRunURL), headers=self.default_headers, json=data).json()
@staticmethod
def create(self, tagoRunURL, newUserObj):
return requests.post('{api_endpoint}/run/{tagoRunURL}/signup'.format(api_endpoint=API_TAGO, tagoRunURL=tagoRunURL), headers=self.default_headers, data... | ject):
data = {
'email': emailAndPasswordObject.email,
'password': emailAndPasswordObject.password
}
return requests.post('{api_endpoint}/run/{tagoRunURL}/login'.format(api_endpoint=API_TAGO, tagoRunURL=tagoRunURL), headers=self.default_headers, json=data).json()
@staticmethod
def confirmUs... |
Ircam-Web/mezzanine-organization | organization/network/migrations/0005_auto_20160905_1853.py | Python | agpl-3.0 | 2,404 | 0.003328 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-09-05 16:53
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('organization_network', '000... | model_name='personactivity',
name='function',
),
migrations.RemoveField(
model_name='personactivity',
name='rd_quota',
),
migrations.AddField(
model_name='personactivity',
name='is_permanent',
field=models... | field=models.IntegerField(blank=True, null=True, verbose_name='R&D quota (float)'),
),
migrations.AddField(
model_name='personactivity',
name='rd_quota_text',
field=models.CharField(blank=True, max_length=128, null=True, verbose_name='R&D quota (text)'),
... |
imxana/ec_forum | ec_forum/account.py | Python | mit | 4,404 | 0.003633 | # import pymysql
from flask import request,jsonify
import ec_forum.error as error
import ec_forum.sql as sql
import ec_forum.expr as expr
from ec_forum.salt import encrypt, decrypt
from config import MyConfig
sqlQ = sql.sqlQ()
def run(app):
@app.route('/sign_up', methods=['POST'])
def sign_up():
if r... | res[11],
'u_answers': res[12],
'u_watchusers': res[13],
'u_tags': res[14],
'u_intro': res[15],
})
| @app.route('/safe/sign_del', methods=['POST'])
def sign_del():
if request.method != 'POST':
return jsonify(error.requestError)
if not MyConfig.DEBUG:
return jsonify(error.methodAbort)
u_id = request.values.get('u_id', '')
u_psw = request.values.get('u_psw', '... |
bsmr-Bitcraze/crazyflie-clients-python | win32install/generate_nsis.py | Python | gpl-2.0 | 1,303 | 0 | # -*- coding: utf-8 -*-
import os
from subprocess import PIPE
from subprocess import Popen
import jinja2
DIS | T_PATH = "..\\build\\exe.win32-3.6"
# Get list of files and directory to install/uninstall
INSTALL_FILES = []
INSTALL_DIRS = []
os.chdir(os.path.join(os.path.dirname(__file__), DIST_PATH))
for root, dirs, files in os.walk("."):
for f in files:
INSTALL_FILES += [os.path.join(root[2:], f)]
INSTALL_DIRS ... | files in {} folders to install.".format(len(INSTALL_FILES),
len(INSTALL_DIRS)))
# Get git tag or VERSION
try:
process = Popen(["git", "describe", "--tags"], stdout=PIPE)
(output, err) = process.communicate()
exit_code = process.wait()
except OSError... |
gabry3795/android_kernel_huawei_mt7_l09 | drivers/vendor/hisi/build/scripts/transfer_sh.py | Python | gpl-2.0 | 3,462 | 0.015598 | #!/usr/bin/python
#-*- coding: UTF-8 -*-
#**************************************************************
#
# °æÈ¨ËùÓÐ (C), 2001-2012,»ªÎª¼¼ÊõÓÐÏÞ¹«Ë¾
#
#**************************************************************
#ÎļþÃû transfer_sh.py
#°æ±¾ºÅ £º³õ¸å
#×÷Õß £ºl00167020
#Éú³ÉÈÕÆÚ £º2013Ä... | f trans target left last time
if os.path.exists(trans_target):
os.system('rm -f ' + trans_target)
compress_cmd = ' '.join(['cd',trans_target_path, '&&', compress_tool, trans_target, stuff_to_compress])
errcode = os.system(compress_cmd)
if errcode != 0:
print "[ERROR]:compress... | on['TRANSFER_TOOL_PATH']
elif "Linux" == os_type:
trans_tool_path = "/opt/deployment/scripts"
else:
trans_tool_path = "c:/Development"
trans_tool_path = os.path.normpath(trans_tool_path)
trans_tool = os.path.join(trans_tool_path,"hibuild_transfer.py")
if not os.path.exis... |
FederatedAI/FATE | python/fate_arch/federation/_datastream.py | Python | apache-2.0 | 1,298 | 0.001541 | #
# Copyright 2019 The FATE 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 obtai | n a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for ... | governing permissions and
# limitations under the License.
#
import io
import sys
import json
# Datastream is a wraper of StringIO, it receives kv pairs and dump it to json string
class Datastream(object):
def __init__(self):
self._string = io.StringIO()
self._string.write("[")
def get_siz... |
harry-ops/opencloud | webvirtcloud/vrtManager/create.py | Python | gpl-2.0 | 7,955 | 0.00176 | import string
from vrtManager import util
from vrtManager.connection import wvm | Connect
from webvirtcloud.settings import QEMU_CONSOLE_DEFAULT_TYPE
def get_rbd_storage_data(stg):
xml = stg.XMLDesc(0)
ceph_user = util.get_xml_path(xml, "/pool/source/auth/@username")
ceph_host = util.get_xml_path(xml, "/pool/source/host/@name")
secrt_uuid = util.get_xml_path(xml, "/pool/source/auth... | ges_images(self):
"""
Function return all images on all storages
"""
images = []
storages = self.get_storages()
for storage in storages:
stg = self.get_storage(storage)
try:
stg.refresh(0)
except:
pass
... |
PisiLinuxNew/kaptan | kaptan/libkaptan/ui_other.py | Python | gpl-3.0 | 4,525 | 0.003095 | # Copyright 2016 Metehan Özbek <mthnzbk@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is... | fromTheme("preferences-system").pixmap(64, 64))
groupLabelImage.setMaximumSize(64,64)
groupHLayout1.addWidget(groupLabelImage)
groupLabel1 = QLabel()
groupLabel1.setWordWrap(True)
groupLabel1.setText(self.tr("<p>Configuration tools for Pisi Linux such as the display, firewall, ke... | "user manager.</p>"))
groupButton1 = QPushButton()
groupButton1.setMaximumWidth(200)
groupButton1.setText(self.tr("System Settings"))
groupHLayout1.addWidget(groupLabel1)
groupHLayout1.addItem(QSpacerItem(40, 20, QSizePolicy.Preferred, QSizePolicy.Preferr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.