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 |
|---|---|---|---|---|---|---|---|---|
geometalab/G4SE-Compass | compass-api/G4SE/api/migrations/0010_NO_WAY_BACK_drop_obsolete_tables_20161012_0747.py | Python | mit | 1,451 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-10-12 07:47
from __future__ import unicode_literals
from django.db import migrations
drop_harvested_records = [
"DROP TRIGGER harvested_tsvectorupdate_de ON harvested_r | ecords;",
"DROP TRIGGER harvested_tsvectorupdate_en ON harvested_records;",
"DROP TRIGGER harvested_tsvectorupdate_fr ON harvested_records",
"DROP TABLE harvested_records;",
]
drop_records = [
"DROP TRIGGER tsvectorupdate_en ON records;",
"DROP TRIGGER tsvectorupdate_de ON records;",
"DROP TRI... | trigger_de();",
"DROP FUNCTION records_trigger_en();",
"DROP FUNCTION records_trigger_fr();",
"DROP FUNCTION harvested_records_trigger_de();",
"DROP FUNCTION harvested_records_trigger_en();",
"DROP FUNCTION harvested_records_trigger_fr();",
]
class Migration(migrations.Migration):
dependenci... |
kelle/astropy | astropy/coordinates/tests/test_funcs.py | Python | bsd-3-clause | 2,515 | 0.001194 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Tests for miscellaneous functionality in the `funcs` module
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import pytest
import numpy as np
from numpy import t... | thern_winter_solstice = Time('2010-12-21')
equinox_1 = Time('2010-3-21')
equinox_2 = Time('2010-9-21')
gcrs1 = get_sun(equinox_1)
assert np.abs(gcrs1.dec.deg) < 1
gcrs2 = get_sun(Time([northern_summer_solstice, equinox_2, northern_winter_solstice]))
assert np.all(np.abs(gcrs2.dec - [23. | 5, 0, -23.5]*u.deg) < 1*u.deg)
def test_concatenate():
from .. import FK5, SkyCoord
from ..funcs import concatenate
fk5 = FK5(1*u.deg, 2*u.deg)
sc = SkyCoord(3*u.deg, 4*u.deg, frame='fk5')
res = concatenate([fk5, sc])
np.testing.assert_allclose(res.ra, [1, 3]*u.deg)
np.testing.assert_all... |
obi-two/Rebelion | data/scripts/templates/object/tangible/mission/quest_item/shared_rakir_banai_q2_needed.py | Python | mit | 477 | 0.046122 | #### NOTICE: T | HIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/mission/quest_item/shared_rakir_banai_q2_needed.iff"
result.attribute_template_id... | CATIONS ####
return result |
vrenkens/Nabu-asr | nabu/processing/tfwriters/alignment_writer.py | Python | mit | 651 | 0.003072 | '''@file alignment_writer.py
contains the AlignmentWriter | class'''
import numpy as np
import tensorflow as tf
import tfwriter
class AlignmentWriter(tfwriter.TfWriter):
'''a TfWriter to write kaldi alignments'''
def _get_example(self, data):
'''write data to a file
Args:
data: the data to be written'''
data_feature = tf.train.F... | Example(features=tf.train.Features(feature={
'data': data_feature}))
return example
|
DjangoAdminHackers/ixxy-admin-utils | ixxy_admin_utils/admin_mixins.py | Python | mit | 6,862 | 0.005683 | from django.http import HttpResponseRedirect
from django.contrib.contenttypes.models import ContentType
from django.utils.translation import ugettext as _
from .custom_fields import (
BooleanTimeStampField,
BooleanTimeStampFormField,
BooleanTimeStampWidget,
)
try:
from dal_select2.widgets import ModelS... | ter '_redirect' and redirect to that on save"""
def response_post_save_change(self, request, obj):
if '_redirect' in request.GET:
return HttpResponseRedirect(request.GET['_redirect'])
else:
return super(RedirectableAdmin, self).response_post_save_change(request, obj)
... | return HttpResponseRedirect(request.GET['_redirect'])
else:
return super(RedirectableAdmin, self).response_post_save_add(request, obj)
def delete_view(self, request, object_id, extra_context=None):
response = super(RedirectableAdmin, self).delete_view(request, object_id, extra_c... |
rajarahulray/iDetector | tests_and_ References/table_view_text_box.py | Python | mit | 1,160 | 0.010345 | import tkinter as tk
class ExampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
t = SimpleTable(self, 10,2)
t.pack(side="top", fill="x")
t.set(0,0,"Hello, world")
class SimpleTable(tk.Frame):
def __init__(self, parent, rows=10, columns=2):
# use black background ... | dgets = []
for row in range(rows):
current_row = []
for column in range(columns):
label = tk.Label(self, text="%s/%s" % (row, column),
borderwidth=0, width=10, height = 10)
label.grid(row=row, column=column, sti | cky="nsew", padx=1, pady=1)
current_row.append(label)
self._widgets.append(current_row)
for column in range(columns):
self.grid_columnconfigure(column, weight=1)
def set(self, row, column, value):
widget = self._widgets[row][column]
widget.configure... |
dgbc/django-arctic | example/example/settings.py | Python | mit | 3,469 | 0.000288 | """
Django settings for example project.
Generated by 'django-admin startproject' using Django 1.9.4.
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
f... | ARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csr | f.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'example.urls'
TEMPLATE... |
tianz/MyInventory | manage.py | Python | mit | 254 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault | ("DJANGO_SETTINGS_MODULE", "myinventory.settings")
from django.core.management im | port execute_from_command_line
execute_from_command_line(sys.argv)
|
jcartledge/sublime-worksheet | repl/pexpect.py | Python | mit | 79,154 | 0.004321 | """Pexpect is a Python module for spawning child applications and controlling
them automatically. Pexpect can be used for automating interactive applications
such as ssh, ftp, passwd, telnet, etc. It can be used to a automate setup
scripts for duplicating software package installations on different servers. It
can be u... | The run() function can often | be used instead of creating a spawn instance.
For example, the following code uses spawn::
from pexpect import *
child = spawn('scp foo myname@host.example.com:.')
child.expect ('(?i)password')
child.sendline (mypassword)
The previous code can be replace with the following::
... |
nickgaya/python2 | python2/client/client.py | Python | mit | 2,862 | 0 | # TODO: Logging
import contextlib
import json
import logging
import weakref
from python2.client.codec import ClientCodec
from python2.client.exceptions import Py2Error
from python2.client.object import Py2Object
SPECIAL_EXCEPTION_TYPES = {t.__name__: t for t in (StopIteration, TypeError)}
logger = logging.getLogge... | ta['result'] == 'raise':
exception_type = Py2Error
if data['types']:
# Dynamically generate Py2Error subclass with relevant base
# types. This is a hack to allow iterators to work correctly.
bases = [Py2Error]
bases.extend(SPECIAL_... | exception_type = type('Py2Error~', tuple(bases), {})
raise exception_type(
self.codec.decode(data['message']),
exception=self.codec.decode(data['exception'])
)
else:
raise Exception("Invalid server response: result={!r}".format(
... |
scailer/picarchive | apps/notice/models.py | Python | mit | 582 | 0 | # -*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Notice(models.Model):
text = models.TextField(_(u'Заметка'))
user = models.ForeignKey('account.User', verbose_name=_(u'Пользователь'))
picture = models.ForeignKey('picture.Picture', verbose_... | auto_now_add=True)
class Meta:
verbose_name = _(u'За | метка')
verbose_name_plural = _(u'Заметки')
|
truemped/dopplr | dopplr/solr/__init__.py | Python | apache-2.0 | 707 | 0 | # vim: set fileencoding=utf-8 :
#
# Copyright (c) 2012 Retresco GmbH
# Copyright (c) 2012 Daniel Truemper <truemped at googlemail.com>
#
# 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
#
# ht... | License for the specific language governing permissions and
# limitations under the License.
#
#
"""
This is d | opplr.
"""
|
kyvinh/home-assistant | homeassistant/components/history.py | Python | apache-2.0 | 12,100 | 0 | """
Provide pre-made queries on top of the recorder component.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/history/
"""
import asyncio
from collections import defaultdict
from datetime import timedelta
from itertools import groupby
import logging
imp... | default=[]):
vol.All(cv.ensure_list, [cv.string])
}),
CONF_INCLUDE: vol.Schema({
vol.Optional(CONF_ENTITIES, default=[]): cv.entity_ids,
vol.Optional(CONF_DOMAINS, default=[]):
vol.All(cv.ensure_list, [cv.string])
})
}),
}, extra=vol.AL... | ostat', 'climate')
IGNORE_DOMAINS = ('zone', 'scene',)
def last_5_states(entity_id):
"""Return the last 5 states for entity_id."""
entity_id = entity_id.lower()
states = recorder.get_model('States')
return recorder.execute(
recorder.query('States').filter(
(states.entity_id == ent... |
jschavem/facial-expression-classification | source/classification/cv_subjects_multithreaded_pca.py | Python | mit | 5,651 | 0.003185 | from sklearn.metrics import confusion_matrix
from sklearn.metrics import f1_score
from sklearn.metrics import accuracy_score
from sklearn.naive_bayes import GaussianNB
from threading import Thread
import time
from Queue import Queue, Empty
from lib.in_subject_cross_validation import *
import lib.in_subject_cross_valid... | ), average_f1,
accuracy)
def main():
dataset = 'koelstra-approach'
class_id = 0
ground_truth_variable_count = 3
attr_count = attribute_counts[dataset][class_id]
# attr_count = None
# Load our dataset into memory |
Xs, ys = libcv._load_full_dataset(dataset, class_id, ground_truth_variable_count)
# Perform cross-validation on the dataset, using RFE to achieve the target attr_count
actual, predicted = cross_validate_combined_dataset(Xs, ys, attr_count, threaded=False)
print_report(actual, attr_count, class_id, da... |
fsantini/rasPyCNCController | gcode/GCodeLoader.py | Python | gpl-3.0 | 2,216 | 0.002256 | # rasPyCNCController
# Copyright 2016 Francesco Santini <francesco.santini@gmail.com>
#
# This file is part of rasPyCNCController.
#
# rasPyCNCController 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 ... | analyzer.fastf = self.g0_feed
try:
with open(self.file) as f:
for line in f:
analyzer.Ana | lyze(line)
self.gcode.append(line)
self.times.append(analyzer.getTravelTime()*60) # time returned is in minutes: convert to seconds
except:
self.busy = False
e = sys.exc_info()[0]
self.load_error.emit("%s" % e)
return
... |
bgris/ODL_bgris | doc/gitwash_dumper.py | Python | gpl-3.0 | 8,036 | 0.000249 | #!/usr/bin/env python
''' Checkout gitwash repo into directory and do search replace on name '''
from __future__ import (absolute_import, division, print_function)
import os
from os.path import join as pjoin
import shutil
import sys
import re
import glob
import fnmatch
import tempfile
from subprocess import call
from... | SUFFIX")
parser.add_option("--project-url", dest="project_url",
help="URL for projec | t web pages",
default=None,
metavar="PROJECT_URL")
parser.add_option("--project-ml-url", dest="project_ml_url",
help="URL for project mailing list",
default=None,
metavar="PROJECT_ML_URL")
(options, arg... |
socketubs/pyhn | pyhn/poller.py | Python | mit | 568 | 0 | # -*- coding: utf-8 -*-
from time import sleep
from threading import Thread
class Poller(Thread):
def __init__(self, gui, delay=5):
if delay < 1:
delay = 1
self.gui = gui
self.delay = delay |
self.is_running = True
self.count | er = 0
super(Poller, self).__init__()
def run(self):
while self.is_running:
sleep(0.1)
self.counter += 0.1
if self.counter >= self.delay * 60:
self.gui.async_refresher(force=True)
self.counter = 0
|
afaheem88/tempest_neutron | tempest/api/image/v2/test_images_tags_negative.py | Python | apache-2.0 | 1,715 | 0 | # All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
#... | mpest.common.utils import data_utils
from tempest import exceptions
from tempest import test
class ImagesTagsNegativeTest(ba | se.BaseV2ImageTest):
@test.attr(type=['negative', 'gate'])
def test_update_tags_for_non_existing_image(self):
# Update tag with non existing image.
tag = data_utils.rand_name('tag-')
non_exist_image = str(uuid.uuid4())
self.assertRaises(exceptions.NotFound, self.client.add_image... |
sivakuna-aap/superdesk-core | superdesk/io/ingest_provider_model.py | Python | agpl-3.0 | 9,799 | 0.002857 | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import loggi... | .info("Created Ingest Channel. Data:{}".format(docs))
def on_update(self, updates, original):
if updates.get('content_expiry') == 0:
updates['cont | ent_expiry'] = app.config['INGEST_EXPIRY_MINUTES']
if 'is_closed' in updates and original.get('is_closed', False) != updates.get('is_closed'):
self._set_provider_status(updates, updates.get('last_closed', {}).get('message', ''))
def on_updated(self, updates, original):
do_notification =... |
agiliq/django-graphos | graphos/tests.py | Python | bsd-2-clause | 38,867 | 0.002135 | from django.test import TestCase
from pymongo.errors import CollectionInvalid
from .sources.base import BaseDataSource
from .sources.simple import SimpleDataSource
from .sources.csv_file import CSVDataSource
from .sources.model import ModelDataSource
from .sources.mongo import MongoDBDataSource
from .renderers impor... | template"))
self.assertRaises(GraphosException, chart.get_html_template)
self.a | ssertTrue(hasattr(chart, "get_js_template"))
self.assertRaises(GraphosException, chart.get_js_template)
self.assertTrue(hasattr(chart, "get_html_id"))
self.assertTrue(self.html_id, chart.get_html_id())
self.assertTrue(hasattr(chart, "as_html"))
self.assertRaises(GraphosException,... |
dejlek/pulsar | pulsar/apps/rpc/jsonrpc.py | Python | bsd-3-clause | 11,409 | 0 | import sys
import json
import logging
import asyncio
from collections import namedtuple
from pulsar import AsyncObject, as_coroutine, new_event_loop, ensure_future
from pulsar.utils.string import gen_unique_id
from pulsar.utils.tools import checkarity
from pulsar.apps.wsgi import Json
from pulsar.apps.http import Http... | rror) and proc:
msg = checkarity(proc, args, kwargs, discount=1)
else:
msg = None
rpc_id = data.get('id') if isinstance(data, dict) else None
res, status = self._get_error_and_status(
result, msg=msg, | rpc_id=rpc_id, exc_info=exc_info)
else:
res = {
'id': data.get('id'),
'jsonrpc': self.version,
'result': result
}
status = 200
return res, status
def _get_error_and_status(self, exc, msg=None, rpc_id=None,
... |
patricklaw/pants | src/python/pants/backend/python/goals/repl.py | Python | apache-2.0 | 5,683 | 0.002815 | # Copyright 2020 Pants proj | ect contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE | ).
import os
from pants.backend.python.subsystems.ipython import IPython
from pants.backend.python.util_rules.local_dists import LocalDistsPex, LocalDistsPexRequest
from pants.backend.python.util_rules.pex import Pex, PexRequest
from pants.backend.python.util_rules.pex_environment import PexEnvironment
from pants.back... |
naturalness/partycrasher | lp/bucketizer.py | Python | gpl-3.0 | 4,063 | 0.004922 | #!/usr/bin/env python
# Copyright 2015 Joshua Charles Campbell
# 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.
# ... | 110-1301, USA.
import MySQLdb
from sys import argv
import re, os, shutil, errno
def f1(seq):
# not order preserving
set = {}
map(set.__setitem__, seq, [])
return set.keys()
def main():
db = MySQLdb.connect("localhost", "bicho", argv[1], "bicho")
bugkets = dict()
bugs_to_bugkets = dict()
... | new_bugket = True
while new_bugket:
new_bugket = False
cursor = db.cursor()
cursor.execute("SELECT lp_id, duplicate_of, duplicates_list FROM issues_ext_launchpad NATURAL JOIN issues;")
for row in cursor:
#print repr(row)
lp_ids = [row[0]]
if ro... |
VolosHack/Python-presentation | workshop/list_comprehensions.py | Python | mit | 1,322 | 0.003782 | # List-Set-Dict comprehension exercises
# - - - - - - - - - - - - - - - - -
# Write a comprehension whose values is the first 10 powers of 2
def bin_power:
# write code here #
return
# Write a list comprehension whose value is the cartesian product
# of two lists A , B.
# Example: A = [1,2,3], B = [4,5,6]:
# ... | ['A','B','C'], B = [ 5.0, 7.5, 3.14 ]
# returns: { 'A':5.0, 'B':7.5, 'C':3.14 }
def zip_lists(A, B):
# write code here #
return
# Write a comprehension whose values is the set consisting
# of | the odd numbers up to 100
def odd_list:
# write code here #
return
# Write a function which takes a list of positive numbers and returns
# a list that consist of: twice of that number if that number is divisible by 3
# square of that number if that number is not.
# Example: A = [3, 2,... |
nicolasfauchereau/paleopy | paleopy/plotting/vector_plot.py | Python | mit | 1,697 | 0.0165 | import numpy as np
from numpy import ma
from matplotlib import pyplot as plt
from mpl_toolkits.basemap import Basemap as bm
from mpl_toolkits.basemap import addcyclic
import palettable
class vector_plot:
def __init__(self, ucompos, vcompos):
self.ucompos = ucompos
self.vcompos = vcompos
se... | palettable.colorbrewer.sequential.Oranges_9.mpl_colormap
f, ax = plt.subplots(figsize=(10,6))
m.ax = ax
x, y = m(lons, lats)
im = m.pcolormesh(lons, lats, self.windspeed.data, cmap=cmap)
cb = m.colorbar(im)
cb.set_label('wind speed (m/s)', fontsize=14)
Q = ... | e', scale=scale)
l,b,w,h = ax.get_position().bounds
qk = plt.quiverkey(Q, l+w-0.1, b-0.03, 5, "5 m/s", labelpos='E', fontproperties={'size':14}, coordinates='figure')
m.drawcoastlines()
return f
|
MaterialsDiscovery/PyChemia | pychemia/code/vasp/vaspxml.py | Python | mit | 19,297 | 0.00228 | """
Created on April 25 2020
@author: Pedram Tavadze
"""
import os
import numpy as np
from .xml_output import parse_vasprun
from .incar import VaspInput
from ..codes import CodeOutput
from ...core import Structure
from ...visual import DensityOfStates
from ...crystal.kpoints import KPoints
class VaspXML(CodeOutput):
... | ne
# self.stress = None
#self.array_sizes = {}
self.data = self.read()
if self.has_diverged:
return
self.bands = self._get_bands()
self.bands_projected = self._get_bands_projected()
def read(self):
return parse_vasprun(self.filename)
def _g... | al']['dos']
['total']['array']['data'].keys())
energies = np.array(
self.data['general']['dos']['total']['array']['data'][spins[0]])[:, 0]
dos_total = {'energies': energies}
for ispin in spins:
dos_total[self.spins_dict[ispin]] = np.array(
... |
odoo-jarsa/addons-jarsa | connector_cva/tests/test_product_template.py | Python | agpl-3.0 | 1,627 | 0 | # -*- coding: utf-8 -*-
# © <2016> <Jarsa Sistemas, S.A. de C.V.>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp.tests.common import TransactionCase
from mock import MagicMock
from lxml import etree
import requests
class TestProductTemplate(TransactionCase):
"""
This will t... | _context(
{'active_ids': product_tem.ids})
product.update_price_multi()
product_template = self.cva.create_product(etree.XML(self.xml)[0])
cva = self.cva.create({
'name': '40762',
'main_location': self.env.ref('connector_cva.loc_torreon').id})
cva.exe... | cva.connect_cva.return_value = etree.XML(self.xml)
product = product_template.with_context(
{'active_ids': product_template.ids})
product.write({
'standard_price': 0.00,
})
product.update_price_multi()
self.assertEqual(product.standard_price, 114.94,
... |
chengzhoukun/LeetCode | 112. Path Sum/Path Sum.py | Python | lgpl-3.0 | 599 | 0.001669 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param {TreeNode} root
# @param {integer} sum
# @return {boolean}
def hasPathSum(self, root, sum):
if root is None... | root.left is None and root. | right is None:
return True
else:
return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(
root.right, sum - root.val
)
|
kiriappeee/reply-later | src/core/tests/TestMessageSender.py | Python | mit | 14,145 | 0.011453 | import unittest
from unittest.mock import Mock, patch
import copy
from datetime import timezone, timedelta, datetime
from ..reply.Reply import Reply
from ..reply import ReplyCRUD
from ..user.User import User
from ..messager import TweetAdapter, MessageBreaker, MessageSender
from ..data import DataConfig
from ..schedule... | eetAdapter, 'sendReply')
def test_messageIsSentCorrectlyWhenUnder140Chars(self, sendReplyPatch, usernameMethod, urlLengthPatch):
sendReplyPatch.side_effect = [1234]
urlLengthPatch.return_value = (23,23)
usernameMethod.return_value = "example"
d = datetime.now(tz = timezone(timedelta(... | 292, replyId = 1)
mockReplyDataStrategy = Mock()
mockReplyDataStrategyAttrs = {"getReplyByReplyId.side_effect": [copy.deepcopy(replyToSend), |
lo0ol/Ultimaker-Cura | plugins/LayerView/__init__.py | Python | agpl-3.0 | 997 | 0.007021 | # Copyright (c) 2015 Ultimak | er B.V.
# Cura is released under the terms of the AGPLv3 or higher.
from . import LayerView, LayerViewProxy
from PyQt5.QtQml import qmlRegisterType, qmlRegisterSingletonType
from UM.i18n import i18nCatalog
catalo | g = i18nCatalog("cura")
def getMetaData():
return {
"plugin": {
"name": "Layer View",
"author": "Ultimaker",
"version": "1.0",
"description": catalog.i18nc("Layer View plugin description", "Provides the Layer view."),
"api": 2
},
"... |
robertwb/incubator-beam | sdks/python/apache_beam/testing/load_tests/load_test_metrics_utils.py | Python | apache-2.0 | 19,588 | 0.006586 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | s:
list of :class:`DistributionMetric` objects
"""
submit_timestamp = time.time()
dist_types = ['count', 'max', 'min', 'sum']
distribution_dicts = []
for dist_type in dist_types:
try:
distribution_dicts.append(
get_distribution_dict(dist_type, submit_timestamp, dist, metric_id))
ex... | , submit_timestamp, dist, metric_id):
"""Function creates :class:`DistributionMetric`
Args:
metric_type(str): type of value from distribution metric which will
be saved (ex. max, min, mean, sum)
submit_timestamp: timestamp when metric is saved
dist(object) distribution object from pipeline result... |
svanschalkwyk/datafari | windows/python/Lib/test/test_popen2.py | Python | apache-2.0 | 4,315 | 0.002086 | """Test script for popen2.py"""
import warnings
warnings.filterwarnings("ignore", ".*popen2 module is deprecated.*",
DeprecationWarning)
warnings.filterwarnings("ignore", "os\.popen. is deprecated.*",
DeprecationWarning)
import os
import sys
import unittest
import popen... | # Locks get messed up or something. Generally we're supposed
# to avoid mixing "posix" fork & exec with native threads, and
# they may be right about that after all.
raise unittest.SkipTest("popen2() doesn't work on " + sys.platform)
# if we don't have os.popen, check that
# we have os.fork. if no... | om os import fork
del fork
class Popen2Test(unittest.TestCase):
cmd = "cat"
if os.name == "nt":
cmd = "more"
teststr = "ab cd\n"
# "more" doesn't act the same way across Windows flavors,
# sometimes adding an extra newline at the start or the
# end. So we strip whitespace off both ... |
mortonjt/micronota | micronota/bfillings/_base.py | Python | bsd-3-clause | 5,337 | 0 | # ----------------------------------------------------------------------------
# Copyright (c) 2015--, micronota development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# ---------------------------------------------... | _init__(self, dat, out_dir, tmp_dir=None):
self.dat = dat
self.out_dir = out_dir
# create dir if not exist
makedirs(self.out_dir, exist_ok=True)
if tmp_dir is None:
self.tmp_dir = mkdtemp(prefix='tmp', dir=out_dir)
else:
self.tmp_dir = tmp_dir
... | ll__(self, input, **kwargs) -> dict:
'''Identify features for the input.
Parameters
----------
input : ``skbio.Sequence`` or sequence file.
Yield
-----
dict passable to ``skbio.metadata.IntervalMetadata``
'''
if isinstance(input, Sequence):
... |
fkorotkov/pants | tests/python/pants_test/bin/test_loader_integration.py | Python | apache-2.0 | 1,537 | 0.004554 | # coding=utf-8
# Copyright 2016 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants_test.pant... | s_exe:test'}
)
self.assert_success(pants_run)
self.assertIn('T E S T', pants_run.stdout_data)
def test_alternate_entrypoint_bad(self):
pants_run = self.run_pants(command=['help'], extra_env={'PANTS_ENTRYPOINT': 'badness'})
self.assert_failure(pants_run)
self.assertIn('entrypoint must be', pan... | command=['help'],
extra_env={'PANTS_ENTRYPOINT': 'pants.bin.pants_exe:TEST_STR'}
)
self.assert_failure(pants_run)
self.assertIn('TEST_STR', pants_run.stderr_data)
self.assertIn('not callable', pants_run.stderr_data)
|
maning/inasafe | realtime/test_shake_event.py | Python | gpl-3.0 | 24,765 | 0.000202 | # -*- coding: utf-8 -*-
"""
InaSAFE Disaster risk assessment tool developed by AusAid and World Bank
- **Shake Event Test Cases.**
Contact : ole.moller.nielsen@gmail.com
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as publishe... | if not myFlag:
myMessage = 'Expected %s features, got %s' % (theCount, myCount)
myDataSource.ReleaseResultSet(myLayer)
myDataSource.Destroy()
return myFlag, myMessage
def testEventToContours(self):
"""Check we can extract contours from the event"""
myShakeId =... | ours(theForceFlag=True,
theAlgorithm='invdist')
assert self.checkFeatureCount(myPath, 16)
assert os.path.exists(myPath)
myExpectedQml = myPath.replace('shp', 'qml')
myMessage = '%s not found' % myExpectedQml
assert os.path.exists(my... |
cjhak/b2share | invenio/modules/records/views.py | Python | gpl-2.0 | 13,449 | 0.000446 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2012, 2013, 2014, 2015 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 (at your... | return format_record(recid, of, user_info=user_info, *args,
**kwargs)
@register_template_context_processor
def record_context():
from invenio.modules.comments.api import get_mini_reviews
from invenio.legacy.bibdocfile.api import BibRecDocs
... | for f in all_files if f.is_restricted(current_user)[0] == 0]
has_private_files = len(files) < len(all_files)
return dict(recid=recid,
record=record,
tabs=tabs,
title=title,
get_mini_reviews=get_mini_... |
charismab45515t/dtbs-carrent | customer_auto_email/__openerp__.py | Python | gpl-2.0 | 624 | 0.016026 | # -*- coding: utf-8 -*-
{
"name" : "Automatical email to customer",
"version" : "1.0",
"author" : "DTBS",
"description": """
| Sends automatic when customer created
""",
"website" : "http://dtbsindo.web.id",
"category" : "",
# 'depends': ['base','csmart_base','sale_stock'],
' | depends': ['base','csmart_base','sale'],
"data" : [
'views/email_template_customer_auto.xml',
'views/configuration.xml',
'views/configuration_data.xml',
'views/menu.xml'
],
'js': [],
'css': [],
'qweb': [],
"active": False,
"installable": True,
} |
rnixx/kivy | kivy/uix/pagelayout.py | Python | mit | 7,321 | 0 | """
PageLayout
==========
.. image:: images/pagelayout.gif
:align: right
The :class:`PageLayout` class is used to create a simple multi-page
layout, in a way that allows easy flipping from one page to another using
borders.
:class:`PageLayout` does not currently honor the
:attr:`~kivy.uix.widget.Widget.size_hint... | # there's already a left margin
x = right - half_border
else:
x = right
c.height = h
c.width = width
Animation(
x=x,
y=y_parent,
**self.anim_kwargs).start(c)
def on_touch_down(self... | ren
):
return
page = self.children[-self.page - 1]
if self.x <= touch.x < page.x:
touch.ud['page'] = 'previous'
touch.grab(self)
return True
elif page.right <= touch.x < self.right:
touch.ud['page'] = 'next'
touch.g... |
os-cloud-storage/openstack-workload-disaster-recovery | dragon/workload_policy/actions/plugins/instance_image_action.py | Python | apache-2.0 | 6,714 | 0.000149 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
'''-------------------------------------------------------------------------
Copyright IBM Corp. 2015, 2015 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 obta... | e_gen):
instance = InstanceResource(self._image_id, self._name, resource_id=self._resource_id)
template_gen.add_instance(instance)
def failover(self, context, resource_id, resource_data, container_name):
return self._import_from_swift(context, resource_id,
... | er_name):
LOG.debug("resource %s data %s container %s" %
(resource_id, resource_data, container_name))
swift_client = self.clients.swift()
data_chunks = resource_data["chunks"]
image_id = resource_data["image_id"]
image_response_data = StringIO.StringIO()
... |
monk-ee/puppetdb-python | puppetdb/v3/aggregate_event_counts.py | Python | mit | 6,665 | 0.005553 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2013 Arcus, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
#... | The response is a single JSON map containing aggregated event-count information and a total for how many event-count results were aggregated.
{
"successes": 2,
"failures": 0,
"noops": 0,
"skips": 1,
"total": 3
}
"""
__author__ = "monkee"
__version__ = "1.0.1"
__maintainer__ = "monk-ee"
__email__ | = "magic.monkee.magic@gmail.com"
__status__ = "Development"
from puppetdb import utils
API_VERSION = 'v3'
def get_aggregate_event_counts(api_url=None, query='', summarize_by='', count_by='', counts_filter='', distinct_resources='', verify=False, cert=list()):
"""
Returns facts
:param api_url: Base Pupp... |
occrp/id-backend | api_v3/views/review_exports.py | Python | mit | 1,593 | 0 | from csv import DictWriter
from datetime import datetime
from itertools import chain
from django.db import models
from django.db.models.functions import Concat
from django.http import StreamingHttpResponse
from rest_framework import permissions
from .reviews import ReviewsEndpoint
from .ticket_exports import TicketEx... | sEndpoint(ReviewsEndpoint):
permission_classes = (permissions.IsAdminUser, )
def list(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
ticket_url = \
TicketExportsEndpoint.TICKET_URI.format(self.request.get_host())
cols = dict(
... | output_field=models.CharField()
),
Date=models.F('created_at'),
Rating=models.F('rating'),
Link=models.F('link'),
Comment=models.F('body')
)
writer = DictWriter(DummyBuffer(), fieldnames=cols.keys())
header_with_rows = chai... |
oleg-alexandrov/pytest | testing/test_cache.py | Python | mit | 11,823 | 0.000592 | import sys
import pytest
import os
import shutil
import py
pytest_plugins = "pytester",
class TestNewAPI:
def test_config_cache_makedir(self, testdir):
testdir.makeini("[pytest]")
config = testdir.parseconfigure()
with pytest.raises(ValueError):
config.cache.makedir("key/name")... | ode.Source("""
def test_1():
assert 1
def test_2():
assert 1
def test_3():
assert 0
"""))
result = testdir.runpytest("--lf")
| result.stdout.fnmatch_lines([
"*2 passed*1 desel*",
])
result = testdir.runpytest("--lf")
result.stdout.fnmatch_lines([
"*1 failed*2 passed*",
])
result = testdir.runpytest("--lf", "--cache-clear")
result.stdout.fnmatch_lines([
"... |
JackKelly/neuralnilm_prototype | scripts/e71.py | Python | mit | 2,878 | 0.00139 | from __future__ import print_function, division
from neuralnilm import Net, RealApplianceSource, BLSTMLayer, SubsampleLayer, DimshuffleLayer
from lasagne.nonlinearities import sigmoid, rectify
from lasagne.objectives import crossentropy
from lasagne.init import Uniform, Normal
from lasagne.layers import LSTMLayer, Dens... | nterval=50,
loss_function=crossentropy,
layers_config=[
{
'type': DimshuffleLayer,
'pattern': (0, 2, 1)
},
{
'type': Conv1DLayer,
'num_filters': 50,
'filter_length': 3,
'stride': 1,
'nonlinearity': sigmoi... | 'num_filters': 50,
'filter_length': 3,
'stride': 1,
'nonlinearity': sigmoid,
'W': Uniform(10),
'b': Uniform(10)
},
{
'type': DimshuffleLayer,
'pattern': (0, 2, 1)
},
{
'type': LSTMLayer,
... |
Dwarfartisan/pyparsec | src/parsec/state.py | Python | mit | 707 | 0 | #!/usr/bin/python3
# coding:utf-8
from .error import ParsecE | of
class BasicState(object):
def __init__(self, data):
self.data = data
self.index = 0
self.tran = -1
def next(self | ):
if 0 <= self.index < len(self.data):
re = self.data[self.index]
self.index += 1
return re
else:
raise ParsecEof(self)
def begin(self):
if self.tran == -1:
self.tran = self.index
return self.index
def commit(self, t... |
hgl888/chromium-crosswalk-efl | mojo/python/tests/bindings_structs_unittest.py | Python | bsd-3-clause | 6,707 | 0.00656 | # 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.
import math
import unittest
# pylint: disable=F0401
import mojo.system
# Generated files
# pylint: disable=F0401
import sample_import_mojom
import sample_i... | self.assertEquals(defaults_test.a16, -1.2E+20)
self.assertEquals(defaults_test.a17, 1.23E-20)
self.assertEquals(defaults_test.a18, None)
self.assertEquals(defaults_test.a19, None)
self.assertEquals(defaults_test.a20, sample_service_mojom.Bar.Type.BOTH)
self.assertEquals(defaults_test.a21, | None)
self.assertTrue(isinstance(defaults_test.a22, sample_import2_mojom.Thing))
self.assertEquals(defaults_test.a23, 0xFFFFFFFFFFFFFFFF)
self.assertEquals(defaults_test.a24, 0x123456789)
self.assertEquals(defaults_test.a25, -0x123456789)
self.assertEquals(defaults_test.a26, float('inf'))
self.a... |
imk1/IMKTFBindingCode | averageZeroSignalsWithinPeaks.py | Python | mit | 2,918 | 0.025703 | import sys
import argparse
from itertools import izip
import math
def parseArgument():
# Parse the input
parser = argparse.ArgumentParser(description = "Make regions with 0 signal the average of their surrounding regions")
parser.add_argument("--signalsFileName", required=True, help='Signals file')
parser.add_argu... |
else:
outputFile.write(str(lastSignal) + "\n")
elif (lastPeakIndex == lastLastPeakIndex) and (not math.isnan(lastLastSignal)):
# Set the output to the region before it
outputFile.write(str(lastLastSignal) + "\n")
else:
outputFile.write(str(lastSignal) + "\n")
if signal != 0:
# The curre... | lastSignal == 0:
# The final signal was a zero, so set it to the signal before it
if (lastPeakIndex == lastLastPeakIndex) and (not math.isnan(lastLastSignal)):
# Set the output to the region before it
outputFile.write(str(lastLastSignal) + "\n")
else:
outputFile.write(str(lastSignal) + "\n")
signalsFil... |
moskytw/tacit | tests/test_correctness.py | Python | mit | 884 | 0.003394 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from itertools import izip
from tacit import tac
ordered_list_path = 'data/ordered.list'
expected_lines = open(ordered_list_path).read().splitlines(True)
expected_lines.reverse()
expected_count = len(expected_lines)
for bsize in range(10):
count = 0
... | count += 1
if bsize > 0:
if count != expected_count:
print >> sys.stderr, 'error: bsize=%d, expected_count=%r, count=%r' % (bsize, expected_count, count)
else:
if count != 0:
print >> sys.stderr, 'error: bsize=%d, expected_count=0, count=%r' % (bsize, count)
| |
cheng10/Shanbay_Clone | words/forms.py | Python | gpl-3.0 | 407 | 0 | from django import forms
from django.contrib.auth.m | odels import User
from models import Learner
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
| class Meta:
model = User
fields = ('username', 'email', 'password')
class LearnerForm(forms.ModelForm):
class Meta:
model = Learner
fields = ('vocab_book', 'words_perday')
|
benvanwerkhoven/kernel_tuner | kernel_tuner/strategies/pso.py | Python | apache-2.0 | 4,015 | 0.001743 | """ The strategy that uses particle swarm optimization"""
from __future__ import print_function
from __future__ import division
import random
import numpy as np
from kernel_tuner.strategies.minimize import _cost_func, get_bounds_x0_eps
def tune(runner, kernel_options, device_options, tuning_options):
""" Find th... | (bounds)
self.args = args
self.velocity = np.random.uniform(-1, 1, self.ndim)
self.position = np.random.uniform([b[0] for b in bounds], [b[1] for b in bounds])
self.best_pos = self.position
self.best_time = | 1e20
self.time = 1e20
def evaluate(self, cost_func):
self.time = cost_func(self.position, *self.args)
# update best_pos if needed
if self.time < self.best_time:
self.best_pos = self.position
self.best_time = self.time
def update_velocity(self, best_posi... |
andresfcardenas/marketing-platform | landing/forms.py | Python | bsd-3-clause | 803 | 0 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from landing.models import LandingRegister
class LandingForm(forms.ModelForm):
class Meta:
model = LandingRegister
fields = (
'nam... | elds['email'].widget | .attrs['placeholder'] = 'Email'
self.helper.add_input(
Submit(
'submit',
'Solicitar Información',
css_class='button'
),
)
|
dreadrel/UWF_2014_spring_COP3990C-2507 | notebooks/scripts/book_code/code/decorator5.py | Python | apache-2.0 | 750 | 0.005333 | d | ef tracer(func): # State via enclosing scope and func attr
def wrapper(*args, **kwargs): # calls is per-function, not global
wrapper.calls += 1
print('call %s to %s' % (wrapper.calls, func.__name__))
return func(*args, **kwargs)
wrapper.calls = 0
return ... | apper
@tracer
def spam(a, b, c): # Same as: spam = tracer(spam)
print(a + b + c)
@tracer
def eggs(x, y): # Same as: eggs = tracer(eggs)
print(x ** y)
spam(1, 2, 3) # Really calls wrapper, assigned to spam
spam(a=4, b=5, c=6) # wrapper calls spam
eggs(2, 16) #... |
Vishakha1990/Lambdas | awsLambda_ours/nearbyfriends/findnearbypeoplelocal.py | Python | apache-2.0 | 1,712 | 0.003505 | from __future__ import print_function
import time
import uuid
import sys
import socket
import logging
import gpxpy.geo
import redis
from operator import itemgetter
r = redis.Redis(
hos | t='datanode-001.zumykb.0001.use2.cach | e.amazonaws.com',
port=6379)
def get_distance(lat, querylat, querylong):
splitloc = lat
friendts = splitloc[0]
friendlat = float(splitloc[1])
friendlog = float(splitloc[2])
return gpxpy.geo.haversine_distance(friendlat, friendlog, querylat, querylong)
def handler():
"""
This function... |
arju88nair/projectCulminate | venv/lib/python3.5/site-packages/pylint/test/functional/undefined_loop_variable.py | Python | apache-2.0 | 733 | 0.006821 | # pylint: disable=missing-docstring
def do_stuff(some_random_list):
for var in some_random_list:
pass
return var # [undefined-loop- | variable]
def do_else(some_random_list):
for var in some_random_list:
if var == 42:
break
else:
var = 84
return var
__revision__ = 'yo'
TEST_LC = [C for C in __revision__ if C.isalpha()]
B = [B for B in __revision__ if B.isalpha()]
VAR2 = B # nor this one
for var1, var2 in ... | notherthing()
for x in []:
pass
for x in range(3):
VAR5 = (lambda: x)()
|
glujan/lapka | tests/unit/test_fetch.py | Python | mit | 9,020 | 0.002443 | import unittest
from pathlib import Path
from unittest.mock import patch
from urllib.parse import urljoin, urlparse
from aiohttp import ClientSession
from lxml.etree import XPath, XPathSyntaxError
from tests.utils import AsyncMeta, fake_response as f_resp
from lapka import fetch
class TestShelter(unittest.TestCase,... | ssertDictEqual(data, valid_data)
class TestNaPaluchuWawPl(TestConcreteShelter, unittest.TestCase, metaclass=AsyncMeta):
shelter_class = fetch.NaPaluchuWawPl
animals_urls = {
"animals": [
"http://www.napaluchu.waw.pl/czekam_na_ciebie/wszystkie_zwierzeta_do_adopcji/011100429",
"... | .napaluchu.waw.pl/czekam_na_ciebie/wszystkie_zwierzeta_do_adopcji:2",
}
@classmethod
def setUpClass(cls):
fp = Path(__file__).parent / 'assets' / 'animal_11.html'
with open(fp, 'r') as f:
cls.animal = f.read()
fp = Path(__file__).parent / 'assets' / 'animals_list_11.htm... |
Robobench/rapman-subuser | logic/subuserCommands/repair.py | Python | lgpl-3.0 | 1,044 | 0.025862 | #!/usr/bin/env python
# This file should be compatible with both Python 2 and 3.
# If it is not, please file a bug report.
import pathConfig
#external imports
import optparse,sys
#internal imports
import subuserlib.classes.user,subuserlib.verify,subuserlib.commandLineArguments
########################################... | og [options]"
description = """
Repair your subuser installation.
This is usefull when migrating from one machine to another. You can copy your ~/.subuser folder to the new machine and run repair, and things should just work.
"""
parser = optparse.OptionParser(usage=usage,description=description,formatter=subuser... | ealArgs)
def verify(realArgs):
options,arguments=parseCliArgs(realArgs)
user = subuserlib.classes.user.User()
subuserlib.verify.verify(user)
user.getRegistry().commit()
if __name__ == "__main__":
verify(sys.argv[1:])
|
Gjum/SpockBot | spockbot/mcdata/recipes.py | Python | mit | 2,639 | 0 | from collections import defaultdict, namedtuple
from minecraft_data.v1_8 import recipes as raw_recipes
RecipeItem = namedtuple('RecipeItem', 'id meta amount')
class Recipe(object):
def __init__(self, raw):
self.result = reformat_item(raw['result'], None)
if 'ingredients' in raw:
sel... | ta
if 'count' not in raw:
raw['count'] = 1
return RecipeItem(raw['id'], raw['met | adata'], raw['count'])
elif isinstance(raw, list):
return RecipeItem(raw[0], raw[1], 1)
else: # single ID or None
return RecipeItem(raw or None, default_meta, 1)
def reformat_shape(shape):
return [[reformat_item(item, None) for item in row] for row in shape]
def iter_recipes(item_id, me... |
sahat/bokeh | sphinx/source/tutorial/exercises/boxplot.py | Python | bsd-3-clause | 2,199 | 0.003638 | import numpy as np
import pandas as pd
from bokeh.plotting import *
# Generate some synthetic time series for six different categories
cats = list("abcdef")
y = np.random.randn(2000)
g = np.random.choice(cats, 2000)
for i, l in enumerate(cats):
y[g == l] += i // 2
df = pd.DataFrame(dict(score=y, group=g))
# Find ... | se `rect` t | o draw the whiskers. It's slightly cheating, but it's
# easier than using segments or lines, since we can specify widths simply with
# categorical percentage units
rect(cats, lower.score, 0.2, 0, line_color="black")
rect(cats, upper.score, 0.2, 0, line_color="black")
# EXERCISE: use `circle` to draw the outliers
# EX... |
mahak/neutron | neutron/extensions/l3_ext_ndp_proxy.py | Python | apache-2.0 | 817 | 0 | # Copyright 2022 Troila
# 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... | NY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from neutron_lib.api.definitions import l3_ext_ndp_proxy as apidef
from neutron_lib.api | import extensions
class L3_ext_ndp_proxy(extensions.APIExtensionDescriptor):
api_definition = apidef
|
jrtomps/root | main/python/cmdLineUtils.py | Python | lgpl-2.1 | 47,974 | 0.01357 | #!/usr/bin/env @python@
# ROOT command line tools module: cmdLineUtils
# Author: Julien Ripoche
# Mail: julien.ripoche@u-psud.fr
# Date: 20/08/15
"""Contain utils for ROOT command line tools"""
##########
# Stream redirect functions
# The original code of the these functions can be found here :
# http://stackoverflo... | ilog)
def getParserSingleFile(theHelp, theEpilog=""):
"""
Get a commandline parser with the defaults of the commandline uti | ls and a
source file or not.
"""
parser = _getParser(theHelp, theEpilog)
parser.add_argument("FILE", nargs='?', help="Input file")
return parser
def getParserFile(theHelp, theEpilog=""):
"""
Get a commandline parser with the defaults of the commandline utils and a
list of source files.
"""
... |
Yukarumya/Yukarum-Redfoxes | testing/mozharness/configs/single_locale/tc_linux32.py | Python | mpl-2.0 | 927 | 0.001079 | import os
EN_US_BINARY_URL = "%(en_us_ | binary_url)s"
config = {
"locales_file": "src/browser/locales/all-locales",
"tools_repo": "https://hg.mozilla.org/build/tools",
"mozconfig": "src/browser/config/mozconfigs/linux32/l10n-mozconfig",
"bootstrap_env": {
"NO_MERCURIAL_SETUP_CHECK": "1",
"MOZ_OBJDIR": "obj-l10n",
"EN_... | "LOCALE_MERGEDIR": "%(abs_merge_dir)s/",
"MOZ_UPDATE_CHANNEL": "%(update_channel)s",
"DIST": "%(abs_objdir)s",
"LOCALE_MERGEDIR": "%(abs_merge_dir)s/",
"L10NBASEDIR": "../../l10n",
"MOZ_MAKE_COMPLETE_MAR": "1",
'TOOLTOOL_CACHE': os.environ.get('TOOLTOOL_CACHE'),
}... |
Kirkkonen/NetForSpeech | nfsmain/models.py | Python | apache-2.0 | 3,681 | 0.001642 | from django.db import models
from django.core.urlresolvers import reverse
from django.utils import timezone
from datetime import date
# Create your models here.
class ManagedEntity():
# submitted_by = models.ForeignKey()
submitted_at = models.DateField(auto_now_add=True)
class Organisation(models.Model):
... | sation, blank=True, related_name='employee_current_ | set')
previous_work = models.ManyToManyField(Organisation, blank=True, related_name='employee_former_set')
def __str__(self):
return ' '.join([self.index_name, self.secondary_names, self.other_names])
def get_absolute_url(self):
return reverse('main:speaker_detail', kwargs={'pk': self.pk})... |
rabipanda/tensorflow | tensorflow/python/debug/lib/debug_gradients.py | Python | apache-2.0 | 15,460 | 0.004851 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | adients_by_tensors(y):
train_op = tf.train.GradientDescentOptimizer(z)
# Now we can reflect through grad_debugger to get the gradient tensor
# with respect to y.
y_grad = grad_debugger.gradient_tensor(y)
# or
y_grad = grad_debugger.gradient_tensor("y:0")
```
Args:
graph: the `t... | urns:
The GradientsDebugger instance itself.
"""
if not isinstance(tensors, list):
tensors = [tensors]
tensor_name_regex = []
for tensor in tensors:
tensor_name_regex.append(re.escape(tensor.name) + "$")
tensor_name_regex = "(" + "|".join(tensor_name_regex) + ")"
return self.... |
pierotofy/WebODM | app/tests/test_api_task_import.py | Python | mpl-2.0 | 6,442 | 0.002173 | import os
import time
import io
import requests
from django.contrib.auth.models import User
from guardian.shortcuts import remove_perm, assign_perm
from rest_framework import status
from rest_framework.test import APIClient
import worker
from app.cogeo import valid_cogeo
from app.models import Project
from app.models... | mpletion
c = 0
while c < 10:
worker.tasks.process_pending_tasks()
file_import_task.refresh_from_db()
if file_import_task.status == status_codes.COMPLETED:
break
c += 1
time.sleep(1)
s... | g_node, None)
self.assertEqual(file_import_task.auto_processing_node, False)
# Can access assets
res = client.get("/api/projects/{}/tasks/{}/assets/odm_orthophoto/odm_orthophoto.tif".format(project.id, file_import_task.id))
self.assertEqual(res.status_code, status.HTTP_2... |
sjhawke/piface-cad | lib/writetheweather.py | Python | gpl-3.0 | 1,742 | 0.011481 | #!/usr/bin/env python3
import os
import requests
import time
import json
def getWeatherAsWords():
# Settings for your API key and location details read from environment strings, e.g. exports etc
appid = str(os.environ.get('apikey'))
locid = str(os.environ.get('locationkey'))
lat = str(os.environ.get(... | status_code))
if r.status_code == 200:
# get count - check for zero and return amber.
body = r.json()
w = body['weather']
main = body['main']
temp = int(round(main['temp'],0))
outlook = w[0]['description']
weather = str(temp) + ... | # print(uv_uri)
uvreq = requests.get(uv_uri, timeout=5)
if uvreq.status_code == 200:
body = uvreq.json()
uv = body['value']
uvindex = ''
if(uv>8.0):
uvindex = 'VH'
elif(uv>5.0):
uvindex = "H"
elif(uv... |
eduNEXT/edx-platform | common/djangoapps/course_modes/migrations/0005_auto_20151217_0958.py | Python | agpl-3.0 | 1,002 | 0.000998 | from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('course_modes', '0004_auto_20151113_1457'),
]
operations = [
migrations.SeparateDatabaseAndState(
database_operations=[],
state_operations=[
migra... | model_name='coursemode',
name='_expiration_datetime',
field=models.DateTimeField(db_column='expiration_datetime', default=None, blank=True, help_text='OPTIONAL: After this date/time, users will no longer be able to enroll in this mode. Leave this blank if users... | ses for the course.', null=True, verbose_name='Upgrade Deadline'),
),
]
)
]
|
eggsandbeer/scheduler | synergy/mx/tree_node_details.py | Python | bsd-3-clause | 2,627 | 0.002284 | __author__ = 'Bohdan Mushkevych'
from werkzeug.utils import cached_property
from synergy.conf import settings
from synergy.system import time_helper
from synergy.conf import context
from synergy.mx.rest_model import RestTimetableTreeNode, RestJob
from synergy.mx.base_request_handler import BaseRequestHandler, valid_a... | quest_valid = True if self.tree else False
@classmethod
def get_details(cls, node, as_model=False):
"""method returns either RestJob instance or corresponding document, depending on the as_model argument """
rest_job = RestJob(
process_name=node.process_name,
timeperiod=... | len(node.children),
number_of_failures='NA' if not node.job_record else node.job_record.number_of_failures,
state='NA' if not node.job_record else node.job_record.state,
log=node.job_record.log)
if as_model:
return rest_job
else:
return rest_j... |
mtholder/phyloplumber | phyloplumber/controllers/projects.py | Python | gpl-3.0 | 8,738 | 0.005035 | # The projects controller provides an interface for version-controlled projects
# stored on the fs as subdirectories of
# ${top_internal_dir}/projects where top_internal_dir is a variable in the
# .ini file used to launch the server.
#
# The structure of these directories is assumed to be:
# name.txt -- plain ... | name_for_project(dir)
index_file = os.path.join(self.dir, 'index.xml')
try:
inp = open(index_file, 'rU')
except:
if os.path.exists(self.dir):
raise CorruptedProjectError(project_id, 'index file missing')
raise InvalidProjectIDError(project_id)
... | raise CorruptedProjectError(project_id, 'Error parsing the index file:\n' + str(x))
def get_entities(self):
return []
entity_list = property(get_entities)
class NewProjectForm(formencode.Schema):
allow_extra_fields = True
filter_extra_fields = True
name = formencode.validators.UnicodeStri... |
mikitex70/pelican-plugins | i18n_subsites/test_i18n_subsites.py | Python | agpl-3.0 | 5,011 | 0.000798 | '''Unit tests for the i18n_subsites plugin'''
import os
import locale
import unittest
import subprocess
from tempfile import mkdtemp
from shutil import rmtree
from . import i18n_subsites as i18ns
from pelican import Pelican
from pelican.tests.support import get_settings
from pelican.settings import read_settings
cl... | ns._SIGNAL_HANDLERS_DB.items():
sig = getattr(i18ns.signals, sig_name)
self.assertIn(id(handler), sig.receivers)
# clean up
sig.disconnect(handler)
class TestFullRun(unittest.TestCase):
'''Test runni | ng Pelican with the Plugin'''
def setUp(self):
'''Create temporary output and cache folders'''
self.temp_path = mkdtemp(prefix='pelicantests.')
self.temp_cache = mkdtemp(prefix='pelican_cache.')
def tearDown(self):
'''Remove output and cache folders'''
rmtree(self.temp_... |
open-craft/opencraft | instance/serializers/openedx_appserver.py | Python | agpl-3.0 | 3,375 | 0.000296 | # -*- coding: utf-8 -*-
#
# OpenCraft -- tools to aid developing and hosting free software projects
# Copyright (C) 2015-2019 OpenCraft <contact@opencraft.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Fre... | ##############
class OpenEdXAppServerSerializer(serializers.ModelSerializer):
"""
Detailed serializer for OpenEdXAppServer
"""
instance = InstanceReferenceMinimalSerializer(source='owner')
server = OpenStackServerSerializer()
class Meta:
model = OpenEdXAppServer
fields = tuple... | lds()) + (
'configuration_database_settings',
'configuration_storage_settings',
'configuration_theme_settings',
'configuration_site_configuration_settings',
'common_configuration_settings',
'configuration_settings',
'instance',
... |
HeinerTholen/Varial | varial/test/test_tools.py | Python | gpl-3.0 | 3,530 | 0 | #!/usr/bin/env python
import varial.tools
import unittest
import shutil
import os
class ResultCreator(varial.tools.Tool):
def run(self):
self.result = varial.wrp.Wrapper(name=self.name)
class ResultSearcher(varial.tools.Tool):
def __init__(self, name, input_path):
super(ResultSearcher, self... | )
def test_lookup_result_parallel(self):
searchers, chain = self._setup_chains(varial.tools.ToolChainParallel)
chain = varial.tools.ToolChainVanilla(self.base_name, [chain])
varial.tools.Runner(chain)
for srchr in searchers:
self.assertIsNotNone(
srchr.... | 'Result not found for input_path: %s' % srchr.input_path
)
suite = unittest.TestLoader().loadTestsFromTestCase(TestTools)
if __name__ == '__main__':
unittest.main()
|
iivvoo/resturo | resturo/serializers.py | Python | isc | 2,545 | 0 | from django.contrib.auth.models import User
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings
from .models import EmailVerification, modelresolver
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'fi... | _kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
user = self.Meta.model(
email=validated_data['email'],
username=validated_data['userna | me'],
first_name=validated_data['first_name'],
last_name=validated_data['last_name']
)
user.set_password(validated_data['password'])
user.save()
# XXX should be jwt / token agnostic!
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
jwt_payloa... |
EduPepperPD/pepper2013 | common/lib/xmodule/xmodule/static_content.py | Python | agpl-3.0 | 6,505 | 0.001845 | # /usr/bin/env python
"""
This module has utility functions for gathering up the static content
that is defined by XModules and XModuleDescriptors (javascript and css)
"""
import logging
import hashlib
import os
import errno
import sys
from collections import defaultdict
from docopt import docopt
from path import path... | n classes:
module_js = class_.get_javascript()
for filetype in ('coffee', 'js'):
for idx, fragment in enumerate(module_js.get(filetype, [])):
js_fragments.add((idx, filetype, fragment))
for idx, filetype, fragment in sorted(js_fragments):
filename = "{idx:0=3d | }-{hash}.{type}".format(
idx=idx,
hash=hashlib.md5(fragment).hexdigest(),
type=filetype)
contents[filename] = fragment
_write_files(output_root, contents, {'.coffee': '.js'})
return [output_root / filename for filename in contents.keys()]
def _write_files(output_r... |
DaniFdezAlvarez/wikidataExplorer | wikidata_exp/wdexp/wikidata/commands/common_incoming_props_DUMP.py | Python | gpl-2.0 | 5,792 | 0.002762 | __author__ = 'Dani'
import ijson
import json
PG_SCORE = "pg_score"
INCOMING_EDGES = "in_edges"
OUTCOMING_EDGES = "out_edges"
LABEL = "label"
DESCRIPTION = "desc"
class CommonIncomingCommand(object):
def __init__(self, source_dump_file, out_file, source_target_ids_file, topk_target_entities):
... |
if target in self._edges_dict:
if property not in self._edges_dict[target][INCOMING_EDGES]:
self._edges_dict[target][INCOMING_EDGES][property] = 0
self._edges_dict[ta | rget][INCOMING_EDGES][property] += 1
|
fprados/nipype | nipype/interfaces/freesurfer/model.py | Python | bsd-3-clause | 41,958 | 0.004886 | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""The freesurfer module provides basic functions for interfacing with
freesurfer tools.
Change directory to provide relative paths for doctests
>>> import os
>>> filepath = os.path.dirname( os... | d by white space')
surf_measure_file = InputMultiPath(File(exists=True), argstr='--is %s...',
xor=('surf_measure', 'surf_measure_file', 'surf_area'),
desc='file alternative to surfmeas, still requires list of subjects')
source_format = traits.Str(argstr='--srcfmt %s', desc='... | )')
vol_measure_file = InputMultiPath(traits.Tuple(File(exists=True),
File(exists=True)),
argstr='--iv %s %s...',
desc='list of volume measure and reg file tuples')
proj_frac = traits.Float(argstr='--pro... |
ahmedaljazzar/edx-platform | openedx/core/djangoapps/waffle_utils/tests/test_init.py | Python | agpl-3.0 | 5,739 | 0.003311 | """
Tests for waffle utils features.
"""
import crum
import ddt
from django.test import TestCase
from django.test.client import RequestFactory
from edx_django_utils.cache import RequestCache
from mock import patch
from opaque_keys.edx.keys import CourseKey
from waffle.testutils import override_flag
from .. import Cour... | equest()
self.addCleanup(crum.set_current_request, None)
crum.set_current_request(request)
RequestCache.clear_all_namespaces()
@ddt.data(
{'course_override': WaffleFlagCourseOverrideModel.ALL_CHOICES.on, 'waffle_enabled': False, 'result': True},
{'course_override': WaffleFla... | ': True, 'result': False},
{'course_override': WaffleFlagCourseOverrideModel.ALL_CHOICES.unset, 'waffle_enabled': True, 'result': True},
{'course_override': WaffleFlagCourseOverrideModel.ALL_CHOICES.unset, 'waffle_enabled': False, 'result': False},
)
def test_course_waffle_flag(self, data):
... |
tschalch/pyTray | src/lib/reportlab/graphics/samples/scatter_lines_markers.py | Python | bsd-3-clause | 3,824 | 0.02432 | #Autogenerated by ReportLab guiedit do not edit
from reportlab.graphics.charts.legends import Legend
from reportlab.graphics.charts.lineplots import ScatterPlot
from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin, String
from reportlab.graphics.charts.textlabels import Label
from excelcolors import ... | pace = 5
self.Legend.dy = 5
self.Legend.dx = 5
self.Legend.deltay = 5
self.Legend.alignment ='right'
self.chart.lineLabelFormat = None
self.chart.xLabel = 'X Axis'
self.chart.y = 30
... | xis.labelTextFormat = '%d'
self.chart.yValueAxis.forceZero = 1
self.chart.xValueAxis.forceZero = 1
self.chart.joinedLines = 1
self._add(self,0,name='preview',validate=None,desc=None)
if __name__=="__main__": #NORUNTESTS
ScatterLinesM... |
ging/horizon | openstack_dashboard/dashboards/project/instances/tabs.py | Python | apache-2.0 | 3,495 | 0 | # Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | return {"instance": instance,
"cons | ole_log": data}
class ConsoleTab(tabs.Tab):
name = _("Console")
slug = "console"
template_name = "project/instances/_detail_console.html"
preload = False
def get_context_data(self, request):
instance = self.tab_group.kwargs['instance']
console_type = getattr(settings, 'CONSOLE_TYP... |
danallan/octal-application | server/apps/maps/forms.py | Python | gpl-3.0 | 3,363 | 0.007136 | from django import forms
from django.contrib.auth.hashers import check_password
from models import Graphs, Concepts
from utils import graphCheck, GraphIntegrityError
import json
class GraphForm(forms.ModelForm):
json_input = forms.BooleanField(label=("JSON Input"), required=False,
help_text=("Check th... | nError("Error: graph cannot be blank")
try:
graph_list = json.loads(json_data)
return graphCheck(graph_list)
except ValueError:
raise forms.ValidationError("Error: malformed JSON")
except GraphIntegrityError as e:
raise forms.ValidationError("Err... | ata', 'lti_key', 'lti_secret', 'secret']
labels = {
'name': ("Unit Name"),
'study_active': ("Research study"),
'lti_key': ("Consumer Key"),
'lti_secret': ("Shared Secret"),
}
help_texts = {
'public': ("Public units are displayed on the ... |
gkotton/vmware-nsx | vmware-nsx/neutron/tests/unit/vmware/apiclient/test_api_eventlet_request.py | Python | apache-2.0 | 12,642 | 0 | # Copyright (C) 2009-2012 VMware, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | return (mysock, myresponse, myconn)
def test_issue_request_trigger_exception(self):
(mysock, myresponse, myconn) = self.prep_issue_request()
self.client.acquire_connection.return_value = None
self.req._issue_request | ()
self.assertIsInstance(self.req._request_error, Exception)
self.assertTrue(self.client.acquire_connection.called)
def test_issue_request_handle_none_sock(self):
(mysock, myresponse, myconn) = self.prep_issue_request()
myconn.sock = None
self.req.start()
self.assert... |
oxc/Flexget | flexget/plugins/list/sonarr_list.py | Python | mit | 11,933 | 0.003017 | from __future__ import unicode_literals, division, absolute_import
from builtins import * # pylint: disable=unused-import, redefined-builtin
from future.moves.urllib.parse import urlparse
import json
import logging
from collections import MutableSet
import requests
from requests import RequestException
from flexget... | izes the quality parameter
fg_cutoff = ''
path = None
if not show['monitored'] and self.config.get(
'only_monitored'): # Checks if to retrieve just monitored shows
continue
if show['status'] == 'ended' and not self.config.get('include_... | lf.config.get('include_data') and profiles_json: # Check if to retrieve quality & path
path = show.get('path')
for profile in profiles_json:
if profile['id'] == show['profileId']: # Get show's profile data from all possible profiles
fg_qualit... |
Commonists/SurfaceImageContentGap | surfaceimagecontentgap/__init__.py | Python | mit | 59 | 0 | """ Surface image content gap. " | ""
__version__ | = '1.3-dev'
|
Einsteinish/PyTune3 | utils/feedfinder.py | Python | mit | 13,462 | 0.008394 | """feedfinder: Find the Web feed for a Web page
http://www.aaronsw.com/2002/feedfinder/
Usage:
feed(uri) - returns feed found for a URI
feeds(uri) - returns all feeds found for a URI
>>> import feedfinder
>>> feedfinder.feed('scripting.com')
'http://scripting.com/rss.xml'
>>>
>>> feedfinder.fe... | n ('http', 'https'): return 0
try:
data = _gatekeeper.get(uri, check=False)
except (KeyError, UnicodeDecodeError):
return False
count = couldBeFeedData(data)
return count
def sortFeeds(feed1Info, feed2Info):
return cmp(feed2Info[ | 'headlines_rank'], feed1I |
shucommon/little-routine | python/AI/opencv/gui/mouse.py | Python | gpl-3.0 | 477 | 0.035639 | import numpy as np
import cv2 as cv
# mouse callback function
def draw_circle(event,x,y,flags,param):
| if event == cv.EVENT_LBUTTONDBLCLK:
cv.circle(img,(x,y),50,(255,0,0),-1)
# Create a black image, a window and bind the function to window
img = np.zeros((512,512,3), np.uint8)
cv.namedWindow('image')
cv.setMouseCallback('image',draw_circle)
while(1):
cv.imshow('image',img)
# esc
if c | v.waitKey(20) & 0xFF == 27:
break
cv.destroyAllWindows()
|
yochow/autotest | client/tests/cpuset_tasks/cpuset_tasks.py | Python | gpl-2.0 | 939 | 0.003195 | import os, time
import subprocess
from autotest_lib.client.bin import test
from autotest_lib.client.common_lib import utils, error
class cpuset_tasks(test.test):
version = 1
preserve_srcdir = | True
def initialize(self):
self.job.require_gcc()
def setup(self):
os.chdir(self.srcdir)
utils.system('make')
def execute(self):
os.chdir(self.tmpdir)
tasks_bin = os.path.join(self.srcdir, 'tasks')
p = subprocess.Popen([tasks_bin, ' 25000'])
time... | _container/tasks',
ignore_status=True)
except IOError:
utils.nuke_subprocess(p)
raise error.TestFail('cat cpuset/tasks failed with IOError')
utils.nuke_subprocess(p)
if result and result.exit_status:
raise error.TestFail('cat cpu... |
jlmdegoede/Invoicegen | hour_registration/tests.py | Python | gpl-3.0 | 11,185 | 0.003934 | from django.test import TestCase
from django.test import Client
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
import datetime
from .models import *
from django.utils import timezone
from django.contrib.auth.models import Group, ContentType, Permission
from django.db.models imp... | user', password='secret')
self.c.get(reverse('start_time_tracking', kwargs={'product_id': self.order_one.id}))
response = self.c.get(reverse('start_time_tracking', kwargs={'product_id': self.order_one.id}))
self.assertEqual(response.status_code, 200)
response_str = str(response.content, ... | def test_end_time_tracking(self):
self.c.login(username='testuser', password='secret')
self.c.get(reverse('start_time_tracking', kwargs={'product_id': self.order_one.id}))
response_end = self.c.get(reverse('end_time_tracking', kwargs={'product_id': self.order_one.id}))
self.assertContain... |
jaeilepp/eggie | ui/preprocessDialog.py | Python | bsd-2-clause | 23,303 | 0.00515 | '''
Created on Dec 16, 2014
@author: Jaakko Leppakangas
'''
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import pyqtSignal
from PyQt4.Qt import QApplication, QSettings, pyqtSlot
from time import sleep
import numpy as np
import matplotlib.pyplot as plt
import sys
from threading import Thread, Event
from general... | f.conditions) == 0:
spectrumWidget = PowerSpectrumWidget(tmax, self)
spectrumWidget.index = 0
spectrumWidget.removeWidget.connect(self.on_RemoveWidget_clicked)
spectrumWidget.channelCopy.connect(self.copyChannels)
self.ui.verticalLayoutConditions.addWidget(spe... | to the console and back.
"""
if self.ui.actionDirectOutput.isChecked():
sys.stdout = EmittingStream(textWritten=self.normalOutputWritten)
sys.stderr = EmittingStream(textWritten=self.errorOutputWritten)
else:
sys.stdout = sys.__stdout__
sys.stderr ... |
dreibh/planetlab-lxc-plcapi | PLC/Methods/GetSession.py | Python | bsd-3-clause | 1,423 | 0.001405 | import time
from PLC.Method import Method
from PLC.Parameter import Parameter, Mixed
from PLC.Auth import Auth
from PLC.Sessions import Session, Sessions
from PLC.Nodes import Node, Nodes
from PLC.Persons import Person, Persons
class GetSession(Method):
"""
Returns a new session key if a user or node authenti... | henticated with a session key, just return it
if 'session' in auth:
return auth['session']
session = Session(self.api)
if isinstance(self.caller, Person):
# XXX Make this configurable
if expires is None:
session['expires'] = int(time.time()) ... | (expires)
session.sync(commit=False)
if isinstance(self.caller, Node):
session.add_node(self.caller, commit=True)
elif isinstance(self.caller, Person):
session.add_person(self.caller, commit=True)
return session['session_id']
|
seisman/HinetPy | tests/localtest_client_multi_threads.py | Python | mit | 289 | 0 | import os
from datetime import datetime
from | HinetPy import Client
username = os.environ["HINET_USERNAME"]
password = os.environ["HINET_PASSWORD"]
client = Client(usernam | e, password)
starttime = datetime(2017, 1, 1, 0, 0)
client.get_continuous_waveform("0101", starttime, 20, threads=4)
|
urbn/kombu | t/unit/asynchronous/test_timer.py | Python | bsd-3-clause | 4,311 | 0 | from __future__ import absolute_import, unicode_literals
import pytest
from datetime import datetime
from case import Mock, patch
from kombu.asynchronous.timer import Entry, Timer, to_timestamp
from kombu.five import bytes_if_py2
class test_to_timestamp:
def test_timestamp(self):
assert to_timestamp(... | 2
args2, _ = t.schedule.enter_after.call_args_list[1]
sec2, tref2, _ = args2
assert sec2 == 0.03
tref2.canceled = True
tref2()
assert t.schedule.enter_after.call_count == 2
finally:
t.stop()
@patch('ko | mbu.asynchronous.timer.logger')
def test_apply_entry_error_handled(self, logger):
t = Timer()
t.schedule.on_error = None
fun = Mock()
fun.side_effect = ValueError()
t.schedule.apply_entry(fun)
logger.error.assert_called()
def test_apply_entry_error_not_handled(... |
pmacosta/pexdoc | docs/support/pcontracts_example_3.py | Python | mit | 2,517 | 0.000397 | # pcontracts_example_3.py
# Copyright (c) 2013-2019 Pablo Acosta-Serafini
# See LICENSE for details
# pylint: disable=C0111,C0410,W0613,W0702
from __future__ import print_function
import os, pexdoc.pcontracts
@pexdoc.pcontracts.new_contract(ex1=(RuntimeError, "Invalid name"))
def custom_contract1(arg):
if not ar... | .pcontracts.new_contract((OSError, "File could not be opened"))
def custom_contract7(arg):
if not arg:
raise ValueError(pexdoc.pcontracts.get_exdesc())
@pexdoc.pcontracts.new_contract("Invalid name")
def custom_contract8(arg):
if not arg:
raise ValueError(pexdoc.pcontracts.get_exdesc())
@pex... | .get_exdesc())
@pexdoc.pcontracts.new_contract()
def custom_contract10(arg):
if not arg:
raise ValueError(pexdoc.pcontracts.get_exdesc())
@pexdoc.pcontracts.new_contract(
(TypeError, "Argument `*[argument_name]*` has to be a string")
)
def custom_contract11(city):
if not isinstance(city, str):
... |
lovelysystems/pyjamas | examples/timesheet/ApplicationConstants.py | Python | apache-2.0 | 951 | 0.023134 |
# vim: set ts=4 sw=4 expandtab:
class Notification(object):
STARTUP = "startup"
SHOW_DIALOG = "showDialog"
HELLO = "hello"
# | Menu
MENU_FILE_OPEN = "menuFileOpen"
MENU_FILE_SAVEAS = "menuFileSaveAs"
MENU_FILE_PREFS = "menuFilePreferences"
MENU_VIEW_EDIT = "menuViewEdit"
MENU_VIEW_SUM = "menuViewS | ummary"
MENU_HELP_CONTENTS = "menuHelpContents"
MENU_HELP_ABOUT = "menuHelpAbout"
FILE_LOADED = "fileLoaded"
EDIT_SELECTED = "editMode"
SUM_SELECTED = "summaryMode"
# Date picker
DISPLAY_DAY = "displayDay"
PREV_DAY = "previousDay"
NEXT_D... |
KrzysztofMadejski/volontulo | apps/volontulo/utils.py | Python | mit | 2,269 | 0 | # -*- coding: utf-8 -*-
u"""
.. module:: utils
"""
from django.contrib.admin.models import LogEntry
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.shortcuts import get_object_or_404
from django.shortcuts import redirect
from django.utils.text import s... | s history."""
LogEntry.objects.log | _action(
user_id=req.user.pk,
content_type_id=ContentType.objects.get_for_model(obj).pk,
object_id=obj.pk,
object_repr=str(obj),
action_flag=action
)
def correct_slug(model_class, view_name, slug_field):
u"""Decorator that is reposponsible for redirect to url with corre... |
racheliel/My-little-business | MyLittleBuisness/web/pages/page.py | Python | mit | 648 | 0.018519 | from google.appengine.ext.webapp import template
from models.user import User
from models.page import Page
import webapp2
import json
class PageHandler(webapp2.RequestHandler):
def get(self, page_ | id):
template_params = {}
user = None
if self.request.cookies.get('session'):
user = User.chec | kToken(self.request.cookies.get('session'))
if not user:
self.redirect('/')
page = Page.getPageUser(user,title)
if page:
html = template.render("web/templates/page.html", template_params)
self.response.write(html)
app = webapp2.WSGIApplication([
('/pages/(.*)', PageHan... |
lpsinger/astropy | astropy/coordinates/tests/test_angles.py | Python | bsd-3-clause | 35,759 | 0.001064 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Test initalization and other aspects of Angle and subclasses"""
import threading
import warnings
import numpy as np
import pytest
from numpy.testing import assert_allclose, assert_array_equal
import astropy.units as u
from ast... | eld Angle.
# (a9 is regression test for #5327)
a8 = a1 + 1.*u.deg
assert type(a8) is Angle
a9 = 1.*u.deg + a1
assert type(a9) is Angle
with pytest.raises(TypeError):
a6 *= a5
with pytest.raises(TypeError):
a6 *= u.m
with pytest.raises(TypeError):
np.sin(a6, out... | which caused problems before: #8368
a = Angle([0., 2.], 'deg')
a_mean = a.mean()
assert type(a_mean) is Angle
assert a_mean == 1. * u.degree
a_std = a.std()
assert type(a_std) is Angle
assert a_std == 1. * u.degree
a_var = a.var()
assert type(a_var) is u.Quantity
assert a_var == ... |
stoqs/stoqs | stoqs/loaders/CANON/loadCN13ID_october2013.py | Python | gpl-3.0 | 11,697 | 0.010088 | #!/usr/bin/env python
__author__ = 'Mike McCann,Duane Edgington,Reiko Michisaki'
__copyright__ = '2013'
__license__ = 'GPL v3'
__contact__ = 'mccann at mbari.org'
__doc__ = '''
Master loader for all Worden's CN13ID Western Flyer cruise in October 2013
CN13ID: CANON 2013 Interdisciplinary
Mike McCann
MBARI 23 ... | iption = 'Warden cruise on Western Flyer into the California Current System off Monterey Bay',
x3dTerrains = {
'https://stoqs.mbari. | org/x3d/Globe_1m_bath_10x/Globe_1m_bath_10x_scene.x3d': {
'position': '14051448.48336 -15407886.51486 6184041.22775',
'orientation': '0.83940 0.33030 0.43164 1.44880',
'centerOfRotation': '0 0 0',
... |
townboy/coil | solver.py | Python | mit | 9,646 | 0.005183 | #!/usr/bin/env python
# -*- utf-8 -*-
import re
import copy
import time
# This is const data
direct = ['u', 'r', 'd', 'l']
direct_vector = [{'x' : -1, 'y' : 0},
{'x' : 0, 'y' : 1},
{'x' : 1, 'y' : 0},
{'x' : 0, 'y' : -1}]
def calculateNum(i, f, y):
return i * y + f
def is_empty_not_chang... | return fill, False
# just fit small 100 hash
def hash_function(map_data, x, y):
response = 0
for i in range(map_data['x']):
for f in range(map_data['y']):
response *= 2
if map_data['map'][i][f]:
response += 1
response = response * 100 + x
response = re... | += 1
fill, is_continue = get_must_info(copy.deepcopy(map_use_dfs), x, y)
if 0 == fill:
return path
if not is_continue:
return 'no solution'
hash_code = hash_function(map_use_dfs, x, y)
if hash_code in hash_table:
return 'no solution'
... |
ArcherSys/ArcherSys | Lib/test/test_plistlib.py | Python | mit | 63,176 | 0.003134 | <<<<<<< HEAD
<<<<<<< HEAD
# Copyright (C) 2003-2013 Python Software Foundation
import unittest
import plistlib
import os
import datetime
import codecs
import binascii
import collections
import struct
from test import support
from io import BytesIO
ALL_FORMATS=(plistlib.FMT_XML, plistlib.FMT_BINARY)
# The testdata is... | dmRITWdiMllnWW1sdVlYSjVJR2QxYm1zK0FBRUNBdz09Cgk8L2RhdGE+Cgk8
a2V5PsOFYmVucmFhPC9rZXk+Cgk8c3RyaW5nPlRoYXQgd2FzIGEgdW5pY29k
ZSBrZXkuPC9zdHJpbmc+CjwvZGljdD4KPC9wbGlzdD4K'''),
plistlib.FMT_BINARY: binascii | .a2b_base64(b'''
YnBsaXN0MDDfEBABAgMEBQYHCAkKCwwNDg8QERITFCgpLzAxMjM0NTc2OFdh
QmlnSW50WGFCaWdJbnQyVWFEYXRlVWFEaWN0VmFGbG9hdFVhTGlzdF8QD2FO
ZWdhdGl2ZUJpZ0ludFxhTmVnYXRpdmVJbnRXYVN0cmluZ1thbkVtcHR5RGlj
dFthbkVtcHR5TGlzdFVhbkludFpuZXN0ZWREYXRhWHNvbWVEYXRhXHNvbWVN
b3JlRGF0YWcAxQBiAGU... |
yufeldman/arrow | python/pyarrow/tests/test_tensor.py | Python | apache-2.0 | 4,521 | 0 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | or.from_numpy(data)
tensor2 = pa.Tensor.fr | om_numpy(np.ascontiguousarray(data))
eq(tensor1, tensor2)
data = data.copy()
data[9, 0, 0] = 1.0
tensor2 = pa.Tensor.from_numpy(np.ascontiguousarray(data))
ne(tensor1, tensor2)
def test_tensor_hashing():
# Tensors are unhashable
with pytest.raises(TypeError, match="unhashable"):
ha... |
AloneRoad/waskr | waskr/tests/test_database.py | Python | mit | 5,538 | 0.016071 | import unittest
from time import strftime, time, gmtime
from pymongo import Connection
from waskr.database import Stats
config = {
'db_engine': 'mongodb',
'db_host': 'localhost',
'db_port': 27017,
}
class TestDatabase(unittest.TestCase):
def __init__(self, *args, **params):
... | skr['stats']
self.users = self.waskr['user']
self.db = Stats(config, test=True)
self.single_stat = dict(
time = 9999,
respon | se = 9999,
url = '/',
application = 'foo',
server_id = '1'
)
def setUp(self):
"""Creates a new empty database for testing"""
connection = Connection(
config['db_host'],
config['db_port'])
waskr ... |
mapado/CatchMemeAll | twitter_server.py | Python | apache-2.0 | 763 | 0.002621 | import tweepy
import os
from flask import Flask, make_response, jsonify
CONSUMER_KEY = os.environ['CATCHMEMEAL | L_TWITTER_CONSUMER_TOKEN']
CONSUMER_SECRET = os.environ['CATCHMEMEALL_TWITTER_CONSUMER_SECRET']
app = Flask(__name__)
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
api = tweepy.API(auth)
@app.route('/twitter/ava | tar/<username>', methods=['GET'])
def get_user_avatar(username):
try:
user = api.get_user(username)
except tweepy.TweepError:
return make_response(jsonify({'error': 'no username %s' % (username)}), 404)
else:
json_data = {'avatar': user.profile_image_url}
return make_response... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.