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 |
|---|---|---|---|---|---|---|---|---|
miing/mci_migo | identityprovider/models/emailaddress.py | Python | agpl-3.0 | 4,191 | 0 | # Copyright 2010, 2012 Canonical Ltd. This software is licensed under
# the GNU Affero General Public License version 3 (see the file
# LICENSE).
import logging
import re
from datetime import datetime
from django.core.validators import validate_email
from django.db import models
from django.utils.translation import... | tatus=EmailStatus.NEW)
return email_address
def get_from_phone_id(self, phone_id):
email = self._generate_email_from_phone_id(phone_id)
email_address = self.get(email=email)
return email_address
class EmailAddress(models.Model):
email = models.TextField(validators=[validate_em... | date_created = models.DateTimeField(
default=datetime.utcnow, blank=True, editable=False)
account = models.ForeignKey(
Account, db_column='account', blank=True, null=True)
objects = EmailAddressManager.for_queryset_class(EmailAddressQuerySet)()
class Meta:
app_label = 'identitypro... |
mdenbina/kapok | kapok/lib/slope.py | Python | gpl-3.0 | 2,658 | 0.007524 | # -*- coding: utf-8 -*-
"""Terrain slope calculation, and ground range spacing calculation from
DEM.
Author: Michael Denbina
Copyright 2016 California Institute of Technology. All rights reserved.
United States Government Sponsorship acknowledged.
This program is free software: you ... | pe = np.arctan(rngslope / ((spacing[1]/np.sin(inc)) + (rngslope/np.tan(inc))))
return rngslope, azslope
def calcgrspacing(dem, spacing, inc):
"""Calculate ground range pixel spacing.
Given an input DEM in radar (azimuth, slant range) coordinates, the DEM
pixel spacing (i... | spacing: the slant range spacing of the DEM, in meters.
inc: the incidence angle, in radians.
Returns:
grspacing: Ground range spacing for each pixel, in meters.
"""
(azgrad,srgrad) = np.gradient(dem)
grspacing = ((spacing/np.sin(inc)) + (srgrad/np.tan(inc)))
... |
LLNL/spack | var/spack/repos/builtin/packages/r-triebeard/package.py | Python | lgpl-2.1 | 652 | 0.003067 | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT fi | le for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RTriebeard(RPackage):
"""triebeard: 'Radix' Trees in 'Rcpp'"""
homepage = "https://github.com/Ironholds/triebeard/"
url = "https://cloud.r-project.org/src/contrib/triebeard_0.3.0.tar.gz"
list_url = "https... | 9cea1aab24e21a85375ca473ad11c2eff400d65c6202c0fb4ef91ec3')
depends_on('r-rcpp', type=('build', 'run'))
|
birknilson/oyster | examples/piechart/requirements.py | Python | mit | 139 | 0.064748 | Flask= | =0.10.1
Jinja2==2.7.2
MarkupSafe==0.18
Werkzeug==0.9.4
distribute==0.6.31
itsdangerous==0.23
lxml==3.3.1
pygal==1.3.1
wsgiref= | =0.1.2
|
NTHU-CVLab/ActivityProps | network/trainer.py | Python | apache-2.0 | 2,961 | 0.001351 | import pickle
from sklearn.model_selection import train_test_split
from preprocess.feature import FeatureFile
from network.model import FC1Net, FC4Net, MLPModel, SaNet
from network.evaluate import NetEvaluator
class Trainer:
def __init__(self, feature_file=None):
self.exclude_features_keys = None
... | True).run((train_x, train_y), (test_x, test_y), args.save)
self.evaluator((train_x, train_y), (test_x, test_y), self.X, self.Y)
def evaluator(self, train, test, X, Y):
train_x, train_y = train
test_x, te | st_y = test
evaluator = NetEvaluator(X, Y)
evaluator.X, evaluator.Y = self.X, self.Y
evaluator.train_x, evaluator.test_x, evaluator.train_y, evaluator.test_y = train_x, test_x, train_y, test_y
print('=== evaluator & cross-validate ===')
evaluator.baseline_svm()
evaluato... |
justathoughtor2/atomicApe | cygwin/lib/python2.7/site-packages/pylint/test/extensions/test_elseif_used.py | Python | gpl-3.0 | 1,359 | 0 | """Tests for the pylint checker in :mod:`pylint.extensions.check_elif
"""
import os
import os.path as osp
import unittest
from pylint import checkers
from pylint.extensions.check_elif import ElseifUsedChecker
from pylint.lint import PyLinter
from pylint.reporters import BaseReporter
class TestReporter(BaseReporter)... | f setUpClass(cls):
cls._linter = PyLinter()
cls._linter.set_reporter(TestReporter())
checkers.initialize(cls._linter)
cls._linter.register | _checker(ElseifUsedChecker(cls._linter))
def test_elseif_message(self):
elif_test = osp.join(osp.dirname(osp.abspath(__file__)), 'data',
'elif.py')
self._linter.check([elif_test])
msgs = self._linter.reporter.messages
self.assertEqual(len(msgs), 2)
... |
SaileshPatel/Python-Exercises | ex16.py | Python | mit | 1,257 | 0.001591 | # importing 'argv' from 'sys' library
from sys import argv
# assigning the variables 'script' (which is the name of the script), and 'filename' (which is the name of a file) to the command line argument array 'argv'
script, filename = argv
# printing string with formatter r | epresenting 'filename'
print "We're going to erase %r." % filename
# printing string
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."
raw_input("?")
print "Opening the file..."
# assigning operator to variable. using 'open' to open the file.
target = open(filename, 'w')
# pri... | n
target.truncate()
print "Now I'm going to ask you for three lines."
# assigning user data to variable and printing string
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "I'm going to write these to the file."
# writing string from variable to the file
target.write(... |
joopert/home-assistant | tests/components/google_assistant/test_smart_home.py | Python | apache-2.0 | 28,484 | 0.000807 | """Test Google Smart Home."""
from unittest.mock import patch, Mock
import pytest
from homeassistant.core import State, EVENT_CALL_SERVICE
from homeassistant.const import ATTR_UNIT_OF_MEASUREMENT, TEMP_CELSIUS, __version__
from homeassistant.setup import async_setup_component
from homeassistant.components import camer... | _CONFIG, MockConfig
REQ_ID = "ff36a3cc-ec34-11e6-b1a0-64510650abcf"
@pytest.fixture
def registries(hass):
"""Registry mock setup."""
from types import SimpleNamespace
ret = SimpleNamespace()
ret.entity = mock_registry(hass)
ret.device = mock_device_registry(hass)
ret.area = mock_area_registr... | t(None, "Demo Light", state=False, hs_color=(180, 75))
light.hass = hass
light.entity_id = "light.demo_light"
await light.async_update_ha_state()
# This should not show up in the sync request
hass.states.async_set("sensor.no_match", "something")
# Excluded via config
hass.states.async_set(... |
xenserver/auto-cert-kit | autocertkit/operations_tests.py | Python | bsd-2-clause | 13,353 | 0.001573 | # Copyright (c) Citrix Systems Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms,
# with or without modification, are permitted provided
# that the following conditions are met:
#
# * Redistributions of source code must retain the above
# copyright notice, this list of conditions a... | tion complete: All VMs have been suspended")
# Resume all VMs
log.debug( | "Resuming VMs: %s" % vm_ref_list)
host_ref = get_pool_master(session)
task_list = [(lambda x=vm_ref: session.xenapi.Async.VM.resume_on(x,
|
jsannemo/programming-battle | battle/battle/api/__init__.py | Python | bsd-2-clause | 1,247 | 0.005613 | import os.path
from enum import Enum
class NamedEnum(Enum):
def __init__(self, name):
self.display_name = name
@classmethod
def get_names(cls):
return [name for name, _ in cls.__members__.items()]
class Role(NamedEnum):
solver = ('Solver')
tester = ('Tester')
class Status(NamedE... | (ExtensionEnum, self).__init__(name)
class Language(ExtensionEnum):
cpp = ('C++', 'cpp | ')
python = ('Python', 'py')
def detect_language(filename):
extension = os.path.splitext(filename)[-1]
if extension == '.cpp' or extension == '.cc':
return Language.cpp
if extension == '.py':
return Language.python
return None
|
baidu/Paddle | python/paddle/fluid/tests/unittests/test_pool3d_op.py | Python | apache-2.0 | 13,221 | 0.000454 | # Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | ol,
'use_cudnn': self.use_cudnn,
'ceil_mode': self.ceil_mode,
'data_format':
'AnyLayout', # TODO(dzhwinter) : should be fix latter
'exclusive': self.exclusive,
'adaptive': self.adaptive
| }
self.outputs = {'Out': output}
def testcudnn(self):
return core.is_compiled_with_cuda() and self.use_cudnn
def test_check_output(self):
if self.testcudnn():
place = core.CUDAPlace(0)
self.check_output_with_place(place, atol=1e-5)
else:
se... |
apache/flink | flink-python/pyflink/datastream/tests/test_connectors.py | Python | apache-2.0 | 20,161 | 0.004018 | ################################################################################
# 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... | _properties.getProperty('bootstrap.servers'))
self.assertEqual('test_group', j_properties.getProperty('group.id'))
self.assertTrue(get_field_value(flink_kafka_consumer.get_java_function(),
'enableCommitOnCheckpoints'))
j_start_up_mode = get_field_va | lue(flink_kafka_consumer.get_java_function(), 'startupMode')
j_deserializer = get_field_value(flink_kafka_consumer.get_java_function(), 'deserializer')
j_deserialize_type_info = invoke_java_object_method(j_deserializer, "getProducedType")
deserialize_type_info = typeinfo._from_java_type(j_deser... |
obi-two/Rebelion | data/scripts/templates/object/tangible/wearables/armor/mandalorian/shared_armor_mandalorian_helmet.py | Python | mit | 494 | 0.044534 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
fr | om swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/wearables/armor/mandalorian/shared_armor_mandalorian_helmet.iff"
result.attribute_template_id = 0
result.stfName("wearables_name","armor_mandalorian_helmet")
#### BEGIN MODIFICATIONS ####
#### END MODIFICAT... | ult |
merlin-lang/kulfi | simulate/viz/LatencyDiffPoints.py | Python | lgpl-3.0 | 5,142 | 0.004084 | import os
import operator
import sys
from collections import defaultdict
import matplotlib.pyplot as pp
import CommonConf
BASE = 'ksp'
algs = ['mcf', 'raeke', 'edksp', 'vlb', 'ksp', 'ecmp']
def setupMPPDefaults():
pp.rcParams['font.size'] = 66
pp.rcParams['mathtext.default'] = 'regular'
pp.rcParams['ytick... | a'] = 0.4
pp.rcParams['legend.numpoints'] = 1
pp.rcParams['legend.scatterpoints'] = 1
def parse_rtt_file(rtt_file):
rtts = dict()
with open(rtt_file) as f:
for l in f.readlines():
tokens = l.split()
rtts[tokens[0]] = float(tokens[1])
return rtts
def parse_path_file... | (paths_file) as f:
for l in f.readlines():
if "->" in l:
src = l.split()[0]
dst = l.split()[2]
paths[(src,dst)] = dict()
else:
if len(l.strip()) == 0:
continue
path = tuple(l.split('@')[0]... |
masom/doorbot-api-python | doorbot/views/dashboard/account.py | Python | mit | 610 | 0.001639 | from flask import Blueprint, render_template
from ...middlewares import auth_manager
from .middlewares import s
from ...container import container
account = Blueprint('account', __name__, url_prefix='/account')
def view():
account = container.account
return render_template('accounts/view.html', account=acco... |
account = container.account
return render_template('accounts/view.html', account=account)
account.add_url_rule(
'', 'view',
s(view),
methods=['GET']
)
account.add_url_rule(
'/edit | ', 'update',
s(auth_manager),
methods=['GET', 'POST']
)
|
okolisny/integration_tests | cfme/tests/networks/test_sdn_crud.py | Python | gpl-2.0 | 1,613 | 0.00124 | import pytest
from cfme.cloud.provider.azure import AzureProvider
from cfme.cloud.provider.ec2 import EC2Provider
from cfme.cloud.provider.openstack import OpenStackProvider
from cfme.networks.provider import NetworkProviderCollection
from cfme.utils import testgen
from cfme.utils.appliance.implementations.ui import na... | """
view = navigate_to(provider, 'Details')
net_prov_name = view.contents.relationships.get_text_of("Network Manage | r")
collection = NetworkProviderCollection(appliance)
network_provider = collection.instantiate(name=net_prov_name)
view = navigate_to(network_provider, 'Details')
parent_name = view.entities.relationships.get_text_of("Parent Cloud Provider")
assert parent_name == provider.name
testing_list =... |
sam-m888/gprime | gprime/filters/rules/media/_hasnotematchingsubstringof.py | Python | gpl-2.0 | 1,769 | 0.005653 | #
# gPrime - A web-based genealogy program
#
# Copyright (C) 2002-2006 Donald N. Allingham
#
# 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 optio... | ubstrbase import HasNoteSubstrBase
#-------------------------------------------------------------------------
# "Media having notes that contain a substring"
#-------------------------------------------------------------------------
class HasNoteMatchingSubstringOf(HasNoteSubstrBase):
| """Media having notes containing <substring>"""
name = _('Media objects having notes containing <substring>')
description = _("Matches media objects whose notes contain text "
"matching a substring")
|
adrianholovaty/django | django/templatetags/tz.py | Python | bsd-3-clause | 5,488 | 0 | from datetime import datetime, tzinfo
try:
import pytz
except ImportError:
pytz = None
from django.template import Node
from django.template import TemplateSyntaxError, Library
from django.utils import timezone
register = Library()
# HACK: datetime is an old-style class, create a new-style equivalent
# so ... | e_tz = use_tz
def render(self, context):
old_setting = context.use_tz
context.use | _tz = self.use_tz
output = self.nodelist.render(context)
context.use_tz = old_setting
return output
class TimezoneNode(Node):
"""
Template node class used by ``timezone_tag``.
"""
def __init__(self, nodelist, tz):
self.nodelist = nodelist
self.tz = tz
def r... |
anhstudios/swganh | data/scripts/templates/object/tangible/wearables/armor/stormtrooper/shared_armor_stormtrooper_chest_plate.py | Python | mit | 507 | 0.043393 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DO | CUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/wearables/armor/stormtrooper/shared_armor_stormtrooper_chest_plate.iff"
result.attribute_template_id = 0
result.stfName("wearables_name","armor_stormtrooper_chest_plate")
#### BEGI... | ND MODIFICATIONS ####
return result |
google/pigweed | pw_presubmit/py/presubmit_test.py | Python | apache-2.0 | 1,944 | 0 | #!/usr/bin/env python3
# Copyright 2020 The Pigweed Authors
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | function_2],
)
def test_empty(self):
self.assertEqual({}, presubmit.Programs())
def test_access_present_members(self):
self.assertEqual('first', self._programs['first'].name)
self.assertE | qual((_fake_function_1, _fake_function_2),
tuple(self._programs['first']))
self.assertEqual('second', self._programs['second'].name)
self.assertEqual((_fake_function_2, ), tuple(self._programs['second']))
def test_access_missing_member(self):
with self.assertRaises... |
NAMD/pypln.backend | tests/test_worker_bigrams.py | Python | gpl-3.0 | 2,288 | 0.000874 | # coding: utf-8
#
# Copyright 2012 NAMD-EMAP-FGV
#
# This file is part of PyPLN. You can get more information at: http://pypln.org/.
#
# PyPLN 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 o... | _score(self):
# We need this list comprehension because we need to save the word list
# in mongo (thus, it needs to be json serializable). Also, a list is
# what will be available to the worker in real situations.
| tokens = [w for w in
nltk.corpus.genesis.words('english-web.txt')]
doc_id = self.collection.insert({'tokens': tokens}, w=1)
Bigrams().delay(doc_id)
refreshed_document = self.collection.find_one({'_id': doc_id})
bigram_rank = refreshed_document['bigram_rank']
... |
RedhawkSDR/framework-codegen | redhawk/codegen/jinja/python/ports/templates/generic.provides.py | Python | lgpl-3.0 | 1,314 | 0.005327 | #{#
# This file is protected by Copyright. Please refer to the COPYRIGHT file
# distributed with this source distribution.
#
# This file is part of REDHAWK core.
#
# REDHAWK core is free software: you can redistri | bute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# REDHAWK core is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the i... | for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see http://www.gnu.org/licenses/.
#}
#% set className = portgen.className()
class ${className}(${component.baseclass.name}.${portgen.templateClass()}):
def __init__(self, parent, name... |
LaurentClaessens/phystricks | testing/demonstration/exCircleThree.py | Python | gpl-3.0 | 652 | 0.015337 | from phystricks import *
def exCircleThree():
pspict,fig = SinglePicture("exCircleThree")
circle = Circle(Point(0,0),1.5)
circle.angleI = 45
circle.angleF = 380
circle.wave(0.1,0.1)
circle.parameters.color = "green"
circleB = Circle(Point(0,0),1.5)
circleB.angleI = circle.angleF-360
... | pspict.DrawDefaultAxes()
pspict.comment="A large green wavy part and a small red wavy part."
fig.no_figure()
fig.conclude()
fig.write_the_file()
| |
AEDA-Solutions/matweb | backend/Models/Grau/RespostaEditar.py | Python | mit | 179 | 0.039106 | from Framework.Resposta import Res | posta
from Models.Grau.Grau import Grau as ModelGrau
class Re | spostaEditar(Resposta):
def __init__(self,mensagem):
self.corpo = mensagem
|
1flow/1flow | oneflow/core/admin/__init__.py | Python | agpl-3.0 | 2,818 | 0.00284 | # -*- coding: utf-8 -*-
u"""
Copyright 2013-2014 Olivier Cortès <[email protected]>.
This file is part of the 1flow project.
1flow 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... | try,
MailAccount,
Author,
Folder,
SyncNode,
NodePermissions,
)
if settings.FULL_ADMIN:
from helpcontent import HelpContent, HelpContentAdmin
admin.site.register(HelpConte | nt, HelpContentAdmin)
from website import WebSite, WebSiteAdmin
admin.site.register(WebSite, WebSiteAdmin)
admin.site.register(Author)
admin.site.register(Folder)
from processor import (
Processor, ProcessorAdmin,
ProcessingChain,
ChainedItem, ChainedItemAdmin,
ChainedItemParameter,
ProcessingEr... |
BlueDragonX/fm-dot | i3/lib/i3.py | Python | bsd-3-clause | 4,205 | 0 | """
API for communicating with the i3 window manager.
"""
import json
import subprocess
class I3Msg(object):
"""Send messages to i3."""
def __init__(self, socket=None, msgbin=None):
"""
Initialize the messager.
@param socket The socket to connect to i3 via.
@param msgbin The... | default arguments.
"""
if i3msg is None:
i3msg = I3Msg()
self.i3 = i3msg
def commands(self, cmds, ignore=None):
"""
Run multiple of commands.
@param cmds An iterable containing commands to run.
@param ignore A regex used to ignore certain lines.... | None.
@return A list of results, one for each command.
"""
results = []
for cmd in cmds:
if len(cmd.strip()) == 0 or (
ignore is not None and ignore.match(cmd)):
results.append(None)
else:
results.append(self.i3.... |
Aurora0000/descant | forums/migrations/0018_auto_20150518_1634.py | Python | mit | 467 | 0.002141 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migra | tions
class Migration(migrations.Migration):
dependencies = [
('forums', '0017_auto_20150517_1552'),
]
operations = [
migrations.AlterField(
| model_name='post',
name='reply_to',
field=models.ForeignKey(related_name='replies', blank=True, editable=False, to='forums.Post', null=True),
),
]
|
jimi-c/ansible | lib/ansible/modules/storage/netapp/sf_snapshot_schedule_manager.py | Python | gpl-3.0 | 13,004 | 0.002538 | #!/usr/bin/python
# (c) 2017, NetApp, Inc
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
... |
- Volume IDs that you want to set the snapshot schedule for.
- At | least 1 volume ID is required for creating a new schedule.
- required when C(state=present)
required: false
retention:
description:
- Retention period for the snapshot.
- Format is 'HH:mm:ss'.
required: false
schedule_id:
description:
- The sche... |
tersmitten/ansible | lib/ansible/modules/remote_management/lxca/lxca_cmms.py | Python | gpl-3.0 | 4,442 | 0.001576 | #!/usr/bin/python
# GNU General Public License v3.0+ (see COPYING or
# https://www.gnu.org/licenses/gpl-3.0.txt)
#
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'supported_by': 'community',
'status': ['preview']
}
... | = '''
---
version_added: "2.8"
author:
- Naval Patel (@navalkp)
- Prashant Bhosale (@prabhosa)
module: lxca_cmms
short_description: Custom module for lxca cmms invent | ory utility
description:
- This module returns/displays a inventory details of cmms
options:
uuid:
description:
uuid of device, this is string with length greater than 16.
command_options:
description:
options to filter nodes information
default: cmms
choices:
- cmms
... |
philgyford/django-spectator | spectator/events/migrations/0042_auto_20200407_1039.py | Python | mit | 1,302 | 0 | # Generated by Django 3.0.5 on 2020-04-07 10:39
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("spectator_events", "0041_event_ticket"),
]
operations = [
migrations.AlterField(
model_name="venue... | blank=True,
help_text='Optional. ID of a cinema at\n<a href="http://cinematreasures.org/">Cinema Treasures</a>.', # noqa: E501
null=True,
),
),
migrations.AlterField(
model_name="w | ork",
name="imdb_id",
field=models.CharField(
blank=True,
help_text="Starts with 'tt', e.g. 'tt0100842'.\nFrom <a href=\"https://www.imdb.com\">IMDb</a>.", # noqa: E501
max_length=12,
validators=[
django.core.va... |
Tianyi94/EC601Project_Somatic-Parkour-Game-based-on-OpenCV | Old Code/ControlPart/Create_pos&neg.py | Python | mit | 444 | 0.006757 | def create_pos_n_neg():
for file_type in ['neg']:
for img in os.listdir(file_type):
if file_type | == 'pos':
| line = file_type+'/'+img+' 1 0 0 50 50\n'
with open('info.dat','a') as f:
f.write(line)
elif file_type == 'neg':
line = file_type+'/'+img+'\n'
with open('bg.txt','a') as f:
f.write(line)
|
googleapis/python-policy-troubleshooter | google/cloud/policytroubleshooter_v1/services/iam_checker/async_client.py | Python | apache-2.0 | 11,763 | 0.00204 | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | regular endpoint) and "auto" (auto switch to the
default mTLS endpoint if client certificate is present, this is
the default value). However, the ``api_endpoint`` property takes
precedence if provided.
(2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment ... | `client_cert_source`` property can be used
to provide client certificate for mutual TLS transport. If
|
imbstack/pasquino | migrations/env.py | Python | mit | 2,643 | 0.001135 | from __future__ import with_statement
from alembic import context
from sqlalchemy import engine_from_config, pool
from logging.config import fileConfig
import logging
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config ... | om_config(config.get_section(config.config_ini_section),
prefix='sqlalchemy.',
poolclass=pool.NullPool)
connection = engine.connect()
context.configure(connection=connection,
target_metadata=target_metadata,
... | vision_directives=process_revision_directives,
**current_app.extensions['migrate'].configure_args)
try:
with context.begin_transaction():
context.run_migrations()
finally:
connection.close()
if context.is_offline_mode():
run_migrations_offline()
else:
... |
zaffra/Inquire | GAE/api.py | Python | bsd-3-clause | 17,740 | 0.003439 | ##
# api.py
#
# This file is the workhorse for the the entire web application.
# It implements and provides the API required for the iOS portion
# of the project as well as interacting with Google's datastore
# for persistent storage of our models.
##
# for sending mail
from google.appengine.api import mail
# Used i... | question_id: id of an existing question
@param answer: the text for the answe | r to a question
@returns one answer object
"""
# session and authenticated user
user = Session().get("user")
# required parameters
question_id = int(request.REQUEST.get("question_id"))
answer = request.REQUEST.get("answer")
# find the question associated with the question_id par... |
annayqho/TheCannon | code/apokasc_lamost/kepler_apogee_lamost_overlap.py | Python | mit | 2,584 | 0.011223 | import numpy as np
import os
# APOGEE-APOKASC overlap
inputf = "/home/annaho/TheCannon/examples/example_apokasc/apokasc_DR12_overlap.npz"
apogee_apokasc = np.load(inputf)['arr_0']
# APOGEE-LAMOST overlap
inputf = "/home/annaho/TheCannon/examples/example_DR12/Data"
apogee_lamost = np.array(os.listdir(inputf))
# APO... | ls_all = np.loadtxt(
label_file, usecols=(2,3,4,5), delimiter=',', dtype=float)
inds = np.array([np.where(apogee_id_all==a)[0][0] for a in overlap])
apogee_id = apogee_id_all[inds]
apogee_labels = apogee_labels_all[inds,:]
# get all APOKASC parameters
apokasc_id_all = np.load("example_apokasc/apokasc_DR12_ov... | ple_apokasc/tr_label.npz")['arr_0']
inds = np.array([np.where(apokasc_id_all==a)[0][0] for a in overlap])
apokasc_id = apokasc_id_all[inds]
apokasc_labels = apokasc_labels_all[inds]
# get all LAMOST parameters
inputf = "/home/annaho/TheCannon/examples/test_training_overlap/lamost_sorted_by_ra_with_dr2_params.txt"
la... |
rcbops/opencenter | tests/test_expressions.py | Python | apache-2.0 | 11,034 | 0 | #
# OpenCenter(TM) is Copyright 2013 by Rackspace US, Inc.
##############################################################################
#
# OpenCenter is licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. This
# version of ... |
self.interfaces = {}
self.nodes['node-1'] = self._model_create('nodes', name='node-1')
self.interf | aces['chef'] = self._model_create('filters', name='chef',
filter_type='interface',
expr='facts.x = true')
self.nodes['container'] = self._model_create('nodes', name='container')
def tearDown(self):
... |
mdhaber/scipy | scipy/fftpack/tests/test_real_transforms.py | Python | bsd-3-clause | 23,941 | 0.000877 | from os.path import join, dirname
import numpy as np
from numpy.testing import assert_array_almost_equal, assert_equal
import pytest
from pytest import raises as assert_raises
from scipy.fftpack._realtransforms import (
dct, idct, dst, idst, dctn, idctn, dstn, idstn)
# Matlab reference data
MDATA = np.load(join(... | ual(y[j], dct(x[j], type=self.type),
decimal=self.dec)
x = x.T
y = dct(x, axis=0, type=self.type)
for j in range(nt):
assert_array_almost_equal(y[:,j], dct(x[:,j], type=self.type),
decimal=self.dec)
class _TestDCTIBas... | t32, self.rdt)
for xr in X:
x = np.array(xr, dtype=self.rdt)
y = dct(x, norm='ortho', type=1)
y2 = naive_dct1(x, norm='ortho')
assert_equal(y.dtype, dt)
assert_array_almost_equal(y / np.max(y), y2 / np.max(y), decimal=self.dec)
class _TestDCTIIBase(_T... |
Micronaet/micronaet-mx8 | sale_box_volume/__openerp__.py | Python | agpl-3.0 | 1,492 | 0.002011 | ###############################################################################
#
# Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.it>).
#
# This program is fre | e 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 option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied ... |
MicroTrustRepos/microkernel | src/l4/pkg/python/contrib/Doc/includes/tzinfo-examples.py | Python | gpl-2.0 | 5,063 | 0.003555 | from datetime import tzinfo, timedelta, datetime
ZERO = timedelta(0)
HOUR = timedelta(hours=1)
# A UTC class.
class UTC(tzinfo):
"""UTC"""
def utcoffset(self, dt):
return ZERO
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return ZERO
utc = UTC()
# A class building... | else:
return ZERO
def tzname(self, dt):
return _time.tzname[self._isdst(dt)]
def _isdst(self, dt):
tt = (dt.year, dt.month, dt.day,
dt.hour, dt.minute, dt.second,
dt.weekday(), 0, -1)
stamp = _time.mktime(tt)
tt = _time.localtime(stam... | ne()
# A complete implementation of current DST rules for major US time zones.
def first_sunday_on_or_after(dt):
days_to_go = 6 - dt.weekday()
if days_to_go:
dt += timedelta(days_to_go)
return dt
# US DST Rules
#
# This is a simplified (i.e., wrong for a few cases) set of rules for US
# DST sta... |
hashinisenaratne/HSTML | lib/scripts/include_bib.py | Python | gpl-2.0 | 2,972 | 0.01817 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# file include_bib.py
# This file is part of LyX, the document processor.
# Licence details can be found in the file COPYING.
# authors Richard Heck and [SchAirport]
# Full author contact details are available in file CREDITS
# This script is intended to include a BibTe... | n have it in the export menu.
#
# We do not activate this converter by default, because there are problems
# when one tries to use multiple bibliographies.
#
# Please report any problems on the devel list.
import sys, os
class secbib:
def __init__(self | , start = -1, end = -1):
self.start = start
self.end = end
class BibError(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
def InsertBib(fil, out):
''' Inserts the contents of the .bbl file instead of the bibliography in a new .tex file '''
texlist... |
Endika/event | event_project/wizard/project_template_wizard.py | Python | agpl-3.0 | 1,219 | 0 | # -*- coding: utf-8 -*-
# See README.rst file on addon root folder for license details
from openerp import models, fields, exceptions, api
from openerp.tools.translate import _
class ProjectTemplateWizard(models.TransientModel):
_name = 'project.template.wizard'
project_id = fields.Many2one(
comodel... | vent_id.project_id.write({
'name': self.event_id.name,
'date_start': self.event_id.date_begin,
'date': self.event_id.date_begin,
'calculation_type': 'date_end',
})
self.event_id.project_id.project_recalculate() | |
richardcornish/smsweather | gunicorn.py | Python | bsd-3-clause | 95 | 0.010526 | bind = 'unix:/run/emojiweather.so | ck'
pythonpath = 'emojiweather'
workers = 2
accesslog | = '-' |
wiki-ai/wb-vandalism | wb_vandalism/feature_lists/wikidata.py | Python | mit | 6,094 | 0.003446 | from revscoring.features import user
from revscoring.features.modifiers import not_, log
from ..features import diff, revision
class properties:
"""
Mapping of english descriptions to property identifiers
"""
IMAGE = 'P18'
SEX_OR_GENDER = 'P21'
COUNTRY_OF_CITIZENSHIP = 'P27'
INSTANCE_OF =... | ANCE_OF, items.HUMAN,
name='revision.is_human')
has_birthday = \
revision.has_property(properties.DATE_OF_BIRTH,
name='revision.has_birthday')
dead = \
revision.has_property(properties.DATE_OF_DEATH,
name='revision.dead')
is_blp... | coring.features.diff.numeric_chars_added + 1),
# log(revscoring.features.diff.numeric_chars_removed + 1),
# revscoring.features.diff.proportion_of_chars_added,
# revscoring.features.diff.proportion_of_chars_removed,
# revscoring.features.diff.proportion_of_numeric_chars_added,
# revscoring.features.diff.... |
trailofbits/manticore | manticore/core/smtlib/__init__.py | Python | agpl-3.0 | 268 | 0 | from .expression impo | rt Expression, Bool, BitVec, Array, BitVecConstant, issymbolic # noqa
from .constraints import ConstraintSet # noqa
from .solver import * # noqa
from . import operators as Operators # noqa
import logging
logger = log | ging.getLogger(__name__)
|
comodit/combox | combox/control.py | Python | mit | 569 | 0.010545 | import time, sys, | os, helper
from comodit_client.api import Client
from comodit_client.api.exceptions import PythonApiException
from comodit_client.rest.exceptions import ApiException
from combox.config import | config
from helper import create_host, get_short_hostname, exec_cmd, exec_cmds, fork_cmd
def stop():
print "Stopping virtual machine"
success = exec_cmds(['VBoxManage controlvm "%s" poweroff' % config['vm']['name']])
def start():
print "Starting virtual machine"
fork_cmd('VBoxManage startvm --type he... |
FabienPean/sofa | applications/plugins/SofaPython/examples/sceneDataIO_write.py | Python | lgpl-2.1 | 5,843 | 0.004963 | import sys, os, platform, math
import Sofa
import Flexible.IO
import Flexible.sml
import SofaPython.Tools
from SofaPython.Tools import listToStr as concat
import numpy
from numpy import linalg
# variables
__file = __file__.replace('\\', '/') # windows
CURRENTDIR = os.path.dirname(os.path.abspath(__fil... | e.cr | eateObject('MechanicalObject', template='E332', name='E')
eNode.createObject('CorotationalStrainMapping', template='F332,E332', method='polar')
eNode.createObject('HookeForceField', template='E332', name='ff', youngModulus='1E3', poissonRatio='0', viscosity='0')
# contact and visual model
... |
Makerblaker/Sprinkler | server.py | Python | gpl-3.0 | 4,160 | 0.040625 | #!/usr/bin/python3
import _thread
import RPi.GPIO as GPIO
import socket
import time
from time import sleep
from sys import exit
import datetime
#import MySQLdb
# Start task command
# sleep 30 && python /home/pi/Scripts/Sprinkler/Sprinkler.py > /home/pi/Scripts/Sprinkler/log.txt 2>&1
# Set GPIO output poi... | f mainRun():
global isRaining
addLog("System", "Main Thread started")
# Always check the switch
_thread.start_new_thread(checkSwitch, ((),))
while True:
global se | rversocket
clientsocket,addr = serversocket.accept()
fromClient = clientsocket.recv(1024)
clientsocket.close()
strFromClient = str(fromClient.decode("ascii"))
addLog("Recived", strFromClient)
# Split incoming message
requestType = strFromClient.split(":")
# Do something with that messa... |
LordDarkula/chess_py | chess_py/core/algebraic/notation_const.py | Python | mit | 330 | 0 | # -*- coding: utf-8 -*-
"""
Class stores integer values for various types of moves in algebraic notation.
Copyright © 2016 Aubhro Sengupta. All rights reserved.
"""
MOVE | MENT = 0
CAPTURE = 1
KING_SIDE_CASTLE = 2
QUEEN_SIDE_CASTL | E = 3
EN_PASSANT = 4
PROMOTE = 5
CAPTURE_AND_PROMOTE = 6
NOT_IMPLEMENTED = 7
LONG_ALG = 8
|
google/openhtf | openhtf/util/xmlrpcutil.py | Python | apache-2.0 | 4,133 | 0.008226 | # 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... | ROXY_TIMEOUT_S = 3
# https://github.com/PythonCharmers/python-future/issues/280
# pylint: disable=g-import-not-at-top,g-importing-member
if sys.version_info[0] < 3:
from SimpleXMLRPCServer import SimpleXMLRPCServer # pytype: disable=import-error
else:
from xmlrpc.server import SimpleXMLRPCServer # pytype: disabl... | sable=missing-class-docstring
def __init__(self, timeout_s, *args, **kwargs):
http.client.HTTPConnection.__init__(self, *args, **kwargs)
self.timeout_s = timeout_s
def settimeout(self, timeout_s):
self.timeout_s = timeout_s
self.sock.settimeout(self.timeout_s)
def connect(self):
http.client... |
Kotaimen/stonemason | stonemason/formatbundle/exceptions.py | Python | mit | 259 | 0 | # -*- encoding: utf-8 -*-
__author__ = 'kotaimen'
__date__ = '2/19/15'
class FormatError(Exception):
pass
class InvalidMapType(FormatError):
pass
class InvalidTileFormat(FormatError):
pass
class NoMatch | ingMapWrit | er(FormatError):
pass
|
srottem/indy-sdk | docs/how-tos/negotiate-proof/python/step2.py | Python | apache-2.0 | 2,916 | 0.006859 | # 1.
print_log('\n1. Creates Issuer wallet and opens it to get handle.\n')
await
wallet.create_wallet(pool_name, issuer_wallet_name, None, None, None)
issuer_wallet_handle = await
wallet.open_wallet(issuer_wallet_name, None, None)
# 2.
print_log('\n2. Cre... | 'name': 'gvt',
'version': '1.0',
'attr_names': ['age', 'sex', 'height', 'name']
}
}
schema_json = json.dumps(schema)
schema_key = {
'name': schema['data']['name'],
'version': schema['data']['version'],
'did': schema... | print_log('Claim Definition: ')
pprint.pprint(json.loads(claim_def_json))
# 4.
print_log('\n4. Prover creates Link Secret\n')
link_secret_name = 'link_secret'
await
anoncreds.prover_create_master_secret(prover_wallet_handle, link_secret_name)
# 5.
pr... |
pwndbg/pwndbg | pwndbg/prompt.py | Python | mit | 1,730 | 0.001734 | import gdb
import pwndbg.decorators
import pwndbg.events
import pwndbg.gdbutils
import pwndbg.memoize
from pwndbg.color import disable_colors
from pwndbg.color import message
funcs_list_str = ', '.join(message.notice('$' + f.name) for f in pwndbg.gdbutils.functions.functions)
hint_lines = (
'loaded %i commands. ... | r
pwndbg.decorators.first_prompt = True
ne | w = (gdb.selected_inferior(), gdb.selected_thread())
if cur != new:
pwndbg.events.after_reload(start=cur is None)
cur = new
if pwndbg.proc.alive and pwndbg.proc.thread_is_stopped:
prompt_hook_on_stop(*a)
@pwndbg.memoize.reset_on_stop
def prompt_hook_on_stop(*a):
pwndbg.commands.c... |
Azure/azure-sdk-for-python | sdk/cognitiveservices/azure-cognitiveservices-search-visualsearch/azure/cognitiveservices/search/visualsearch/models/structured_value.py | Python | mit | 3,167 | 0.000316 | # 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 ... | :ivar web_search_url: The URL to Bing's search result for this item.
:vartype web_search_url: str
:ivar name: The name of the thing represented by this object.
:vartype name: str
:ivar url: The URL to get more information about the thing represented by
this object.
:vartyp | e url: str
:ivar image: An image of the item.
:vartype image:
~azure.cognitiveservices.search.visualsearch.models.ImageObject
:ivar description: A short description of the item.
:vartype description: str
:ivar alternate_name: An alias for the item.
:vartype alternate_name: str
:ivar bin... |
mschuurman/FMSpy | nomad/initconds/explicit.py | Python | lgpl-3.0 | 1,004 | 0.003984 | """
Sample a specific geometry or set of geometries.
"""
import numpy as np
import nomad.core.glbl as glbl
import nomad.core.trajectory as trajectory
import nomad.core.log as log
def set_initial_coords(wfn):
"""Takes initial position and momentum from geometry specified in input"""
coords = glbl.properties['i... | .Trajectory(glbl.properties['n_states'], ndim,
| width=glbl.properties['crd_widths'],
mass=glbl.properties['crd_masses'],
parent=0, kecoef=glbl.modules['integrals'].kecoef)
# set position and momentum
itraj.update_x(np.array(coord[0]))
itraj.update_p(np.array(... |
gwind/YWeb | yweb/yweb/utils/i18n.py | Python | mit | 142 | 0 | # coding: utf-8
def | ugettext(message):
'''返回原字符串
为了使用 _('') 方式标记字符串
'''
ret | urn message
|
mgraffg/simplegp | SimpleGP/tests/test_gpmae.py | Python | apache-2.0 | 1,069 | 0.000935 | # Copyright 2013 Mario Graff Guerrero
# 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 wri... | nse.
from SimpleGP import GPMAE
import numpy as np
def test_gpmae():
x = np.linspace(-10, 10, 100)
pol = np.array([0.2, -0.3, 0.2])
X = np.vstack((x**2, x, np.ones(x.shape[0])))
y = (X.T * pol).sum(axis=1)
x = x[:, np.newaxis]
gp = GPMAE.init_cl(verbose=True,
ge | nerations=30, seed=0,
max_length=1000).train(x, y)
gp.run()
fit = gp.fitness(gp.get_best())
print fit
assert fit >= -0.7906
|
phatblat/AbletonLiveMIDIRemoteScripts | Push2/session_recording.py | Python | mit | 842 | 0.014252 | # Source Generated with Decompyle | ++
# File: session_recording.pyc (Python 2.5)
from __future__ import absolute_import
from pushbase.session_recording_component import FixedLengthSessionRecordingComponent
class SessionRecordingComponent(FixedLengthSessionRecordingCom | ponent):
def __init__(self, *a, **k):
super(SessionRecordingComponent, self).__init__(*a, **a)
self.set_trigger_recording_on_release(not (self._record_button.is_pressed))
def set_trigger_recording_on_release(self, trigger_recording):
self._should_trigger_recording = trigger_re... |
valsaven/md5hash | md5hash/__init__.py | Python | mit | 103 | 0 | __a | ll__ = ["md5", "size", "calculate", "scan"]
from md5hash.md5hash import md5, size, calcu | late, scan
|
sathnaga/avocado-vt | virttest/utils_libvirtd.py | Python | gpl-2.0 | 15,212 | 0.000197 | """
Module to control libvirtd service.
"""
import re
import logging
import aexpect
from avocado.utils import path
from avocado.utils import process
from avocado.utils import wait
from virttest import libvirt_version
from virttest import utils_split_daemons
from . import remote as remote_old
from . import utils_misc... |
:params service_name: Service name such as virtqemud or libvirtd.
If service_name is None, all sub daemons will be operated when
modular daemon environment is enabled. | Otherwise,if service_name is
a single string, only the given daemon/service will be operated.
:params session: An session to guest or remote host.
"""
self.session = session
if self.session:
self.remote_runner = remote_old.RemoteRunner(session=self.session)
... |
xzturn/caffe2 | caffe2/python/rnn/__init__.py | Python | apache-2.0 | 821 | 0.001218 | # Copyright (c) 2016-present, Facebook, 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... | absolute_import
from __f | uture__ import division
from __future__ import print_function
from __future__ import unicode_literals
|
Brutus5000/BiReUS | bireus/client/patch_tasks/base.py | Python | mit | 3,803 | 0.003681 | # coding=utf-8
import abc
import logging
import tempfile
from bireus.client.download_service import AbstractDownloadService
from bireus.client.notific | ation_service import NotificationService
from bireus.shared import *
from bireus.shared.diff_head import DiffHead
from bireus.shared.diff_item import DiffItem
from bireus.shared.repository import ProtocolException
logger = logging.getLogger(__name__)
class PatchTask(abc.ABC):
_patch_tasks = None
def __init_... | notification_service: NotificationService, download_service: AbstractDownloadService,
repository_url: str, repo_path: Path, patch_file: Path):
self._notification_service = notification_service
self._download_service = download_service
self._url = repository_url
self._re... |
virtuald/pynsq | nsq/writer.py | Python | mit | 7,774 | 0.002059 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import logging
import time
import functools
import random
import inspect
from ._compat import string_types
from .client import Client
from nsq import protocol
from . import async
logger = logging.getLogger(__name__)
class Writer(Client):
"""
A ... | imeout(time.time() + self.r | econnect_interval, reconnect_callback)
def _finish_pub(self, conn, data, command, topic, msg):
if isinstance(data, protocol.Error):
logger.error('[%s] failed to %s (%s, %s), data is %s',
conn.id if conn else 'NA', command, topic, msg, data)
|
pegasus-isi/pegasus | packages/pegasus-python/src/Pegasus/init-old.py | Python | apache-2.0 | 14,973 | 0.001069 | import errno
import os
import pwd
import shutil
import sys
from jinja2 import Environment, FileSystemLoader
class TutorialEnv:
LOCAL_MACHINE = ("Local Machine Condor Pool", "submit-host")
USC_HPCC_CLUSTER = ("USC HPCC Cluster", "usc-hpcc")
OSG_FROM_ISI = ("OSG from ISI submit node", "osg")
XSEDE_BOSC... | ation Modeling using Containers", "population")
MPI = ("MPI Hello World", "mpi-hw")
def choice(question, options, default):
"Ask the user to choose from a short list of named options"
while True:
sys.stdout.write("{} ({}) [{}]: ".format(question, "/".join(options), default))
| answer = sys.stdin.readline().strip()
if len(answer) == 0:
return default
for opt in options:
if answer == opt:
return answer
def yesno(question, default="y"):
"Ask the user a yes/no question"
while True:
sys.stdout.write("{} (y/n) [{}]: ".f... |
grnet/mupy | muparse/migrations/0004_auto__chg_field_graph_slug__chg_field_graph_name.py | Python | gpl-3.0 | 4,828 | 0.007457 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'Graph.slug'
db.alter_column('muparse_graph', 'slug', self.gf('django.db.models.fields.Slu... | 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'node': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm[ | 'muparse.Node']"}),
'pageurl': ('django.db.models.fields.CharField', [], {'max_length': '512'}),
'updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
},
'muparse.nodegroup': {
'Meta': {'ordering': "['name']", 'object_name': '... |
scripnichenko/glance | glance/db/sqlalchemy/models_artifacts.py | Python | apache-2.0 | 12,959 | 0 | # Copyright (c) 2015 Mirantis, 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 writin... | .to_dict()
d.pop('type_version_prefix')
| d.pop('type_version_suffix')
d.pop('type_version_meta')
d.pop('version_prefix')
d.pop('version_suffix')
d.pop('version_meta')
d['type_version'] = str(self.type_version)
d['version'] = str(self.version)
tags = []
for tag in self.tags:
tags.a... |
bardia-heydarinejad/Graph | home/views.py | Python | mit | 852 | 0.038732 | from django.shortcuts import render_to_response,RequestContext
from django.http import HttpResponse,HttpResponseRedirect
from urllib import urlencode
from time import sleep
from vertex.models import *
from django.core.exceptions import ObjectDoesNotExist
from login.views import authDetail
def home(request):
if not a... | authDetail(request)[1]
vertex = Vertex.objects.get(email = client.email)
flows = vertex.flow_set.order_by('-last_forward_date')[:5]
return render_to_response('home.html',
{"USER_EMAIL":client.email,"login":True,'VERTEX_DETAIL':client,'flows':flows,'VERTEX_ID':client.id},
context_instance=RequestContext(req... | t))
# Create your views here.
|
sbergot/python | efront/test/testTarget.py | Python | bsd-3-clause | 696 | 0.002874 | import unittest
from efront import repo
from mock import Mock
class TestTarget(unittest.TestCase):
def setUp(self):
self.target = repo.Target("myTarget")
self.target | .root_names = ["git", "svn"]
def test_print_svn(self):
self.target.add("svn")
self.assertEqual(str(self.target), " svn myTarget")
def test_print_git(self):
self.target.add("git")
self.assertEqual(str(self.target), "git myTarget")
de | f test_print_both(self):
self.target.add("git")
self.target.add("svn")
self.assertEqual(str(self.target), "git svn myTarget")
if __name__ == '__main__':
unittest.main()
|
DarioGT/docker-carra | src/protoExt/views/protoActionAction.py | Python | mit | 3,186 | 0.015066 | # -*- coding: utf-8 -*-
from protoLib.getStuff import getDjangoModel
from protoExt.utils.utilsWeb import JsonError , doReturn
from . import validateRequest
import json
from django.contrib.admin.sites import site
from protoExt.utils.utilsBase import traceError
def protoExecuteAction(request):
""" Ejecuta una ... | action(cBase.modelAdmin, request, Qs , cBase.parameters)
return doReturn (returnObj)
except Exc | eption as e:
traceError()
return JsonError( str(e) )
def doAdminDetailAction( request, cBase ):
for action in cBase.modelAdmin.actions:
if action.__name__ == cBase.actionName:
break
if not action:
return JsonError( 'Action notFound')
try:
returnObj =... |
adrianogil/SublimeUnityIntel | unityparser/csharp/csharp_reference.py | Python | mit | 147 | 0 | class CSharpReference():
def __init__(self,):
self.refere | nce_object = None
self.line_ | in_file = -1
self.file_name = ''
|
SohKai/ChronoLogger | web/flask/lib/python2.7/site-packages/openid/extensions/__init__.py | Python | mit | 117 | 0 | """OpenID Extension modules."""
__al | l__ = ['ax', 'pape', 'sreg']
from openid.extension | s.draft import pape5 as pape
|
imbasimba/astroquery | astroquery/solarsystem/jpl/__init__.py | Python | bsd-3-clause | 235 | 0 | # Licensed under a 3-clause BS | D style license - see LICENSE.rst
"""
astroquery.solarsystem.jpl
--------------------------
a collection of data services provided by JPL
"""
from .sbdb import *
from .horizons import *
from | . import *
|
raybrshen/pattern_recognition | noise_detection/tools/mix_wav.py | Python | apache-2.0 | 864 | 0.005787 | __author__ = 'ray'
import wave
import numpy as np
wav_1_path = "origin.wav"
wav_2_path = "clap.wav"
wav_out_path = "mixed.wav"
wav_1 = wave.open(wav_1_path, 'rb')
wav_2 = wave.open(wav_2_path, 'rb')
wav_out = wave.open(wav_out_path, 'wb')
len_1 = wav_1.getnframes()
len_2 = wav_2.getnframes()
| if len_1>len_2:
wav_out.setparams(wav_1.getpar | ams())
else:
wav_out.setparams(wav_2.getparams())
signal_1 = np.fromstring(wav_1.readframes(-1), 'Int16')
signal_2 = np.fromstring(wav_2.readframes(-1), 'Int16')
if len_1>len_2:
signal_out = np.append(signal_1[:len_2]+signal_2, signal_1[len_2:]).tostring()
elif len_2>len_1:
signal_out = np.append(signal_1... |
zetaops/ulakbus | ulakbus/services/personel/hitap/hizmet_nufus_guncelle.py | Python | gpl-3.0 | 1,651 | 0.001821 | # -*- coding: utf-8 -*-
# Copyright (C) 2015 ZetaOps Inc.
#
# This file is licensed under the GNU General Public License v3
# (GPLv3). See LICENSE.txt for details.
"""HITAP Nufus Guncelle
Hitap'a personelin Nufus bilgilerinin guncellenmesini yapar.
"""
from ulakbus.services.personel.hitap.hitap_service import Za... | hi',
'durum': 'durum',
'emekliSicilNo': 'emekli_sicil_no',
'ilkSoyad': 'ilk_soy_ad',
'kurumSicili': 'kurum_sicil',
| 'maluliyetKod': 'maluliyet_kod',
'memuriyetBaslamaTarihi': 'memuriyet_baslama_tarihi',
'sebep': 'sebep',
'soyad': 'soyad',
'tckn': 'tckn',
'aciklama': 'aciklama',
'yetkiSeviyesi': 'yetki_seviyesi',
'kurumaBaslamaTarihi': 'kuruma... |
bl4ckdu5t/registron | tests/interactive/test_pyqt4.py | Python | mit | 1,490 | 0.00472 | # -*- coding: utf-8 -*-
#-----------------------------------------------------------------------------
# Copyright (c) 2013, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License with exception
# for distributing bootloader.
#
# The full license is in the file COPYING.txt, dist... | .setWindowTitle("Hello World from PyQt4")
#self.resize(500, 300)
self.show()
def sizeHint(self):
return self.label.sizeHint()
def keyPressEvent(self, event):
if event.key() == QtCore.Qt.Key_Escape:
self.close()
def main():
app = Qt.QApplication(sys.argv)
r... | print("Qt4 plugin paths: " + unicode(list(app.libraryPaths())))
print("Qt4 image read support: " + read_formats)
print('Qt4 Libraries path: ' + unicode(QtCore.QLibraryInfo.location(QtCore.QLibraryInfo.LibrariesPath)))
ex = MyDialog()
app.exec_()
if __name__ == "__main__":
main()
|
Python3Development/KodiAPI | api.py | Python | gpl-3.0 | 3,710 | 0 | from functools import wraps
from flask import Flask, request, jsonify, g
import base64
import libs.db_connector as dbconn
import libs.db_query as dao
import libs.json_keys as jkey
import libs.json_builder as jparse
import config.api_config as apiconf
# region constants
DEBUG = True
LOCAL_NETWORK = "0.0.0.0"
V = apicon... | offset = int(request.args.get('offset', 0))
amount = int(request.args.get('amount', 20))
rows = dao.get_recently_played(db(), offset, amount)
return response(jparse.parse_recently_played(rows))
@app.route("/api/" + V + "/shows/mark", methods=['POST'])
@requires_authorization
def mark_shows():
data = r... | api/" + V + "/seasons/mark", methods=['POST'])
@requires_authorization
def mark_seasons():
data = request.get_json()
success = dao.mark_seasons(db(False), data)
return response({"success": success})
@app.route("/api/" + V + "/episodes/mark", methods=['POST'])
@requires_authorization
def mark_episodes():
... |
prakashksinha/playground | bookmarks/models.py | Python | apache-2.0 | 1,100 | 0.012727 | # import needed models
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
# Create you | r models here.
# create user object
class Person(User):
internal_id = models.CharField(max_length=25, null=True, blank=True)
verified = models.NullBooleanField(default=False)
approval_date = models.DateTimeField(null=True, blank=True)
# create list object
class List(models.Model):
name... | = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now=True)
links = models.ManyToManyField("Link")
def __str__(self):
return self.name
# create link object
class Link(models.Model):
name = models.CharField('Link Name', max_length... |
mdmintz/SeleniumBase | seleniumbase/fixtures/words.py | Python | mit | 4,708 | 0 | # -*- coding: utf-8 -*-
''' Small Dictionary '''
class SD:
def translate_in(language):
words = {}
words["English"] = "in"
words["Chinese"] = "在"
words["Dutch"] = "in"
words["French"] = "dans"
words["Italian"] = "nel"
words["Japanese"] = "に"
words["K... | = "タイトルを確認"
words["Korean"] = "제목 확인"
words["Portuguese"] = "VERIFICAR TÍTULO"
words["Russian"] = "ПОДТВЕРДИТЬ НАЗВАНИЕ"
words["Spanish"] = "VERIFICAR TÍTULO"
return words[language]
def translate_assert_no_404_errors(language):
words = {}
words["English"] = "... | s["Chinese"] = "检查断开的链接"
words["Dutch"] = "CONTROLEREN OP GEBROKEN LINKS"
words["French"] = "VÉRIFIER LES LIENS ROMPUS"
words["Italian"] = "VERIFICARE I COLLEGAMENTI"
words["Japanese"] = "リンク切れを確認する"
words["Korean"] = "끊어진 링크 확인"
words["Portuguese"] = "VERIFICAR SE HÁ LIN... |
benoitc/couchdbkit | couchdbkit/schema/properties.py | Python | mit | 35,449 | 0.003836 | # -*- coding: utf-8 -
#
# This file is part of couchdbkit released under the MIT license.
# See the NOTICE for more information.
""" properties used by Document object """
import decimal
import datetime
import re
import time
try:
from collections import MutableSet, Iterable
def is_iterable(c):
retur... | d:
raise BadValueError("Property %s is required." % self.name)
else:
if self.choices and value is not None:
if isinstance( | self.choices, list): choice_list = self.choices
if isinstance(self.choices, dict): choice_list = self.choices.keys()
if isinstance(self.choices, tuple): choice_list = [key for (key, name) in self.choices]
if value not in choice_list:
rai... |
mr-niels-christensen/finna-be-octo-archer | briefme/src/main/rdflib/plugins/parsers/notation3.py | Python | gpl-2.0 | 61,070 | 0.002554 | #!/usr/bin/env python
u"""
notation3.py - Standalone Notation3 Parser
Derived from CWM, the Closed World Machine
Authors of the original suite:
* Dan Connolly <@@>
* Tim Berners-Lee <@@>
* Yosi Scharf <@@>
* Joseph M. Reagle Jr. <[email protected]>
* Rich Salz <[email protected] | >
http://www.w3.org/2000/1 | 0/swap/notation3.py
Copyright 2000-2007, World Wide Web Consortium.
Copyright 2001, MIT.
Copyright 2001, Zolera Systems Inc.
License: W3C Software License
http://www.w3.org/Consortium/Legal/copyright-software
Modified by Sean B. Palmer
Copyright 2007, Sean B. Palmer.
Modified to work with rdflib by Gunnar Aastrand ... |
jendap/tensorflow | tensorflow/python/data/experimental/kernel_tests/restructured_dataset_test.py | Python | apache-2.0 | 3,111 | 0.004179 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | e_list is None:
self.assertIs(None, shape.ndims)
else:
self.assertEqual(expected_shape_list, shape.as_list())
fail_cases = [((i32, dtypes.int64, i32), None),
((i32, i32, i32, i32), None),
| ((i32, i32, i32), ((None, None), None)),
((i32, i32, i32), (None, None, None, None)),
((i32, i32, i32), (None, [None], [21, 30]))]
for new_types, new_shape_lists in fail_cases:
with self.assertRaises(ValueError):
# pylint: disable=protected-access
n... |
zmetcalf/fusionbox-demo-project | adaptive/models.py | Python | gpl-3.0 | 558 | 0 | import widgy
from widgy.models import Content
from widgy.utils import update_context, render_to_string
@widgy.register
class Adaptive(Content):
def render(self, context):
template = 'widgy/adaptive/render.html'
size = context.get('device_info')
if size['type'] == 'tablet':
t... | elif size['type'] == 'phone':
template = 'widgy/adaptive/phone.html'
| with update_context(context, {'self': self}):
return render_to_string(template, context)
|
tkaitchuck/nupic | external/linux64/lib/python2.6/site-packages/PIL/GifImagePlugin.py | Python | gpl-3.0 | 10,996 | 0.003183 | #
# The Python Imaging Library.
# $Id: GifImagePlugin.py 2134 2004-10-06 08:55:20Z fredrik $
#
# GIF file handling
#
# History:
# 1995-09-01 fl Created
# 1996-12-14 fl Added interlace support
# 1996-12-30 fl Added animation support
# 1997-01-05 fl Added write support, fixed local colour map bug
# 1997-02-23 fl ... | 004 by Secret Labs AB
# Copyright (c) 1995-2004 by Fredrik Lundh
#
# See the README file for information on usage and redistribution.
#
__version__ = "0.9"
import Image, ImageFile, ImagePalette
# --------------------------------------------------------------------
# Helpers
def i16(c):
return ord(c | [0]) + (ord(c[1])<<8)
def o16(i):
return chr(i&255) + chr(i>>8&255)
# --------------------------------------------------------------------
# Identify/read GIF files
def _accept(prefix):
return prefix[:6] in ["GIF87a", "GIF89a"]
##
# Image plugin for GIF images. This plugin supports both GIF87 and
# GIF89 ... |
ravyg/algorithms | python/22_generateParentheses.py | Python | gpl-3.0 | 529 | 0.009452 | class Solution(object):
def generateParenthesis(self, n):
if n < 1: return []
parens=[]
def generate(p, left, right):
if left:
generate(p + '(', left-1, right)
if right > left:
generate(p + ')', left, right-1)
| if not right: # Base Condition.
parens.append(p),
return parens
output = generate('', n, | n)
return output
n=3
obj = Solution()
output = obj.generateParenthesis(n)
print(output)
|
Redder/Weather-App-Python | Weather.py | Python | mit | 4,583 | 0.031857 | '''
Name: Weather Application
Author: Redder04
Extra Requirements: Unirest, Mashape Key
Unirest: http://unirest.io/
Mashape: https://www.mashape.com/
Description: This application will connect to a Mashape Weather API. The user will
supply a City or State (I might add GPS Capabilites later) and send the request. The ... | ["high"]
L1 = data[0]["low"]
L2 = data[1]["low"]
L3 = data[2]["low"]
L4 = data[3]["low"]
L5 = data[4]["low"]
L6 = data[5]["low"]
L7 = data[6]["low"]
C1 = data[0]["condition"]
C2 = data[1]["condition"]
C3 = data[2]["condition"]
C4 = data[3]["condition"]
C5 = data[4]["condition"]
C6 = data[5][... | 'High: ' + H1)
print('Low: ' + L1)
print('================================')
print('\n')
print('================================')
print(DOW2)
print('Condition: ' + C2)
print('High: ' + H2)
print('Low: ' + L2)
print('================================')
print('\n')
print('===========================... |
adambrenecki/django | django/db/backends/oracle/base.py | Python | bsd-3-clause | 40,557 | 0.001381 | """
Oracle database backend for Django.
Requires cx_Oracle: http://cx-oracle.sourceforge.net/
"""
from __future__ import unicode_literals
import decimal
import re
import platform
import sys
import warnings
def _setup_environment(environ):
# Cygwin requires some special voodoo to set the environment variables
... | )
fmt = "(%s %s INTERVAL '%s %02d:%02d:%02d.%06d' DAY(%d) TO SECOND(6))"
return fmt % (sql, connector, days, hours, minutes, seconds,
timedelta.microseconds, day_precision)
def date_trunc_sql(self, lookup_type, field_name):
# http://docs.oracle.com/cd/B19306_01/server.102/b1... | if lookup_type in ('year', 'month'):
return "TRUNC(%s, '%s')" % (field_name, lookup_type.upper())
else:
return "TRUNC(%s)" % field_name
# Oracle crashes with "ORA-03113: end-of-file on communication channel"
# if the time zone name is passed in parameter. Use interpolation... |
alexaverill/make-snake | snake/game.py | Python | gpl-2.0 | 3,912 | 0.000256 | #!/usr/bin/env python
# game.py
#
# Copyright (C) 2013, 2014 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
#
import stage
import gameloop
import math
import random
import config
import gamestate as gs
direction = (0, 0)
lastPos = (0, 0)
snake = []
speed = 1
ap... | ore
try:
if score > gs.state['highest_score']:
gs.state['highest_score'] = score
except Exception:
pass
# adjust total number of apples
try:
gs.state['total_number_of_apples'] += 1
except Exception:
pass
def moveSnake():
global grow, lastPos
la... | ake):
if i == 0:
x = part[0] + speed * direction[0]
y = part[1] + speed * direction[1]
else:
x = last_unchanged[0]
y = last_unchanged[1]
last_unchanged = (snake[i][0], snake[i][1])
snake[i] = (x, y)
if grow:
snake.append(last_... |
marwahaha/python-fundamentals | challenges/04-Functions/B_script_conventions.py | Python | apache-2.0 | 610 | 0 | # A funny, but common thing you'll see in python scipts is that if __name__ ...
# block below
# To start off, just run this script and see what happens.
# Then run the test and note that it fails in a curious way!
print "I was run - maybe by a test?"
if __name__ == '__main__':
# The problem is that this variab... | to be defined OUTSIDE the if
# __name__ block. Can you move it above where it will be | picked up by the
# test?
# Don't forget to fix the indentation!
module_var = "I am totally defined"
print "I'm being run directly"
print "And module_var is:", module_var
|
tomcounsell/Cobra | apps/public/views/custom_order.py | Python | gpl-2.0 | 4,294 | 0.015137 | import json
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from apps.admin.utils.exception_handling import ExceptionHandler
from apps.commission.models import Commission
from apps.seller.models.product import Product
from settings.people import support_team
import re
from apps... | t = int(round((product.weight * 1.05) + 100)) #add 5% + 100grams
response = {'display_price_estimate': product.display_price}
product.pk = None #DO NOT SAVE!!!
return HttpResponse(json.dumps(response | ), content_type='application/json')
else:
return HttpResponse(status=500)
except Exception as e:
ExceptionHandler(e, "error in product.custom_order_estimate")
return HttpResponse(str(e), status=500)
@csrf_exempt
def request(request): #todo: change function name
if request.method == 'POST' and ... |
wheelcms/wheelcms_axle | wheelcms_axle/actions.py | Python | bsd-2-clause | 3,462 | 0.003177 | from .registry import Registry
from drole.types import Permission
def action(f):
"""
mark a method as being an action.
"""
if isinstance(f, Permission):
def decorator(decorated):
decorated.action = True
decorated.permission = f
return decorated
re... | """
Action resolution is as follows:
- A handler is registered on an action and optionally a spoke and
path
- spoke and path have to match if specified
if there are no entries at all, find a handler on the spoke
itself.
To consid... | al (geld in iedere context)
- voor bepaalde spoke
- voor bepaald path
- spoke en path
Vervolgens zoek je een handler in die context. Als je een nauwkeurige
context specificeert, dan verwacht
Een action die op path P en spoke S geregistreerd is ma... |
dvklopfenstein/PrincetonAlgorithms | py/AlgsSedgewickWayne/testcode/order.py | Python | gpl-2.0 | 768 | 0.041667 | #!/usr/bin/env python
import sys
def run_277853s():
N = 1
while N<16384:
run_277853(N)
N = N*2
def run_277853(N):
cnt = 0
#for (int i = 1; i*i <= N; i = i*2)
i = 1
while i*i <= N:
cnt += 1
print(N, i, cnt)
i = i*4
#print "{:> | 5}=N {:>5}=cnt".format(N, cnt)
def run_605062s():
N = 1
while N<4096:
run_605062(N)
N = N*2
def run_605062(N):
"""N^(1/2).
The body of inner loop is executed 1 + 2 + 4 + 8 + ... + sqrt(N) ~ 2 sqrt(N)
"""
cnt = 0
#for (int i = 1; i*i <= N; i = i*2)
i = 1
while i <= N:
#for (int j = 0; ... | #print i, j, cnt
#print i
i = i*2
print("{:>5}=N {:>5}=cnt".format(N, cnt))
if __name__ == '__main__':
run_277853s()
|
prestona/qpid-proton | tests/java/shim/curl.py | Python | apache-2.0 | 1,678 | 0.004768 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | S OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License
#
from org.apache.qpid.proton.messenger.impl import Address
def pn_url():
return Address()
def pn_url_parse(urlstr):
return Address(urlstr)
def pn_... | return url.getUser()
def pn_url_get_password(url): return url.getPass()
def pn_url_get_host(url): return url.getHost() or None
def pn_url_get_port(url): return url.getPort()
def pn_url_get_path(url): return url.getName()
def pn_url_set_scheme(url, value): url.setScheme(value)
def pn_url_set_username(url, value): url.s... |
Azure/azure-sdk-for-python | sdk/iothub/azure-mgmt-iothub/azure/mgmt/iothub/v2016_02_03/aio/operations/_iot_hub_resource_operations.py | Python | mit | 67,149 | 0.004914 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | odel=error, error_format=ARMErrorFormat)
deserialized = self._deserialize | ('IotHubDescription', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}'} # type: ignore
as... |
weka-io/easypy | easypy/properties.py | Python | bsd-3-clause | 1,878 | 0.002662 | """
This module is about 'property' descriptors.
"""
import sys
from functools import wraps
from easypy.caching import cached_property # public import, for back-compat
_builtin_property = property
def safe_property(fget=None, fset=None, fdel=None, doc=None):
"""
A pythonic property which raises a RuntimeE... | xception, another exception occurred:
...
Traceback (most recent call last):
...
RuntimeError: Attribute | error within a property (blap)
"""
if fget is not None:
@wraps(fget)
def callable(*args, **kwargs):
try:
return fget(*args, **kwargs)
except AttributeError:
_, exc, tb = sys.exc_info()
raise RuntimeError("Attribute error wi... |
talbrecht/pism_pik06 | test/regression/test_29.py | Python | gpl-3.0 | 4,068 | 0.009095 | #!/usr/bin/env python
import subprocess, shutil, shlex, os
from sys import exit, argv
from netCDF4 import Dataset as NC
import numpy as np
def process_arguments():
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument("PISM_PATH")
parser.add_argument("MPIEXEC")
parser.a... | nly the constant yield stress model works without till";
pism_overrides.default_tauc = 1e6;
pism_overrides.default_tauc_doc = "set default to 'high tauc'";
nc.close()
def run_pism(opts):
cmd = "%s %s/pismr -config_override testPconfig.nc -boot_file inputforP_regression.nc -Mx %d -My %d -Mz 11 -Lz 400... | d -report_mass_accounting -y 0.08333333333333 -max_dt 0.01 -no_mass -energy none -stress_balance ssa+sia -ssa_dirichlet_bc -o end.nc" % (opts.MPIEXEC, opts.PISM_PATH, 21, 21)
print cmd
subprocess.call(shlex.split(cmd))
def check_drift(file1, file2):
nc1 = NC(file1)
nc2 = NC(file2)
stored_drift = ... |
andbof/plantdb | qr/functions.py | Python | gpl-2.0 | 4,614 | 0.007152 | from PyQRNative import *
from PIL.Image import BILINEAR, BICUBIC, ANTIALIAS, NEAREST
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import portrait, A4
from reportlab.lib.units import cm, mm
from StringIO import StringIO
from plant.tag import create_tag
import time
from datetime import datetime
QR_TY... | r_lxma | rgin': 1*cm, 'qr_rxmargin': 1*cm, 'qr_ymargin': 5.0*cm, 'created': True, 'paired': False},
'Sticky labels 70x37mm':
{'qr_size': 2.5*cm, 'qr_lxmargin': 0.50*cm, 'qr_rxmargin': 0.50*cm, 'qr_ymargin': 1.2*cm, 'created': False, 'paired': False},
'Sticky labels 70x37mm (paired)':
... |
stonekyx/binary | vendor/scons-local-2.3.4/SCons/Tool/m4.py | Python | gpl-3.0 | 2,309 | 0.003898 | """SCons.Tool.m4
Tool-specific initialization for m4.
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 - 2014 The SCons Foundation
#
# Permission is hereby granted, free of charge, to a... | son obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or | sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRA... |
atlas0fd00m/CanCat | cancat/vstruct/defs/windows/win_6_3_i386/ntdll.py | Python | bsd-2-clause | 239,574 | 0.002162 | # Version: 6.3
# Architecture: i386
# CompanyName: Microsoft Corporation
# FileDescription: NT Layer DLL
# FileVersion: 6.3.9600.17031 (winblue_gdr.140221-1952)
# InternalName: ntdll.dll
# LegalCopyright: Microsoft Corporation. All rights reserved.
# OriginalFilename: ntdll.dll
# ProductName: Microsoft Windows Operati... | NtPostCreateKey = 11
REG_NOTIFY_CLASS.RegNtPreOpenKey = 12
REG_NOTIFY_CLASS.RegNtPostOpenKey = 13
REG_NOTIFY_CLASS.RegNtKeyHandleClose = 14
REG_NOTIFY_CLASS.RegNtPreKeyHandleClose = 14
REG_NOTIFY_CLASS.RegNtPostDeleteKey = 15
REG_NOTIFY_CLASS.RegNtPostSetValueKey = 16
REG_NOTIFY_CLASS.RegNtPostDeleteValueKey = 17
REG_N... | 21
REG_NOTIFY_CLASS.RegNtPostQueryKey = 22
REG_NOTIFY_CLASS.RegNtPostQueryValueKey = 23
REG_NOTIFY_CLASS.RegNtPostQueryMultipleValueKey = 24
REG_NOTIFY_CLASS.RegNtPostKeyHandleClose = 25
REG_NOTIFY_CLASS.RegNtPreCreateKeyEx = 26
REG_NOTIFY_CLASS.RegNtPostCreateKeyEx = 27
REG_NOTIFY_CLASS.RegNtPreOpenKeyEx = 28
REG_NOTI... |
nrgaway/qubes-tools | builder-tools/libs/say-1.4.2/test/test_styling.py | Python | gpl-2.0 | 4,257 | 0.005168 |
from say import *
from say.styling import StyleDef
import six
def test_basic_styling():
fmt = Fmt()
assert fmt('this', style='green+underline') == six.u('\x1b[32;4mthis\x1b[0m')
assert fmt('this', style='bold+red') == six.u('\x1b[31;1mthis\x1b[0m')
def test_readme_example():
fmt = Fmt()
fmt.st... | fmt.style(bwu2='blue+white+underline')
assert fmt(x, style='bwu') == fmt(x, style='blue+white+underline')
assert fmt(x, style='bwu') == fmt(x, style='bwu2')
def test_Relative():
assert Relative(4) == 4
assert Relative(+4) == Relative(4)
assert Relative(-5) == -5
as | sert Relative(0) == 0
assert Relative(1) + Relative(2) == Relative(3)
assert Relative(1) + 2 == 3
assert 1 - Relative(1) == 0
assert Relative(2) - Relative(-1) == Relative(3)
assert Relative(5) - Relative(2) == Relative(3)
assert 1 + Relative(2) == 3
assert repr(Relative(4)) == 'Relative(+4)... |
edsu/twarc | utils/media2warc.py | Python | mit | 8,273 | 0.003143 | #!/usr/bin/env python
"""
This utility extracts media urls from tweet jsonl.gz and save them as warc records.
Warcio (https://github.com/webrecorder/warcio) is a dependency and before you can use it you need to:
% pip install warcio
You run it like this:
% python media2warc.py /mnt/tweets/ferguson/tweets-0001.jsonl... | ox
https://github.com/internetarchive/warc | prox/blob/master/warcprox/dedup.py
"""
def __init__(self):
self.file = os.path.join(args.archive_dir,'dedup.db')
def start(self):
conn = sqlite3.connect(self.file)
conn.execute(
'create table if not exists dedup ('
' key varchar(300) primary key,'
... |
tedlee/markov | markovgen.py | Python | mit | 2,709 | 0.032484 | """
What
-----
A Markov Chain is a sequence of values where the next value
depends only on the current value (and not past values). It's
basically a really simple state machine, where given the present
state, the future state is conditionally independent of the past.
Thus we can ask the question: Given the present ... | random
# Class for generating markov chain
class Markov(object):
def __init__(self, open_file):
# Simple dict cache
self.cache = {}
self.open_file = open_file
# Grabs all the words from the file
self.words = self.file_to_words()
# Verifys number of words in corpus
self.word_size = len(self.words)
... | elf.database()
# Function that grabs all the words from the given file
def file_to_words(self):
self.open_file.seek(0)
data = self.open_file.read()
words = data.split()
return words
def triples(self):
""" Generates triples from the given data string. So if our string were
"What a lovely day", we'd... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.