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 |
|---|---|---|---|---|---|---|---|---|
CLVsol/clvsol_odoo_addons | clv_document_export/models/model_export_document_item.py | Python | agpl-3.0 | 2,203 | 0.001362 | # -*- coding: utf-8 -*-
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class ModelExportDocumentItem(models.Model):
_description = 'Model Export Document Item'
_name = "clv.model_expor... | ,
store=False
)
sequence = fields.Integer(
string='Sequence',
default=10
)
model_export_display = fields.Boolean(string='Display in Export', default=True)
class ModelExport(models.Model):
_inherit = 'clv.model_export'
use_document_items = fields.Boolea... | _export_id',
string='Model Export Document Items'
)
count_model_export_document_items = fields.Integer(
string='Model Export Document Items (count)',
compute='_compute_count_model_export_document_item',
store=True
)
@api.depends('model_export_document_item_ids... |
eubr-bigsea/stand | stand/util/dummy_executor.py | Python | apache-2.0 | 7,975 | 0.000502 | # -*- coding: utf-8 -*-}
"""
A dummy executor that process Lemonade jobs and only returns fake statuses and
data. Used to test Stand clients in an integration test.
"""
import datetime
import json
import logging
import logging.config
import random
import eventlet
import socketio
from flask_script import Manager
# Log... | 'id': job['workflow_id']},
room=room, namespace="/stand")
job_entity = Job.query.get(job.get('job_id'))
job_entity.sta | tus = StatusExecution.RUNNING
job_entity.finished = datetime.datetime.utcnow()
db.session.add(job_entity)
db.session.commit()
for task in job.get('workflow', {}).get('tasks', []):
if task['operation']['id'] == 25: # comment
continue
... |
fossfreedom/coverart-browser | coverart_listview.py | Python | gpl-3.0 | 2,367 | 0 | # -*- Mode: python; coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*-
#
# Copyright (C) 2012 - fossfreedom
# Copyright (C) 2012 - Agustin Carrasco
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Fou... | "ListView"
name = 'listview'
use_plugin_window = False
def __init__(self):
super(ListView, self).__init__()
self.view = self
self._has_initialised = False
self.show_policy = ListShowingPolicy(self)
def initialise(self, source):
if self._has_initialised:
... | self._has_initialised = True
self.view_name = "list_view"
super(ListView, self).initialise(source)
# self.album_manager = source.album_manager
self.shell = source.shell
def switch_to_view(self, source, album):
self.initialise(source)
GLib.idle_add(self.shel... |
andersonsilvade/python_C | Python32/aulas/letras.py | Python | mit | 199 | 0.045226 | letras=[]
i=1
while i <= 10:
letras.append(input("letras : "))
i+=1
i=0
cont=0
| whil | e i <=9:
if letras[i] not in 'aeiou':
cont+=1
i+=1
print("foram lidos %d consoantes" %cont)
|
pranner/CMPUT410-Lab6-Django | v1/bin/django-admin.py | Python | apache-2.0 | 164 | 0 | #!/cshome/pranjali/410/CMPUT410-Lab6-Django/v1/bin/python
from django.core | import ma | nagement
if __name__ == "__main__":
management.execute_from_command_line()
|
dlutxx/memo | data/nation_parse.py | Python | mit | 3,087 | 0.000984 | # -*- coding: utf8 -*-
#
# 国家统计局 行政区域代码 文本:
#
# http://www.stats.gov.cn/tjsj/tjbz/xzqhdm/
#
from __future__ import print_function
from collections import OrderedDict
class Area(object):
level = None
def __init__(self, code, name, parent=None):
'''use unicode name'''
self.code = int(code)
... | self.level, self.parent.code, self.name)
def __str__(self):
return unicode(self).encode('utf8')
class ContainerArea(Area):
sub_unit_kls = None
def __init__(self, code, name, parent=None):
super(ContainerArea, self).__init__(code, name, parent)
self.subunits = Order... | = int(code)
unit = self.sub_unit_kls(code, name, self)
self.subunits[code] = unit
def get_sub_unit(self, code):
code = int(code)
return self.subunits[code]
def __unicode__(self):
ret = []
if self.name == u'市辖区':
ret.append(u'%6d %1d %6d %s' % (self.... |
ghorn/debian-casadi | docs/examples/python/vdp_indirect_single_shooting.py | Python | lgpl-3.0 | 4,479 | 0.013842 | #
# This file is part of CasADi.
#
# CasADi -- A symbolic framework for dynamic optimization.
# Copyright (C) 2010-2014 Joel Andersson, Joris Gillis, Moritz Diehl,
# K.U. Leuven. All rights reserved.
# Copyright (C) 2011-2014 Greg Horn
#
# CasADi is free software; you can... | nit()
# The initial state
x_init = NP.array([0.,1.])
# The initial costate
l_init = MX.sym("l_init" | ,2)
# The initial condition for the shooting
X = vertcat((x_init,l_init))
# Call the integrator
X, = integratorOut(I.call(integratorIn(x0=X)),"xf")
# Costate at the final time should be zero (cf. Bryson and Ho)
lam_f = X[2:4]
g = lam_f
# Formulate root-finding problem
rfp = MXFunction([l_init],[g])
# Select a solv... |
chambers-brian/SIG_Digital-Strategy_SI_ODP_Backend | tests/unit/dataactvalidator/test_a26_appropriations.py | Python | cc0-1.0 | 1,546 | 0.003881 | from tests.unit.dataactcore.factories.staging import AppropriationFactory
from tests.unit.dataactcore.factories.domain import SF133Factory
from tests.unit.dataactvalidator.utils import number_of_errors, query_columns
_FILE = 'a26_appropriations'
_TAS = 'a26_appropriations_tas'
def test_column_headers(database):
... | 133Factory(tas=tas, period=1, fiscal_year=2016, line=1640, amount=1)
ap = AppropriationFactory(tas=tas, contract_authority_amount_cpe=1)
assert number_of_errors(_FILE, database, models=[sf1, sf2, ap]) == 0
def test_failure(database) | :
""" Tests that ContractAuthorityAmountTotal_CPE is not provided if TAS has contract authority value
provided in GTAS """
tas = "".join([_TAS, "_failure"])
sf1 = SF133Factory(tas=tas, period=1, fiscal_year=2016, line=1540, amount=1)
sf2 = SF133Factory(tas=tas, period=1, fiscal_year=2016, line=1640... |
fedora-conary/conary | conary/repository/netrepos/netauth.py | Python | apache-2.0 | 50,922 | 0.003613 | #
# Copyright (c) SAS Institute Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | d on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import itertools
import os
import time
import urllib, urllib2
import xml
from conary import conarycfg, versions
fr... | , tracelog
from conary.dbstore import sqlerrors
from conary.repository.netrepos import items, versionops, accessmap
from conary.server.schema import resetTable
# FIXME: remove these compatibilty error classes later
UserAlreadyExists = errors.UserAlreadyExists
GroupAlreadyExists = errors.GroupAlreadyExists
MAX_ENTITLE... |
Velmont/digital-signage-server | lib/utils/imagekit.py | Python | mit | 4,036 | 0.006442 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Image utilities
Cr | eated by: Rui Carmo
License: MIT (see LICENSE for details)
"""
from operator import itemgetter
def linear_partition(seq, k):
if k <= 0:
return []
n = len(seq) - 1
if k > n:
return map(lambda x: [x], seq)
table, solution = linear_partition_table(seq, k)
k, ans = k-2, []
while k ... | [i] for i in xrange(0, n+1)]] + ans
def linear_partition_table(seq, k):
n = len(seq)
table = [[0] * k for x in xrange(n)]
solution = [[0] * (k-1) for x in xrange(n-1)]
for i in xrange(n):
table[i][0] = seq[i] + (table[i-1][0] if i else 0)
for j in xrange(k):
table[0][j] = seq[0]
... |
FrogLogics/mget | build/lib.linux-x86_64-3.5/Mget/downloader/common.py | Python | gpl-2.0 | 3,835 | 0.041982 | #!/usr/bin/env python3
import os, sys
import time
from ..utils import (std, strip_site, MGet, urlparse, HTMLParser)
class FileDownloader(MGet):
def __init__(self, info = {}):
self.last_len = 0
self.alt_prog = 0.0
def getLocalFilesize(self, filename):
tmp_name = self.temp_name(filename)
if os.path.exists(f... | og = int(self.alt_prog * width)
pro | g_bal = width - int(self.alt_prog * width)
progress_bar = "[" + " " * (prog) + "<=>" + " " * (prog_bal) + "] "
_res = [ "(^_^) " if int(self.alt_prog * 10) in list(range(0, 10, 4)) else "(0_0) ",
progress_bar, "%-12s " % ("{:02,}".format(self.cursize)),
"%9s%12s" % (self.calc_speed(dif,bytes).decode()," ")]
... |
daTokenizer/quickstorm | storm/virtualenvs/_resources/resources/bolts/action_bolt.py | Python | apache-2.0 | 1,292 | 0.023994 | # [\0] | #
# #
# This code is confidential and proprietary, All rights reserved. #
# #
# Tamar Labs 2015. #
# #
# @author: Adam Lev-Libfeld (adam@tamarlabs.com) #
... |
from external.actions import ActionDB
class ActionBolt(Bolt):
def initialize(self, storm_conf, context):
actionDB = ActionDB()
def process(self, tup):
try:
action_num = tup.values[0]
if action_num < len(actionDB.actions):
... |
leppa/home-assistant | homeassistant/components/pi_hole/const.py | Python | apache-2.0 | 1,452 | 0.002066 | """Constants | for the pi_hole intergration."""
from datetime import timedelta
DOMAIN = "pi_hole"
CONF_LOCATION = "location"
CON | F_SLUG = "slug"
DEFAULT_LOCATION = "admin"
DEFAULT_METHOD = "GET"
DEFAULT_NAME = "Pi-Hole"
DEFAULT_SSL = False
DEFAULT_VERIFY_SSL = True
SERVICE_DISABLE = "disable"
SERVICE_DISABLE_ATTR_DURATION = "duration"
SERVICE_DISABLE_ATTR_NAME = "name"
SERVICE_ENABLE = "enable"
SERVICE_ENABLE_ATTR_NAME = SERVICE_DISABLE_ATTR_N... |
bmcfee/librosa | librosa/filters.py | Python | isc | 37,764 | 0.001059 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Filters
=======
Filter bank construction
------------------------
.. autosummary::
:toctree: generated/
mel
chroma
constant_q
semitone_filterbank
Window functions
----------------
.. autosummary::
:toctree: generated/
window_bandwidth
... | 0. , 0. ],
[ 0. , 0. , ..., 0. , 0. ],
...,
[ 0. , 0. , ..., 0. , 0. ],
[ 0. , 0. , ..., 0. , 0. ]])
>>> import matplotlib.pyplot as plt
>>> fig, ax = plt.subplots()
>>> img = librosa.display.specshow(melfb, x_axis='linear', ax=ax)
>... | el filter', title='Mel filter bank')
>>> fig.colorbar(img, ax=ax)
"""
if fmax is None:
fmax = float(sr) / 2
# Initialize the weights
n_mels = int(n_mels)
weights = np.zeros((n_mels, int(1 + n_fft // 2)), dtype=dtype)
# Center freqs of each FFT bin
fftfreqs = fft_frequencies(sr... |
wbap/hackathon-2017-sample | agent/ml/experience.py | Python | apache-2.0 | 3,373 | 0.004447 | # coding: utf-8
import numpy as np
from chainer import cuda
from builtins import range
class Experience:
def __init__(self, use_gpu=0, data_size=10**5, replay_size=32, hist_size=1, initial_exploration=10**3, dim=10240):
self.use_gpu = use_gpu
self.data_size = data_size
self.replay_size =... | s_replay = cuda.to_gpu(s_replay)
s_dash_replay = cuda.to_gpu(s_dash_replay)
return replay_start, s_replay, a_replay, r_replay, s_dash_repla | y, episode_end_replay
else:
return replay_start, 0, 0, 0, 0, False
def end_episode(self, time, last_state, action, reward):
self.stock(time, last_state, action, reward, last_state, True)
replay_start, s_replay, a_replay, r_replay, s_dash_replay, episode_end_replay = \
... |
ava-project/ava-website | website/apps/user/migrations/0003_emailvalidationtoken.py | Python | mit | 973 | 0.002055 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-09-16 21:51
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 = [
migrations.swappable_depende... | ame='EmailValidationToken',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('token', models.CharField(max_length=100, unique=True)),
('expire', models.DateTimeField()),
('consumed', m... | b.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
|
ZerpaTechnology/AsenZor | apps/votSys/user/vistas/templates/inicio.py | Python | lgpl-3.0 | 147 | 0.020408 | # -*- coding: utf-8 -*-
print '''<!DOCTYPE html><html>'''
incluir(data,"he | ad")
print | '''<body>'''
incluir(data,"header")
print '''</body></html>''' |
weblabdeusto/weblablib | weblablib/backends/__init__.py | Python | agpl-3.0 | 326 | 0 | # Copyright 2017 onwards LabsLan | d Experimentia S.L.
# This software is licensed under the GNU AGPL v3:
# GNU Affero General Public License version 3 (see the file LICENSE)
# Read in the documentation about the license
from __future__ import unicode_literals, print_function, division
from .redis_manager imp | ort RedisManager
|
SimplyCo/cityproblems | cityproblems/accounts/urls.py | Python | mit | 1,489 | 0.006716 | from django.conf.urls import patterns, url
urlpatterns = patterns('cityproblems.accounts.views',
url(r'^register/$', 'register', name="accounts_register"),
url(r'^profile/edit/$', 'accounts_profile_edit', name="accounts_profile_edit"),
url(r'^profil... | mail_confirm', name="accounts_process_email | _confirm"),
url(r'^passwd_reset/(\d+)/$', 'accounts_passwd_reset', name="accounts_passwd_reset"),
url(r'^passwd_change/$', 'accounts_passwd_change', name="accounts_passwd_change"),
)
urlpatterns += patterns('',
url(r'^logout/$... |
anduslim/codex | codex_project/actors/haversine.py | Python | mit | 554 | 0.001805 | from math import r | adians, cos, sin, asin, sqrt
def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# haversine fo... | m is the radius of the Earth
km = 6367 * c
return km
|
SpotOnInc/espwrap | tests/test_sendgrid_v3.py | Python | mit | 6,880 | 0.003351 | # -*- coding: utf-8 -*-
from __future__ import print_function, division, unicode_literals, absolute_import
import sys
try:
from unittest.mock import Mock, patch
except ImportError:
from mock import Mock, patch
import pytest
from espwrap.base import batch
from espwrap.adaptors.sendgrid_v3 import SendGridMass... | tags = ['unit', 'test', 'for', 'the', 'win']
webhook_data = {
'm_id': '56f2c1341a89ddc8c04d5407',
'env': 'local',
'p_id': '56f2c1571a89ddc8c04d540a',
}
me.set_reply_to_addr('custsupport@spam.com')
me.set_from_addr('donotreply@spam.com')
me.add_recipients([
{
... | },
},
{
'name': 'Jim',
'email': 'spam2@spam.com',
'merge_vars': {
'CUSTOMER_NAME': 'Jim',
'SOMETHING_UNIQUE': 'tester',
},
},
{
'name': '姓',
'email': 'test@test.com',
... |
PyQwt/PyQwt5 | Doc/sourceforge.py | Python | gpl-2.0 | 990 | 0.005051 | #!/usr/bin/env python
import os
import re
import sys
group_id = '142394'
def stamp(html):
"""Stamp a Python HTML documentation page with the SourceForge logo"""
def rep | lace(m):
return ('<span class="release-info">%s '
'Hosted on <a href="http://sourc | eforge.net">'
'<img src="http://sourceforge.net/'
'sflogo.php?group_id=%s&type=1" width="88" height="31"'
'border="0" alt="SourceForge Logo"></a></span>'
% (m.group(1), group_id))
mailRe = re.compile(r'<span class="release-info">(.*)</span>')
## ... |
david30907d/feedback_django | example/get_feedback/migrations/0002_auto_20160519_0326.py | Python | mit | 1,184 | 0.000845 | # -*- coding: utf-8 -*-
from __future__ import | unicode_literals
from django.db import migr | ations, models
class Migration(migrations.Migration):
dependencies = [
('get_feedback', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='course',
name='feedback_amount',
field=models.DecimalField(default=0, decimal_places=0, max_digit... |
metzlar/cms-form-plugin | cms_form_plugin/migrations/0001_initial.py | Python | gpl-2.0 | 3,411 | 0.007916 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'FormPlugin'
db.create_table(u'cmsplugin_formplugin', (
... | uccess_url', self.gf('django.db.models.fields.URLField')(max_length=200, null=True)),
('post_to_url', self.gf('django.db.models.fields.URLField')(max_length=200)),
))
db.send_create_signal(u'cms_form_plugin', ['FormPlugin'])
def backwards(self, orm):
# Deleting model 'FormPlugi... | 'cms.cmsplugin': {
'Meta': {'object_name': 'CMSPlugin'},
'changed_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'creation_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
u'id': ('d... |
kickapoo/enhydris | enhydris/tests/admin/test_station.py | Python | agpl-3.0 | 16,487 | 0.00182 | import datetime as dt
from io import StringIO
from locale import LC_CTYPE, getlocale, setlocale
from django.contrib.auth.models import Permission, User
from django.contrib.gis.geos import Point
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase, override_settings
from model... | /enhydris/station/add/")
self.assertEqual(response.status_code, 200)
self.assertContains(response, "Creator")
self.assertContains(response, "Maintainers")
def test_add_station_has_creator_and_maintainers_for_user_with_model_perms(self):
self.client.login(username="elaine", password=... | 00)
self.assertContains(response, "Creator")
self.assertContains(response, "Maintainers")
def test_add_station_has_only_maintainers_for_user_without_model_perms(self):
self.client.login(username="bob", password="topsecret")
response = self.client.get("/admin/enhydris/station/add/")
... |
eljost/pysisyphus | tests/test_irc/test_irc.py | Python | gpl-3.0 | 7,603 | 0.000921 | #!/usr/bin/env python3
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import pytest
from pysisyphus.calculators.AnaPot import AnaPot
from pysisyphus.calculators.MullerBrownSympyPot import MullerBrownPot
from pysisyphus.calculators.PySCF import PySCF
from pysisyphus.calculators import Gau... | irc.run()
# calc.plot_irc(irc, show=True, title=f"length {step_length:.2f}")
assert irc.forward_is_converged
assert irc.backward_is_converged
@using("pyscf")
@pytest.mark.parametrize(
"step_length", [
0.1,
0.2,
0.3,
# 0.4, # sometimes fails in the CI
]
)
def te... | "lib:hcn_iso_hf_sto3g_ts_opt.xyz")
calc = PySCF(basis="sto3g", verbose=0)
geom.set_calculator(calc)
irc_kwargs = {
"step_length": step_length,
"displ_energy": 0.0005,
}
irc = GonzalezSchlegel(geom, **irc_kwargs)
irc.run()
assert irc.forward_is_converged
assert irc.backwa... |
HydrelioxGitHub/home-assistant | homeassistant/components/tradfri/__init__.py | Python | apache-2.0 | 3,856 | 0 | """Support for IKEA Tradfri."""
import logging
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import EVENT_HOMEASSISTANT_STOP
import homeassistant.helpers.config_validation as cv
from homeassistant.util.json import load_json
from .const import (
CONF_IMPORT_GROUPS, CON... | hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, on_hass_stop)
api = factory.request
gateway = Gateway()
try:
gateway_info = await api(gateway.get_gateway_info())
except RequestError:
| _LOGGER.error("Tradfri setup failed.")
return False
hass.data.setdefault(KEY_API, {})[entry.entry_id] = api
hass.data.setdefault(KEY_GATEWAY, {})[entry.entry_id] = gateway
dev_reg = await hass.helpers.device_registry.async_get_registry()
dev_reg.async_get_or_create(
config_entry_id=en... |
lmazuel/azure-sdk-for-python | azure-mgmt-web/azure/mgmt/web/models/reissue_certificate_order_request.py | Python | mit | 2,522 | 0.00119 | # 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 ... | ource type.
:vartype type: str
:param key_size: Certificate Key Size.
:type key_size: int
:param delay_existing_revoke_in_hours: Delay in hours to revoke existing
certificate after the new certificate is issued.
:type delay_existing_revoke_in_hours: int
:param csr: Csr to be used for re-key... | :type csr: str
:param is_private_key_external: Should we change the ASC type (from
managed private key to external private key and vice versa).
:type is_private_key_external: bool
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonl... |
illagrenan/gtask-client | fabfile.py | Python | mit | 2,356 | 0.000424 | # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
import os
import configparser
from fabric.context_managers import cd
from fabric.decorators import task
from fabric.api import env
from fabric.operations import put, run, local
from fabric.utils import abort
from zip_dir.utils import create_zip_archive... | .isdir(dist_path) or not os.listdir(dist_path):
abort("Dist path doesn't exist or dist directory is empty")
| create_zip_archive(dist_path, os.path.join(".tmp", DIST_ZIP_FILENAME))
run("mkdir -p {0}".format(APP_BASE_DIR))
put(os.path.join(".tmp", DIST_ZIP_FILENAME), APP_BASE_DIR)
with cd(APP_BASE_DIR):
run("unzip -o {0}".format(DIST_ZIP_FILENAME))
run("rm {0}".format(DIST_ZIP_FILENAME))
gr... |
ezequielpereira/Time-Line | timelinelib/wxgui/dialogs/editevent/view.py | Python | gpl-3.0 | 12,695 | 0.000788 | # Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015 Rickard Lindberg, Roger Lindberg
#
# This file is part of Timeline.
#
# Timeline 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 th... | nds_today_checkbox_text": _("Ends today"),
"to_label": _("to"),
"text_label": _("Text:"),
"category_label": _("Category:"),
"container_label": _("Container:"),
"page_description": _("Description"),
"page_icon": _("Icon"),
"page_alert": ... | gress"),
"add_more_label": _("Add more events after this one"),
"enlarge": _("&Enlarge"),
"reduce": _("&Reduce"),
}, title=title, style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)
self.controller.on_init(
config,
db.get_time_type(),
... |
openstack-packages/DLRN | dlrn/tests/test_driver_koji.py | Python | apache-2.0 | 24,497 | 0 | # -*- coding: utf-8 -*-
# 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, softw... | e(output_directory=self.temp_dir)
e | xpected = [mock.call(['brew',
'--principal', self.config.koji_krb_principal,
'--keytab', self.config.koji_krb_keytab,
'build', '--wait',
self.config.koji_build_target,
... |
adarshdec23/Market | core/preference/main.py | Python | apache-2.0 | 3,319 | 0.008738 | from collections import *
from config import main
import heapq
class UserPreference:
def __init__(self):
self.results = []
self.list1 = []
self.list2 = []
self.list3 = []
self.list4 = []
self.categories = []
self.sold_average = []
self.bought_averag... | ):
self.categories.append(self.list2[i][3])
self.categories = list(set(self.categories))
i = 0
for item in self.list2:
self.list4.append(self.categories.index(item[3]))
self.sold_average = [0]*len(self.categories)
self.bought... | b=[0]*len(self.categories)
for item in self.list2:
cat = item[3]
ind = self.categories.index(cat)
if item[4] == 'sold':
self.sold_average[ind]+= int(float(item[5]))
else:
self.bought_average[ind]+= int(float(item[5]))
... |
guilhermedallanol/dotfiles | vim/plugged/vial/vial/plugins/bufhist/plugin.py | Python | mit | 3,812 | 0.000787 | from time import time
from itertools import groupby
from vial import vfunc, vim, dref
from vial.utils import echon, redraw
from os.path import split
MAX_HISTORY_SIZE = 100
VHIST = 'vial_buf_hist'
VLAST = 'vial_last_buf'
def add_to_history(w, bufnr):
history = list(w.vars[VHIST])
history[:] = [r for r in his... | nd
now - lastbuf[1] > vim.vars['vial_bufhist_timeout']):
history = add_to_history(w, bufnr)
if bufnr not in history:
history = add_to_history(w, bufnr)
names = {r.number: (split(r.name)
if r.name
else ['', '[buf-{}]'.format... | in names, history)
dups = True
while dups:
dups = False
for name, g in groupby(sorted(names.iteritems(), key=skey), skey):
g = list(g)
if len(g) > 1:
dups = True
for nr, (path, _) in g:
p, n = split(path)
... |
annegabrielle/secure_adhoc_network_ns-3 | ns3_source_code/ns-3.10/bindings/python/apidefs/gcc-LP64/ns3_module_udp_echo.py | Python | gpl-2.0 | 8,335 | 0.017876 | from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers
def register_types(module):
root_module = module.get_root()
## udp-echo-client.h: ns3::UdpEchoClient [class]
module.add_class('UdpEchoClient', parent=root_m | odule['ns3::Application'])
## udp-echo-server.h: ns3::UdpEchoServer [class]
module.add_class('UdpEchoServer', parent=root_module['ns3::Application'])
## Register a nested module for the namespace Config
nested_module = module.add_cpp_namespace('Config')
register_types_ns3_Config(nested_mod... |
## Register a nested module for the namespace addressUtils
nested_module = module.add_cpp_namespace('addressUtils')
register_types_ns3_addressUtils(nested_module)
## Register a nested module for the namespace aodv
nested_module = module.add_cpp_namespace('aodv')
register... |
erik-sn/xlwrap | xlwrap.py | Python | mit | 14,765 | 0.001422 | import os
import ntpath
import xlrd
import openpyxl
from openpyxl.utils import coordinate_from_string, column_index_from_string
from openpyxl.utils.exceptions import CellCoordinatesException
class ExcelManager:
"""
Wrapper that opens and operates on .xls, .xlsx or .xlsm excel files. By
default we take in ... | instance(args[0], str):
name = args[0]
index = None
elif isinstance(args[0], int):
| name = None
index = args[0]
else:
raise ValueError('Specify either the sheet name or sheet index to change sheets')
if self.__is_xls:
self.__select_xls_sheet(name, index - 1 if index else None)
else:
self.__select_excel_sheet(name, index - 1 if in... |
thinkAmi-sandbox/Bottle-sample | lan_access.py | Python | unlicense | 589 | 0.005236 | # -*- coding:utf-8 -*-
from bottle import route, run
@route("/")
def access():
return "OK!"
# hostデフォルト値は、127.0.0.1
# OK - localhost / 127.0.0.1
# NG - 192.168.0.10 / hostname
# run(port=8080, debug=True, reloader=True)
# run(host="localhost", port=8080, debug=True, reloader=True)
# OK - 192.168.... | ug=True, reloader=True)
# run(host="<your hostname>", port=8080, debug= | True, reloader=True)
# OK - ALL
# run(host="0.0.0.0", port=8080, debug=True, reloader=True) |
HarmonyEnterpriseSolutions/harmony-platform | src/gnue/common/datasources/drivers/sql/mssql/Behavior.py | Python | gpl-2.0 | 1,600 | 0.00625 | # GNU Enterprise Common Library - Schema support for MS-SQL
#
# Copyright 2000-2007 Free Software Foundation
#
# This file is part of GNU Enterprise.
#
# GNU Enterprise 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 Foun... | ----------------------------------------------------------
def __init__ (self, connection):
Base.Behavior.__init_ | _ (self, connection)
|
lotrekagency/heimdall | server/server.py | Python | mit | 371 | 0.008086 | imp | ort falcon
import json
class QuoteResource:
def on_get(self, req, resp):
"""Handles GET requests"""
quote = {
'quote': 'I\'ve always been more interested in the future than in the past.',
'author': 'Grace Hopper'
}
resp.body = json.dumps(quote)
api = falcon... | rce())
|
gotostack/swift | test/functional/tests.py | Python | apache-2.0 | 82,395 | 0.000158 | #!/usr/bin/python -u
# Copyright (c) 2010-2012 OpenStack Foundation
#
# 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 ap... | p = False
class TestAccountDevUTF8(Base2, TestAccountDev):
set_up = False
class TestAccount(Base):
env = TestAccountEnv
set_up = False
def testNoAuthToken(self):
self.assertRaises(ResponseError, self.env.account.info,
cfg={'no_auth_token': True})
self.asser... | unt.containers,
cfg={'no_auth_token': True})
self.assert_status([401, 412])
def testInvalidUTF8Path(self):
invalid_utf8 = Utils.create_utf8_name()[::-1]
container = self.env.account.container(invalid_utf8)
self.assert_(not container.create(cfg={'no_path_quo... |
stormi/tsunami | src/secondaires/navigation/commandes/matelot/liste.py | Python | bsd-3-clause | 3,827 | 0.00131 | # -*-coding:Utf-8 -*
# Copyright (c) 2013 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# lis... | init__(self, "liste", "list")
self.tronquer = True
self.aide_courte = "liste les matelots de l'équipage"
self.aide_longue = \
"Cette commande liste les matelots de votre équipage. " \
"Elle permet d'obtenir rapidement des informations pratiques " \
"sur le nom... | salle = personnage.salle
if not hasattr(salle, "navire"):
personnage << "|err|Vous n'êtes pas sur un navire.|ff|"
return
navire = salle.navire
equipage = navire.equipage
if not navire.a_le_droit(personnage, "officier"):
personnage << "|err|Vous ne pou... |
DamnWidget/mamba | mamba/application/app.py | Python | gpl-3.0 | 7,315 | 0 | # -*- test-case-name: mamba.test.test_application mamba.test.test_mamba -*-
# Copyright (c) 2012 - Oscar Campos <oscar.campos@member.fsf.org>
# See LICENSE for more details
"""
.. module: app
:platform: Linux
:synopsis: Mamba Application Manager
.. moduleauthor:: Oscar Campos <oscar.campos@member.fsf.org>
"""... | from mamba import Mamba
app = Mamba({'name': 'MyApp', 'description': 'My App', ...})
:param options: options to initialize the application with
:type options: dict
"""
def __init__(self, options | =None):
"""Mamba constructor"""
super(Mamba, self).__init__()
if hasattr(self, 'initialized') and self.initialized is True:
return
self.monkey_patched = False
self.development = False
self.already_logging = False
self._mamba_ver = _mamba_version.ver... |
ttreeagency/PootleTypo3Org | pootle/apps/staticpages/views.py | Python | gpl-2.0 | 5,490 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2012-2013 Zuza Software Foundation
#
# This file is part of Pootle.
#
# Pootle 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... | View)
from pootle.core.views import SuperuserRequiredMixin
from .forms import agreement_form_factory
from .models import AbstractPage, LegalPage, StaticPage
class PageModelMixin(object):
"""Mixin used to set the view's page model according to the
`page_type` argument caught in a url pattern.
"""
de... | 'legal': LegalPage,
'static': StaticPage,
}.get(self.page_type)
if self.model is None:
raise Http404
return super(PageModelMixin, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
ctx = super(PageModelMixin, self).get_context_da... |
zuun77/givemegoogletshirts | codejam/2016/Round2/q1.py | Python | apache-2.0 | 877 | 0.013683 | def solve(N, R, P, S):
if max | ([R, P, S]) > 2**(N-1): return "IMPOSSIBLE"
if N > 2 and max([R, P, S]) == 2**(N-1): return "IMPOSSIBLE"
min_val = min([R, P, S])
rep = 2**N//3
if min_val < rep: return "IMPOSSIBLE"
if N == 1:
tmp = ""
if P: tmp += "P"
if R: tmp += "R"
if S: tmp += "S"
return ... | //2
preS = S//2
if preP < P-preP: preP += 1
elif preR < R-preR: preR += 1
else: preS += 1
ans = solve(N-1, preR, preP, preS) + solve(N-1, R-preR, P-preP, S-preS)
return ans
for case in range(1, eval(input()) + 1):
N, R, P, S = map(int, input().split())
print("Case #... |
SerpentCS/purchase-workflow | purchase_order_line_sequence/models/__init__.py | Python | agpl-3.0 | 413 | 0 | # -*- coding: utf-8 -*-
# Author: Alexandre Fayolle
# Copyright 2013 Camptocamp SA
# Author: Damien Crier
# Copyright 2015 Camptocamp SA
# © 20 | 15 Eficent Business and IT Consulting Services S.L. -
# Jordi Ballester Alomar
# © 2015 Serpent Consulting Services Pvt. Ltd. - Sudhir Arya
# License LGPL-3.0 or later (https://www.gnu | .org/licenses/lgpl.html).
from . import purchase
from . import invoice
|
dhodges/sgfspider | tests/test_igokisen.py | Python | mit | 1,778 | 0.006187 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import pdb
import unittest
from datetime import date
from testing_utils import setupTestDB, fake_response_from_file
from scrapy.http import Response, Request, HtmlResponse
from sgfSpider.dbsgf import DBsgf, DBNewsItem
from sgfSpider.spiders.igokis... | rted(urls), [
u'http://igokisen.web.fc2.com/jp/sgf/40goseit1.sgf',
u'http://igokisen.web.fc2.com/jp/sgf/40goseit2.sgf',
u'http://igokisen.web.fc2.com/jp/sgf/40goseit3.sgf',
u'http://igokis | en.web.fc2.com/jp/sgf/40goseit4.sgf'
])
if __name__ == '__main__':
unittest.main()
|
carlos-ferras/Sequence-ToolKit | view/gensec/dialogs/processes/ui_tl.py | Python | gpl-3.0 | 8,875 | 0.001691 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/home/krl1to5/Work/FULL/Sequence-ToolKit/2016/resources/ui/gensec/process/tl.ui'
#
# Created by: PyQt5 UI code generator 5.5.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_pro... | temp | ")
self.layout_7.addWidget(self.save_temp)
spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.layout_7.addItem(spacerItem2)
self.verticalLayout_2.addLayout(self.layout_7)
self.horizontalLayout_8.addWidget(self.form_are... |
GustavoHennig/ansible | contrib/vault/vault-keyring.py | Python | gpl-3.0 | 3,430 | 0.001166 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) 2014, Matt Martz <matt@sivel.net>
# (c) 2016, Justin Mayer <https://justinmayer.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 later version.
#
# Ansible 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 GNU Ge... |
sccblom/vercors | deps/z3/4.4.1/Windows NT/intel/bin/example.py | Python | mpl-2.0 | 178 | 0 | # Copyright (c) Microsoft Corporation 2015
from z3 import *
x = Real('x')
y = Real('y')
s = Solver()
| s.add(x + y > 5, x > 1, y > 1) |
print(s.check())
print(s.model())
|
elelay/gPodderAsRSSReader | src/gpodder/gtkui/desktop/sync.py | Python | gpl-3.0 | 13,131 | 0.003427 | # -*- coding: utf-8 -*-
#
# gPodder - A media aggregator and podcast client
# Copyright (c) 2005-2011 Thomas Perl and the gPodder Team
#
# gPodder 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... | K+ UI and sync module |
# Thomas Perl <thp@gpodder.org>; 2009-09-05 (based on code from gui.py)
import gtk
import threading
import gpodder
_ = gpodder.gettext
from gpodder import util
from gpodder import sync
from gpodder.liblogger import log
from gpodder.gtkui.desktop.syncprogress import gPodderSyncProgress
from gpodder.gtkui.desktop.d... |
rdhyee/osf.io | api/nodes/views.py | Python | apache-2.0 | 141,472 | 0.004298 | import re
from modularodm import Q
from rest_framework import generics, permissions as drf_permissions
from rest_framework.exceptions import PermissionDenied, ValidationError, NotFound, MethodNotAllowed, NotAuthenticated
from rest_framework.status import HTTP_204_NO_CONTENT
from rest_framework.response import Response
... | lient
# requests a collection through a node endpoint, we return a 404
if node.is_collection or node.is_registration:
raise NotFound
# May raise a permission denied
if check_object_permissions:
self.check_object_ | permissions(self.request, node)
return node
class DraftMixin(object):
serializer_class = DraftRegistrationSerializer
def get_draft(self, draft_id=None):
node_id = self.kwargs['node_id']
if draft_id is None:
draft_id = self.kwargs['draft_id']
draft = get_object_or_... |
google/smilesparser | test_smilesparser_rdkit.py | Python | apache-2.0 | 6,797 | 0.010152 | # Copyright 2016 Google Inc. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agre... | , indent)
else:
| print " " * indent + item, dir(item)
def iterate_branch(self, branch, indent=0):
self.atomStack.append(self.prevAtomIdx)
for item in branch[0]:
if isinstance(item, smilesparser.AST.Bond):
self.inspect_bond(item.bond, indent+1)
elif isinstance(item, smilesparser.AST.SMILES):
self... |
jamielennox/python-kiteclient | kiteclient/tests/v1/utils.py | Python | apache-2.0 | 1,915 | 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... | lf.metadata,
"ticket": self.ticket}
class DummyGroupResponse(object):
def __init__(self, name):
self.name = name
def request(self, path, method, **kwargs):
return self
def json(self):
return {"name": self.name}
class DummyGroupKeyResponse(object):
def __ini... | self.group_key = group_key
def request(self, path, method, **kwargs):
return self
def json(self):
return {"signature": self.signature,
"metadata": self.metadata,
"group_key": self.group_key}
|
fortesit/search-engine | posting-list-search-k-distanced-words.py | Python | mit | 663 | 0.045249 | #! /usr/bin/env python
from sys import argv
script, q1, q2, k = argv
fw = open('c.txt', 'w+')
for docid in range(1,192):
filename = 'data/' + str(docid) + '.txt'
fr = open(filename)
| string = fr.read()
pp1 = []
pp2 = []
l = []
position = 0
for token in string.split():
if token == q1:
pp1.append(position)
if token == q2:
pp2.append(position)
position += 1
for i in pp1:
for j in pp2:
if abs(i - | j) <= int(k):
l.append(j)
elif j > i:
break
while l and abs(l[0] - i) > int(k):
l.pop(0)
prev_ps = -1
for ps in l:
if ps != prev_ps:
fw.write(str(docid) + ' ' + str(i) + ' ' + str(ps) + '\n')
prev_ps = ps
|
jelly/calibre | src/calibre/linux.py | Python | gpl-3.0 | 45,645 | 0.003856 | __license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
''' Post installation script for linux '''
import sys, os, cPickle, textwrap, stat, errno
from subprocess import check_call, check_output
from functools import partial
from calibre import __appname__, prints, guess_type
from calib... | 'ebook-viewer = calibre.gui_launch:ebook_viewer',
'ebook-edit = calibre.gui_launch:ebook_edit',
],
}
class PreserveMIMEDefaults(object):
def __init__(self):
| self.initial_values = {}
def __enter__(self):
def_data_dirs = '/usr/local/share:/usr/share'
paths = os.environ.get('XDG_DATA_DIRS', def_data_dirs)
paths = paths.split(':')
paths.append(os.environ.get('XDG_DATA_HOME', os.path.expanduser(
'~/.local/share')))
pa... |
OCA/partner-contact | partner_contact_department/tests/test_recursion.py | Python | agpl-3.0 | 915 | 0 | # © 2016 Tecnativa - Vicent Cubells
# License AG | PL-3.0 or later (https://www.gnu.org/licenses/agpl-3.0).
from odoo.exceptions import UserError
from odoo.tests import common
class TestRecursion(common.SavepointCase):
@classmethod
def setUpClass(cls):
super(TestRecursion, cls).setUpClass()
cls.department_obj = cls.env["res.partner.department"... | ls.department_obj.create({"name": "Dpt. 1"})
cls.dpt2 = cls.department_obj.create(
{"name": "Dep. 2", "parent_id": cls.dpt1.id}
)
def test_recursion(self):
""" Testing recursion """
self.dpt3 = self.department_obj.create(
{"name": "Dep. 3", "parent_id": self.... |
bnmrrs/runkeeper-api | runkeeper/httpclient.py | Python | mit | 1,887 | 0.00159 | #
# The MIT License
#
# Copyright (c) 2009 Ben Morris
#
# 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, modi... | are, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of th | e Software.
#
# THE SOFTWARE IS PROVIDED "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... |
apdjustino/DRCOG_Urbansim | src/opus_core/variables/utils/parse_tree_pattern_generator.py | Python | agpl-3.0 | 1,882 | 0.005845 | # Opus/UrbanSim urban simulation software.
# Copyright (C) 2010-2011 University of California, Berkeley, 2005-2009 University of Washington
# See opus_core/LICENSE
# Utility classes that can be used to generate parse tree patterns. These
# utilities take a sample expression or statement, and return a parse tree that... | l editing on
# the parse tree as needed (for example, replacing a specific value with a pattern).
import parser
from symbol im | port sym_name
from token import tok_name
from pprint import pprint
# pretty-prints a symbolic parse tree for expr (as for use with 'eval')
# the symbolic names will be strings, so to use this as a constant
# in some code you'll need to replace the quotes with nothing
# (except for the actual string constants ...)
def ... |
JimboMonkey1234/pushserver | handlers/Handler.py | Python | mit | 725 | 0.002759 | #!/usr/bin/env python
from collections import namedtuple
Payload = namedtuple('Payload', ['iden', 'body', 'send_date', 'sender'])
class Handler(object):
@staticmethod
def config():
re | turn
def __init__(self, logger):
self.logger = logger
def create_translator():
return
def create_listener(task):
return
def configure_modules(modules, push_config):
return
class Translator(object):
def get_recent():
return
def is_valid(message):
... | up(message):
return
def to_payload(message):
return
def respond(message, response):
return
|
moopie/botologist | plugins/streams/cache.py | Python | mit | 445 | 0.031461 | cl | ass StreamCache:
def __init__(self):
self.initiated = False
self.new_cache = []
self.old_cache = []
def push(self, streams):
assert isinstance(streams, list)
self.old_cache = self.new_cache
self.new_cache = streams
if not self.initiated:
self.initiated = T | rue
def get_all(self):
return set(self.new_cache + self.old_cache)
def __contains__(self, stream):
return stream in self.new_cache or stream in self.old_cache
|
SLiana/inf1340_2015_asst1 | exercise3.py | Python | mit | 2,130 | 0.004695 | #!/usr/bin/env python
""" Assignment 1, Exercise 3, INF1340, Fall, 2015. Troubleshooting Car Issues.
This module contains one function diagnose_car(). It is an expert system to
interactive diagnose car issues.
"""
__author__ = 'Susan Sim'
__email__ = "ses@drsusansim.org"
__copyright__ = "2015 Susan Sim"
__license__... | Inputs: As is but not nested - same indentation all the way through
# Expected Outputs: To fol | low the decision logic of the question tree
# Errors: Did not proceed according to logic. fixed by nesting properly
"""
"""
def diagnose_car():
silent = raw_input("Is the car silent when you turn the key? ")
#this begins the line of questions on the left side of the question tree
if silent == 'Y':
... |
22i/minecraft-voxel-blender-models | models/extra/blender-scripting/lib/iron_golem.py | Python | gpl-3.0 | 1,325 | 0.018113 | import bpy
import os
# join them together ctrl+j
bpy.ops.object.join()
def get_override(area_type, region_type):
for area in bpy.context.screen.areas:
if area.type == area_type:
for region in area.regions:
if r | egion.type == region_type:
override = {'area': area, 'region': region}
return override
#error message if the area o | r region wasn't found
raise RuntimeError("Wasn't able to find", region_type," in area ", area_type,
"\n Make sure it's open while executing script.")
#we need to override the context of our operator
override = get_override( 'VIEW_3D', 'WINDOW' )
#rotate about the X-axis by 45 degrees
bpy.o... |
PeerioTechnologies/peerio-client-mobile | tests/test.py | Python | gpl-3.0 | 414 | 0.002415 | impor | t time
import appium
import selenium
from common.helper import *
from common.processes import *
capabilities = {
"androidDeviceSocket": "com.peerio_devtools_remote",
"chromeOptions": {
'androidPackage': 'com.peerio',
'androidActivity': '.MainActivity',
"androidDeviceSocket": "co | m.peerio_devtools_remote"
}
}
restartAppium()
restartChromedriver()
test_connect_android()
|
joushou/stackable | utils.py | Python | mit | 3,175 | 0.033701 | #
# Utility stackables
#
from __future__ import print_function, absolute_import, unicode_literals, division
from stackable.stackable import Stackable, StackableError
import json, pickle
from time import sleep
from threading import Thread, Event
from datetime import datetime, timedelta
class StackablePickler(Stackable... | elf.timestamp = datetime.now()
def ping():
self.w.wait(self.interval)
try:
self._feed(s | elf.ping_string)
except:
pass
x = Thread(target=ping)
x.daemon = True
x.start()
def process_output(self, data):
if self.send and (datetime.now() - self.timestamp) > timedelta(seconds=30):
raise StackableError('Pong not received')
return data
def process_input(self, data):
if data == self.pong_... |
GarrettArm/TheDjangoBook | mysite_project/milage/urls.py | Python | gpl-3.0 | 452 | 0.002212 | from django.urls import path, include
from .routers import router
from . import views
app_name = "milage"
urlpatterns = [
path("api/", include(router.urls), name="api_router"),
path("class-based/", views.ClassBas | edView.as_view(), name="class_based_drf"),
path(
"class-based-detail/<int:pk>",
views.ClassBasedDetailView.as_view(),
name="class_detail",
| ),
path("", views.BaseView.as_view(), name="index"),
]
|
Anber/django-extended-messages | setup.py | Python | bsd-3-clause | 1,190 | 0.017647 | import os, extended_messages
from setuptools import setup, find_packages
if extended_messages.VERSION[-1] == 'final':
CLASSIFIERS = ['Development Status :: 5 - Stable']
elif 'beta' in extended_messages.VERSION[-1]:
CLASSIFIERS = ['Development Status :: 4 - Beta']
else:
CLASSIFIERS = ['Development Status ::... | ngo-extended-messages/tree/master',
license = 'BSD License',
platforms=['OS Independent'],
classifiers = CLASSIFIERS,
requires=[
| 'django (>1.2.0)',
'simplejson',
],
packages=find_packages(),
zip_safe=False
) |
kafan15536900/ADfree-Player-Offline | onServer/ruletool/oconfiglist.py | Python | gpl-3.0 | 562 | 0 | [
{
"name": "syoukuloader",
"status": "0"
},
{
"name": "syoukuplayer",
"status": "0"
},
{
"name": "sku6",
| "status": "0"
},
{
"name": "studou",
"status": "0"
},
{
"name": "sletv",
"status": "0"
},
{
"name": "siqiyi",
"status": "0"
},
{
"name": "spps",
"status": "0"
},
{
"name | ": "ssohu",
"status": "0"
},
{
"name": "ssohu_live",
"status": "0"
}
]
|
vyos-legacy/vyconfd | vyconf/utils/__init__.py | Python | lgpl-2.1 | 35 | 0 | from | .item_status im | port * # noqa
|
belokop/indico_bare | indico/modules/groups/forms.py | Python | gpl-3.0 | 1,904 | 0.000525 | # This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (a... | es/>.
from __future__ import unicode_literals
from wtforms.fields import StringField, BooleanField, SelectField
from wtforms.validators import DataRequired, ValidationError
from indico.core.db import db
from indico.modules.groups.models.groups import LocalGroup
from indico.util.i18n import _
from indico.web.forms.ba... | cipalListField
class SearchForm(IndicoForm):
provider = SelectField(_('Provider'))
name = StringField(_('Group name'), [DataRequired()])
exact = BooleanField(_('Exact match'))
class EditGroupForm(IndicoForm):
name = StringField(_('Group name'), [DataRequired()])
members = PrincipalListField(_('G... |
jballanc/openmicroscopy | components/tools/OmeroWeb/omeroweb/webclient/forms.py | Python | gpl-2.0 | 111,021 | 0.010998 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#
#
# Copyright (c) 2008-2011 University of Dundee.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License... | = logging.getLogger(__name__)
########################################## | ########################
# Static values
# TODO: change to reverse
help_button = "%swebgateway/img/help16.png" % settings.STATIC_URL
help_wiki = '<span id="markup" title="Markups - <small>If you\'d like to include URL please type:<br/><b>http://www.openmicroscopy.org.uk/</b></small>"><img src="%s" /></span>' % help_b... |
shashankjagannath/shashankfoo | genresigpath.py | Python | cc0-1.0 | 1,485 | 0.032997 | import time
import glob
import os
import types
import socket
def read_paths ():
fulllist = []
for file in glob.glo | b("*96*messages"):
print 'reading ' + file
fullfile = (open(file).read().splitlines())
for x in fullfile:
if 'RPD_MPLS_LSP_CHANGE'in x and 'Sep 17' in x:
if 'flag' in x:
fulllist.append(x.split())
print 'done reading'
... | onfigs/addresses.txt").read().splitlines())
for x in dnsfile:
if '96c'in x or 'ibr' in x or '96l' in x or '20lsr' in x :
dnsdict[x.split(":")[0]] = x.split(":")[1] +" " + x.split(":")[2]
for x in newpaths:
z = [x[8],x[12]]
for y in x:
if 'flag=0x2' in y:
rest = y.split('(',1)[0]
z.append(dnsdict[r... |
SunDwarf/Pyte | pyte/tokens_33.py | Python | mit | 2,143 | 0.000467 | # _V!(3, 3)
# This file was automatically generated by `dump_dis.py`.
# This file is designed for Python (3, 3).
import sys
# Check Python version
if sys.version_info[0:2] != (3, 3):
raise SystemError("Inappropriate Python version for these bytecode symbols.")
# Begin tokens. These are ordered.
POP_TOP = 1
ROT_T... | LETE_NAME = 91
UNPACK_SEQUENCE = 92
FOR_ITER = 93
UNPACK_EX = 94
STORE_ATTR = 95
DELETE_ATTR = 96
STORE_GLOBAL = 97
DELETE_GLOBAL = 98
LOAD_CONST = 100
LOAD_NAME = 101
BUILD_TUPLE = 102
BUILD_LIST = 103 |
BUILD_SET = 104
BUILD_MAP = 105
LOAD_ATTR = 106
COMPARE_OP = 107
IMPORT_NAME = 108
IMPORT_FROM = 109
JUMP_FORWARD = 110
JUMP_IF_FALSE_OR_POP = 111
JUMP_IF_TRUE_OR_POP = 112
JUMP_ABSOLUTE = 113
POP_JUMP_IF_FALSE = 114
POP_JUMP_IF_TRUE = 115
LOAD_GLOBAL = 116
CONTINUE_LOOP = 119
SETUP_LOOP = 120
SETUP_EXCEPT = 121
SETUP... |
EmanueleCannizzaro/scons | src/engine/SCons/Tool/applelink.py | Python | mit | 2,828 | 0.003182 | """SCons.Tool.applelink
Tool-specific initialization for the Apple gnu-like linker.
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 - 2016 The SCons Foundation
#
# Permission is hereby... | S'
# override the default for loadable modules, which are different
# on OS X than dynamic shared libs. echoing what XCode does for
# pre/suffixes:
env['LDMODULEPREFIX'] = ''
env['LDMODULESUFFIX'] = ''
env['LDMODULEFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -bundle')
env['LDMODULECOM'] = '$L... | env):
return env['PLATFORM'] == 'darwin'
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
|
kzlin129/practice-typing | lib/python2.7/site-packages/profilehooks.py | Python | apache-2.0 | 26,416 | 0.000341 | """
Profiling hooks
This module contains a couple of decorators (`profile` and `coverage`) that
can be used to wrap functions and/or methods to produce profiles and line
coverage reports. There's a third convenient decorator (`timecall`) that
measures the duration of function execution without the extra profiling
ove... | me__ = fn.__name__
new_fn.__dict__ = fn.__dict__
new_fn.__module__ = fn.__module__
return new_fn
def coverage(fn):
"""Mark `fn` for line coverage analysis.
Results will be printed to sys.stdout on progr | am termination.
Usage::
def fn(...):
...
fn = coverage(fn)
If you are using Python 2.4, you should be able to use the decorator
syntax::
|
MingfeiPan/leetcode | array/74.py | Python | apache-2.0 | 655 | 0.003396 | #这个题面试时遇到过, 本身matrix是有特点的, 如果从左下角开始搜索 就可以看到规律
class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
i = len(matrix) - 1
| j = 0
flag = 0
if not matrix or not matr | ix[0]:
return False
while i >= 0 and j < len(matrix[0]):
if matrix[i][j] == target:
return True
elif matrix[i][j] < target:
j += 1
else:
i -= 1
return False
|
jaufrec/whatnext | clog/migrations/0011_auto_20160528_0055.py | Python | gpl-3.0 | 419 | 0 | # | -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-05-28 00:55
from __future__ | import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('clog', '0010_auto_20160410_2149'),
]
operations = [
migrations.AlterUniqueTogether(
name='variable',
unique_together=set([('user', 'name')]),
... |
greut/invenio-kwalitee | kwalitee/cli/prepare.py | Python | gpl-2.0 | 6,883 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of kwalitee
# Copyright (C) 2014, 2015 CERN.
#
# kwalitee 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) an... | n,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
#
# In applying this licence, CERN does not waive the privileges and immunities
# granted to it by virtue of its status as an Int | ergovernmental Organization
# or submit itself to any jurisdiction.
"""Prepare release news from git log.
Prepares release news from git log messages, breaking release news
into (1) sections (e.g. Security fixes, detected from commit labels)
and (2) modules (e.g. search, detected from commit log headlines).
"""
from... |
stephenliu1989/HK_DataMiner | hkdataminer/template_matching/Select_angle/__init__.py | Python | apache-2.0 | 23 | 0.043478 | from .cal_va | r_byPCA | *
|
globocom/GloboNetworkAPI-client-python | networkapiclient/EquipamentoAmbiente.py | Python | apache-2.0 | 6,040 | 0.002815 | # -*- coding:utf-8 -*-
# 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 "Lice... | oNotFoundError: Equipment not registered.
:raise EquipamentoAmbienteNaoExisteError: Environment not registered.
:raise VipIpError: IP-related equipment is being used for a request VIP.
:raise XMLError: Networkapi failed to generate the XML response.
:raise DataBaseError: Networkapi faile... | er of Equipment is invalid or was not informed.')
if not is_valid_int_param(id_environment):
raise InvalidParameterError(
u'The identifier of Environment is invalid or was not informed.')
url = 'equipment/' + \
str(id_equipment) + '/environment/' + str(id_enviro... |
fedora-conary/conary | conary_test/verifytest.py | Python | apache-2.0 | 12,956 | 0.015282 | #
# Copyright (c) SAS Institute Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | verify.verify(['unknownpkg=@rpl:linux'], db, self.cfg)
self.logFilter.remove()
self.logFilter.compare(('error: trove unknownpkg is not installed',
'error: version @rpl:linux of trove unknownpkg is not installed'))
def testVerifyWithSignatures(self):
# Make sure that verify work... | self.addComponent('foo:runtime', '1.0', '',
['/foo'])
self.addComponent('foo:data', '1.0')
self.addCollection('foo', '1.0', [':runtime', ':data'])
self.updatePkg(['foo', 'foo:runtime'], recurse=False)
self.writeFile(self.rootDir + '/foo', 'newtext')
... |
A-Kokolis/thesis-ntua | scc_implementation/scc_countermeasures.py | Python | gpl-3.0 | 2,957 | 0.00372 | import abc
import logging
from time import sleep, time
from subprocess import call, check_output
from config import sim_dump_location, safe_location, devel
import infoli_diagnostics
import sys
class countermeasure(object):
''' Countermeasure class '''
__metaclass__ = abc.ABCMeta
@abc.abstractmet... | dvfs: ")
self.manager.dvfs.dvfsOperation(checkpoint)
print "Restarting from step" + str(checkpoint)
logging.info("Restarting from step " + str(checkpoint))
with self.manager.lock:
# Copy safe checkpoints
#for i in range(self.manager.num_cores):
... | nt) + '/InferiorOlive_Output%d.txt' %i, sim_dump_location])
self.manager.rccerun([self.manager.restart_exec] + self.manager.exec_list[1:]) # use False as extra last argument to avoid piping stdout for diagnostics - useful for measurements
logging.info("Restart Simulation countermeasure completed")... |
pkovac/evedustrial | eve/db.py | Python | mit | 1,136 | 0.011444 | from . xml import EVECACHEPATH
import time
from os import path
import urllib
import MySQLdb as mysql
from urllib2 import urlopen
class EveDb(object):
"""
This class is responsible for loading up an instance of the eve static
dump information. Without this, most functionality of this library will
not wor... | t__(self, database, user, passwd, host="localhost"):
self.db = mysql.connect(host=host, user=user, passwd=passwd, db=database)
def get_item_row(self, id):
cur=self.db.cursor()
cols = ("typeID", "typeName", "description", "volume")
cur.execute("select "+ ",".join(cols) + " fr... | w = cur.fetchone()
row = dict(zip(cols, row))
return row
def get_location_row(self, id):
return
def get_location_by_string(self, id):
return
def get_item_by_string(self, txt):
c = self.db.cursor()
c.execute("select typeName from invTypes where typeName GLOB '%... |
OCA/l10n-spain | l10n_es_aeat_mod347/tests/__init__.py | Python | agpl-3.0 | 104 | 0 | # L | icense AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from . import test_l10n_es_a | eat_mod347
|
mmpagani/oq-hazardlib | openquake/hazardlib/gsim/edwards_fah_2013a.py | Python | agpl-3.0 | 9,481 | 0 | # -*- coding: utf-8 -*-
# The Hazard Library
# Copyright (C) 2013-2014, GEM Foundation
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your opt... | a3'] *
np.power(mag, 2) + C['a4'] * np.power(mag, 3)
+ C['a5'] * np.power(mag, 4) + C['a6'] *
np.power(mag, 5) + C['a7'] * np.power(mag, 6)
)
def _compute_term_2(self, C, mag, R):
"""
(a8 + a9.*M + a10.*M.*M + a11.*M.*M.*M).*d(r)
"""
retur... | 3(self, C, mag, R):
"""
(a12 + a13.*M + a14.*M.*M + a15.*M.*M.*M).*(d(r).^2)
"""
return (
(C['a12'] + C['a13'] * mag + C['a14'] * np.power(mag, 2) +
C['a15'] * np.power(mag, 3)) * np.power(R, 2)
)
def _compute_term_4(self, C, mag, R):
"""
... |
lCharlie123l/django-thumborstorage | tests/thumbor_project/thumbor_project/wsgi.py | Python | mit | 1,446 | 0.000692 | """
WSGI config for thumbor_project project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` command | s discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django W | SGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks
# if running multiple ... |
ntim/g4sipm | sample/run/luigi/all.py | Python | gpl-3.0 | 561 | 0.023173 | #!/usr/bin/env python
import luigi
import dynamic_range_simulation
import darknoise_simulation
import pde_simulation
i | mport relative_pde_simulation
import n_pe_simulation
import crosstalk_neighbour_simulation
class All(luigi.WrapperTask):
def requires(self):
yield crosstalk_neighbour_simulation.All()
yield darknoise_simulation.All()
yield dynamic_range_simulation.All()
yield n_pe_simulation.All()
yield pde_s... | eld relative_pde_simulation.All()
if __name__ == "__main__":
luigi.run(main_task_cls=All)
|
alexm92/sentry | tests/sentry/models/test_event.py | Python | bsd-3-clause | 1,907 | 0 | from __future__ import absolute_import
from sentry.testutils import TestCase
class EventTest(TestCase):
def test_legacy_tags(self):
event = self.create_event(data={
'tags': [
('logger', 'foobar'),
('site', 'foo'),
('server_name', 'bar'),
... | event = self.create_event(message='foo bar')
assert event.get_legacy_message() == 'foo bar'
def test_message_interface(self):
event = self.create_event(
message='biz baz',
data={
'sentry.interfaces.Message': {'message': 'foo bar'}
},
... | _with_formatting(self):
event = self.create_event(
message='biz baz',
data={
'sentry.interfaces.Message': {
'message': 'foo %s',
'formatted': 'foo bar',
'params': ['bar'],
}
},
... |
asedunov/intellij-community | python/testData/completion/relativeFromImportInNamespacePackage2/nspkg1/a.after.py | Python | apache-2.0 | 17 | 0.058824 | from . import fo | o | |
joelsmith/openshift-tools | ansible/roles/lib_openshift_3.2/library/oadm_ca.py | Python | apache-2.0 | 35,621 | 0.002892 | #!/usr/bin/env python # pylint: disable=too-many-lines
# ___ ___ _ _ ___ ___ _ _____ ___ ___
# / __| __| \| | __| _ \ /_\_ _| __| \
# | (_ | _|| .` | _|| / / _ \| | | _|| |) |
# \___|___|_|\_|___|_|_\/_/_\_\_|_|___|___/_ _____
# | \ / _ \ | \| |/ _ \_ _| | __| \_ _|_ _|
# | |) | (_) ... | if url:
cmd.append('--from={0}/{1}'.format(url, image))
cmd.append('-n{0}'.format(self.namespace))
cmd.append('--confirm | ')
return self.openshift_cmd(cmd)
#pylint: disable=too-many-arguments
def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
'''Base command for oc '''
cmds = []
if oadm:
cmds = ['/usr/bin/oadm']
else:
cmds = ... |
mdcic/ssp | docs/source/conf.py | Python | gpl-3.0 | 752 | 0.00133 | # -*- coding: utf-8 -*-
import sys, os
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.todo']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'ssp'
copyright = u'2013, Yury Konovalov'
version = '0.0.1'
release = '0.0.1'
exclude_patterns = []
pygments_style = 'sphinx'
html_theme ... | ename = 'sspdoc'
latex_elements = {
}
latex_ | documents = [
('index', 'ssp.tex', u'ssp Documentation',
u'Yury Konovalov', 'manual'),
]
man_pages = [
('index', 'ssp', u'ssp Documentation',
[u'Yury Konovalov'], 1)
]
texinfo_documents = [
('index', 'ssp', u'ssp Documentation',
u'Yury Konovalov', 'ssp', 'One line description of project.',
'Miscel... |
yoe/veyepar | dj/scripts/email_url.py | Python | mit | 1,390 | 0.009353 | #!/usr/bin/python
# email_url.py
# emails the video URL to the presenters
from email_ab import email_ab
class email_url(email_ab):
ready_state = 7
subject_template = "[{{ep.show.name}}] Video up: {{ep.name}}"
body_body = """
The video of your talk is posted:
{{url}}
{% if ep.state == 7 %}
Look... | ame__ == '__main__':
p=email_url | ()
p.main()
|
opencorato/votainteligente-portal-electoral | votainteligente/settings.py | Python | gpl-3.0 | 2,935 | 0.000681 | """
Django settings for votainteligente project.
Generated by 'django-admin startproject' using Django 1.8.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Bu... | 'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'votainteligente.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'd... | '),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'it-it'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
STATIC_RO... |
xen/flask-rq | docs/conf.py | Python | mit | 9,809 | 0.006932 | # -*- coding: utf-8 -*-
#
# Flask-RQ documentation build configuration file, created by
# sphinx-quickstart on Mon Mar 12 15:35:21 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# Al... | to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.... | prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. Major themes that come with
# Sphinx are currently 'default' and 'sphinxdoc'.
html_theme = 'flask_small'
# Theme options... |
Havate/havate-openstack | proto-build/gui/horizon/Horizon_GUI/openstack_dashboard/openstack/common/rpc/impl_fake.py | Python | apache-2.0 | 5,854 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy | of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implie | d. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Fake RPC implementation which calls proxy methods directly with no
queues. Casts will block, but this is very useful for tests.
"""
import inspect
# NOTE(russellb): We specifically want to use json, not ... |
feend78/evennia | evennia/contrib/tutorial_world/rooms.py | Python | bsd-3-clause | 40,655 | 0.001746 | """
Room Typeclasses for the TutorialWorld.
This defines special types of Rooms available in the tutorial. To keep
everything in one place we define them together with the custom
commands needed to control them. Those commands could also have been
in a separate module (e.g. if they could have been re-used elsewhere.)... | g.
# This tells search that we want to handle error messages
| # ourself. This also means the search function will always
# return a list (with 0, 1 or more elements) rather than
# result/None.
looking_at_obj = caller.search(args,
# note: excludes room/room aliases
... |
Colibri-Embedded/FABEmu | examples/rpiemu.py | Python | gpl-2.0 | 909 | 0.006601 | #!/usr/bin/env python
import os, Queue
import sys
from time import sleep
from threading import Thread
from libs.qemu import QemuInstance, UARTLineParser
# External
if len(sys.argv) > 1:
print "ARGS:", str(sys.argv)
sys.path.append(os.path.dirname( sys.argv[1] ))
########################################... | dels.totumduino import TotumDuino
from models.fabtotum import FABTotum
# FABTotum model
ft = FABTotum()
# Totumduino model
td = TotumDuino(ft)
|
# Start a TD thread
td.run()
print("* Totumduino thread started")
# UART line parser
parser = UARTLineParser(qemu=rpi, line_handler=td.uart0_transfer)
parser.start()
parser.loop()
# Finish the TD thread
td.finish()
|
OriHoch/pysiogame | game_boards/game070.py | Python | gpl-3.0 | 12,968 | 0.018124 | # -*- coding: utf-8 -*-
import classes.level_controller as lc
import classes.game_driver as gd
import classes.extras as ex
import classes.board
import random
import pygame
class Board(gd.BoardGame):
def __init__(self, mainloop, speaker, config, screen_w, screen_h):
self.level = lc.Level(self,mainloop,5,... | Letter,"",self.bg_col,"",1)
self.carry1l.append(self.board.ships[-1])
self.carry1l[-1].set_outline(self. | grey, 2)
self.carry1l[-1].pos_id = i
self.board.units[-1].align = 2
#add 10
for i in range(self.n1sl - 1):
self.board.add_unit(data[0]-3-i*3,1,1,1,classes.board.Label,"+",self.bg_col,"",0)
self.board.add_unit(data[0]-2-i*3,1,1,1,classes.board.Letter,"",se... |
jbms/mintapi | mintapi/api.py | Python | mit | 25,488 | 0.000471 | import json
import random
import time
import re
try:
from StringIO import StringIO # Python 2
except ImportError:
from io import BytesIO as StringIO # Python 3
from datetime import date, datetime, timedelta
import requests
from requests.adapters import HTTPAdapter
try:
from requests.packages.urlli... | if get_detail:
accounts = self.populat | e_extended_account_detail(accounts)
return accounts
def set_user_property(self, name, value):
url = ('https://wwws.mint.com/bundledServiceController.xevent?' +
'legacy=false&token=' + self.token)
req_id = str(self.request_id)
self.request_id += 1
result = self... |
lsaffre/lino-welfare | lino_welfare/modlib/isip/__init__.py | Python | agpl-3.0 | 413 | 0 | # -*- coding: UTF-8 -*-
# Copyrigh | t 2012-2015 Rumma & Ko Ltd
# License: BSD (see file COPYING for details)
"""See :doc:`/specs/isip`.
"""
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from lino.api import ad
class Plugin(ad.Plugin):
"See :class:`lino.core.plugin.Plugin`."
verbose_name = _... | g']
|
tyagow/AdvancingTheBlog | src/posts/migrations/0002_post_user.py | Python | mit | 633 | 0.00158 | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-01-05 03:11
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 = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('posts', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='post',
name='user',
... | n_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
]
|
jvs/sourcer | sourcer/expressions/sep.py | Python | mit | 2,062 | 0.000485 | from outsourcer import Code
from . i | mport utils
from .base import Expression
from . | constants import BREAK, POS, RESULT, STATUS
class Sep(Expression):
num_blocks = 2
def __init__(
self,
expr,
separator,
discard_separators=True,
allow_trailer=False,
allow_empty=True,
):
self.expr = expr
self.separ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.