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 |
|---|---|---|---|---|---|---|---|---|
DzinVision/adventofcode-2016 | day_13.py | Python | gpl-3.0 | 1,232 | 0.000812 | from queue import Queue
seed = 1362
seen = set()
def is_empty(x, y):
n = x*x + 3*x + 2*x*y + y + y*y + seed
return bin(n).count('1') % 2 == 0
def valid_moves(x, y):
result = []
actions = [-1, 1]
for action in actions:
new_x = x + action
if x > 0 and is_empty(new_x, y) and (new_x... | en:
result.append((new_x, y))
new_y = y + action
if y > 0 and is_empty(x, new_y) and (x, new_y) not in seen:
result.append | ((x, new_y))
return result
state = {
'coords': (1, 1),
'moves': 0
}
que = Queue()
que.put(state)
locations = 0
solved_1 = False
solved_2 = False
while not solved_1 or not solved_2:
current_state = que.get()
moves = current_state['moves']
if current_state['coords'] in seen:
continue... |
shellphish/rex | rex/exploit/techniques/rop_to_accept_system.py | Python | bsd-2-clause | 3,231 | 0.004333 | import logging
from angrop.errors import RopException
from ...vulnerability import Vulnerability
from .. import Exploit, CannotExploit
from ..technique import Technique
l = logging.getLogger("rex.exploit.techniques.rop_to_accept_system")
class RopToAcceptSystem(Technique):
name = "rop_to_accept_system"
ap... | oit:
raise CannotExploit("[%s] unable to insert chain" % self.name)
# add the constraint to the state that the chain must exist at the address
chain_mem | = self.crash.state.memory.load(chain_addr, chain.payload_len)
self.crash.state.add_constraints(chain_mem == self.crash.state.solver.BVV(chain.payload_str()))
if not self.crash.state.satisfiable():
raise CannotExploit("[%s] generated exploit is not satisfiable" % self.name)
return E... |
DIRACGrid/DIRAC | src/DIRAC/TransformationSystem/Client/TaskManagerPlugin.py | Python | gpl-3.0 | 5,584 | 0.002865 | """ Container for TaskManager plug-ins, to handle the destination of the tasks
| """
import six
from DIRAC import gLogger
from DIRAC.Core.Utilities.List import fromChar
from DIRAC.Core.Utilities.SiteSEMapping import getSitesForSE
from DIRAC.DataManagementSystem.Utilities.DMSHelpers import DMSHelpers
from DIRAC.ConfigurationSystem.Client.Helpers.Resources import getSites
from DIRAC.TransformationSy... | self.params here could be
{'Status': 'Created', 'TargetSE': 'Unknown', 'TransformationID': 1086L, 'RunNumber': 0L,
'Site': 'DIRAC.Test.ch', 'TaskID': 21L, 'InputData': '', 'JobType': 'MCSimulation'}
which corresponds to paramsDict in TaskManager (which is in fact a tasks dict)
"""
def _BySE(self):
... |
Mirantis/mos-horizon | openstack_dashboard/test/integration_tests/pages/project/compute/volumes/volumesnapshotspage.py | Python | apache-2.0 | 5,448 | 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
# d... | ble(self.driver, self.conf)
def switch_to_volumes_tab(self):
self._get_element(*self._volumes_tab_locator).click()
return VolumesPage(self.driver, self.conf)
def _get_row_with_volume_snapshot_name(self, name):
return self.volumesnapshots_table.get_row(
self.SNAPSHOT_TABLE_N... | lume_snapshot_name(name))
def delete_volume_snapshot(self, name):
row = self._get_row_with_volume_snapshot_name(name)
confirm_form = self.volumesnapshots_table.delete_volume_snapshot(row)
confirm_form.submit()
def delete_volume_snapshots(self, names):
for name in names:
... |
nonZero/OpenCommunity | src/users/migrations/0003_auto_20150607_1606.py | Python | bsd-3-clause | 2,009 | 0.002987 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from acl.models import Role
from communities.models import Community, CommunityGroup, Committee, CommunityGroupRole
from django.db import models, migrations
def create_default_groups(apps, schema_editor):
Membership = apps.get_model("users", "Members... | tle="chairman"),
group=c.community.groups.get(title="chairman")),
CommunityGroupRole(committee=c, role=c.community.roles.get(title="board"),
group=c.community.groups.get(tit | le="board")),
CommunityGroupRole(committee=c, role=c.community.roles.get(title="member"),
group=c.community.groups.get(title="member"))
])
class Migration(migrations.Migration):
dependencies = [
('users', '0002_auto_20150607_1350'),
]
operations ... |
EricMuller/mynotes-backend | requirements/twisted/Twisted-17.1.0/docs/core/examples/shoutcast.py | Python | mit | 565 | 0.00354 | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Example Shou | tcast client. Run with:
python shoutcast.py localhost 8080
"""
from __future__ import print_function
import sys
from twisted.internet import protocol, reactor
from twisted.protocols.shoutcast import ShoutcastClient
class Test(ShoutcastClient):
def gotMetaData(self, data):
print("meta:", data)
def g... | f, data):
pass
host = sys.argv[1]
port = int(sys.argv[2])
protocol.ClientCreator(reactor, Test).connectTCP(host, port)
reactor.run()
|
plotly/python-api | packages/python/plotly/plotly/graph_objs/bar/_outsidetextfont.py | Python | mit | 11,250 | 0.0008 | from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Outsidetextfont(_BaseTraceHierarchyType):
# class properties
# --------------------
_parent_path_str = "bar"
_path_str = "bar.outsidetextfont"
_valid_props = {"color", "colorsrc", "family... | "Arial", "Balto", "Courier New", "Droid
S | ans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT
Sans Narrow", "Raleway", "Times New Roman".
familysrc
Sets the source reference on Chart Studio Cloud for
family .
size
sizesrc
Se... |
sigurdga/nidarholm | news/migrations/0003_use_content_fields.py | Python | agpl-3.0 | 5,196 | 0.008083 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
def forwards(self, orm):
"Write your forwards methods here."
for story in orm.Story.objects.all():
story.content = story.text
... | els.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), |
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", '... |
django-de/djangosnippets.org | cab/urls/users.py | Python | bsd-3-clause | 225 | 0 | from django.urls import path
f | rom ..views import popular, snippets
urlpatterns = [
path('', popular.to | p_authors, name='cab_top_authors'),
path('<username>/', snippets.author_snippets, name='cab_author_snippets'),
]
|
chrisbarber/dask | dask/dataframe/tests/test_reshape.py | Python | bsd-3-clause | 6,521 | 0.00092 |
import numpy as np
import pandas as pd
import pandas.util.testing as tm
import pytest
import dask.dataframe as dd
from dask.dataframe.utils import assert_eq, PANDAS_ge_0190
@pytest.mark.parametrize('data', [
pd.Series([1, 1, 1, 2, 2, 1, 3, 4], dtype='category'),
pd.Series(pd.Categorical([1, 1, 1, 2, 2, 1, ... | unc='count')
exp_index = pd.CategoricalIndex(['A', 'B'], name='B')
exp = pd.Series([np.float64] * 2, index=exp_index)
tm.assert_series_equal(res.dtypes, exp)
exp = pd.pivot_table(df, index='A', columns='B',
values='C', aggfunc='count').astype(np.float64)
if PA | NDAS_ge_0190:
assert_eq(res, exp)
else:
# because of a pandas 0.18.x bug, categorical dtype is not preserved
assert_eq(res, exp, check_names=False, check_column_type=False)
def test_pivot_table_errors():
df = pd.DataFrame({'A': np.random.choice(list('abc'), size=10),
... |
72squared/redpipe | redpipe/futures.py | Python | mit | 16,126 | 0 | # -*- coding: utf-8 -*-
"""
The `Future()` object in **RedPipe** gives us the ability to make the pipeline
interface of redis-py look like the non-pipelined interface.
You call a command and get a response back.
Only the response is not the actual data.
It is an empty container called a `Future`.
There is a callback at... | assert(future == [1]) |
assert([v for v in future] == [1])
assert(future + [2] == [1, 2])
And here is a dictionary:
.. code-block:: python
future = Future()
future.set({'a': 1})
assert(future == {'a': 1})
assert(dict(future) == {'a': 1})
assert({k: v for k, v in future.items()} == {'a': 1})
There are many more... |
alforro/sgpa2015 | miembros/urls.py | Python | gpl-2.0 | 703 | 0.008535 |
from django.conf.urls import patterns, url
from miembros import views
from django.contrib.auth.decorators import login_required
urlpatterns = patterns('',
url(r | '^configurar/(?P<pk>\d+)$', login_required(views.IndexView.as_view()), name='miembros_listar'),
url(r'^crear/(?P<pk>\d+)/(?P<usuario>\d+)$', login_required(views.CreateMiembro.as_view()), name='crear_miembro'),
url(r'^quitar/(?P<pk>\d+)$', login_required(views.DeleteMiembro.as_view()), name='quitar_miembro'),
... | _usuarios/(?P<pk>\d+)$', login_required(views.IndexViewVerUser.as_view(context_object_name='no_miembros')), name='ver_usuarios'),
) |
ahoarau/m3meka | python/scripts/m3qa/calibrate_arm_a1r1.py | Python | mit | 4,744 | 0.038997 | #Copyright 2008, Meka Robotics
#All rights reserved.
#http://mekabot.com
#Redistribution and use in source and binary forms, with or without
#modification, are permitted.
#THIS SOFTWARE IS PROVIDED BY THE Copyright HOLDERS AND CONTRIBUTORS
#"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
#LIMITED... | TAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES INCLUDING,
#BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
#LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
#CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
#LIABILITY, OR TORT (INCLUDING NEGLIGEN | CE OR OTHERWISE) ARISING IN
#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
#POSSIBILITY OF SUCH DAMAGE.
import time
import numpy.numarray as na
#import Numeric as nu
import math
import os
import sys
import yaml
import m3.unit_conversion as m3u
from m3qa.calibrate import *
from m3qa.calibrate_sensors... |
claudep/pootle | pootle/apps/pootle_config/getters.py | Python | gpl-3.0 | 1,264 | 0 | # -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed u | nder the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from pootle.core.delegate import config
from pootle.core.plugin import getter
from .exceptions import ConfigurationError
from .mod | els import Config
@getter(config)
def config_getter(**kwargs):
sender = kwargs["sender"]
instance = kwargs.get("instance")
key = kwargs.get("key")
if sender:
if instance is not None and not isinstance(instance, sender):
raise ConfigurationError(
"'instance' must be... |
dakrauth/django-swingtime | swingtime/admin.py | Python | mit | 686 | 0 | from django.contrib.contenttypes.admin import GenericTabularInline
from django.contrib import admin
from swingtime.models import *
class EventTypeAdmin(admin.ModelAdmin):
| list_display = ('label', 'abbr')
class OccurrenceInline(admin.TabularInline):
mode | l = Occurrence
extra = 1
class EventNoteInline(GenericTabularInline):
model = Note
extra = 1
class EventAdmin(admin.ModelAdmin):
list_display = ('title', 'event_type', 'description')
list_filter = ('event_type', )
search_fields = ('title', 'description')
inlines = [EventNoteInline, Occur... |
jdzero/foundation | foundation/models/manager.py | Python | mit | 209 | 0 | from djan | go.db.models import manager
from .query import QuerySet
__all__ = 'Manager',
class Manager(manager.Manager.from_queryset(QuerySet)):
use_for_related_fields = True
| use_in_migrations = True
|
whosonfirst/py-mapzen-whosonfirst-mapshaper-utils | setup.py | Python | bsd-3-clause | 1,496 | 0.003342 | #!/usr/bin/env python
# Remove .egg-info directory if it exists, to avoid dependency problems with
# partially-installed packages (20160119/dphiffer)
import os
import sys
import shutil
setup = os.path.abspath(sys.argv[0])
parent = os.path.dirname(setup)
pkg = os.path.basename(parent)
if pkg.startswith("py-mapzen"):... | ", "")
pkg = pkg.replace("-", ".")
egg_info = "%s.egg-info" % pkg
egg_info = os.path.join(parent, egg_info)
if os.path.exists(egg_info):
shutil.rmtree(egg_info)
from setuptools import setup, find_packages
packages = find_packages()
desc = open("README.md").read()
version = open("VERSION").re... | irst.mapshaper.utils'],
version=version,
description='Python utility methods for working with Who\'s On First documents and Mapshaper',
author='Mapzen',
url='https://github.com/whosonfirst/py-mapzen-whosonfirst-mapshaper-utils',
install_requires=[
'mapzen.whosonfirst.mapshaper>=0.05',
... |
beiko-lab/gengis | bin/Lib/site-packages/scipy/stats/_binned_statistic.py | Python | gpl-3.0 | 15,105 | 0.000265 | from __future__ import division, print_function, absolute_import
import numpy as np
from scipy.lib.six import callable
def binned_statistic(x, values, statistic='mean',
bins=10, range=None):
"""
Compute a binned statistic for a set of data.
This is a generalization of a h... | ], edges[1], xy
def binned_statistic_dd(sample, values, statistic='mean',
bins=10, range=None):
"""
Compute a multidimensional binned statistic for a set of data.
This is a generalization of a histogramdd function. A histogram divides
| the space into bins, and returns the count of the number of points in
each bin. This function allows the computation of the sum, mean, median,
or other statistic of the values within each bin.
.. versionadded:: 0.11.0
Parameters
----------
sample : array_like
Data to hist... |
talha81/TACTIC-DEV | src/pyasm/search/sql_dumper.py | Python | epl-1.0 | 18,207 | 0.008184 | ###########################################################
#
# Copyright (c) 2005, 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 permi... | e:
size = 256
if is_nullable:
f.write("table.add('%s',%s'%s', length='%s' )\n" % (column, space, data_type, size))
else:
f.write("table.add('%s',%s'%s', length='%s', not_null=True )\n" % (column, space, data_type, size))
... | else:
f.write("table.add('%s',%s'%s', not_null=True )\n" % (column, space, data_type))
# add the constraints
constraints = impl.get_constraints(db_resource, table)
for constraint in constraints:
name = constraint.get("name")
columns = constraint.get("co... |
pdubroy/kurt | build/MacOS/PyInstaller/pyinstaller-svn-r812/hooks/hook-carchive.py | Python | gpl-2.0 | 1,029 | 0.002915 | # Copyright (C) 2005, Giovanni Bajo
# Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the... | Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
import sys
def hook(mod):
if sys.version[0] > '1':
for i in range(len(mod.imports)-1, -1, -1):
if mod.imports[i][0] == 'strop | ':
del mod.imports[i]
return mod
|
btxgit/gazee | gazee/config.py | Python | gpl-3.0 | 9,088 | 0.002311 | # .oooooooo .oooo. oooooooo .ooooo. .ooooo.
# 888' `88b `P )88b d'""7d8P d88' `88b d88' `88b
# 888 888 .oP"888 .d8P' 888ooo888 888ooo888
# `88bod8P' d8( 888 .d8P' .P 888 .o 888 .o
# `8oooooo. `Y888""8o d8888888P `Y8bod8P' `Y8bod8P'
# d" YD
# "Y88888P'
#
# config class - btx
#
i... | try:
os.makedirs(self.datapath)
except PermissionError:
print("You don't have the permissions | to create that path.\nExiting.")
sys.exit(1)
else:
print("Exiting.")
sys.exit(1)
firstdir = dirfound = self.datapath
cfile = os.path.join(dirfound, "app.ini")
if os.path.exists(cfile):
cf... |
kennym/itools | xapian/catalog.py | Python | gpl-3.0 | 14,778 | 0.002369 | # -*- coding: UTF-8 -*-
# Copyright (C) 2008 David Versmisse <david.versmisse@itaapy.com>
# Copyright (C) 2008 Juan David Ibáñez Palomar <jdavid@itaapy.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... | #######################################
def index_document(self, document):
"""Add a new document.
" | ""
db = self._db
metadata = self._metadata
fields = self._fields
# Check the input
if type(document) is dict:
doc_values = document
elif isinstance(document, CatalogAware):
doc_values = document.get_catalog_values()
else:
raise... |
noironetworks/neutron | neutron/db/migration/alembic_migrations/versions/mitaka/expand/32e5974ada25_add_neutron_resources_table.py | Python | apache-2.0 | 1,390 | 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
# ... | rt sqlalchemy as sa
"""Add standard attribute table
Revision ID: 32e5974ada25
Revises: 13cfb89f881a
Create Date: 2015-09-10 00:22:47.618593
"""
# revision identifiers, used by Alembic.
revision = '32e | 5974ada25'
down_revision = '13cfb89f881a'
TABLES = ('ports', 'networks', 'subnets', 'subnetpools', 'securitygroups',
'floatingips', 'routers', 'securitygrouprules')
def upgrade():
op.create_table(
'standardattributes',
sa.Column('id', sa.BigInteger(), autoincrement=True),
sa.Co... |
FlowFX/unkenmathe.de | src/um/exercises/migrations/0022_auto_20171004_0954.py | Python | agpl-3.0 | 483 | 0 | # -*- coding: utf-8 -*-
# Generated by Djang | o 1.11.5 on 2017-10-04 09:54
from __future__ import unicode_literals
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
dependencies = [
('exercises', '0021_auto_20171004_0954'),
]
operations = [
migrations.AlterField(
model_name='exe... | eld(default=uuid.uuid4, unique=True),
),
]
|
lsk112233/Clone-test-repo | pages/tests/test_views.py | Python | apache-2.0 | 1,280 | 0 | from .base import BasePageTests
from django.contrib.sites.models import Site
from django.contrib.redirects.models import Redirect
class PageViewTests(BasePageTests):
def test_page_view(self):
r = self.client.get('/one/')
self.assertEqual(r.context['page'], self.p1)
# drafts are available... | .cont | ext['page'], self.p1)
def test_redirect(self):
"""
Check that redirects still have priority over pages.
"""
redirect = Redirect.objects.create(
old_path='/%s/' % self.p1.path,
new_path='http://redirected.example.com',
site=Site.objects.get_current... |
geobricks/pgeo | pgeo/error/custom_exceptions.py | Python | gpl-2.0 | 1,045 | 0.000957 | class PGeoException(Exception):
status_code = 400
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self, message)
self.message = message
if status_code is not None:
self.status_code = status_code
self.payload = payload
def t | o_dict(self):
rv = dict(self.payload or ())
rv['message'] = self.message
rv['status_code'] = self.status_code
return rv
def get_message(self):
return self.message
def get_status_code(self):
return self.status_code
errors = {
510: 'Error fetching available ... | not currently supported.',
513: 'Error while parsing the payload of the request.',
# geoserver
520: "There is already a store named",
521: "No coverage store named",
522: "Layer file doesn't exists",
523: "Error creating workspace",
# Data processing
550: "Error processing data",
} |
wolverineav/neutron | neutron/agent/linux/ovsdb_monitor.py | Python | apache-2.0 | 4,444 | 0 | # Copyright 2013 Red Hat, 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 agre... | _events(self):
devices_added = []
devices_removed = []
dev_to_ofport = {}
for row in self.iter_stdout():
json = jsonutils.loads(row).get('data')
for ovs_id, action, name, ofport, external_ids in json:
if ex | ternal_ids:
external_ids = ovsdb.val_to_py(external_ids)
if ofport:
ofport = ovsdb.val_to_py(ofport)
device = {'name': name,
'ofport': ofport,
'external_ids': external_ids}
if acti... |
danrg/RGT-tool | src/RGT/XML/SVG/Filters/baseComponentTransferNode.py | Python | mit | 502 | 0.011952 | from RGT.XML.SVG.basicSvgNode import BasicSvgNode
from RGT.XML.SVG.Attribs.transferFunctionElementAttributes import TransferFunctionElementAttributes
class BaseComponentTransferNode(BasicSvgNode, TransferFunctionElementAttributes):
def __init__(self, ownerDoc, tagName):
BasicSvgNode.__init__(self, o... | tionElementAttributes.__init__(self)
self._allowedSvgChildNodes.update({self.SV | G_ANIMATE_NODE, self.SVG_SET_NODE})
|
gabrielStanovsky/props | props/graph_representation/node.py | Python | mit | 18,324 | 0.016809 | from props.graph_representation.word import Word,NO_INDEX, strip_punctuations
import cgi
from copy import deepcopy
from props.dependency_tree.definitions import time_prep, definite_label,\
adjectival_mod_dependencies
COPULA = "SAME AS" # the textual value of a copula node
PROP = "PROP" # t... | Node.copy(self)
ret.parent_relation = self.parent_relation
if hasattr(self, 'str'):
ret.str = self.str
return ret
def is_re | lative(self):
if "relative" not in self.features:
return False
return self.features["relative"]
def is_prenominal(self):
# TODO: this should be a property of the edge and not the node
return (self.parent_relation == "amod")
def get_text(self,gr):
... |
jpwilliams/appenlight-client-python | appenlight_client/ext/logging/logbook.py | Python | bsd-3-clause | 3,050 | 0.000328 | from __future__ import absolute_import
import logbook
import logging
import threading
import datetime
import time
from appenlight_client.ext.logging import EXCLUDED_LOG_VARS
from appenlight_client.timing import get_local_storage
from appenlight_client.utils import asbool, parse_tag, PY3
log = logging.getLogger(__name... | rd):
appenlight_storage = get_local_storage()
r_dict = convert_record_to | _dict(record, self.ae_client_config)
if r_dict:
if r_dict not in appenlight_storage.logs:
appenlight_storage.logs.append(r_dict)
def get_records(self, thread=None):
"""
Returns a list of records for the current thread.
"""
appenlight_storage = get... |
invisiblek/python-for-android | python3-alpha/python3-src/Lib/test/test_httplib.py | Python | apache-2.0 | 24,526 | 0.000775 | import errno
from http import client
import io
import os
import array
import socket
import unittest
TestCase = unittest.TestCase
from test import support
here = os.path.dirname(__file__)
# Self-signed cert file for 'localhost'
CERT_localhost = os.path.join(here, 'keycert.pem')
# Self-signed cert file for 'fakehostna... | ult host header on | IPv6 transaction should wrapped by [] if
# its actual IPv6 address
expected = b'GET /foo HTTP/1.1\r\nHost: [2001::]:81\r\n' \
b'Accept-Encoding: identity\r\n\r\n'
conn = client.HTTPConnection('[2001::]:81')
sock = FakeSocket('')
conn.sock = sock
conn.re... |
adam-urbanczyk/freecad-pluginloader | InitGui.py | Python | lgpl-3.0 | 13,949 | 0.043659 | #***************************************************************************
#* *
#* Copyright (c) 2015 microelly <microelly2@freecadbuch.de> *
#* *
#* Th... | 0px;padding:0px;}\
QPushButton { margin-right:0px;margin-left:0px;margin:0 px;padding:0px;;\
background-color: lightblue;text-align:left;;padding:6px;padding-left:4px;color:brown; }")
self.mygroupbox=mygroupbox
myform = QtGui.QFormLayout()
self.myform=myform
self.myform.setSpacing(0)
mygroupb... | n00 = QtGui.QPushButton(QtGui.QIcon('icons:freecad.svg'),"Plugin Manager Version " + __version__)
self.pushButton01 = QtGui.QPushButton(QtGui.QIcon(FreeCAD.ConfigGet('AppHomePath')+'/Mod/mylib/icons/mars.png'),"Plugin Loader" )
self.pushButton01.clicked.connect(self.start)
layout.addWidget(self.pushButt... |
yehnan/python_book_yehnan | ch10/package_example/formats/foo.py | Python | gpl-2.0 | 459 | 0.008715 |
import sys
sys.path.appen | d('/cygdrive/d/yehnan/wr_python_drmaster/python_book_yehnan/ch10')
# import package_example.formats.bar
# square = package_example.formats.bar.square
# from bar import square
from . import bar
square = bar.square
# from .bar import square
def sos(a, b):
return square(a) + square(b)
if _... | ('ok')
|
weichen2046/IntellijPluginDevDemo | enterprise-repo/enterprepo/pluginjar/migrations/0001_initial.py | Python | apache-2.0 | 1,243 | 0.002414 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-09-07 11:22
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migratio | ns.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('pluginrepo', '0005_plugin_vendor'),
]
operations = [
migrations.CreateModel(
| name='PluginVersionedFile',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('uploadTime', models.DateTimeField(auto_now_add=True)),
('version', models.CharField(max_length=100)),
... |
Azure/azure-sdk-for-python | sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/_configuration.py | Python | mit | 2,963 | 0.004387 | # 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 ... | **kwargs # type: Any
):
# type: (...) -> None
self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs)
self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs)
self.proxy_policy = kwargs.get('proxy_policy') or p... | .ProxyPolicy(**kwargs)
self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs)
self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs)
self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs... |
Paebbels/pyAttribute | doc/conf.py | Python | apache-2.0 | 5,614 | 0.011578 | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... | phinx.ext.ifconfig',
'sphinx.ext.viewcode',
# SphinxContrib extensions
# BuildTheDocs extensions
# 'btd.sphinx.autoprogram',
# 'btd.sphinx.graphviz',
# 'btd.sphinx.inheritance_diagram',
# Other extensions
# 'DocumentMember',
'sphin | x_fontawesome',
'sphinx_autodoc_typehints',
# local extensions
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also ... |
h4wldev/Frest | app.py | Python | mit | 1,064 | 0.00188 | # -*- coding: utf-8 -*-
"""
frest - flask restful api frame
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This project is the frame of the restful api server created with flask.
:copyright: (C) 2017 h4wldev@gmail.com
:license: MIT, see LICENSE for more details.
"""
import os
from flask_script import Server, Ma... | import APP_DEFAULT_PORT, APP_SECRET_KEY, ENVIRONMENT
from app.modules.auth import login, token
if __name__ == '__main__':
port = int(os.environ.get | ('PORT', APP_DEFAULT_PORT))
app.secret_key = APP_SECRET_KEY
db.create_all()
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
if ENVIRONMENT == 'production' or ENVIRONMENT == 'testing':
manager.add_command('runserver', Server(host='0.0.0.0',... |
lpakula/django-oscar-paypal | paypal/payflow/facade.py | Python | bsd-3-clause | 6,767 | 0.000887 | """
Bridging module between Oscar and the gateway module (which is Oscar agnostic)
"""
from oscar.apps.payment import exceptions
from paypal.payflow import codes, gateway, models
def authorize(order_number, amt, bankcard, billing_address=None):
"""
Make an *authorisation* request
This holds the money on... |
def referenced_sale(order_number, pnref, amt):
"""
Capture funds using the bank/address details of a previous transaction
This is equivalent to a *sale* transaction but without the user having to
enter their payment details.
There are two main uses for this:
1. This allows custo | mers to checkout without having to re-enter their
payment details.
2. It allows an initial authorisation to be settled in multiple parts. The
first settle should use delayed_capture but any subsequent ones should
use this method.
:order_number: Order number.
:pnref: PNREF of a previo... |
sbfnk/epiwork-website | apps/survey/migrations/0006_auto__add_field_surveyuser_oneuser.py | Python | agpl-3.0 | 12,365 | 0.007845 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'SurveyUser.oneuser'
db.add_column('survey_surveyuser', 'oneuser', self.gf('django.db.model... | odels.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
| 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical':... |
MarcoLemmens/sporttotaal | app.py | Python | apache-2.0 | 5,918 | 0.009125 | #!/usr/bin/env python
from __future__ import print_function
from future.standard_library import install_aliases
install_aliases()
from urllib.parse import urlparse, urlencode
from urllib.request import urlopen, Request
from urllib.error import HTTPError
import json
import os
from flask import Flask
from flask impor... | e": "apiai-weather-webhook-sample"
}
else:
return {}
def makeYqlQuery(req):
result = req.get("result")
parameters = result.get("parameters")
city = parameters.get("geo-city")
| if city is None:
return None
return "select * from weather.forecast where woeid in (select woeid from geo.places(1) where text='" + city + "')"
def makeWebhookResult(data):
query = data.get('query')
if query is None:
return {}
result = query.get('results')
if result is None:
... |
blizzz/pyocclient | owncloud/test/test.py | Python | mit | 48,130 | 0.002757 | # -*- coding: utf-8 -*-
# vim: expandtab shiftwidth=4 softtabstop=4
#
import unittest
from unittest_data_provider import data_provider
import os
import shutil
import owncloud
import datetime
import time
import tempfile
import random
import six
from config import Config
def getSupportedDavVersion():
# connect just... | /in dir.txt', ''))
listing = self.client.list(self.test_root)
self.assertEquals(len(listing), 5)
self.assertEquals(listing[0].get_name(), 'abc.txt')
self.assertEquals(listing[1].get_name(), 'file one.txt')
self.assertEquals(listing[2].get_name(), 'subdir | ')
self.assertEquals(listing[3].get_name(), 'zz+z.txt')
self.assertEquals(listing[4].get_name(), u'中文.txt')
self.assertTrue(listing[2].is_dir())
self.assertFalse(listing[3].is_dir())
listing = self.client.list(self.test_root, depth="infinity")
self.assertEquals(len(list... |
tkralphs/Dip | Dip/src/dippy/examples/wedding/wedding.py | Python | epl-1.0 | 5,083 | 0.012788 | """
A formulation in original variables of a wedding seating problem
Authors: Stuart Mitchell 2010
"""
import pulp
try:
import path
except ImportError:
pass
try:
import src.dippy as dippy
from src.dippy import DipSolStatOptimal
ex | cept ImportError:
import coinor.dippy as dippy
from coinor.dippy import DipSolStatOptimal
debug_print = False
max_tables = 5
max_table_size = 4
guests = 'A B C D E F G I J K L M N O P Q R'.split()
def happiness(guest_a, guest_b):
"""
Return the happiness (0 is the best) of al | locating two
guests together in the same table
"""
return abs(ord(guest_a) - ord(guest_b))
#create the set of possible tables
tables = range(max_tables)
possible_seatings = [(g, t) for g in guests
for t in tables]
#create a binary variable to model if a guest sits a... |
LSmit202/Mal-Py | tests/test_cycleanalyzer.py | Python | bsd-3-clause | 1,162 | 0 | # coding=utf-8
"""
malpy.cycleanalyzer.CycleAnalyzer Tests
"""
from __future__ import print_function
from nose.tools import assert_equal
import malpy.cycleanalyzer
import malpy.parser
PARSER = malpy.parser.Parser()
RUNNER = malpy.cycleanalyzer.CycleAnalyzer()
class TestMalCycleAnalyzer(object):
"""Tests the pa... | lass for consistency in the public facing API.
"""
def test_reset(self):
"""validate reset works properly.
Returns: None
"""
test_program = PARSER.parse("MOVEI V63, R0\nEND\n")
RUNNER.run(test_program, [0] * 64)
assert_equal(RUNNER.registers[0], 63)
... | (RUNNER.curr_state, valc)
assert_equal(RUNNER.states, dict([]))
def test_run(self):
"""validate runner works proper with Cycle checking JIT actions
Returns: None
"""
loop_instr = PARSER.parse("BR L1\nBR L0\nEND\n")
mem = RUNNER.run(loop_instr, [0]*64)
a... |
RYLF/pythontip | 33.py | Python | gpl-3.0 | 479 | 0.02864 | # coding=utf-8
# Title | :大幂次运算
# 给你两个正整数a(0 < a < 100000)和n(0 <= n <=100000000000),计算(a^n) % 20132013并输出结果
import math
# Test
a,n =100 | 00,10000000
# Answer
ret = 1 #余数
def PowerMod(a, n, ret):
if n == 0:
return ret
if n % 2: # n为奇数
ret = ret * a % 20132013
return PowerMod(a*a%20132013, n/2, ret) #n为偶数。a^n %m = (a^2^n/2)%m = ((a^2%m)^n/2)%m
print PowerMod(a, n, ret) |
FabienPean/sofa | applications/plugins/Flexible/examples/IO/saveSimu.py | Python | lgpl-2.1 | 4,119 | 0.028648 | #!/usr/bin/python
import Sofa
import Flexible.IO
import sys,os
datadir=os.path.dirname(os.path.realpath(__file__))+"/data/"
nbFrames = 10
nbGaussPoints = 1
file_Dof= datadir + "dofs.py"
file_SF= datadir + "SF.py"
file_GP= datadir + "GP.py"
# scene creation method
def createScene(rootNode):
rootNode.createObject('... | MechanicalObject', templa | te="F332")
bnode.createObject('LinearMapping', template="Affine,F332")
Enode = bnode.createChild('E')
Enode.createObject('MechanicalObject', template="E332" )
Enode.createObject('GreenStrainMapping', template="F332,E332" )
Enode.createObject('HookeForceField', template="E332", youngModulus="2000.0" ,poissonRa... |
OliverCole/ZeroNet | src/lib/merkletools/__init__.py | Python | gpl-2.0 | 4,984 | 0.001404 | import hashlib
import binascii
class MerkleTools(object):
def __init__(self, hash_type="sha256"):
hash_type = hash_type.lower()
if hash_type == 'sha256':
self.hash_function = hashlib.sha256
elif hash_type == 'md5':
self.hash_function = hashlib.md5
elif hash_t... | {} nor supported'.format(hash_type))
self.reset_tree()
def _to_hex(self, x):
try: # python3
return x.hex()
except: # python2
return binascii.hexlify(x)
def reset_tree(self) | :
self.leaves = list()
self.levels = None
self.is_ready = False
def add_leaf(self, values, do_hash=False):
self.is_ready = False
# check if single leaf
if isinstance(values, tuple) or isinstance(values, list):
for v in values:
if do_hash:
... |
vane/django_tornado | django_tornado/wsgi.py | Python | bsd-3-clause | 403 | 0.002481 | """
WSGI config for django_tornado project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangopr | oject.com/en/1.6/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_tornado.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_appli | cation()
|
veerendra2/python-scripts | code_snippets/python/yaml_read-write.py | Python | gpl-3.0 | 533 | 0.001876 | #!/usr/bin/env python
"""
Author : Veerendra Kakumanu
Description : Simple yaml file | reader and writer
"""
import os
import yaml
import io
def read_yaml(file_name):
if not os.path.exists(file_name):
print "{} not found! Please check.".format(file_name)
exit(1)
with open(file_name) as f:
data = yaml.load(f)
return data
def write_yaml(data, yaml_file):
with io... | tf8') as outfile:
yaml.dump(data, outfile, default_flow_style=False, allow_unicode=True) |
blite/python-curl | tests/test_multi_socket.py | Python | lgpl-2.1 | 1,924 | 0.007277 | #! /usr/bin/env python
# -*- coding: iso-8859-1 -*-
# vi:ts=4:et
# $Id: test_multi_socket.py,v 1.1 2006/11/10 15:03:05 kjetilja Exp $
import os, sys
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
import pycurl
urls = (
"http://curl.haxx.se",
"http://www.python.o... | a progress bar, etc.)
m.select(1.0)
# close handles
for c in m.handles:
# save info in standard Python attributes
c.http_code = c.getinfo(c.HTTP_CODE)
# pycurl API calls
m.remove_handle(c)
| c.close()
m.close()
# print result
for c in m.handles:
data = c.body.getvalue()
if 0:
print "**********", c.url, "**********"
print data
else:
print "%-53s http_code %3d, %6d bytes" % (c.url, c.http_code, len(data))
|
cassandra-dataset-manager/cdm | tests/sample/install.py | Python | apache-2.0 | 165 | 0.012121 | from cdm.installer import Installer, SimpleC | QLSchema
class SampleInstaller(SimpleCQLSchema, Installer):
def install_cassandra(self):
c = self.contex | t
|
JohnGriffiths/nipype | nipype/interfaces/camino/tests/test_auto_FSL2Scheme.py | Python | bsd-3-clause | 1,562 | 0.028169 | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from nipype.testing import assert_equal
from nipype.interfaces.camino.convert import FSL2Scheme
def test_FSL2Scheme_inputs():
input_map = dict(args=dict(argstr='%s',
),
bscale=dict(argstr='-bscale %d',
units='NA',
),
bval_file=dict(argstr='-... | environ=dict(nohash=True,
usedefault=True,
),
flipx=dict(argstr='-flipx',
),
flipy=dict(argstr='-flipy',
),
flipz=dict(argstr='-flipz',
),
ignore_exception=dict(nohash=True,
usedefault=True,
),
interleave=dict(argstr='-interleave',
),
numscans=dict(argstr='-numsc... | ict(nohash=True,
),
usegradmod=dict(argstr='-usegradmod',
),
)
inputs = FSL2Scheme.input_spec()
for key, metadata in input_map.items():
for metakey, value in metadata.items():
yield assert_equal, getattr(inputs.traits()[key], metakey), value
def test_FSL2Scheme_outputs():
... |
Venturi/cms | env/lib/python2.7/site-packages/aldryn_people/south_migrations/0018_auto__chg_field_persontranslation_description.py | Python | gpl-2.0 | 15,148 | 0.007856 | # -*- 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):
# Changing field 'PersonTranslation.description'
db.alter_column(u'aldry... | models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': '... | 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('d... |
jolyonb/edx-platform | lms/djangoapps/ccx/tests/test_models.py | Python | agpl-3.0 | 7,054 | 0.000284 | """
tests for the models
"""
import json
from datetime import datetime, timedelta
import ddt
from pytz import utc
from student.roles import CourseCcxCoachRole
from student.tests.factories import AdminFactory
from xmodule.modulestore.tests.django_utils import TEST_DATA_SPLIT_MODULESTORE, ModuleStoreTestCase
from xmodu... | one)
def test_structure_json(self):
"""
Test a json stored in the structure_json
"""
dummy_struct = [
"block-v1:Organization+CN101+CR-FALL15+type | @chapter+block@Unit_4",
"block-v1:Organization+CN101+CR-FALL15+type@chapter+block@Unit_5",
"block-v1:Organization+CN101+CR-FALL15+type@chapter+block@Unit_11"
]
json_struct = json.dumps(dummy_struct)
ccx = CcxFactory(
course_id=self.course.id,
coach... |
SINGROUP/pycp2k | pycp2k/classes/_each52.py | Python | lgpl-3.0 | 1,113 | 0.001797 | from pycp2k.inputsection import InputSection
class _each52(InputSection):
d | ef __init__(self):
InputSection.__init__(self)
self.Just_energy = None
self.Powell_opt = None
sel | f.Qs_scf = None
self.Xas_scf = None
self.Md = None
self.Pint = None
self.Metadynamics = None
self.Geo_opt = None
self.Rot_opt = None
self.Cell_opt = None
self.Band = None
self.Ep_lin_solver = None
self.Spline_find_coeffs = None
self... |
v-iam/azure-sdk-for-python | azure-mgmt-resource/azure/mgmt/resource/resources/v2016_02_01/models/deployment_properties.py | Python | mit | 2,606 | 0.000384 | # 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 ... | self.template_link = template_link
self.paramete | rs = parameters
self.parameters_link = parameters_link
self.mode = mode
self.debug_setting = debug_setting
|
Lukc/ospace-lukc | client-pygame/lib/osci/dialog/EmpireOverviewDlg.py | Python | gpl-2.0 | 10,358 | 0.031956 | #
# Copyright 2001 - 2006 Ludek Smid [http://www.ospace.net/]
#
# This file is part of IGE - Outer Space.
#
# IGE - Outer Space 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 Lice... | ), player.prodIncreasePool, min(ratio * 100, math.sqrt(ratio) * 100), _("effectivity")
))
# fleet support
total = getattr(player.stats, 'fleetSupportProd', 0) + player.fleetUpgradePool * Rules.operProdRatio
if total > player | .stats.prodProd / 10:
effectivity = - 100 * (total - player.stats.prodProd / 10) / max(player.stats.prodProd, 1)
else:
effectivity = 0
text.append(u' %s: %+d (%s %d %s, %+d %% %s)' % (
_("Fleet support"),
- total,
_("first"),
player.stats.prodProd / 10,
_("CP is free"),
effectivity,
_(... |
adamginsburg/APEX_CMZ_H2CO | observing/noise_stats.py | Python | bsd-3-clause | 2,860 | 0.005594 | from paths import rpath,mpath,opath
from make_apex_cubes import all_apexfiles,get_source_tel_line,_is_sci, hdr_to_freq
from pyspeckit.spectrum.readers import read_class
from astropy.table import Table
from astropy import log
from astropy.utils.console import ProgressBar
import numpy as np
import os
import pylab as pl
... | for sp,h in ProgressBar(spdheader)])
tbl = Table([datadict[apex_filename][t][ii]
for t in telescopes
for ii in (0,1)],
names=[t+"_"+s
for t in telescopes
... | for t in telescopes
for s in ('STDDEV','TSYS',)
])
log.info(os.path.basename(apex_filename)+"_tsys.fits")
tbl.write(os.path.basename(apex_filename)+"_tsys.fits", overwrite=True)
tbldict[apex_filename] = tbl
if ... |
dstl/lighthouse | apps/api/views.py | Python | mit | 3,467 | 0.000288 | # (c) Crown Owned Copyright, 2016. Dstl.
import os
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.urlresolvers import reverse
from django.http import JsonResponse
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt... | def dispatch(self, request, *args, **kwargs):
return super(APIBase, self).dispatch(request, *args, **kwargs)
class APIDocView(StaticPageViewBase):
template_name = 'api | /documentation.html'
def get_markdown_directory(self):
return os.path.join(
settings.BASE_DIR,
'apps',
'api',
'documentation',
)
class APIHome(APIDocView):
slug = 'index'
class APIDocHomeRedirect(RedirectView):
permanent = True
def ge... |
valesi/electrum | gui/kivy/uix/dialogs/create_restore.py | Python | gpl-3.0 | 11,183 | 0.000626 | ''' Dialogs and widgets Responsible for creation, restoration of accounts are
defined here.
Namely: CreateAccountDialog, CreateRestoreDialog, RestoreSeedDialog
'''
from functools import partial
from kivy.app import App
from kivy.clock import Clock
from kivy.lang import Builder
from kivy.properties import ObjectPrope... | nt: 1, None
height: self.minimum_height
| WizardButton:
id: back
text: _('Back')
root: root
Button:
id: scan
text: _('QR')
on_release: root.scan_seed()
WizardButton:
id: next
text: _('Next')
root: root
<ShowSeedDialog>
spacin... |
anushbmx/kitsune | kitsune/users/models.py | Python | bsd-3-clause | 24,753 | 0.000525 | import hashlib
import logging
import random
import re
import time
from datetime import datetime, timedelta
from django.conf import settings
from django.contrib.auth.models import User, Group
from django.contrib.sites.models import Site
from django.db import models
from django.utils.translation import ugettext as _, ug... | pass
# Latest Support Forum answer:
try:
answer = Answer.objects.filter(
creator=self.user).latest('created')
dates.append(answer.created)
except Answer.DoesNotExist:
pass
# Latest KB Revision edited:
try:
| revision = Revision.objects.filter(
creator=self.user).latest('created')
dates.append(revision.created)
except Revision.DoesNotExist:
pass
# Latest KB Revision reviewed:
try:
revision = Revision.objects.filter(
reviewer=self... |
tejal29/pants | src/python/pants/backend/codegen/tasks/jaxb_gen.py | Python | apache-2.0 | 6,748 | 0.008447 | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
import re
... | = target.package
if output_package is None:
output_package = self._guess_package(source)
output_package = self._correct_package(output_package)
output_directory = output_dir
safe_mkdir(output_directory)
args = ['-p', output_package, '-d', output_directory, path_to_xs... | ({code})'.format(code=result))
target_files.append(self._sources_to_be_generated(target.package, path_to_xsd))
cache.append((target, target_files))
return cache
def genlangs(self):
return {'java': lambda t: t.is_jvm}
def createtarget(self, lang, gentarget, dependees):
predicates = self.... |
jmacarthur/2dgames | microhack/tilereader.py | Python | mit | 2,912 | 0.016827 | import xml.etree.ElementTree as ET
TILELAYER = "world"
OBJECTLAYER = "objects"
TILESIZE = 32
actionMap = { "pub": 1, "exit": 2, "magicshop": 3 }
def processTileLayer(layer):
mapData = []
for e in layer:
if(e.tag=="data"):
if(e.attrib['encoding'] != "csv"):
print "Tile data ... | processAction(links, e, props)
else:
for | p in e:
if(p.tag == "polyline"):
addPolyLine(links,e,p,props)
return (links,objects)
def readMap(filename):
tree = ET.parse(filename)
root = tree.getroot()
for child in root:
if(child.tag=="layer"):
if(child.attrib['name']==TILELAYER):
... |
xavierdutreilh/djangoproject.com | releases/models.py | Python | bsd-3-clause | 9,309 | 0.000859 | import datetime
from distutils.version import LooseVersion
from django.conf import settings
from django.core.cache import cache
from django.db import models
from django.utils.functional import cached_property
from django.utils.version import get_complete_version, get_major_version
# A version of django.utils.version... |
(type(self).objects
.filter(major=self.major, minor=self.minor,
micro=self.micro - 1, status='f')
.update(eol_date=self.date))
def __str__(self):
return self.version
@cached_prope | rty
def version_tuple(self):
"""Return a tuple in the format of django.VERSION."""
version = self.version.replace('-', '').replace('_', '')
version = LooseVersion(version).version
if len(version) == 2:
version.append(0)
if not isinstance(version[2], int):
... |
khaleeque-ansari/Online-Coding- | ProjectEulerCode/prob2.py | Python | apache-2.0 | 188 | 0.026596 | sum =0
num1 = 1
num2 = 2 |
num3 = 3
while( num2 <= 4000000):
sum = sum + num2
num1 = num2 + num3
num2 = num3 + num1
num3 = num1 + num2
|
print sum,
|
dyule/RandomBytes | ProgAsArt/interactive.py | Python | gpl-3.0 | 662 | 0.013595 | '''
Interactive graphics setup.
Just load this file into IDLE, run it (F5 on Windows), and access the Python console.
'''
# Import the graphics library so that y | ou may use its object in the console.
from graphics import *
win = GraphWin('This is awesome', 500, 500)
win.setBackground('blue')
poly = Circle( Point(250, 250), 175)
poly.setFill( 'orange' )
poly.draw(wi | n)
mytext = Text( Point(250, 250), "Hello world")
mytext.setFill('black')
mytext.setSize(30)
mytext.draw(win)
for i in range(10):
mypoint = win.getMouse()
newcircle = Circle( mypoint, 25)
newcircle.setFill('red')
newcircle.draw(win)
win.getMouse()
win.close()
|
ric2b/Vivaldi-browser | chromium/chrome/test/chromedriver/test/test_environment.py | Python | bsd-3-clause | 3,855 | 0.008042 | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""TestEnvironment classes.
These classes abstract away the various setups needed to run the WebDriver java
tests in various environments.
"""
from __futur... | avaTests(self):
"""Get the list of passed java tests.
Returns:
List of passed test names.
"""
with open(os.path.join(_THIS_DIR, 'java_tests.txt'), 'r') as f:
return _EXPECTATIO | NS['ApplyJavaTestFilter'](
self.GetOS(), [t.strip('\n') for t in f.readlines()])
class DesktopTestEnvironment(BaseTestEnvironment):
"""Manages the environment java tests require to run on Desktop."""
# override
def GetOS(self):
return util.GetPlatformName()
class AndroidTestEnvironment(DesktopT... |
initialed85/mac_os_scripts | mac_os_scripts/configure_ntp.py | Python | mit | 1,870 | 0.000535 | """
This script is responsible for enabling NTP and setting the NTP server
Commands used:
- systemsetup -setusingnetworktime on
- systemsetup -setnetworktimeserver (NTP server)
"""
from common import CLITieIn
class NTPConfigurator(CLITieIn):
def enable_ntp(self):
command = '/usr/sbin/systemsetup -set... | != 0:
self._logger.error(
'{0} failed stating {1}'.format(
command, command_output
| )
)
return False
return True
def run(self, server):
if not self.enable_ntp():
self._logger.error('failed enable_ntp; cannot continue')
return False
if not self.set_ntp_server(server):
self._logger.error('failed set_ntp_server;... |
rjdp/cement | tests/core/extension_tests.py | Python | bsd-3-clause | 1,546 | 0 | """Tests for cement.core.extension."""
from cement.core import exc, backend, extension, handler, output, interface
from cement.utils import test
class IBogus(interface.Interface):
class IMeta:
| label = 'bogus'
class BogusExtensionHandler(extension.CementExtensionHandler):
class Meta:
interface = IBogus
label = 'bogus'
class ExtensionTestCase(test.CementCoreTestCase):
@test.raises(exc.FrameworkError)
def test_invalid_extension_handler(self):
# the handler type bog... | ext._setup(self.app)
ext.load_extensions(['cement.ext.ext_configparser'])
def test_load_extensions_again(self):
ext = extension.CementExtensionHandler()
ext._setup(self.app)
ext.load_extensions(['cement.ext.ext_configparser'])
ext.load_extensions(['cement.ext.ext_con... |
git-keeper/git-keeper | tests/acceptance/gkserver_base/mysmtpd.py | Python | agpl-3.0 | 3,257 | 0.000614 | #!/usr/bin/python3
# Copyright 2016 Nathan Sommer and Ben Coleman
#
# This program is free software: you can r | edistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# t | he Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public... |
jiajiax/crosswalk-test-suite | tools/atip/atip/web/web.py | Python | bsd-3-clause | 29,871 | 0.00087 | # Copyright (c) 2014 Intel Corporation.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of works must retain the original copyright notice, this list
# of conditions and the following disclaimer.... | m selenium.common.exceptions import (
NoSuchElementException,
StaleElementReferenceException,
NoAlertPresentException,
WebDriverException)
from atip.tizen import tizen
from atip.common import common
try:
from urlparse import urljoin, urlparse
except ImportE | rror:
from urllib.parse import urljoin, urlparse
class WebAPP(common.APP):
def __init__(self, app_config=None, app_name=None,
apk_pkg_name=None, apk_activity_name=None):
self.driver = None
self.app_type = common.APP_TYPE_WEB
self.app_name = app_name
self.app_i... |
nibrahim/PFractL | PfractL.py | Python | gpl-2.0 | 14,705 | 0.022509 | #!/usr/bin/python
# Copyright (C) 2002 Noufal Ibrahim <noufal@cisco.com>
#
# This program is part of PfractL
#
# PfractL 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 (a... | self.y=HEIGHT-369
if (not self.fractal.has_key('ma | xlevel')):
logger("Fractal maximum level depth unspecified",MESG)
logger("Using default 6",MESG)
self.fractal["maxlevel"]=6
if (not self.fractal.has_key('sangle')):
logger("Fractal starting angle unspecified",MESG)
logger("Using default 0",MESG)
... |
rec/BiblioPixel | bibliopixel/colors/tables.py | Python | mit | 2,158 | 0.000463 | """
Tables of named colors
"""
import itertools, re
from . import juce, classic
def canonical_name(name):
return name.replace(' ', '').lower()
def to_triplet(color):
rg, b = color // 256, color % 256
r, g = rg // 256, rg % 256
return r, g, b
def set_user_colors(colors):
from . import names
... | iteration over all name, color pairs in tables"""
yield from _TO_COLOR_USER.items()
for name, color in _TO_COLOR.items():
if name not in _TO_COLOR_USER:
yield name, color
def contains(x):
"""Return true if this string or integer tuple appears in tables"""
if isinstance(x, str):
... | eturn x in _TO_COLOR_USER or x in _TO_COLOR
else:
x = tuple(x)
return x in _TO_NAME_USER or x in _TO_NAME
def _classic_pairs():
find = re.compile(r'[A-Z][a-z0-9]+').finditer
for name in dir(classic):
if name == 'Green_HTML':
yield 'green html', classic.Green_HTML
... |
kalrey/swift | test/unit/common/middleware/helpers.py | Python | apache-2.0 | 4,791 | 0 | # Copyright (c) 2013 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 ... | nses" % (
(method, path),))
return resp
def __call__(self, env, start_response):
method = env['REQUEST_METHOD']
path = env['PATH_INFO']
_, acc, cont, obj = split_path(env['PATH_INFO'], 0, 4,
| rest_with_last=True)
if env.get('QUERY_STRING'):
path += '?' + env['QUERY_STRING']
if 'swift.authorize' in env:
resp = env['swift.authorize']()
if resp:
return resp(env, start_response)
req_headers = swob.Request(env).headers
... |
lilydjwg/nvchecker | nvchecker_source/repology.py | Python | mit | 896 | 0.013393 | # MIT licensed
# Copyright (c) 2019 lilydjwg <lilydjwg@gmail.com>, et al.
from nvchecker.api import GetVersionError
API_URL = 'https://repology.org/api/v1/project/{}'
async def get_version(name, conf, *, cache, **kwargs):
project = conf.get('repology') or name
repo = conf.get('repo') |
subrepo = conf.get('subrepo')
if not repo:
raise GetVersionError('repo field is required for repology source')
url = API_URL.format(project)
data = await cache.get_json(url)
pkgs = [pkg for pkg in data if pkg['repo'] == repo]
if not pkgs:
raise GetVersionError('package is not found', repo=repo)
... | pkgs if pkg.get('subrepo') == subrepo]
if not pkgs:
raise GetVersionError('package is not found in subrepo',
repo=repo, subrepo=subrepo)
versions = [pkg['version'] for pkg in pkgs]
return versions
|
tvwenger/galfacts | make_plots.py | Python | mit | 4,077 | 0.011038 | """
make_plots.py
Generate plots for GALFACTS transient search. Cleans up other codes
by having these scripts separate.
04 June 2014 - Trey Wenger - Creation
06 June 2014 - Trey Wenger - Added functions for make_clusters
11 June 2014 - Joseph Kania - Editied
12 June 2014 - Trey Wenger - Allow for running on headless ma... | ,
filename):
"""Generate plot of 4 stokes parameters"""
fig, (ax1, ax2, ax3, ax4) = plt.subplots(4, sharex=True)
| ax1.plot(x_data,I_data)
ax1.set_xlim(np.nanmin(x_data),np.nanmax(x_data))
ax1.set_ylim(np.nanmin(I_data[I_data.nonzero()]),
np.nanmax(I_data))
ax1.set_ylabel("Stokes I (K)")
ax2.plot(x_data,Q_data)
ax2.set_ylim(np.nanmin(Q_data),np.nanmax(Q_data))
ax2.set_ylabel("Stokes Q (K)"... |
openwisp/netjsonconfig | netjsonconfig/backends/base/renderer.py | Python | gpl-3.0 | 1,401 | 0 | from jinja2 import Environmen | t, PackageLoader
class BaseRenderer(object):
"""
Base Renderer class
Renderers are used to generate a string
which represents the router configuration
"""
def __init__(self, backend):
self.config = backend.config
self.backend = b | ackend
@property
def env_path(self):
return self.__module__
@property
def template_env(self):
return Environment(
loader=PackageLoader(self.env_path, 'templates'), trim_blocks=True
)
@classmethod
def get_name(cls):
"""
Returns the name of th... |
LoginRadius/python-sdk | lib/LoginRadius/api/advanced/reauthentication_api.py | Python | mit | 15,654 | 0.008624 | # -- coding: utf-8 --
# Created by LoginRadius Development Team
# Copyright 2019 LoginRadius Inc. All rights reserved.
#
class ReAuthenticationApi:
def __init__(self, lr_object):
"""
:param lr_object: this is the reference to the parent LoginRadius object.
"""
self._lr_object = lr... | authentication token created by the MFA re-authentication API. This API checks re-authentications created by OTP.
Args:
event_based_multi_factor_token: Model Class containing Definition for SecondFactorValidationToken
uid: UID, the unified identifier for each user account
... | Response containing Definition of Complete Validation data
18.38
"""
if(event_based_multi_factor_token is None):
raise Exception(self._lr_object.get_validation_message("event_based_multi_factor_token"))
if(self._lr_object.is_null_or_whitespace(uid)):
rai... |
hillscottc/quest | questapp/urls.py | Python | gpl-2.0 | 484 | 0.004132 | from django | .conf.urls import patterns, url
from django.contrib import admin
import views
admin.autodiscover()
urlpatterns = patterns(
'',
url(r'^$', views.HomeView.as_view(), name="home"),
url(r'^clues/$', views.CluesView.as_view(), name="clues"),
url(r'^test$', views.TestView.as_view(), name="test"),
ur... | (), name="clues-by-cat"),
)
|
deanhiller/databus | webapp/play1.3.x/python/Lib/ftplib.py | Python | mpl-2.0 | 29,449 | 0.002988 | """An FTP client class and some helper functions.
Based on RFC 959: File Transfer Protocol (FTP), by J. Postel and J. Reynolds
Example:
>>> from ftplib import FTP
>>> ftp = FTP('ftp.python.org') # connect to host, default port
>>> ftp.login() # default, i.e.: user anonymous, passwd anonymous@
'230 Guest log... | xr-x 2 root wheel 1024 Jan 3 1994 bin
drwxr-xr-x 2 root wheel 1024 Jan 3 1994 etc
d-wxrwxr-x 2 ftp wheel 1024 Sep 5 13:43 incoming
drwxr-xr-x 2 root wheel 1024 Nov 17 1993 lib
drwxr-xr-x 6 1094 wheel 1024 Sep 13 19:07 pub |
drwxr-xr-x 3 root wheel 1024 Jan 3 1994 usr
-rw-r--r-- 1 root root 312 Aug 1 1994 welcome.msg
'226 Transfer complete.'
>>> ftp.quit()
'221 Goodbye.'
>>>
A nice test that reveals some of the network dialogue would be:
python ftplib.py -d localhost -l -p -l
"""
#
# Changes ... |
k00n/site_update_notifier | siteUpdateNotifier/sun/views.py | Python | mit | 141 | 0 | from | django.shortcuts import render
from django.views import View
class SiteUpdateNotifier(V | iew):
def get(self, request):
pass
|
jmesteve/saas3 | openerp/addons_extra/website_login/controller/__init__.py | Python | agpl-3.0 | 1,072 | 0.000933 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (c) 2013 ErpAndCloud All Rights Reserved
# h | ttps://github.com/jmesteve
# <engineering@erpandcloud.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 opti... | r 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 the GNU Gen... |
certik/sympy-oldcore | sympy/core/tests/test_eval_power.py | Python | bsd-3-clause | 1,302 | 0.019969 | from sympy.core import *
def test_rational():
a = Rational(1, 5)
assert a**Rational(1, 2) == a**Rational(1, 2)
assert 2 * a**Rational(1, 2) == 2 * a**Rational(1, 2)
assert a**Rational(3, 2) == a * a**Rational(1, 2)
assert 2 * a**Rational(3, 2) == 2*a * a**Rational(1, 2)
assert a**Rational(17... | a**Rational(2, 3)
assert 2 * a**Rational(17, 3) == 2*a**5 * a**Rational(2, 3)
def test_large_rational():
e = (Rational(123712**12-1,7)+Rational( | 1,7))**Rational(1,3)
assert e == 234232585392159195136 * (Rational(1,7)**Rational(1,3))
def test_negative_real():
def feq(a,b):
return abs(a - b) < 1E-10
assert feq(Basic.One() / Real(-0.5), -Integer(2))
def test_expand():
x = Symbol('x')
assert (2**(-1-x)).expand() == Rational(1,2)*2**(-... |
ltilve/ChromiumGStreamerBackend | tools/telemetry/third_party/webpagereplay/proxyshaper_test.py | Python | bsd-3-clause | 4,988 | 0.005012 | #!/usr/bin/env python
# Copyright 2012 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0 |
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
... | xyshaper
import StringIO
import unittest
# pylint: disable=bad-whitespace
VALID_RATES = (
# input, expected_bps
( '384Kbit/s', 384000),
('1536Kbit/s', 1536000),
( '1Mbit/s', 1000000),
( '5Mbit/s', 5000000),
( '2MByte/s', 16000000),
( '0', 0),
( '5... |
russiancow/stag | stag/base.py | Python | mit | 1,436 | 0.000696 | try:
from StringIO import StringIO
except ImportError:
from io import StringIO
from inspect import isgenerator
class Element(object):
tag = ''
self_closing = False
def __init__(self, *children, **attrs):
if children and isinstance(children[0], dict):
self.attrs = children[0]
... | closing tags can't have children.")
if children and isgenerator(children[0]):
children = children[0]
for child in children:
if child is not None:
if isinstance(child, list):
self.add_children(child)
else:
| self.children.append(child)
|
tbeadle/django | tests/custom_managers/models.py | Python | bsd-3-clause | 7,050 | 0.001702 | """
Giving models a custom manager
You can use a custom ``Manager`` in a particular model by extending the base
``Manager`` class and instantiating your custom ``Manager`` in your model.
There are two reasons you might want to customize a ``Manager``: to add extra
``Manager`` methods, and/or to modify the initial ``Q... | ')
favorite_thing_type = models.ForeignKey('contenttypes.ContentType', models.SET_NULL, null=True)
favorite_thing_id = models.IntegerField(null=True)
favorite_thing = GenericForeignKey('favorite_thing_type', 'favorite_thing_id')
objects = PersonManager()
fun_people = FunPeopleManager()
boring_p... | et_custom_manager = CustomManager('hello')
custom_init_queryset_manager = CustomInitQuerySet.as_manager()
def __str__(self):
return "%s %s" % (self.first_name, self.last_name)
@python_2_unicode_compatible
class FunPerson(models.Model):
first_name = models.CharField(max_length=30)
last_name = ... |
Stefan-Korner/SpacePyLibrary | Tutorial/Example_7.py | Python | mit | 2,134 | 0.007498 | #!/usr/bin/env python3
#******************************************************************************
# (C) 2019, Stefan Korner, Austria *
# *
# The Space Python Library is free software; you can redi... | CCSDS TM Frame object that wraps the binary data
tmFrame = CCSDS.FRAME.TMframe(binFrame)
# extract the TM Packets
leadingFragment, tmPackets, trailingFragment = tmFrame.getPackets()
LOG("leadingFragment = " + str(leadingFragment))
for i, tmPacket i | n enumerate(tmPackets):
LOG("tmPacket_" + str(i) + " = " + UTIL.DU.array2str(tmPacket))
LOG("trailingFragment = " + str(trailingFragment))
# close file
frameFile.close()
|
Fillll/reddit2telegram | reddit2telegram/channels/~inactive/mootivati0n/app.py | Python | mit | 142 | 0.007042 | #encoding:utf-8
subreddit = 'motivation'
t_channel = '@Mootivati0n'
def send_post(submi | ssion, | r2t):
return r2t.send_simple(submission)
|
sagiss/sardana | src/sardana/sardanamodulemanager.py | Python | lgpl-3.0 | 9,493 | 0.003266 | #!/usr/bin/env python
##############################################################################
##
## This file is part of Sardana
##
## http://www.sardana-controls.org/
##
## Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain
##
## Sardana is free software: you can redistribute it and/or modify
## it und... | _name in sys.modules:
module = sys.modules[module_name]
else:
module = self.loadModule(module_name, path)
excl = list(_MINIMUM_EXCLUDE)
if exclude is not None:
excl.extend(exclude)
import sardana.util.deepreload
with PathContext(path):
... | except:
self.error("Error deep reloading module %s", module_name)
self.debug("Details:", exc_info=1)
raise
def loadModule(self, module_name, path=None):
"""Loads the given module name. If the module has been already loaded
into this python interpreter... |
nemesiscodex/JukyOS-sugar | src/jarabe/desktop/favoriteslayout.py | Python | gpl-2.0 | 21,062 | 0.000475 | # Copyright (C) 2008 One Laptop Per Child
# Copyright (C) 2010 Sugar Labs
#
# 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 versi... | ng or spiral around the XO man."""
__gt | ype_name__ = 'RingLayout'
icon_name = 'view-radial'
"""Name of icon used in home view dropdown palette."""
key = 'ring-layout'
"""String used in profile to represent this view."""
# TRANS: label for the ring layout in the favorites view
palette_name = _('Ring')
"""String used to identify thi... |
aheba/ctp | parseur_noeuds.py | Python | mit | 14,972 | 0.01543 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2015 Mael Valais <mael.valais@univ-tlse3.fr>
#
# Distributed under terms of the MIT license.
#
# Pour lancer glpsol et générer en même temps le graphe.dot :
# python parseur_noeuds.py --dat noeuds.txt > data.dat && \
# glpsol -m ctp.mod -... | quoi j'utilise points_per_inch ?
# - les `pos="3,4"!` sont en points
# - les `width="0.1"` et `height | ="0.1"` sont en inch
# 72 correspond au nombre de "points" pour un "inch" dans .dot
# 1 inch * ratio_inch_point = points
points_per_inch = 72
normalisation = 300
# On veut que les pos=x,y se retrouvent dans l'espace [0,max]
x_max = max([p[1] for p in [noeud_depot]+noeuds_atteignables+noeuds... |
libretees/libreshop | libreshop/products/tests/models/.~c9_invoke_taooUl.py | Python | gpl-3.0 | 3,977 | 0.004526 | import logging
from django.test import TestCase
from ...models import Attribute
# Initialize logger.
logger = logging.getLogger(__name__)
# Create your tests here.
class AttributeValueModelTest(TestCase):
def test_model_has_inventory_field(self):
'''
Test that Attribute_Value.inventory is present... | attribute_value2 = Attribute_Value.objects.create(attribute=attribute2,
inventory=inventory, value='quux')
num_associated_attributes = (Attribute_Value.objects.
filter(inventory=inventory).count())
self.assertEqual(num_associated_attributes, 2)
def test_inventory_can... | iple similar Attributes cannot be associated to an
Inventory object.
'''
inventory = Inventory.objects.create(name='foo')
attribute = Attribute.objects.create(name='bar')
attribute_value = Attribute_Value.objects.create(attribute=attribute,
inventory=inventory, value=... |
r0n22/RemoteQTH-N1MM | RotatorSystem.py | Python | gpl-2.0 | 827 | 0.008464 | import socket
import xml.etree.ElementTree as ET
UDP_IP_Recieve = ''
UDP_PORT_Recieve = 12040
TCP_IP_Send = "127.0.0.1"
TCP_Por | t_Send = 91
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP_Recieve, UDP_PORT_Recieve))
print "Program Started:"
while True:
data, addr = sock.recvfrom(1024) # buffer size is 1024 byt | es
tree = ET.fromstring(data)
Heading = int(float(tree.find("goazi").text))
Heading = (Heading + 180) % 360
print "Beam Heading at "+ str(Heading) + " Degrees"
print "Packet Sent :AP1" + "{0:03d}".format(Heading) +";AM1;\r"
sendTCP = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sendTCP.... |
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/social/backends/twilio.py | Python | agpl-3.0 | 1,384 | 0 | """
Amazon auth backend, docs at:
http://psa.matiasaguirre.net/docs/backends/twilio.html
"""
from re import sub
from social.p3 import urlencode
f | rom social.backends.base import BaseAuth
class TwilioAuth(BaseAuth):
name = 'twilio'
ID_KEY = 'AccountSid'
def get_user_details(self, response):
"""Return twilio details, Twilio only provides AccountSID as
parameters."""
# / | complete/twilio/?AccountSid=ACc65ea16c9ebd4d4684edf814995b27e
return {'username': response['AccountSid'],
'email': '',
'fullname': '',
'first_name': '',
'last_name': ''}
def auth_url(self):
"""Return authorization redirect url."""
... |
dhocker/athomepowerlineserver | commands/delete_group_device.py | Python | gpl-3.0 | 1,253 | 0 | #
# Delete a device from a group
# Copyright © 2020 Dave Hocker
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# See the LICENSE file for more details.
#
from co... | tionGroupDevice(ServerCommand):
"""
Command handler for assigning a device to a group
"""
def Execute(self, request):
device_id = request["args"]["device-id"]
group_id = request["args"]["group-id"]
agd = ActionGroupDevices()
result = agd.delete_device(group_id, device_id... | er of devices deleted
if result >= 0:
r['result-code'] = 0
r['group-id'] = group_id
r['device_id'] = device_id
r['message'] = "Success"
else:
# Probably invalid device type
r['result-code'] = 1
r['error'] = 1
... |
mtb-za/fatiando | gallery/3-mesh/prism_model.py | Python | bsd-3-clause | 1,037 | 0 | """
Simple prism model
------------------
Create a simple geologic model using rectangular prisms
(:class:`fatiando.mesher.Prism`) and plot it in 3D with
:mod:`fatiando.vis.myv`.
"""
from fatiando.mesher import Prism
from fatiando.vis import myv
# Models in Fatiando are basically sequences of geometric elements from... | an have as many physical properti | es as you want.
# Here, we'll give the prisms a density and a magnetization vector.
model = [
Prism(-1500, -500, -1500, -500, 1000, 2000,
{'magnetization': [3, 5, 4], 'density': 500}),
Prism(500, 1500, 1000, 2000, 500, 1500,
{'magnetization': [10, 2, 1], 'density': -250})]
# Create a 3D fig... |
brong/brong-offlineimap | offlineimap/repository/IMAP.py | Python | gpl-2.0 | 10,516 | 0.003709 | # IMAP repository support
# Copyright (C) 2002 John Goerzen
# <jgoerzen@complete.org>
#
# 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... | t__(self, reposname, account):
"""Initialize an IMAPRepository object."""
BaseRepository.__init__(self, reposname, account)
self.imapserver = imapserver.ConfigedIMAPServer(self)
self.folders = None
self.nametrans = lambda foldername: fol | dername
self.folderfilter = lambda foldername: 1
self.folderincludes = []
self.foldersort = cmp
localeval = self.localeval
if self.config.has_option(self.getsection(), 'nametrans'):
self.nametrans = localeval.eval(self.getconf('nametrans'),
... |
boh1996/LectioAPI | importers/importTeamAccounting.py | Python | mit | 1,725 | 0.041739 | import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'scrapers'))
sys.path.append("..")
from datetime import datetime
from pymongo import MongoClient
from database import *
import error
import sync
import team_accounting as teamAccountingApi
def importTeamAccounting ( school_id, branch_id, team... | bjectList["error"])
return False
else:
error.log | (__file__, False, "Unknown error")
return False
except Exception, e:
error.log(__file__, False, str(e))
return False |
Distrotech/pygobject | demos/gtk-demo/demos/appwindow.py | Python | lgpl-2.1 | 13,729 | 0.00488 | #!/usr/bin/env python
# -*- Mode: Python; py-indent-offset: 4 -*-
# vim: tabstop=4 shiftwidth=4 expandtab
#
# Copyright (C) 2010 Red Hat, Inc., John (J5) Palmieri <johnp@redhat.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License a... | # is_active
)
(COLOR_RED,
COLOR_GREEN,
COLOR_BLUE) = range(3)
color_action_entries = (
("Red", None, # name, stock id
"_Red", "<control>R", # label, accelerator
"Blood", COLOR_RED), # tooltip, value
... | en", "<control>G", # label, accelerator
"Grass", COLOR_GREEN), # tooltip, value
("Blue", None, # name, stock id
"_Blue", "<control>B", # label, accelerator
"Sky", COLOR_BLUE), # tooltip, val... |
miurahr/seahub | seahub/invitations/migrations/0005_auto_20160629_1614.py | Python | apache-2.0 | 366 | 0 | # -*- coding: utf-8 -*-
f | rom django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('invitations', '0004_auto_20160629_1610'),
]
operations = [
migrations.RenameField(
model_name='invitation',
old_name='expire_date',
| new_name='expire_time',
),
]
|
hanlind/nova | nova/conf/configdrive.py | Python | apache-2.0 | 4,097 | 0.001709 | # All Rights Reserved.
#
# Licensed under the Apache License, | Version 2.0 (the "License"); you may
| # not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.