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 |
|---|---|---|---|---|---|---|---|---|
dawran6/zulip | zerver/views/messages.py | Python | apache-2.0 | 50,733 | 0.003686 | from __future__ import absolute_import
from django.utils.translation import ugettext as _
from django.utils import timezone
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 import Q
from django.... | e(cond))
elif operand == 'mentioned' or operand == 'alerted':
cond = column("flags").op("&")(UserMessage.flags.mentioned.mask) != 0
return query.where(maybe_negate(cond))
raise BadNarrowOperator("unknown 'is' operand " + operand)
_alp | hanum = frozenset(
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
def _pg_re_escape(self, pattern):
# type: (Text) -> Text
"""
Escape user input to place in a regex
Python's re.escape escapes unicode characters in a way which postgres
fails on, u'... |
bsmr-eve/Pyfa | eos/effects/shiphybriddamagebonuscf.py | Python | gpl-3.0 | 319 | 0.00627 | # shipHybridDamageBonusCF
#
# Used by:
# Ship: Raptor
type = "passive"
def handler(fit, ship, context):
fit.modules.filteredItemBoost(lambda mod: mod.item.requiresSkill("Small Hybrid Turret"),
"damageMultiplier", ship.getModifiedItemAttr("shipB | onusCF"), ski | ll="Caldari Frigate")
|
cosven/FeelUOwn | feeluown/gui/tray.py | Python | gpl-3.0 | 7,673 | 0.001442 | import logging
import sys
from PyQt5.QtCore import Qt, QEvent
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QSystemTrayIcon, QAction, QMenu, QApplication
from feeluown.player import State
from feeluown.gui.helpers import elided_text
TOGGLE_APP_TEXT = ('激活主窗口', '隐藏主窗口')
TOGGLE_PLAYER_TEXT = ('播放', '暂停')
... | ed.connect(self.on_player_state_changed)
self._app.playlist.song_changed.connect(self.on_player_song_changed)
self._app.theme_mgr.theme_changed.connect(self.on_theme_changed)
q_app = QApplication.instance()
q_app.applicationStateChanged.connect(self.on_app_state_changed)
self._a... | )
def setup_ui(self):
self._menu.addAction(self._status_action)
self._menu.addAction(self._toggle_player_action)
self._menu.addAction(self._prev_action)
self._menu.addAction(self._next_action)
self._menu.addSeparator()
if self._toggle_app_action is not None:
... |
40423131/2017springcd_hw | w11/w11/add.py | Python | agpl-3.0 | 29 | 0.034483 | def add(a, b):
re | turn a+b | |
jballanc/openmicroscopy | components/tools/OmeroPy/test/gatewaytest/test_get_objects.py | Python | gpl-2.0 | 23,630 | 0.011595 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
gateway tests - Testing the gateway.getObject() and searchObjects() methods
Copyright 2013 Glencoe Software, Inc. All rights reserved.
Use is subject to license terms supplied in LICENSE.txt
pytest fixtures used as defined in conftest.py:
- gatewaywrap... | ypes - check they include ones from above
tags = list( gatewaywrapper.gateway.getObjects("TagAnnotation") )
for t in tags:
assert t.OMERO_T | YPE == tag.OMERO_TYPE
assert tagId |
areeda/gwpy | gwpy/timeseries/io/gwf/lalframe.py | Python | gpl-3.0 | 6,759 | 0 | # -*- coding: utf-8 -*-
# Copyright (C) Duncan Macleod (2014-2020)
#
# This file is part of GWpy.
#
# GWpy 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)... | ument is not supported by lalframe, "
"if you require ADC scaling, please install "
"python-ldas-tools-framecpp",
)
stream = open_data_source(source)
# parse times and restrict to available data
epoch = lal.LIGOTimeGPS(stream.epoch.gpsSeconds,
st... | if end is None:
end = epoch + streamdur
duration = float(end - start)
# read data
out = series_class.DictClass()
for name in channels:
out[name] = series_class.from_lal(
_read_channel(stream, str(name), start=start, duration=duration),
copy=False)
lalfram... |
clinton-hall/nzbToMedia | libs/common/guessit/monkeypatch.py | Python | gpl-3.0 | 729 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Monkeypatch initialisation functions
"""
try:
from collec | tions import OrderedDict
except ImportError: # pragma: no-cover
from ordereddict import OrderedDict # pylint:disable=import-error
from rebulk.match import Match
def monkeypatch_rebulk():
"""Monkeypatch rebulk classes"""
| @property
def match_advanced(self):
"""
Build advanced dict from match
:param self:
:return:
"""
ret = OrderedDict()
ret['value'] = self.value
if self.raw:
ret['raw'] = self.raw
ret['start'] = self.start
ret['end'] = self.... |
synicalsyntax/zulip | zerver/lib/import_realm.py | Python | apache-2.0 | 58,863 | 0.003415 | import datetime
import logging
import os
import shutil
from typing import Any, Dict, Iterable, List, Optional, Tuple
import boto3
import ujson
from bs4 import BeautifulSoup
from django.conf import settings
from django.db import connection
from django.db.models import Max
from django.utils.timezone import now as timezo... | volved | in a huddle from the subscription object
This helps to generate a unique huddle hash from the updated user_profile ids
"""
id_map_to_list['huddle_to_user_list'] = {
value: [] for value in ID_MAP['recipient_to_huddle_map'].values()}
for subscription in data[table]:
if subscription['recip... |
thoraxe/openshift-ansible | roles/lib_openshift/library/oc_project.py | Python | apache-2.0 | 58,493 | 0.001214 | #!/usr/bin/env python
# pylint: disable=missing-docstring
# flake8: noqa: T001
# ___ ___ _ _ ___ ___ _ _____ ___ ___
# / __| __| \| | __| _ \ /_\_ _| __| \
# | (_ | _|| .` | _|| / / _ \| | | _|| |) |
# \___|___|_|\_|___|_|_\/_/_\_\_|_|___|___/_ _____
# | \ / _ \ | \| |/ _ \_ _| | __| \_ ... | s certain pods in this project to run on certain nodes.
required: false
default: None
aliases: []
author:
- "Kenny Woodson <kwoodson@redhat.com>"
extends_documentation_fragment: []
'''
EXAMPLES = '''
- name: create secret
oc_project:
state: present
name: openshift-ops
display_name: operations... | - top=secret
- noncustomer=True
'''
# -*- -*- -*- End included fragment: doc/project -*- -*- -*-
# -*- -*- -*- Begin included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
class YeditException(Exception): # pragma: no cover
''' Exception class for Yedit '''
pass
# pylint: disable=too-... |
torchingloom/edx-platform | lms/djangoapps/courseware/tests/test_lti_integration.py | Python | agpl-3.0 | 4,365 | 0.003207 | """LTI integration tests"""
import oauthlib
from . import BaseTestXmodule
from collections import OrderedDict
import mock
import urllib
class TestLTI(BaseTestXmodule):
"""
Integration test for lti xmodule.
It checks overall code, by assuring that context that goes to template is correct.
As par | t of that, checks oauth signature generation by mocking signing function
of `oauthlib` library.
"""
CATEGORY = "lti"
def setUp(self):
| """
Mock oauth1 signing of requests library for testing.
"""
super(TestLTI, self).setUp()
mocked_nonce = u'135685044251684026041377608307'
mocked_timestamp = u'1234567890'
mocked_signature_after_sign = u'my_signature%3D'
mocked_decoded_signature = u'my_sig... |
mbayon/TFG-MachineLearning | venv/lib/python3.6/site-packages/scipy/special/basic.py | Python | mit | 62,914 | 0.000143 | #
# Author: Travis Oliphant, 2002
#
from __future__ import division, print_function, absolute_import
import operator
import numpy as np
import math
from scipy._lib.six import xrange
from numpy import (pi, asarray, floor, isscalar, iscomplex, real,
imag, sqrt, where, mgrid, sin, place, issubdtype,
... | d Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996, chapter 5.
https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
"""
if not isscalar(nt) or (floor(nt) != nt) or (nt > 1200):
raise ValueError("Number must be integer <= 1... | s Jn(x), Jn'(x), Yn(x), and Yn'(x).
Returns 4 arrays of length `nt`, corresponding to the first `nt` zeros of
Jn(x), Jn'(x), Yn(x), and Yn'(x), respectively.
Parameters
----------
n : int
Order of the Bessel functions
nt : int
Number (<=1200) of zeros to compute
See jn_zer... |
nottorp/cloudvoting | src/python/cloudclient/CCPlugin.py | Python | lgpl-2.1 | 358 | 0.036313 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
from abc import ABCMeta, abstractmethod
from cloudclient import CCResponse
| class CCPlugin(object):
"""@Interface"""
__metaclass__ = ABCMeta
@abstractmethod
def perform(self):
pass
@abstractmethod
def __init__(self):
self._path = None
self._request = None
"""@AttributeType c | loudclient.CCResponse"""
|
alexisbellido/django-vodkamartini-article | vodkamartiniarticle/helper.py | Python | bsd-3-clause | 3,113 | 0.001285 | import re
from django.template.defaultfilters import slugify
from django.conf import settings
def check_internal_spam_words(content):
return any(word.lower() in (content.lower()) for word in settings.SPAM_WORDS)
def get_client_ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
... | queryset.filter(**{slug_field_name: slug}):
slug = original_slug
end = '%s%s' % (slug_separator, next)
if slug_len and len(slug) + len(end) > slug_len:
slug = slug[:slug_len-len(end)]
slug = _slug_strip(slug, slug_separator)
slug = '%s%s' % (slug, end)
... | ug_strip(value, separator='-'):
"""
Cleans up a slug by removing slug separator characters that occur at the
beginning or end of a slug.
If an alternate separator is used, it will also replace any instances of
the default '-' separator with the new separator.
"""
separator = separat... |
eternnoir/PttBroadcaster | PttBroadcaster/IrcBroadcaster.py | Python | gpl-2.0 | 1,307 | 0.00153 | # -*- coding: utf-8 -*-
import IrcBot
from threading import Thread
from time | import sleep
from PyrserPTT import PyserPtt
from . import googl
pttDomain = 'http://www.ptt.cc'
class IrcBroadcaster():
def __init__(self, board, delayTime, channel, nickname, server, port=6667):
self.ircbot = IrcBot.Bot(channel, nickname, server, port)
self.b | oard = board
self.delayTime = delayTime
self.channel = channel
self.pttPyser = PyserPtt.PyserPtt(board, 5)
self.googl = googl.Googl()
def start(self):
self.botTread = Thread(target=self.ircbot.start)
self.botTread.daemon = True
self.botTread.start()
s... |
mganeva/mantid | scripts/SANS/sans/state/state_functions.py | Python | gpl-3.0 | 4,927 | 0.002639 | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source
# & Institut Laue - Langevin
# SPDX - License - Identifier: GPL - 3.0 +
"""Set of general purpose functions which are... | :param variables: A dictionary which contains the variable n | ames and values which are involved in the error.
:return: a formatted validation message string.
"""
message = ""
for key, value in sorted(variables.items()):
message += "{0}: {1}\n".format(key, value)
message += instruction
return {error_message: message}
def set_detector_names(state,... |
ToxicFrog/bup | lib/bup/metadata.py | Python | lgpl-2.1 | 43,696 | 0.002037 | """Metadata read/write support for bup."""
# Copyright (C) 2010 Rob Browning
#
# This code is covered under the terms of the GNU Library General
# Public License as described in the bup LICENSE file.
from __future__ import absolute_import
from copy import deepcopy
from errno import EACCES, EINVAL, ENOTTY, ENOSYS, EOP... | # content-creator
# forks
#
# ntfs
# type - regular dir ...
# times - creation, modification, posix change, access
# hard-link-info
# link-target
# attributes - see attrib
# ACLs
# forks (alternate data streams)
# crtime?
#
# fat
# type - regu | lar dir ...
# perms - rwxrwxrwx (maybe - see wikipedia)
# times - creation, modification, access
# attributes - see attrib
verbose = 0
_have_lchmod = hasattr(os, 'lchmod')
def _clean_up_path_for_archive(p):
# Not the most efficient approach.
result = p
# Take everything after any '/../'.
pos ... |
rburhum/django-user-analytics | user_analytics/migrations/0001_initial.py | Python | bsd-2-clause | 1,229 | 0.00895 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'TrackedUser'
db.create_table('user_analytics_trackeduser', (
('id', self.gf('d... | ('django.db.models.fields.TextField')(null=True, blank=True)),
))
db.send_create_signal('user_analytics', ['TrackedUser'])
def backwards(self, orm):
# Deleting model 'TrackedUser'
db.delete_table('user_analytics_trackeduser')
models = {
'user_analytics.tracke... | .models.fields.AutoField', [], {'primary_key': 'True'}),
'user_agent': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'})
}
}
complete_apps = ['user_analytics']
|
geocryology/GeoCryoLabPy | equipment/Calibration.py | Python | gpl-3.0 | 4,929 | 0.014405 | # Input: - ***_avg csv file outputted by calibration code
# - csv with reference thermometer uncertainty at every temp step
# Output: - results csv file
# - figure with - a plot of fitted curve
# - a plot with residual errors
# - a plot of fitted curv... | n/zeros[i] for n in x]
## Fitting curve
popt, pcov = curve_fit(func, res, ydata, bounds=(0, | [1.0e-1, 1.0e-2, 1.0e-4, 1.0e-5]),
absolute_sigma = True, sigma = table_ru['Uncert'])
## Calculating uncertainties
a, b, c, d = unc.correlated_values(popt, pcov) # Calculates correlated +/- uncertainty of parameters
x = np.array([unc.ufloat(n, 0.15) for n in x])
... |
shearichard/spellsplash | splsplsh_project/spellweb/migrations/0005_auto_20140923_2219.py | Python | gpl-3.0 | 18,373 | 0.000054 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def combine_names(apps, schema_editor):
# We can't import the Word model directly as it may be a newer
# version than this migration expects. We use the historical version.
Word = apps.get_model("spell... | "EW"))
lst_words.append(Word(level=1, word='I', source="EW"))
lst_words.append(Word(level=1, word='it', source="EW"))
lst_words.append(Word(level=1, word='the', s | ource="EW"))
lst_words.append(Word(level=1, word='was', source="EW"))
lst_words.append(Word(level=1, word='and', source="EW"))
lst_words.append(Word(level=1, word='in', source="EW"))
lst_words.append(Word(level=1, word='my', source="EW"))
lst_words.append(Word(level=1, word='to', source="EW"))
l... |
okfn/jsontableschema-bigquery-py | tableschema_bigquery/storage.py | Python | mit | 9,230 | 0.000433 | # -*- coding: utf-8 -*-
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
import io
import six
import time
import unicodecsv
import tableschema
from apiclient.http import MediaIoBaseUpload
from .mapper import Mapper
# ... | ecute()
# Add to descriptors/fallbacks
self.__descriptors[bucket] = descriptor
self.__fallbacks[bucket] = fallbacks
# Remove buckets cache
self.__buckets = None
def delete(self, bucket=None, ignore=False):
"""https://github.com/frictionlessdata/tablesch... | cket is None:
buckets = reversed(self.buckets)
# Iterater over buckets
for bucket in buckets:
# Non-existent bucket
if bucket not in self.buckets:
if not ignore:
message = 'Bucket "%s" doesn\'t exist.' % bucket
... |
chexov/queueit | beanstalkd/queueit/__init__.py | Python | mit | 12,543 | 0.001595 | #!/usr/bin/env python
# encoding: utf-8
import logging
import os
import sys
import time
import beanstalkc
logging.basicConfig(level=logging.DEBUG, format=u'%(asctime)-15s %(name)-12s: %(levelname)-8s %(message)s')
LOG = logging.getLogger('queueit')
LOG.setLevel(logging.DEBUG)
# Loading values from the shell ENV
QHOS... | ing reserved jobs..")
map(lambda j: j.touch(), batch_jobs)
break
# continue
cmd.extend(map(lambda j: j.body, batch_jobs))
LOG.debug(u"Calling command %s...%s" % (u" ".join(cmd)[:30], u" ".join(cmd)[-15:]))
# LOG.debug(u"Calling command %s" % (u" ... | job):
job.bury()
LOG.info(u"Job %s buried" % job.jid)
map(_bury, batch_jobs)
else:
def _put(job):
jid = qconn_out.put(job.body)
print(job.body)
job.delete()
LOG.info(u"New job put in to %s: %... |
blorgon9000/pyopus | pyopus/evaluator/aggregate.py | Python | gpl-3.0 | 38,782 | 0.043964 | """
.. inheritance-diagram:: pyopus.evaluator.aggregate
:parts: 1
**Parformance aggregation module (PyOPUS subsystem name: AG)**
**Normalization** is the process where a performance measure is scaled in such
way that values not satifying the goal result in normalized values smaller than
0. If the perfo... | the whole array
and the return value is a scalar worst corner index.
"""
pass
def report(self, name, nName=12, nGoal=12, nSigGoal=3):
"""
Formats the goal as a string of the form
*name* *normalization_symbol* *goal* where *name*
is the name of the performance measure. The *normali... | idth of performance measure name and
goal formatting. *nSigGoal* is the number of significant digits of the
*goal* in the formatted string.
"""
pass
# Normalization for targets of the form value>goal.
class Nabove(Nbase):
"""
Performance normalization class requiring the performance to to be... |
GoogleCloudPlatform/datacatalog-connectors-rdbms | google-datacatalog-rdbmscsv-connector/system_tests/cleanup_results_test.py | Python | apache-2.0 | 1,359 | 0.000736 | #!/usr/bin/python
#
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | ense 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.
import os
import unitt | est
from google.cloud import datacatalog
datacatalog_client = datacatalog.DataCatalogClient()
class CleanupResultsTest(unittest.TestCase):
def test_entries_should_not_exist_after_cleanup(self):
query = 'system={}'.format(os.environ['RDBSCSV2DC_TYPE'])
scope = datacatalog.SearchCatalogRequest.S... |
infobip/oneapi-python | oneapi/exceptions.py | Python | apache-2.0 | 39 | 0 | class OneA | piError(Exception):
pass
| |
samuelclay/NewsBlur | apps/monitor/views/newsblur_tasks_codes.py | Python | mit | 1,165 | 0.008584 | import datetime
from django.conf import settings
from django.shortcuts import render
from django.views import View
class TasksCodes(View):
def get(self, request):
data = dict((("_%s" % s['_id'], s['feeds']) for s in self.stats))
chart_name = "task_codes"
chart_type = "counter"
form... | monitor/prometheus_data.html', context | , content_type="text/plain")
@property
def stats(self):
stats = settings.MONGOANALYTICSDB.nbanalytics.feed_fetches.aggregate([{
"$match": {
"date": {
"$gt": datetime.datetime.now() - datetime.timedelta(minutes=5),
},
... |
LEDS/millennium-falcon | millenium_falcon_old/gestao/models.py | Python | apache-2.0 | 2,775 | 0.006128 | from __future__ import unicode_literals
from django.db import models
class Parceiro(models.Model):
#Na verdade é o Cliente com nome mais bonito
nome_parceiro = models.CharField(max_length=255)
nome_representante = models.CharField(max_length=255)
telefone = models.CharField(max_length=255)
email = ... | def __str__(self):
return self.nome
class Bolsa(models.Model):
nome_bolsa = models.CharField(max_length=255, blank=True)
fomento = models.ForeignKey("Fomento", on_delete=models.CASCADE)
valor_bolsa = models.IntegerField(default=0)
projeto = models.ForeignKey("Projeto", on_delete=models.CASCAD... | str__(self):
return self.nome_bolsa
class Alocacao_bolsa(models.Model):
bolsa = models.ForeignKey("Bolsa", null=True)
inicio = models.DateField(null=True)
fim = models.DateField(null=True)
pessoa = models.ForeignKey("Pessoa", null=True)
class Pessoa(models.Model):
nome = models.CharField(m... |
ST-Data-Mining/crater | wei/data.py | Python | mit | 2,913 | 0.02712 | #__author__ = 'FuWei'
from __future__ import print_function, division
import sys
import pdb
from os import listdir
from os.path import isfile, join
# from table import *
class o(object):
def __init__(i, **filed):
i.__dict__.update(filed)
return i
class Row(object):
def __init__(i,data):
i.x = data[:-1]
... | = 0:
hea | der = line.split(",")
newheader = header[:]
if "$" not in header[0]:
for item in header[:-1]:
newheader +=["$"+item]
newheader +=["$<"+header[-1]]
else:
train += ",".join(newheader)
tune +=",".join(newheader)
if count %2... |
liweitianux/django_skaschool | django_skaschool/settings_production.py | Python | bsd-2-clause | 7,604 | 0.002893 | """
Django settings for django_skaschool project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR... | pplication/x-dvi', # dvi
'application/x-latex', # latex
'application/x-rar-compressed', # rar
'application/x-tar', # tar
'image/bmp', # bmp
'ima | ge/gif', # gif
'image/jpeg', # jpg
'image/png', # png
'image/tiff', # tif
'text/csv', # csv
'text/plain', # txt
'text/rtf', # rtf
't... |
unhammer/hfst3 | python/test/test_streams_2.py | Python | gpl-3.0 | 615 | 0.004902 | import libhfst
transducers = []
is | tr = libhfst.HfstInputStream()
while not istr.is_eof():
transducers.append(istr.read())
istr.close()
if not len(transducers) == 3:
raise RuntimeError('Wrong number of transducers read.')
i = 0
for re in ['föö:bär','0','0-0']:
if not transducers[i].compare(libhfst.regex(re)):
raise RuntimeError('Tr... | cers are not equivalent.')
i += 1
if len(transducers) > 0:
f = libhfst.hfst_stdout()
i=0
transducers[i].write_att(f)
i += 1
while i < len(transducers):
f.write('--\n')
transducers[i].write_att(f)
i += 1
|
ravello/ansible | v2/ansible/compat/tests/unittest.py | Python | gpl-3.0 | 1,147 | 0 | # (c) 2014, Toshio Kuratomi <tkuratomi@ansible.com>
#
# This file is part of Ansible
#
# Ans | ible 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 later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY W... | ed a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
'''
Compat module for Python2.7's unittest module
'''
import sys
# Python 2.6
if sys.v... |
richbrowne/f5-cccl | f5_cccl/resource/ltm/test/test_pool.py | Python | apache-2.0 | 7,378 | 0.003117 | #!/usr/bin/env python
# Copyright 2017 F5 Networks 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... | me': '172.16.0.101:8080',
'partition': 'Common',
| 'session': 'monitor-enabled',
'priorityGroup': 0,
'connectionLimit': 0,
'description': None}
]
},
'name': u'pool1'
},
{'description': None,
'partition': 'Common',
'loadBalancingMode': 'round-robin',
'monitor': '/Common/http ',
'na... |
chopmann/warehouse | warehouse/migrations/env.py | Python | apache-2.0 | 1,309 | 0.000764 | from alembic import context
from sqlalchemy import create_engine, pool
from warehouse import db
def run_migrations_offline():
"""
Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine ... | :
"""
Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a | connection with the context.
"""
options = context.config.get_section(context.config.config_ini_section)
url = options.pop("url")
engine = create_engine(url, poolclass=pool.NullPool)
connection = engine.connect()
context.configure(connection=connection, target_metadata=db.metadata)
try:
... |
ingadhoc/project | project_ux/models/project_task.py | Python | agpl-3.0 | 2,136 | 0 | ##############################################################################
# For copyright and license notices, see __manifest__.py file in module root
# directory
##############################################################################
from | odoo import models, api, fields
class ProjectTask(models.Model):
_inherit = 'project.task'
template_task = fields.Boolean(
| copy=False,
string="Is task template?",
)
template_task_id = fields.Many2one(
'project.task',
compute="_compute_template_task_id",
domain=[('template_task', '=', True)],
string='Template Task',
copy=False,
readonly=False,
)
def _compute_t... |
agronholm/apscheduler | src/apscheduler/datastores/mongodb.py | Python | mit | 19,667 | 0.002492 | from __future__ import annotations
import operator
from collections import defaultdict
from contextlib import ExitStack
from datetime import datetime, timedelta, timezone
from logging import Logger, getLogger
from typing import Any, Callable, ClassVar, Iterable
from uuid import UUID
import attrs
import pymongo
import... | if self.start_from_scratch:
self._tasks.delete_many({}, session=session)
self._schedules.delete_many({}, session=s | ession)
self._jobs.delete_many({}, session=session)
self._jobs_results.delete_many({}, session=session)
self._schedules.create_index('next_fire_time', session=session)
self._jobs.create_index('task_id', session=session)
self._jobs.... |
bokeh/bokeh | examples/howto/server_embed/django_embed/django_embed/urls.py | Python | bsd-3-clause | 1,707 | 0.001757 | """django_embed URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-... | ase_path = settings.BASE_PATH
bokeh_apps = [
autoload("sea_surface", views.sea_surface_handler),
document("sea_surface_with_template", views.sea_surface_handler_with_template),
document("bokeh_apps/sea_surface", base_path / "bokeh_apps" / "sea_surface.py"),
document("shape_viewer", views.shape_viewer_h... | th = Path(bokeh.__file__).parent.parent / "examples" / "app"
bokeh_apps += directory(apps_path)
urlpatterns += static_extensions()
urlpatterns += staticfiles_urlpatterns()
|
sgillies/rasterio | tests/test_pad.py | Python | bsd-3-clause | 306 | 0.009804 |
import affine
import numpy
import rasterio
def test_pad():
arr = numpy.ones((10, 10))
trans = affine.Affine(1.0, 0.0, 0.0, 0.0, -1.0, 10.0)
arr2, trans2 = rasterio.pad(arr, trans, 2, 'edge')
| assert arr2.shape == (14, 14)
assert trans2.xoff == -2.0
assert tran | s2.yoff == 12.0
|
odie5533/Python-RTSP | rdt.py | Python | gpl-3.0 | 21,513 | 0.003254 | # Copyright (C) 2008 David Bern
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed... | buf[8 + i] ^= RealChallenge.XOR_TABLE[i];
sum = md5( ''.join([ chr(i) for i in buf ]) )
response = sum.hexdigest() + '01d0a8e3'
chksum = list()
for i in range(0, 8):
chk | sum.append(response[i * 4])
chksum = ''.join(chksum)
return (response, chksum)
compute = staticmethod(compute)
AV_WB32 = staticmethod(AV_WB32)
class RDTClient(RTSPClient):
data_received = 0
out_file = None
prev_timestamp = None
prev_stream_num = None
streamids =... |
drxaero/calibre | src/calibre/gui2/store/stores/archive_org_plugin.py | Python | gpl-3.0 | 1,689 | 0.005921 | # -*- coding: utf-8 -*-
from __future__ import (unicode_literals, division, abso | lute_import, print_function)
store_version = 1 # Needed for dynamic plugin loading
__license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
from calibre.gui2.store.basic_config import BasicStoreConfig
from calibre.gui2.store.opensearch_store import OpenS... |
open_search_url = 'http://bookserver.archive.org/catalog/opensearch.xml'
web_url = 'http://www.archive.org/details/texts'
# http://bookserver.archive.org/catalog/
def search(self, query, max_results=10, timeout=60):
for s in OpenSearchOPDSStore.search(self, query, max_results, timeout):
... |
kushalbhola/MyStuff | venv/Lib/site-packages/pip/_vendor/cachecontrol/heuristics.py | Python | apache-2.0 | 4,144 | 0 | import calendar
import time
from email.utils import formatdate, parsedate, parsedate_tz
from datetime import datetime, timedelta
TIME_FMT = "%a, %d %b %Y %H:%M:%S GMT"
def expire_after(delta, date=None):
date = date or datetime.utcnow()
return date + delta
def datetime_to_header(dt):
return formatdat... | return {}
if 'date' not in headers or 'last-modified' not in headers:
return {}
date = calendar.timegm(parsedate_tz(headers['date']))
last_modified = parsedate(headers['last-modified'])
if date is None or last_modified is None:
return {}
n | ow = time.time()
current_age = max(0, now - date)
delta = date - calendar.timegm(last_modified)
freshness_lifetime = max(0, min(delta / 10, 24 * 3600))
if freshness_lifetime <= current_age:
return {}
expires = date + freshness_lifetime
return {'expires': time... |
IamMoondance/Attempts | hw_01_04/convert_tests.py | Python | mit | 672 | 0 | #!/usr/bin/env python3
base = open("test.txt", "r")
tests = base.readlines()
base.close()
is_in = False
is_out = False
test_number = 0
for line in tests:
if line == 'Input:\n':
is_out = False
is_in = True
if test_number > 0:
test_out.close()
| test_in = open("in_"+str(test_number)+'.txt', "w")
elif line = | = 'Output:\n':
is_out = True
is_in = False
test_in.close()
test_out = open("out_"+str(test_number)+'.txt', "w")
test_number += 1
elif is_in:
test_in.write(line)
elif is_out:
test_out.write(line)
exit(test_number - 1)
|
abcsds/tw | tw/common/trans.py | Python | gpl-3.0 | 491 | 0.004073 | # -*- coding: utf-8 -*-
# P | ut the string you want to manually translate in this file, like this:
#
# _('Something that is not translated in offcial Django distro.')
#
# When you run `django-admin.py makemessage -l <language-code>` command, it will create a message file:
#
# locale/<language-code>/LC_MESSAGES/django.po
#
# For more information ab... | angoproject.com/en/dev/topics/i18n/translation/
from django.utils.translation import ugettext_lazy as _
|
FederatedAI/FATE | python/federatedml/evaluation/metrics/regression_metric.py | Python | apache-2.0 | 2,315 | 0.001296 | from scipy.stats import stats
from sklearn.metrics import explained_variance_score
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
from sklearn.metrics import median_absolute_error
from sklearn.metrics import r2_score
import numpy as np
class RMSE(object):
@staticm... | e(object):
@staticmethod
def compute(labels, pred_scores):
return explained_variance_score(labels, pred_scores)
class MedianAbsoluteError(object):
@staticmethod
def compute(labels, pred_scores):
return median_absolute_error(labels, pred_scores)
class IC(object):
"""
Compute... | le and loss
When k = 2, result is genuine AIC;
when k = log(n), results is BIC, also called SBC, SIC, SBIC.
"""
def compute(self, k, n, dfe, loss):
aic_score = k * dfe + 2 * n * loss
return aic_score
class IC_Approx(object):
"""
Compute Information Criterion value with... |
GandaG/fomod-designer | src/ui_templates/window_settings.py | Python | apache-2.0 | 48,001 | 0.002167 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'resources/templates/window_settings.ui'
#
# Created by: PyQt5 UI code generator 5.5.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog... | tWeight(75)
self.label_9.setFont(font)
self.label_9.setObjectName("label_9")
self.verticalLayout_10.addWidget(self.label_9)
self.horizontalLayout_7 | = QtWidgets.QHBoxLayout()
self.horizontalLayout_7.setObjectName("horizontalLayout_7")
self.label_10 = QtWidgets.QLabel(self.tab_5)
self.label_10.setObjectName("label_10")
self.horizontalLayout_7.addWidget(self.label_10)
self.button_colour_required = QtWidgets.QPushButton(self.ta... |
orbingol/NURBS-Python | geomdl/functools_lru_cache.py | Python | mit | 8,538 | 0.002108 | # backports.functools_lru_cache v1.5
# https://github.com/jaraco/backports.functools_lru_cache
# Copyright (c) 2014-2018 Jason R. Coombs
#
# 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 wit... | = kwd_mark
for item in sorted_items:
key += item
if typed:
key += tuple(type(v) for v in args)
if kwds:
key += tuple(type(v) for k, v in sorted_items)
elif len(key) == 1 and type(key[0]) in fasttypes:
return key[0]
return _HashedSeq(key)
def lru_cach... | res are disabled and the cache
can grow without bound.
If *typed* is True, arguments of different types will be cached separately.
For example, f(3.0) and f(3) will be treated as distinct calls with
distinct results.
Arguments to the cached function must be hashable.
View the cache statistics... |
crossroadchurch/paul | openlp/plugins/alerts/lib/alertstab.py | Python | gpl-2.0 | 9,914 | 0.00121 | # -*- coding: utf-8 -*-
# vim: autoindent shiftwidth=4 expandtab textwidth=120 tabstop=4 softtabstop=4
###############################################################################
# OpenLP - Open Source Lyrics Projection #
# ------------------------------------------------------... | 'Font size:'))
self.font_size_spin_box.setSuffix(UiStrings().FontSizePtUnit)
self.timeout_label.setText(translate('AlertsPlugin.AlertsTab', 'Alert timeout:'))
self.timeout_spin_box.setSuffix(UiStrings().Seconds)
self.preview_group_box.setTitle(UiStrings().Preview)
self.font_previ... | ackground_color = color
self.update_display()
def on_font_combo_box_clicked(self):
"""
The Font Combo was changed.
"""
self.update_display()
def on_font_color_changed(self, color):
"""
The Font Color button has clicked.
"""
self.font_colo... |
petrblahos/modellerkit | step07/view03.py | Python | mit | 4,058 | 0 | """
A micro wx App with a list of the things checked on the checklist.
"""
import datetime
import random
import wx
import hotmodel
import production
import hotwidgets
class ProcView(hotwidgets.MVCList):
"""
A specialized version of MVCList that sets columns for the process
op... | self.model.add_listener(self.mapper)
wx.CallAfter(lambda: self.model.set_product("FIRST8", 1))
def on_product(self, model, fqname, event_name, key):
"""
An article or sn change handler.
"""
self.product.SetLabel("%s %s" % (self.model.article, self.model.sn))... | Button "Next" handler: Display the next product.
"""
evt.Skip()
self.model.set_product("AAAQA%s" % random.randint(0, 9), 1)
def on_add_op(self, evt):
"""
Button "add op" handler: Add a random operation to the operation
list.
"""
... |
ericMayer/tekton-master | backend/appengine/routes/paginas/home.py | Python | mit | 527 | 0.001898 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicod | e_literals
from google.appengine.api import users
from gaecookie.decorator import no_csrf
from gaepermission import facade
from gaepermission.decorator import login_not_required
from tekton import router
from config.template_middleware import TemplateResponse
from routes.login import google, facebook
from routes.login.... | onse(op) |
qsnake/gpaw | gpaw/svnversion_io.py | Python | gpl-3.0 | 1,337 | 0.004488 | # Copyright (C) 2003 CAMP
# Please see the accompanying LICENSE file for further information.
from os import path
try:
from subprocess import Popen, PIPE
except ImportError:
from os import popen3
else:
def popen3(cmd):
p = Popen(cmd, shell=True, close_fds=True,
stdin=PIPE, stdout... | itten to '+svnversionfile
# assert svn:ignore property if the installation is under svn control
# because svnversion.py has to be ignored by svn!
cmd = popen3('svn propset svn:ignore svnversion.py '+dir)[1]
output = cmd.read()
cmd.close()
def get_svnversion_from_svn(dir):
# try to get the las | t svn version number from svnversion
cmd = popen3('svnversion -n '+dir)[1] # assert we are in the project dir
output = cmd.read().strip()
cmd.close()
if output.startswith('exported'):
# we build from exported source (e.g. rpmbuild)
output = None
return output
svnversion = get_svnver... |
keras-team/keras | keras/engine/compile_utils.py | Python | apache-2.0 | 26,900 | 0.007695 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | issing_dict_keys(outputs, struct)
# Allow passing one object that applies to all outputs.
if not tf.nest.is_nested(struct) and tf.nest.is_nested(outputs):
struct = tf.nest.map_structure(lambda _: struct, outputs)
return struct
def _maybe_broadcast_to_outputs(self, outputs, objects):
"""Determin... | NOTE: This method should only be called for Metrics / Losses, not for
y_true / sample_weight.
Args:
outputs: Model predictions.
objects: Arbitrary nested structure (e.g. of losses or metrics)
Returns:
Arbitrary nested structure of objects, maybe copied to each output.
Applies a Lo... |
daniel-koehn/Theory-of-seismic-waves-II | 12_1D_SH_Spectral_Elements/lagrange1st.py | Python | gpl-3.0 | 1,327 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
from gll import gll
from lagrange impor | t lagrange
from legendre import legendre
def lagrange1st(N):
"""
| # Calculation of 1st derivatives of Lagrange polynomials
# at GLL collocation points
# out = legendre1st(N)
# out is a matrix with columns -> GLL nodes
# rows -> order
"""
out = np.zeros([N+1, N+1])
[xi, w] = gll(N)
# initialize dij matrix (see Funaro 1993 or... |
gromacs/copernicus | cpc/command/platform.py | Python | gpl-2.0 | 11,772 | 0.0079 | # This file is part of Copernicus
# http://www.copernicus-computing.org/
#
# Copyright (C) 2011, Sander Pronk, Iman Pouya, Erik Lindahl, and others.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as published
# by the Free Soft... | esource values
self.prefResources = dict()
self.runvars = runvars.RunVars()
def addMaxResource(self, rsrc):
"""Add a single max. resource to the platform."""
| self.maxResources[rsrc.name] = rsrc
def getMaxResources(self):
"""Get the list (dict) of max. resources."""
return self.maxResources
def getMaxResource(self, name):
"""Get a specific max. resource value or None."""
if self.maxResources.has_key(name):
return self.max... |
ZMMzhangmingming/liupengyuan.github.io | chapter2/homework/computer/5-10/201611680890-5.10.py | Python | mit | 1,296 | 0.015873 |
# coding: utf-8
# In[ ]:
#练习一:文本加密解密(先看有关ASCII码的相关知识以及码表,查维基百科或百度百科)
#输入:一个txt文件(假设全是字母的英文词,每个单词之间用单个空格隔开,假设单词最长为10个字母)
#加密:得到每个单词的长度 n ,随机生成一个9位的数字,将 n-1 与这个9位的数字连接,形成一个10位的数字,
#作为密匙 key 。依照 key 中各个数字对单词中每一个对应位置的字母进行向后移位(例:如过 key 中某数字为 2 ,
#对应该位置的字母为 a ,加密则应移位成 c ,如果超过 z ,则回到 A 处继续移位),对长度不到10的单词,移位后,
#将移位后的单词利用随机字母... | 原来的文本。
#(提示,利用 ord() 及 chr() 函数, ord(x) 是取得字符 x 的ASCII码, chr(n) 是取得整数n(代表ASCII码)对应的字符。
#例: ord(a) 的值为 97 , chr(97) 的值为 'a' ,因字母 a 的ASCII码值为 97 。)
fh = open(r'd:\temp\words.txt')
tex | t = fh.read()
fh.close()
print(len(text))
print(text)
|
nlgcoin/guldencoin-official | test/lint/lint-format-strings.py | Python | mit | 12,730 | 0.003614 | #!/usr/bin/env python3
#
# Copyright (c) 2018-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Lint format strings: This program checks that the number of arguments passed
# to a variadic format ... | nction_call = "{}(".format(function_name)
assert remaining.startswith(expected_function_call)
parts = [expected_function_call]
remaining = remaining[len(expected_function_call):]
open_parentheses = 1
open_template_arguments = 0
in_string = False
parts.append("")
for i, char in enumerate | (remaining):
parts.append(parts.pop() + char)
if char == "\"":
in_string = not in_string
continue
if in_string:
continue
if char == "(":
open_parentheses += 1
continue
if char == ")":
|
pLeBlanc93/ArcREST | src/arcrest/common/__init__.py | Python | apache-2.0 | 193 | 0.005181 | from __future_ | _ import absolute_import
from . import spatial
from . import general
from . import geometry
from . import filters
from . import servicedef
from . import find
__version__ = "3. | 5.6" |
aio-libs/aioodbc | aioodbc/pool.py | Python | apache-2.0 | 5,833 | 0 | # copied from aiopg
# https://github.com/aio-libs/aiopg/blob/master/aiopg/pool.py
import asyncio
import collections
from .connection import connect
from .utils import _PoolContextManager, _PoolConnectionContextManager
__all__ = ['create_pool', 'Pool']
def create_pool(minsize=10, maxsize=10, echo=False, loop=None,
... | en(self._free)
while n < free:
conn = self._free[-1]
if self._recycle > -1 \
and self._loop.time() - conn.last_usage > self._recycle:
await conn.close()
self._free.pop()
else:
self._free.rotate()
... | conn = await connect(echo=self._echo, loop=self._loop,
**self._conn_kwargs)
# raise exception if pool is closing
self._free.append(conn)
self._cond.notify()
finally:
self._acquiring -= 1
... |
luogangyi/bcec-nova | nova/tests/objects/test_instance.py | Python | apache-2.0 | 50,449 | 0.000079 | # Copyright 2013 IBM Corp.
#
# 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 agree... | expected = {'nova_object.name': 'Instance',
'nova_object.namespace': 'nova',
'nova_object.version': '1.13',
'nova_object.data':
{'uuid': 'fake-uuid',
'access_ip_v4': '1.2.3.4',
| 'access_ip_v6': '::1'},
'nova_object.changes': ['uuid', 'access_ip_v6',
'access_ip_v4']}
self.assertEqual(primitive, expected)
inst2 = instance.Instance.obj_from_primitive(primitive)
self.assertIsInstance(inst2.access_ip_v4, netad... |
knoopr/ShotForTheHeart | ShotForTheHeart/utils.py | Python | gpl-2.0 | 2,874 | 0.038274 | from django.contrib.auth import authenticate, login, get_user_model
from mailin import Mailin
from string import punctuation
def authorize(request):
email = request.POST.get('Email')
password = request.POST.get('Password')
if len(email) < 6 or len(password) < 10:
return {'ERROR' : 'Too short'}
else:
user = a... | rm:
return {'ERROR' : 'The two passwords do not match.'}
elif len(password) < 10:
return {'ERROR' : 'The password is too short.'}
security_combo = [0,0,0]
for c in password:
if c.isupper():
security_combo[0] = 1
elif c.isalpha():
security_combo[1] = 1
elif c.i | sdigit():
security_combo[2] = 1
elif c in punctuation:
security_combo[2] = 1
if 0 in security_combo:
return {'ERROR' : 'Password is not complex enough. Password requires 1 lower, 1 upper and 1 symbol or number.'}
return {'VALID' : 'Good'}
def register(request):
email = request.POST.get('Email')
passw... |
CMPUT404Proj/CMPUT404-project-socialdistribution | social_dist/authors/admin.py | Python | apache-2.0 | 266 | 0.003759 | from django.contrib import admin
from .models import Author, GlobalAuthor, LocalRelation, GlobalRelation
# Register your models here.
admin.site.register(Author)
adm | in.site.register(GlobalAuthor)
admin.site.register(LocalRelat | ion)
admin.site.register(GlobalRelation) |
enthought/etsproxy | enthought/traits/ui/editors/boolean_editor.py | Python | bsd-3-clause | 61 | 0 | # proxy module |
from traitsui.editors.boolean_edit | or import *
|
mikulcak/forsyde_psopc | source_code/system_creation/lib/modify_arbiters.py | Python | bsd-3-clause | 14,408 | 0.024014 | #!/usr/bin/python
##
#
# @file
## This script modifies the VHDL system code generated by SOPC Builder.
# It parses the basic system description to find all slave modules that are connected to more than one master module and
# modifies the SOPC-generated arbitrators to support a TDMA access scheme.
# @copyright BSD N... | else:
pass
return snippet
## This function modifies the global list of slave and master | connections used in the main 'modify' function
# for a given slave, it adds it to the list and adds all masters connected to it
#
# @param slave The slave for which the masters have to be identified
# @param slave_list_element The element of the global slave list representing the slave
# @param input_xml_file The basic... |
youtube/cobalt | cobalt/tools/gyp_to_gn.py | Python | bsd-3-clause | 28,277 | 0.009265 | #!/usr/bin/env python
# Copyright 2014 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.
# Modifications Copyright 2017 The Cobalt Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "Licens... | # os_posix == (not 0) -> False, os_posix != (not 0) -> True
# ditto for os_bsd
new_node = ast.Num(0 if isinstance(compare.ops[0], ast.Eq) else 1)
return ast.copy_location(new_node, compare)
else:
return compare
def visit_BoolOp(self, boolop): # pylint: disable=invalid-name
... | om
the elimination of OS comparisons.
"""
doing_and = isinstance(boolop.op, ast.And)
new_values = map(self.visit, boolop.values)
new_values_filtered = []
for v in new_values:
if isinstance(v, ast.Num):
# "x and False", or "y or True" - short circuit
if (doing_and and v.n =... |
fmaschler/networkit | networkit/profiling/job.py | Python | mit | 485 | 0.049485 | #
# file: multiprocessing.py
# author: Mark Erb
#
class Job:
""" abstract job class """
def __init__(self, type, name):
""" constructor """
self.__name = name
self.__type = type
def getName(self):
""" return the name connected with the job """
return self.__name
def getType(se... | class: overwrite this method") | |
Yelrado/evadoc | languages/id.py | Python | gpl-3.0 | 14,086 | 0.025486 | # coding: utf-8
{
'!langcode!': 'id',
'!langname!': 'Indonesian',
'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN',
'%d days ago': '%d har... | s': 'Layouts',
'License for': 'Lisensi untuk',
'Live Chat': 'Live Chat',
'loading...': 'sedang memuat...',
'Logged in': 'Masuk',
'Logged out': 'Keluar',
'Login': 'Masuk',
'Login to the Administrative Interface': 'Masuk ke antarmuka Administrasi', |
'Logout': 'Keluar',
'Lost Password': 'Lupa Kata Sandi',
'Lost password?': 'Lupa kata sandi?',
'Maintenance': 'Pemeliharaan',
'Manage': 'Mengelola',
'Manage %(action)s': 'Manage %(action)s',
'Manage Access Control': 'Manage Access Control',
'Manage Cache': 'Mengelola Cache',
'Memberships': 'Memberships',
'Menu Model': ... |
stscieisenhamer/glue | glue/viewers/image/qt/slice_widget.py | Python | bsd-3-clause | 5,216 | 0.001917 | from __future__ import absolute_import, division, print_function
import numpy as np
from glue.core.coordinates import Coordinates
from glue.viewers.common.qt.data_slice_widget import SliceWidget
from glue.viewers.image.state import AggregateSlice
from glue.utils.decorators import avoid_circular
__all__ = ['MultiSlic... | backProperty
from glue.core.state_objects import State
app = get_qapp()
class FakeViewerState(State):
x_att = CallbackProperty()
y_att = CallbackProperty()
reference_data = CallbackProperty()
slices = CallbackPrope | rty()
viewer_state = FakeViewerState()
data = Data(x=np.random.random((3, 50, 20, 5, 3)))
viewer_state.reference_data = data
viewer_state.x_att = data.get_pixel_component_id(0)
viewer_state.y_att = data.get_pixel_component_id(3)
viewer_state.slices = [0] * 5
widget = MultiSliceWidgetHelp... |
MnO2/rediscli | release.py | Python | bsd-3-clause | 2,125 | 0.003765 | #!/usr/bin/env python
from __future__ import print_function
import re
import ast
import subprocess
import sys
DEBUG = False
def version(version_file):
_version_re = re.compile(r'__version__\s+=\s+(.*)')
with open(version_file, 'rb') as f:
ver = str(ast.literal_eval(_version_re.search(
f.r... | subprocess.check_output(cmd)
def create_source_tarball():
cmd = ['python', 'setup.py', 'sdist']
print(' '. | join(cmd))
subprocess.check_output(cmd)
def push_to_github():
cmd = ['git', 'push', 'origin', 'master']
print(' '.join(cmd))
subprocess.check_output(cmd)
def push_tags_to_github():
cmd = ['git', 'push', '--tags', 'origin']
print(' '.join(cmd))
subprocess.check_output(cmd)
def checklist(qu... |
Pelagicore/dbus-proxy | component-test/conftest.py | Python | lgpl-2.1 | 5,485 | 0.001459 |
# Copyright (C) 2013-2016 Pelagicore AB <joakim.gross@pelagicore.com>
#
# This library is free software; you can redistribute it and/or
# modi | fy it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
... | eived a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301, USA.
#
# For further information see LICENSE
import pytest
import os
from os import environ
import sys
import tempfile
fro... |
codenote/chromium-test | tools/sharding_supervisor/sharding_supervisor.py | Python | bsd-3-clause | 2,601 | 0.013841 | #!/usr/bin/env python
# Copyright (c) 2012 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.
"""Defer to run_test_cases.py."""
import os
import optparse
import sys
ROOT_DIR = os.path.dirname(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
def pop_known_arguments(args):
"""Extrac | ts known arguments from the args if present."""
rest = []
run_test_cases_extra_args = []
for arg in args:
if arg.startswith(('--gtest_filter=', '--gtest_output=')):
run_test_cases_extra_args.append(arg)
elif arg == '--run-manual':
run_test_cases_extra_args.append(arg)
elif arg == '--gtest_... |
jpaugh/braille-converter | bin/brl.py | Python | mit | 404 | 0.014851 | #!/usr/bin/env python
# start braile-conve | rter
#
# Copyright 2012 Jonathan Paugh
# See COPYING for license details
import os, sys
if __name__ == '__main__ | ':
mypath = os.path.realpath(os.path.dirname(__file__))
impath = os.path.dirname(mypath)
init_file = os.path.join(impath, 'braille', '__init__.py')
if os.path.isfile(init_file):
sys.path.append(impath)
from braille import __main__
|
etkirsch/legends-of-erukar | erukar/system/engine/model/GenerationProfile.py | Python | agpl-3.0 | 586 | 0.010239 | import math, functools, operator
class GenerationProfile():
def __init__(self, **kwargs):
super().__init__()
for kw in kwargs:
setattr(self, kw, kwargs[kw])
def stochasticity_weight(self, profile):
weights = [
getattr(self, parameter).variable_correlation(getatt... | , p | arameter, -math.inf))\
for parameter in profile.__dict__.keys() if hasattr(self, parameter)
]
return sum(weights) / len([getattr(self, parameter).strength for parameter in profile.__dict__.keys() if hasattr(self, parameter)])
|
kbaseapps/NarrativeService | lib/NarrativeService/sharing/sharemanager.py | Python | mit | 2,862 | 0.002446 | import NarrativeService.feeds as feeds
import NarrativeService.util.workspace as ws
from baseclient import ServerError
# from storage.mongo import (
# save_share_request,
# find_existing_share_request
# )
SERVICE_TOKEN_KEY = "service-token"
WS_TOKEN_KEY = "ws-admin-token"
class ShareRequester(object):
def... | raise ValueError('Missing required parameter "{}"'.format(r))
level = params["share_level"]
if level not in ["a", "w", "r"]:
raise ValueError("Invalid share level: {}. Should be one of a, n, | r.".format(level))
|
hubward/ansible-softlayer | softlayer_vs_ip.py | Python | apache-2.0 | 1,999 | 0.010505 | #!/usr/bin/python
# -*- coding: utf-8 -*-
DOCUMENTATION = '''
---
module: softlayer_vs_ip
short_description: Retrieves instance ip addresses from Softlayer
description:
- Retrieves instance ip addresses of all adapters from Softlayer
- the result is stored in the "result" dict entry of he registered variable
... | d: true
author: scoss
notes:
- Instead of supplying api_key and username, .softlayer or env variables
'''
from ansible.module_utils.basic import *
import SoftLayer
import sys
import logging
import time
from softlayer_vs_basic import *
class IpAddressReader(SoftlayerVirtualServerBasic):
def __init__(self, sl_... | lServerBasic.__init__(self, sl_client, instance_config)
def read_ip_address(self):
sl_instance = self.sl_virtual_guest.getObject(id=self.get_vs_id(True), mask='primaryBackendIpAddress, primaryIpAddress')
return sl_instance
def main():
module_helper = AnsibleModule(
argument_spec ... |
daTokenizer/quickstorm | storm/virtualenvs/src/bolts/actor.py | Python | apache-2.0 | 1,036 | 0.025097 | # [\0] #
# #
# This code is confidential and proprietary, All rights reserved. #
# #
# Tamar Labs 2015. #
# #
# @author: Adam Lev-Libfeld (adam@tamarlabs.... | ctorBolt(Bolt):
def initialize(self, storm_conf, context):
self.actor = Actor()
def process(self, tup):
try:
if (tup.stream == "assignment"):
self.actor.perform(*tup.values)
else:
self.logger.log("ERROR: got bad tuple")
except:
import sys, traceback
msg = "Unex... | or:%s" % (action_num, "\n".join(traceback.format_exception(*sys.exc_info())))
self.logger.error(msg)
|
PetePriority/home-assistant | setup.py | Python | apache-2.0 | 2,240 | 0 | #!/usr/bin/env python3
"""Home Assistant setup script."""
from datetime import datetime as dt
from setuptools import setup, find_packages
import | homeassistant.const as hass_const
PROJECT_NAME = ' | Home Assistant'
PROJECT_PACKAGE_NAME = 'homeassistant'
PROJECT_LICENSE = 'Apache License 2.0'
PROJECT_AUTHOR = 'The Home Assistant Authors'
PROJECT_COPYRIGHT = ' 2013-{}, {}'.format(dt.now().year, PROJECT_AUTHOR)
PROJECT_URL = 'https://home-assistant.io/'
PROJECT_EMAIL = 'hello@home-assistant.io'
PROJECT_GITHUB_USERNA... |
acuriel/Nixtla | nixtla/segmentation/handspeed_based/implementation.py | Python | gpl-2.0 | 3,204 | 0.006242 | # -*- coding: utf-8 -*-
'''
Created on Nov 14, 2014
Implementation of a hand speed-based segmentation module
@author: Arturo Curiel
'''
import zope.interface as zi
try:
import magic
except:
import nixtla.core.tools.magic_win as magic
from nixtla.core.base_module import BaseModule
from nixtla.segmentation.i... | row)
if results:
for result in results:
self.send_to_channels((signer_id,
{articulator:result}
))
return True
def check_input_compliance(self, input_data)... | t len(input_data) == 2
assert "str" in str(type(input_data[0]))
# Check that we are passing speeds, the only
# measure truly needed to calculate segments
for articulator in self.articulators:
assert not input_data[1][articulator+'_v'].empty |
sagarjauhari/time_lapse_pics | Timelapse.py | Python | mit | 2,372 | 0.027825 | # -*- coding: utf-8 -*-
"""
Created on Sun Dec 29 16:34:30 2013
@author: sagar
"""
import cv2
import numpy as np
import itertools
import sys
from os.path import join
MIN_MATCH_COUNT = 10
class TimeLapse:
def find_keypoints(self, img1, img2):
sift = cv2.SIFT()
# find the keypoints and des... |
flann = cv2.FlannBasedMatcher(index_params, search_params)
matches = flann.knnMatch(des1,des2,k=2)
# store all the good matches as per Lowe's ratio test.
good = []
for m,n in matches:
if m.distance < 0.7*n.distance:
| good.append(m)
return kp1, kp2, good
def homography(self, img1, img2):
kp1, kp2, good = self.find_keypoints(img1, img2)
if len(good)>MIN_MATCH_COUNT:
src_pts = np.float32([ kp1[m.queryIdx].pt for m in good ]).reshape(-1,1,2)
dst_pts = np.float32([ kp2[m.trainIdx]... |
flypenguin/docker-loadummy | gray_conversion.py | Python | mit | 4,637 | 0.000216 | #!/usr/bin/env python3
html_colors = {
"aliceblue": "f0f8ff",
"antiquewhite": "faebd7",
"aqua": "00ffff",
"aquamarine": "7fffd4",
"azure": "f0ffff",
"beige": "f5f5dc",
"bisque": "ffe4c4",
"black": "000000",
"blanchedalmond": "ffebcd",
"blue": "0000ff",
"blueviolet": "8a2be2"... | 55.0 * 0.7152
+ int(hex_str[4:], 16) / 255.0 * 0.0722
)
if gray_value <= 0.0031308:
gray_value *= 12.92
else:
gray_value = 1.055 * gray_value ** (1 / 2.4) - 0.055
return gray_value
if __name__ == "__main__":
import os
color_hex_str = get_html_color(os.environ.get("COL... | e")) or "ffffff"
print("Using hex value: ", color_hex_str)
gray_value = get_gray_value(color_hex_str)
print("Grayscale value: ", gray_value)
|
aoqfonseca/twitter_watcher | twitter_watcher/observers.py | Python | mit | 1,472 | 0 | # -*- coding: utf-8 -*-
import logging
from twitter_watcher.actions import Callback
log = logging.getLogger(__name__)
class ObserverTwitter(Callback):
def __init__(self, **kwargs):
self.url = kwargs['url_callback']
self.usernames = kwargs['usernames']
self.hashtags = kwargs['hashtags']... | ags = self.tweet.get('entities').get('hashtags')
hashtags = [item['text'] for item in hashtags]
intersection = [item for item in hashtags if item in self.hashtags]
if not in | tersection and self.hashtags:
return False
return True
def validate(self):
if not isinstance(self.usernames, list):
raise ValueError("usernames should be a list")
if not isinstance(self.hashtags, list):
raise ValueError("hashtags should be a list")
... |
42cs/book | modules/luther/sphinx/codelens/visualizer.py | Python | mit | 6,598 | 0.006669 | # Copyright (C) 2011 Bradley N. Miller
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distribute... | self.JS_VARVAL = ""
def raw_dict(input_code, output_trace):
ret = dict(code=input_code, trace=output_trace)
return ret
def js_var_finalizer(input_code, output_trace):
| global JS_VARNAME
ret = dict(code=input_code, trace=output_trace)
json_output = json.dumps(ret, indent=None)
return "var %s = %s;" % (self.JS_VARNAME, json_output)
self.options['divid'] = self.arguments[0]
if self.content:
source = "\n".join(self.conte... |
leeseuljeong/leeseulstack_neutron | neutron/db/securitygroups_rpc_base.py | Python | apache-2.0 | 20,934 | 0.000191 | # Copyright 2012, Nachi Ueno, NTT MCL, 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
#
# Unles... |
sg_info = {'devices': ports,
'security_groups': {},
'sg_ | member_ips': {}}
rules_in_db = self._select_rules_for_ports(context, ports)
remote_security_group_info = {}
for (port_id, rule_in_db) in rules_in_db:
remote_gid = rule_in_db.get('remote_group_id')
security_group_id = rule_in_db.get('security_group_id')
etherty... |
dcadams/xblock-sdk | hello_world/hello_world/hello_world.py | Python | agpl-3.0 | 3,022 | 0.003309 | """TO-DO: Write a description of what this XBlock is."""
import pkg_resources
from django.templatetags.static import static
from xblock.core import XBlock
from xblock.fields import Scope, Integer
from xblock.fragment import Fragment
class HelloWorldXBlock(XBlock):
"""
TO-DO: document what your XBlock does.... |
studentIdList = []
studentIdCount = []
def resource_string(self, path):
"""Handy helper for getting resources from our kit."""
data = pkg_resources.resource_string(__name__, path)
| return data.decode("utf8")
# TO-DO: change this view to display your data your own way.
def student_view(self, context=None):
"""
The primary view of the HelloWorldXBlock, shown to students
when viewing courses.
"""
html = self.resource_string("static/html/hello_world.ht... |
project-capo/amber-python-drivers | setup.py | Python | mit | 2,925 | 0.001026 | # coding=utf-8
# !/usr/bin/env python
import sys
try:
from setuptools import setup
except ImportError:
sys.stderr.write('using distutils\n')
from distutils.core import setup
with open('requirements.txt') as f:
required = f.read().splitlines()
required = [ req.split('#egg=')[1] if '#' in req else r... | ersion='1.19',
description='Amber drivers in python',
author=u'Paweł Suder',
author_email='pawel@suder.info',
url='http://project-capo.github.io/',
download_url='http://github.com/project-capo/amber-python-drivers/',
keywords=[
'amber',
'dummy',
'hokuyo',
'drive | to point',
'drive support',
'roboclaw',
'panda'
],
classifiers=[
'Programming Language :: Python',
'Development Status :: 4 - Beta',
'Environment :: Other Environment',
'Intended Audience :: Developers',
'License :: Other/Proprietary License',
... |
wxgeo/geophar | wxgeometrie/sympy/printing/pretty/__init__.py | Python | gpl-2.0 | 222 | 0.004505 | """ASCII-ART 2D pr | etty-printer"""
from .pretty import (pretty, pretty_print, pprint, pprint_use_unicode,
pprint_try_use_unicode, pager_print)
# if unicode output is avai | lable -- let's use it
pprint_try_use_unicode()
|
Morgan-Stanley/treadmill | lib/python/treadmill/bootstrap/install.py | Python | apache-2.0 | 13,260 | 0 | """Treadmill bootstrap module.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import io
import errno
import json
import logging
import os
import sys
import subprocess
import tempfile
import pkg_resources
if os.n... | % os.path.join(dst_control_dir, ''))
if pkg_resources.resource_isdir(package_name, src_control_dir):
_install(package, src_control_dir, dst_dir, params,
prefix_len=prefix_len, rec=rec)
elif pkg_resources.resource_exists(package_name, src_control_dir_file):
_LOGGER.info('Expan... | rces.resource_string(
package_name,
src_control_dir_file
)
if svscan_conf_file:
svscan_conf = yaml.load(svscan_conf_file.decode('utf8'))
else:
svscan_conf = {}
scan_dir = supervisor.create_scan_dir(
dst_path,
svsca... |
OCA/stock-logistics-warehouse | stock_vertical_lift/wizards/vertical_lift_shuttle_manual_barcode.py | Python | agpl-3.0 | 671 | 0 | # Copyright 2019 Campt | ocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class VerticalLiftShuttleManualBarcode(models.TransientModel):
_name = "vertical.lift.shuttle.manual.barcode"
_description = "Action to input a barcode"
barcode = fields.Char(s | tring="Barcode")
def button_save(self):
active_id = self.env.context.get("active_id")
model = self.env.context.get("active_model")
assert model
record = self.env[model].browse(active_id).exists()
if not record:
return
if self.barcode:
record.o... |
reviewboard/reviewboard | reviewboard/diffviewer/evolutions/diffcommit_relations.py | Python | mit | 485 | 0 | from djan | go_evolution.mutations import AddField
from django.db import models
from djblets.db.fields import RelationCounterField
MUTATIONS = [
AddField('DiffSet', 'commit_count', RelationCounterField, null=True),
AddField('DiffSet', 'file_count', RelationCounterField, null=True),
AddField('DiffCommit', 'file_count'... | |
Jycraft/jycraft-server-plugin | python/spigot/mcapi.py | Python | bsd-3-clause | 7,416 | 0.004989 | print('Importing command definitions...')
from jycraft.plugin.interpreter import PyContext
from org.bukkit import Bukkit
from org.bukkit import Location
from org.bukkit import Material
from org.bukkit import Effect
from org.bukkit.command import Command
from org.bukkit.event import Listener, EventPriority
from rando... | OCK = BlockType.GoldBlock
# IRON_BLOCK = BlockType.IronBlock
# STONE_SLAB_DOUBLE = BlockType.DoubleStoneSlab
# STONE_SLAB = BlockType.StoneSlab
# BRICK_BLOCK = BlockType.BrickBlock
# TNT = BlockType. | TNT
# BOOKSHELF = BlockType.Bookshelf
# MOSS_STONE = BlockType.MossyCobble
# OBSIDIAN = BlockType.Obsidian
# TORCH = BlockType.Torch
# FIRE = BlockType.FireBlock
# STAIRS_WOOD = BlockType.OakStairs
# CHEST = BlockType.Chest
# DIAMOND_ORE ... |
lmazuel/azure-sdk-for-python | azure-mgmt-datalake-store/azure/mgmt/datalake/store/models/data_lake_store_account_management_client_enums.py | Python | mit | 2,046 | 0 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | b = "Commitment_500TB"
commitment_1_pb = "Commitment_1PB"
commitment_5_pb = "Commitment_5PB"
class DataLakeStoreAccountStatu | s(Enum):
failed = "Failed"
creating = "Creating"
running = "Running"
succeeded = "Succeeded"
patching = "Patching"
suspending = "Suspending"
resuming = "Resuming"
deleting = "Deleting"
deleted = "Deleted"
undeleting = "Undeleting"
canceled = "Canceled"
class DataLakeStoreA... |
joerabelo/geraldo | geraldo/graphics.py | Python | lgpl-3.0 | 3,556 | 0.003937 | from reportlab.lib.colors import black
from reportlab.lib.units import cm
from base import BAND_WIDTH, BAND_HEIGHT, Elemen | t
class Graphic(Element):
"""Base graphic class"""
visible = True
stroke = True
stroke_color = black
stroke_width = 1
fill = False
fill_color = black
def __init__( | self, **kwargs):
for k,v in kwargs.items():
setattr(self, k, v)
def set_rect(self, **kwargs):
"""This method will adapt the graphic element in a rect."""
self.left = kwargs.get('left', self.left)
self.top = kwargs.get('top', self.top)
if 'width' in kwargs:
... |
ariddell/pystan | pystan/tests/test_pickle.py | Python | gpl-3.0 | 4,607 | 0.000868 | import io
import os
import pickle
import sys
import tempfile
import unittest
import numpy as np
import pystan
from pystan.tests.helper import get_model
from pystan.experimental import unpickle_fit
class TestPickle(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.pickle_file = os.path.join(te... | rue((fit_from_pickle.extract()['y'] == y).all())
def test_pickle_model_and_reload(self):
pickle_file = self.pickle_file
pickle_file2 = os.path.join(tempfile.mkdtemp(), 'stanmodel.pkl')
model_code = self.model_code
model = pystan.StanModel(model_code=model_code, model_name="normal1")... | pickle.dump(model, f)
del model
with open(pickle_file, 'rb') as f:
model_from_pickle = pickle.load(f)
self.assertIsNotNone(model_from_pickle.sampling(iter=100).extract())
with open(pickle_file2, 'rb') as f:
model_from_pickle = pickle.load(f)
self.assertI... |
mthornhill/dj-stripe | djstripe/utils.py | Python | bsd-3-clause | 2,190 | 0.003196 | # -*- coding: utf-8 -*-
import warnings
from django.core.exceptions import ImproperlyConfigured
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AnonymousUser
from .models import Customer
ANONYMOUS_USER_ERROR_MSG = (
"The subscription_payment_required decorator requires the ... | read the warning at"
"http://dj-stripe.readthedocs.org/en/latest/usage.html#ongoing-subscriptions"
)
def user_has_active_subscription(user):
warnings.warn("Deprecated - Use ``subscriber_has_active_subscription`` instead. This method will be removed in dj-stripe 1.0.", DeprecationWarning)
return subscribe... | ck if a subscriber has an active subscription.
Throws improperlyConfigured if the subscriber is an instance of AUTH_USER_MODEL
and get_user_model().is_anonymous == True.
Activate subscription rules (or):
* customer has active subscription
If the subscriber is an instance of AUTH_USER_MODEL, ac... |
ridfrustum/django-assets | django_assets/pytest_plugin.py | Python | bsd-2-clause | 210 | 0.009524 | import pytest
import django_assets.env
@pytest.fixture(autouse=True)
def set_django_assets_env():
print("Set django assets environment")
django_ | assets.env.get_env() # ini | tialise django-assets settings
|
sdpython/pymyinstall | _unittests/ut_win_installer/test_batch.py | Python | mit | 881 | 0.001135 | """
@brief test log(time=3s)
"""
import os
import unittest
from pyquickhelper.loghelper import fLOG
from pyquickhelper.pycode import get_temp_folder
from pymyinstall.packaged | import small_set
from pymyinstall | .win_installer.win_batch import create_win_batches
class TestBatch(unittest.TestCase):
def test_batch(self):
fLOG(
__file__,
self._testMethodName,
OutputPrint=__name__ == "__main__")
temp = get_temp_folder(__file__, "temp_batch")
list_modules = small_s... |
adustm/mbed | tools/export/gnuarmeclipse/__init__.py | Python | apache-2.0 | 40,515 | 0.000617 | """
mbed SDK
Copyright (c) 2011-2017 ARM Limited
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 wr... | olders: {0}'.format(len(self.include_path))
self.as_defines = self.toolchain.get_symbols(True)
self.c_defines = self.toolchain.get_symbols()
self.cpp_defines = self.c_defines
print 'Symbols: {0}'.format(len(self.c_defines))
self.ld_script = self.filter_dot(
self.res... | cript)
self.options = {}
for id in profile_ids:
# There are 4 categories of options, a category common too
# all tools and a specific category for each of the tools.
opts = {}
opts['common'] = {}
opts['as'] = {}
opts['c'] = {}
... |
khosrow/metpx | sundew/lib/SenderFTP.py | Python | gpl-2.0 | 25,874 | 0.027016 | """
MetPX Copyright (C) 2004-2006 Environment Canada
MetPX comes with ABSOLUTELY NO WARRANTY; For details type see the file
named COPYING in the root of the source directory tree.
"""
"""
#############################################################################################
# Name: SenderFTP.py
#
# Authors: Pe... | lkw = len(kw)
if keywd[:lkw] == kw : return v + keywd[lkw:]
return defval
def dirMkdir(self,destDir) :
"""
MG 20080625
Now throw exception while creating directory
this fix a bug that when the directory was not
created the | file could be written in the parent dir.
"""
self.chdir(self.originalDir)
try :
self.chdir(destDir)
except:
DD = destDir.split("/")
if destDir[0:1] == "/" : DD[0] = "/" + DD[0]
for d in DD :
try ... |
algorhythms/HackerRankAlgorithms | Two arrays.py | Python | apache-2.0 | 1,587 | 0.003151 | """
ou are given two integer arrays, A and B, each containing N integers. The size of the array is less than or equal to
1000. You are free to permute the order of the elements in the arrays.
Now here's the real question: Is there an permutation A', B' possible of A and B, such that, A'i+B'i >= K for all i,
where A'i ... | annot detect list()
for i in xrange(N):
if not A[i] + B[i] >= K:
return "NO"
return "YES"
if __name__ = | = "__main__":
import sys
f = open("1.in", "r")
# f = sys.stdin
testcases = int(f.readline().strip())
for t in xrange(testcases):
# construct cipher
N, K = map(int, f.readline().strip().split(" "))
A = map(int, f.readline().strip().split(' '))
B = map(int, f.readline... |
mnannt/mnist_experiments | mnist_evaluate.py | Python | mit | 402 | 0 | from __future__ import print_function |
from mnist import evaluate
import sys
model = evaluate.init()
prediction1, confidence1 = evaluate.from_local_image(sys.argv[1], model)
print("prediction: {}; confidence | : {:.2f}".format(prediction1, confidence1))
prediction2, confidence2 = evaluate.from_local_image(sys.argv[1], model)
print("prediction: {}; confidence: {:.2f}".format(prediction2, confidence2))
|
kawamon/hue | desktop/core/ext-py/pytest-4.6.11/src/_pytest/recwarn.py | Python | apache-2.0 | 9,347 | 0.001391 | # -*- coding: utf-8 -*-
""" recording warnings during test function execution. """
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import inspect
import re
import sys
import warnings
import six
import _pytest._code
from _pytest.deprecated import PYTEST_WAR... | """Clear the list of recorded warnings."""
self._list[:] = []
def __enter__(self):
if self._entered:
__tracebackhide__ = True
raise RuntimeError("Cannot enter %r twice" % self)
self._list = super(WarningsRecorder, self).__enter__()
warnings.simplefilter("alw... | an be re-warned. python2 has no
# concept of this so we must reset the warnings registry manually.
# trivial patching of `warnings.warn` seems to be enough somehow?
if six.PY2:
def warn(message, category=None, stacklevel=1):
# duplicate the stdlib logic due to
... |
xutian/avocado-vt | virttest/env_process.py | Python | gpl-2.0 | 84,275 | 0.000664 | from __future__ import division
import os
import time
import re
import logging
import glob
import threading
import shutil
import sys
import copy
import multiprocessing
try:
from urllib.request import ProxyHandler, build_opener, install_opener
except ImportError:
from urllib2 import ProxyHandler, build_opener, i... | .QemuImg(params, base_dir, image_name)
logging.info("Create image on %s." % image.storage_type)
image.create(params)
def preprocess_vm(test, params, env, name):
"""
Preprocess a single VM object according to the instructions in params.
Start the VM if requested and get a screendump.
:... | environment (a dict-like object).
:param name: The name of the VM object.
"""
vm = env.get_vm(name)
vm_type = params.get('vm_type')
connect_uri = params.get('connect_uri')
target = params.get('target')
create_vm = False
if not vm or not isinstance(vm, virt_vm.BaseVM.lookup_vm_class(vm_... |
ProjectFacet/facet | project/project/settings/development.py | Python | mit | 2,242 | 0.000892 | """Development settings for facet project."""
from django.conf import settings
from django.test.runner import DiscoverRunner
from django.core.mail.utils import DNS_NAME
from .base import *
##############################################################################
# Core Django stuff
SECRET_KEY = "abc... | il, so just print to the console
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
# Fix for broken DNS at some wifi hot-spots
DNS_NAME._fqdn = "localhost"
######################################
# Caching --- don't actual cache
CACHES = {
'default': {
'BACKEND': 'django.core.c... | programmers get lonely.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
},
},
'loggers': {
'': {
'handlers': ['console'],
... |
gavinballard/shopify_python_api | shopify/resources/blog.py | Python | mit | 220 | 0 | from ..base import ShopifyResource
from shopify import mixins
import shopify
class | Blog(ShopifyResource, mixins.Metafields, mixins.Events):
def articles(self):
return shopify.Article.find(blog_id=s | elf.id)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.