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 |
|---|---|---|---|---|---|---|---|---|
embali/aiowing | aiowing/apps/admin/tests/test_admin.py | Python | mit | 2,851 | 0 | from aiohttp import ClientSession
from aiowing import settings
async def test_unauthenticated_records(test_app, test_client):
cli = await test_client(test_app)
resp = await cli.get(test_app.router['admin_records'].url(),
allow_redirects=False)
assert resp.headers.get('Location') ... | t_app)
resp = await cli.post(test_app.router['admin_login'].url(),
data={'email': settings.SUPERUSER_EMAIL,
'password': settings.SUPERUSER_PASSWORD},
allow_redirects=False)
assert resp.headers.get('Location') == \
test_a... | = await cli.get(test_app.router['admin_logout'].url(),
allow_redirects=False)
assert resp.headers.get('Location') == test_app.router['admin_login'].url()
await resp.release()
async def test_authenticated_records(test_app, test_client):
cli = await test_client(test_app)
resp = ... |
mmgen/mmgen | scripts/tx-v2-to-v3.py | Python | gpl-3.0 | 962 | 0.015593 | #!/usr/bin/env python3
# Convert MMGen 'v2' transaction file (amounts as BTCAmt())
# to MMGen 'v3' (amounts as strings)
# v3 tx files were introduced with MMGen version 0.9.7
import sys,os
repo_root = os.path.split(os.path.abspath(os.path.dirname(sys.argv[0])))[0]
sys.path = [repo_root] + sys.path
from mmgen.common i... | : "Convert MMGen transaction file from v2 format to v3 format",
'usage': "<tx file>",
'options': """
-h, --help Print this help message
-d, --outdir=d Output files to directory 'd' instead of working dir
-q, --quiet Write (and overwrite) files without prompting
-S, --stdout Write data to | STDOUT instead of file
"""
}
}
cmd_args = opts.init(opts_data)
import asyncio
from mmgen.tx import CompletedTX
if len(cmd_args) != 1:
opts.usage()
tx = asyncio.run(CompletedTX(cmd_args[0],quiet_open=True))
tx.file.write(ask_tty=False,ask_overwrite=not opt.quiet,ask_write=not opt.quiet)
|
wojcech/agilentpyvisa | agilentpyvisa/B1500/tester.py | Python | agpl-3.0 | 39,893 | 0.008623 | # vim: set fileencoding: utf-8 -*-
# -*- coding: utf-8 -*-
import visa
from itertools import cycle, starmap, compress
import pandas as pd
import numpy as np
from collections import OrderedDict
from .force import *
from .force import (
DCForce,
StaircaseSweep,
... | diagnostics(self, item):
""" from the manual:
| - before using DiagnosticItem.trigger_IO , connect a BNC cable between the Ext Trig In and
Out connectors.
- After executing DiagnosticItem.high_voltage_LED confirm the status of LED. Then enter the AB
command
If the LED does not blink, the B1500 must be repaired.
... |
pombredanne/metamorphosys-desktop | metamorphosys/META/src/Python27Packages/py_modelica/py_modelica/modelica_simulation_tools/tool_base.py | Python | mit | 12,494 | 0.002401 | # Copyright (C) 2013-2015 MetaMorph Software, Inc
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this data, including any software or models in source or binary
# form, as well as any drawings, specifications, and documentation
# (collectively "the Data"), to deal in the Data ... | ths to additional packages
lib_package_names = [] # names of additional packages
max_simulation_time = 43200 # (=12h) time threshold before simulation is aborted
## Variables with execution statistics
compilation_time = -1
translation_time = -1
make_time = -1
simu | lation_time = -1
total_time = -1
def _initialize(self,
model_config):
"""
Creates a new instance of a modelica simulation.
dictionary : model_config
Mandatory Keys : 'model_name' (str), 'model_file_name' (str)
Optional Keys : 'M... |
espressopp/espressopp | src/interaction/StillingerWeberTripleTerm.py | Python | gpl-3.0 | 8,110 | 0.006289 | # Copyright (C) 2012,2013
# Max Planck Institute for Polymer Research
# Copyright (C) 2008,2009,2010,2011
# Max-Planck-Institute for Polymer Research & Fraunhofer SCAI
#
# This file is part of ESPResSo++.
#
# ESPResSo++ is free software: you can redistribute it and/or modify
# it under the terms of the G... | f setPotential(self, type1, type2, type3, potential):
if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugrou | p():
self.cxxclass.setPotential(self, type1, type2, type3, potential)
def getPotential(self, type1, type2, type3):
if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup():
self.cxxclass.setPotential(self, type1, type2, type3)
def ... |
gbin/err-backend-discord | discordb.py | Python | gpl-3.0 | 24,430 | 0.00176 | import asyncio
import logging
import sys
import re
from abc import ABC, abstractmethod
from typing import List, Optional, Union
from discord.utils import find
from errbot.backends.base import (
Person,
Message,
Room,
RoomOccupant,
Presence,
ONLINE,
OFFLINE,
AWAY,
DND,
RoomError... | s:
raise RuntimeError("Can't invite to a non-existent channel")
for identifier in args:
if not isinstance(identifier, DiscordPerson): |
raise RuntimeError("Can't invite non Discord Users")
asyncio.run_coroutine_threadsafe(
self.discord_channel().set_permissions(
identifier.discord_user(), read_messages=True
),
loop=DiscordBackend.client.loop,
)... |
SDHM/vitess | test/schema.py | Python | bsd-3-clause | 9,880 | 0.008502 | #!/usr/bin/env python
import logging
import unittest
import os
import environment
import utils
import tablet
shard_0_master = tablet.Tablet()
shard_0_replica1 = tablet.Tablet()
shard_0_replica2 = tablet.Tablet()
shard_0_rdonly = tablet.Tablet()
shard_0_backup = tablet.Tablet()
shard_1_master = tablet.Tablet()
shard_... | n tablets:
t.create_db(db_name)
t.start_vttablet(wait_for_state=None)
| # wait for the tablets to start
shard_0_master.wait_for_vttablet_state('SERVING')
shard_0_replica1.wait_for_vttablet_state('SERVING')
shard_0_replica2.wait_for_vttablet_state('SERVING')
shard_0_rdonly.wait_for_vttablet_state('SERVING')
shard_0_backup.wait_for_vttablet_state('NOT_SERVING')
sh... |
anhstudios/swganh | data/scripts/templates/object/tangible/mission/quest_item/shared_slooni_jong_q1_needed.py | Python | mit | 477 | 0.046122 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel): |
result = Tangible()
result.template = "object/tangible/mission/quest_item/shared_slooni_jong_q1_needed.iff"
result.attribute_template_id = -1
result.stfName("loot_tals_n","slooni_jong_q1_needed")
#### BEGIN MODIFICATIONS ####
#### END MODI | FICATIONS ####
return result |
openeventdata/Focus_Locality_Extraction | Focus_Locality/Sentence_Embedding_Approach/Testing/SIFpreprocessing_test.py | Python | mit | 5,830 | 0.014923 | #!/usr/bin/env python2
# -*- coding: utf-8 -*- |
"""
Created on Fri Mar 10 11:34:46 2017
@author: maryam
"""
import nltk
import numpy | as np
import sys
from nltk.corpus import stopwords
from sklearn.decomposition import TruncatedSVD
np.seterr(divide='ignore', invalid='ignore')
#reload(sys)
#sys.setdefaultencoding("utf-8")
stop = set(stopwords.words('english'))
to_filter = [',', '?', '!', ':', ';', '(', ')', '[', ']', '{', '}', "'s",'``', '"', "'", ... |
hatbot-team/hatbot | statistics/__init__.py | Python | mit | 144 | 0 | __author__ = | 'moskupols'
__all__ = ['Statistics', 'BlackList', 'console_statistic']
from .statistics import *
from . import console_statisti | c
|
blomquisg/heat | heat/common/utils.py | Python | apache-2.0 | 10,575 | 0.000851 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of t | he National Aeronautics and Space Administration.
# 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/license | s/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitatio... |
pancho-villa/Phuey | phuey/light_cli.py | Python | mit | 1,447 | 0.002764 | from sys import stdout
import argparse
import json
import logging
from .phuey import Bridge, Light
logger = logging.getLogger()
def command_interpreter(command):
python_dict = {}
commands = command.split(',')
for c in commands:
k, v = c.split('=')
if v.lower() == "true":... | e)s-%(funcName)s/%(lineno)d - %(message)s'
formatter = logging.Formatter(fmt)
ch.setFormatter(formatter)
logger.addHandler(ch)
|
light = Light(bridge_ip, user, lid, 'my light')
logger.debug(command)
light.state = json.loads(command)
|
SciTools/iris | lib/iris/tests/unit/experimental/ugrid/mesh/test_Mesh__from_coords.py | Python | lgpl-3.0 | 9,316 | 0.000107 | # Copyright Iris contributors
#
# This file is part of Iris and is released under the LGPL license.
# See COPYING and COPYING.LESSER in the root of the repository for full
# licensing details.
"""
Unit tests for the :meth:`iris.experimental.ugrid.mesh.Mesh.from_coords`.
"""
# Import iris.tests first so that some thing... | nts=lat_orig.points, bounds=np.tile(lat_orig.bounds, 2)
)
with self.assertRaisesRegex(
ValueError, "bounds shapes are not identical"
):
_ = self.create()
self.lat = lat_orig.copy(
points=lat_orig.points[-1], bounds=lat_orig.bounds[-1]
)
... | ueError, "points shapes are not identical"
):
_ = self.create()
def test_reorder(self):
# Swap the coords.
self.lat, self.lon = self.lon, self.lat
mesh = self.create()
# Confirm that the coords have been swapped back to the 'correct' order.
self.assertEqu... |
JulienMcJay/eclock | windows/Python27/Lib/site-packages/pywin32-218-py2.7-win32.egg/Demos/security/get_policy_info.py | Python | gpl-2.0 | 1,166 | 0.023156 | import win32security,win32file,win32api,ntsecuritycon,win32con
policy_handle = win32security.GetPol | icyHandle('rupole',win32security.POLICY_ALL_ACCESS)
## mod_nbr, mod_time = win32security.LsaQueryInformationPolicy(policy_handle,win32security.PolicyModificationInformation)
## print mod_nbr, mod_time
domain_name,dns_domain_name, dns_forest_name, domain_guid, domain_sid = \
| win32security.LsaQueryInformationPolicy(policy_handle,win32security.PolicyDnsDomainInformation)
print domain_name, dns_domain_name, dns_forest_name, domain_guid, domain_sid
event_audit_info=win32security.LsaQueryInformationPolicy(policy_handle,win32security.PolicyAuditEventsInformation)
print event_audit_info
domain... |
kahliloppenheimer/Naive-Bayes-Classifier | corpus.py | Python | mit | 3,727 | 0.00161 | # -*- mode: Python; coding: utf-8 -*-
"""For the purposes of classification, a corpus is defined as a collection
of labeled documents. Such documents might actually represent words, images,
etc.; to the classifier they are merely instances with features."""
from abc import ABCMeta, abstractmethod
from csv import read... | t_class=Document):
self.documents = []
self.datafiles = glob(datafiles)
for datafile in self.datafiles:
self.load(datafile, document_class)
# Act as a mutable | container for documents.
def __len__(self): return len(self.documents)
def __iter__(self): return iter(self.documents)
def __getitem__(self, key): return self.documents[key]
def __setitem__(self, key, value): self.documents[key] = value
def __delitem__(self, key): del self.documents[key]
@abstr... |
MostlyOpen/odoo_addons | myo_summary/models/annotation.py | Python | agpl-3.0 | 1,419 | 0 | # -*- coding: utf-8 -*-
###############################################################################
#
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol
#
# This program is free sof | tware: 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 warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
#... |
bretttegart/treadmill | lib/python/treadmill/cli/admin/ldap/cell.py | Python | apache-2.0 | 6,420 | 0 | """Implementation of treadmill admin ldap CLI cell plugin.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import io
import click
from ldap3.core import exceptions as ldap_exceptions
from treadmill import admin
... | able=True))
@click.option('--status', help='Cell status')
@click.option('-m', '--manifest', help='Load cell from manifest file.',
type=click.Path(exists=True, readable=True))
@click.argument('cell')
@cli.admin.ON_EXCEPTIONS
def configure(cell, version, root, location, username, arc... | username, ssq_namespace, data, status, manifest):
"""Create, get or modify cell configuration"""
admin_cell = admin.Cell(context.GLOBAL.ldap.conn)
attrs = {}
if manifest:
with io.open(manifest, 'rb') as fd:
attrs = yaml.load(stream=fd)
if version:
... |
wh-acmer/minixalpha-acm | LeetCode/Python/binary_tree_postorder_traversal_iter.py | Python | mit | 324 | 0.006173 | #!/usr/bin/env python
#coding: utf-8
# Definition for a binary tree node
class TreeNo | de:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param root, a tree node
# | @return a list of integers
def postorderTraversal(self, root):
pass
|
BryceLohr/authentic | authentic2/attribute_aggregator/user_profile.py | Python | agpl-3.0 | 4,952 | 0.002827 | '''
VERIDIC - Towards a centralized access control system
Copyright (C) 2011 Mikael Ates
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
Licen... | if not isinstance(value, basestring) and hasattr(value,
'__iter__'):
attr['values'] = map(unicode, value)
else:
attr['values'] = [unicode(value)]
data.append(attr)
else:
logger.debug('get_attribut... | nd')
except (SiteProfileNotAvailable, ObjectDoesNotExist):
logger.debug('get_attributes: No user profile')
return None
attributes[SOURCE_NAME] = data
return attributes
|
ndparker/tdi | docs/examples/loading2.py | Python | apache-2.0 | 623 | 0.004815 | #!/usr/bin/env python
import warnings as _warnings
_warnings.resetwarnings()
_warnings.filterwarnings('error')
# BEGIN INCLUDE
import tempfile
from tdi import html
file_1 = tempfile.NamedTemporaryFile()
try:
file_2 = tempfile.NamedTemporaryFile()
try:
file_1.write("""<html lang="en"><body tdi:overlay=... | >""")
file_2.flush()
template = html.from_ | files([file_1.name, file_2.name])
finally:
file_2.close()
finally:
file_1.close()
template.render()
|
molmod/yaff | yaff/sampling/test/test_harmonic.py | Python | gpl-3.0 | 4,266 | 0.000469 | # -*- coding: utf-8 -*-
# YAFF is yet another force-field code.
# Copyright (C) 2011 Toon Verstraelen <Toon.Verstraelen@UGent.be>,
# Louis Vanduyfhuys <Louis.Vanduyfhuys@UGent.be>, Center for Molecular Modeling
# (CMM), Ghent University, Ghent, Belgium; all rights reserved unless otherwise
# stated.
#
# This file is pa... | ])
system.align_cell(lcs)
ff.update_rvecs(system.cell.rvecs)
opt = QNOptimizer(FullCellDOF(ff, gpos_rms=1e-6, grvecs_rms=1e-6))
opt.run()
rvecs0 = system.cell.rvecs.copy()
vol0 = system.cell.volume
pos0 = system.pos.copy()
e0 = ff.compute()
elastic = estimate_elastic(ff)
assert... | ert abs(rvecs0 - system.cell.rvecs).max() < 1e-10
assert abs(vol0 - system.cell.volume) < 1e-10
assert elastic.shape == (6, 6)
# Make estimates of the same matrix elements with a simplistic approach
eps = 1e-3
from nose.plugins.skip import SkipTest
raise SkipTest('Double check elastic constant ... |
nrego/westpa | src/oldtools/aframe/data_reader.py | Python | gpl-3.0 | 22,795 | 0.011099 | # Copyright (C) 2013 Matthew C. Zwier and Lillian T. Chong
#
# This file is part of WESTPA.
#
# WESTPA is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any... | _metaclass__=type
import logging, warnings
log = logging.getLogger(__name__)
import itertools, re
from itertools import imap
import nump | y, h5py
import west, westpa
from oldtools.aframe import AnalysisMixin
from west import Segment
from oldtools.miscfn import parse_int_list
class WESTDataReaderMixin(AnalysisMixin):
'''A mixin for analysis requiring access to the HDF5 files generated during a WEST run.'''
def __init__(self):
super(WEST... |
alistairlow/tensorflow | tensorflow/contrib/distributions/python/ops/bijectors/weibull_impl.py | Python | apache-2.0 | 5,615 | 0.003384 | # 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... | control_flow_ops.with_dependencies([
check_ops.assert_positive(
self._scale,
message="Argument scale was not positive")
], self._scale)
self._concentration = control_flow_ops.with_dependencies([
check_ops.assert_positive(
self._con... | s,
validate_args=validate_args,
name=name)
@property
def scale(self):
"""The `l` in `Y = g(X) = 1 - exp((-x / l) ** k)`."""
return self._scale
@property
def concentration(self):
"""The `k` in `Y = g(X) = 1 - exp((-x / l) ** k)`."""
return self._concentration
def _forward(sel... |
becxer/pytrain | test_pytrain/test_HMM/__init__.py | Python | mit | 23 | 0 | fro | m test_HMM import | *
|
AdrianGaudebert/socorro-crashstats | crashstats/auth/urls.py | Python | mpl-2.0 | 385 | 0 | from django.conf.urls.defaults i | mport patterns, url, include
from . import views
urlpatterns = patterns(
'',
url(r'^browserid/mozilla/$', views.mozilla_browserid_verify,
name='mozilla_browserid_verify'),
url(r'^browserid/$', include('django_browserid.urls')),
url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page':... | name='logout'),
)
|
qnorsten/svtplay-dl | lib/svtplay_dl/error.py | Python | mit | 1,137 | 0.002639 | # ex:ts=4:sw=4:sts=4:et
# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
from __future__ import absolute_import
class UIException(Exception):
pass
class ServiceError(Exception):
pass
class NoRequestedProtocols(UIException):
"""
This excpetion is thrown when the service provides strea... | ory parameters, requested
and found. Both should be lists. requested is the protocols
we want and found is the protocols that can be used to
access the stream.
"""
| self.requested = requested
self.found = found
super(NoRequestedProtocols, self).__init__(
"None of the provided protocols (%s) are in "
"the current list of accepted protocols (%s)" % (
self.found, self.requested
)
)
def __repr__(self):... |
suutari-ai/shoop | shuup_tests/api/test_admin.py | Python | agpl-3.0 | 1,366 | 0.000732 | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE fi | le in the root directory of this source tree.
import pytest
from shuup import configuration
from shuup.api.admin_module.views.permissions import APIPermissionView
from shuup.api.permissions import make_permission_config_key, PermissionLevel
from shuup.core import cache
from shuup.core.api.users import UserViewSet
from... | shuup.testing.utils import apply_request_middleware
def setup_function(fn):
cache.clear()
@pytest.mark.django_db
def test_consolidate_objects(rf):
get_default_shop()
# just visit to make sure GET is ok
request = apply_request_middleware(rf.get("/"))
response = APIPermissionView.as_view()(reque... |
RobbieRain/he | test.py | Python | apache-2.0 | 7 | 0.142857 | z | hangyu | |
benjyw/pants | src/python/pants/option/option_value_container_test.py | Python | apache-2.0 | 3,316 | 0.000905 | # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import unittest
from pants.option.option_value_container import OptionValueContainerBuilder
from pants.option.ranked_value import Rank, RankedValue
class OptionValueContainerTest(unitte... | self.assertEqual(1, o["foo"])
self.assertEqual(1, o.get("foo"))
self.ass | ertEqual(1, o.get("foo", 2))
self.assertIsNone(o.get("unknown"))
self.assertEqual(2, o.get("unknown", 2))
with self.assertRaises(AttributeError):
o["bar"]
def test_iterator(self) -> None:
ob = OptionValueContainerBuilder()
ob.a = RankedValue(Rank.FLAG, 3)
... |
mozilla/relman-auto-nag | auto_nag/scripts/workflow/p1_no_assignee.py | Python | bsd-3-clause | 3,281 | 0.00061 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
from libmozdata import utils as lmdutils
from auto_nag import utils
from auto_nag.bzcleaner import BzCleaner
from auto_... |
fields = ["tri | age_owner", "flags"]
params = {
"bug_type": "defect",
"include_fields": fields,
"resolution": "---",
"f1": "priority",
"o1": "equals",
"v1": "P1",
"f2": "days_elapsed",
"o2": "greaterthaneq",
"v2": self.n... |
VictorLowther/swift | swift/common/direct_client.py | Python | apache-2.0 | 18,186 | 0.001045 | # Copyright (c) 2010-2012 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 to ... | limit
if prefix:
qs += '&prefix=%s' % quote(prefix)
if delimiter:
qs += '&delimiter=%s' % quote(delimiter)
with Timeout(conn_timeout):
conn = http_connect(node[' | ip'], node['port'], node['device'], part,
'GET', path, query_string=qs)
with Timeout(response_timeout):
resp = conn.getresponse()
if not is_success(resp.status):
resp.read()
raise ClientException(
'Account server %s:%s direct GET %s gave status %s'... |
Fazer56/Assignment3 | charitysite/volunteer/urls.py | Python | mit | 352 | 0.028409 | #local u | rls.py file
from django.conf.urls import url, include
from . import views
urlpatterns = [
#url(r'^', views.appView.postLocation, name = 'postLocation'),
url(r'^volunteer/', views.appView.member, name = 'member'),
#url(r'^(?P<member_id>[0-9]+)/$', views.appView.detail, name = 'detail'),... | #url(r'^(?P<>))
]
|
WhittKinley/aima-python | submissions/Sery/vacuum2.py | Python | mit | 1,432 | 0.002095 | import agents as ag
def HW2Agent() -> object:
"An agent that keeps track of what locations are clean or dirty."
oldPercepts = [('None', 'Clean')]
oldActions = ['NoOp']
actionScores = [{
'Right': 0,
'Left': 0,
'Up': -1,
'Down': -1,
'NoOp': -100,
}]
level ... | actionScores.append({
'Righ | t': 0,
'Left': 0,
'Up': -1,
'Down': -1,
})
highest = -80
for actionType, score in actionScores[level].items():
if score > highest:
highest = score
... |
poobalan-arumugam/stateproto | src/extensions/lang/python/qhsm/testsamplehsm1.py | Python | bsd-2-clause | 1,506 | 0.003984 | import qhsm
from qhsm import QSignals, QEvent
# generated by PythonGenerator version 0.1
class TestSample1(qhsm.QHsm):
def initialiseStateMachine(self):
self.initialiseState(self.s_StateX)
def s_StateX(self, ev):
if ev.QSignal == QSignals.Entry:
self.enterStateX()
elif e... |
def s_State1(self, ev):
if ev.QSignal == "Hello":
self.sayHello2()
self.transitionTo(self.s_State0)
eli | f ev.QSignal == QSignals.Entry:
self.enterState1()
elif ev.QSignal == QSignals.Exit:
self.exitState1()
else:
return self._TopState
return None
#end of TestSample1
pass
|
spnow/grr | lib/rdfvalues/basic_test.py | Python | apache-2.0 | 6,320 | 0.005697 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2012 Google Inc. All Rights Reserved.
"""Basic rdfvalue tests."""
import time
from grr.lib import rdfvalue
from grr.lib.rdfvalues import test_base
class RDFBytesTest(test_base.RDFValueTestCase):
rdfvalue_class = rdfvalue.RDFBytes
def GenerateSample(se... | sertEqual(url.Path(), "/hunts/W:AAAAAAAA/Results/some/path")
self.assertEqual(url._urn.netloc, "")
self.assertEqual(url._urn.scheme, "aff4")
# Test that we can handle urns with a '?' and do not interpret them as
# a delimiter between url and parameter list.
str_url = "aff4:/C.0000000000000000/fs/os... | 5:])
def testInitialization(self):
"""Check that we can initialize from common initializers."""
# Empty Initializer not allowed.
self.assertRaises(ValueError, self.rdfvalue_class)
# Initialize from another instance.
sample = self.GenerateSample("aff4:/")
self.CheckRDFValue(self.rdfvalue_cl... |
openstack/nomad | cyborg/objects/attach_handle.py | Python | apache-2.0 | 3,799 | 0 | # Copyright 2019 Intel, 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 a... | rker=marker)
else:
db_ahs = cls.dbapi.attach_handle_list(context)
obj_ah_list = cls._from_db_object_list(db_ahs, context)
return obj_ah_list
def save(self, context):
"""Update an AttachHandle record in the DB"""
updates = self.obj_get_changes()
db_ahs = s... | stroy(self, context):
"""Delete a AttachHandle from the DB."""
self.dbapi.attach_handle_delete(context, self.uuid)
self.obj_reset_changes()
|
sameerparekh/pants | src/python/pants/util/fileutil.py | Python | apache-2.0 | 961 | 0.006243 | # coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function | ,
unicode_literals, with_statement)
import os
import shutil
from pants.util.contextutil import temporary_file
def atomic_copy(src, dst):
"""Copy the file src to dst, overwriting dst atomically."""
| with temporary_file(root_dir=os.path.dirname(dst)) as tmp_dst:
shutil.copyfile(src, tmp_dst.name)
os.rename(tmp_dst.name, dst)
def create_size_estimators():
def line_count(filename):
with open(filename, 'rb') as fh:
return sum(1 for line in fh)
return {
'linecount': lambda srcs: sum(line_cou... |
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_06_01/aio/operations/_ddos_protection_plans_operations.py | Python | mit | 30,431 | 0.005159 | # 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 ... | ameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
request = self._client.delete(url, query_parameters, header_parame... | ponse.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None... |
Tethik/faktura | migrations/versions/74af9cceeeaf_.py | Python | mit | 634 | 0.004732 | """empty message
Revision ID: 74af9cceeeaf
Revises: 6e7b88dc4544
Create Date: 2017-07-30 20:47:07.982489
"""
# revision identifier | s, used by Alembic.
revision = '74af9cceeeaf'
down_revision = '6e7b88dc4544'
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('customer', sa.Column('vat_number', sa.String(length=100), nullable=True))
# ### end Alemb... | )
# ### end Alembic commands ###
|
Crobisaur/HyperSpec | Python/loadData2Hdf.py | Python | gpl-3.0 | 5,400 | 0.010741 | __author__ = "Christo Robison"
import numpy as np
from scipy import signal
from scipy import misc
import h5py
from PIL import Image
import os
import collections
import matplotlib.pyplot as plt
import convertBsqMulti as bsq
import png
'''This program reads in BSQ datacubes into an HDF file'''
def loadBSQ(path = '/ho... |
#b = np | .uint8(numBands / 31)
# print(b / 31)
tempRed = labelImg[:,:,0] == 255
tempGreen = labelImg[:,:,1] == 255
tempBlue = labelImg[:,:,2] == 255
tempYellow = np.logical_and(tempRed, tempGreen)
tempPink = np.logical_and(tempRed, tempBlue)
temp = np.zeros(np.shape(tempRed))
temp[tempRed] = 1
... |
adelinastanciu/game-of-life | game.py | Python | gpl-2.0 | 5,982 | 0.010532 | import pygame
import sys
WINDOW_TITLE = "Game Of Life"
# Define some colors
BLACK = ( 0, 0, 0)
PURPLE = ( 22, 20, 48)
WHITE = (255, 255, 255)
GREEN = ( 0, 255, 0)
RED = (255, 0, 0)
BLUE = ( 67, 66, 88)
# This sets the width and height of each grid location
width = 2... | reen = pygame.display.set_mode(size)
# Set title of screen
pygame.display.set_caption(WINDOW_TITLE)
#Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen | updates
clock = pygame.time.Clock()
# -------- Main Program Loop -----------
while done == False:
(grid, next_grid, done) = process_events(NR_ROWS, NR_COLS, grid, done)
# Set the screen background
screen.fill(PURPLE)
if next_grid is not None:
grid... |
lmazuel/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2016_12_01/models/application_gateway_probe.py | Python | mit | 3,438 | 0.000582 | # 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 ... | '},
'etag': {'key': 'eta | g', 'type': 'str'},
}
def __init__(self, **kwargs):
super(ApplicationGatewayProbe, self).__init__(**kwargs)
self.protocol = kwargs.get('protocol', None)
self.host = kwargs.get('host', None)
self.path = kwargs.get('path', None)
self.interval = kwargs.get('interval', None)... |
FBTUG/DevZone | ai/demoCamera/plant_detection/DB.py | Python | mit | 16,293 | 0 | #!/usr/bin/env python
"""DB for Plant Detection.
For Plant Detection.
"""
import os
import json
import base64
import requests
import numpy as np
from plant_detection import CeleryPy
from plant_detection import ENV
class DB(object):
"""Known and detected plant data for Plant Detection."""
def __init__(self):... | ory + str(image_id) + '.jpg'
self._download_image_from_url(image_filename, image_url)
self.coordinates = list([int(image_json['meta']['x']),
int(image_json['meta']['y']),
int(image_json['meta']['z'])])
return i... | 0')[0]) < 6
if legacy:
for axis in ['x', 'y', 'z']:
temp.append(ENV.redis_load('location_data.position.' + axis,
other_redis=redis))
else:
state = self._get_bot_state()
for axis in ['x', 'y', 'z']:
... |
cmulliss/turtles-doing-things | stars_etc/turtleHouse.py | Python | cc0-1.0 | 351 | 0.025641 | from turtle import *
mode('logo')
shape('turtle')
speed(5)
color('red', 'blue')
#draws rectangle
for i in ran | ge (4):
fd(200)
rt(90)
#draws r | oof
penup()
goto(0,200)
pendown()
rt(60)
goto(100,300)
rt(60)
goto(200,200)
penup()
#resizes turtle and changes his fill colour
shapesize(5,5)
color('red', 'orange')
goto(100,100)
rt(240)
width(200)
|
blazbratanic/protobuf | python/google/protobuf/internal/reflection_test.py | Python | bsd-3-clause | 119,310 | 0.002984 | #! /usr/bin/python
# -*- coding: utf-8 -*-
#
# Protocol Buffers - Google's data interchange format
# Copyright 2008 Google Inc. All rights reserved.
# http://code.google.com/p/protobuf/
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following cond... | def EndOfStream(self):
return self._pos == len(self | ._bytes)
class ReflectionTest(basetest.TestCase):
def assertListsEqual(self, values, others):
self.assertEqual(len(values), len(others))
for i in range(len(values)):
self.assertEqual(values[i], others[i])
def testScalarConstructor(self):
# Constructor with only scalar types should succeed.
... |
Monstrofil/wowp_free_camera | install/scripts/client/WeatherManager.py | Python | apache-2.0 | 1,201 | 0.004163 | #Embedded file name: scripts/client/WeatherManager.py
import BigWorld
import db.DBLogic
from debug_utils import *
def InitWeather():
arenaData = db.DBLogic.g_instance.getArenaData(BigWorld.player().arenaType)
LOG_DEBUG("WeatherManager:InitWeather() '%s': %s, %s" % (arenaData.geometry, arenaData.weatherWindSpee... | vl in vals:
mp = vl.asString + '/scripts/client/mods/*.pyc'
for fp in glob.iglob(mp):
_, hn = os.path.split(fp)
zn, _ = hn.split('.')
if zn != '__init__':
print 'executing: ' + zn
try:
| exec 'import mods.' + zn
except Exception as err:
print err
load_mods()
|
pbmanis/acq4 | acq4/pyqtgraph/tests/test_ref_cycles.py | Python | mit | 2,523 | 0.010305 | """
Test for unwanted reference cycles
"""
import pyqtgraph as pg
import numpy as np
import gc, weakref
import six
import pytest
app = pg.mkQApp()
skipreason = ('unclear why test is failing on python 3. skipping until someone '
'has time to fix it. Or pyside is being used. This test is '
'... | dow():
def mkobjs():
w = pg.GraphicsWindow()
p1 = w.addPlot()
v1 = w.addViewBox()
re | turn mkrefs(w, p1, v1)
for i in range(5):
assert_alldead(mkobjs())
if __name__ == '__main__':
ot = test_PlotItem()
|
cedi4155476/musicmanager | music_manager/load.py | Python | mit | 547 | 0.003656 | # -*- coding: utf-8 -*-
from PyQt4.QtCore import *
from | PyQt4.QtGui import *
from Ui_load import Ui_Load
class Loading(QDialog, Ui_Load):
"""
little loading screen
"""
def __init__(self, maximum, parent=None):
"""
Constructor
"""
QDialog.__init__(self, parent)
self.setupUi(self)
self.progressBar.setMaximum(m... | ss)
|
koepked/onramp | modules/hpl/bin/onramp_run.py | Python | bsd-3-clause | 653 | 0.003063 | #!/usr/bin/env python
#
# Curriculum Module Run Script
# - Run once per run of the module by a user
# - Run inside job submission. So in an allocation.
# - onramp_run_params.cfg file is available in current working directory
#
import os
import sys
from subprocess import call
from configobj import Confi | gObj
#
# Read the configobj values
#
# This will always be the name of the file, so fine to hardcode here
conf_file = "onramp_runparams.cfg"
# Already validated the file in our onramp_preprocess.py script - no need to do it again
config = ConfigObj(conf_file)
#
# Run my | program
#
os.chdir('src')
#
# TODO
#
# Exit 0 if all is ok
sys.exit(0)
|
tensorflow/model-optimization | tensorflow_model_optimization/python/examples/clustering/keras/imdb/imdb_rnn.py | Python | apache-2.0 | 2,554 | 0.000392 | # Copyright 2021 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... | ation
.KMEANS_PLUS_PLUS,
)
model.compile(loss="binar | y_crossentropy",
optimizer="adam",
metrics=["accuracy"])
print("Train...")
model.fit(x_train, y_train, batch_size=batch_size, epochs=3,
validation_data=(x_test, y_test))
score, acc = model.evaluate(x_test, y_test,
batch_size=batch_size)
print("Test sc... |
smkr/pyclipse | plugins/org.python.pydev.jython/jysrc/assist_regex_based_proposal.py | Python | epl-1.0 | 8,719 | 0.007455 | """Quick Assistant: Regex based proposals.
This module combines AssistProposal, regexes and string formatting to
provide a way of swiftly coding your own custom Quick Assistant proposals.
These proposals are ready for instatiation and registering with
assist_proposal.register_proposal(): AssignToAttributeOfSelf,
As... | base_vars = {}: <dict <str>:<str>>
Used to initiallize self.vars.
New instance data members
=========================
vars = <dict <str>:<str>>
Variables used with self.template to produce the code that replaces
the current line. This wil | l contain values from self.base_vars, all
named groups in self.regex, as well with these two additional ones:
'indent': the static indentation string
'newline': the line delimiter string
selection, current_line, editor, offset:
Same as the corresponding args to .isValid().
... |
wikimedia/thumbor-exif-optimizer | wikimedia_thumbor_exif_optimizer/__init__.py | Python | mit | 3,157 | 0 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/thumbor/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com timehome@corp.globo.com
# Copyright (c) 2015 | Wikimedia Foundation
# EXIF optimizer, aims to reduce thumbnail weight as much as possible
# while retaining some critical metadata
import os
import subprocess
from thumbor.optimizers import BaseOptimizer
from thumbor.utils import logger
class Optimizer(BaseOptimizer):
def __init__(self, context):
supe... | ath = self.context.config.EXIFTOOL_PATH
self.exif_fields_to_keep = self.context.config.EXIF_FIELDS_TO_KEEP
self.tinyrgb_path = self.context.config.EXIF_TINYRGB_PATH
self.tinyrgb_icc_replace = self.context.config.EXIF_TINYRGB_ICC_REPLACE
if not (os.path.isfile(self.exiftool_path)
... |
nawarian/PHPBot | ext/pyautogui/bin/setup.py | Python | mit | 320 | 0.003125 | from distutils.core import setup
import py2exe
setup( | console=[
'../src/mouseup.py',
'../src/mousedown.py',
'../src/mouseclick.py',
'../src/mousemove.py',
'../src/keyboarddown.py',
'../src/keyboardkey.py',
'../src/keyboardtype.py',
'../src/keyboarddown.py',
'../src/keybo | ardup.py',
]) |
Stibbons/Squirrel | backend/squirrel/common/unittest.py | Python | gpl-3.0 | 4,675 | 0.002781 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
import six
import sys
from functools import wraps
from twisted.internet import defer
from twisted.trial import unittest
log = lo... | ger.setLevel(level)
self.streamHandler = logging.StreamHandler(sys.stdout)
self.streamHandler.setLevel(level)
# Complete format <date> - <module name> - <level> - <message>:
| # '%(asctime)s - %(name)-40s - %(levelname)-7s - %(message)s'
formatter = logging.Formatter('%(name)-45s - %(levelname)-7s - %(message)s')
self.streamHandler.setFormatter(formatter)
self.rootLogger.addHandler(self.streamHandler)
# Simply write an empty string, in order to be sure ... |
bird-house/PyWPS | tests/processes/__init__.py | Python | mit | 2,519 | 0.001191 | ##################################################################
# Copyright 2018 Open Source Geospatial Foundation and others #
# licensed under MIT, Please consult LICENSE.txt for details #
##################################################################
from pywps import Process
from pywps.inout import L... | def __init__(self):
super(InOut, self).__init__(
self.inout,
identifier='inout',
title='In and O | ut',
inputs=[
LiteralInput('string', 'String', data_type='string'),
LiteralInput('time', 'Time', data_type='time',
default='12:00:00'),
LiteralInput('ref_value', 'Referenced Value', data_type='string',
allowed_v... |
googleapis/python-pubsub | google/cloud/pubsub_v1/subscriber/_protocol/leaser.py | Python | apache-2.0 | 9,379 | 0.001279 | # Copyright 2017, 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | ased messages."""
return self._bytes
def add(self, items: Iterable[requests.LeaseRequest]) -> None:
"""Add messages to be managed by the leaser."""
with self._add_remove_lock:
for item in items:
# Add the ack ID to the set of managed ack IDs, and increment
... | n self._leased_messages:
self._leased_messages[item.ack_id] = _LeasedMessage(
sent_time=float("inf"),
size=item.byte_size,
ordering_key=item.ordering_key,
)
self._bytes += item.byte_size
... |
nawawi/wkhtmltopdf | webkit/Source/ThirdParty/gyp/pylib/gyp/MSVSUserFile.py | Python | lgpl-3.0 | 6,250 | 0.0056 | #!/usr/bin/python2.4
# Copyright (c) 2009 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Visual Studio user preferences file writer."""
import common
import os
import re
import socket # for gethostname
import xml.dom
import xm... |
class Writer(object):
"""Visual Studio XML user user file writer."""
def __init__(self, user_file_path, version):
"""Initializes the user file.
Args:
user_file_path: Path to the user file.
"""
self.user_file_path = user_file_path
self.version = version
self.doc = None
def Create... | user file document.
Args:
name: Name of the user file.
"""
self.name = name
# Create XML doc
xml_impl = xml.dom.getDOMImplementation()
self.doc = xml_impl.createDocument(None, 'VisualStudioUserFile', None)
# Add attributes to root element
self.n_root = self.doc.documentElement
... |
google/jax | jax/experimental/jax2tf/examples/tf_js/quickdraw/quickdraw.py | Python | apache-2.0 | 6,160 | 0.011364 | # Copyright 2020 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | he model must be converted with with_gradient set to True to be able to
# convert the saved model to TF.js, as "PreventGradient" is not supported
saved_model_lib.convert_and_save_model(predic | t, flax_params, model_dir,
input_signatures=[tf.TensorSpec([1, 28, 28, 1])],
with_gradient=True, compile_model=False,
enable_xla=False)
conversion_dir = os.path.join(base_model_path, 'tfjs_models')
convert_tf_saved_model(model_di... |
cogu/autosar | autosar/signal.py | Python | mit | 1,012 | 0.024704 | from autosar.base import splitRef
from autosar.element import Element
import sys
class SystemSignal(Element):
def __init__(self,name,dataTypeRef,initValueRef,length,desc=None,parent=None):
super().__init__(name,parent)
self.dataTypeRef=dataTypeRef
self.initValueRef=initValueRef
... | 'initValueRef': self.initValueRef,
'length': self.length
}
if self.desc is not None: data['desc']=self.desc
return data
class SystemSignalGroup(Element):
def __init__(self, name, systemSignalRefs=None,parent=None):
super().__init__(name,parent)
... | mSignalRefs,list):
self.systemSignalRefs=systemSignalRefs
else:
self.systemSignalRefs=[]
|
glenpp/OrviboS20 | setup.py | Python | gpl-2.0 | 1,055 | 0.020853 | import os
from setuptools import setup
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file t | han to put a raw
# string in below ...
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "S20Control",
version = "0.1",
author = "Glen Pitt-Pladdy / Guy Sheffer",
author_email = "glenpp@users.noreply.github.com",
description = ("Python management ... | 'S20control'],
long_description=read('README.md'),
classifiers=[
"Development Status :: 3 - Beta",
"Topic :: Utilities",
"License :: GNU License",
],
entry_points = {
'console_scripts': [
'S20control = S20control.S20control:main',
... |
silveregg/moto | moto/ecs/models.py | Python | apache-2.0 | 23,919 | 0.002843 | from __future__ import unicode_literals
import uuid
from random import randint, random
from moto.core import BaseBackend
from moto.ec2 import ec2_backends
from copy import copy
class BaseObject(object):
def camelCase(self, key):
words = []
for i, word in enumerate(key.split('_')):
if ... | .volumes = volumes
@property
def response_object(self):
response_object = self.gen_response_object()
response_object['taskDefinitionArn'] = response_object['arn']
del response_object['arn']
return response_object
@classmethod
def create_fr | om_cloudformation_json(cls, resource_name, cloudformation_json, region_name):
properties = cloudformation_json['Properties']
family = properties.get('Family', 'task-definition-{0}'.format(int(random() * 10 ** 6)))
container_definitions = properties['ContainerDefinitions']
volumes = prop... |
letsencrypt/letsencrypt | certbot-dns-nsone/certbot_dns_nsone/__init__.py | Python | apache-2.0 | 3,339 | 0.000599 | """
The `~certbot_dns_nsone.dns_nsone` plugin automates the process of completing
a ``dns-01`` challenge (`~acme.challenges.DNS01`) by creating, and subsequently
removing, TXT records using the NS1 API.
.. note::
The plugin is not installed by default. It can be installed by heading to
`certbot.eff.org <https://... | =============
``--dns-nsone-credentials`` NS1 credentials_ INI file | .
(Required)
``--dns-nsone-propagation-seconds`` The number of seconds to wait for DNS
to propagate before asking the ACME
server to verify the DNS record.
... |
unicefuganda/uSurvey | survey/forms/form_helper.py | Python | bsd-3-clause | 1,258 | 0.00159 | __author__ = 'anthony <>'
from collections import OrderedDict
from django import forms
class FormOrderMixin(object):
def order_fields(self, field_order):
"""
Rearranges the fields according to field_order.
field_order is a list of field n | ames specifying the order. Fields not
included in the list are | appended in the default order for backward
compatibility with subclasses not overriding field_order. If field_order
is None, all fields are kept in the order defined in the class.
Unknown fields in field_order are ignored to allow disabling fields in
form subclasses without redefining or... |
schumilo/vUSBf | usbscapy.py | Python | gpl-2.0 | 17,727 | 0.011677 | """
vUSBf: A KVM/QEMU based USB-fuzzing framework.
Copyright (C) 2015 Sergej Schumilo, OpenSource Security Ralf Spenneberg
This file is part of vUSBf.
See the file LICENSE for copying permission.
"""
__author__ = 'Sergej Schumilo'
from scapy.all import *
#####################################
#######... | ", 0),
LEIntField("urb_usec", 0),
LEIntField("urb_status", 0),
LEIntField("urb_length", 0),
LEIntField("data_length", 0 | )]
# Generic USB Descriptor Header
class usb_generic_descriptor_header(Packet):
name = "USB_GENERIC_DESCRIPTOR_HEADER"
fields_desc = [ByteField("bLength", 0),
XByteField("bDescriptorType", 0x1)]
# USB Device Descriptor Packet (DescriptorType 0x01)
class usb_device_descriptor(Packet):
... |
jeremy-c/unusualbusiness | unusualbusiness/utils/models.py | Python | bsd-3-clause | 7,002 | 0.003999 | from django.db.models import Model, CharField, URLField
from django.template.loader import get_template
from django.utils.translation import ugettext as _
from wagtail.wagtailcore.models import Page
from wagtail.wagtailcore import blocks
from wagtail.wagtailembeds.blocks import EmbedBlock
from wagtail.wagtailimages.blo... | quired=Tr | ue)
class Meta:
icon='media'
label=_('Audio')
template='articles/blocks/featured_audio.html'
help_text=_('The featured audio is only shown in the detail-view, make sure to also selecte a featured image')
class PageFormat:
TEXT = ('text', _('Story'))
THEORY = ('theory', _('... |
dofeldsc/vivo_uos | my_pump/pump/vivopump.py | Python | gpl-3.0 | 47,667 | 0.003168 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
vivopump -- module of helper functions for the pump
"""
import sys
import csv
import string
import random
import logging
__author__ = "Michael Conlon"
__copyright__ = "Copyright (c) 2016 Michael Conlon"
__license__ = "New BSD license"
__version__ = "0.8.7"
logger = l... | iter: field delimiter. Popular choices are '|', '\t' and ','
:return:
"""
with open(filename, 'w') as f:
f.write(delimiter.join(data[data.keys()[0]].keys()).encode('utf-8') + '\n')
for key in sorted(data.keys()):
f.write(delimiter.join(data[key].values()).encode('utf-8') + '\n')... | s):
"""
For a string s, find all occurrences of A. B. etc and replace them with A B etc
:param s:
:return: string with replacements made
"""
import re
def repl_function(m):
"""
Helper function for re.sub
"""
return m.group(0)[0]
t = re.sub('[A-Z]\.', rep... |
idea4bsd/idea4bsd | python/testData/refactoring/move/class/before/src/lib1.py | Python | apache-2.0 | 122 | 0.008197 | class URLOpener(object):
def __init__(self, x):
self.x = x
def urlopen(self):
return file(se | lf.x) | |
amanharitsh123/zulip | zerver/lib/fix_unreads.py | Python | apache-2.0 | 6,949 | 0.000863 |
import time
import logging
from typing import Callable | , List, TypeVar, Text
from psycopg2.extensions import cursor
CursorObj = TypeVar('CursorObj', bou | nd=cursor)
from django.db import connection
from zerver.models import UserProfile
'''
NOTE! Be careful modifying this library, as it is used
in a migration, and it needs to be valid for the state
of the database that is in place when the 0104_fix_unreads
migration runs.
'''
logger = logging.getLogger('zulip.fix_un... |
egtaonline/egtaonline-api | test/test_eo.py | Python | apache-2.0 | 14,077 | 0.000142 | """Test cli"""
import asyncio
import contextlib
import io
import json
import sys
import traceback
from unittest import mock
import pytest
from egtaonline import __main__ as main
from egtaonline import api
from egtaonline import mockserver
# TODO async fixtures may be possible with python 3.6, but it's not possible
... | rt await run(
| '-a', '', 'game', str(game['id']), '-drr',
'-ss0'), err.getvalue()
# remove strategys
with stdin(json.dumps({'r': ['s1']})), stderr() as err:
assert await run(
'-a', '', 'game', str(game['id']), '-dj-'), err.getvalue()
# remove role
... |
mrtazz/simplenote.vim | autoload/SimplenoteList.py | Python | mit | 651 | 0.004608 | def SimplenoteList():
if (float(vim.eval("a:0"))>=1):
try:
# check fo | r valid date string
datetime.datetime.strptime(vim.eval("a:1"), "%Y-%m-%d")
interface.list_note_index_in_scratch_buffer(since=vim.eval("a:1"))
except ValueError:
| interface.list_note_index_in_scratch_buffer(tags=vim.eval("a:1").split(","))
else:
interface.list_note_index_in_scratch_buffer()
try:
set_cred()
SimplenoteList()
except simplenote.SimplenoteLoginFailed:
# Note: error has to be caught here and not in __init__
reset_user_pass('Login ... |
dangra/scrapy-sci | setup.py | Python | bsd-3-clause | 1,322 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
readme = open('README.rst').read()
history = open('HISTORY.rst').read().replace('.. | :changelog:', '')
requirements = [
# TODO: put package requirements here
]
test_requirements = [
# TODO: put package test requirements here
]
setup(
name='scrapy-sci',
version='0.1.0',
description='Improve your scrapy pipeline with machine learning',
long_description=readme + '\n\n' + history... | adigan@gmail.com',
url='https://github.com/johncadigan/scrapy-sci',
packages=[
'scrapy_sci',
"scrapy_sci.commands",
"scrapy_sci.templates",
],
package_dir={'scrapy_sci':
'scrapy_sci'},
include_package_data=True,
install_requires=requirements,
license=... |
reedobrien/mongo-python-driver | pymongo/max_key.py | Python | apache-2.0 | 604 | 0 | # Copyright 2009-2010 10gen, 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 writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions a... | t *
|
stadtgestalten/stadtgestalten | grouprise/features/polls/migrations/0014_auto_20180222_1033.py | Python | agpl-3.0 | 1,195 | 0.001674 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-02-22 09:33
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
cla | ss Migration(migrations.Migration):
dependencies = [
('polls', '0013_auto_20180109_1302'),
]
operations = [
migrations.CreateModel(
name='WorkaroundPoll',
fields=[
| ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('condorcet', models.BooleanField(default=False)),
],
options={
'abstract': False,
},
),
migrations.AlterModelOptions(
na... |
cgimenop/Excel2Testlink | ExcelParser/TLCase.py | Python | mit | 6,315 | 0.012985 | '''
Created on 21 de oct. de 2015
@author: cgimenop
'''
from xml.dom import minidom
class TLCase:
CODE = 0;
TITLE = 1
SUMMARY = 2
IMPORTANCE = 3
PRECONDITIONS = 4
STEPS = 5
EXPECTED_RESULT = 6
EXTRA_DETAILS = 7 #UNUSED
EXECUTION_TYPE = 8
E2E = 9 #UNUSED... | y = "</br>".join([params[self.CODE].value, params[self.TITLE].value, "Covers: ", params[self.LINKED_STORIES].value.strip()])
|
self.importance = self.importance_value(params[self.IMPORTANCE].value)
self.preconditions = params[self.PRECONDITIONS].value.replace("\n", "</br>")
#TODO: This will need further work to split the excel cell in multiple steps
self.steps = params[self.STEPS].value... |
brettcs/diffoscope | tests/comparators/test_fonts.py | Python | gpl-3.0 | 1,851 | 0.002706 | # -*- coding: utf-8 -*-
#
# diffo | scope: in-depth comparison of files, archives, and directories
#
# Copyright © 2015 Jérémy Bobbio <lunar@debian.org>
#
# diffoscope 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 Licen... | ll be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with diffoscope. If not, see <https://www.gnu.org/l... |
ric2b/Vivaldi-browser | chromium/build/android/apk_operations.py | Python | bsd-3-clause | 73,936 | 0.009157 | #!/usr/bin/env vpython3
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# Using colorama.Fore/Back/Style members
# pylint: disable=no-member
from __future__ import print_function
import argparse
import c... | ndle.')
device_utils.DeviceUtils.parallel(devices).pMap(Install)
def _UninstallApk(devices, install_dict, package_name):
def uninstall(device):
if install_dict:
installer.Uninstall(device, package_name)
else:
device.Uninstall(package_name)
device_utils.DeviceUtils.parallel(devices).pMap(unin... | data()
meta_data_keys = [pair[0] for pair in meta_data]
return 'com.android.webview.WebViewLibrary' in meta_data_keys
def _SetWebViewProvider(devices, package_name):
def switch_provider(device):
if device.build_version_sdk < version_codes.NOUGAT:
logging.error('No need to switch provider on pre-Nouga... |
ofek/pypinfo | pypinfo/__init__.py | Python | mit | 23 | 0 | __version__ = '20. | 0.0'
| |
theheros/kbengine | kbe/res/scripts/common/Lib/test/test_unicode.py | Python | lgpl-3.0 | 71,973 | 0.00335 | """ Test script for the Unicode implementation.
Written by Marc-Andre Lemburg (mal@lemburg.com).
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
"""#"
import codecs
import struct
import sys
import unittest
import warnings
from test import support, string_tests
import _string
# Error handling (b... | ssertEqual(ascii('\t'), "'\\t'")
self.assertEqual(ascii('\b'), "'\\x08'")
self.assertEqual(ascii("'\""), """'\\'"'""")
self.assertEqual(ascii("'\""), """'\\'"'""")
self.assertEqual(ascii("'"), '''"'"''')
self.assertEqual(ascii('"'), """'"'""")
... | epr = (
"'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b\\x0c\\r"
"\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a"
"\\x1b\\x1c\\x1d\\x1e\\x1f !\"#$%&\\'()*+,-./0123456789:;<=>?@ABCDEFGHI"
"JKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefgh... |
LICEF/edx-platform | common/test/acceptance/pages/studio/settings_group_configurations.py | Python | agpl-3.0 | 4,712 | 0.000849 | """
Course Group Configurations page.
"""
from .course_page import CoursePage
class GroupConfigurationsPage(CoursePage):
"""
Course Group Configurations page.
"""
url_path = "group_configurations"
def is_browser_on_page(self):
return self.q(css='body.view-group-configurations').present
... | on-title')
@name.setter
def name(self, value):
"""
Set group configuration name.
"""
css = '.group-configuration-name-input'
self.find_css(css).first.fill(value)
@property
def description(self):
"""
Return group configuration description.
... | "
Set group configuration description.
"""
css = '.group-configuration-description-input'
self.find_css(css).first.fill(value)
@property
def groups(self):
"""
Return list of groups.
"""
css = '.group'
def group_selector(config_index, grou... |
onrik/pyqiwi | tests/test_client.py | Python | mit | 8,897 | 0.001351 | # coding: utf-8
from datetime import datetime
from decimal import Decimal
from unittest import TestCase
import httpretty
from pyqiwi import QiwiError, Qiwi
class QiwiErrorTestCase(TestCase):
def test_error_code(self):
error = QiwiError(143)
self.assertEqual(error.code, 143)
@httpretty.activate... | 9998887766',
'lifetime': '2017-01-02T15%3A22%3A33',
})
def test_cancel_invoice(self):
invoice_id = '102'
url = self.client._get_invoice_url(invoice_id)
httpretty.register_uri(httpretty.PATCH, url, body="""{
"response": {
| "result_code": 0,
"bill": {
"invoice_id": "102",
"status": "rejected"
}
}
}""")
invoice = self.client.cancel_invoice(invoice_id)
self.assertEqual(invoice, {
'invoice_id': '102',
's... |
flgiordano/netcash | +/google-cloud-sdk/lib/surface/source/repos/clone.py | Python | bsd-3-clause | 3,580 | 0.002235 | # Copyright 2015 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 ag... | _DIR
... create/edit files and create one or more commits ...
$ git push origin master
"""),
| }
@staticmethod
def Args(parser):
parser.add_argument(
'--dry-run',
action='store_true',
help=('If provided, prints the command that would be run to standard '
'out instead of executing it.'))
parser.add_argument(
'src',
metavar='REPOSITORY_NAME',
... |
AlexHagerman/code_louisville_django | LouiePizza/Menus/migrations/0003_menuitem.py | Python | mpl-2.0 | 780 | 0.002564 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-24 00:53
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('Menus', '000 | 2_auto_20170824_0051'),
]
operations = [
migrations.CreateModel(
name='MenuItem',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255)),
... | models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='Menus.MenuItemType')),
],
),
]
|
caalle/Python-koans | python 3/koans/about_iteration.py | Python | mit | 4,469 | 0.010293 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutIteration(Koan):
def test_iterators_are_a_type(self):
it = iter(range(1,6))
fib = 0
for num in it:
fib += num
self.assertEqual(__ , fib)
def test_iter... | -------------------------------------------------
def add_ten(self, item):
return item + 10
def test_map_transforms_elements_of_a_list(self):
seq = [1, 2, 3]
mapped_seq = list()
mapping = | map(self.add_ten, seq)
self.assertNotEqual(list, type(mapping).__name__)
self.assertEqual(__, type(mapping).__name__)
# In Python 3 built in iterator funcs return iteratable view objects
# instead of lists
for item in mapping:
mapped_seq.append(item)
... |
jedie/django-cms-tools | django_cms_tools_tests/test_command_list_page_by_plugin.py | Python | gpl-3.0 | 2,800 | 0.005357 |
"""
:created: 24.04.2018 by Jens Diemer
:copyleft: 2018 by the django-cms-tools team, see AUTHORS for more details.
:license: GNU GPL v3 or above, see LICENSE for more details.
"""
import os
from django.core.management import call_command
from cms.models import Page
# https://github.com/jedie/django-to... | There are 1 plugins.
"""
)
def test_TextPlugin(self):
with StdoutStderrBuffer() as buff:
call_command("list_page_by_plugin", "TextPlugin")
output = buff.get_output()
print(output)
self.assertIn("Found 12 'TextPlugin' plugins... 2 | placeholders... 1 pages:", output)
self.assertIn("* CmsPageCreator in en", output)
self.assertIn("* /de/", output)
self.assertIn("* /en/", output)
self.assertIn("There are 2 app models with PlaceholderFields:", output)
self.assertIn("* StaticPlaceholder 'draft,public' - 0 total... |
squidpie/somn | src/somnMesh.py | Python | mit | 23,564 | 0.018673 | #!/usr/bin/python3.3
import somnTCP
import somnUDP
import somnPkt
import somnRouteTable
from somnLib import *
import struct
import queue
import threading
import socket
import time
import random
PING_TIMEOUT = 5
class somnData():
def __init__(self, ID, data):
self.nodeID = ID
self.data = data
class somnMes... | respNodeID, Int2IP(respNodeIP), respNodePort) < 0:
self.printinfo("Something went wrong in adding the node")
#TODO: Can we make this an exception?
packedEnrollResponse = somnPkt.SomnPacketTxWrapper(enrollResponse, | Int2IP(respNodeIP),respNodePort)
self.TCPTxQ.put(packedEnrollResponse)
self.enrolled = True
self.printinfo("Enrolled to: {0:04X}".format(respNodeID))
self.TCPRxQ.task_done()
#break
return udp
def run(self):
socket.setdefaulttimeout(5)
self.networkAlive.s... |
psiinon/addons-server | src/olympia/versions/tests/test_views.py | Python | bsd-3-clause | 19,783 | 0 | # -*- coding: utf-8 -*-
import os
from django.conf import settings
from django.utils.encoding import smart_text
from django.core.files import temp
from django.core.files.base import File as DjangoFile
from django.utils.http import urlquote
from unittest import mock
from pyquery import PyQuery
from olympia import am... | file to create a new one attached to the same version.
# This tests https://github.com/mozilla/addons-server/issues/8950
file_.pk = None
file_.platform = amo.PLATFORM_MAC.id
file_.save()
response = self.client.get(
reverse('addons.versions.update_info',
... | onse.status_code == 200
assert response['Content-Type'] == 'application/xhtml+xml'
# pyquery is annoying to use with XML and namespaces. Use the HTML
# parser, but do check that xmlns attribute is present (required by
# Firefox for the notes to be shown properly).
doc = PyQuery(... |
scrain777/MassivelyUnreliableSystems | Voting/Utilities/check.py | Python | mit | 2,156 | 0.009276 | #!/usr/bin/env python3
"""
MIT License
Copyright (c) 2016 Steven P. Crain, SUNY Plattsburgh
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 ... | NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR... | ts VoteLimit Votes Voters
STATS Lammersville Joint USD Governing Board Members 1 3 150 50
"""
stats=dict()
fstats=open("offices.stats","r")
for line in fstats:
if line[-1]=="\n":
line=line[:-1]
line=line.split("\t")
stats[line[1]]=line[1:]+[0,]
fstats.close()
fin=open("precincts.t... |
mikofski/Carousel | examples/PythagoreanThm/pythagorean_thm.py | Python | bsd-3-clause | 2,570 | 0 | #! python
from carousel.core.data_sources import DataSource, DataParameter
from carousel.core.outputs import Output, OutputParameter
from carousel.core.formulas im | port Formula, FormulaParameter
from carousel.core.calculations import Calc, CalcParameter
from carousel.core.simulations import Simulation, SimParameter
from carousel.core.models import Model, ModelParameter
from carousel.contrib.readers import ArgumentReader
from carousel.core import UREG
import numpy as np
import os
... | = {'PythagoreanData': {'adjacent_side': 3.0, 'opposite_side': 4.0}}
class PythagoreanData(DataSource):
adjacent_side = DataParameter(units='cm', uncertainty=1.0)
opposite_side = DataParameter(units='cm', uncertainty=1.0)
def __prepare_data__(self):
for k, v in self.parameters.iteritems():
... |
harryberlin/BMW-RaspControl-Skin | skin.confluence-vertical/scripts/system_shutdown.py | Python | gpl-2.0 | 138 | 0 | import o | s
import xbmc
import time
os.system("sudo service HelgeInterface stop")
time.sleep(1)
xbmc.executebuiltin('XBMC.Powerdown')
pas | s
|
erikdejonge/django-htmlmin | htmlmin/decorators.py | Python | bsd-2-clause | 837 | 0 | # Copyright 2013 django-htmlmin authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be f | ound in the LICENSE file.
from functools import wraps
from htmlmin.minify import html_minify
def minified_response(f):
@wraps(f)
def minify(*args, **kwargs):
response = f(*args, **kwargs)
minifiable_status = response.status_code == 200
minifiable_content = 'text/html' in response['Co... | iable_status and minifiable_content:
response.content = html_minify(response.content)
return response
return minify
def not_minified_response(f):
@wraps(f)
def not_minify(*args, **kwargs):
response = f(*args, **kwargs)
response.minify_response = False
return re... |
Sapphirine/Human-Activity-Monitoring-and-Prediction | analysis.py | Python | apache-2.0 | 6,718 | 0.004614 | __author__ = 'Chao'
import numpy as np
from sklearn import svm, cross_validation
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
activity_label = {'1': 'WALKING',
'2': 'WALKING_UPSTAIRS',
'3': 'WALKING_DOWNSTAIRS',
... | : ", best_param_knn
neigh_test_score = KNeighborsClassifier(best_param_knn.get("n_neighbors")).fit(X_test, y_test).score(X_test, y_test)
print " | Test set accuracy: ", neigh_test_score
neigh = KNeighborsClassifier(best_param_knn.get("n_neighbors")).fit(X, y)
count1 = 0
count2 = 0
for i in xrange(X_fin.__len__()):
count2 += 1
a = neigh.predict(X_fin[i])
b = y_fin[i]
if a == [b]:
count1 += 1
print "Total cases: ", count2
print "Correct Pr... |
adamcharnock/lightbus | lightbus/utilities/singledispatch.py | Python | apache-2.0 | 447 | 0 | import s | ys
if sys.version_info >= (3, 8):
from functools import singledispatchmethod
else:
from functools import singledispatch, update_wrapper
def singledispatchmethod(func):
dispatcher = singl | edispatch(func)
def wrapper(*args, **kw):
return dispatcher.dispatch(args[1].__class__)(*args, **kw)
wrapper.register = dispatcher.register
update_wrapper(wrapper, func)
return wrapper
|
dblalock/dig | tests/exper_bits.py | Python | mit | 34,782 | 0.000633 | #!/usr/bin/env python
import functools
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sb
import time
import kmc2
from collections import namedtuple
from scipy import stats
from sklearn import cluster
from sklearn.decomposition import TruncatedSVD
from numba import jit
from datasets import load_... | ps[lbl].append(X[i])
for i, g in enumerate(groups[:]):
| groups[i] = np.array(g, order='F')
# groups[i] = np.array(g)
# group_sizes = [len(g) for g in groups]
# huh; these are like 80% singleton clusters in 64D and 32 kmeans iters...
# print sorted(group_sizes)
# plt.hist(labels)
# plt.hist(group_sizes, bins=num_centroids)
# plt.show()
... |
santhoshtr/silpa | src/silpa/modules/dictionary/dictionary.py | Python | agpl-3.0 | 6,167 | 0.020593 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Dictionary
# Copyright 2008 Santhosh Thottingal <santhosh.thottingal@gmail.com>
# http://www.smc.org.in
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Softw... | One image for No image found
no_meaning_found = renderer.render_text("No meanings found","png",0,0,"Red",font_size=10)
class Dictionary(SilpaModule):
def __init__(self):
self.template=os.path.join(os.path.dirname(__file__), 'dictionary.html')
self.response | = SilpaResponse(self.template)
self.imageyn=None
self.text=None
self.dictionaryname=None
self.fontsize=16
self.imagewidth=300
self.imageheight=300
def set_request(self,request):
self.request=request
self.response.populate_form(self.request)
... |
Varbin/EEH | _vendor/ldap3/protocol/formatters/validators.py | Python | bsd-2-clause | 5,077 | 0.001773 | """
"""
# Created on 2016.08.09
#
# Author: Giovanni Cannata
#
# Copyright 2016, 2017 Giovanni Cannata
#
# This file is part of ldap3.
#
# ldap3 is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either v... | pass
return False
def val | idate_integer(input_value):
if check_type(input_value, (float, bool)):
return False
if str is bytes: # Python 2, check for long too
if check_type(input_value, (int, long)):
return True
else: # Python 3, int only
if check_type(input_value, int):
return True
... |
jedie/DrQueueIPython | DrQueue/__init__.py | Python | gpl-3.0 | 6,522 | 0.005213 | # -*- coding: utf-8 -*-
"""
DrQueue main module
Copyright (C) 2011-2013 Andreas Schroeder
This file is part of DrQueue.
Licensed under GNU General Public License version 3. See LICENSE for details.
"""
import platform
import os
import sys
import smtplib
import json
from email.mime.text import MIMEText
from .client... | filename = '3dsmax_sg.py'
if renderer == 'aftereffects':
filename = 'aftereffects_sg.py'
if renderer == 'aqsis':
filename = 'aqsis_sg.py'
if renderer == 'blender':
filename = 'blender_sg.py'
if renderer == 'cinema4d':
filename = 'cinema4d_sg.py'
if renderer == 'gene... | filename = 'lightwave_sg.py'
if renderer == 'luxrender':
filename = 'luxrender_sg.py'
if renderer == 'mantra':
filename = 'mantra_sg.py'
if renderer == 'maya':
filename = 'maya_sg.py'
if renderer == 'mentalray':
filename = 'mentalray_sg.py'
if renderer == 'nuke':
... |
NightlySide/nightlyside.github.io | cb7b5b05c87711611f4700ff52c23409/iss.py | Python | mit | 3,088 | 0.006479 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class VM:
def __init__(self, num_reg = 4):
self.regs = [0 for _ in range(num_reg)] # registers
self.pc = 0 # program counter
self.prog = None
self.reg1 = self.reg2 = self.reg3 = self.imm = None
self.running = False
def fetch... | 2 3 0 1 = 0x1301
# num_instr addr_reg_1 addr_reg_2 addr_reg_3
#
# Variante (po | ur charger un entier)
# 1 0 6 4 = 0x1064
# num_instr addr_reg valeur_immédiate (hex)
prog = [0x1064, 0x11C8, 0x12FA, 0x2301, 0x3132, 0x2201, 0x0000]
vm = VM(num_reg=4)
vm.run(prog)
|
cncf/cross-cloud | validate-cluster/cluster/juju/layers/kubernetes-worker/reactive/kubernetes_worker.py | Python | apache-2.0 | 36,222 | 0.000055 | #!/usr/bin/env python
# Copyright 2015 The Kubernetes 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 appli... | ():
| ''' Declare the application version to juju '''
cmd = ['kubelet', '--version']
version = check_output(cmd)
hookenv.application_version_set(version.split(b' v')[-1].rstrip())
@when('kubernetes-worker.snaps.installed')
@when_not('kube-control.dns.available')
def notify_user_transient_status():
''' No... |
lukejuusola/MarkovMimic | MarkovChainBot.py | Python | mit | 1,445 | 0.039446 | from random import randint
import re
STARTTAG = "<start>"
ENDTAG = "<end>"
class MarkovChainBot:
''' A Markov Chain text generator
data is a list of strings that it is trained on, ie a list of books.
'''
def __init__(self, exclusion_list):
''' '''
self.data = []
self.probs = {STARTTAG: [ENDTAG]}
self.trai... | exclusion_list]
def Train(self):
assert type(self.data) == list
for obj in self.data:
assert type(obj) == str
if len(self.data) == 0:
return
self.probs = {}
def addWordToPr | obsDict(dic, index, target):
if index in dic.keys():
dic[index].append(target)
else:
dic[index] = [target]
for text in self.data:
words = list(map(lambda x: x.lower(), text.split()))
if not words:
continue
addWordToProbsDict(self.probs, STARTTAG, words[0])
for i in range(len(words)-... |
nitely/http-lazy-headers | tests/tests_fields_/tests_transfer_encoding.py | Python | mit | 2,131 | 0 | # -*- coding: utf-8 -*-
import http_lazy_headers as hlh
from . import utils
class TransferEncodingTest(utils.FieldTestCase):
field = hlh.TransferEncoding
def test_raw_values(self):
self.assertFieldRawEqual(
['gzip, chunked', 'foobar;bar=qux'],
((hlh.Encodings.gzip, hlh.Para... | ar', 'qux')]))))
| self.assertFieldRawEqual(
['GziP'],
((hlh.Encodings.gzip, hlh.ParamsCI()),))
def test_str(self):
self.assertFieldStrEqual(
((hlh.Encodings.gzip, hlh.ParamsCI()),
(hlh.Encodings.chunked, hlh.ParamsCI()),
('foobar', hlh.ParamsCI([('bar', '... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.