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 |
|---|---|---|---|---|---|---|---|---|
Jarob22/selenium | py/selenium/webdriver/__init__.py | Python | apache-2.0 | 1,735 | 0 | # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | less required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from... | x # noqa
from .firefox.firefox_profile import FirefoxProfile # noqa
from .chrome.webdriver import WebDriver as Chrome # noqa
from .chrome.options import Options as ChromeOptions # noqa
from .ie.webdriver import WebDriver as Ie # noqa
from .edge.webdriver import WebDriver as Edge # noqa
from .opera.webdriver impor... |
EventGhost/EventGhost | eg/Classes/AddActionGroupDialog.py | Python | gpl-2.0 | 1,500 | 0.000667 | # -*- coding: utf-8 -*-
#
# This file is part of EventGhost.
# Copyright © 2005-2020 EventGhost Project <http://www.eventghost.net/>
#
# EventGhost 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 versio... | ublic License for
# more details.
#
# You should have received a copy of the GNU General Public License along
# with EventGhost. If not, see <http://www.gnu.org/licenses/>.
# Local imports
import eg
class Text(eg.TranslatableStrings):
caption = "Add Actions?"
message = (
"EventGhost can add a folder w... | "
"configuration tree. If you want to do so, select the location where "
"it should be added and press OK.\n\n"
"Otherwise press the cancel button."
)
class AddActionGroupDialog(eg.TreeItemBrowseDialog):
def Configure(self, parent=None):
eg.TreeItemBrowseDialog.Configure(
... |
weblabdeusto/weblablib | examples/simple/example.py | Python | agpl-3.0 | 3,126 | 0.006398 | from __future__ import print_function
import time
from flask import Flask, session, url_for
from flask_debugtoolbar import DebugToolbarExtension
from weblablib import WebLab, requires_active, weblab_user, poll
app = Flask(__name__)
# XXX: IMPORTANT SETTINGS TO CHANGE
app.config['SECRET_KEY'] = 'something random' # e... | n one lab in the same redis database
# app.config['WEBLAB_CALLBACK_URL'] = '/lab/public' # If you don't pass it in the creator
# app.config['WEBLAB_TIMEOUT'] = 15 # in seconds, default value
# app.config['WEBLAB_SCHEME'] = 'https'
weblab = Web | Lab(app, callback_url='/lab/public')
toolbar = DebugToolbarExtension(app)
@weblab.initial_url
def initial_url():
"""
This returns the landing URL (e.g., where the user will be forwarded).
"""
return url_for('.lab')
@weblab.on_start
def on_start(client_data, server_data):
"""
In this code, you ... |
samskeller/zeroclickinfo-fathead | lib/fathead/py_pi/parse.py | Python | apache-2.0 | 1,981 | 0.003534 | #!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
import codecs
import json
import re
import urllib
with codecs.open('download/package-jsons', encoding='utf-8') as in_file, \
codecs.open('output.txt', mode='wb', encoding='utf-8') as out_file:
for package_json in in_file:
package_dict = json.loads(p... | ownloads']['last_month'])
for classifier in package_info['classifiers']:
if classifier.startswith('Development Status'):
abstract_lines.append('Development status: %s' % classifier.split(' - ')[-1])
break
ab | stract_lines.append("<pre><code>pip install " + package_info['name'] + "</code></pre>")
official_site = ''
# check for real links. We can get stuff like 'unknown', '404' in here
if package_info['home_page'] and re.search(r'www.', package_info['home_page']):
official_site = '[' + pac... |
espressopp/espressopp | src/analysis/NeighborFluctuation.py | Python | gpl-3.0 | 1,852 | 0.00378 | # Copyright (C) 2012,2013
# Max Planck Institute for Polymer Research
# Copyright (C) 2008,2009,2010,2011
# Max-Planck-Institute for Polymer Research & Fraunhofer SCAI
#
# This file is part of ESPResSo++.
#
# ESPResSo++ is free software: you can redistribute it and/or modify
# it under the terms of the G... | ):
cxxinit(self, analysis_NeighborFluctuation, system, radius)
if pmi.isController :
class NeighborFluctuation(Observable, metaclass=pmi.Proxy):
pmiproxydefs = dict(
cls = 'espressopp.analysis.NeighborFl | uctuationLocal'
)
|
ronaldahmed/robot-navigation | neural-navigation-with-lstm/MARCO/plastk/rand.py | Python | mit | 1,050 | 0.02381 | """
Random numbers for PLASTK.
$Id: rand.py,v 1.4 2005/08/20 16:46:14 jp Exp $
"""
#from RandomArray import *
import sys
def shuffle(L):
"""
Return randomly permuted version of L. (non-destructive)
"""
return [L[i] for i in permutation(len(L))]
def strseed(s):
s1 = s[::2]
s2 = s[1::2]
... | retur | n seq[sample_index(weights)]
def sample_index(weights):
total = sum(weights)
if total == 0:
return randrange(len(weights))
index = random() * total
accum = 0
for i,x in enumerate(weights):
accum += x
if index < accum:
return i
def strhash(s,base=31,mod=214748364... |
devonjones/PSRD-Parser | src/psrd/sql/animal_companions.py | Python | gpl-3.0 | 1,808 | 0.03042 | from psrd.sql.utils import test_args
def create_animal_companion_details_table(curs):
sql = '\n'.join([
"CREATE TABLE animal_companion_details (",
" animal_companion_details_id INTEGER PRIMARY KEY,",
" section_id INTEGER NOT NULL,",
" ac TEXT,",
" attack TEXT,",
" cmd TEXT,",
" ability_scores TEXT... | tack=None,
cmd=None, ability_scores=None, special_abilities= | None,
special_qualities=None, special_attacks=None, size=None, speed=None,
bonus_feat=None, level=None, **kwargs):
values = [section_id, ac, attack, cmd, ability_scores, special_abilities,
special_qualities, special_attacks, size, speed, bonus_feat, level]
test_args(kwargs)
sql = '\n'.join([
"INSERT INTO ani... |
efornal/platy | manage.py | Python | gpl-3.0 | 248 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
| os.environ.setdefault("DJANGO_SETTINGS_MODULE", "platy.settings")
from django.core.management import execute_from_command_line
| execute_from_command_line(sys.argv)
|
alexras/pelican | pelican/generators.py | Python | agpl-3.0 | 31,054 | 0.000773 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
import os
import six
import logging
import shutil
import fnmatch
import calendar
from codecs import open
from collections import defaultdict
from functools import partial
from itertools import chain, groupby
from operator import attrgette... | heme_path,
"themes", "simple", | "templates"))
self.env = Environment(
trim_blocks=True,
lstrip_blocks=True,
loader=ChoiceLoader([
FileSystemLoader(self._templates_path),
simple_loader, # implicit inheritance
PrefixLoader({'!simple': simple_loader}) # explic... |
tectronics/l5rcm | dal/skill.py | Python | gpl-3.0 | 2,619 | 0.008782 | # -*- coding: iso-8859-1 -*-
# Copyright (C) 2011 Daniele Simonetti
#
# 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.
#
... |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Publi | c License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
class MasteryAbility(object):
@staticmethod
def build_from_xml(elem):
f = MasteryAbility()
f.rank = int(elem.attrib['rank'])
f.rule = elem.attrib['rul... |
brotherlogic/gobuildmaster | BuildAndRun.py | Python | apache-2.0 | 1,102 | 0.00363 | macimport os
import subprocess
name = "gobuildmaster"
current_hash = ""
for line in os.popen("md5sum " + name).readlines():
current_hash = line.split(' ')[0]
# Move the old version over
for line in os.popen('cp ' + name + ' old' + name).readlines():
print line.strip()
# Rebuild
for line | in os.popen('go build').readlines():
print line.strip()
size_1 = os.path.getsize('./old' + name)
size_2 = os.path.getsize('./' + name)
lines = os.popen('ps -ef | grep ' + name).readlines()
running = False
for line in lines:
if "./" + name in line:
running = True
new_hash = ""
for line in os.popen("m... |
if size_1 != size_2 or new_hash != current_hash or not running:
if not running:
for line in os.popen('cat out.txt | mail -E -s "Crash Report ' + name + '" [email protected]').readlines():
pass
for line in os.popen('echo "" > out.txt').readlines():
pass
for l... |
popazerty/dvbapp2-gui | lib/python/Screens/Ci.py | Python | gpl-2.0 | 11,228 | 0.036961 | from Screen import Screen
from Components.ActionMap import ActionMap
from Components.ActionMap import NumberActionMap
from Components.Label import Label
from Components.config import config, ConfigSubsection, ConfigSelection, ConfigSubList, getConfigListEntry, KEY_LEFT, KEY_RIGHT, KEY_0, ConfigNothing, ConfigPIN
from ... | = 4
def setCIBitrate(configElement):
if configElement.value == "no":
eDVBCI_UI.getInstance().setClockRate(configElement.slotid, eDVBCI_UI.rateNormal)
else:
eDVBCI_UI.getInstance().setClockRate(configElement.slotid, eDVBCI_UI.rateHigh)
def InitCiConfig():
config.ci = ConfigSubList()
for slot in range(MAX_NUM_C... | , _("Yes"))], default = "auto")
if SystemInfo["CommonInterfaceSupportsHighBitrates"]:
config.ci[slot].canHandleHighBitrates = ConfigSelection(choices = [("no", _("No")), ("yes", _("Yes"))], default = "yes")
config.ci[slot].canHandleHighBitrates.slotid = slot
config.ci[slot].canHandleHighBitrates.addNotifier(... |
normanmaurer/autobahntestsuite-maven-plugin | src/main/resources/twisted/python/runtime.py | Python | apache-2.0 | 4,513 | 0.003988 | # -*- test-case-name: twisted.python.test.test_runtime -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from __future__ import division, absolute_import
import os
import sys
import time
import imp
import warnings
from twisted.python i | mport compat
if compat._PY3:
_threadModule = "_thread"
else:
_threadModule = "thread"
def shortPythonVersion():
"""
Returns the Python version as a dot-separated string.
"""
return "%s.%s.%s" % sys.version_info[:3]
knownPlatforms = {
'nt': 'win32',
'ce': 'win32',
'posix': 'pos... | dules.os': 'java',
}
_timeFunctions = {
#'win32': time.clock,
'win32': time.time,
}
class Platform:
"""
Gives us information about the platform we're running on.
"""
# See http://twistedmatrix.com/trac/ticket/3413
# By oberstet
if os.name == 'java' and hasattr(os, '_name')... |
BioModelTools/TemplateSB | run.py | Python | mit | 543 | 0.003683 | """
Running the template pre-processor standalone.
Input: Templated Antimony model (stdin)
Output: Expanded Antimony model (stdout)
"""
import fileinput
import os
import sys
directory = os.path.dirname(os.path.abspath(__file__))
path = os.path.join(directory, "T | emplateSB")
sys.path.append(path)
from template_processor import TemplateProc | essor
template_stg = ''
for line in fileinput.input():
template_stg += "\n" + line
processor = TemplateProcessor(template_stg)
expanded_stg = processor.do()
sys.stdout.write(expanded_stg)
|
bennahugo/RFIMasker | RFIMasker/version.py | Python | gpl-3.0 | 88 | 0.022727 | # Do not edit this file, pipeli | ne versioning is governed by git tags
__version__="1.0.1 | " |
netleibi/fastchunking | fastchunking/benchmark.py | Python | apache-2.0 | 988 | 0.003036 | import os
import time
import timeit
import fastchunking
if __name__ == '__main__':
print("Benchmarking RabinKarpChunking creation time...")
NUMBER = 10000
total_time = timeit.timeit('fastchunking.RabinKarpCDC(48, 0).create_chunker(128)',
setup='import fastchunking', number=N... | unk size = {chunk_size:5d} bytes): {throughput:7.2f} MiB/s"
t = time.time() - t
print(msg.format(chunk_size=chunk_size, throughput=SIZE / 1024 / 1024 / t if t else float('i | nf')))
|
paurosello/frappe | frappe/tests/test_search.py | Python | mit | 1,419 | 0.026779 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import unittest
import frappe
from frappe.desk.search import search_link
class TestSearch(unittest.TestCase):
def test_search_field_sanitizer(self):
# pass
search_link('Doc... | , searchfield='select * from tabSessions) --')
self.assertRaises(frappe.DataError,
search_link, 'DocType', 'Customer', query=None, filters=None,
page_length=20, searchfield='name or (select * from tabSessions)')
self.assertRaises(frappe.DataError,
search_link, 'DocType', 'Customer', query=None, filters=N... | pe', 'Customer', query=None, filters=None,
page_length=20, searchfield=';')
self.assertRaises(frappe.DataError,
search_link, 'DocType', 'Customer', query=None, filters=None,
page_length=20, searchfield=';')
|
QualiSystems/vCenterShell | package/cloudshell/cp/vcenter/models/DeployFromImageDetails.py | Python | apache-2.0 | 396 | 0.005051 | from cloudshell.cp.vcenter.models.vCenterVMFromImageResourceModel import vCenterVMFromImageResourceModel
class DeployFromImageDetails(object):
def __ini | t__(self, image_params, app_name):
""" |
:type image_params: vCenterVMFromImageResourceModel
:type app_name: str
:return:
"""
self.image_params = image_params
self.app_name = app_name |
qusp/orange3 | Orange/widgets/regression/owknnregression.py | Python | bsd-2-clause | 2,723 | 0.000367 | """
"""
import Orange.data
import Orange.regression.knn as knn
import Orange.classification
from Orange.preprocess.preprocess import Preprocess
from | Orange.widgets import widget, gui
from Orange.widgets.settings import Setting
class OWKNNRegression(widget.OWWidget):
name = "k Nearest Neighbors Regression"
description = "K-nearest neighbours learner/model."
icon = "icons/kNearestNeighbours.svg"
priority = 20
inputs = [("Data", Orange.data.Tab... | lassification.SklModel)]
want_main_area = False
learner_name = Setting("k Nearest Neighbors Regression")
n_neighbors = Setting(5)
metric_index = Setting(0)
def __init__(self, parent=None):
super().__init__(parent)
self.preprocessors = ()
self.data = None
box = gu... |
facebookresearch/ParlAI | parlai/chat_service/core/socket.py | Python | mit | 5,922 | 0.000844 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this so | urce tree.
import errno
import json
import logging
import threading
import time
import websocket
import parlai.chat_service.utils.logging as log_utils
SOCKET_TIMEOUT = 6
# Socket handler
class ChatServiceMessageSocket:
"""
ChatServiceMessageSocket is a wrapper around websocket to forward messages from the
... | """
server_url: url at which the server is to be run
port: port for the socket to operate on
message_callback: function to be called on incoming message objects (format: message_callback(self, data))
"""
self.server_url = server_url
self.port... |
BlackEarth/bxml | bxml/rng.py | Python | mpl-2.0 | 408 | 0.019608 |
from .xml import XML
class RNG(XML):
NS | = {
'a': "http://relaxng.org/ns/compatibility/annotations/1.0",
'epub': "http://www.idpf.org/2007/ops",
'sch': "http://purl.oclc.org/dsdl/schematron",
'html': "http://www.w3.org/1999/xhtml",
'r': "http://relaxng.org/ns/structure/1.0",
'datatypeL | ibrary': "http://www.w3.org/2001/XMLSchema-datatypes"
}
|
oemof/oemof_base | src/oemof/solph/groupings.py | Python | gpl-3.0 | 2,875 | 0 | # -*- coding: utf-8 -*-
"""Groupings needed on an energy system for it to work with solph.
If you want to use solph on an energy system, you need to create it with these
groupings specified like this:
.. code-block: python
from oemof.network import EnergySystem
import solph
energy_system = EnergySy... | ving to do an import at runtime in the
# init method of solph's `EnergySystem`. A better way would be to add a
# method (maybe `constraints`, `constraint_group`, `constraint_type` or
# something like that) to solph's node hierarchy, which gets overridden in
# each s | ubclass to return the appropriate value. Then we can just call the
# method here.
# This even gives other users/us the ability to customize/extend how
# constraints are grouped by overriding the method in future subclasses.
cg = getattr(node, "constraint_group", fallback)
return cg()
standard_flo... |
drayanaindra/shoop | shoop/core/models/product_media.py | Python | agpl-3.0 | 3,018 | 0.002319 | # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2015, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import with_statement
from django.db import models
from dja... | _name="media")
shops = models.ManyToManyField("Shop", related_name="product_media")
kind = EnumIntegerField(
ProductMediaKind, db_index | =True, default=ProductMediaKind.GENERIC_FILE, verbose_name=_('kind')
)
file = FilerFileField(blank=True, null=True, verbose_name=_('file'))
external_url = models.URLField(blank=True, null=True, verbose_name=u'URL')
ordering = models.IntegerField(default=0)
# Status
enabled = models.BooleanField... |
svb2357/projecteuler | 14/answer.py | Python | gpl-2.0 | 492 | 0.012195 | #!/usr/bin/env python2
# Solution to project euler problem 14
def collatzlength(start):
x = start
cnt = 0
while x != 1:
x = nextcollatz(x)
| cnt += 1
return cnt
def nextcollatz(x):
if x % 2 == 0:
return x/2
else:
return 3*x + 1
def solution(n):
mx = (0,0)
for i in xrange(2, n + 1):
ln = collatzlength(i)
if ln > mx[1]:
mx | = (i, ln)
print mx
return mx
solution(1000000)
|
realestate-com-au/bespin | bespin/operations/plan.py | Python | mit | 829 | 0.006031 | from bespin.errors import BadOption, MissingPlan
from in | put_algorithms.spec_base import NotSpecified
class Plan(object):
@classmethod
def find_stacks(kls, configuration, stacks, plan):
if plan in (None, NotSpecified):
raise BadOption("Please specify a plan", available=list(configuration["plans"].keys()))
if plan not in configuration["pl... | ssing = []
for stack in configuration["plans"][plan]:
if stack not in stacks:
missing.append(stack)
if missing:
raise BadOption("Some stacks in the plan don't exist", missing=missing, available=list(stacks.keys()))
for stack in configuration["plans"][pl... |
Phexcom/product-launcher | lwc/settings/base.py | Python | gpl-3.0 | 3,530 | 0.005099 | """
Django settings for lwc project.
Generated by 'django-admin startproject' using Django 1.9.7.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
# Bui... | for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '7fm_f66p8e!p%o=sr%d&cue(%+bh@@j_y6*b3d@t^c5%i8)1)2'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []... | ARER_URL = "http://127.0.0.1:8000/?ref="
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'joins',
]
MIDDLEWARE_CLASSES = [
'djang... |
wodo/WebTool3 | webtool/server/migrations/0025_instruction_special.py | Python | bsd-2-clause | 519 | 0.001927 | # -*- coding: utf-8 | -*-
# Generated by Django 1.11.6 on 2018-12-11 04:11
from __future__ import unicode_literals
from django.db import migrations, mod | els
class Migration(migrations.Migration):
dependencies = [
('server', '0024_auto_20181210_2022'),
]
operations = [
migrations.AddField(
model_name='instruction',
name='special',
field=models.BooleanField(default=False, help_text='Kreative Kursinhalte'... |
thesgc/chembiohub_ws | deployment/settings/default.py | Python | gpl-3.0 | 4,286 | 0.012599 | from .base import *
import os
import pwd
import sys
DEBUG=True
TEMPLATE_DEBUG = DEBUG
def get_username():
return pwd.getpwuid( os.getuid() )[ 0 ]
CONDA_ENV_PATH = os.getenv("CONDA_ENV_PATH")
ENV_NAME = os.path.split(CONDA_ENV_PATH)[1]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.post... | G = {
'version': 1,
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d % | (message)s'
},
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'handlers': {
'console': { #Logging is sent out to standard out
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'simp... |
mrquim/mrquimrepo | script.module.livestreamer/lib/livestreamer/plugins/oldlivestream.py | Python | gpl-2.0 | 697 | 0.002869 | import re
from livestreamer.plugin import Plugin
from livestreamer.stream import HLSStream
PLAYLIST_URL = "http://x{0}x.api.channel.livestream.com/3.0/playlist.m3u8"
_url_re = re.compile("http(s)?://(www\.)?livestream.com/(?P<channel>[^&?/]+)")
class OldLivestream(Plugin):
@classmethod
def can_handle_url(s... | = PLAYLIST_URL.format(channel)
return HLSStream.parse_variant_playlist(self.session, playlist_url, check_stre | ams=True)
__plugin__ = OldLivestream
|
mick001/utility-scripts | print_autocad_drawings.py | Python | gpl-2.0 | 8,162 | 0.010904 | # -*- coding: utf-8 -*-
"""
Created on Sun Sep 3 17:20:04 2017
@author: Michy
@name: AutoCAD drawing printer BOT.
@description:
This program is a BOT that prints to pdf all the .dwg files in a given folder.
Given a folder (data_wd) the program will try to print every .dwg file in that
folder.
... | It gathers all the .dwg files in the given directory.
2) For each file, it opens the file with the default program (which,
is assumed to be AutoCAD) then CTRL + P is pressed to open the print menu.
Then, the k | eys "m" and "i" are pressed in sequence, since this is enough
to select the PDF printer in my case. Then "Enter" is pressed, the name
of the output pdf file is entered, "enter" is pressed again, and then finally
the drawing is closed using "CTRL + F4".
Please make sure that this pro... |
Hawk94/dust | backend/users/test/test_views.py | Python | mit | 1,735 | 0.000576 | from django.urls import reverse
from django.forms.models import model_to_dict
from django.contrib.auth.hashers import check_password
from nose.tools import ok_, eq_
from rest_framework.test import APITestCase
from faker import Faker
from ..models import U | ser
from .factories import UserFactory
fake = Faker()
class TestUserAPI(APITestCase):
"""
Tests the /users endpoint.
"""
def setUp(self):
self.url = reverse('user-list')
self.user_data = model_to_dict(UserFactory.build())
def test_post_request_with_no_data_fails(self):
r... |
def test_post_request_with_valid_data_succeeds(self):
response = self.client.post(self.url, self.user_data)
eq_(response.status_code, 201)
user = User.objects.get(pk=response.data.get('id'))
eq_(user.username, self.user_data.get('username'))
ok_(check_password(self.user_dat... |
semk/voldemort | voldemort/config.py | Python | apache-2.0 | 1,783 | 0 | # -*- coding: utf-8 -*-
#
# Voldemort config
#
# @author: Sreejith K
# Created On 19th Sep 2011
import os
import logging
from yaml import load, dump, Loader, Dumper
log = logging.getLogger(__name__)
DEFAULT_CONFIG = """\
# voldemort configuration file
layout_dirs :
- layout
- include
... | g.info('Loading voldemort configuration')
config_file = os.path.join(work_dir, name)
if not os.pa | th.exists(config_file):
write_config = raw_input(
'No configuration file found. Write default config? [Y/n]: ')
write_config = (
write_config == 'Y' or
write_config == 'y' or
write_config == '') and True or False
if write_config:
log.in... |
anchore/anchore | anchore/anchore-modules/queries/get-retrieved-files.py | Python | apache-2.0 | 3,253 | 0.004304 | #!/usr/bin/env python
import sys
import os
import re
import traceback
import tarfile, io
import anchore.anchore_utils
def get_retrieved_file(imgid, srcfile, dstdir):
ret = list()
extractall = False
if srcfile == 'all':
extractall = True
thedstdir = os.path.join(dstdir, imgid)
tarfiles ... | srcname = ret[0]
dstname = ret[1]
outlist.append([imgid, tags, srcname, dstname])
else:
warns.append("Could not find any stored files matching input '"+str(srcfile)+"' in image's stored files")
except Exception as err:
# handle the case where something wrong happened
... | match case
if len(outlist) < 1:
#outlist.append(["NOMATCH", "NOMATCH", "NOMATCH"])
pass
anchore.anchore_utils.write_kvfile_fromlist(config['output'], outlist)
if len(warns) > 0:
anchore.anchore_utils.write_plainfile_fromlist(config['output_warns'], warns)
sys.exit(0)
|
jbd/treewatcher | examples/monitor-threaded.py | Python | gpl-3.0 | 4,149 | 0.00482 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
#
# Copyright (c) 2010 Jean-Baptiste Denis.
#
# This is free software; you can redistribute it and/or modify it under the
# terms of the GNU General Public License version 3 and superior as published by the Free
# Software Foundation.
#
# A copy of the license has been inclu... | ead().name))
def unmount(self, path, is_dir):
""" callback called on a 'IN_UNMOUNT' event """
_LOGGER.info("unmount: %s %s %s" % (path, is_dir, threading.current_thread().name))
if __name__ == '__main__':
# Yeah, command line parsing
if len(sys.argv) < 2:
print "usage:", sys.argv... | path_to_watch, "is not a valid directory."
sys.exit(2)
# We instanciate our callbacks object
callbacks = MonitorCallbacks()
# we get a source tree monitor
stm = choose_source_tree_monitor()
# we set our callbacks
stm.set_events_callbacks(callbacks)
# we will use two threads to hand... |
Luthaf/Zested | Zested.py | Python | bsd-2-clause | 91 | 0 | #!/u | sr/bin/env python3
from zested.main import main
if __name__ == "__main__" | :
main()
|
FireWRT/OpenWrt-Firefly-Libraries | staging_dir/target-mipsel_1004kc+dsp_uClibc-0.9.33.2/usr/lib/python3.4/idlelib/idle_test/test_searchdialogbase.py | Python | gpl-2.0 | 5,860 | 0.001706 | '''Unittests for idlelib/SearchDialogBase.py
Coverage: 99%. The only thing not covered is inconsequential --
testing skipping of suite when self.needwrapbutton is false.
'''
import unittest
from test.support import requires
from tkinter import Tk, Toplevel, Frame, Label, BooleanVar, StringVar
from idlelib import Sear... | lf.dialog.top = Toplevel(self.root)
entry, label = self.dialog.make_entry("Test:", 'hello')
equal(label['text'], 'Test:')
self.assertIn(entry.get(), 'hello')
egi = entry.grid_info()
equal(int(egi['row']), 0)
equal(int(egi['column']), 1)
equal(int(egi['rowspan']),... | pan']), 1)
equal(self.dialog.row, 1)
def test_create_entries(self):
self.dialog.row = 0
self.engine.setpat('hello')
self.dialog.create_entries()
self.assertIn(self.dialog.ent.get(), 'hello')
def test_make_frame(self):
self.dialog.row = 0
self.dialog.top ... |
SARL-Engineering/ZScan_Processor | Framework/TrayNotifier/TrayNotifierCore.py | Python | lgpl-3.0 | 3,597 | 0.00278 | # coding=utf-8
#####################################
# Imports
#####################################
# Python native imports
from PyQt5 import QtCore, QtWidgets, QtGui
import logging
#####################################
# Global Variables
#####################################
UI_LOGO = "logo_small.jpg"
############... | .QSystemTrayIcon.Context: # Happens on right-click, ignore for tray menu instead
pass
elif event in [QtWidgets.QSystemTrayIcon.Trigger, QtWidgets.QSystemTrayIcon.Double | Click]:
self.main_screen.show()
self.main_screen.setWindowState(
self.main_screen.windowState() & ~QtCore.Qt.WindowMinimized | QtCore.Qt.WindowActive)
self.main_screen.activateWindow()
elif event.text() == "Show":
self.main_screen.show()
... |
haakenlid/django-extensions | django_extensions/management/commands/runserver_plus.py | Python | mit | 22,214 | 0.003061 | # -*- coding: utf-8 -*-
from __future__ import print_function
import logging
import os
import re
import socket
import sys
import time
import django
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.management.base import BaseCommand, CommandError
from django.cor... | ault=False,
help="Disable the PIN in werkzeug. USE IT WISELY!"),
if USE_STATICFILES:
pa | rser.add_argument('--nostatic', action="store_false", dest='use_static_handler', default=True,
help='Tells Django to NOT automatically serve static files at STATIC_URL.')
parser.add_argument('--insecure', action="store_true", dest='insecure_serving', default=False,
... |
CospanDesign/nysa-artemis-usb2-platform | artemis_usb2/spi_flash/serial_flash_manager.py | Python | gpl-2.0 | 5,915 | 0.007101 | # Copyright (c) 2010-2011, Emmanuel Blot <[email protected]>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# noti... | ND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import os
import sys
import json
from array import array as Array
sys | .path.append(os.path.join(os.path.dirname(__file__), os.pardir))
from spi import SpiController
#Get all types of the SPI Flash
import numonyx_flash
CMD_JEDEC_ID = 0x9F
#Exceptions
class SerialFlashNotSupported(Exception):
"""Exception thrown when a non-existing feature is invoked"""
class SerialFlashUnknownJe... |
LearnEra/LearnEraPlaftform | cms/envs/common.py | Python | agpl-3.0 | 21,668 | 0.002538 | # -*- coding: utf-8 -*-
"""
This is the common settings file, intended to set sane defaults. If you have a
piece of configuration that's dependent on a set of feature flags being set,
then create a function that returns the calculated value based on the value of
FEATURES[...]. Modules that extend this one can change th... | ATURE C | ONFIGURATION #############################
FEATURES = {
'USE_DJANGO_PIPELINE': True,
'GITHUB_PUSH': False,
# for consistency in user-experience, keep the value of the following 3 settings
# in sync with the ones in lms/envs/common.py
'ENABLE_DISCUSSION_SERVICE': True,
'ENABLE_TEXTBOOK': True,... |
cesardeazevedo/sniffle | sniffle/wsgi.py | Python | mit | 391 | 0.005115 | """
It exposes the WSGI callable as a module-level v | ariable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sniffle.settings")
from django.core.wsgi import get_wsgi_application
from dj_static imp | ort Cling
application = Cling(get_wsgi_application())
|
TeaBough/calico-docker | calico_containers/tests/unit/container_test.py | Python | apache-2.0 | 39,497 | 0.000709 | # Copyright 2015 Metaswitch 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 law or agreed to in w... | IPPool
class TestContainer(unittest.TestCase):
@parameteriz | ed.expand([
({'<CONTAINER>':'node1', 'ip':1, 'add':1, '<IP>':'127.a.0.1'}, True),
({'<CONTAINER>':'node1', 'ip':1, 'add':1, '<IP>':'aa:bb::zz'}, True),
({'add':1, '<CONTAINER>':'node1', '<IP>':'127.a.0.1'}, True),
({'add':1, '<CONTAINER>':'node1', '<IP>':'aa:bb::zz'}, True)
])
de... |
Nikolay-Kha/PyCNC | cnc/sensors/thermistor.py | Python | mit | 1,948 | 0 | """
This module reads temperature from NTC thermistor connected to ads111x.
Circuit diagram for this module should be like this:
Vcc
---
|
|
.-.
| |
| | R1
'-'
|
o----------------o------------> ads111x input
| |
| | |
... | 0, 4):
try:
t = get_temperature(i)
except (IOError, OSError):
t = None
print("T{}={}".forma | t(i, t))
print("-----------------------------")
time.sleep(0.5)
|
purism/pdak | dak/dak.py | Python | gpl-2.0 | 8,306 | 0.002047 | #!/usr/bin/env python
"""
Wrapper to launch dak functionality
G{importgraph}
"""
# Copyright (C) 2005, 2006 Anthony Towns <[email protected]>
# Copyright (C) 2006 James Troup <[email protected]>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License... | e(functionality, 1)
# Invoke the module
module = __import__(cmdname.replace("-","_"))
try:
module.main()
except KeyboardInterrupt:
msg = 'KeyboardInterrupt caught; exiting'
print msg
if logger:
logger.log([msg])
sys.exit(1)
except SystemExit:
... | 1]:
logger.log(['exception', line])
raise
###################################################### |
devilry/devilry-django | devilry/devilry_account/crapps/account/select_language.py | Python | bsd-3-clause | 2,654 | 0.00113 | # import pycountry as pycountry
from django.conf import settings
from django.http import HttpResponseRedirect, Http404
from django.utils import translation
from django.views.generic import TemplateView
from devilry.devilry_account.crapps.account import utils
from devilry.devilry_account.models import User
class Lang... | d_languagecode
else:
request.session['SELECTED_LANGUAGE_CODE'] = selected_languagecode
return HttpResponseRedirect('/account/')
def __update_user_language_code(self, request, languagecode):
try:
user = User.objects.get(id=request.user.id)
except User.DoesNotE... | user.full_clean()
user.save()
def __get_selected_languagecode(self, data):
selected_languagecode = data.get('selected_language', None)
if not selected_languagecode:
return translation.get_language()
languagecodes = [language[0] for language in settings.LANGUAGES]
... |
projecthamster/hamster-dbus | tests/storage/common.py | Python | gpl-3.0 | 748 | 0 | # -*- coding: utf-8 -*-
"""Module to provide a common base ``TestCase``."""
from __future__ import absolute_import, unicode_literals
import dbusmock
class HamsterDBusManagerTestCase(dbusmock.DBusTestCase):
"""
Common testcase for storage backend unittests.
This test case makes sure tests are run | against a new private session bus
instance and provides easy access to the underlying dbus connection.
"""
@classmethod
def setUpClass(cls):
"""Setup new private session bus."""
cls.start_session_bus()
cls.dbus_con = cls.get | _dbus()
def tearDown(self):
"""Terminate any service launched by the test case."""
self.service_mock.terminate()
self.service_mock.wait()
|
mvendra/mvtools | download_url.py | Python | mit | 992 | 0.00504 | #!/usr/bin/env python3
import sys
i | mpor | t os
import urllib.request
import path_utils
# credit: https://stackoverflow.com/questions/22676/how-to-download-a-file-over-http
def download_url(source_url, target_path):
if os.path.exists(target_path):
return False, "Target path [%s] already exists" % target_path
contents = None
try:
... |
mikepii/retail_store_foot_traffic_monitor | tracking/management/commands/checkin.py | Python | apache-2.0 | 1,191 | 0.004198 | import datetime
from optparse import make_option
from django.conf import settings
from djang | o.core.management.base import BaseCommand, CommandError
from six import print_
import bigbro
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make | _option('--store',
dest='store',
help='Watch log subdirectory'),
)
help = 'Log employee RFID check-ins.'
def handle(self, *args, **options):
print_('Note: RFID scanner must be set up for keyboard input (see README).')
print_('Waiting for RFID input. P... |
google/material-design-icons | update/venv/lib/python3.9/site-packages/pip/_internal/utils/models.py | Python | apache-2.0 | 1,329 | 0 | """Utilities for defining models
"""
import operator
from typing import Any, Callable, Type
class KeyBasedCompareMixin:
"""Provides comparison capabilities that is based on a key"""
__slots__ = ["_compare_key", "_defining_class"]
def __init__(self, key, defining_class):
# type: (Any, Type[KeyBa... | def __eq__(self, other):
# type: (Any) -> bool
return self. | _compare(other, operator.__eq__)
def _compare(self, other, method):
# type: (Any, Callable[[Any, Any], bool]) -> bool
if not isinstance(other, self._defining_class):
return NotImplemented
return method(self._compare_key, other._compare_key)
|
ASMlover/study | python/proto/pyRpc/logger.py | Python | bsd-2-clause | 1,837 | 0.000544 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
#
# Copyright (c) 2016 ASMlover. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyrig... | AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQ | UENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE ... |
kirbyfan64/hy | setup.py | Python | mit | 3,580 | 0 | #!/usr/bin/env python
# Copyright (c) 2012, 2013 Paul Tagliamonte <[email protected]>
#
# 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 limita | tion
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or su... | TIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER... |
gsarma/ChannelWorm | scripts/iv_curve_from_model.py | Python | mit | 606 | 0.006601 | import subprocess, os
if os.path.bas | ename(os.getcwd()) != 'scripts':
print("Run this from the scripts directory")
exit()
#make a "sandox" for the large number of files being generated
try:
os.mkdir('simfiles')
except OSError:
| pass
os.chdir('simfiles')
subprocess.call(['pynml-channelanalysis', '-temperature', '34', '-minV', '-55', '-maxV', '80', '-duration', '600', '-clampBaseVoltage', '-55', '-clampDuration', '580', '-stepTargetVoltage', '10', '-erev', '50', '-caConc', '0.001', '-clampDuration', '600', '-stepTargetVoltage', '5', '-iv... |
bnaul/scikit-learn | sklearn/feature_selection/tests/test_rfe.py | Python | bsd-3-clause | 16,445 | 0 | """
Testing Recursive feature elimination
"""
from operator import attrgetter
import pytest
import numpy as np
from numpy.testing import assert_array_almost_equal, assert_array_equal
from scipy import sparse
from sklearn.feature_selection import RFE, RFECV
from sklearn.datasets import load_iris, make_friedman1
from s... | port SVC, SVR, LinearSVR
from sk | learn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import GroupKFold
from sklearn.compose import TransformedTargetRegressor
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing... |
cherry-wb/SideTools | examples/tutorial/t8.py | Python | apache-2.0 | 3,265 | 0.001225 | #!/usr/bin/env python
# PyQt tutorial 8
import sys
from PySide import QtCore, QtGui
class LCDRange(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
lcd = QtGui.QLCDNumber(2)
self.slider = QtGui.QSlider(QtCore.Qt.Horizontal)
se... |
def setRange(self, minValue, maxValue):
if minValue < 0 or maxValue > 99 or minValue > maxValue:
QtCore.qWarning("LCDRange.setRange(%d, %d)\n"
"\tRange must be 0..99\n"
"\tand minValue must not be greater than maxValue" % (minValue, maxValue))
... | e)
class CannonField(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.currentAngle = 45
self.setPalette(QtGui.QPalette(QtGui.QColor(250, 250, 200)))
self.setAutoFillBackground(True)
def angle(self):
return self.cur... |
makerplane/FIX-Gateway | tests/test_database.py | Python | gpl-2.0 | 20,881 | 0.001724 | # Copyright (c) 2018 Phil Birkelbach
#
# 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... | min: -180.0
ma | x: 180.0
units: deg
initial: 0.0
tol: 200
- key: AOA
description: Angle of attack
type: float
min: -180.0
max: 180.0
units: deg
initial: 0.0
tol: 200
aux:
- Min
- Max
- 0g
- Warn
- Stall
- key: CTLPTCH
description: Pitch Control
type: float
min: -1.0
max: 1.0
units: '%/100'
... |
mitya57/debian-buildbot | buildbot/db/buildsets.py | Python | gpl-2.0 | 7,930 | 0.000883 | # This file is part of Buildbot. Buildbot 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, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... | .pool.do(thd)
def getBuildset(self, bsid):
def thd(conn):
| bs_tbl = self.db.model.buildsets
q = bs_tbl.select(whereclause=(bs_tbl.c.id == bsid))
res = conn.execute(q)
row = res.fetchone()
if not row:
return None
return self._row2dict(row)
return self.db.pool.do(thd)
def getBuilds... |
ChinaMassClouds/copenstack-server | openstack/src/ceilometer-2014.2.2/ceilometer/alarm/notifier/trust.py | Python | gpl-2.0 | 2,433 | 0 | #
# Copyright 2014 eNovance
#
# 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, ... | plit("@")[1]
# Remove the trust prefix
scheme = action.scheme[6:]
action = parse.SplitResult(scheme, netloc, action.path, action.query,
action.fragment)
headers = {'X-Auth-Token': client.auth_token}
rest.RestAlarmNotif | ier.notify(
action, alarm_id, previous, current, reason, reason_data, headers)
|
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/lepl/stream/core.py | Python | agpl-3.0 | 12,016 | 0.006491 |
# The contents of this file are subject to the Mozilla Public License
# (MPL) Version 1.1 (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.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS"
# b... | s of the LGPL License and not to allow others to use your version
# of this file under the MPL, indicate your decision by deleting the
# provisions above and replace them with the notice and other provisions
# required by the LGPL License. If you do not delete the | provisions
# above, a recipient may use your version of this file under either the
# MPL or the LGPL License.
'''
Default implementations of the stream classes.
A stream is a tuple (state, helper), where `state` will vary from location to
location, while `helper` is an "unchanging" instance of `StreamHelper`,
defi... |
xyang619/AdmixSim | mssim2eigen.py | Python | gpl-3.0 | 3,816 | 0.019654 | '''
Name: mssim2eigen.py
Date: 2014-8-25
Version: 1.01
Author: Young
Description:
Convert the output of MS simulation into eigenstrat format, only deal with
1 repeat siutation
Input file: the output of MS simulation
Output files: prefix.ind prefix.snp prefix.geno
Arguments:
-h --help print hel... | }\t1\t{:.8f}\t{}\t{}\t{}\n'.format(i,gp,pp,a1,a2))
i+=1
print('Write snpfile into {}'.format(snpfile))
def gen(simfile, npop=1, ninds=None, L=1e7, prefix='sim'):
gen_ind(npop, ninds, prefix)
genofile='{}.geno'.format(prefix)
with open(simfile) as f,open(genofile, 'w') as gf:
for... | n range(5):
f.readline() #skip 5 line
posline=f.readline() #posline
gen_snp(posline, L, prefix)
tm=[] #temp matrix
line=f.readline()
while line:
h1=[]
for c in line[:-1]:
h1.append(int(c))
i=0
lin... |
openstack/storlets | tests/unit/swift_middleware/handlers/test_proxy.py | Python | apache-2.0 | 34,297 | 0 | # Copyright (c) 2010-2015 OpenStack Foundation
#
# 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... | , len(calls))
def test_GET_with_storlets_object_404(self):
target = '/v1/AUTH_a/c/o'
self.base_app.register('GET', target, HTTPNotFound)
storlet = '/v1/AUTH_a/storlet/Storlet-1.0.jar'
self.base_app.register('GET', storlet, HTTPOk, body=b'jar binary')
with storlet_enabled():... | -1.0.jar'}
resp = self.get_request_response(target, 'GET', headers=headers)
self.assertEqual('404 Not Found', resp.status)
calls = self.base_app.get_calls()
self.assertEqual(2, len(calls))
def test_GET_with_storlets_and_http_range(self):
target = '/v1/AUTH_a... |
blackgnezdo/mailcrypt | tests/remailer/gtkwatcher.py | Python | gpl-2.0 | 11,898 | 0.002353 | #! /usr/bin/python
if __name__ == '__main__':
import pygtk
pygtk.require("2.0")
import time, cPickle
import gobject, gtk, gtk.glade
from watcher import Watcher
def time_string(latency):
if latency == None:
return "?"
latency = int(latency)
hours = latency / 3600
latency -= hours * 360... | 0)
self.src_age_item = xml.get_widget("src_age_item")
self.src_age_item.set_sensitive(0)
self.src_abandon_item = xml.get_widget("src_abandon_item")
# dest panel
self.dst_popup = xml.get_widget("dst_popup")
xml.get_widget("dest_message_options1").set_sensitive(0)
... | ent_item")
self.dst_sent_item.set_sensitive(0)
self.dst_original_item = xml.get_widget("dst_original_item")
self.dst_flush_item = xml.get_widget("dst_flush_item")
xml.signal_connect('do_dst_flush', self.do_dst_flush)
xml.signal_connect('do_dst_original', self.do_dst_original)
... |
stoewer/nixpy | docs/source/examples/multipleROIs.py | Python | bsd-3-clause | 4,189 | 0.001433 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Copyright © 2014 German Neuroinformatics Node (G-Node)
All rights reserved.
Redistribution and use | in source and binary forms, with or without
modification, are permitted under the terms of the BSD License. See
LICENSE file in the root of the Project.
Author: Jan Grewe <[email protected]>
This tutorial shows how to store image data in nix-files.
See https://github.com/G-node/nix/wiki for more information.... | 972, photographed by Dwight Hooker.This 512x512
electronic/mechanical scan of a section of the full portrait:
Alexander Sawchuk and two others[1] - The USC-SIPI image
database. Via Wikipedia -
http://en.wikipedia.org/wiki/File:Lenna.png#mediaviewer/File:Lenna.png
"""
import nixio as nix
import numpy as np
import ... |
jcmgray/quijy | quimb/linalg/approx_spectral.py | Python | mit | 30,236 | 0 | """Use stochastic Lanczos quadrature to approximate spectral function sums of
any operator which has an efficient representation of action on a vector.
"""
import functools
from math import sqrt, log2, exp, inf, nan
import random
import warnings
import numpy as np
import scipy.linalg as scla
from scipy.ndimage.filters... | struct | _lanczos_tridiag_MPO = raise_cant_find_library_function(reqs)
# --------------------------------------------------------------------------- #
# 'Lazy' representation tensor contractions #
# --------------------------------------------------------------------------- #
def lazy_ptr_l... |
TomoyoshiToyoda/language_processing | language_processing_100/python3/sect1/NLP00.py | Python | mit | 137 | 0.007299 | #! /usr/bin/env python3
if __name__ == '__main__':
message = " | stressed"
l = list( | message)
l.reverse()
print(''.join(l))
|
bnoordhuis/suv | deps/gyp/test/ios/gyptest-per-config-settings.py | Python | isc | 1,320 | 0.010606 | #!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies that device and simulator bundles are built corre | ctly.
"""
import TestGyp
import subprocess
import sys
def CheckFileType(file, expected):
proc = subprocess.Popen(['lipo', '-info', file], stdout=subprocess.PIPE)
o = proc.communicate()[0].strip()
assert not proc.returncode
if not expected in o:
print 'File: Expected %s, got %s' % (expected, o)
test.f... | rts.
test = TestGyp.TestGyp(formats=['ninja'])
test.run_gyp('test-device.gyp', chdir='app-bundle')
for configuration in ['Debug-iphoneos', 'Debug-iphonesimulator']:
test.set_configuration(configuration)
test.build('test-device.gyp', test.ALL, chdir='app-bundle')
result_file = test.built_file_path('T... |
mdutkin/m2core | m2core/__init__.py | Python | mit | 171 | 0 | from m2core.m2core import M2Core, logger
from m2core import bases
from m2core import data_schemes
fro | m m2core | import db
from m2core import utils
from m2core import common
|
teeple/pns_server | work/install/Python-2.7.4/Lib/plat-irix5/CL_old.py | Python | gpl-2.0 | 6,162 | 0.003246 | #
# cl.h - Compression Library typedefs and prototypes
#
# 01/07/92 Cleanup by Brian Knittel
# 02/18/92 Original Version by Brian Knittel
#
#
# originalFormat parameter values
#
from warnings import warnpy3k
warnpy3k("the CL_old module has been removed in Python 3.0", stacklevel=2)
del warnpy3k
MAX_NUMBER_O... | # invalid parameter
BAD_COMPRESSION_SCHEME = -7 # compression scheme parameter invalid
BAD_COMPRESSOR_HANDLE = -8 | # compression handle parameter invalid
BAD_COMPRESSOR_HANDLE_POINTER = -9 # compression handle pointer invalid
BAD_BUFFER_HANDLE = -10 # buffer handle invalid
BAD_BUFFER_QUERY_SIZE = -11 # buffer query size too large
JPEG_ERROR = -12 # error from libj... |
shankari/e-mission-server | emission/core/wrapper/battery.py | Python | bsd-3-clause | 1,602 | 0.01186 | from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
import logging
import emission.core.wrapper.wrapperbase as ecwb
import enum a... | y used to make the battery
"android_temperature": ecwb.WrapperBase.Access.RO, # android-only: current temperature
"android_voltage": ecwb.WrapperBase.Access.RO, # android-only: current voltage
"ts": ecwb | .WrapperBase.Access.RO,
"local_dt": ecwb.WrapperBase.Access.RO,
"fmt_time": ecwb.WrapperBase.Access.RO
}
enums = {"battery_status": BatteryStatus}
geojson = []
nullable = []
local_dates = ['local_dt']
def _populateDependencies(self):
pass
|
jmartinm/InvenioAuthorLists | modules/bibcirculation/lib/bibcirculation_utils.py | Python | gpl-2.0 | 21,079 | 0.003985 | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2008, 2009, 2010, 2011 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; either version 2 of the
## License, or ... | @return book cov | er
"""
from xml.dom import minidom
import urllib
# connect to AWS
cover_xml = urllib.urlopen('http://ecs.amazonaws.com/onca/xml' \
'?Service=AWSECommerceService&AWSAccessKeyId=' \
+ CFG_BIBCIRCULATION_AMAZON_ACCESS_KEY + \
... |
aoldoni/tetre | lib/parsers_cache.py | Python | mit | 1,577 | 0.001902 | import os
import pickle
from parsers_backend import get_tree
from directories import dirs
def get_cached_sentence_image(argv, output_path, img_path):
"""Returns if the image is already generated or not, and avoids generating if yes.
Args:
argv: The command line arguments | .
output_path: The path for the output folder.
img_path: The path to the image file to be checked.
Returns:
A boolean flagging if image is already gene | rated or not.
"""
cache_file_final = output_path + img_path
if argv.tetre_force_clean:
return False
else:
return os.path.isfile(cache_file_final)
def get_cached_tokens(argv):
"""Returns the already parsed sentences containing the word being search, if the folder was not modified.... |
GNOME/mm-common | util/meson_aux/skeletonmm-tarball.py | Python | gpl-2.0 | 1,665 | 0.010811 | #!/usr/bin/env python3
# External command, intended to be called with run_command() or custom_target()
# in meson.build
# argv[1] argv[2] argv[3:]
# skeletonmm-tarball.p | y <output_file_or_check> <source_dir> <input_files...>
import os
import sys
import shutil
import tarfile
if sys.argv[1] == 'check':
# Called from run_command() during setup or config | uration.
# Check which archive format can be used.
# In order from most wanted to least wanted: .tar.xz, .tar.gz, .tar
available_archive_formats = []
for af in shutil.get_archive_formats():
# Keep the formats in a list, skip the descriptions.
available_archive_formats += [af[0]]
if 'xztar' in availabl... |
eecsu/BET | examples/nonlinearMap/myModel.py | Python | gpl-3.0 | 1,989 | 0.003519 | # Copyright (C) 2016 The BET Development Team
# -*- coding: utf-8 -*-
import numpy as np
import math as m
'''
Suggested changes for user:
Try setting QoI_num = 2.
Play around with the x1, y1, and/or, x2, y2 values to try and
"optimize" the QoI to give the highest probability region
on the reference parameter above.... | oI maps
if QoI_num == 1:
def QoI_map(parameter_samples):
Q1 = QoI_component(x[0], y[0])
return np.array([Q1.eval(parameter_samples)]).transpose()
else:
def QoI_map(parameter_samples):
Q1 = QoI_co | mponent(x[0], y[0])
Q2 = QoI_component(x[1], y[1])
return np.array([Q1.eval(parameter_samples), Q2.eval(parameter_samples)]).transpose()
# Define a model that is the QoI map
def my_model(parameter_samples):
QoI_samples = QoI_map(parameter_samples)
return QoI_samples
|
micropython-IMU/micropython-bmx055 | bmm050.py | Python | mit | 2,581 | 0.001162 | """
bmm050 is a micropython module for the Bosch BMM050 sensor.
It measures the magnetic field in three axis.
The MIT License (MIT)
Copyright (c) 2016 Sebastian Plamauer [email protected]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (... | THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTH... | THE
SOFTWARE.
"""
from time import sleep
# from stackoverflow J.F. Sebastian
def _twos_comp(val, bits=8):
"""
compute the 2's complement of int val with bits
"""
if (val & (1 << (bits - 1))) != 0: # if sign bit is set
val = val - (1 << bits) # compute negative value
return val ... |
cosmolab/cosmogenic | cosmogenic/sim.py | Python | bsd-2-clause | 6,358 | 0.001101 | """
Simulate geomorphic scenarios along with CN production.
"""
from __future__ import division, print_function, unicode_literals
import numpy as np
import scipy.integrate
from cosmogenic import production
def nexpose(n, z, ti, tf=0, p=None, tol=1e-4, thickness=None):
"""
Calculate concentrations for an arb... | gl = gl * np.ones(n_gl)
intergl = intergl * np.ones(n_gl)
dz = dz * np.ones(n_gl)
# interleave the two arrays
tmp = np.column_stack((gl, intergl)).reshape(1, gl.size * 2).flatten()
t = np.add.accumulate(np.concatenate(([0, postgl], tmp)))
tmp = np.column_stack((dz, np.zeros(dz.size))).reshape... | xpose samples a depths z (g/cm**2) from time ti until time tf
(both in years) at production rate p(z). Adjust their concentrations for
radioactive decay since tf. Return the concentration of nuclide n.
If p is not supplied, n.production_rate is used.
"""
if p is None:
p = n.production_r... |
2gis/vmmaster | tests/unit/test_commands.py | Python | mit | 16,406 | 0.000488 | # coding: utf-8
import copy
import json
from mock import Mock, PropertyMock, patch
from tests.helpers import Handler, BaseTestCase, ServerMock, get_free_port, DatabaseMock
from core.exceptions import CreationException, ConnectionError, \
SessionException, TimeoutException
from core.config import setup_config, co... | ck()
):
from core.db.models import Session, Provider, Endpoint
self.session = Session('origin_1')
self.session.name = "session1"
provider = Provider(name='noname', url='nourl')
vm = Endpoint(Mock(), '', pr | ovider)
vm.name = 'vm1'
vm.ip = self.host
vm.ports = {
'selenium': self.webdriver_server.port,
'agent': self.vmmaster_agent.port,
'vnc': self.vnc_server.port
}
self.session.endpoint = vm
self.session... |
airanmehr/bio | Scripts/KyrgysHAPH/GenomeAFS.py | Python | mit | 1,365 | 0.017582 | '''
Copyleft Feb 11, 2017 Arya Iranmehr, PhD Student, Bafna Lab, UC San Diego, Email: [email protected]
'''
import numpy as np;
np.set_printoptions(linewidth=200, precision=5, suppress=True)
import pandas as pd;
pd.options.display.max_rows = 20;
pd.options.display.expand_frame_repr = False
import pylab as plt;
imp... | lse))
a.apply(lambda x: kplt. | SFSChromosomwise(x, True, True))
def SFS():
plotSFSall()
plotSFSall('X')
plotSFSall('Y')
plotChromAll() |
corymintz/mtools | mtools/util/logfile.py | Python | apache-2.0 | 10,383 | 0.003949 | from mtools.util.logevent import LogEvent
from mtools.util.input_source import InputSource
from math import ceil
from datetime import datetime
import time
import re
class LogFile(InputSource):
""" wrapper class for log files, either as open file streams of from stdin. """
def __init__(self, filehandle):
... | wrong
line = self.filehandle.readline()
if line == '':
raise StopIteration
line = line.rstrip('\n')
le = LogEvent(line)
# hint format and nextpos from previous line
if self._datetime_format and self._datetime_nextpos != None:
ret = le.set... | if not ret:
# logevent indicates timestamp format has changed, invalidate hint info
self._datetime_format = None
self._datetime_nextpos = None
elif le.datetime:
# print "not hinting"
# gather new hint info from another logevent
... |
ox-it/humfrey | humfrey/linkeddata/uri.py | Python | bsd-3-clause | 3,761 | 0.002925 | import re
import urllib
import urlparse
try:
from urlparse import parse_qs
except ImportError:
from cgi import parse_qs
import rdflib
from django.conf import settings
from django.core.urlresolvers import reverse
if 'django_hosts' in settings.INSTALLED_APPS:
from django_hosts.reverse import reverse_full
... | t_pattern):
self._base = base
self._format_pattern = format_pattern
def __getitem__(self, format):
if format is None:
return self._base
else:
return self._format_pattern % {'format': format}
def doc_forwards(uri, graph=None, described=None):
"""
Deter... | njunctiveGraph that can be checked for a description
of uri. described is a ternary boolean (None for 'unknown').
"""
if isinstance(uri, unicode):
encoded_uri = uri.encode('utf-8')
else:
encoded_uri = urllib.unquote(uri)
for id_prefix, doc_prefix, _ in get_id_mapping():
if ... |
dajusc/trimesh | trimesh/exchange/dae.py | Python | mit | 13,245 | 0.000151 | import io
import copy
import uuid
import numpy as np
try:
# pip install pycollada
import collada
except BaseException:
collada = None
from .. import util
from .. import visual
from ..constants import log
def load_collada(file_obj, resolver=None, **kwargs):
"""
Load a COLLADA (.dae) file into a... | # Get UV coordinates if possible
vis = None
if primitive.material in local_material_map:
mater | ial = copy.copy(
local_material_map[primitive.material])
uv = None
if len(primitive.texcoordset) > 0:
texcoord = primitive.texcoordset[0]
texcoord_index = primitive.texcoord_indexset[0]
... |
iankronquist/numinous-nimbus | cs290/howto/site/pelicanconf.py | Python | mit | 883 | 0.001133 | #!/usr/bin/env python
# -*- coding: utf-8 -*- | #
from __future__ import unicode_literals
AUTHOR = u'Ian Kronquist'
SITENAME = u'CS290 How-To Guide'
SITEURL = ''
PATH = 'content'
TIMEZONE = 'America/Los_Angeles'
DEFAULT_L | ANG = u'en'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
AUTHOR_FEED_ATOM = None
AUTHOR_FEED_RSS = None
# Blogroll
LINKS = (('Pelican', 'http://getpelican.com/'),
('Python.org', 'http://python.org/'),
('Jinja2', ... |
mlperf/training_results_v0.6 | Fujitsu/benchmarks/resnet/implementations/mxnet/3rdparty/tvm/topi/tests/python/test_topi_bitserial_conv2d.py | Python | apache-2.0 | 4,850 | 0.008247 | import numpy as np
import tvm
import topi
import topi.testing
from topi.util import get_const_tuple
from tvm.contrib.pickle_memoize import memoize
def generate_quantized_np(shape, bits, out_dtype):
min_val = 0
max_val = 1 << bits
return np.random.randint(min_val, max_val, size=shape).astype(out_dtype)
def... | i.generic.schedule_bitserial_conv2d_nchw([B])
a_shape = get_const_tuple(A.shape)
w_shape = get_const_tuple(W.shape)
@memoize("topi.tests.test_topi_bitseral_ | conv2d_nchw")
def get_ref_data():
a_np = generate_quantized_np(get_const_tuple(a_shape), activation_bits, input_type)
w_np = generate_quantized_np(get_const_tuple(w_shape), weight_bits, input_type)
if dorefa:
w_ = np.copy(w_np).astype(out_dtype)
for x in np.nditer(w_,... |
totalvoice/totalvoice-python | totalvoice/cliente/api/conta.py | Python | mit | 6,794 | 0.003725 | # coding=utf-8
from __future__ import absolute_import
from .helper import utils
from .helper.routes import Routes
from totalvoice.cliente.api.totalvoice import Totalvoice
import json, requests
class Conta(Totalvoice):
def __init__(self, cliente):
super(Conta, self).__init__(cliente)
def criar_conta(... |
response = requests.post(host, headers=utils.build_header(self.cliente.access_token), data=data)
return response.content
def deletar(self, id):
"""
:Descrição:
Função para deletar uma conta.
:Utilização:
deletar(id)
:Parâmetros:
- id:
... | d])
response = requests.delete(host, headers=utils.build_header(self.cliente.access_token))
return response.content
def get_by_id(self, id):
"""
:Descrição:
Função para buscar as informações de uma conta.
:Utilização:
get_by_id(id)
:Parâme... |
Yadnyawalkya/integration_tests | cfme/tests/services/test_config_provider_servicecatalogs.py | Python | gpl-2.0 | 4,833 | 0.003517 | # -*- coding: utf-8 -*-
import pytest
from cfme import test_requirements
from cfme.services.myservice import MyService
from cfme.services.service_catalogs import ServiceCatalogs
from cfme.utils import testgen
from cfme.utils.blockers import GH
from cfme.utils.log import logger
pytestmark = [
test_requirements.se... | s=new_idlist, scope='module')
@pytest.fixture(scope="modul | e")
def config_manager(config_manager_obj):
""" Fixture that provides a random config manager and sets it up"""
if config_manager_obj.type == "Ansible Tower":
config_manager_obj.create(validate=True)
else:
config_manager_obj.create()
yield config_manager_obj
config_manager_obj.delete... |
d3banjan/polyamide | webdev/lib/python2.7/site-packages/pip/commands/wheel.py | Python | bsd-2-clause | 9,184 | 0 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import logging
import os
import warnings
from pip.basecommand import Command
from pip.index import PackageFinder
from pip.exceptions import CommandError, PreviousBuildDirError
from pip.req import InstallRequirement, RequirementSet, parse_requirements
from... | t os.path.exists(options.wheel_dir):
os.makedirs(options.wheel_dir)
# parse args and/or requirements f | iles
for name in args:
requirement_set.add_requirement(
InstallRequirement.from_line(
name, None, isolated=options.isolated_mode,
)
)
for name in options.editables:
... |
terrycojones/dark-matter | test/test_fastq.py | Python | mit | 4,526 | 0 | from six.moves import builtins
from dark.reads import AARead, DNARead, RNARead
from dark.fastq import FastqReads
from dark.utils import StringIO
from unittest import TestCase, skip
try:
from unittest.mock import patch, mock_open
except ImportError:
from mock import patch
class TestFastqReads(TestCase):
... | '+', '!!!!'])
with patch.object(builtins, 'open', mock_open(read_data=data)):
reads = list(FastqReads('filename.fastq', RNARead))
self.assertTrue(isinstance(reads[0], RNARead))
@skip('Some tests are broken and skipped under latest BioPython')
def testTwoFiles(self):
"""... | class SideEffect(object):
def __init__(self, test):
self.test = test
self.count = 0
def sideEffect(self, filename):
if self.count == 0:
self.test.assertEqual('file1.fastq', filename)
self.count += 1
... |
renesugar/arrow | python/pyarrow/tests/test_array.py | Python | apache-2.0 | 58,523 | 0 | # -*- coding: utf-8 -*-
# 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
# "... | pe='str')
assert np_a | rr.tolist() == ['0', '1', '2', '3']
# If PyArrow array has null values, numpy type will be changed as needed
# to support nulls.
arr = pa.array([0, 1, 2, None])
assert arr.type == pa.int64()
np_arr = np.asarray(arr)
elements = np_arr.tolist()
assert elements[:3] == [0., 1., 2.]
assert n... |
kdeloach/model-my-watershed | deployment/cfn/utils/constants.py | Python | apache-2.0 | 568 | 0 | EC2_INSTANCE_TYPES = [
't2.micro',
't2.small',
't2.medium',
't2.large',
'r4.large'
]
RDS_INSTANCE_TYPES = [
'db.t2.micro',
'db.t2.small',
'db.t2.medium',
'db.t2.large'
]
ELASTICACHE_INSTANCE_TYPES = [
'cache.m1.small'
]
ALLOW_ALL_CIDR = '0.0.0.0/0'
VPC_CIDR = '10.0.0.0/16'
GR... | HTTPS = 443
KIBANA = 5601
POSTGRESQL = 5432
REDIS = 6379
RELP = 20514
SSH = 22
STATSITE = 8125
AMAZON_S3_HOSTED_ZONE_ID = 'Z3AQBSTGFYJSTF'
AMAZON_S3_WE | BSITE_DOMAIN = 's3-website-us-east-1.amazonaws.com'
|
katyast/Se-Python-17-Stoliarova | pages/create_film_page.py | Python | apache-2.0 | 347 | 0.002882 | from pages.internal_page import InternalPage
fr | om pages.blocks.film_form import FilmForm
from selenium.webdriver.support.select import Select
class CreateFilmPage(InternalPage):
def __init__(self, driver, base_url):
super(CreateFilmPage, self).__init__(driver, base_url)
self.film | _form = FilmForm(self.driver, self.base_url) |
dimagi/commcare-hq | corehq/apps/linked_domain/migrations/0011_auto_20200728_2316.py | Python | bsd-3-clause | 804 | 0.001244 | # Generated by Django 2.2.13 on 2020-07-28 23:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
| ('linked_domain', '0010_auto_20200622_0156'),
]
operations = [
migrations.AlterField(
model_name='domainlinkhistory',
name='model',
field=models.CharField(choices=[('app', ' | Application'), ('custom_user_data', 'Custom User Data Fields'), ('custom_product_data', 'Custom Product Data Fields'), ('custom_location_data', 'Custom Location Data Fields'), ('roles', 'User Roles'), ('toggles', 'Feature Flags and Previews'), ('fixture', 'Lookup Table'), ('case_search_data', 'Case Search Settings'), (... |
dilipbobby/DataScience | Python3/Level-1/allprimes.py | Python | apache-2.0 | 457 | 0.04814 |
#print | 's all prime numbers in a given range limit
_author__ = "Dilipbobby"
#Take the input from the user:
lower = int(input("Enter lower range: "))
upper = int(input("Enter upper range: "))
#condtion to print all prime numbers that are in btw given number limits
for num in range(lower,upper + 1):
if num > 1... | |
e2jk/nautilus-image-manipulator | nautilus_image_manipulator/NautilusImageManipulatorDialog.py | Python | gpl-3.0 | 26,709 | 0.002621 | # -*- coding: utf-8 -*-
### BEGIN LICENSE
# Copyright (C) 2010-2013 Emilien Klein <emilien _AT_ klein _DOT_ st>
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program ... | else:
# There is only one image, send that image alone (don't zip the file)
self.upload_file(im, im.newFiles[0])
else:
# The user doesn't want to send the images, we're done!
self.destroy()
def on_packing_done(self, im, zipfile):
"""... | l the images have been packed together."""
self.upload_file(im, zipfile)
def upload_file(self, im, fileToUpload):
"""Uploads a file to a website."""
# Import the module that takes care of uploading to the selected website
import_string = "from upload.z_%s import UploadSite" % \
... |
ruchee/vimrc | vimfiles/bundle/vim-python/submodules/toml/toml/__init__.py | Python | mit | 723 | 0 | """Python module which parses and emits TOML.
Released under the MIT license.
| """
from toml import encoder
from toml import decoder
__version__ = "0.10.2"
_spec_ = "0.5.0"
load = decoder.load
loads = decoder.loads
TomlDecoder = decoder.TomlDecoder
TomlDecodeError = decoder.TomlDecodeError
TomlPreserveCommentDecoder = decoder.TomlPreserveCo | mmentDecoder
dump = encoder.dump
dumps = encoder.dumps
TomlEncoder = encoder.TomlEncoder
TomlArraySeparatorEncoder = encoder.TomlArraySeparatorEncoder
TomlPreserveInlineDictEncoder = encoder.TomlPreserveInlineDictEncoder
TomlNumpyEncoder = encoder.TomlNumpyEncoder
TomlPreserveCommentEncoder = encoder.TomlPreserveComme... |
mrcl/HakketyYaks | app/grant_hunter_vars.py | Python | mit | 2,621 | 0.058375 |
def calc_approve( pool, area, age, group, amount, percent ):
debug=False
print("calculating results")
approve=0.65
decline=0.35
approve *= list_pool[pool][0]
decline *= list_pool[pool][1]
approve *= list_area[area][0]
decline *= list_area[area][1]
approve *= list_age[age][0]
decline *= list_a | ge[age][1]
approve *= list_group[group][0]
decline *= list_group[group][1]
approve *= list_amount[amount][0]
decline *= list_amount[amount][1]
approve *= list_percent[percent][0]
decline *= list_percent[percent][1]
result="Your grant application is likely to be "
if (approve > decline):
result+="approved.... | result
list_pool={
'Creative Communities Local Funding Scheme':(0.126,0.186),
'Social And Recreation Fund':(0.114,0.164),
'Betty Campbell Accommodation Assistance':(0.066,0.024),
'Wellington Venue Subsidy':(0.063,0.028),
'Built Heritage Incentive Fund':(0.060,0.029),
'C H Izard Bequest':(0... |
indico/indico | indico/modules/events/reminders/util.py | Python | mit | 1,052 | 0.003802 | # This file is part of Indico.
# Copyright (C) 2002 - 2022 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE fil | e for more details.
from indico.modules.events.models.events import EventType |
from indico.web.flask.templating import get_template_module
def make_reminder_email(event, with_agenda, with_description, note):
"""Return the template module for the reminder email.
:param event: The event
:param with_agenda: If the event's agenda should be included
:param note: A custom message to... |
JakeWimberley/Weathredds | tracker/urls.py | Python | gpl-3.0 | 2,582 | 0.003486 | """
Copyright 2016 Jacob C. Wimberley.
This file is part of Weathredds.
Weathredds 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... | url(r'async/togglePin$', views.asyncTogglePin, name='togglePin'),
url(r'async/toggleTag$', views.asyncToggleTag, name='toggleTag'),
url(r'async/toggleFrozen$', views.asyncToggleFrozen, name='toggleFrozen'),
url(r'async/threadsForPeriod$', views.asyncThreadsForPeriod, name='threadsForPeriod'),
url | (r'async/eventsAtTime$', views.asyncEventsAtTime, name='eventsAtTime'),
url(r'async/associateEventsWithThread$', views.asyncAssociateEventsWithThread, name='associateEventsWithThread'),
]
|
sinabahram/GrowTheTribe | GrowTheTribe/apps/talks/forms.py | Python | gpl-3.0 | 489 | 0.002045 | from django.forms import ModelForm
from django.forms.models import inlineformset_factory
from .models import Talk, Appearance, Resource
class Tal | kForm(ModelForm):
class Meta:
model = Talk
class AppearanceForm(ModelForm):
class Meta:
model = Appearance
class ResourceForm(ModelForm):
class Meta:
model = Resource
ResourceFormSet = inlineformset_fac | tory(Talk, Resource, extra=1)
AppearanceFormSet = inlineformset_factory(Talk, Appearance, extra=1)
|
fabiomontefuscolo/reciclapy | objects.py | Python | gpl-2.0 | 2,200 | 0.004545 | # -*- coding: utf-8 -*-
# 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 distributed in the hope tha... | details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
import pyga | me, random
VEL = 25
class Object(pygame.sprite.Sprite):
def __init__(self):
super(Object, self).__init__()
self.shooted = False
self.position = None
def shoot(self):
self.shooted = True
def update(self):
if self.shooted:
self.rect.center = (self.rect.c... |
twuilliam/pyMuse | pymuse/viz.py | Python | mit | 6,204 | 0.003385 | __author__ = 'benjamindeleener'
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
from datetime import datetime, timedelta
from numpy import linspace
def timeTicks(x, pos):
d = timedelta(milliseconds=x)
return str(d)
class MuseViewer(object):
def __init__(self, acquisition_freq, signal... | er(format | ter)
self.ax4.xaxis.set_major_formatter(formatter)
plt.ion()
def show(self):
plt.show(block=False)
self.refresh()
def refresh(self):
time_now = datetime.now()
if (time_now - self.last_refresh).total_seconds() > self.refresh_freq:
self.last_refre... |
griimick/feature-mlsite | app/twitter/views.py | Python | mit | 1,537 | 0.006506 | from flask import Blueprint, request, render_template
from ..load import processing_results, api
import string
import tweepy
twitter_mod = Blueprint('twitter', __name__, template_folder='templates', static_folder='static')
ascii_chars = set(string.printable)
ascii_chars.remove(' ')
ascii_chars.add('...')
def takeout... | rn render_template('projects/twitter.html', message='Please | enter a valid topic')
text = []
for tweet in tweepy.Cursor(api.search, topic, lang='hi').items(50):
temp = ''.join(takeout_non_ascii(tweet.text))
if not len(temp) in range(3):
text.append(temp)
if len(text) == 0:
ret... |
vsajip/django | tests/regressiontests/queries/tests.py | Python | bsd-3-clause | 87,329 | 0.002714 | from __future__ import absolute_import,unicode_literals
import datetime
from operator import attrgetter
import pickle
import sys
from django.conf import settings
from django.core.exceptions import FieldError
from django.db import DatabaseError, connection, connections, DEFAULT_DB_ALIAS
from django.db.models import Co... | ),
['<Item: one>']
)
self.assertQue | rysetEqual(
Item.objects.filter(tags__in=[self.t1, self.t2]).distinct().order_by('name'),
['<Item: one>', '<Item: two>']
)
self.assertQuerysetEqual(
Item.objects.filter(tags__in=[self.t1, self.t2]).filter(tags=self.t3),
['<Item: two>']
)
#... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.