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 |
|---|---|---|---|---|---|---|---|---|
iRGBit/QGIS | python/plugins/processing/algs/qgis/Dissolve.py | Python | gpl-2.0 | 6,208 | 0.001611 | # -*- coding: utf-8 -*-
"""
***************************************************************************
Dissolve.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
******************************... | ools import vector, dataobjects
class Dissolve(GeoAlgorithm):
INPUT = 'INPUT'
OUTPUT = 'OUTPUT'
FIELD = 'FIELD'
#==========================================================================
#def getIcon(self):
# return QtGui.QIcon(os.path.dirname(__file__) + "/icons/dissolve.png")
#=====... | i(
self.getParameterValue(Dissolve.INPUT))
vproviderA = vlayerA.dataProvider()
fields = QgsFields()
fieldname = self.getParameterValue(Dissolve.FIELD)
try:
fieldIdx = vlayerA.fieldNameIndex(fieldname)
field = vlayerA.fields().field(fieldname)
... |
jasonwee/asus-rt-n14uhp-mrtg | src/lesson_application_building_blocks/atexit_sys_exit.py | Python | apache-2.0 | 172 | 0.005814 |
impo | rt atexit
import sys
def all_done():
print('all_done()')
print('Registering')
atexit.register(all_done)
print('Registered')
print('Exiting. | ..')
sys.exit()
|
fvalverd/AutoApi | auto_api/__init__.py | Python | mit | 2,932 | 0 | # -*- coding: utf-8 -*-
from flask import Flask
from flask.views import http_method_funcs
from .auth import secure
from .config import config_autoapi
from .messages import message
from .operations import invalid_operation, login, logout, password, roles, user
from .views import get, post, delete, put, patch
class Au... | Customize routes
self.prefix = self.__class__.__name__
self.load_more_routes()
# AutoApi rest routes
self.prefix = 'AutoApi'
self.load_api_rest()
def welcome(self):
return message('Wel | come to AutoApi.')
def _name(self, view):
return '{prefix}.{name}'.format(prefix=self.prefix, name=view.__name__)
def add(
self, path, view, api=None, skip_auth=False,
method='POST', role=None, all_methods=False, no_api=False
):
"""" Bind path with view on AutoApi """
... |
home-assistant/home-assistant | tests/components/mqtt/test_device_trigger.py | Python | apache-2.0 | 43,669 | 0.001305 | """The tests for MQTT device triggers."""
import json
import pytest
import homeassistant.components.automation as automation
from homeassistant.components.device_automation import DeviceAutomationType
from homeassistant.components.mqtt import _LOGGER, DOMAIN, debug_info
from homeassistant.helpers import device_regist... | m homeassistant.helpers.trigger import async_initialize_triggers
from homeassistant.setup import async_setup_component
from tests.common import (
assert_lists_same,
async_fire_mqtt_message,
async_get_device_automations,
async_mock_service,
mock_device_registry,
mock_registry,
)
from tests.compo... | test.fixture
def device_reg(hass):
"""Return an empty, loaded, registry."""
return mock_device_registry(hass)
@pytest.fixture
def entity_reg(hass):
"""Return an empty, loaded, registry."""
return mock_registry(hass)
@pytest.fixture
def calls(hass):
"""Track calls to a mock service."""
return... |
MikaelSchultz/dofiloop-sentinel | sentinel/device/urls.py | Python | mit | 1,788 | 0.001119 | from django.conf.urls import url
from .views import *
urlpatterns = [
url(r'^(?P<command>[A-Za-z0-9]+)$',
view=IndexView.as_view(), name='index'),
url(r'^$', view=IndexView.as_view(), name='index'),
url(r'^add/$',view=DeviceAddView.as_view(), name='add'),
url(r'^(?P<device_id>[0-9]+)/remove/$'... | onfigureNetwork | InterfaceView.as_view(),
name='configure_network_interfaces'),
url(r'^(?P<device_id>[0-9]+)/configure/partitions/$',
view=DeviceConfigurePartitionsView.as_view(),
name='configure_partitions'),
url(r'^(?P<device_id>[0-9]+)/details/$',
view=DeviceDetailView.as_view(),
name=... |
nonZero/demos-python | src/examples/short/systems_programming/os_chdir.py | Python | gpl-3.0 | 399 | 0.002506 | #!/usr/bin/python2
'''
This example shows how to use the os chdir command.
Note that an exception is thrown if a directory name which cannot be
changed to is supplied (bad name, access problem and more).
'''
import os # for chdir, system
|
# a wrong directory on purpose...
try:
os.chdir('/tmp | i')
except:
print('yes, got an exception for a bad directory')
os.chdir('/tmp')
os.system('ls')
|
amagdas/superdesk | server/apps/archive/archive_link.py | Python | agpl-3.0 | 2,628 | 0.001522 | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
from flask i... | _item['_id']]
def _validate_link(self, target, target_id):
"""
Validates the article to be linked
:param target: article to be linked
:param target_id: id of the article to be linked
:raises: SuperdeskApiError
"""
if not target:
raise SuperdeskApi... | raise SuperdeskApiError.badRequestError("Takes can't be created for an Item having Embargo")
if get_resource_service('published').is_rewritten_before(target['_id']):
raise SuperdeskApiError.badRequestError(message='Article has been rewritten before !')
|
abstract-open-solutions/l10n-italy | l10n_it_vat_registries/account_tax_registry.py | Python | agpl-3.0 | 1,452 | 0 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015 Agile Business Group
# (<http://www.agilebg.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the L... | e details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#
from openerp import models, fields
class AccountTaxRegistry(models.Model):
_name = 'account.tax.registry'
name = fields.Char('Name', requir... | 'account.tax.registry'))
journal_ids = fields.One2many(
'account.journal', 'tax_registry_id', 'Journals', readonly=True)
type = fields.Selection([
('customer', 'Customer Invoices'),
('supplier', 'Supplier Invoices'),
('corrispettivi', 'Corrispettivi'),
], 'Layout', req... |
edisonlz/fruit | web_project/base/site-packages/django/contrib/admin/sites.py | Python | apache-2.0 | 18,705 | 0.001818 | from functools import update_wrapper
from django.http import Http404, HttpResponseRedirect
from django.contrib.admin import ModelAdmin, actions
from django.contrib.admin.forms import AdminAuthenticationForm
from django.contrib.auth import logout as auth_logout, REDIRECT_FIELD_NAME
from django.contrib.contenttypes impor... | a model is abstract, this will raise ImproperlyConfigured.
"""
if not admin_class:
admin_class = ModelAdmin
if isinstance(model_or_iterable, ModelBase):
model_or_iterable = [model_or_iterable]
for model in model_or_iterable:
if model._meta.abstract:
... | 'cannot be registered with admin.' % model.__name__)
if model in self._registry:
raise AlreadyRegistered('The model %s is already registered' % model.__name__)
# Ignore the registration if the model has been
# swapped out.
if not model... |
google-research/google-research | cnn_quantization/tf_cnn_benchmarks/test_data/create_cifar10_test_data.py | Python | apache-2.0 | 2,409 | 0.004981 | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Vers | ion 2.0 (the "License");
# yo | u 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 ... |
culots/meld | meld/diffutil.py | Python | gpl-2.0 | 18,634 | 0.000161 | # Copyright (C) 2002-2006 Stephen Kennedy <stevek@gnome.org>
# Copyright (C) 2009, 2012-2013 Kai Willadsen <kai.willadsen@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either vers... | one:
return None
def _find_blank_lines(txt, lo, hi):
while lo < hi and not txt[lo]:
lo += 1
while lo < hi and not txt[hi - 1]:
hi -= 1
ret | urn lo, hi
tag = chunk.tag
c1, c2 = _find_blank_lines(texts[pane1], chunk[1], chunk[2])
c3, c4 = _find_blank_lines(texts[pane2], chunk[3], chunk[4])
if c1 == c2 and c3 == c4:
return None
if c1 == c2 and tag == "replace":
tag = "insert"
elif c3 == c4 and tag == "replace":
... |
lfalvarez/django-candidator | runtests.py | Python | mit | 638 | 0.003135 | #!/usr/bin/env python
import sys
from django.conf import settings
import django
if not settings.configured:
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'testing_settings'
from distutils.version import StrictVersion
if not Str | ictVersion(djan | go.get_version()) < StrictVersion("1.8"):
django.setup()
from django.test.utils import get_runner
def runtests():
test_runner_klass = get_runner(settings)
test_runner = test_runner_klass(verbosity=1, interactive=True, failfast=False)
failures = test_runner.run_tests(['candidator', ])
sys.exit... |
fotinakis/sentry | src/sentry/tsdb/inmemory.py | Python | bsd-3-clause | 6,068 | 0.001154 | """
sentry.tsdb.inmemory
~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import six
from collections import Counter, defaultdict
from django.utils import timezone
from sentry.uti... | equency_series(self, model, items, start, end=None, rollup=None):
rollup, series = self.get_optimal_rollup_se | ries(start, end, rollup)
results = {}
for key, members in items.items():
result = results[key] = []
source = self.frequencies[model][key]
for timestamp in series:
scores = source[self.normalize_ts_to_rollup(timestamp, rollup)]
result.a... |
jesah/leaflet_webgl | webserver.py | Python | gpl-2.0 | 407 | 0.007371 | from http.se | rver import SimpleHTTPRequestHandler, HTTPServer
from socketserver import ThreadingMixIn
import threading
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
"""Handle requests in a separate thread."""
if __name__ == '__main__':
server = ThreadedHTTPServer(('localhost', 8000), SimpleHTTPRequestHandler)
... | arting server, use <Ctrl-C> to stop')
server.serve_forever()
|
rlugojr/rekall | rekall-core/rekall/plugins/core.py | Python | gpl-2.0 | 39,315 | 0.00056 | # Rekall Memory Forensics
# Copyright (C) 2012 Michael Cohen
# Copyright 2013 Google Inc. All Rights Reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, ... | oup(0))
text = line[leading_space:]
# First line is always included.
if not paragraph:
paragraph = [text]
first_line = True
first_line_indent = leading_space
continue
if first_line and last_leading_space !... | eading_space != last_leading_space:
if paragraph:
yield paragraph, first_line_indent
paragraph = []
if text:
paragraph.append(text)
last_leading_space = leading_space
first_line_indent = leading_spac... |
openaid-IATI/OIPA | OIPA/iati/migrations/0025_auto_20180830_1637.py | Python | agpl-3.0 | 525 | 0.001905 | # Generated by Django 2.0.6 on 2018-08-30 16: | 37
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('iati', '0024_auto_20180830_1232'),
]
operations = [
migrations.AlterField(
model_name='resultindicatorperiodtargetcomment',
name... | atorPeriod'),
),
]
|
rcbops/nova-buildpackage | nova/api/openstack/compute/contrib/cloudpipe.py | Python | apache-2.0 | 5,929 | 0.000169 | # Copyright 2011 Openstack, 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 agreed... | s = "os-cloudpipe"
namespace = "http://docs.openstack.org/compute/ext/cloudpipe/api/v1.1"
updated = "2011-12-16T00:00:00+00:00"
def get_resources(self):
resources = []
res = extensions.ResourceExtension('os-cloudpipe',
| CloudpipeController())
resources.append(res)
return resources
|
jasonost/clinicaltrials | trial_criteria/StanfordPOStagging.py | Python | mit | 1,663 | 0.006615 | from bs4 import Beauti | fulSoup
import httplib, codecs, datetime
import cPickle as pickl | e
import time
def stan_tag(criteria, server):
tagged = []
file_count = 47
for ix, c in enumerate(criteria[2250000:]):
# initialize list of sentences
sents = []
try:
# send text to server
server.request('', c)
res = BeautifulSoup(server.getrespons... |
ragavvenkatesan/Convolutional-Neural-Networks | yann/special/gan.py | Python | mit | 41,157 | 0.018247 | """
Support for the implementation from
Goodfellow, Ian, Jean Pouget-Abadie, Mehdi Mirza, Bing Xu, David Warde-Farley, Sherjil Ozair,
Aaron Courville, and Yoshua | Bengio. "Generative adversarial nets." In Advances in Neural Information
Processing Systems, pp. 2672-2680. 2014.
TODO:
There seems to be something wrong with the fine-tuning update. Code crashes after a call to
_new_era. This needs debugging and fixing.
"""
import time
import numpy
import theano.tensor as T... | False
if progressbar_installed is True:
import progressbar
from yann.network import network
from yann.core.operators import copy_params
class gan (network):
"""
This class is inherited from the network class and has its own methods modified in support of gan
networks.
Todo:
Sumith Chintala... |
legoktm/mtirc | tests/main.py | Python | mit | 4,313 | 0.001855 | #!/usr/bin/env python
"""
Copyright (C) 2013 Legoktm
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publi... | 0310 \x0302http://en.wikipedia.org/w/index.php?diff=560860840&oldid=560857945\x03 \x035*\x03 \x030337.98.125.156\x03 \x035*\x03 (+179) \x0310/* After the Islamic Revolution */\x03'
| self.action = u'\x0314[[\x0307Special:Log/abusefilter\x0314]]\x034 hit\x0310 \x0302\x03 \x035*\x03 \x030382.93.10.193\x03 \x035*\x03 \x031082.93.10.193 triggered [[Special:AbuseFilter/260|filter 260]], performing the action "edit" on [[\x0302Jack Dorsey\x0310]]. Actions taken: Disallow ([[Special:AbuseLog/8932011|... |
danleyb2/Instagram-API | InstagramAPI/src/http/Response/MediaInfoResponse.py | Python | mit | 1,452 | 0.000689 | from InstagramAPI.src.http.Response.Objects.Comment import Comment
from .Objects.User import User
from .Response import Response
class MediaInfoResponse(Response):
def __init__(self, response):
self.taken_at = None
self.image_url = None
self.like_count = None
self.likers = None
... | ment(com | ment))
self.comments = comments
else:
self.setMessage(response['message'])
self.setStatus(response['status'])
self.setFullResponse(response)
def getTakenTime(self):
return self.taken_at
def getImageUrl(self):
return self.image_url
def get... |
crashlytics/aurora | src/test/python/apache/aurora/client/test_config.py | Python | apache-2.0 | 9,093 | 0.006049 | #
# 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 ... |
}
bio = BytesIO(bad_config)
with pytest.raises(AuroraConfig.InvalidConfig) as cm:
get_auro | ra_config('hello_world', bio).job()
assert 'Unexpected unbound refs' in str(cm.value.message)
def test_get_config_select():
bio = BytesIO(MESOS_CONFIG_WITHOUT_ANNOUNCE)
get_aurora_config(
'hello_world',
bio,
select_env='test',
select_role='john_doe',
select_cluster='test-cluster')... |
jancespivo/apicaller | setup.py | Python | apache-2.0 | 869 | 0 | # -*- coding: utf-8 -*-
from setuptools import setup
NAME = "apicaller"
DESCRIPTION = "APICaller makes the creating API client library easier."
AUTHOR = "Jan Češpivo"
AUTHOR_EMAIL = "jan.cespivo@gmail.com"
URL = "https://github.com/cespivo/apicaller"
VERSION = '0.1.2a'
setup(
name=NAME,
| version=VERSION,
description=DESCRIPTION,
author=AUTHOR,
author_email=AUTHOR_EMAIL,
license="Apache 2.0",
url=URL,
py_modules=['apicaller'],
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Intended Au | dience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
],
install_requires=[
"requests>=2.4.3",
],
)
|
jlmadurga/django-oscar | src/oscar/apps/address/admin.py | Python | bsd-3-clause | 371 | 0 | from django.contrib import admin
from osc | ar.core.loading import get_model
class UserAddressAdmin(admin.ModelAdmin):
readonly_fields = ('num_orders',)
class CountryAdmin(admin.ModelAdmin):
searc | h_fields = ('name',)
admin.site.register(get_model('address', 'useraddress'), UserAddressAdmin)
admin.site.register(get_model('address', 'country'), CountryAdmin)
|
smlacombe/sageo | app/forms/view.py | Python | gpl-3.0 | 5,955 | 0.005877 | #
# Copyright (C) 2013 Savoir-Faire Linux Inc.
#
# This file is part of Sageo
#
# Sageo 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 optio... | .iteritems():
if ha | sattr(filt_obj, 'form_def') and filt_obj.form_def:
cols = filt_obj.get_col_def()
for col_id in range(0, len(cols)):
setattr(ViewFiltersForm, cols[col_id].name, filt_obj.form_def[col_id])
class ViewForm(ModelForm, TranslatedForm):
class Meta:
model = View
columns = ModelFi... |
azjps/bokeh | bokeh/models/callbacks.py | Python | bsd-3-clause | 3,093 | 0.00194 | """ Client-side interactivity. """
from __future__ import absolute_import
from types import FunctionType
from ..model import Model
from ..util.dependencies import import_required
from ..util.compiler import nodejs_compile, CompilationError
from ..core.properties import abstract
from ..core.properties import Dict, In... | =args)
args = Dict(String, Instance(Model), help="""
A mapping of names to Bokeh plot objects. These objects are made
available to the c | allback code snippet as the values of named
parameters to the callback.
""")
code = String(default="", help="""
A snippet of JavaScript code to execute in the browser. The
code is made into the body of a function, and all of of the named objects in
``args`` are available as parameters that the ... |
mfem/PyMFEM | mfem/_par/nonlinearform.py | Python | bsd-3-clause | 14,566 | 0.008788 | # This file was automatically generated by SWIG (http://www.swig.org).
# Version 4.0.2
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info as _swig_python_version_info
if _swig_python_version_info < (2, 7, 0):
raise Runtime... | gs)
def GetBdrFaceIntegrators(self):
r"""GetBdrFaceIntegrators(NonlinearForm self) -> mfem::Array< mfem::NonlinearFormIntegrator * > const &"""
return _nonlinearform.NonlinearForm_GetBdrFaceIntegrators(self)
GetBdrFaceIntegrators = _swig_new_instance_method(_nonlinearform.NonlinearForm_GetBdrF... | rray bdr_attr_is_ess, Vector rhs=None)"""
return _nonlinearform.NonlinearForm_SetEssentialBC(self, bdr_attr_is_ess, rhs)
SetEssentialBC = _swig_new_instance_method(_nonlinearform.NonlinearForm_SetEssentialBC)
def SetEssentialVDofs(self, ess_vdofs_list):
r"""SetEssentialVDofs(NonlinearForm self,... |
sim-x/simx | simx/core/OutputStream.py | Python | lgpl-2.1 | 1,732 | 0.018476 | # Copyright (c) 2012. Los Alamos National Security, LLC.
# This material was produced under U.S. Government contract DE-AC52-06NA25396
# for Los Alamos National Laboratory (LANL), which is operated by Los Alamos
# National Security, LLC for the U.S. Department of Energy. The U.S. Government
# has rights to use, rep... | lf.output_str = StringIO()
# define output stream writer method
# sim_obj should be derived from either PyEntity or PyService
def write(self,sim_obj,record_type,*message):
for token in message:
self.output_str.write(str(token));
self.output_str.write(" ");
... | .output_str.truncate(0)
# create output stream
output = OutputStream()
|
kaneod/physics | python/esc_tools.py | Python | gpl-3.0 | 45,419 | 0.019287 | ################################################################################
#
# esc_tools.py
#
# Library of electronic-structure related code - updated version of esc_lib.
#
################################################################################
#
# Copyright 2014 Kane O'Donnell
#
# This library is fr... | ]
else:
return eV / 27.21138505
def hartree2eV(hartree):
""" eV = hartree2eV(hartree)
Converts hartree to eV, conversion factor 1 eV = 1.0 / 27.21138505 Ht
"""
if type(hartre | e) == type([]):
return [hartree2eV(x) for x in hartree]
else:
return hartree * 27.21138505
def eV2rydberg(eV):
""" rydberg = eV2rydberg(eV)
Converts eV to rydberg, conversion factor 1 Ht = 13.6 eV
"""
if type(eV) == type([]):
r |
pdellaert/ansible | lib/ansible/modules/cloud/vmware/vmware_host_facts.py | Python | gpl-3.0 | 12,620 | 0.001506 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2017, Wei Gao <gaowei3@qq.com>
# Copyright: (c) 2018, Ansible Project
#
# 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... | s C(vsphere).
type: list
required: False
version_adde | d: '2.10'
extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = r'''
- name: Gather vmware host facts
vmware_host_facts:
hostname: "{{ esxi_server }}"
username: "{{ esxi_username }}"
password: "{{ esxi_password }}"
register: host_facts
delegate_to: localhost
- name: Gather vmware host ... |
AtteqCom/zsl | src/zsl/resource/model_resource.py | Python | mit | 19,715 | 0.001877 | """
:mod:`zsl.resource.model_resource` -- REST for a DB model.
----------------------------------------------------------
Resources provide a way how to directly access DB tables (raw models) and
perform CRUD operations upon them. The default classes of the models should be
overridden to provide more logic or restrict... | self._args:
self._args[' | fields'] = self._args['fields'].split(',')
# we can pass related fields with this, ensure its in 'related' union of two lists
self._args['related'] = list(
set(self._args.get('related', [])) | set(related_from_fields(self._args['fields'])))
@property
def params(self):
... |
AjabWorld/ajabsacco | ajabsacco/core/migrations/0008_auto_20150508_0631.py | Python | apache-2.0 | 2,861 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.contrib.postgres.fields.hstore
class Migration(migrations.Migration):
dependencies = [
('core', '0007_auto_20150508_0617'),
]
operations = [
migrations.AddField(
... | ,
name='meta',
field=django.contrib.postgres.fields.hstore.HStoreField(null=True),
),
migrations.AddField(
model_name='security',
name='meta',
field=django.contrib.postgres.fields.hstore.HStoreField(null=True),
),
migrations.Add... | django.contrib.postgres.fields.hstore.HStoreField(null=True),
),
migrations.AlterField(
model_name='generalledgeraccount',
name='meta',
field=django.contrib.postgres.fields.hstore.HStoreField(null=True),
),
migrations.AlterField(
model_name... |
SUSE/azure-sdk-for-python | azure-mgmt-resource/azure/mgmt/resource/resources/v2016_09_01/models/deployment.py | Python | mit | 1,018 | 0 | # 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 ... | ---
from msrest.serialization import Model
class Deployment(M | odel):
"""Deployment operation parameters.
:param properties: The deployment properties.
:type properties: :class:`DeploymentProperties
<azure.mgmt.resource.resources.v2016_09_01.models.DeploymentProperties>`
"""
_validation = {
'properties': {'required': True},
}
_attribute_... |
jodal/comics | comics/comics/gunnerkrigg.py | Python | agpl-3.0 | 793 | 0.001261 | from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "Gunnerkrigg Court"
language = "en"
url = "http://www.gunnerkrigg.com/"
start_date = "2005-08-13"
rights = "Tom Siddell"
class Crawler(CrawlerBa... | rc*="/comics/"]')
text = ""
for content in page.text('table[cellpadding="5"] td', allow_multiple=True):
text += content + "\n\n"
text = text.strip()
return CrawlerImage(url, | title, text)
|
PatrickCmd/Yummy-Recipes-App | tests/test_app.py | Python | mit | 2,276 | 0.007909 | import unittest
from classes.app import App
from classes.user import User
class TestAppCase(unittest.TestCase):
def setUp(self):
self.app = App()
self.user = User('pwalukagga@gmail.com', 'pato123', 'Patrick',
'Walukagga')
def test_signup_user_is_created(self):
... | , 'Henry',
'Kato')
self.app.signup_user(self.user)
self.assertEqual(len(self.app.users), 2)
self.user = User('henry@ymail.com', 'henry0009', 'Henry',
'Mutunji')
self.app.si | gnup_user(self.user)
self.assertEqual(len(self.app.users), 3)
def test_signin_user_logins_successfully(self):
self.app.signup_user(self.user)
self.user = User('pwalukagga@gmail.com', 'pato123')
self.assertEqual(self.app.signin_user(self.user), 1)
def test_signin_user_lo... |
cparawhore/ProyectoSubastas | store/views.py | Python | mit | 2,791 | 0.029022 | from django.shortcuts import render_to_response
from django.views.generic import CreateView
from store.models import cloud_users
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse_lazy
from ... | ame=usuario,email=email,password=password_one)
u.save()
return render_to_response('thanks_register.html',context_instance=RequestContext(r | equest))
else:
ctx = {'form':form}
return render_to_response('signup.html',ctx,context_instance=RequestContext(request))
ctx = {'form':form}
return render_to_response('signup.html',ctx,context_instance=RequestContext(request)) |
AnishShah/tensorflow | tensorflow/python/training/session_manager_test.py | Python | apache-2.0 | 32,877 | 0.009095 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | from __future__ import division
from __future__ import print_function
import os
from tensorflow.python.client import session as session_lib
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.framework import errors_impl
from tensorflow.python.framework... | m tensorflow.python.platform import gfile
from tensorflow.python.platform import test
from tensorflow.python.training import checkpoint_management
from tensorflow.python.training import saver as saver_lib
from tensorflow.python.training import server_lib
from tensorflow.python.training import session_manager
class Se... |
sirrice/dbtruck | dbtruck/__init__.py | Python | mit | 46 | 0 |
__a | ll__ = ['dbload', 'parse | rs', 'exporters']
|
pmart123/security_id | tests/test_validation.py | Python | bsd-2-clause | 5,859 | 0.001195 | from unittest import TestCase
import pytest
from cymbology.validation import val_check_digit, length_error_message
from cymbology import Isin, Cusip, Sedol
from cymbology.exceptions import (InvalidCharacterError, CheckDigitError, CheckSumError,
CountryCodeError, LengthError, NullErro... |
@pytest.mark.parametrize('input', ['30303M102', '09062X103'])
def test_char_cusip(input):
assert Cusip().validate(input) == input
@pytest.mark.parametrize('input,expected', [('30303M | 102', True), ('30303M101', False)])
def test_is_valid(input, expected):
assert Cusip().is_valid(input) == expected
def test_cusip_country_code_error():
with pytest.raises(CountryCodeError):
Cusip().validate('I0303M109')
# --------------------------------------------------------------
# helper tests
... |
Mrs-X/PIVX | test/functional/feature_uacomment.py | Python | mit | 1,480 | 0.004054 | #!/usr/bin/env python3
# Copyright (c) 2017 T | he Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the -uacomment option."""
from test_framework.test_framework import PivxTestFramework
from test_framework.util import assert_equal
class Uacomment... | self):
self.log.info("test multiple -uacomment")
test_uacomment = self.nodes[0].getnetworkinfo()["subversion"][-12:-1]
assert_equal(test_uacomment, "(testnode0)")
self.restart_node(0, ["-uacomment=foo"])
foo_uacomment = self.nodes[0].getnetworkinfo()["subversion"][-17:-1]
... |
flipjack/tecnoservicio | tecnoservicio/ordenes/apps.py | Python | bsd-3-clause | 113 | 0.017699 | from django | .apps import AppConfig
class UsersConfig(AppConfig):
name = 'users'
| verbose_name = "Usuarios" |
MattNolanLab/ei-attractor | grid_cell_model/analysis/clustering.py | Python | gpl-3.0 | 5,770 | 0.003466 | '''
Simple clustering techniques.
Classes
---------
.. autosummary::
ClusteredData
MergedClusters
ThresholdClusters
'''
import numpy as np
import collections
from abc import ABCMeta, abstractmethod
import logging
_logger = logging.getLogger(__name__)
class ClusteredData(collections.Sequence):
''... | f):
ret = ""
for idx, c in enumerate(self):
ret += "Cluster {0}: {1}\n".format(idx, c)
return ret
class MergedClusters(ClusteredData):
'''
Result of a c | lustering procedure in which clusters have been merged.
'''
def __init__(self, data, _clusters, parent):
ClusteredData.__init__(self, data, _clusters)
self._parent = parent
@property
def parent(self):
return self._parent
class ThresholdClusters(ClusteredData):
def __init_... |
PhdDone/AD3 | python/example.py | Python | lgpl-3.0 | 2,817 | 0.000355 | import matplotlib.pyplot as plt
import numpy as np
from ad3 import simple_grid, general_graph
def example_binary():
# generate trivial data
x = np.ones((10, 10))
x[:, 5:] = -1
x_noisy = x + np.random.normal(0, 0.8, size=x.shape)
x_thresh = x_noisy > .0
# create unaries
unaries = x_noisy
... | ow(x_thresh, interpolation='nearest')
plt.subplot(235, title="cut_simple")
plt.imshow(result, interpolation='nearest')
plt.subplot(236, title="cut_from_graph")
plt.imshow(result_graph.reshape(x.shape), interpolation='nearest')
plt.show()
def example_multinomial():
# generate dataset with th | ree stripes
np.random.seed(4)
x = np.zeros((10, 12, 3))
x[:, :4, 0] = 1
x[:, 4:8, 1] = 1
x[:, 8:, 2] = 1
unaries = x + 1.5 * np.random.normal(size=x.shape)
x = np.argmax(x, axis=2)
unaries = unaries
x_thresh = np.argmax(unaries, axis=2)
# potts potential
pairwise_potts = 2 *... |
pculture/mirovideoconverter3 | mvc/__main__.py | Python | gpl-3.0 | 289 | 0 | if __name__ == "__main__":
try:
from mvc.ui.widgets import Applica | tion
except ImportError:
from mvc.ui.console import Application
| from mvc.widgets import app
from mvc.widgets import initialize
app.widgetapp = Application()
initialize(app.widgetapp)
|
apache/incubator-airflow | tests/providers/google/cloud/operators/test_dataflow_system.py | Python | apache-2.0 | 14,915 | 0.00228 | #
# 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... | "dataflow",
"flex-template",
"build",
GCS_FLEX_TEMPLATE_TEMPLATE_PATH,
"--image",
GCR_FLEX_TEMPLATE_IMAGE,
"--sdk-language",
"JAVA",
| "--metadata-file",
f.name,
]
)
# Create a Pub/Sub topic and a subscription to that topic
self.execute_cmd(["gcloud", "pubsub", "topics", "create", PUBSUB_FLEX_TEMPLATE_TOPIC])
self.execute_cmd(
[
"gcloud",
... |
jsproull/kriek | kriek/globalsettings/tests.py | Python | gpl-2.0 | 357 | 0.019608 | from | django.test import TestCase
# Create your tests here.
from kriek.globalsettings.models import GlobalSettings
class GlobalSettingsTestCase(TestCase):
def setUp(s | elf):
GlobalSettings.objects.create(key='UNITS', value='metric')
def test_defaults(self):
units = GlobalSettings.objects.get_setting('UNITS').value
self.assertEqual(units, 'metric') |
hazelmollusk/anansi | web/views.py | Python | gpl-2.0 | 2,285 | 0.018818 | from django.views.generic import TemplateView, ListView, DetailView, DeleteView, UpdateView, CreateView
from django.db.models.loading import get_models
from ..models import *
class DashView(TemplateView):
template_name = 'anansi/dash.html'
def get_context_data(self, **kwargs):
context = super(DashView,... | _types'] = [
(m.__name__, m._meta.verbose_name.title())
for m in get_models()
if issubclass(m, Collector) and m is not Collector
]
return context
class CollectorDetailView(NameDetailView): model = Collector
class CollectorUpdateView(Up | dateView): model = Collector
class CollectorCreateView(CreateView): model = Collector
class CollectorDeleteView(DeleteView): model = Collector
class LibraryListView(ListView): model = Library
class LibraryDetailView(NameDetailView): model = Library
class LibraryUpdateView(UpdateView): model = Library
class LibraryCrea... |
Distrotech/scons | test/Flatten.py | Python | mit | 2,713 | 0.004423 | #!/usr/bin/env python
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
... | ['file2a.in', 'file2b.in'])
print list(map(str, Flatten(['begin', f1, 'middle', f2, 'en | d'])))
print list(map(str, env.Flatten([f1, [['a', 'b'], 'c'], f2])))
SConscript('SConscript', "env")
""")
test.write(['work', 'SConscript'], """
Import("env")
print Flatten([1, [2, 3], 4])
print env.Flatten([[[[1], 2], 3], 4])
""")
test.write('file1.in', "file1.in\n")
test.write('file2a.in', "file2a.in\n")
test.writ... |
jcu-eresearch/Edgar | importing/edgar_importing/birdlife_shapefile_import.py | Python | bsd-3-clause | 8,026 | 0.001994 | import csv
import argparse
import json
import logging
import textwrap
from edgar_importing import db
from edgar_importing import ala
from geoalchemy import WKTSpatialElement
import geoalchemy.functions
import sqlalchemy
import shapely.wkt
from shapely.geometry import Polygon, MultiPolygon
# map of BLA categories to db... | continue
taxon_spno = int(row['SpNo'])
if taxon_spno in taxons:
raise RuntimeError('Duplicate SpNo: ' + str(taxon_spno))
| species_name = row['SpSciName']
if species_name in translations:
_log.info('Translating species "%s" into "%s"', species_name,
translations[species_name])
species_name = translations[species_name]
species = ala.species_for_scientific... |
wxgeo/geophar | wxgeometrie/geolib/tests/test_cercles.py | Python | gpl-2.0 | 4,490 | 0.004232 | # -*- coding: utf-8 -*-
from math import sqrt, sin, cos
from random import random
from pytest import XFAIL
from tools.testlib import assertAlmostEqual, assertEqual
from wxgeometrie.geolib import (Cercle_points, Cercle_diametre, Cercle_rayon, Demicercle,
Arc_oriente, Arc_points, Label_... | ertAlmostEqual(a.centre.coordonnees, (122.51970100911581, -114.11725498641933))
def test_Arc_oriente():
A = Point(-1.2561, 45.236)
B = Point(251.2561, 41.256)
C = Point(-42.25, 2.351)
a = Arc_oriente(A, B, C)
assert(A in a)
assert(B in a)
assert(C in a)
assertAlmostEqual(a.longueur, 120... | A = Point(-1.2561, 45.236)
B = Point(251.2561, 41.256)
c = Demicercle(A, B)
assertAlmostEqual(Milieu(A, B).coordonnees, c.centre.coordonnees)
assertAlmostEqual(c.diametre, Segment(A, B).longueur)
assertAlmostEqual(c.rayon, Segment(A, B).longueur/2)
def test_Cercle_rayon():
A = Point(-2.586, 7.... |
enixdark/rabbitmq-py | ria/load_bal/cluster_producer.py | Python | mit | 1,208 | 0.062914 | import json
import sys, time
from config import *
from rb import AMQP
from optparse import OptionParser
if __name__ == "__main__":
opt_parse = OptionParser()
opt_parse.add_option('-m', '--message', dest = 'message',
help = "message to send to rabbit server")
opt_parse.add_option('-b', '--host', dest = 'hostname'... | -port', dest = 'port',
help = "port server")
opt_parse.add_option('-u', '--user', dest = 'username',
help = "username")
opt_parse.add_option('-P', '--pass', dest = 'pasword',
help = "pasword")
params = opt_parse.parse_args()[0]
if params.hostname == None and len(sys.argv) > 1:
params = urlparse(sys.argv... | lse USERNAME
PASSWORD = params.pasword if params.password != None else PASSWORD
except:
pass
AMQP_HOST = params.hostname
AMQP_PORT = int(params.port)
msg = json.dumps({"content": "Cluster Sending test", "time" : time.time()})
amqp = AMQP(USERNAME,PASSWORD,AMQP_HOST,AMQP_PORT,PATH)
amqp.connect()
amqp.send(me... |
skosukhin/spack | var/spack/repos/builtin/packages/xphelloworld/package.py | Python | lgpl-2.1 | 2,024 | 0.000988 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | neral Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suit | e 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class Xphelloworld(AutotoolsPackage):
"""Xprint sample applications."""
homepage = "http://cgit.freedesktop.org/xorg/app/xphelloworld"
url = "https://www.x.org/archive/... |
indictranstech/erpnext | erpnext/agriculture/doctype/soil_texture/test_soil_texture.py | Python | agpl-3.0 | 518 | 0.015444 | # -*- coding: utf-8 -*-
# Copyright (c) 2017, Frappe Technolog | ies Pvt. Ltd. and Contributors
# See license.txt
from __future__ import unicode_literals
import frappe
import unittest
class TestSoilTexture(unittest.TestCase):
def test_texture_selection(self):
soil_tex = frappe.get_all('Soil Texture', fields=['name'], filters={'collection_datetime': '2017-11-08'})
doc = frappe... | 'Silt Loam') |
StealthMicro/OctoPi-Makerbot | env/Lib/site-packages/flask_principal/__init__.py | Python | agpl-3.0 | 13,726 | 0.000219 | # -*- coding: utf-8 -*-
"""
flask_principal
~~~~~~~~~~~~~~~
Identity management for Flask.
:copyright: (c) 2012 by Ali Afshar.
:license: MIT, see LICENSE for more details.
"""
from __future__ import with_statement
__version__ = '0.3.5'
from functools import partial, wraps
from collections impo... | Once loaded it is sent using the `identity-loaded` signal | , and should be
populated with additional required information.
Needs that are provided by this identity should be added to the `provides`
set after loading.
"""
def __init__(self, id, auth_type=None):
self.id = id
self.auth_type = auth_type
self.provides = set()
def ca... |
fairbird/OpenPLI-BlackHole | lib/python/Components/ActionMap.py | Python | gpl-2.0 | 2,554 | 0.035239 | from enigma import eActionMap
class ActionMap:
def __init__(self, contexts = [ ], actions = { }, prio=0):
self.actions = actions
self.contexts = contexts
self.prio = prio
self.p = eActionMap.getInstance()
self.bound = False
self.exec_active = False
self.enabled = True
def setEnabled(self, enabled):
... | for this complicated code.
# it's not more than converting a "documented" actionmap
# (where the values are possibly (function, help)-tuples)
# into a "classic" actionmap, where values are just functions.
# the classic actionmap is then passed to the ActionMap constructor,
# the collected helpstrings (with correc... | dict = { }
for (action, funchelp) in actions.iteritems():
# check if this is a tuple
if isinstance(funchelp, tuple):
alist.append((action, funchelp[1]))
adict[action] = funchelp[0]
else:
adict[action] = funchelp
ActionMap.__init__(self, [context], adict, prio)
parent.helpList.append((self, ... |
carquois/blobon | blobon/punns/migrations/0021_auto__add_reblog.py | Python | mit | 6,910 | 0.008394 | # -*- 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):
# Adding model 'Reblog'
db.create_table('punns_reblog', (
('id', self.gf('django.db.models.field... | .fields.URLField', [], {'max_length': '300', 'blank': 'True'}),
'status': ('djan | go.db.models.fields.CharField', [], {'max_length': '2', 'null': 'True', 'blank': 'True'}),
'tags': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['punns.Tags']", 'null': 'True', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'m... |
tanglei528/glance | glance/store/cinder.py | Python | apache-2.0 | 6,798 | 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... | icense 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.
"""Storage backend for Cinder"" | "
from cinderclient import exceptions as cinder_exception
from cinderclient import service_catalog
from cinderclient.v2 import client as cinderclient
from oslo.config import cfg
from glance.common import exception
from glance.common import utils
import glance.openstack.common.log as logging
from glance.openstack.com... |
larry16898/oms | asserts/migrations/0007_auto_20170515_1241.py | Python | mit | 996 | 0.002049 | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-05-15 04:41
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
| ('asserts', '0006_auto_20170515_1227'),
]
operations = [
migrations.CreateModel(
name='AssertCategory',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(ma... | l_name='assert',
name='category',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='assert_set', to='asserts.AssertCategory', verbose_name='资产类别'),
),
]
|
pkimber/base | example_base/tests/test_model_versioned_delete.py | Python | apache-2.0 | 2,006 | 0 | # -*- encoding: utf-8 -*-
import pytest
from django.utils import timezone
from base.model_utils import BaseError
from example_base.models import FruitCake
from login.tests.factories import UserFactory
from .factories import FruitCakeFactory
@pytest.mark.django_db
def test_factory():
FruitCakeFactory()
@pytest... | True, 1),
(19, True, 2),
(19, False, 0),
] == [(o.number, o.deleted, o.deleted_version) for o in result]
@pytest.mark.django_db
def test_set_deleted_model():
"""Standard way to delete rows from non-versioned delete mo | dels"""
obj = FruitCakeFactory()
with pytest.raises(BaseError) as e:
obj.set_deleted(UserFactory())
assert 'model with deleted version tracking' in str(e.value)
@pytest.mark.django_db
def test_undelete():
obj = FruitCakeFactory()
user = UserFactory()
FruitCake.objects.set_deleted(obj, ... |
trnewman/VT-USRP-daughterboard-drivers_python | gr-pager/src/usrp_flex.py | Python | gpl-3.0 | 7,028 | 0.015509 | #!/usr/bin/env python
#
# Copyright 2006,2007 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your op... | usrp_sink)
# Set up 22KHz-wide bandpass about center frequency. Decimate by 10
# to get channe | l rate of 25Ksps
taps = optfir.low_pass(1.0, # Filter gain
250e3, # Sample rate
11000, # One-sided modulation bandwidth
12500, # One-sided channel bandwidth
0.1, # Passband ripple
... |
epitron/youtube-dl | youtube_dl/extractor/slideshare.py | Python | unlicense | 2,132 | 0.002345 | from __future__ import unicode_literals
import re
import json
from .common import InfoExtractor
from ..compat import (
compat_urlparse,
)
from ..utils import (
ExtractorError,
get_element_by_id,
)
class SlideshareIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?slideshare\.net/[^/]+?/(?P<title>.... | 'description', fatal=False)
| return {
'_type': 'video',
'id': info['slideshow']['id'],
'title': info['slideshow']['title'],
'ext': ext,
'url': video_url,
'thumbnail': info['slideshow']['pin_image_url'],
'description': description.strip() if description else None,
... |
bjvanderweij/pymuco | pymuco/midi/parser.py | Python | gpl-2.0 | 3,303 | 0.024523 | from pymuco.midiio import *
from pymuco.midi import representation
class MidiParser(MidiOutStream.MidiOutStream):
"""
This class listens to a select few midi events relevant for a simple midifile containing a pianomelody
"""
def __init__(self, midifile):
self.midifile = midifile
self.notes_on = {}
... | ond, frame, framePart)
def time_signature(self, nn, dd, cc, bb):
self.midifile.time_signature = (nn, dd, cc, bb)
def key_signature(self, sf, mi) | :
self.midifile.key_signature = (sf, mi)
def program_name(self, data):pass
def sequencer_specific(self, data):pass
def aftertouch(self, channel=0, note=0x40, velocity=0x40):pass
def continuous_controller(self, channel, controller, value):pass
def patch_change(self, channel, patch):
self.midifile[st... |
alexgorban/models | official/nlp/bert/create_pretraining_data.py | Python | apache-2.0 | 16,735 | 0.009382 | # Copyright 2019 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... | q, rng):
"""Create `TrainingInstance`s from raw text."""
all_documents = [[]]
# Input file format:
# (1) One sentence per line. These should ideally be actual sentences, not
# entire paragraphs or arbitrary spans of text. (Because we use the
# sentence boundaries for the "next sentence prediction" task).
... | f.io.gfile.GFile(input_file, "rb") as reader:
while True:
line = tokenization.convert_to_unicode(reader.readline())
if not line:
break
line = line.strip()
# Empty lines are used as document delimiters
if not line:
all_documents.append([])
tokens... |
AlanLaughter/huehuehue | huev.1/hue.py | Python | gpl-3.0 | 3,687 | 0.014917 | #!/usr/bin/env python2
#hue interpreter v .1
#by Alan Laughter
#released under the GPL v.3
#hue is identical to brainfuck (for the moment) and is converted with the following table:
#HUE = ]
#hue = >
#huE = <
#hUe = +
#hUE = -
#Hue = .
#HuE = ,
#HUe = [
#this version cannot accept input properly however can run any o... | hich may be garbled nonsense) into individual instructions with Find_words and the instruction set
#this was originally a point of great frustration, but I found a functional function (huehuehue) online (see the module for details)
for String in strings:
for instruction in FindW(String, words = instr_set):
... | struction)
#names the current executing instruction
instr_num = 0
#these variables make looping possible
ignore = False
HUe_list = []
HUE_list = []
while(True):
#breaks the main loop when it runs out of instructions
if instr_num == len(instructions):
break
#assigns the current instruction
ins... |
pwndbg/pwndbg | pwndbg/constants/ia64.py | Python | mit | 26,808 | 0.021188 | from .constant import Constant
__NR_ni_syscall = Constant('__NR_ni_syscall',1024)
__NR_exit = Constant('__NR_exit',1025)
__NR_read = Constant('__NR_read',1026)
__NR_write = Constant('__NR_write',1027)
__NR_open = Constant('__NR_open',1028)
__NR_close = Constant('__NR_close',1029)
__NR_creat = Constant('__NR_creat',103... | cess',1049)
__NR_sync = Constant('__NR_sync',1050)
__NR_fsync = Constant('__NR_fsync',1051)
__NR_fdatasync = Constant('__NR_fdatasync',1052)
__NR_kill = Constant('__NR_kill',1053)
__NR_rename = Constant('__NR_rename',1054)
__NR_mkdir = Constant('__NR_mkdir',1055)
__NR_rmdir = Constant('__NR_rmdir',1056)
__NR_dup = Cons... | = Constant('__NR_times',1059)
__NR_brk = Constant('__NR_brk',1060)
__NR_setgid = Constant('__NR_setgid',1061)
__NR_getgid = Constant('__NR_getgid',1062)
__NR_getegid = Constant('__NR_getegid',1063)
__NR_acct = Constant('__NR_acct',1064)
__NR_ioctl = Constant('__NR_ioctl',1065)
__NR_fcntl = Constant('__NR_fcntl',1066)
... |
Lesaria/Interview | Intro2Program2.py | Python | gpl-3.0 | 502 | 0.015936 | #Intro2Program 2_6 Copyright Lesaria
#This program is aiming to find index of String B twice occurring in A. This is based on given B occured several times in A.
#Ask user for string A
aString = raw_input("Give the string A: ")
#Ask user for string | B
bString = raw_input("Give the string B: ")
#Find 1st time's index
index = aString.find(bString)
#Generate 2nd time's index
nextIndex = aString | .find(bString, (index+len(bString)))
#Print
print "The index of the 2nd occurrence of B in A is ", nextIndex
|
garrettcap/Bulletproof-Backup | wx/tools/Editra/src/ed_print.py | Python | gpl-2.0 | 6,013 | 0.003326 | ###############################################################################
# Name: ed_print.py #
# Purpose: Editra's printer class #
# Author: Cody Precord <cprecord@editra.org> #
... | eBox(_("There was an error when printing.\n"
"Check that your printer is properly connected."),
_("Printer Error"),
style=wx.ICON_ERROR|wx.OK)
printout.Destroy()
def SetColourMode(self, mode):
"""Sets the color mode tha... | her mode was set or not
@rtype: boolean
"""
if mode in COLOURMODES:
self.print_mode = mode
ret = True
else:
ret = False
return ret
def SetStc(self, stc):
"""Set the stc we are printing for
@param stc: instance of wx.stc.St... |
mmcfarland/model-my-watershed | deployment/cfn/cache_private_dns_record.py | Python | apache-2.0 | 2,548 | 0 | from boto import (
elasticache as ec,
route53 as r53
)
from majorkirby import CustomActionNode
class CachePrivateDNSRecord(CustomActionNode):
"""Represents a private DNS record for the ElastiCache cache cluster"""
INPUTS = {
'Region': ['global:Region'],
'CacheCluster': ['global:CacheC... | ster_endpoint = self.get_cache_cluster_endpoint(
self.get_ | input('CacheCluster'))
self.create_cache_private_dns_record(cache_cluster_endpoint)
def get_cache_cluster_endpoint(self, cache_cluster_id):
"""Get the first cache cluster node endpoint"""
elasticache_conn = ec.connect_to_region(self.region,
pr... |
Thylossus/tud-movie-character-insights | Server/Tools/Parser/corpusInfo.py | Python | apache-2.0 | 3,953 | 0.017202 | #!/usr/bin/python3
ci_version="0.10"
# This script is used to retrieve corpus information. It can be run after the parser
# has finished its work. The corpus information is part of the final report.
# Database connection is configured in the server configuration.
# Include custom libs
import sys
sys.path.append( '../... | )initialize movie-specific variables
movieCount+=1
characters = {}
movieCharacterCount = 0
# For every quote...
for quote in mongoDb.rawQuotes.find({'_id.movie': movie['_id']}):
# Sort the quotes into character-specific lists to be able to generate
# values for the characters
if quote['character'] in charac... | + " " + quote['text']
else:
characters[quote['character']] = quote['text']
movieCharacterCount += 1
# Calculating word counts for every character
wordCounts = {cid: len(txt.split()) for cid,txt in characters.items()}
for char, wc in wordCounts.items():
totalWordCount += wc
characterWordCounts += [wc]
... |
drnlm/sqlobject | sqlobject/util/moduleloader.py | Python | lgpl-2.1 | 1,175 | 0 | import os
import sys
from sqlobject.compat import load_module_from_file
def load_module(module_name):
mod = __import__(module_name)
components = module_name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
def load_module_from_name(filename, module_name):
if mod... | irectory %s (%s)\n'
% (os.path.dirname(filename), e))
f.write('#\n')
f.close()
if module_name in sys.modules:
return sys.modules[module_name]
if '.' in module_name:
parent_name = '.'.join(module_name.split('.')[:-1])
base_name = module_name.split('.')[-1]
... | ule_name, filename)
|
SlashRoot/WHAT | what_apps/meta/models.py | Python | mit | 1,075 | 0.013023 | from django.db import models
from django.db.models.signals import post_save
from what_apps.push.functions import push_with_json
STATUS_CHOICES = (
(0, 'coo | l'), #Everything is cool.
(1, 'not cool'), #Problems with staging only.
(2, 'fuck all.') #Problems with production.
)
class StatusLog(models.Model):
'''
A snapshot of a particular status at a particular time.
'''
created = models.DateTimeField(auto_... | l):
'''
Used only when failures require a description.
'''
incident = models.OneToOneField('meta.StatusLog')
description = models.TextField()
def update_heartbeat(sender, instance, created, **kwargs):
dict_to_push = {'id':instance.id, 'created':instance.created.isoformat()}
#push_with_j... |
tensorflow/datasets | tensorflow_datasets/text/yelp_polarity_test.py | Python | apache-2.0 | 961 | 0.003122 | # coding=utf-8
# Copyright 2022 The TensorFlow Datasets 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | r express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for yelp dataset module."""
from tensorflow_datasets import testing
from tensorflow_datasets.text import yelp_po | larity
class YelpPolarityReviewsTest(testing.DatasetBuilderTestCase):
DATASET_CLASS = yelp_polarity.YelpPolarityReviews
SPLITS = {
"train": 2,
"test": 2,
}
if __name__ == "__main__":
testing.test_main()
|
warner/magic-wormhole | src/wormhole/test/dilate/test_full.py | Python | mit | 11,999 | 0.002334 | from __future__ import print_function, absolute_import, unicode_literals
import wormhole
from twisted.internet import reactor
from twisted.internet.defer import Deferred, inlineCallbacks, gatherResults
from twisted.internet.protocol import Pro | tocol, Factory
from twisted.trial import unittest
from ..common import ServerBase, poll_until
from ..._interfaces import IDilationConnector
from ...eventual import EventualQueue
from ..._dilation._noise import NoiseConnection
APPID = u"lothar.com/dilate-test"
def doBoth(d1, d2):
return gatherResults([d1, d2], Tr... | print("dataReceived: {}".format(data))
self.factory.d.callback(data)
def connectionLost(self, why):
print("connectionLost")
class Full(ServerBase, unittest.TestCase):
@inlineCallbacks
def setUp(self):
if not NoiseConnection:
raise unittest.SkipTest("noiseprotocol un... |
schettino72/pyterm | ddemo.py | Python | mit | 2,060 | 0.002427 | """Fake output as if code was typed in an interactive interpreter
This is used to generate docs
"""
import ast
import sys
from pyterm import Term
# copy from doit.action
class Writer(object):
"""write to many streams"""
def __init__(self, *writers):
"""@param writers - file stream like objects"""
... | '\n'.join(block), '<string>', 'exec'))
block = []
if not line:
term.BOLD('>>>\n')
else:
if line[0] != ' ':
# single line or block start
try:
term.BOLD('''>>> {}\n'''.format(line))
ast.parse(line)
exec(compile(line, ... | end(line)
if block:
exec(compile('\n'.join(block), '<string>', 'exec'))
|
partofthething/home-assistant | homeassistant/components/soma/sensor.py | Python | apache-2.0 | 2,532 | 0.00079 | """Support for Soma sensors."""
from datetime import timedelta
import logging
from requests import RequestException
from homeassistant.const import DEVICE_CLASS_BATTERY, PERCENTAGE
from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle
from . import DEVICES, SomaEntity
from .const im... | sg"]
)
self.is_av | ailable = False
return
# https://support.somasmarthome.com/hc/en-us/articles/360026064234-HTTP-API
# battery_level response is expected to be min = 360, max 410 for
# 0-100% levels above 410 are consider 100% and below 360, 0% as the
# device considers 360 the minimum to move... |
teonlamont/mne-python | mne/inverse_sparse/mxne_optim.py | Python | bsd-3-clause | 46,824 | 0 | from __future__ import print_function
# Author: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
# Daniel Strohmeier <daniel.strohmeier@gmail.com>
#
# License: Simplified BSD
from math import sqrt
import numpy as np
from scipy import linalg
from .mxne_debiasing import compute_bias
from ..utils im... | rows_norm = np.sqrt((Y * Y.conj()).real.reshape(n_positions,
-1).sum(axis=1))
# Ensure shrink is >= 0 while avoiding any division by zero
shrink = np.maximu | m(1.0 - alpha / np.maximum(rows_norm, alpha), 0.0)
active_set = shrink > 0.0
if n_orient > 1:
active_set = np.tile(active_set[:, None], [1, n_orient]).ravel()
shrink = np.tile(shrink[:, None], [1, n_orient]).ravel()
Y = Y[active_set]
if shape is None:
Y *= shrink[active_set][:, n... |
buluba89/Yatcobot | yatcobot/post_queue.py | Python | gpl-2.0 | 1,933 | 0.002069 | from collections import OrderedDict
from yatcobot.plugins.filters import FilterABC
from yatcobot.plugins.ratings import RatingABC
class PostQueue(OrderedDict):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.rating_methods = RatingABC.get_enabled()
self.filte... | ()
self.update(updated_queue)
| def combine_rates(self, *rates):
"""
Combines the rates of multiple features to one final rate
:param rates: a tuple of list of scores ( [Ascore1, Ascore2], [Bscore1,Bscore2])
:return:Returns an a dict with final scores {id:Score}
"""
combined_rates = {}
for r... |
has2k1/plotnine | plotnine/stats/stat_qq.py | Python | gpl-2.0 | 2,879 | 0 | import numpy as np
import pandas as pd
from scipy.stats.mstats import plotting_positions
from ..mapping.evaluation import after_stat
from ..doctools import document
from ..exceptions import PlotnineError
from .distributions import get_continuous_distribution
from .stat import stat
# Note: distribution should be a na... | se PlotnineError(
"The number of quantile values is not the same as "
"the number of sample values.")
quantiles = np.asarray(quantiles)
cdist = get_continuous_distribution(params['distributio | n'])
theoretical = cdist.ppf(quantiles, *params['dparams'])
return pd.DataFrame({'sample': sample,
'theoretical': theoretical})
|
Chuban/moose | python/peacock/tests/utils/test_TerminalUtils.py | Python | lgpl-2.1 | 923 | 0.004334 | #!/usr/bin/env python
from peacock.utils import TerminalUtils
from peacock.utils import Testing
from PyQt5 import QtWidgets
class Tests(Testing.PeacockTester):
qapp = QtWidgets.QApplication([])
def test_convert(self):
output = "\33[1m\33[31mred <&> text\33[39m"
html_output = TerminalUtils.term... | ssertEqual('<span style="color:red;">red <&> text</span>', html_output)
output = "\n\33[1m\33[31m\nfoo\nred text\n\33[39m"
html_output = TerminalUtils.terminalOutputToHtml(output)
self.assertEqual('\n<span style="color:red;">\nfoo\nred text\n</span>', html_output)
# bad color... | "
html_output = TerminalUtils.terminalOutputToHtml(output)
self.assertEqual('<span>unknown color</span>', html_output)
if __name__ == '__main__':
Testing.run_tests()
|
simbha/mAngE-Gin | lib/django/utils/crypto.py | Python | mit | 6,880 | 0.000436 | """
Django's standard crypto functions and utilities.
"""
from __future__ import unicode_literals
import hmac
import struct
import hashlib
import binascii
import time
# Use the system PRNG if possible
import random
try:
random = random.SystemRandom()
using_sysrandom = True
except NotImplementedError:
impo... | secret (which defaults to settings.SECRET_KEY).
A different key_salt should be passed in for every application of HMAC.
"""
if secret is None:
secret = settings.SECRET_KEY
key_salt = force_bytes(key_salt)
secret = force_bytes(secret)
# We need to generate a derived key from our base ... | do this by
# passing the key_salt and our base key through a pseudo-random function and
# SHA1 works nicely.
key = hashlib.sha1(key_salt + secret).digest()
# If len(key_salt + secret) > sha_constructor().block_size, the above
# line is redundant and could be replaced by key = key_salt + secret, sin... |
GoogleCloudPlatform/healthcare | datathon/nusdatathon18/scripts/cbis_ddsm_ml/trainer/tpu_model.py | Python | apache-2.0 | 8,749 | 0.00903 | #!/usr/bin/python
#
# Copyright 2018 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 ag... | ger("batch_size", default=96,
help="Mini-batch size for the training. Note that this is the global batch "
"size and not the per-shard batch. | ")
tf.flags.DEFINE_integer("training_steps", default=1000,
help="Total number of training steps.")
tf.flags.DEFINE_integer("eval_steps", default=100,
help="Total number of evaluation steps.")
tf.flags.DEFINE_float("learning_rate", default=0.05, help="Learning rate.")
tf.flags.DEFINE_integer("iterations", default=50... |
threemeninaboat3247/raipy | register.py | Python | mit | 182 | 0.005495 | im | port os
import pypandoc
f = open('README.txt' | ,'w+')
f.write(pypandoc.convert_file('README.md', 'rst'))
f.close()
os.system("python setup.py sdist upload")
os.remove('README.txt')
|
sirikata/sirikata | scripts/test/cdn_screenshot_eval.py | Python | bsd-3-clause | 836 | 0.013158 | import sys
import os
from colormath.color_objects import LabColor, RGBColor
from PIL import Image
def rgb_to_lab(img_data):
return [RGBColor(r,b,g).convert_to('lab') for (r,g,b) in img_data]
def compute_difference(lab1, lab2):
return sum([l1.delta_e(l2, mode='cie1976') for (l1, l2) in zip(lab1, lab2)])
dir =... |
byte_count = tokens[1]
if(int(byte_count | ) > 0):
cur_image = Image.open(os.path.join(dir, f))
print index, byte_count, sum(RGBColor(rgbcur[0], rgbcur[1], rgbcur[2]).convert_to('lab').delta_e(labend) for (rgbcur, labend) in zip(cur_image.getdata(), end_lab))
|
egaxegax/dbCarta | tablelist/__init__.py | Python | gpl-2.0 | 24 | 0 | from tableli | st i | mport *
|
ProteinDF/ProteinDF_pytools | scripts/pdf-atom-index.py | Python | gpl-3.0 | 2,471 | 0.001619 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import proteindf_bridge as bridge
import proteindf_tools as pdf
def find_atom_index(pdfparam, atomgroup):
answer = set()
for subgrp_key, subgrp in atomgroup.groups():
subgrp_atoms = find_atom_index(pdfparam, subgrp)
answer = answer... | action="store_true",
default=False)
args = parser.parse_args()
# setting
brd_path = args.brd_path[0]
output_path = args.output[0]
verbose = args.verbose |
if args.db:
entry = pdf.PdfArchive(args.db)
atomgroup = entry.get_molecule()
elif args.param:
pdfparam = pdf.load_pdfparam(args.param)
atomgroup = pdfparam.molecule
# load brd file
find_atoms = bridge.load_atomgroup(brd_path)
find_atoms *= pdf.ANG2AU # angstrom -> ... |
Debetux/sr.ht | alembic/versions/5750db1d643_added_hide_option_to_uploads_table.py | Python | mit | 647 | 0.010819 | """added hide option to uploads table
Revision ID: 5750db1d643
Revises: 4c34ca870e0
Create Date: 2015-06-19 18:16:07.073631
"""
# revision identifiers, used by Alembic.
revision = '5750db1d643'
down_revision = '4c34ca870e0'
from alembic import op
imp | ort sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('upload', sa.Column('hidden', sa.Boolean(), nullable=False, server_default="False"))
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###... | )
### end Alembic commands ###
|
bdcht/amoco | amoco/system/linux64/x64.py | Python | gpl-2.0 | 6,623 | 0.000604 | # -*- coding: utf-8 -*-
# This code is part of Amoco
# Copyright (C) 2006-2011 Axel Tillequin (bdcht3@gmail.com)
# published under GPLv2 license
from amoco.system.elf import *
from amoco.system.core import CoreExec, DefineStub
from amoco.code import tag
import amoco.arch.x64.cpu_x64 as cpu
# AMD 64 specific definiti... | p.state[cpu.r12] = cpu.cst(0, 64)
p.state[cpu.r13] = cpu.cst(0, 64)
p.state[cpu.r14] = | cpu.cst(0, 64)
p.state[cpu.r15] = cpu.cst(0, 64)
p.state[cpu.rflags] = cpu.cst(0, 64)
# create the stack space:
if self.ASLR:
p.state.mmap.newzone(p.cpu.rsp)
else:
stack_base = 0x00007FFFFFFFFFFF & ~(self.PAGESIZE - 1)
stack_size = 2 * self.PA... |
josiah14/linear-algebra | programming-the-matrix/1-week/vec/vec.py | Python | mit | 6,607 | 0.006206 | # version code 24ea27 | 739109+
coursera = 1
# Please fill out this stencil and submi | t using the provided submission script.
# Copyright 2013 Philip N. Klein
def getitem(v,k):
"""
Return the value of entry k in v.
Be sure getitem(v,k) returns 0 if k is not represented in v.f.
>>> v = Vec({'a','b','c', 'd'},{'a':2,'c':1,'d':3})
>>> v['d']
3
>>> v['b']
0
"""
pas... |
scottbarstow/iris-python | iris_sdk/models/tndetails.py | Python | mit | 642 | 0.003115 | #!/usr/bin/env python
from __future__ import division, absolute_import, print_function
from future.builtins import super
from iris_sdk.models.base_resource import BaseResource
from iris_sdk.models.data.tndetails import TndetailsData
XML_NAME_TNDETAILS = "TelephoneNumberDetails"
XPATH_TNDETAILS = "/tndetails"
class ... | TAILS
def __init__(self, parent=None, client=None):
super()._ | _init__(parent, client)
TndetailsData.__init__(self)
def get(self):
return self._get_data() |
twitter/pants | tests/python/pants_test/backend/python/tasks/test_build_local_python_distributions_integration.py | Python | apache-2.0 | 4,312 | 0.013915 | # coding=utf-8
# Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
import glob
import os
import re
from builtins import open
from pants.util.collections im... | ed_pants_run = run_target()
self.assert_success(unmodified_pants_run)
self._assert_nation_and_greeting(unmodified_pants_run.stdout_data)
# Modify one of the source files for this target so that the output is different.
py_source_file = os.path.join(
self.hello_install_requires_dir, 'hel... | tents = f.read()
# Replace hello! with hello?
modified_contents = re.sub('!', '?', orig_contents)
with open(py_source_file, 'w') as f:
f.write(modified_contents)
modified_pants_run = run_target()
self.assert_success(modified_pants_run)
self._assert_nation_and_greeting(modifi... |
plxaye/chromium | src/chrome/common/extensions/docs/server2/object_store_creator_test.py | Python | apache-2.0 | 1,331 | 0.007513 | #!/usr/bin/env python
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license tha | t can be
# found in the LICENSE file.
import unittest
from test_object_store import TestObjectStore
from object_store_creator import ObjectStoreCreator
class _FooClass(object):
def __init__(self): pass
class ObjectStoreCreatorTest(unittest.TestCase):
def | setUp(self):
self.creator = ObjectStoreCreator(_FooClass,
'3-0',
'test',
store_type=TestObjectStore)
def testVanilla(self):
store = self.creator.Create()
self.assertEqual('3-0/_FooClass@test... |
nerdcha/escalator | escalator/scorers.py | Python | mit | 1,361 | 0.003674 | '''
Auxiliary code providing vector-valued scoring functions
for convenient use in the parameter-free Ladder Mechanism.
Original algorithm by Avrim Blum and Moritz Hardt
Python implementation by Jamie Hall and Moritz Hardt
MIT License
'''
from sklearn.utils import check_consistent_length
from functools import wraps
... | red)**2)
@validate_input
def absolute_error(y, y_pred):
return np.abs(y-y_pred)
@validate_input
def zero_one_loss(y, y_ | pred):
return np.sum(y != y_pred)
def _check_y_shapes(y_true, y_pred):
''' Check that two target vectors are compatible.
This is based on sklearn's validation in sklearn.metrics.regression._check_reg_targets
and sklearn.metrics.classification._check_targets.
'''
check_consistent_length(y_true,... |
danfairs/django-simpledb | simpledb/compiler.py | Python | bsd-3-clause | 9,054 | 0.00243 | import datetime
import logging
import sys
import uuid
from django.db.models.sql.constants import LOOKUP_SEP, MULTI, SINGLE
from django.db.models.sql.where import AND, OR
from django.db.utils import DatabaseError, IntegrityError
from django.utils.tree import Node
from functools import wraps
from boto.exception import... | assuming infinite' % (
high_mark))
reslice = high_mark
high_mark = None
# TODO: run your low-level qu | ery here
#low_mark, high_mark = self.limits
if high_mark is None:
# Infinite fetching
results = self.db_query.fetch_infinite(offset=low_mark)
if reslice:
results = list(results)[:reslice]
elif high_mark > low_mark:
# Range fetching
... |
rowhit/gitfs | tests/integrations/history/test_read.py | Python | apache-2.0 | 2,728 | 0 | # Copyright 2014 PressLabs SRL
#
# 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,... | ss TestHistoryView(BaseTest):
def test_listdirs(s | elf):
directory = os.listdir("%s/history/" % self.mount_path)
assert directory == self.get_commit_dates()
def test_listdirs_with_commits(self):
commits = self.get_commits_by_date(self.today)[::-1]
directory = os.listdir("%s/history/%s" % (self.mount_path, self.today))
assert... |
yxwzaxns/cowry | client/core/ftpClient.py | Python | mit | 11,520 | 0.002344 | from PyQt5.QtCore import pyqtSignal, QObject
from core.baseSocket import BaseSocket
from core.upload import Upload
from core.download import Download
from core.config import Settings
from core.cryptogram import Cryptogram
from core import utils
class Signal(QObject):
# def __init__(self):
# super(UploadSig... | f download(self, filehash, savefilepath):
# filename = os.path.basename(filepath)
# filesize = os.path.getsize(filepath)
# try:
# with open(filepath, 'rb') as f:
# fileHashCode = hashlib.md5(f.read()).hexdigest()
# except Exception as e:
# return (... | CmdCode)
if retInfo[0] == 1:
self.log.info(retInfo[1])
else:
retInfo = self.recvMsg()
if retInfo[0] == 1:
return (1, retInfo[1])
elif self.recvInfo['status'] == '0':
downloadAuthCode = self.recvInfo['token']
... |
Santi871/SnooHelper | standalone_bot.py | Python | mit | 381 | 0.002625 | """ Run this file to run bots as a standalone application, detached from the webapp """
from snoohelper.utils.teams import SlackTeamsController
TESTING = False
def main():
if not TESTING:
SlackTeamsCont | roller("teams.ini", 'snoohelper_master.db')
else:
SlackTea | msController("teams_test.ini", 'snoohelper_test.db')
if __name__ == "__main__":
main()
|
layuplist/layup-list | lib/constants.py | Python | gpl-3.0 | 221 | 0 | import os
CURRENT_TERM = os.environ["CURRENT_TERM"] # e.g. 16S
SUPPORT_EMAIL = "support@layuplist.com" |
REC_UPVOTE_REQ = 2
OFFERINGS_THRESHOLD_FOR_TERM_UPDATE = int(
os.environ["OFFERIN | GS_THRESHOLD_FOR_TERM_UPDATE"])
|
mohsraspi/mhscs14 | tom/hackafriendsgame.py | Python | gpl-2.0 | 163 | 0.01227 | import minecr | aft as minecraft
mc = minecraft.Minecraft.create()
friendsGame = minecraft.Minecraft.create("10.52.3.156")
friendsGame | .player.setTilePos(16,16,16)
|
jat255/hyperspyUI | hyperspyui/widgets/dataviewwidget.py | Python | gpl-3.0 | 17,266 | 0.000174 | # -*- coding: utf-8 -*-
# Copyright 2014-2016 The HyperSpyUI developers
#
# This file is part of HyperSpyUI.
#
# HyperSpyUI 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
#... | e + 1
ComponentType = QtWidgets.QTreeWidgetItem.UserType + 2
def __init__(self, main_window, parent=None):
super(DataViewWidget, self).__init__(parent)
self.main_window = main_window
self.tree = QtWidgets.QTreeWidget(self)
self.tree.header().close()
self.lut = {}
... | vbox = QtWidgets.QVBoxLayout()
vbox.addWidget(self.tree)
vbox.addLayout(self.editor)
vbox.setContentsMargins(0, 0, 0, 0)
self.setLayout(vbox)
sp = self.sizePolicy()
sp.setVerticalPolicy(QtWidgets.QSizePolicy.Expanding)
self.setSizePolicy(sp)
sp = self.t... |
dragosbdi/bitcredit-2.0 | qa/rpc-tests/invalidblockrequest.py | Python | mit | 4,244 | 0.00377 | #!/usr/bin/env python2
# Copyright (c) 2015 The Bitcredit Core developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
from test_framework.test_framework import ComparisonTestFramework
from test_framework.util import *
fr... | can spend the coinbase.
'''
test = TestInstance(sync_every_block=False)
for i in xrange(100):
block = create_block(self.tip, create_coinbase(height), self.block_time)
block.solve()
self.tip = block.sha256
self.block_time += 1
test.block... |
'''
Now we use merkle-root malleability to generate an invalid block with
same blockheader.
Manufacture a block with 3 transactions (coinbase, spend of prior
coinbase, spend of that spend). Duplicate the 3rd transaction to
leave merkle root and blockheader unchanged b... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.