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 |
|---|---|---|---|---|---|---|---|---|
common-workflow-language/cwltool | tests/test_empty_input.py | Python | apache-2.0 | 513 | 0 | from io import StringIO
from pathlib import Path
from cwltool.main import main
from .util import get_data
def test_empty_input(tmp_path: Path) -> None:
"""Affirm that an empty input works."""
empty_json = "{}"
empty_input = StringIO(empty_json)
params = [
"--outdir",
str(tmp_path),
... | ta("tests/wf/no-parameters-echo.cwl"),
"-",
]
try:
assert main(params, stdin=empty_input) == 0
except SystemExit as err:
| assert err.code == 0
|
alphagov/digitalmarketplace-api | migrations/versions/940_more_supplier_details.py | Python | mit | 1,372 | 0.007289 | """ Extend suppliers table with new fields (to be initially populated from declaration data)
Revision ID: 940
Revises: 930
Create Date: 2017-08-16 16:39:00.000000
"""
# revision identifiers, used by Alembic.
revision = '940'
down_revision = '93 | 0'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_co | lumn(u'suppliers', sa.Column('registered_name', sa.String(), nullable=True))
op.add_column(u'suppliers', sa.Column('registration_country', sa.String(), nullable=True))
op.add_column(u'suppliers', sa.Column('other_company_registration_number', sa.String(), nullable=True))
op.add_column(u'suppliers', sa.Colum... |
weiHelloWorld/accelerated_sampling_with_autoencoder | MD_simulation_on_alanine_dipeptide/current_work/src/biased_simulation.py | Python | mit | 16,759 | 0.007101 | """
This file is for biased simulation for alanine dipeptide only, it is used as the test for
more general file biased_simulation_general.py, which could be easily extend to other new
systems.
"""
from ANN_simulation import *
from simtk.openmm.app import *
from simtk.openmm import *
from simtk.unit import *
from sys i... | ling_factor for ANN_Force')
parser.add_argument("--starting_pdb_file", type=str, default='../resources/alanine_dipeptide.pdb', help='the input pdb file to start simulation')
parser.add_argument("--starting_frame", type=int, default=0, help="index of starting frame in the starting pdb file")
parser.add_argument("--minim... |
parser.add_argument("--equilibration_steps", type=int, default=1000, help="number of steps for the equilibration process")
# next few options are for metadynamics
parser.add_argument("--bias_method", type=str, default='US', help="biasing method for enhanced sampling, US = umbrella sampling, MTD = metadynamics")
parser... |
goocarlos/domaindiscoverer | pythonwhois/net.py | Python | apache-2.0 | 4,072 | 0.030452 | import socket, re, sys
from codecs import encode, decode
from . import shared
def get_whois_raw(domain, server="", previous=None, rfc3490=True, never_cut=False, with_server_list=False, server_list=None):
previous = previous or []
server_list = server_list or []
# Sometimes IANA simply won't give us the right root W... | ain = domain
response = whois_request(request_domain, target_server)
if never_cut:
# If the caller has requested to 'never cut' responses, he will get the original response from the server (this is
# useful for callers that are only interested in the raw data). Otherwise, if the target is verisign-grs, we will
... | card the rest, so that in a multiple-option response the
# parsing code will only touch the information relevant to the requested domain. The side-effect of this is that
# when `never_cut` is set to False, any verisign-grs responses in the raw data will be missing header, footer, and
# alternative domain options ... |
EUDAT-B2SHARE/invenio-old | modules/websearch/lib/search_engine.py | Python | gpl-2.0 | 314,285 | 0.007118 | # -*- coding: utf-8 -*-
## This file is part of Invenio.
## Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 CERN.
##
## Invenio 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;... | AD_EXTERNAL_SYSNO_TAG, \
CFG_BIBRANK_SHOW_DOWNLOAD_GRAPHS, \
CFG_WEBSEARCH_SYNONYM_KBRS, \
CFG_SITE_LANG, \
CFG_SITE_NAME, \
CFG_LOGDIR, \
CFG_BIBFORMAT_HIDDEN_TAGS, \
CFG_SITE_URL, \
CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS, \
CFG_SOLR_URL, \
CFG_WEBSEARCH_DETAILED_META_FORMA... |
CFG_BIBINDEX_CHARS_PUNCTUATION
from invenio.search_engine_config import \
InvenioWebSearchUnknownCollectionError, \
InvenioWebSearchWildcardLimitError, \
CFG_WEBSEARCH_IDXPAIRS_FIELDS,\
CFG_WEBSEARCH_IDXPAIRS_EXACT_SEARCH, \
CFG_SEARCH_RESULTS_CACHE_PREFIX
from invenio.search_engine_util... |
TheTimmy/spack | lib/spack/external/__init__.py | Python | lgpl-2.1 | 2,139 | 0 | ##############################################################################
# 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... | TY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple ... | Suite 330, Boston, MA 02111-1307 USA
##############################################################################
"""
This module contains external, potentially separately licensed,
packages that are included in spack.
So far:
argparse: We include our own version to be Python 2.6 compatible.
distro: ... |
dimagi/commcare-hq | corehq/apps/reports/standard/users/reports.py | Python | bsd-3-clause | 10,221 | 0.00137 | from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Q
from django.template.loader import render_to_string
from django.utils.html import format_html
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from django.utils.translation import ugettex... | if actions and ChangeActionFilter.ALL not in actions:
filters = filte | rs & Q(action__in=actions)
if user_upload_record_id:
filters = filters & Q(user_upload_record_id=user_upload_record_id)
if self.datespan:
filters = filters & Q(changed_at__lt=self.datespan.enddate_adjusted,
changed_at__gte=self.datespan.startda... |
tseaver/google-cloud-python | datastore/tests/unit/test_client.py | Python | apache-2.0 | 44,363 | 0.000654 | # Copyright 2014 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 agreed to in writing, s... | ock()
client_options = ClientOptions("endpoint")
http = object()
client = self._make_one(
project=other,
namespace=namespace,
credentials=creds,
client_info=client_info,
client_options=client_options,
_http=http,
)
... | ertEqual(client.project, other)
self.assertEqual(client.namespace, namespace)
self.assertIs(client._credentials, creds)
self.assertIs(client._client_info, client_info)
self.assertIs(client._http_internal, http)
self.assertIsNone(client.current_batch)
self.assertIs(client.... |
sostenibilidad-unam/sleuth_automation | bin/status.py | Python | gpl-3.0 | 373 | 0.005362 | #!/usr/bin/env python
import pickle
import argparse
from pprint import pprint
description = """
print out run status from pickled Location object
"""
parser = argparse.ArgumentParser(description=description)
parser.add_argument('pickle', type=argparse.FileTyp | e('r'), help='path to location pickle')
args = parser. | parse_args()
l = pickle.load(args.pickle)
pprint(l)
|
tellesnobrega/storm_plugin | sahara/tests/unit/service/validation/edp/test_job_executor_java.py | Python | apache-2.0 | 2,252 | 0 | # Copyright (c) 2013 Red Hat Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... | nguage governing permissions and
# limitations under the License.
import uuid
import mock
import six
from sahara.service.validations.edp import job_executor as je
from sahara.tests.unit.service.validation import utils as u
from sahara.utils import edp
def wrap_it(data):
je.check_job_executor(data, 0)
clas | s FakeJob(object):
type = edp.JOB_TYPE_JAVA
libs = []
class TestJobExecJavaValidation(u.ValidationTestCase):
def setUp(self):
super(TestJobExecJavaValidation, self).setUp()
self._create_object_fun = wrap_it
self.scheme = je.JOB_EXEC_SCHEMA
@mock.patch('sahara.service.validati... |
insiderr/insiderr-app | app/modules/requests/packages/chardet/mbcharsetprober.py | Python | gpl-3.0 | 3,269 | 0.000306 | # ####################### BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Universal charset detector code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 2001
# the Initial Developer. All ... | ate == constants.eItsMe:
self._mState = constants.eFoundIt
break
elif codingState == constants.eStart:
charLen = self._mCodingSM.get_current_charlen()
if i == 0:
| self._mLastChar[1] = aBuf[0]
self._mDistributionAnalyzer.feed(self._mLastChar, charLen)
else:
self._mDistributionAnalyzer.feed(aBuf[i - 1:i + 1],
charLen)
self._mLastChar[0] = aBuf[aLen - 1]
i... |
pelgoros/kwyjibo | revisions/urls.py | Python | gpl-3.0 | 232 | 0.017241 | from django.conf.urls import url
from . import views
app_name = 'revisions'
urlpatterns = [
url(r'^revision/$', views.RevisionView.as_view | (), name = 'revisio | n'),
url(r'^mail/$', views.MailView.as_view(), name = 'mail'),
]
|
kambysese/mne-python | mne/dipole.py | Python | bsd-3-clause | 57,802 | 0.000017 | # -*- coding: utf-8 -*-
"""Single-dipole functions and classes."""
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Eric Larson <larson.eric.d@gmail.com>
#
# License: Simplified BSD
from copy import deepcopy
import functools
from functools import partial
import re
import numpy as np
from .cov ... | is
assumed to be zero (although it can be non-zero when a BEM is us | ed).
.. versionadded:: 0.15
khi2 : array, shape (n_dipoles,)
The χ^2 values for the fits.
.. versionadded:: 0.15
nfree : array, shape (n_dipoles,)
The number of free parameters for each fit.
.. versionadded:: 0.15
%(verbose)s
See Also
--------
fit_dipo... |
crs4/hl7apy | examples/iti_21/client.py | Python | mit | 1,870 | 0.004813 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2012-2018, CRS4
#
# 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... | e connection
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect((host, port))
# send the message
sock.sendall(parse_message(msg).to_mllp().encode('UTF-8'))
# receive the answer
received = sock.recv(1024*1024)
return r | eceived
finally:
sock.close()
if __name__ == '__main__':
res = query('localhost', 6789)
print("Received response: ")
print(repr(res))
|
badp/ganeti | lib/cmdlib/instance_operation.py | Python | gpl-2.0 | 17,072 | 0.007908 | #
#
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later... | CheckNodeOnline(self, self.instance.primary_node)
bep = self.cfg.GetClusterInfo().FillBE(self.instance)
bep.update(self.op.beparams)
# check bridges existence
CheckInstanceBridgesExi | st(self, self.instance)
remote_info = self.rpc.call_instance_info(
self.instance.primary_node, self.instance.name,
self.instance.hypervisor, cluster.hvparams[self.instance.hypervisor])
remote_info.Raise("Error checking node %s" %
self.cfg.GetNodeName(self.instanc... |
pezia/poker-croupier | player/py/lib/api/player_strategy/__init__.py | Python | gpl-2.0 | 52 | 0 | __all | __ = ['ttypes', | 'constants', 'PlayerStrategy']
|
verpoorten/immobilier | main/forms/suivi.py | Python | agpl-3.0 | 3,478 | 0.004037 | ##############################################################################
#
# Immobilier it's an application
# designed to manage the core business of property management, buildings,
# rental agreement and so on.
#
# Copyright (C) 2016-2018 Verpoorten Leïla
#
# This program is free software: you can... | See the
# GNU General Public License for more det | ails.
#
# A copy of this license - GNU General Public License - is available
# at the root of the source code of this program. If not,
# see http://www.gnu.org/licenses/.
#
##############################################################################
from django import forms
from main import models as mdl
fr... |
creasyw/IMTAphy | documentation/doctools/tags/0.4.2/sphinx/quickstart.py | Python | gpl-2.0 | 15,064 | 0.001062 | # -*- coding: utf-8 -*-
"""
sphinx.quickstart
~~~~~~~~~~~~~~~~~
Quickly setup documentation source to work with Sphinx.
:copyright: 2008 by Georg Brandl.
:license: BSD.
"""
import sys, os, time
from os import path
from sphinx.util import make_filename
from sphinx.util.console import purple, bold... | n html_static_path.
html_style = 'default.css'
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_s | hort_title = None
# The name of an image file (within the static path) to place at the top of
# the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None... |
internap/fake-switches | tests/cisco/test_cisco_switch_protocol.py | Python | apache-2.0 | 58,284 | 0.002316 | # Copyright 2015-2016 Internap.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | ---------------- ----- | ---- -------------------------------")
t.readln("1 default active Fa0/2, Fa0/3, Fa0/4, Fa0/5")
t.readln(" Fa0/6, Fa0/7, Fa0/8, Fa0/9")
t.readln(" Fa0/10, Fa0/11, Fa0/12")
... |
cloudera/hue | desktop/core/ext-py/pytest-4.6.11/doc/en/example/py2py3/conftest.py | Python | apache-2.0 | 348 | 0 | # -*- coding: utf-8 -*-
import sys
import pytest
py3 = sys.version_info[0] >= 3
class DummyCollector(pytest.collect.File):
def collect(self):
re | turn []
def pytest_pycollect_makemodule(path, parent):
bn = path.basename
if "py3" in bn and not py3 or ("py2" in bn and py3):
return DummyCollect | or(path, parent=parent)
|
dyoung418/tensorflow | tensorflow/python/estimator/export/export.py | Python | apache-2.0 | 14,219 | 0.005767 | # 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... | :
raise ValueError(
'feature {} must be a Tensor or SparseTensor.'.format(name))
if r | eceiver_tensors is None:
raise ValueError('receiver_tensors must be defined.')
if not isinstance(receiver_tensors, dict):
receiver_tensors = {_SINGLE_RECEIVER_DEFAULT_NAME: receiver_tensors}
for name, tensor in receiver_tensors.items():
if not isinstance(name, six.string_types):
raise ... |
thorwhalen/ut | daf/struct.py | Python | mit | 2,689 | 0.003719 | __author__ = 'thor'
import ut as ms
import pandas as pd
import ut.pcoll.order_conserving
from functools import reduce
class SquareMatrix(object):
def __init__(self, df, index_vars=None, sort=False):
if isinstance(df, SquareMatrix):
self = df.copy()
elif isinstance(df, pd.DataFrame):
... | ],
right_on=self.index_vars[0], suffixes=('', '_y'))
df[self.index_vars[1]] = df[self.index_var | s[1] + '_y']
df.drop(labels=[self.index_vars[0] + '_y', self.index_vars[1] + '_y'], axis=1, inplace=True)
if not isinstance(map_fun, dict) and broadcast_functions:
map_fun = dict(list(zip(self.value_vars, [map_fun] * len(self.value_vars))))
for k, v in map_fun.items():
d... |
WebArchivCZ/Seeder | Seeder/harvests/scheduler.py | Python | mit | 1,219 | 0.00082 | from datetime import date, timedelta
INITIAL_OFFSET = timedelta(days=5)
class IntervalException(Exception):
"""
Exception to be raises when interval is behaving
weirdly - as not an interval
"""
def get_dates_for_timedelta(interval_delta, start=None, stop=None,
skip_weeke... | val
:type start: date
:param stop: when to stop
:param skip_weekend: don't place dates at weekends
:return: [datetime objects]
"""
if start is None:
start = date.today()
if stop is None:
stop = start + timedelta(days=365)
dates = [start]
while dates[-1] + interval_... | if increased_date == dates[-1]:
raise IntervalException(interval_delta)
dates.append(increased_date)
return dates
|
jakob-o/django-filer | filer/fields/multistorage_file.py | Python | bsd-3-clause | 5,617 | 0.001068 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import base64
import hashlib
import warnings
from io import BytesIO
from django.core.files.base import ContentFile
from django.utils import six
from easy_thumbnails import fields as easy_thumbnails_fields
from easy_thumbnails import files as easy_thumbnai... | rFieldFile):
def __init__(self, instance, field, name):
"""
This is a little weird, but I couldn't find a better solution.
Thumbnailer.__init__ is called first for proper object inizialization.
| Then we override some attributes defined at runtime with properties.
We cannot simply call super().__init__ because filer Field objects
doesn't have a storage attribute.
"""
easy_thumbnails_files.Thumbnailer.__init__(self, None, name)
self.instance = instance
self.field ... |
pocketone/django-shoppy | shoppy/util/randomuserid.py | Python | bsd-3-clause | 499 | 0.012024 | import string
from random import | choice
from django.contrib.auth.models import User
def get_random_id():
valid_id = False
test_name = 'EMPTY'
while valid_id is False:
s1 = ''.join([choice(string.ascii_uppercase) for i in range(2)])
s2 = '' | .join([choice(string.digits) for i in range(8)])
test_name = u'%s%s' % (s1,s2)
try:
User.objects.get(username=test_name)
except:
valid_id = True
return test_name
|
blancoamor/crm_rma_blancoamor | crm_rma_blancoamor.py | Python | agpl-3.0 | 14,539 | 0.008941 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-today OpenERP SA (<http://www.openerp.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms o... | imedelta(days=int(stage['day_to_action_next']))
vals['user_id']=stage['user_id'][0]
if 'days_to_date_deadline' in stage and stage['days_to_date_deadline']:
vals['date_deadli | ne']=datetime.today()+timedelta(days=int(stage['days_to_date_deadline']))
return super(crm_claim, self).write(cr, uid, ids, vals, context=context)
def copy(self, cr, uid, _id, default={}, context=None):
default.update({
'number_id': self.pool.get('ir.sequence').get(cr, ... |
krafczyk/spack | var/spack/repos/builtin/packages/flang/package.py | Python | lgpl-2.1 | 3,969 | 0.000756 | ##############################################################################
# Copyright (c) 2017, Los Alamos National Security, LLC
# Produced at the Los Alamos National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, ... | self.spec['pgmath'].prefix.lib, self.spec.prefix.bin))
out.close()
chmod = which('chmod')
chmod('+x', flang)
def setup_environment(self, spack_env, run_env): |
# to find llvm's libc++.so
spack_env.set('LD_LIBRARY_PATH', self.spec['llvm'].prefix.lib)
run_env.set('FC', join_path(self.spec.prefix.bin, 'flang'))
run_env.set('F77', join_path(self.spec.prefix.bin, 'flang'))
run_env.set('F90', join_path(self.spec.prefix.bin, 'flang'))
|
gholt/python-brim | brim/wsgi_fs.py | Python | apache-2.0 | 9,657 | 0.000518 | """A WSGI application that simply serves up files from the file system.
.. warning::
This is an early version of this module. It has no tests, limited
documentation, and is subject to major changes.
Configuration Options::
[wsgi_fs]
call = brim.wsgi_fs.WSGIFS
# path = <path>
# The request ... | ' a {text-decoration: none;}\n'
' .colsize {text-align: right;}\n'
' </style>\n'
' </head>\n'
' <body>\n'
' <h1 id="title">Listing of %s</h1>\n'
' <table id="listing">\n'
' <tr id="heading">\n'
' <th class="col... | ATH_INFO'].count('/') > 1:
body += (
' <tr id="parent" class="item">\n'
' <td class="colname"><a href="../">../</a></td>\n'
' <td class="colsize"> </td>\n'
' <td class="coldate"> </td>\n'
' </tr>\n')
... |
vmthunder/nova | nova/network/api.py | Python | apache-2.0 | 23,489 | 0.000341 | # Copyright (c) 2011 X.commerce, a business unit of eBay Inc.
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2013 IBM Corp.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you... | IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# Licens | e for the specific language governing permissions and limitations
# under the License.
import functools
from oslo.config import cfg
from nova.compute import flavors
from nova import exception
from nova.i18n import _
from nova.network import base_api
from nova.network import floating_ips
from nova.network import m... |
iwm911/plaso | plaso/analysis/browser_search.py | Python | apache-2.0 | 6,727 | 0.008771 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2013 The Plaso Project Authors.
# Please see the AUTHORS file for details on individual 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 L... | nd search appear in string."""
return 'search' in string and 'q=' in string
@classmethod
def GoogleSearch(cls, url):
"""Return back the extracted string."""
if not cls._SearchAndQInLine(url):
return
line = cls._GetBetweenQEqualsAndAmbersand(url)
if not line:
return
return line... | ""Return back the extracted string."""
return cls.GenericSearch(url)
@classmethod
def GenericSearch(cls, url):
"""Return back the extracted string from a generic search engine."""
if not cls._SearchAndQInLine(url):
return
return cls._GetBetweenQEqualsAndAmbersand(url).replace('+', ' ')
@c... |
jackmaney/pg-utils | pg_utils/column/base.py | Python | mit | 10,187 | 0.002945 | import numpy as np
import pandas as pd
from lazy_property import LazyProperty
from . import _describe_template
from .plot import Plotter
from .. import bin_counts
from .. import numeric_datatypes, _pretty_print
from ..util import seaborn_required
class Column(object):
"""
In Pandas, a column of a DataFrame i... | left[overall_index] = entry[0]
right[overall_index] = entry[1]
| overall_index += 1
# We'll take our overall data points to be in the midpoint
# of each binning interval
# TODO: make this more configurable (left, right, etc)
return seaborn.distplot((left + right) / 2.0, **kwargs)
@LazyProperty
def values(self):
"""
... |
orokusaki/pycard | pycard/card.py | Python | mit | 7,293 | 0 | import re
from calendar import monthrange
import datetime
class Card(object):
"""
A credit card that may be valid or invalid.
"""
# A regexp for matching non-digit values
non_digit_regexp = re.compile(r'\D')
# A mapping from common credit card brands to their number regexps
BRAND_VISA = '... | RANDS.items():
if regexp.match(self.number):
return brand
| # Default to unknown brand
return self.BRAND_UNKNOWN
@property
def friendly_brand(self):
"""
Returns the human-friendly brand name of the card.
"""
return self.FRIENDLY_BRANDS.get(self.brand, 'unknown')
@property
def is_test(self):
"""
Returns... |
nburn42/tensorflow | tensorflow/contrib/autograph/pyct/parser_test.py | Python | apache-2.0 | 1,514 | 0.003303 | # | 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 applicab... | or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for parser module."""
from __future__ import absolute_import
from __future__ import division
from __future__ impor... |
knightmare2600/d4rkc0de | bruteforce/gmailbrute.py | Python | gpl-2.0 | 2,738 | 0.039445 | #!usr/bin/python
#Gmail Brute Forcer
#To use this script you need ClientCookie and Client Form.
#http://wwwsea | rch.sourceforge.net/ClientCookie/src/ClientCookie-1.0.3.tar.gz
#http://wwwsearch.sourceforge.net/ClientForm/src/ClientForm-0.1.17.tar.gz
#To install the package, run the following command:
#python setup.py build
#then (with appropriate permissions)
#python setup.py install
#http://www.darkc0de.com
#d3hydr8[at]gmail[do... |
import ClientForm
except(ImportError):
print "\nTo use this script you need ClientCookie and Client Form."
print "Read the top intro for instructions.\n"
sys.exit(1)
from copy import copy
if len(sys.argv) !=3:
print "Usage: ./gmailbrute.py <user> <wordlist>"
sys.exit(1)
try:
words = open(sys.argv[2], "r").r... |
adijo/rosalind | old/gene_enumerations.py | Python | gpl-2.0 | 682 | 0.014663 | #Aditya Joshi
#Enumerating Oriented Gene Ordering
from itertools import permutations,product
from math import fabs
n = int(raw_input())
def make_set(n):
set = []
for x in range(1,n+1):
set += [x]
return set
def plusAndMinusPermutations(items):
for p in permutations(items,len(i... | ign for a,si | gn in zip(p,signs)]
def array_to_string(list):
string = ""
string += str(list[0]) + " " + str(list[1])
return string
count = 0
for x in plusAndMinusPermutations(make_set(n)):
print array_to_string(x)
count += 1
print count
|
bmi-forum/bmi-pyre | pythia-0.8/packages/pyre/pyre/units/force.py | Python | gpl-2.0 | 545 | 0 | #!/usr/bin/env python
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | ~~
#
# Michael A.G. Aivazis
# California Institute of Technology
# (C) 1998-2005 All Rights Reserved
#
# <LicenseText>
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
from SI import me | ter, second
gal = 0.01*meter/second**2
# version
__id__ = "$Id: force.py,v 1.1.1.1 2005/03/08 16:13:41 aivazis Exp $"
#
# End of file
|
kave/Face-Off | face-off/settings/production.py | Python | cc0-1.0 | 866 | 0.001155 | from .base import *
import dj_database_url
if os.environ.get('DEBUG') == 'False':
DEBUG = False
else:
DEBUG = True
try:
from .local import *
except ImportError:
pass
ALLOWED_HOSTS = ['*']
DATABASES = {'default': dj_database_url.config()}
SOCIAL_AUTH_YAMMER_KEY = os.environ.get('SOCIAL_AUTH_YAMMER... | rage.S3PipelineManifestStorage'
STATIC_URL = 'http://s3.amazonaws.com/%s/' % AWS_STORAGE_BUCKET_NAME
AWS_QUERYSTRING_AUTH = False
AWS_S3_FILE_OVERWRITE = True
PIPELINE_JS_COMPRESSOR = 'pipeline.compressors.yuglify.YuglifyCompressor'
PIPELINE_CSS_COMPRESSOR = 'pipeline.compressors.yuglify. | YuglifyCompressor'
PIPELINE_YUGLIFY_BINARY = '/app/.heroku/python/bin/yuglify' |
rpiotti/Flask-AppBuilder | flask_appbuilder/models/base.py | Python | bsd-3-clause | 7,479 | 0.00107 | import datetime
import logging
from functools import reduce
from flask_babelpkg import lazy_gettext
from .filters import Filters
log = logging.getLogger(__name__)
class BaseInterface(object):
"""
Base class for all data model interfaces.
Sub class it to implement your own interface for some data ... | add_row_message = lazy_gettext('Added Row')
edit_row_message = lazy_gettext('Changed Row')
delete_row_message = lazy_gettext('Deleted Row')
delete_integrit | y_error_message = lazy_gettext('Associated data exists, please delete them first')
add_integrity_error_message = lazy_gettext('Integrity error, probably unique constraint')
edit_integrity_error_message = lazy_gettext('Integrity error, probably unique constraint')
general_error_message = lazy_gettext('Genera... |
cbrafter/CrowdTLL | generalCode/sumoConfigGen.py | Python | gpl-3.0 | 1,642 | 0.001827 | """
@file sumoConfigGen.py
@author Craig Rafter
@date 29/01/2016
Code to generate a config file for a SUMO model.
"""
def sumoConfigGen(modelname='simpleT', configFile='./models/simpleT.sumocfg',
exportPath='../', AVratio=0, stepSize=0.01,
run=0, port=8813):
configXML ... | output value="{expPath}vehroute{AVR:03d}_{Nrun:03d}.xml"/-->
<!--queue-output value="{expPath}queuedata{AVR:03d}_{Nrun:03d}.xml"/-->
</output>
<time>
<begin value="0"/>
<step-length value="{stepSz}"/>
</time>
<processing>
<!--TURN OFF TELEPORTING-->
<time-to-telep... | <no-step-log value="true"/>
<error-log value="logfile.txt"/>
</report>
<traci_server>
<remote-port value="{SUMOport}"/>
</traci_server>""".format(model=modelname, expPath=exportPath,
AVR=int(AVratio*100), stepSz=stepSize,
Nrun=... |
la0rg/Genum | GenumCore/vendor/urllib3/util/request.py | Python | mit | 2,180 | 0.000917 | from __future__ import absolute_import
from base64 import b64encode
from ..packages.six import b
ACCEPT_ENCODING = 'gzip,deflate'
|
def make_headers(keep_alive=None, accept_encoding=None, user_agent=None,
basic_auth=None, proxy_basic_auth=None, disable_cache=None):
"""
Shortcuts for generating request headers.
:param keep_alive:
If ``True``, adds 'connection: keep-alive' header.
:param accept_encoding:
... | to 'gzip,deflate'.
List will get joined by comma.
String will be used as provided.
:param user_agent:
String representing the user-agent you want, such as
"python-urllib3/0.6"
:param basic_auth:
Colon-separated username:password string for 'authorization: basic ...'
... |
mc10/project-euler | problem_2.py | Python | mit | 430 | 0.025701 | '''
Problem 2
@author: Kevin Ji
'''
def sum_even_fibonacci( max_value ):
# Initial two elements
prev_term = 1
cur_term = 2
tem | p_sum = 2
while cur_term < max_value:
next_term = prev_term + cur_term
prev_term = cur_term
cur_term = next_term
if cur_term % 2 | == 0:
temp_sum += cur_term
return temp_sum
print( sum_even_fibonacci( 4000000 ) )
|
titilambert/home-assistant | tests/components/hue/test_init.py | Python | apache-2.0 | 8,339 | 0.00024 | """Test Hue setup process."""
from unittest.mock import Mock
import pytest
from homeassistant import config_entries
from homeassistant.components import hue
from homeassistant.setup import async_setup_component
from tests.async_mock import AsyncMock, patch
from tests.common import MockConfigEntry
@pytest.fixture
d... | set yet."""
MockConfigEntry(
domain=hue.DOMAIN,
data={"host": "0.0.0.0"},
unique_id="mock-id",
source=config_ | entries.SOURCE_IGNORE,
).add_to_hass(hass)
entry = MockConfigEntry(
domain=hue.DOMAIN, data={"host": "0.0.0.0"}, unique_id="invalid-id",
)
entry.add_to_hass(hass)
assert await async_setup_component(hass, hue.DOMAIN, {}) is True
await hass.async_block_till_done()
assert entry.unique_i... |
aspc/mainsite | aspc/folio/views.py | Python | mit | 1,132 | 0.007951 | from django.views.generic.detail import DetailView
from django.shortcuts import render, redirect
from django.http import Http404
from aspc.folio.models import Page
class AttachedPageMixin(object):
def get_page(self):
try:
return Page.objects.get(slug=self.page_slug)
except Page.DoesNotE... | ):
context = super(AttachedPageMixin, self).get_context_data(**kwargs)
context['page'] = self.get_page()
return context
def page_view(request, slug_path):
'''slug_path: ^(?P<slug_path>(?:[\w\-\d]+/)+)$ '''
slug_parts = slug_path.rstrip('/').split('/')
p | ages = Page.objects.exclude(managed=True)
for part in slug_parts:
try:
new_page = pages.get(slug=part)
except Page.DoesNotExist:
raise Http404
else:
pages = new_page.page_set.all()
return render(request, "folio/page.html", {
"title": new_p... |
shakamunyi/nova | nova/api/openstack/compute/plugins/v3/tenant_networks.py | Python | apache-2.0 | 8,183 | 0.000122 | # Copyright 2013 OpenStack Foundation
# 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 requ... | urce('networks',
| _sync_networks,
'quota_networks' |
tensorflow/graphics | tensorflow_graphics/geometry/__init__.py | Python | apache-2.0 | 1,274 | 0.005495 | # Copyright 2020 The TensorFlow Authors
#
# Licensed under the Apache License, Ver | sion 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, software
# distributed under the License is distr | ibuted 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.
"""Geometry module."""
from __future__ import absolute_import
from __future__ import division
from __future__ impo... |
rafa1231518/CommunityBot | plugins/gabenizer/mentions.py | Python | gpl-3.0 | 499 | 0.02004 | #!/bin/pytho | n2
# Script that replies to username mentions.
import time
import os
import cPickle
import sys
import traceback
import numpy
import sys
from PIL import Image
from urlparse import urlparse
import gabenizer
IMG = "http://i.4cdn.org/r9k/1463377581531.jpg"
def main():
image = gabenizer.process_image(sys.ar... | ugins/gabenizer/gabenface.png')
image.save("./plugins/gabenizer/whatfuck.png")
if __name__ == "__main__":
main()
|
eaplatanios/tensorflow | tensorflow/python/ops/sparse_ops.py | Python | apache-2.0 | 82,052 | 0.002803 | # 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... | pe = [3, 3]
[0, 2]: "a"
[1, 0]: "b"
[2, 1]: "c"
sp_inputs[1]: shape = [2, 4]
[0, 1]: "d"
[0, 2]: "e"
if expand_nonconcat_dim = False, this will result in an error. But if
expand_nonconcat_dim = True, this will result in:
shape = [3, 7]
[0, 2]: "a | "
[0, 4]: "d"
[0, 5]: "e"
[1, 0]: "b"
[2, 1]: "c"
Graphically this is equivalent to doing
[ a] concat [ d e ] = [ a d e ]
[b ] [ ] [b ]
[ c ] [ c ]
Args:
axis: Dimension to concatenate along. Mus... |
MicroTrustRepos/microkernel | src/l4/pkg/python/contrib/Lib/os.py | Python | gpl-2.0 | 26,337 | 0.003038 | r"""OS routines for Mac, NT, or Posix depending on what system we're on.
This exports:
- all functions from posix, nt, os2, or ce, e.g. unlink, stat, etc.
- os.path is one of the modules posixpath, or ntpath
- os.name is 'posix', 'nt', 'os2', 'ce' or 'riscos'
- os.curdir is a string representing the current di... | generated by the time dirnames itself is
generated.
By default errors from the os.listdir() call are ignored. If
optional arg 'onerror' is specified, it should be a function; it
will be called with one argument, an os.error instance. It can
report the error to continue with the walk, or raise the... | lk. Note that the filename is available as the
filename attribute of the exception object.
By default, os.walk does not follow symbolic links to subdirectories on
systems that support them. In order to get this functionality, set the
optional argument 'followlinks' to true.
Caution: if you pass... |
ChinaMassClouds/copenstack-server | openstack/src/nova-2014.2/nova/objects/agent.py | Python | gpl-2.0 | 2,828 | 0 | # Copyright 2014 Red Hat, Inc
#
# Licensed under the Apache License, Version 2. | 0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ | ing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from nova import db
from nova import exception
... |
italopaiva/propositional-logic | lp/syntax.py | Python | mit | 7,307 | 0.002874 | """Describe the language syntax."""
import re
class Symbol:
"""Describes the language symbols."""
# General pattern of formulas
pattern = '([a-z0-9&\-\|><\(\)]*)'
accepted_chars = '([a-z0-9&\-\|><\(\)]*)'
def __init__(self, value):
"""Init a propositional symbol."""
self.value =... | ntation()
else:
arg2_repr = '(' + self.arg2.str_representation() + ')'
return arg1_repr + self.SYMBOL + arg2_repr
def count_terms(self):
"""Count the terms of the formula."""
return 1 + self.arg1.count_terms() + self.arg2.count_terms()
class UnaryOperator(Operator):
... |
def set_arg(self, arg):
"""Set the operator arg."""
self.arg1 = arg
def subformulas(self):
"""
Get the formula subformulas.
Return itself and the subformulas of its arg.
"""
return self.arg1.subformulas() + [self]
def str_representation(self):
... |
aarpon/obit_microscopy_core_technology | core-plugins/microscopy/3/dss/drop-boxes/MicroscopyDropbox/GenericTIFFSeriesMaximumIntensityProjectionGenerationAlgorithm.py | Python | apache-2.0 | 1,343 | 0.005957 | # -*- coding: utf-8 -* | -
'''
Created on Apr 27, 2016
@author: Aaron Ponti
'''
from ch.systemsx.cisd.openbis.dss.etl.dto.api.impl import MaximumIntensityProjectionGenerationAlgorithm
class GenericTIFFSeriesMaximumIntensityProjectionGenerationAlgorithm(MaximumIntensityProjectionGenerationAlgorithm):
| '''
Custom MaximumIntensityProjectionGenerationAlgorithm for Generic TIFF Series
that makes sure that the first timepoint in a series is registered for
creation of the representative thumbnail.
'''
def __init__(self, datasetTypeCode, width, height, filename):
"""
Constructor
... |
javiteri/reposdmpdos | miltonvz/run.py | Python | gpl-2.0 | 176 | 0.005682 | '' | '
Created on 17/2/2015
@author: PC06
Primer cambio en el proyecto
'''
from include import app
if __name__ == '__main__':
app.run( | "127.0.0.1", 9000, debug=True) |
greggian/TapdIn | django/utils/translation/trans_real.py | Python | apache-2.0 | 20,192 | 0.00213 | """Translation helper functions."""
import locale
import os
import re
import sys
import gettext as gettext_module
from cStringIO import StringIO
from django.utils.importlib import import_module
from django.utils.safestring import mark_safe, SafeData
from django.utils.thread_support import currentThread
... | app = import_module(appname)
apppath = os.path.join(os.path.dirname(app.__file__), 'locale')
if os.path.isdir(apppath):
res = _merge(apppath)
if res is None:
if fallback is not None:
res = | fallback
else:
return gettext_module.NullTranslations()
_translations[lang] = res
return res
default_translation = _fetch(settings.LANGUAGE_CODE)
current_translation = _fetch(language, fallback=default_translation)
return current_translation
def act... |
finiteloopsoftware/django-compressor | compress/utils.py | Python | bsd-3-clause | 69 | 0 | def get_file_exten | sio | n(filename):
return filename.split(".")[-1]
|
openstack/designate | designate/schema/__init__.py | Python | apache-2.0 | 3,897 | 0 | # Copyright 2012 Managed I.T.
#
# Author: Kiall Mac Innes <kiall@managedit.ie>
#
# 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 r... | name] = self._filter_array(subinsta | nce, subschema)
elif 'type' in subschema and subschema['type'] == 'object':
subinstance = instance.get(name, None)
properties = subschema['properties']
filtered[name] = self.filter(subinstance, properties)
else:
filtered[name] = ins... |
hanfang/glmnet_python | glmnet_python/cvglmnet.py | Python | gpl-2.0 | 14,450 | 0.010242 | # -*- coding: utf-8 -*-
"""
--------------------------------------------------------------------------
cvglmnet.m: cross-validation for glmnet
--------------------------------------------------------------------------
DESCRIPTION:
Does k-fold cross-validation for glmnet, produces a plot, and returns
a value ... | nd Rob Tibshirani
Fortran code was written by Jerome Friedman
R wrapper (from which the MATLAB wrapper was adapted) was written by Trevor Hasite
The original MATLAB wrapper was written by Hui Jiang,
and is updated and maintained by Junyang Qian.
This Python wrapper (adapted from the Matlab and R wra... | ERENCES:
Friedman, J., Hastie, T. and Tibshirani, R. (2008) Regularization Paths for Generalized Linear Models via Coordinate Descent,
http://www.jstatsoft.org/v33/i01/
Journal of Statistical Software, Vol. 33(1), 1-22 Feb 2010
Simon, N., Friedman, J., Hastie, T., Tibshirani, R. (2011) Regularizat... |
WalkingMachine/sara_behaviors | sara_flexbe_behaviors/src/sara_flexbe_behaviors/init_sequence_sm.py | Python | bsd-3-clause | 2,331 | 0.023595 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###########################################################
# WARNING: Generated code! #
# ************************** #
# Manual changes may get lost if file is generated again. #
# Only code inside the [MANUAL] ta... | e import Behavior, Autono | my, OperatableStateMachine, ConcurrencyContainer, PriorityContainer, Logger
from sara_flexbe_states.sara_set_head_angle import SaraSetHeadAngle
from sara_flexbe_states.run_trajectory import RunTrajectory
from sara_flexbe_states.set_gripper_state import SetGripperState
# Additional imports can be added inside the follow... |
h-mayorquin/g_node_data_analysis_205 | 1_day/fit_data.py | Python | bsd-2-clause | 1,957 | 0.001533 | import numpy as np
import matplotlib.pyplot as plt
from math import exp
size = 9
dt = 50.0 # ms
dt_2 = 550.0
# Vectors to fit
x_fit = np.zeros(size)
V_max_fit = np.zeros(size)
V0_fit = np.zeros(size)
# Paramters of the model
tau_rec = 1000.0 # ms
tau_mem = 32.0 # ms
tau_in = 1.8 # ms
A = 144.0
u = 0.26
# First ... | x1 ex2', ex1, ex2
problem = ex1 - ex2
problem = ex1 - ex2
this = alpha_fit[-2] * tau_in / tau_diff
that = V0_fit[-2] * exp(-dt_2 / tau_mem)
V0_fit[-1] = that + this * problem
aux = alpha_fit[-1] * tau_mem / (alpha_fit[-1]
* tau_in - V0_fit[-1] * tau_diff)
V_max_fit[-1] = alpha_fit[-1... | (1, 2, 2)
plt.plot(V_max_fit, '*-', label='Vmax_fit')
plt.hold(True)
plt.plot(V0_fit, '*-', label='V0_fit')
plt.legend()
plt.show()
|
mrozekma/Sprint | WebSocket.py | Python | mit | 3,192 | 0.030075 | try:
from tornado.websocket import WebSocketHandler
import tornado.ioloop
tornadoAvailable = True
except ImportError:
class WebSocketHandler(object): pass
tornadoAvailable = False
from json import loads as fromJS, dumps as toJS
from threading import Thread
from Log import console
import Settings
from utils impor... | value else 0
description = ("%s by %s" % (verbs[field], task.creator)) if field in verbs else None
WebSocket.sendChannel("backlog#%d" % task.spri | nt.id, {'type': 'update', 'id': task.id, 'revision': task.revision, 'field': field, 'value': value, 'description': description, 'creator': task.creator.username})
addEventHandler(ShareTaskChanges())
|
reingart/vb2py | vb2py/test/testparser.py | Python | gpl-3.0 | 41,055 | 0.003898 | #
# Turn off logging in extensions (too loud!)
import vb2py.extensions
vb2py.extensions.disableLogging()
from vb2py.vbparser import buildParseTree, VBParserError
#
# Set some config options which are appropriate for testing
import vb2py.config
Config = vb2py.config.VB2PYConfig()
Config.setLocalOveride("General", "Rep... | ,
"a = ((10+20)+(30+40))",
])
# Conditional expressions
tests.extend(["a = a = 1",
"a = a <> 10",
"a = a > 10",
"a = a < 10",
"a = a <= 10",
"a = a >= 10",
"a = a = 1 And b = 2",
"a = a = 1 Or b = 2",
... | Or Not b",
"a = Not a = 1",
"a = Not a",
"a = a Xor b",
"a = b Is Nothing",
"a = b \ 2",
"a = b Like c",
'a = "hello" Like "goodbye"',
])
# Things that failed
tests.extend([
"a = -(x*x)",
"a = -x*... |
taxpon/sverchok | old_nodes/matrix_in.py | Python | gpl-3.0 | 2,720 | 0.003309 | # ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distrib... | nklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
import bpy
import mathutils
from sverchok.node_tree import SverchCustomTreeNode
from sverchok.data_structure import (matrixdef, Matrix_listing, Vector_generate)
class MatrixGenNode(bpy.types.Node, SverchCustomTreeNode):
... | ix in'
bl_icon = 'OUTLINER_OB_EMPTY'
def sv_init(self, context):
s = self.inputs.new('VerticesSocket', "Location")
s.use_prop = True
s = self.inputs.new('VerticesSocket', "Scale")
s.use_prop = True
s.prop = (1, 1 , 1)
s = self.inputs.new('VerticesSocket', "Rotati... |
PennyDreadfulMTG/Penny-Dreadful-Discord-Bot | logsite/views/match_view.py | Python | gpl-3.0 | 2,353 | 0.002125 | import html
import inflect
import titlecase
from flask import url_for
from shared.pd_exception import DoesNotExistException
from .. import APP, importing
from ..data import match
from ..view import View
@APP.route('/match/<int:match_id>/')
def show_match(match_id: int) -> str:
view = Match(match.get_match(matc... | lf.game_three = viewed_match.games[2]
if viewed_match.has_unexpected_third_game is None:
importing.reimport(viewed_match)
self.has_unexpected_third_game = viewed_match.has_unexpected_third_game
if viewed_match.is_tournament is None:
importing.reimport(viewed_match)
... | eturn self.players_string
def og_url(self) -> str:
return url_for('show_match', match_id=self.id, _external=True)
def og_description(self) -> str:
p = inflect.engine()
fmt = titlecase.titlecase(p.a(self.format_name))
description = '{fmt} match.'.format(fmt=fmt)
return d... |
jonaustin/advisoryscan | django/django/contrib/localflavor/it/it_province.py | Python | mit | 2,747 | 0.001458 | # -*- coding: utf-8 -*
PROVINCE_CHOICES = (
('AG', 'Agrigento'),
('AL', 'Alessandria'),
('AN', 'Ancona'),
('AO', 'Aosta'),
('AR', 'Arezzo'),
('AP', 'Ascoli Piceno'),
('AT', 'Asti'),
('AV', 'Avellino'),
('BA', 'Bari'),
# ('BT', 'Barletta-Andria-Trani'), # active starting from 2009... | ,
('SA', 'Salerno'),
('SS', 'Sassari'),
('SV', 'Savona'),
('SI', 'Siena'),
('SR', 'Siracusa'),
('SO', 'Sondrio'),
('TA', 'Taranto'),
('TE', 'Teramo'),
('TR', 'Terni'),
('TO', 'Torino'),
('TP', 'Trapani'),
('TN', 'Trento'),
('TV', 'Treviso'),
('TS', 'Trieste'),
... | Ossola'),
('VC', 'Vercelli'),
('VR', 'Verona'),
('VV', 'Vibo Valentia'),
('VI', 'Vicenza'),
('VT', 'Viterbo'),
)
|
openstack/heat | heat/engine/resources/openstack/trove/instance.py | Python | apache-2.0 | 29,344 | 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
# ... | r'[a-zA-Z0-9_\-]+'),
| ]
),
},
)
),
USERS: properties.Schema(
properties.Schema.LIST,
_('List of users to be created on DB instance creation.'),
default=[],
update_allowed=True,
schema=properties.Schema(
... |
franklingu/Cassandra-benchmarking | benchmarking/sum_up.py | Python | mit | 1,889 | 0.004764 | #!/usr/bin/python
import re
import csv
import os
import json
def read_csv(fn):
results = {}
with open(fn, 'rb') as csvfile:
rows = csv.reader(csvfile, delimiter=',')
for row in rows:
m = re.search('Total Transactions', row[1])
if len(row) == 7 and m:
tem... | ['Time used'], v1['Throughput']])
wi | th open('compilation.csv', 'wb') as f:
writer = csv.writer(f)
writer.writerows(rows)
|
johnjohnlin/nicotb | lib/event.py | Python | gpl-3.0 | 1,550 | 0.013548 | # Copyright (C) 2017,2019, Yu Sheng Lin, johnjohnlys@media.ee.ntu.edu.tw
# This file is part of Nicotb.
# Nicotb 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... | vent(ev: int):
# Do not destroy events created with hier name
waiting_coro[ev] = list()
event_released.add(ev)
# Initialize a default event, so coroutines can implement SystemC-like dont_initialize
INIT_EVENT = CreateEvent()
SignalEvent(INIT_EVENT | )
|
jgillis/casadi | experimental/joel/vdp/vdp.py | Python | lgpl-3.0 | 5,909 | 0.019293 | #
# This file is part of CasADi.
#
# CasADi -- A symbolic framework for dynamic optimization.
# Copyright (C) 2010 by Joel Andersson, Moritz Diehl, K.U.Leuven. All rights reserved.
#
# CasADi is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Pub... | .parse()
# Print the ocp to screen
print ocp
# Sort the variables according to type
var = OCPVariables(ocp.variables)
# The right hand side of the ACADO functions
acado_in = ACADO_FCN_NUM_IN * [[]]
# Time
acado_in[ACADO_FCN_T] = [var.t_]
# Convert stl vector of variables to list of expressions
def toList(v, der=Fa... | = []
for i in v:
if der:
ret.append(i.der())
else:
ret.append(i.var())
return ret
# Differential state
acado_in[ACADO_FCN_XD] = toList(ocp.x_)
# Algebraic state
acado_in[ACADO_FCN_XA] = toList(ocp.z_)
# Control
acado_in[ACADO_FCN_U] = toList(ocp.u_)
# Parameter
acado_in[ACADO_FCN_P] = toLi... |
sandeep6189/Pmp-Webapp | migrations/versions/4fe34588268f_.py | Python | bsd-3-clause | 506 | 0.011858 | """empty message
Revision ID: 4fe34588268f
Revises: 26dba2ff3e74
Create Date: 2014-12-09 0 | 1:41:24.333058
"""
# revision identifiers, used by Alembic.
revision = '4fe34588268f'
down_revision = '26dba2ff3e74'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
pass
### end Alembic commands ###
def downgrade():
### com... | |
wy65701436/harbor | make/photon/prepare/utils/registry_ctl.py | Python | apache-2.0 | 1,152 | 0.002604 | import os
from g import config_dir, templates_dir, DEFAULT_GID, DEFAULT_UID
from utils.misc import prepare_dir
from utils.jinja import render_jinja
registryctl_config_dir = os.path.join(config_dir, "registryctl")
registryctl_config_template_path = os.path.join(templates_dir, "registryctl", "config.yml.jinja")
registr... | mplate_path = os.path.join(templates_dir, "registryctl", "env.jinja")
registryctl_conf_env = os.path.join(config_dir, "registryctl", "env")
levels_map = {
'debug': 'debug',
'info': 'info',
'warning': 'warn',
'error': 'error',
'fatal': 'fatal'
}
def prepare_registry_ctl(config_dict):
# prepare ... | ctl_env_template_path,
registryctl_conf_env,
**config_dict)
# Render Registryctl config
render_jinja(
registryctl_config_template_path,
registryctl_conf,
uid=DEFAULT_UID,
gid=DEFAULT_GID,
level=levels_map[config_dict['log_level']],
**config_dict)
|
dagnelies/pysos | test_dict.py | Python | apache-2.0 | 1,567 | 0.007658 | import time
import test_rnd as rnd
import random
import pysos
# initialize the data
N = 1234
items = [(rnd.utf8(20), rnd.utf8(200)) for i in range(N)]
start = time.time()
db = pysos.Dict('temp/sos_dict')
#import shelve
#db = shelve.open('temp.shelve')
print("%.2fs: %d items loaded" % (time.time() - start, len(db)... | ]
print("%.2fs: %d items deleted" % (time.time() - start, len(items)))
# add all keys
random.shuffle(items)
| for key,val in items:
db[key] ='again ' + val
print("%.2fs: %d items added" % (time.time() - start, len(items)))
# read all keys again
random.shuffle(items)
for key,val in items:
val = db[key]
print("%.2fs: %d items read" % (time.time() - start, len(items)))
N = len(db)
db.close()
print("%.2fs: DB closed cont... |
chrisRubiano/TAP | indexing/buscar.py | Python | gpl-3.0 | 633 | 0.00158 | import sys
import argpars | e
import pickle
def read_index(pickleFile):
pickleFile = open(pickleFile, 'rb')
index = pickle.load(pickleFile)
return index
def main(args):
wordIndex = read_index('indice.pickle')
docIndex = read_index('indice_doc.pickle')
wordList = args.palabras
for word in wordList:
print wor... | alabras', metavar='N', type=str, nargs='+', help='Palabras a buscar en el indice')
args = parser.parse_args()
main(args)
|
mikaelboman/home-assistant | homeassistant/components/dweet.py | Python | mit | 1,961 | 0 | """
A component which allows you to send data to Dweet.io.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/dweet/
"""
import logging
from datetime import timedelta
import voluptuous as vol
from homeassistant.const import EVENT_STATE_CHANGED, STATE_UNKNO... | ottle
_LOGGER = logging.getLogger(__name__)
DOMAIN = "dweet"
DEPENDENCIES = []
REQUIREMENTS = ['dweepy==0.2.0']
CONF_NAME = 'name'
CONF_WHITELIST = 'whitelist'
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=1)
CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({
vol.Required(CONF_NAME): cv.string,
... | tup the Dweet.io component."""
conf = config[DOMAIN]
name = conf[CONF_NAME]
whitelist = conf.get(CONF_WHITELIST, [])
json_body = {}
def dweet_event_listener(event):
"""Listen for new messages on the bus and sends them to Dweet.io."""
state = event.data.get('new_state')
if st... |
clchiou/scons_package | label.py | Python | mit | 4,231 | 0 | # Copyright (c) 2013 Che-Liang Chiou
import os
import re
from SCons.Script import Dir
class Label(object):
VALID_NAME = re.compile(r'^[A-Za-z0-9_.\-/]+$')
@classmethod
def make_label(cls, label_str):
package_str = None
target_str = None
if not isinstance(label_str, str):
... | str = label_str.srcnode().path
package_str, target_str = os.path.split(label_str)
elif label_str.startswith('#'):
label_str = label_str[1:]
if ':' in label_str:
| package_str, target_str = label_str.split(':', 1)
else:
package_str = label_str
elif label_str.startswith(':'):
target_str = label_str[1:]
else:
target_str = label_str
package_name = PackageName.make_package_name(package_str)
... |
abloomston/sympy | sympy/polys/tests/test_polytools.py | Python | bsd-3-clause | 106,107 | 0.001301 | """Tests for user-friendly public interface to polynomial functions. """
from sympy.polys.polytools import (
Poly, PurePoly, poly,
parallel_poly_from_expr,
degree, degree_list,
LC, LM, LT,
pdiv, prem, pquo, pexquo,
div, rem, quo, exquo,
half_gcdex, gcdex, invert,
subresultants,
resu... | =QQ))
assert Poly.from_poly(f, gens=(x, y)) == Poly(x + 7, x, y, domain='ZZ')
assert Poly.from_poly(
| f, gens=(x, y), domain=ZZ) == Poly(x + 7, x, y, domain='ZZ')
assert Poly.from_poly(
f, gens=(x, y), domain=QQ) == Poly(x + 7, x, y, domain='QQ')
assert Poly.from_poly(
f, gens=(x, y), modulus=3) == Poly(x + 7, x, y, domain='FF(3)')
K = FF(2)
assert Poly.from_poly(g) == g
as... |
mateusz-blaszkowski/PerfKitBenchmarker | perfkitbenchmarker/linux_benchmarks/mysql_service_benchmark.py | Python | apache-2.0 | 33,031 | 0.004874 | # Copyright 2014 PerfKitBenchmarker 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 appli... | # total wait time is therefore: "query interval * query limit"
| DB_STATUS_QUERY_LIMIT = 200
# Map from FLAGs.mysql_svc_db_instance_cores to RDS DB Type
RDS_CORE_TO_DB_CLASS_MAP = {
'1': 'db.m3.medium',
'4': 'db.m3.xlarge',
'8': 'db.m3.2xlarge',
'16': 'db.r3.4xlarge', # m3 series doesn't have 16 core.
}
RDS_DB_ENGINE = 'MySQL'
RDS_DB_ENGINE_VERSION = '5.6.23'
RDS_... |
eric-stanley/robotframework | src/robot/libraries/Screenshot.py | Python | apache-2.0 | 13,020 | 0.000998 | # Copyright 2008-2014 Nokia Solutions and Networks
#
# 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 l... | return os.path.normpath(path.replace('/', os.sep))
@property
def _screenshot_dir(self):
return self._given_screenshot_dir or self._log_dir
@property
def _log_dir(self):
variables = BuiltIn().get_variables()
outdir = variables['${OUTPUTDIR}']
log = variables['${L... | log = os.path.dirname(log) if log != 'NONE' else '.'
return self._norm_path(os.path.join(outdir, log))
def set_screenshot_directory(self, path):
"""Sets the directory where screenshots are saved.
It is possible to use `/` as a path separator in all operating systems.
Path to th... |
ardhipoetra/SDN-workbench | sch3.py | Python | gpl-2.0 | 3,578 | 0.044159 | #!/usr/bin/python
from mininet.net import Mininet
from mininet.node import Controller, RemoteController
from mininet.cli import CLI
from mininet.log import setLogLevel, info
import time
import os
import subprocess
import csv
import StringIO
import iptc
HOSTS = 3
p1_log = open('logs-example/log.p1.txt', 'w')
p2_log... | e.protocol = "tcp"
matc | h = rule.create_match("tcp")
match.dport = str(port)
chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "INPUT")
rule.target = rule.create_target("DROP")
chain.delete_rule(rule)
def myNet():
global p1
global p2
global p3
global p4
cPort1=6666
cPort2=6667
hosts=[]
kill = 0
net = Mininet( topo=None, build... |
davesnowdon/nao-recorder | src/main/python/fluentnao/nao.py | Python | gpl-2.0 | 10,366 | 0.006946 | '''
Created on 31st October , 2012
@author: Don Najd
'''
import logging
from naoutil.naoenv import NaoEnvironment, make_environment
from fluentnao.core.arms import Arms
from fluentnao.core.elbows import Elbows
from fluentnao.core.feet import Feet
from fluentnao.core.hands import Hands
from fluentnao.core.head import... | it", speed))
self.env.robotPosture.post.goToPosture("Sit", speed)
self.env.motion.waitUntilMoveIsFinished();
return self;
###################################
# stiffness
###################################
| def stiff(self):
pNames = self.joints.Chains.Body
pStiffnessLists = 1.0
pTimeLists = 1.0
self.env.motion.stiffnessInterpolation(pNames, pStiffnessLists, pTimeLists)
return self;
def rest(self):
self.env.motion.rest()
return self;
def relax(self):
... |
aviarypl/mozilla-l10n-addons-server | src/olympia/api/models.py | Python | bsd-3-clause | 3,638 | 0 | import binascii
import os
import random
from django.db import models
from django.utils.encoding import force_text, python_2_unicode_compatible
from aesfield.field import AESField
from | olympia.amo.fields import PositiveAutoField
from olympia.amo.models import ModelBase
from olympia.users.models import UserProfile
# These are identifiers for the type of API keys that can be stored
# in our database.
SYMMETRIC_JWT_TYPE = 1
API_KEY_TYPES = [
SYMMETRIC_JWT_TYPE,
]
@python_2_unicode_ | compatible
class APIKey(ModelBase):
"""
A developer's key/secret pair to access the API.
"""
id = PositiveAutoField(primary_key=True)
user = models.ForeignKey(UserProfile, related_name='api_keys')
# A user can only have one active key at the same time, it's enforced by
# a unique db constra... |
epinna/weevely3 | tests/test_file_bzip2.py | Python | gpl-3.0 | 5,554 | 0.009903 | from tests.base_test import BaseTest
from tests import config
from core import modules
from core.sessions import SessionURL
from testfixtures import log_capture
from core import messages
import logging
import os
import subprocess
class FileBzip(BaseTest):
# Create and bzip2 binary files for the test
binstring... | self.assertTrue(self.run_argv(["--decompress", self.compressed[0]]));
self.assertEqual(
subprocess.check_output('cat "%s"' % self.uncompressed[0], shell=True),
self.binstring[0]
)
# Recompress it keeping the original file
self.assertTrue(self.run_argv([... | xistance of the original file and remove it
subprocess.check_call('stat -c %%a "%s"' % self.uncompressed[0], shell=True)
subprocess.check_call('rm "%s"' % self.uncompressed[0], shell=True)
#Do the same check
self.assertTrue(self.run_argv(["--decompress", self.compressed[0]]... |
Karaage-Cluster/karaage | karaage/common/__init__.py | Python | gpl-3.0 | 5,700 | 0 | # Copyright 2010-2017, The University of Melbourne
# Copyright 2010-2017, Brian May
#
# This file is part of Karaage.
#
# Karaage 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... | t = QueryDict("", mutable=True)
result['content_type'] = ContentType.objects.get_for_model(obj).pk
result['obj | ect_id'] = obj.pk
url = reverse('kg_log_list') + "?" + result.urlencode()
return HttpResponseRedirect(url)
def add_comment(request, breadcrumbs, obj):
assert obj is not None
assert obj.pk is not None
form = CommentForm(
data=request.POST or None, obj=obj,
request=request, instance=... |
mistercrunch/airflow | tests/sensors/test_external_task_sensor.py | Python | apache-2.0 | 35,537 | 0.002561 | #
# 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... | .test_time_sensor(task_id=TEST_TASK_ID_ALTERNATE)
op = ExternalTaskSensor(
task_id='test_external_task_sensor_check_task_ids',
external_dag_id=TEST_DAG_ID,
external_task_ids=[TEST_TASK_ID, TEST_TASK_ID_ALTERNATE],
dag=self.dag,
)
op.run(start_date=... | =DEFAULT_DATE, ignore_ti_state=True)
def test_catch_overlap_allowed_failed_state(self):
with pytest.raises(AirflowException):
ExternalTaskSensor(
task_id='test_external_task_sensor_check',
external_dag_id=TEST_DAG_ID,
external_task_id=TEST_TASK_ID... |
tritoanst/ccxt | python/ccxt/async/bit2c.py | Python | mit | 6,650 | 0.001353 | # -*- coding: utf-8 -*-
from ccxt.async.base.exchange import Exchange
import hashlib
class bit2c (Exchange):
def describe(self):
return self.deep_extend(super(bit2c, self).describe(), {
'id': 'bit2c',
'name': 'Bit2C',
'countries': 'IL', # Israel
'rateLimi... | e': self.iso8601(timestamp),
'high': None,
'low': None,
'bid': float(ticker['h']),
'ask': float(ticker['l']),
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': float(ticker['ll']),
'ch... | oteVolume': quoteVolume,
'info': ticker,
}
def parse_trade(self, trade, market=None):
timestamp = int(trade['date']) * 1000
symbol = None
if market:
symbol = market['symbol']
return {
'id': str(trade['tid']),
'info': trade,
... |
richardliaw/ray | rllib/examples/models/batch_norm_model.py | Python | apache-2.0 | 7,538 | 0 | import numpy as np
from ray.rllib.models.modelv2 import ModelV2
from ray.rllib.models.tf.misc import normc_initializer
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
from ray.rllib.models.torch.misc import SlimFC, normc_initializer as \
torch_normc_initializer
from ray.rllib.models.torch.torch_modelv2 import... | elf._value_out, [-1])
class KerasBatchNormModel(TFModelV2):
"""Keras version of above BatchNormModel with exactly the same structure.
IMORTANT NOTE: This model will not work with PPO due to a bug in keras
that surfaces when having more than one input place | holder (here: `inputs`
and `is_training`) AND using the `make_tf_callable` helper (e.g. used by
PPO), in which auto-placeholders are generated, then passed through the
tf.keras. models.Model. In this last step, the connection between 1) the
provided value in the auto-placeholder and 2) the keras `is_tra... |
pytroll/satpy | satpy/modifiers/__init__.py | Python | gpl-3.0 | 1,328 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2020 Satpy developers
#
# This file is part of satpy.
#
# satpy 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... | elated utilities."""
# file deepcode ignore W0611: Ignore unused imports in init module
from .base import ModifierBase # noqa: F401, isort: skip
from .atmosphere import CO2Corrector # noqa: F401
from .atmosphere import PSPAtmosphericalCorrection # noqa: F401
from .atmosphere import PSPRayleighReflectance # noqa: ... | .geometry import SunZenithCorrector # noqa: F401
from .spectral import NIREmissivePartFromReflectance # noqa: F401
from .spectral import NIRReflectance # noqa: F401
|
franciscod/python-telegram-bot | telegram/inlinequeryresultcachedvideo.py | Python | gpl-2.0 | 2,181 | 0.001376 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2016
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module | contains the classes that represent Telegram
InlineQueryResultCachedVideo"""
from telegram import InlineQueryResult, InlineKeyboardMarkup, InputMessageContent
class InlineQueryResultCachedVideo(InlineQueryResult):
def __init__(self,
id,
video_file_id,
title,
... |
eikiu/tdf-actividades | _admin-scripts/tdf_gcal.py | Python | cc0-1.0 | 28,476 | 0.034032 | #!/usr/bin/python3
'''
Calculate posting schedules in social media of events and add them to google calendar
so they can be posted using IFTTT (so dirty!)
'''
# Google Developers Console:
# project name: tdf-eventos-gcalcli
# activate gcal API
# activate OAuth 2.0 API
# instal: pip3 install --upgra... | " #IFTTT uses the primary calendar
POST_FOLDER = '_posts'
# where the posts reside
CITIES = ('rio-grande' | ,'ushuaia','tolhuin')
# we are in a subfolder now, must get the parent folder
ROOT_DIR = os.path.dirname(os.getcwd())
PROCESSED_POSTS_FILE = "processed-posts.txt" #date,city,filename
PROCESSED_POSTS_FILE_LINE = "{ciudad}@{filename}"
# how the places folder is called. rio-grande is called riogrande
PLACES_F... |
srguiwiz/nrvr-commander | src/nrvr/util/ipaddress.py | Python | bsd-2-clause | 7,449 | 0.003088 | #!/usr/bin/python
"""nrvr.util.ipaddress - Utilities regarding IP addresses
Class provided by this module is IPAddress.
Works in Linux and Windows.
Idea and first implementation - Leo Baschy <srguiwiz12 AT nrvr DOT com>
Contributor - Nora Baschy
Public repository - https://github.com/srguiwiz/nrvr-commander
Copy... | octets[index] = octet
return octets
elif isinstance(ipaddress, (int, long)):
octets = []
while ipaddress:
octets.append(ipaddress % 256)
ipaddress /= 256
octets += [0 for i in range(max(4 - len(octets), 0))]
octets.rever... | d
def asTuple(cls, ipaddress):
"""For ipaddress="10.123.45.67" return immutable (10, 123, 45, 67)."""
if isinstance(ipaddress, tuple):
return ipaddress
elif isinstance(ipaddress, list):
return tuple(ipaddress)
else:
return tuple(cls.asList(ipaddres... |
syrusakbary/Flask-SuperAdmin | examples/auth/auth.py | Python | bsd-3-clause | 3,960 | 0.000253 | from flask import Flask, url_for, redirect, render_template, request
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext i | mport superadmin, login, wtf
from flask.ext.superadmin.contrib import sqlamodel
from wtforms.fields import TextField, PasswordField
from wtforms.validators import Required, ValidationError
# Creat | e application
app = Flask(__name__)
# Create dummy secrey key so we can use sessions
app.config['SECRET_KEY'] = '123456790'
# Create in-memory database
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.sqlite'
app.config['SQLALCHEMY_ECHO'] = True
db = SQLAlchemy(app)
# Create user model. For simplicity, it wi... |
GbalsaC/bitnamiP | django-wiki/wiki/plugins/attachments/wiki_plugin.py | Python | agpl-3.0 | 2,509 | 0.008768 | # -*- coding: utf-8 -*-
from django.conf.urls.defaults import patterns, url
from django.utils.translation import ugettext_lazy as _
from wiki.core.plugins import registry
from wiki.core.plugins.base import BasePlugin
from wiki.plugins.attachments import views
from wiki.plugins.attachments import models
from wiki.plugi... | url(r'^$', views.AttachmentView.as_view(), name='attachments_index'),
url(r'^search/$', views.AttachmentSearchView.as_view(), name='attachments_search'),
url(r'^add/(?P<attachment_id>\d+)/$', views.AttachmentAddView.as_view(), name='attachments_add'),
url(r'^replace/(?P<attachment_id>\d+)/$', v... | ry'),
url(r'^download/(?P<attachment_id>\d+)/$', views.AttachmentDownloadView.as_view(), name='attachments_download'),
url(r'^delete/(?P<attachment_id>\d+)/$', views.AttachmentDeleteView.as_view(), name='attachments_delete'),
url(r'^download/(?P<attachment_id>\d+)/revision/(?P<revision_id>\d+)/$... |
pexip/os-python-amqp | t/unit/test_utils.py | Python | lgpl-2.1 | 2,126 | 0 | from __future__ import absolute_import, unicode_literals
from case import Mock, patch
from amqp.five import text_t
from amqp.utils import (NullHandler, bytes_to_str, coro, get_errno, get_logger,
str_to_bytes)
class test_get_errno:
def test_has_attr(self):
exc = KeyError('foo')
... | KeyError(34)
assert not get_errno(exc)
def test_no_args(self):
assert not get_errno(object())
class test_coro:
def test_advances(self):
@coro
def x():
yield 1
yield 2
it = x()
| assert next(it) == 2
class test_str_to_bytes:
def test_from_unicode(self):
assert isinstance(str_to_bytes(u'foo'), bytes)
def test_from_bytes(self):
assert isinstance(str_to_bytes(b'foo'), bytes)
def test_supports_surrogates(self):
bytes_with_surrogates = '\ud83d\ude4f'.... |
JanzTam/zulip | zerver/views/messages.py | Python | apache-2.0 | 36,656 | 0.003492 | from __future__ import absolute_import
from django.conf import settings
from django.core import validators
from django.core.exceptions import ValidationError
from django.db import connection
from django.db.models im | port Q
from zerver.dec | orator import authenticated_api_view, authenticated_json_post_view, \
has_request_variables, REQ, JsonableError, \
to_non_negative_int, to_non_negative_float
from django.utils.html import escape as escape_html
from django.views.decorators.csrf import csrf_exempt
from zerver.lib import bugdown
from zerver.lib.ac... |
Sveder/pyweek24 | gamelib/platforms.py | Python | apache-2.0 | 537 | 0 | import pygame
from pygame.colordict import THECOLORS
import data
class Platform(pygame.sprite.Sprite):
def __init__(self, width, height):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface([width, | height])
self.image.fill(THECOLORS["green"])
self.rect = self.image.get_rect()
class Trampoline(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = data.load_image("trampoline.png")
self. | rect = self.image.get_rect()
|
obimod/taiga-back | taiga/timeline/signals.py | Python | agpl-3.0 | 6,716 | 0.003873 | # Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
# Copyright (C) 2014 David Barragán <bameda@dbarragan.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 F... | ects.get(pk=instance.pk)
if instance.user != prev_instance.user:
created_datetime = timezone.now()
# The new member
_push_to_timelines(instance.project, instance.user, instance, "create", created_datetime)
# If we are updating the old user is r... | prev_instance.user,
prev_instance,
"delete",
created_datetime)
except sender.DoesNotExist:
# This happens with some tests, when a membership is created with a concrete id
... |
sadmansk/servo | python/servo/bootstrap.py | Python | mpl-2.0 | 13,376 | 0.00157 | # 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 __future__ import abs | olute_import, print_function
from distutils | .spawn import find_executable
from distutils.version import LooseVersion
import json
import os
import platform
import shutil
import subprocess
from subprocess import PIPE
import servo.packages as packages
from servo.util import extract, download_file, host_triple
def install_trusty_deps(force):
version = str(sub... |
bufferapp/buffer-django-nonrel | tests/modeltests/validation/tests.py | Python | bsd-3-clause | 5,944 | 0.003197 | from django import forms
from django.test import TestCase
from django.core.exceptions import NON_FIELD_ERRORS
from modeltests.validation import ValidationTestCase
from modeltests.validation.models import Author, Article, ModelToValidate
# Import other tests for this package.
from modeltests.validation.validators impor... | or pub_date wasn't provided and the field is
# blank=True, model-validation should pass.
# Also, Article.clean() should be run, so pub_date will be fil | led after
# validation, so the form should save cleanly even though pub_date is
# not allowed to be null.
data = {
'title': 'The state of model validation',
}
article = Article(author_id=self.author.id)
form = ArticleForm(data, instance=article)
self.a... |
indie-dev/Clarissa | bot.py | Python | apache-2.0 | 2,985 | 0.022446 | import os
import sys as sys
os.system("python bot/bot.py engage")
import bot_response as bot
import bot_learn as learner
def hasUserSwore(message):
if "fuck" in message:
return True
elif "bitch" in message:
return True
elif "Fuck" in message:
re... | mand):
print "Clarissa: "+response
else:
print "I do not understand "+message
def getCommands():
return open("commands.bot", "r").read()
def getResponses():
return open("respo | nses.bot", "r").read()
swearNum = 0
try:
if(sys.argv[1] == "--add-command"):
writeCommand(command=sys.argv[2], response=sys.argv[3])
reload(bot)
elif (sys.argv[1] == "--clear-commands"):
#os.remove("commands.bot")
#os.remove("responses.bot")
... |
cfe-lab/Umberjack | test/simulations/indelible/__init__.py | Python | bsd-2-clause | 20 | 0 | __aut | hor__ = | 'thuy'
|
JoseBlanca/ngs_crumbs | crumbs/seq/sff_extract.py | Python | gpl-3.0 | 7,004 | 0.000571 | # Copyright 2012 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia
# This file is part of ngs_crumbs.
# ngs_crumbs 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, ... | lds all sequences'
for fhand in self.fhands:
self._prepare_nucl_counts(fhand.name)
if not self.min_left_clip:
seqs = SffIterator(fhand, trim=self.trim)
else:
seqs = _min_left_clipped_seqs(fha | nd, self.trim,
self.min_left_clip)
for record in seqs:
self._update_nucl_counts(str(record.seq), fhand.name)
yield record
def _prepare_nucl_counts(self, fpath):
'It prepares the structure to store the nucleotide count... |
CarlGraff/fundraisermemorial | fundraiser_app/urls.py | Python | mit | 663 | 0.006033 | from django.conf.urls import url
from fundraiser_app import views
urlpatterns = [
url(r'^$', views.FMItemListView.as_view(), name='fmitem_list'),
url(r'^about/$', views.About | View.as_view(), name='about'),
url(r'^fmitem/(?P<pk>\d+)$', views.FMItemDetailView.as_view(), name='fmitem_detail'),
url(r'^fmitem/new$', views.FMItemCreateView.as_view(), name='fmitem_new'),
url(r'^fmitem/(?P<pk>\d+)/edit$', views.FMItemUpdateView.as_view(), name='fmitem_edit'),
url(r'^fmitem/(?P<pk>\d... | iew.as_view(), name='fmitem_remove'),
url(r'^fmitem/(?P<pk>\d+)/publish/$', views.fmitem_publish, name='fmitem_publish'),
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.