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 |
|---|---|---|---|---|---|---|---|---|
bkosawa/admin-recommendation | crawler/migrations/0006_user_recommended_apps.py | Python | apache-2.0 | 455 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2017-03-25 22:15
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
de | pendencies = [
('crawler', '0005_userapps'),
]
operations = [
migrations.AddField(
m | odel_name='user',
name='recommended_apps',
field=models.ManyToManyField(to='crawler.App'),
),
]
|
scopatz/regolith | regolith/helpers/a_proprevhelper.py | Python | cc0-1.0 | 4,818 | 0.002491 | """Builder for Current and Pending Reports."""
import datetime as dt
import sys
import time
from argparse import RawTextHelpFormatter
import nameparser
from regolith.helpers.basehelper import SoutHelperBase, DbHelperBase
from regolith.dates import month_to_int, month_to_str_int
from regolith.fsclient import _id_key
f... | "pi first name space last name in quotes",
default=None)
subpi.add_argument("type", help=f"{ALLOWED_TYPES}", default=None)
subpi.add_argu | ment("due_date", help="due date in form YYYY-MM-DD")
subpi.add_argument("-d", "--database",
help="The database that will be updated. Defaults to "
"first database in the regolithrc.json file."
)
subpi.add_argument("-q", "--requester",... |
adventurerscodex/uat | components/core/character/proficiency.py | Python | gpl-3.0 | 1,561 | 0 | """Proficiency components."""
from component_objects import Component, Element
class ProficiencyAddModal(Component):
"""Definition of proficiency add modal component."""
modal_div_id = 'addProficiency'
name_id = 'proficiencyAddNameInput'
type_id = 'proficiencyAddTypeInput'
description_id = 'prof... | name_id)
type_ = Element(id_=type_id)
description = Element(id_=description_id)
done = Element(id_=done_id)
class ProficiencyModalTabs(Component):
"""Definition of profici | ency modal tabs component."""
preview_id = 'proficiencyModalPreview'
edit_id = 'proficiencyModalEdit'
preview = Element(id_=preview_id)
edit = Element(id_=edit_id)
class ProficiencyTable(Component):
"""Definition of proficiencys edit modal componenet."""
add_id = 'proficiencyAddIcon'
ta... |
bukzor/pgctl | tests/unit/cli.py | Python | mit | 950 | 0 | # -*- coding: utf-8 -*-
# pylint:disable=redefined-outer-name,unused-argument
from __future__ import absolute_import
from __future__ import unicode_literals
from testfixtures import ShouldRaise
from pgctl.cli import main
def test_start(in_example_dir):
assert main(['start']) == "No such playground service: 'def... | in_example_dir):
assert main(['status']) is None
def test_restart(in_example_dir):
assert main(['restart']) is None
def test_reload(in_example_dir):
assert main(['reload']) is None
def test_log(in_example_dir):
assert main(['log']) is None
def test_debug(in_example_dir):
assert main(['debug'... | sense'])
|
huiyiqun/check_mk | web/htdocs/mkeventd.py | Python | gpl-2.0 | 15,616 | 0.006404 | #!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# | ____ _ _ __ __ _ __ |
# | / ___| |__ ___ ___| | __ | \/ | |/ / |
# | | | | '_ \ / _ \/ __| |/ /... | eventd_configuration():
global cached_config
if cached_config and cached_config[0] is html:
return cached_config[1]
settings = cmk.ec.settings.settings('',
Path(cmk.paths.omd_root),
Path(cmk.paths.default_config_dir),
... | _config(settings)
cached_config = (html, config)
return config
def daemon_running():
return os.path.exists(socket_path)
# Note: in order to be able to simulate an original IP address
# we put hostname|ipaddress into the host name field. The EC
# recognizes this and unpacks the data correctly.
def send_e... |
brandsoulmates/incubator-airflow | airflow/operators/S3_to_FS.py | Python | apache-2.0 | 1,792 | 0 | # -*- coding: utf-8 -*-
#
# 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
... | rgs, **kwargs):
super(S3ToFileSystem, self).__init__(*args, **kwargs)
self.local_location = download_file_location
self.s3_bucket = s3_bucket
self.s3_key = s3_key
self.s3_conn_id = s3_conn_id
def | execute(self, context):
self.s3 = S3Hook(s3_conn_id=self.s3_conn_id)
file_paths = []
for k in self.s3.list_keys(self.s3_bucket, prefix=self.s3_key):
kpath = os.path.join(self.local_location, os.path.basename(k))
# Download the file
self.s3.download_file(self.s... |
vponomaryov/manila | manila_tempest_tests/tests/api/admin/test_migration_negative.py | Python | apache-2.0 | 14,208 | 0 | # Copyright 2015 Hitachi Data Systems.
# 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 req... | d(self):
self.assertRaises(
lib_exc.NotFound, self.shares_v2_client.migration_cancel,
'invalid_share_id')
@tc.attr(base.TAG_NEGATIVE, base.TAG_API_WITH_BACKEND)
@base.skip_if_microversion_lt("2.22")
def test_migration_get_progress_not_found(self):
self.assertRaises(
... | API_WITH_BACKEND)
@base.skip_if_microversion_lt("2.22")
def test_migration_complete_not_found(self):
self.assertRaises(
lib_exc.NotFound, self.shares_v2_client.migration_complete,
'invalid_share_id')
@tc.attr(base.TAG_NEGATIVE, base.TAG_API_WITH_BACKEND)
@base.skip_if_mi... |
jfsantos/neon | tests/test_costs.py | Python | apache-2.0 | 5,749 | 0.001044 | # Copyright 2015 Nervana Systems Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | ulti(),
outputs, targets, expected_result, tol=1e-5)
def test_cross_entropy_multi_derivative(backend_default):
outputs = np | .array([0.5, 1.0, 0.0, 0.0001]).reshape((4, 1))
targets = np.array(([0.5, 0.0, 1.0, 0.2])).reshape((4, 1))
expected_result = ((outputs - targets) / outputs.shape[1])
compare_tensors(CrossEntropyMulti(), outputs, targets, expected_result,
deriv=True, tol=1e-6)
"""
SumSquared
"""
de... |
rven/odoo | addons/microsoft_calendar/models/res_users.py | Python | agpl-3.0 | 5,093 | 0.003927 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
import requests
from odoo.addons.microsoft_calendar.models.microsoft_sync import microsoft_calendar_token
from datetime import timedelta
from odoo import api, fields, models, _
from odoo.exceptions import... | nfo("Calendar Synchro - Starting synchronization for %s", user)
try:
user.with_user(user).sudo()._sync_microsoft_calendar(microsoft)
except Exception as e:
_logger. | exception("[%s] Calendar Synchro - Exception : %s !", user, exception_to_unicode(e))
|
phobson/mpl-probscale | probscale/validate.py | Python | bsd-3-clause | 2,443 | 0 | from matplotlib import pyplot
from .algo import _bs_fit
def axes_object(ax):
""" Checks if a value if an Axes. If None, a new one is created.
Both the figure and axes are returned (in that order).
"""
if ax is None:
ax = pyplot.gca()
fig = ax.figure
elif isinstance(ax, pyplot.Ax... | ues.
"""
valid_args = ["x", "y", "both", None]
if arg not in valid_args:
msg = "Invalid value for {} ({}). Must be on of {}."
raise ValueError(msg.format(argname, arg, valid_args))
elif arg is not None:
arg = arg.lower()
return arg
def axis_type(a | xtype):
"""
Checks that a valid axis type is requested.
- *pp* - percentile axis
- *qq* - quantile axis
- *prob* - probability axis
Raises an error on an invalid value. Returns the lower case version
of valid values.
"""
if axtype.lower() not in ["pp", "qq", "prob"]:
... |
Qwaz/solved-hacking-problem | sciencewar/2018/ezbt/solver.py | Python | gpl-2.0 | 990 | 0.00101 | import binascii
data = '''
D9 51 44 5C 65 D5 3D 7D C8 67 BC 68 C8 68 6F 3F
C8 64 3F 30 48 41 72 3F 75 C8 67 F4 68 48 B9 6E
7C C8 7F 3C 74 5C 74 3C 74 3C 5C 3C 74 3C 5C 77
48 FE E8 67 C8 49 48 48 48 48 48 48 48 48 48 48
71 43 00 00 00 00 00 00
'''
data = data.replace(' ', '')
data = data.replace('\n', '')
data = l... | range(bitsize):
diff.append(val & 1)
val = val >> 1
last = 0
acc = 0
for i in range(bitsize - 1, -1, -1):
now = last ^ diff[i]
acc = (acc << 1) ^ now
last = now
return acc
length = len(data)
for i in range(0, length-8, 8):
acc = 0
shift = 0
for j i... | << shift
shift += 8
acc = unbit(acc, 8 * 8)
for j in range(8):
data[i+j] = acc & 0xFF
acc = acc >> 8
for i in range(length):
data[i] = unbit(data[i])
print ''.join(map(chr, data))
|
Pardus-Linux/pds | pds/tests/test-pds.py | Python | gpl-2.0 | 2,879 | 0.003128 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Pardus Desktop Services Test-Suit
# Copyright (C) 2010, TUBITAK/UEKAE
# 2010 - Gökmen Göksel <gokmen:pardus.org.tr>
# 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
# Softw... | ComboBox(Test)
self.name.setObjectName("name")
self.name.setEditable(True)
self.gridLayout.addWidget(self.name, 0, 0, 1, 1)
self.size = QtGui.QComboBox(Test)
self.size.setObjectName("size")
self.size.setMaximumSize(QtCore.QSize(100, 16777215))
self.size.addItem("1... | size.addItem("48")
self.size.addItem("32")
self.size.addItem("22")
self.size.addItem("16")
self.gridLayout.addWidget(self.size, 0, 1, 1, 1)
self.getButton = QtGui.QPushButton(Test)
self.getButton.setText("Get Icon")
self.getButton.setMaximumSize(QtCore.QSize(100, ... |
overxfl0w/Grampus-Forensic-Utils | Metadata/Documents/OpenOffice/cleanopenoffi.py | Python | gpl-2.0 | 4,193 | 0.00787 | from tempfile import mkdtemp
from zipfile import ZipFile, is_zipfile
from shutil import rmtree, copyfileobj
from xml.dom.minidom import parse
import os
class cleanopenoffi():
def __init__(self, sDocName, newDocName):
self.sDocName = sDocName
self.newDocName = newDocName
self._ms_do()
def _m... | another_node.setAttribute('config:name', str(''))
except:
print "An error has ocurred, but not is very important, you can continue"
j = open(os.path.join('settings.xml'), 'w')
settings.writexml(j)
j.close()
"""
def __compress(self):
... | pFile(self.newDocName, 'w')
for item in zf.infolist():
try:
#triying to write a new document without meta,content & settings .xml
buffer = zf.read(item.filename)
if (item.filename[-8:] != 'meta.xml') and (item.filename[-11:] != 'content.xml') and (ite... |
smartdevicelink/sdl_ios | generator/transformers/structs_producer.py | Python | bsd-3-clause | 1,726 | 0.001738 | """
Structs transformer
"""
import logging
from collections import OrderedDict
from model.struct import Struct
from transformers.common_producer import InterfaceProducerCommon
class StructsProducer(InterfaceProducerCommon):
"""
Structs transformer
"""
def __init__(self, struct_class, enum_names, st... | '].add(self.struct_class)
if not render:
render = OrderedDict()
render['origin'] = item.name
| render['name'] = name
render['extends_class'] = self.struct_class
render['imports'] = imports
render['history'] = item.history
super(StructsProducer, self).transform(item, render)
return render
|
WoodNeck/tataru | test/__init__.py | Python | mit | 64 | 0.015625 | import sys
import | os
sys.path.append(os.path.ab | spath(os.curdir)) |
kadhikari/navitia | source/tyr/tests/integration/users_test.py | Python | agpl-3.0 | 24,886 | 0.002572 | # coding: utf-8
# Copyright (c) 2001-2018, Canal TP and/or its affiliates. All rights reserved.
#
# This file is part of Navitia,
# the software to build cool stuff with public transport.
#
# powered by Canal TP (www.canaltp.fr).
# Help us simplify mobility and open public transport:
# a non ending quest to... | # the Free Software Foundation, either ve | rsion 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# Y... |
ajinabraham/Nosql-Exploitation-Framework | dbattacks/mongoattacks.py | Python | bsd-3-clause | 11,573 | 0.003111 | # Mongo Attack file
import threading
import pymongo
from pymongo import MongoClient
from termcolor import colored
from dbattacks.utils import screenshot
import requests
global passfound
def mongo_conn(target, port=27017, mass=False):
"""
Establishes Connection with MongoDB and Determines whether alive or no... | For NoSQL Framework Launched .. \n", 'blue')
conn = MongoClient(target, port)
try:
db = conn[db] # Use admin by Default
file = open(file_name, "r")
lines = file.read().split('\n')
for names in lines:
# s1 = names
t1 = threading.Thread( | target=tryandgetpass, args=(db, names))
t1.start()
if passfound:
print colored(passfound, 'green')
else:
print colored("[-] Password Not found in the File Specified", 'red')
except Exception, e:
print colored(str(e), 'red')
# Module to try mongo authentic... |
chienlieu2017/it_management | odoo/addons/event_sale/models/event.py | Python | gpl-3.0 | 7,511 | 0.005059 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
import odoo.addons.decimal_precision as dp
class Event(models.Model):
_inherit = 'event.event'
def _default_tickets(self):
... | def _check_auto_confirmation(self):
res = super(EventRegistration, self)._check_auto_c | onfirmation()
if res:
orders = self.env['sale.order'].search([('state', '=', 'draft'), ('id', 'in', self.mapped('sale_order_id').ids)], limit=1)
if orders:
res = False
return res
@api.model
def create(self, vals):
res = super(EventRegistration, se... |
rafaelvalle/MDI | nnet_lasagne.py | Python | mit | 10,609 | 0.000189 | # code adapted from lasagne tutorial
# http://lasagne.readthedocs.org/en/latest/user/tutorial.html
import time
import os
from itertools import product
import numpy as np
from sklearn.cross_validation import KFold
import theano
from theano import tensor as T
import lasagne
from params import nnet_params_dict, feats_tra... | rops = nnet_params_dict['drops']
# Dictionary to store results
results_dict = {}
params_mat = [x for x in product(alphas, gammas, batch_sizes)]
params_mat = np.array(params_mat, dtype=theano.config.floatX)
params_mat = np.column_stack((param | s_mat,
zerosX(params_mat.shape[0]),
zerosX(params_mat.shape[0]),
zerosX(params_mat.shape[0])))
for param_idx in xrange(params_mat.shape[0]):
# load parameters for neural network model
... |
jennywoites/MUSSA | MUSSA_Flask/manage.py | Python | gpl-3.0 | 879 | 0.003413 | """This file sets up a command line manager.
Use "python manage.py" for a list of available commands.
Use "python manage.py runserver" to start the development web server on localhost:5000.
Use "python manage.p | y runserver --help" for additional runserver options.
"""
from flask_migra | te import MigrateCommand
from flask_script import Manager, commands
from app import create_app
from app.commands import InitDbCommand
# Setup Flask-Script with command line commands
manager = Manager(create_app)
manager.add_command('db', MigrateCommand)
manager.add_command('init_db', InitDbCommand)
manager.add_comman... |
OphidiaBigData/ophidia-wps-module | processes/__init__.py | Python | gpl-3.0 | 740 | 0.001351 | #
# Ophidia WPS Module
# Copyright (C) 2015-2021 CMCC Foundation
#
# 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 So | ftware Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General P... | d have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
|
tonghuashuai/OnlyBoard | controller/_url.py | Python | mit | 68 | 0 | #!/usr/bin/env python
# | -*- coding: utf-8 -*-
import root
import j | |
Zardinality/TF_Deformable_Net | lib/datasets/pascal3d.py | Python | mit | 30,673 | 0.003293 | # --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
import xml.dom.minidom as minidom
import os
import PIL
import numpy as... | # Example path to image set file:
# self._pascal3d_path + /VOCdevkit2012/VOC2012/ImageSets/Main/val.txt
image_set_file = os.path.join(self._data_path, 'ImageSets', 'Main',
self._image_set + '.txt')
assert os.path.exists(image_s | et_file), \
'Path does not exist: {}'.format(image_set_file)
with open(image_set_file) as f:
image_index = [x.strip() for x in f.readlines()]
return image_index
def _get_default_path(self):
"""
Return the default path where PASCAL3D is expected to be inst... |
kreativitea/RandomData | utils.py | Python | mit | 739 | 0.005413 | import os
import json
try:
import yaml
except ImportError:
yaml = None
def r | oot():
''' Assuming that this function is in root.utils, returns the root directory
of the | project. '''
path, _ = os.path.split(__file__)
return os.path.abspath(path)
def loadfile(filename, _format=None):
''' Loads a file at a particular `filename` location. '''
with open(filename) as file:
data = file.read()
if not _format:
return data
elif _format=='json':
... |
wwitzel3/awx | awx/main/tests/functional/api/test_job.py | Python | apache-2.0 | 9,725 | 0.003496 | # Python
import pytest
import mock
from dateutil.parser import parse
from dateutil.relativedelta import relativedelta
from crum import impersonate
import datetime
# Django rest framework
from rest_framework.exceptions import PermissionDenied
from django.utils import timezone
# AWX
from awx.api.versioning import rever... | dmin_user):
job_template | = JobTemplate.objects.create(
project=project,
playbook='helloworld.yml'
)
time_of_finish = parse("Thu Feb 23 14:17:24 2012 -0500")
Job.objects.create(
emitted_events=1,
status='finished',
finished=time_of_finish,
job_template=job_template,
project=pro... |
pepsipepsi/nodebox_opengl_python3 | examples/10-gui/05-layout.py | Python | bsd-3-clause | 3,183 | 0.004713 | import os, sys
sys.path.insert(0, os.path.join("..",".."))
from nodebox.graphics impor | t *
from nodebox.gui.controls import *
# Comparison between Rows and Row containers.
# Both are subclasses of Layout.
# Panel 1
# Controls in a Rows layout are drawn below each other.
# Rows.width defines the width of all controls (individual width is ignored).
# Note how the second Field has a height and | wrap=True,
# which makes it a multi-line field with text wrapping.
panel1 = Panel("Panel 1", x=30, y=350)
panel1.append(
Rows([
Field(value="", hint="subject"),
Field(value="", hint="message", height=70, id="field_msg1", wrap=True),
Button("Send"),
], width=200)
)
panel1.pack()
# Panel... |
libyal/libesedb | tests/pyesedb_test_file.py | Python | lgpl-3.0 | 5,223 | 0.006701 | #!/usr/bin/env python
#
# Python-bindings file type test script
#
# Copyright (C) 2009-2021, Joachim Metz <[email protected]>
#
# Refer to AUTHORS for acknowledgements.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as publishe... | f_tables function and number_of_tables property."""
test_source = unittest.source
if not test_source:
raise unittest.SkipTest("missing source")
esedb_file = pyesedb.file()
esedb_file.open(test_source)
number_of_tables = esedb_file.get_number_of_tables()
self.as | sertIsNotNone(number_of_tables)
self.assertIsNotNone(esedb_file.number_of_tables)
esedb_file.close()
if __name__ == "__main__":
argument_parser = argparse.ArgumentParser()
argument_parser.add_argument(
"source", nargs="?", action="store", metavar="PATH",
default=None, help="path of the sour... |
trilan/lemon-publications | publications/feeds.py | Python | isc | 334 | 0 | from django.contrib.syndication.views import Feed
from django.utils import feedgenerator
class PublicationFeed(Feed):
model = None
feed_type = | feedgenerator.Rss201rev2Feed
def items(self):
return self.model.objects.published()[:10]
def item_pubdat | e(self, item):
return item.publication_start_date
|
deapplegate/wtgpipeline | warp_the_pickle_new.py | Python | mit | 33,252 | 0.022735 | #!/usr/bin/env python
import sys, glob,astropy, astropy | .io.fits as pyfits, os.path
#from numpy import *
import scipy
import scipy.interpolate.interpolate as interp
#from readtxtfile import readtxtfile
#from optparse import OptionParser
c = 299792458e10 #Angstroms/s
def get_sdss_spectra(gmi,umg,gmr,imz,number=4,tol=0.01,S_N=5):
import sqlcl
dict_names = ['plat... | ', 'mag_1', 'mag_2']
#query = 'select top ' + str(number) + ' ' + reduce(lambda x,y: x + ',' + y, ['s.' + x for x in dict_names]) + ' from specobjall as s join specphotoall as p on s.specobjid = p.specobjid where abs(s.mag_0 - s.mag_1 - ' + str(gmr) + ') < ' + str(tol) + ' and abs(s.mag_1 - s.mag_2 - ' + str(rmi) +... |
akuks/pretix | src/pretix/control/views/main.py | Python | apache-2.0 | 2,498 | 0 | from django.conf import settings
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.shortcuts import render
from django.utils.translation import ugettext_lazy as _
from django.views.generic import CreateView, ListView, TemplateView
from pretix.base.models import Event, EventPe... | act=self.request.user.pk
).prefetch_related(
"organizer",
)
def index(request):
return render(request, 'pretixcontrol/dashboard.html', {})
class EventCreateStart(TemplateView):
template_name = 'pretixcontrol/events/start.html'
def get_context_data(self, **kwargs):
ct... | ata(**kwargs)
ctx['organizers'] = [
p.organizer for p in OrganizerPermission.objects.current.filter(
user=self.request.user, can_create_events=True
).select_related("organizer")
]
return ctx
class EventCreate(OrganizerPermissionRequiredMixin, CreateView)... |
IPVL/Tanvin-PythonWorks | chapter5/codes/forLoop.py | Python | mit | 353 | 0.016997 | #! / | usr/bin/env python
# example of for loop
words = ['this', 'is', 'an', 'ex', 'parrot']
for word in words:
print word,
print '\n'
# example of for loop in dictionary
d = {'x': 1, 'y': 2, 'z': 3}
for key in d:
print key, 'corresponds to', d[key]
# additional sequence unpacking in for loop
for key, value in d.ite... | ue |
tudorvio/tempest | tempest/api/compute/servers/test_servers_negative.py | Python | apache-2.0 | 21,412 | 0 | # Copyright 2012 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | overning permissions and limitations
# under the License.
import sys
from tempest_lib import exceptions as lib_exc
import testtools
from tempest.api.compute import base
from tempest.common.utils import data_utils
from tempest.common import waiters
from tempe | st import config
from tempest import test
CONF = config.CONF
class ServersNegativeTestJSON(base.BaseV2ComputeTest):
credentials = ['primary', 'alt']
def setUp(self):
super(ServersNegativeTestJSON, self).setUp()
try:
waiters.wait_for_server_status(self.client, self.server_id,
... |
Dhivyap/ansible | lib/ansible/modules/cloud/ovirt/ovirt_host_info.py | Python | gpl-3.0 | 4,875 | 0.002667 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016 Red Hat, Inc.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUME... | ern: name=host* and datacenter=west
register: result
- debug:
msg: "{{ result.o | virt_hosts }}"
# All hosts with cluster version 4.2:
- ovirt_host_info:
pattern: name=host*
cluster_version: "4.2"
register: result
- debug:
msg: "{{ result.ovirt_hosts }}"
'''
RETURN = '''
ovirt_hosts:
description: "List of dictionaries describing the hosts. Host attributes are mapped to dictionary ... |
T3CHNOLOG1C/Plaidohlect | MusicBot/musicbot/bot.py | Python | apache-2.0 | 78,817 | 0.00373 | import os
import sys
import time
import shlex
import shutil
import inspect
import aiohttp
import discord
import asyncio
import traceback
from discord import utils
from discord.object import Object
from discord.enums import ChannelType
from discord.voice_client import VoiceClient
from discord.ext.commands.bot import _g... | Add some sort of `denied` | argument for a message to send when someone else tries to use it
def owner_only(func):
@wraps(func)
async def wrapper(self, *args, **kwargs):
# Only allow the owner to use these commands
orig_msg = _get_variable('message')
if not orig_msg or orig_msg.author.id ==... |
skoslowski/gnuradio | grc/core/blocks/embedded_python.py | Python | gpl-3.0 | 8,172 | 0.000857 | # Copyright 2015-16 Free Software Foundation, Inc.
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-2.0-or-later
#
from __future__ import absolute_import
from ast import literal_eval
from textwrap import dedent
from . import Block, register_build_in
from ._templates import MakoTemplates
from .. imp... | ation = {
| "": dedent(
"""
This block lets you embed a python module in your flowgraph.
Code you put in this module is accessible in other blocks using the ID of this
block. Example:
If you put
a = 2
def double(arg):
return 2 * arg
... |
abramhindle/UnnaturalCodeFork | python/testdata/launchpad/lib/lp/registry/tests/test_oopsreferences.py | Python | agpl-3.0 | 7,128 | 0.001263 | # Copyright 2009-2011 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
"""Tests of the oopsreferences core."""
__metaclass__ = type
from datetime import (
datetime,
timedelta,
)
from pytz import utc
from lp.registry.model.oopsrefe... | = (
"foo https://lp-oops.canonical.com/oops.py?oopsid=%s bar"
% oopsid_old)
with person_logged_in(bug_new.owner):
bug_new.description = (
"foo https: | //oops.canonical.com/oops.py?oopsid=%s bar"
% oopsid_new)
self.store.flush()
now = datetime.now(tz=utc)
day = timedelta(days=1)
self.failUnlessEqual(
set([oopsid_old, oopsid_new]),
referenced_oops(now - day, now, "product=1", {}))
self.fail... |
jupyterhub/kubespawner | kubespawner/spawner.py | Python | bsd-3-clause | 109,371 | 0.002076 | """
JupyterHub Spawner to spawn user notebooks on a Kubernetes cluster.
This module exports `KubeSpawner` class, which is the actual spawner
implementation that should be used by JupyterHub.
"""
import asyncio
import os
import signal
import string
import sys
import warnings
from functools import partial
from functools... | efore we start the reflectors, so this must run before
# watcher start in normal execution. We still want to get the
# namespace right for test, though, so we need self.user to have
# been set in order to do that.
# By now, all the traitlets have been set, so we can use them to
... | .info("Using user namespace: {}".format(self.namespace))
self.pod_name = self._expand_user_properties(self.pod_name_template)
self.dns_name = self.dns_name_template.format(
namespace=self.namespace, name=self.pod_name
)
self.secret_name = self._expand_user_properties(self.se... |
ToonTownInfiniteRepo/ToontownInfinite | otp/ai/MagicWordManagerAI.py | Python | mit | 1,950 | 0.004615 | from direct.directnotify import DirectNotifyGlobal
from direct.distributed.DistributedObjectAI import DistributedObjectAI
from otp.ai.MagicWordGlobal import *
from direct.distributed.PyDatagram import PyDatagram
from direct.distributed.MsgTypes import *
class MagicWordManagerAI(DistributedObjectAI):
notify = Direc... | ),
targetId, target.getAdminAccess(),
wor | d, response)
|
alanmcruickshank/superset-dev | tests/security_tests.py | Python | apache-2.0 | 7,916 | 0.000126 | from superset import security, sm
from .base_tests import SupersetTestCase
def get_perm_tuples(role_name):
perm_set = set()
for perm in sm.find_role(role_name).permissions:
perm_set.add((perm.permission.name, perm.view_menu.name))
return perm_set
class RolePermissionTests(SupersetTestCase):
... | sm.find_permission_view_menu(
'can_edit', 'UserDBModelView')))
self.assertTrue(security.is_admin_only(
sm.find_permission_view_menu(
'can_approve', 'Superset')))
self.assertTrue(security.is_admin_only(
sm.find_permission_view_menu(
... | ))
def test_is_alpha_only(self):
self.assertFalse(security.is_alpha_only(
sm.find_permission_view_menu('can_show', 'TableModelView')))
self.assertTrue(security.is_alpha_only(
sm.find_permission_view_menu('muldelete', 'TableModelView')))
self.assertTrue(security.is_a... |
SatelliteQE/robottelo | tests/upgrades/test_usergroup.py | Python | gpl-3.0 | 3,681 | 0.002173 | """Test for User Group related Upgrade Scenario's
:Requirement: UpgradedSatellite
:CaseAutomation: Automated
:CaseLevel: Acceptance
:CaseComponent: UsersRoles
:Assignee: sganar
:TestType: Functional
:CaseImportance: High
:Upstream: No
"""
import pytest
from nailgun import entities
from nailgun.config import Ser... | pre_create_usergroup_with_ldap_user)
def test_post_verify_usergroup_membership(self, request, dependent_scenario_name):
| """After upgrade, check the LDAP user created before the upgrade still exists and its
update functionality should work.
:id: postupgrade-7545fc6a-bd57-4403-90c8-c68a7a3b5bca
:steps:
1. verify ldap user(created before upgrade) is part of user group.
2. Update ldap aut... |
oinopion/hurl | setup.py | Python | bsd-3-clause | 827 | 0 | from distutils.core import setup
from os import path
ROOT = path.dirname(__file__)
README = path.join(ROOT, 'README.rst')
setup(
name='hurl',
py_modules=['hurl'],
url=' | https://github.com/oinopion/hurl',
author='Tomek Paczkowski & Aleksandra Sendecka',
author_email='[email protected]',
version='2.1',
license='New BSD License',
long_description=open(README).read(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Envi... | 'Operating System :: OS Independent',
'Framework :: Django',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
],
)
|
chrisfilo/NeuroVault | neurovault/apps/statmaps/migrations/0027_auto_20150220_0305.py | Python | mit | 1,314 | 0.001522 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('statmaps', '0026_populate_cogatlas'),
]
operations = [
migrati | ons.AddField(
model_name='statisticmap',
name='cognitive_paradigm_cogatlas',
field=models.CharField(help_text=b"Task (or lack of it) performed by the subjects in the scanner described using <a href='http://www.cognitiveatlas.org/'>Cognitive Atlas</a> terms", max_length=200, null=True... | ality',
field=models.CharField(help_text=b'Brain imaging procedure that was used to acquire the data.', max_length=200, verbose_name=b'Modality & Acquisition Type', choices=[(b'fMRI-BOLD', b'fMRI-BOLD'), (b'fMRI-CBF', b'fMRI-CBF'), (b'fMRI-CBV', b'fMRI-CBV'), (b'Diffusion MRI', b'Diffusion MRI'), (b'Structu... |
dshulyak/solar | solar/solar/cli/system_log.py | Python | apache-2.0 | 2,234 | 0.000895 |
import sys
import click
from solar.core import testing
from solar.core import resource
from solar.system_log import change
from solar.system_log import operations
from solar.system_log import data
from solar.cli.uids_history import get_uid, remember_uid, SOLARUID
@click.group()
def changes():
pass
@changes.c... | turn
commited.reverse()
click.echo(commited)
@changes.command()
def test():
results = testing.test_all()
for name, result in results.items():
msg = '[{status}] {name} {message}'
kwargs = {
'name': name,
'message': '',
'status': 'OK',
}
... | = click.style('OK', fg='green')
else:
kwargs['status'] = click.style('ERROR', fg='red')
kwargs['message'] = result['message']
click.echo(msg.format(**kwargs))
@changes.command(name='clean-history')
def clean_history():
data.CL().clean()
data.CD().clean()
|
tzpBingo/github-trending | codespace/python/tencentcloud/iai/v20200303/iai_client.py | Python | mit | 65,319 | 0.002484 | # -*- coding: utf8 -*-
# Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. 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... | = 'iai'
def AnalyzeDenseLandmarks(self, request):
"""对请求图片进行五官定位(也称人脸关键点定位),获得人脸的精准信息,返回多达888点关键信息,对五官和脸部轮廓进行精确定位。
:param request: Request instance for AnalyzeDenseLandmarks.
:type request: :class:`tencentcloud.iai.v20200303.models.AnalyzeDenseLandmarksR | equest`
:rtype: :class:`tencentcloud.iai.v20200303.models.AnalyzeDenseLandmarksResponse`
"""
try:
params = request._serialize()
body = self.call("AnalyzeDenseLandmarks", params)
response = json.loads(body)
if "Error" not in response["Response"]:
... |
yceruto/django | django/utils/termcolors.py | Python | bsd-3-clause | 7,357 | 0.00068 | """
termcolors.py
"""
from django.utils import six
color_names = ('black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white')
foreground = dict((color_names[x], '3%s' % x) for x in range(8))
background = dict((color_names[x], '4%s' % x) for x in range(8))
RESET = '0'
opt_dict = {'bold': '1', 'underscore':... | The first instruction c | an contain a slash
# to break apart fg/bg.
colors = styles.pop().split('/')
colors.reverse()
fg = colors.pop()
if fg in color_names:
definition['fg'] = fg
if colors and colors[-1] in color_names:
definition['bg'] = c... |
Always0806/GPIOTableGen | Util.py | Python | gpl-3.0 | 4,608 | 0.059245 | # encoding: utf-8
import sys
import os
import signal
from openpyxl.utils import get_column_letter
from openpyxl import Workbook,load_workbook
ItemList=[]
## {{{ http://code.activestate.com/recipes/410692/ (r8)
# This class provides the functionality we want. You only need to look at
# this if you want to know how thi... | lToStruct(filename):
try:
wb = load_workbook(filename)
except IOError:
print ("Can't open file exit")
sys.exit(0)
ws = wb.active
index_row=2
print ("clear All data in excel")
tmp_row=index_row
while True:
BallName=ws[GetColumnLetter(ws,1,'BallName')+str(tmp_row)].value
if BallName==None:
break;
... | (tmp_row)]:
for cell in row:
cell.value = None
tmp_row = tmp_row+1;
while True:
BallName=ws[GetColumnLetter(ws,1,'BallName')+str(index_row)].value
if BallName==None:
break;
GPIOPPin=ws[GetColumnLetter(ws,1,'GPIO')+str(index_row)].value
if GPIOPPin!=None:
ItemList.append(Items(BallName,GPIO... |
wkerzendorf/tardis | tardis/plasma/properties/property_collections.py | Python | bsd-3-clause | 1,533 | 0.00848 | from tardis.plasma.properties import *
class PlasmaPropertyCollection(list):
pass
basi | c_inputs = PlasmaPropertyCollection([TRadiative, Abundance, Density,
TimeExplosion, AtomicData, JBlues, DilutionFactor, LinkTRadTElectron,
RadiationFieldCorrectionInput, NLTESpecies, PreviousBetaSobolev,
PreviousElectronDensities])
basic_properties = PlasmaPropertyCollection([BetaRadiation,
Levels, Line... | ndex,
LinesUpperLevelIndex, TauSobolev, LevelNumberDensity, IonNumberDensity,
StimulatedEmissionFactor, SelectedAtoms, ElectronTemperature])
lte_ionization_properties = PlasmaPropertyCollection([PhiSahaLTE])
lte_excitation_properties = PlasmaPropertyCollection([LevelBoltzmannFactorLTE])
macro_atom_properties = ... |
cmusatyalab/elijah-openstack | client/cloudlet_client.py | Python | apache-2.0 | 36,615 | 0.000819 | #!/usr/bin/env python
# Elijah: Cloudlet Infrastructure for Mobile Computing
#
# Author: Kiryong Ha <[email protected]>
#
# Copyright (C) 2011-2014 Carnegie Mellon University
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You m... | str(requested_basevm_id)
raise CloudletClientError(msg)
cpu_count, memory_mb = get_resource_size(basevm_xml)
flavor_list = get_list(server_address, token, end_point, "flavors")
flavor_ref, flavor_id = find_matching_flavor(flavor_list, cpu_count,
memor... | == None:
msg = "Cannot find matching flavor: vcpu (%d), ram (%d MB), disk (%d GB)\n" % (
cpu_count, memory_mb, basevm_disk)
msg += "Please create the matching at your OpenStack"
raise CloudletClientError(msg)
# generate request
meta_data = {"overlay_url": overlay_url}
s... |
weissj3/MWTools | Scripts/MakeTableResultsandErrors.py | Python | mit | 1,034 | 0.005803 | import sys
params = open(sys.argv[1], 'r')
errors = open(sys.argv[2], 'r')
error = []
for line in errors:
if len(line) < 5: continue
error.append(map(float, line.replace('[', '').replace(']', '').split(',')))
print error
output = []
count = 0
paramCount = 0
roundValues = [4, 2, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2... | nd(float(ln[i]), roundValues[paramCount])) + "\pm" + str(round(error[count][paramCount], roundValues[paramCount])) + "$ & "
paramCount += 1
output.append(out[0:len(out)-3])
# print out[0:len(out)-3]
if paramCount == 20:
count += 1
paramCount = 0
for i in output:
print i
wedge = r... | print str(wedge[count]) + " & " + output[j*5+i] + " \\\\"
print "\hline"
count += 1
print ""
|
tonybaloney/st2 | st2common/st2common/services/datastore.py | Python | apache-2.0 | 8,753 | 0.001828 | # Licensed to the StackStorm, Inc ('StackStorm') 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 use th... | e from a namespace local to the pack/class. Defaults to True.
:type: local: ``bool``
:param scope: Scope under which item is sa | ved. Defaults to system scope.
:type: local: ``str``
:param decrypt: Return the decrypted value. Defaults to False.
:type: local: ``bool``
:rtype: ``str`` or ``None``
"""
if scope != SYSTEM_SCOPE:
raise ValueError('Scope %s is unsupported.' % scope)
... |
cligu/compdisc | lexical_chains.py | Python | apache-2.0 | 6,335 | 0.004893 | """
lexical chain module for text tiling
"""
from tile_reader import TileReader
from scoring import boundarize, depth_scoring, window_diff
# ======================================================================================================================
# Main
# ================================================... | ues_n = set(sents[n])
intersection = uniques_i.intersection(uniques_n)
# add the intersections to all affected transitions between sent[i] and sent[i+diff]
for k in list(xrange(diff)):
| [actives[i+k].add(word) for word in intersection]
return actives
@staticmethod
def _get_boundaries(scores, boundary_type):
"""
Calculate boundaries from gap scores
:param scores: list containing # of active chains across each sentence gap in doc
:param b... |
costibleotu/czl-scrape | sanatate/scrapy_proj/helpers/__init__.py | Python | mpl-2.0 | 147 | 0 | # -*- coding: utf-8 -*-
from scrapy_proj.helpers.leg | al import *
from scrapy_proj.helpers.romanian import *
from sc | rapy_proj.helpers.text import *
|
softDi/clusim | ns3/ns-3.26/.waf-1.8.19-b1fc8f7baef51bd2db4c2971909a568d/waflib/Tools/errcheck.py | Python | apache-2.0 | 6,003 | 0.06047 | #! /usr/bin/env python
# encoding: utf-8
# WARNING! Do not edit! https://waf.io/book/index.html#_obtaining_the_waf_file
typos={'feature':'features','sources':'source','targets':'target','include':'includes','export_include':'export_includes','define':'defines','importpath':'includes','installpath':'install_path','isco... |
for x in('c','cxx','d','fc'):
if not x in lst and lst and lst[0]in[x+y for y in('program','shlib','stlib')]:
Logs.error('%r features is probably missing %r'%(self,x))
TaskGen.feature('*')(check_err_features)
def check_err_order(self):
if not hasattr(self,'rule')and not'subst'in Utils.to_list(self.features... | rder constraint %r on non-rule based task generator %r'%(x,self))
else:
for x in('before','after'):
for y in self.to_list(getattr(self,x,[])):
if not Task.classes.get(y,None):
Logs.error('Erroneous order constraint %s=%r on %r (no such class)'%(x,y,self))
TaskGen.feature('*')(check_err_order)
def ... |
ideascube/ideascube | ideascube/cards.py | Python | agpl-3.0 | 1,516 | 0.00066 | from django.conf import settings
from ideascube.configuration import get_config
# For unittesting purpose, we need to mock the Catalog class.
# However, the mock is made in a fixture and at this moment, we don't
# know where the mocked catalog will be | used.
# So the fixture mocks 'ideascube.serveradmin.catalog.Catalog'.
# If we want to use the moc | ked Catalog here, we must not import the
# Catalog class directly but reference it from ideascube.serveradmin.catalog
# module.
from ideascube.serveradmin import catalog as catalog_mod
def build_builtin_card_info():
card_ids = settings.BUILTIN_APP_CARDS
return [{'id': i} for i in card_ids]
def build_extra_a... |
GoeGaming/lutris | lutris/util/audio.py | Python | gpl-3.0 | 262 | 0 | import subprocess
from lutris.util.log import logger
def reset_pulse():
""" Reset pulseaudio. """
pulse_reset = "pulseaudio --kill | && sleep 1 && pulseaudio --start"
subproc | ess.Popen(pulse_reset, shell=True)
logger.debug("PulseAudio restarted")
|
OpenBookProjects/ipynb | XKCD-style/xkcdplot.py | Python | mit | 8,352 | 0.001796 | """
XKCD plot generator
-------------------
Author: Jake Vanderplas
This is a script that will take any matplotlib line diagram, and convert it
to an XKCD-style plot. It will work | for plots with line & text elements,
including axes labels and titles (but not axes tick labels).
The idea for this comes from work by Damon McDougall
http://www.mail-archive.com/[email protected]/msg25499.html
from:
http://nbviewer.ipython.org/url/jakevdp.github.com/downloads/notebooks/XKCD_p | lots.ipynb
"""
import numpy as np
import pylab as pl
from scipy import interpolate, signal
import matplotlib.font_manager as fm
# We need a special font for the code below. It can be downloaded this way:
import os
import urllib2
#import urllib.request as urllib2
if not os.path.exists('Humor-Sans.ttf'):
fhandle ... |
sumaxime/LIFAP1 | TD/TD3/Code/Python/3.py | Python | mit | 243 | 0 | #!/usr/bin/python
# Afficher les dix nom | bres su | ivants la valeur N donnée en paramètre
def show_num(a):
for i in range(10):
print(a, end='')
a += 1
print('Donne moi une valeur : ', end='')
a = int(input())
show_num(a)
|
okin006/tracker | tracker/urls.py | Python | mit | 811 | 0 | """tracker URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-bas... | b import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
| url(r'^ticket/', include('tracker.ticket.urls')),
]
|
eXk0n/nagios-plugins | apcupsd-nagios.py | Python | mit | 1,574 | 0.021601 | #!/usr/bin/env python
import subprocess
import sys
warning = False
critical = False
load = subprocess.check_output("/usr/sbin/apcaccess -p LOADPCT -u", shell=True).rstrip()
bcharge = subprocess.check_output("/usr/sbin/apcaccess -p BCHARGE -u", shell=True).rstrip()
timeleft = subprocess.check_output("/usr/sbin/apcacce... | pcaccess -p LINEV -u", shell=True).rstrip()
battv = subprocess.check_output("/usr/sbin/apcaccess -p BATTV -u", shell=True).rstrip( | )
if float(load) > 70.0:
warning = True
elif float(load) > 90.0:
citical = True
if float(linev) > 240.0:
warning = True
elif float(linev) > 250.0:
critical = True
if float(linev) < 210.0:
warning = True
elif float(linev) < 200.0:
critical = True
if float(battv) > 28.0:
warning = True
elif float(battv) > 29.0... |
tensorflow/privacy | tensorflow_privacy/privacy/optimizers/dp_optimizer_keras_test.py | Python | apache-2.0 | 19,265 | 0.003426 | # Copyright 2019, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | zed.VectorizedDPKerasSGDOptimizer),
( | 'DPAdagradVectorized',
dp_optimizer_keras_vectorized.VectorizedDPKerasAdagradOptimizer),
('DPAdamVectorized',
dp_optimizer_keras_vectorized.VectorizedDPKerasAdamOptimizer),
)
def testAssertOnNoCallOfComputeGradients(self, cls):
"""Tests that assertion fails when DP gradients are not computed... |
jriehl/numba | examples/kernel-density-estimation/kernel_density_estimation.py | Python | bsd-2-clause | 1,135 | 0.003524 | #
# Copyright (c) 2017 Intel Corporation
# SPDX-License-Identifier: BSD-2-Clause
#
from numba import njit, prange
import numpy as np
import argparse
import time
def kde(X):
b = 0.5
points = np.array([-1.0, 2.0, 5.0])
N = points.shape[0]
n = X.shape[0]
exps = 0
# "prange" in a normal function i... | n):
p = X[i]
d = (-(p-points)**2)/(2*b**2)
m = np.min(d)
exps += m-np.log(b*N)+np.log(np.sum(np.exp(d-m)))
return exps
def main():
parser = argparse.ArgumentParser(description='Kernel-Density')
parser.add_argument('--size', dest='size', type=int, default=10000000)
parser... | e
iterations = args.iterations
np.random.seed(0)
kde(np.random.ranf(10))
print("size:", size)
X = np.random.ranf(size)
t1 = time.time()
for _ in range(iterations):
res = kde(X)
t = time.time()-t1
print("checksum:", res)
print("SELFTIMED:", t)
if __name__ == '__main__':
... |
AdnCoin/AdnCoin | qa/rpc-tests/maxuploadtarget.py | Python | mit | 10,732 | 0.003075 | #!/usr/bin/env python2
#
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
from test_framework.mininode import *
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
import time
'''... | equest new blocks
# test_nodes[2] will test resetting the counte | rs
test_nodes = []
connections = []
for i in xrange(3):
test_nodes.append(TestNode())
connections.append(NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_nodes[i]))
test_nodes[i].add_connection(connections[i])
NetworkThread().start() # Start up... |
JasonHanG/tensor-gallery | basic-operation/linear_regression.py | Python | apache-2.0 | 1,901 | 0.002104 | import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import xlrd
DATA_FILE = 'data/fire_theft.xls'
# Step 1: read in data from the .xls file
book = xlrd.open_workbook(DATA_FILE, encoding_override="utf-8")
sheet = book.sheet_by_index(0)
data = np.asarray([sheet.row_values(i) for | i in range(1, sheet.nrows)])
n_samples = sheet.nrows - 1
# Step 2: create placeholders for input X (number of fire) and l | abel Y (number of theft)
X = tf.placeholder(tf.float32, name='X')
Y = tf.placeholder(tf.float32, name='Y')
# Step 3: create weight and bias, initialized to 0
w = tf.Variable(0.0, name='weights')
b = tf.Variable(0.0, name='bias')
# Step 4: build model to predict Y
Y_predicted = X * w + b
# Step 5: use the square erro... |
jdl-mit-alum/code-quality | python_2_7/Search/docs/conf.py | Python | gpl-3.0 | 8,441 | 0.005331 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# parlogser documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# a... | top of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon
# of the docs. This file should be a Windows icon file (.ico) being
# 16x16 or 32x32 pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets)
# here, relative... | copied after the builtin
# static files, so a file named "default.css" will overwrite the builtin
# "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page
# bottom, using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants... |
robotpy/robotpy-wpilib-utilities | tests/test_magicbot_sm.py | Python | bsd-3-clause | 13,059 | 0.003293 | from magicbot.state_machine import (
default_state,
state,
timed_state,
AutonomousStateMachine,
StateMachine,
IllegalCallError,
NoFirstStateError,
MultipleFirstStatesError,
MultipleDefaultStatesError,
InvalidStateName,
)
from magicbot.magic_tunable import setup_tunables
import ... | assert sm.current_state == ""
assert not sm.is_executing
sm.engage()
sm.execute()
sm.engage()
sm.execute()
sm.execute()
sm.execute()
assert sm.current_state == "must_finish"
assert sm.is_executing
sm.next_state("ordinary3")
sm.engage( | )
sm.execute()
assert sm.current_state == "timed_must_finish"
sm.execute()
assert sm.is_executing
assert sm.current_state == "timed_must_finish"
for _ in range(7):
wpitime.step(0.1)
sm.execute()
assert sm.is_executing
assert sm.current_state == "timed_must_fin... |
ashishb/python_dep_generator | setup.py | Python | mit | 604 | 0.019868 | from setuptools import setup
setup(name='python_dep_generator',
version='0.1',
description='Generates python code dependency graph',
url='http | s://github.com/ashishb/python_dep_generator',
author='Ashish Bhatia',
author_email='[email protected]',
license='MIT',
packages=['python_dep_generator'],
# install_requires=['argparse', 'importlib', 'inspect', 'logging', 'sys'] | ,
entry_points = {
'console_scripts': ['generate-dep=python_dep_generator.generate_dep:main'],
},
zip_safe=False)
|
kdheepak89/power-grid-helper | tests/test_functional.py | Python | bsd-3-clause | 4,009 | 0.000249 | # -*- coding: utf-8 -*-
"""Functional tests using WebTest.
See: http://webtest.readthedocs.org/
"""
from flask import url_for
from power_grid_helper.user.models import User
from .factories import UserFactory
class TestLoggingIn:
"""Login."""
def test_can_log_in_returns_200(self, user, testapp):
""... | com'
form['password'] = 'secret'
form['confirm'] = 'secret'
# Submits
res = form.submit().follow()
assert res.status_ | code == 200
# A new user was created
assert len(User.query.all()) == old_count + 1
def test_sees_error_message_if_passwords_dont_match(self, user, testapp):
"""Show error if passwords don't match."""
# Goes to registration page
res = testapp.get(url_for('public.register'))
... |
pculture/unisubs | utils/one_time_data.py | Python | agpl-3.0 | 1,410 | 0.004255 | # Amara, universalsubtitles.org
#
# Copyright (C) 2017 Participatory Culture Foundation
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your op... | rt reverse
def _mk_key(token):
return "one-time-data-" + token
def set_one_time_data(data):
token = str(uuid.uuid4())
key = _mk_key(token)
cache.set(key, data, 60)
retur | n '{}://{}{}'.format(settings.DEFAULT_PROTOCOL,
settings.HOSTNAME,
reverse("one_time_url", kwargs={"token": token}))
def get_one_time_data(token):
key = _mk_key(token)
data = cache.get(key)
# It seems like Brightcove wants to hit it twice
... |
mlflow/mlflow | examples/shap/multiclass_classification.py | Python | apache-2.0 | 964 | 0.002075 | import os
import numpy as np
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
import shap
import mlflow
# prepare training data
X, y = load_iris(return_X_y=True, as_frame=True)
# train a model
model = RandomForestClassifier()
model.fit(X, y)
# log an explanation
with mlf... | oba, X)
# list artifacts
client = mlflow.tracking.MlflowClient()
artifact_path = "model_explanations_shap"
artifacts = [x.path for x in client.list_artifacts(run.info.run_id, artifact_path)]
print("# artifacts:")
print(artifacts)
# load back the logged explanation
dst_path = client.download_artifacts(run.info.run_id,... | lues = np.load(os.path.join(dst_path, "base_values.npy"))
shap_values = np.load(os.path.join(dst_path, "shap_values.npy"))
# show a force plot
shap.force_plot(base_values[0], shap_values[0, 0, :], X.iloc[0, :], matplotlib=True)
|
sdispater/tomlkit | tests/test_write.py | Python | mit | 437 | 0 | from tomlkit import dumps
from tomlkit import loads
def test_write_backslash():
| d = {"foo": | "\\e\u25E6\r"}
expected = """foo = "\\\\e\u25E6\\r"
"""
assert expected == dumps(d)
assert loads(dumps(d))["foo"] == "\\e\u25E6\r"
def test_escape_special_characters_in_key():
d = {"foo\nbar": "baz"}
expected = '"foo\\nbar" = "baz"\n'
assert expected == dumps(d)
assert loads(dumps(d))["... |
euhackathon/commission-today-api | backend/backend/migrations/0006_auto_20141203_0021.py | Python | mit | 1,218 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('backend', '0005_organization_registered'),
]
operations = [
migrations.RemoveField(
model_name='organization',
... | ank=True),
preserve_default=True,
| ),
migrations.AlterField(
model_name='organization',
name='name',
field=models.CharField(max_length=128, null=True, blank=True),
preserve_default=True,
),
]
|
praus/Label-Big-Mail | big_mail_labeler.py | Python | mit | 3,890 | 0.006684 | #!/usr/bin/env python
import argparse
import email
import bisect
try:
from imapclient import IMAPClient
except ImportError:
import sys
print >>sys.stderr, """This script requires IMAPClient, a convenient Python IMAP library.
http://imapclient.freshfoo.com/
You can install it using PyPI:
(sudo) pip in... | old)
big_uids = [ msg[0] for msg in big_messages ]
def print_messages():
print "\n--- Messages bigger than {}: ".format(options.threshold).ljust(80, '-')
print "Format: <date> | <size> | <from> | <subject>"
for msgid, data in big_messages:
headers = email.message_from_string(data['RFC822.HEADER'])... | _label:
print "Labeling big messages with label %s" % options.label
server.create_folder(options.label)
server.copy(big_uids, options.label)
print "Your messages larger than {} bytes have been labeled with label {}".format(options.threshold, options.label)
if options.print_msgs or options.no_label:
... |
ridgek/shunter | tests/test_application.py | Python | bsd-3-clause | 1,174 | 0.000852 | from StringIO import StringIO
import unittest
from shunter.request import HTTPRequest
import mockapp
class TestApplication(unittest.TestCase):
def setUp(self):
self.app = mockapp.application
def test_get_response(self):
request = HTTPRequest({'REQUEST_METHOD': 'GET',
| 'PATH_INFO | ': '',
'Content-Type': 'text/plain'})
response = self.app.get_response(request)
self.assertEqual(response.content.read(), 'Hello World!')
self.assertEqual(response.status, 200)
request = HTTPRequest({'REQUEST_METHOD': 'GET',
... |
l33tdaima/l33tdaima | pr1662e/array_strings_are_equal.py | Python | mit | 950 | 0.002105 | from typing import List
class Solution:
def arrayStringsAreEqualV1(self, word1: List[str], word2: List[str]) -> bool:
return "".join(word1) == "".join(word2)
def arrayStringsAreEqualV2(self, word1: List[str], word2: List[str]) -> bool:
def generator(word: List[str]):
for s in word... | ue),
(["a", "cb"], ["ab", "c"], False),
(["abc", "d", "defg"], | ["abcddefg"], True),
]:
sol = Solution()
actual = sol.arrayStringsAreEqualV1(word1, word2)
print("Array strings", word1, "and", word2, "are equal ->", actual)
assert actual == expected
assert sol.arrayStringsAreEqualV1(word1, word2) == expected
|
Hackerfleet/hfos | isomer/hfos/core.py | Python | agpl-3.0 | 1,475 | 0 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# HFOS - Hackerfleet Operating System
# ===================================
# Copyright (C) 2011-2019 Heiko 'riot' Weinen <[email protected]> and others.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General P... | option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of th... | ro General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
__author__ = "Heiko 'riot' Weinen"
__license__ = "AGPLv3"
"""
Module: HFOS Core
=================
"""
from isomer.component import ConfigurableComponent, handler
from isomer.database import objectmodels
from isomer.... |
tomhsx/django-inventory | inventory/urls.py | Python | mit | 242 | 0 | from django.conf.urls import patterns, include, url
from django.contrib import a | dmin
admin.autodiscover()
urlpatterns = patterns(
'',
url(r'^$', 'inventory.views.home', name='home'),
| url(r'^admin/', include(admin.site.urls)),
)
|
TaskEvolution/Task-Coach-Evolution | taskcoach/taskcoachlib/thirdparty/src/reportlab/__init__.py | Python | gpl-3.0 | 1,715 | 0.00758 | #Copyright ReportLab Europe Ltd. 2000-2012
#see license.txt for license details
#history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/__init__.py
__version__=''' $Id$ '''
__doc__="""The Reportlab PDF generation library."""
Version = "2.7"
import sys
if sys.version_info[0:2] < (2, 7)... | sion to suppo0rt Python 2.5 an | d 2.6.
Python 2.3 users may still use ReportLab 2.4 or any other bugfixes
derived from it, and Python 2.4 users may use ReportLab 2.5.
Python 2.2 and below need to use released versions beginning with
1.x (e.g. 1.21), or snapshots or checkouts from our 'version1' branch.
Our current plan is... |
taejoonlab/taejoonlab-toolbox | PopGen/dominant_nucl.py | Python | gpl-3.0 | 2,301 | 0.010865 | #dominant
import os
folder = sys.argv[1]
def make_file_list(input_dir):
file_list = []
input_file_list = os.listdir | (input_dir)
for input_file in input_file_list:
if input_file[-8:] == '.cluster':
file_list.append(input | _file)
return file_list
file_list = make_file_list(folder)
for each_file in file_list:
with open(folder + each_file,'r') as f:
print each_file
clustername = each_file.replace('.cluster','')
sample = each_file.split('_')[1]
sample_name = each_file.split('.')[0]
uniq = op... |
frouty/odoogoeen | extra-addons/aeroo/report_aeroo_sample/__init__.py | Python | agpl-3.0 | 1,534 | 0.000652 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2008-2011 Alistek Ltd (http://www.alistek.com) All Rights Reserved.
# General contacts <[email protected]>
#
# WARNING: This program as such is intended to be used by professional
#... | tware Foundation; either version 3
# of t | he License, or (at your option) any later version.
#
# This module is GPLv3 or newer and incompatible
# with OpenERP SA "AGPL + Private Use License"!
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PA... |
rekka/intro-fortran-2016 | web/python/implicit_euler.py | Python | mit | 1,047 | 0.002865 | import math
import nu | mpy as np
import matplotlib
matplotlib.use('SVG')
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
x1 = 2.
x = np.linspace(0, x1, 100)
ax.plot(x, np.exp(-5. * x), linewidth=2, label = '$x(t)$')
N = 4
h = x1 / N
sx = np.linspace(0, x1, N + 1)
sy = [(1 + 5. * h)**(-n) for n in range(N + 1)]
ax.plot(sx, sy,... |
ax.spines['top'].set_visible(False)
ax.spines['bottom'].set_bounds(0, x1)
plt.tick_params(
axis='y',
which='both',
left='on',
right='off',
labelleft='off')
ax.xaxis.set_ticks_position('bottom')
ax.set_xticks(sx)
ax.set_xticklabels(["$t_{}$".format(i) for i in range(N+1)])
ax.set_xlim((0 - 0.05, x1 ... |
Pecacheu/Eagle2Kicad | Library/Library.py | Python | mit | 3,113 | 0.008352 | '''
Created on Apr 3, 2012
@author: Dan
'''
from Common.Converter import *
from Common.Module import *
from Common.Symbol import DevicePart
from Common.Device import Deviceset
class Library(object):
__slots__ = ("name", "modules", "symbols", "converter", "deviceparts")
def __init__(self, node, name, conver... | e:
symbolsHash[sn] = symbol
for deviceset in devicesetsLs | t: #strange if not?
#just iterater over all posible device packages
for device in deviceset.getDevices():
#we have to create a number of symbols to match diffrent pin configurations
#the real name of device is <deviceset> name plus name of <device>... |
OCA/report-print-send | remote_report_to_printer/tests/__init__.py | Python | agpl-3.0 | 61 | 0 | from . import test_remote_print | er
from . import | test_printer
|
torchbox/django-modelcluster | modelcluster/forms.py | Python | bsd-3-clause | 16,632 | 0.003487 | from __future__ import unicode_literals
from django.forms import ValidationError
from django.core.exceptions import NON_FIELD_ERRORS
from django.forms.formsets import TOTAL_FORM_COUNT
from django.forms.models import (
BaseModelFormSet, modelformset_factory,
ModelForm, _get_foreign_key, ModelFormMetaclass, Mode... | ormset saving mechanism.
no_id_instances = [obj for obj in manager.all() if obj.pk is None]
if no_id_instances:
manager.remove | (*no_id_instances)
manager.add(*saved_instances)
manager.remove(*self.deleted_objects)
self.save_m2m() # ensures any parental-m2m fields are saved.
if commit:
manager.commit()
return saved_instances
def clean(self, *args, **kwargs):
self.validate_uniq... |
pearsonlab/nipype | examples/fmri_fsl_feeds.py | Python | bsd-3-clause | 5,653 | 0.00283 | #!/usr/bin/env python
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
=================
fMRI: FEEDS - FSL
=================
A pipeline example that data from the FSL FEEDS set. Single subject, two
stimuli.
You can find it at http://www.fmrib.ox.ac.... | t the layout of | our data. The
:class:`nipype.pipeline.Node` module wraps the interface object and provides
additional housekeeping and pipeline specific functionality.
"""
datasource = pe.Node(interface=nio.DataGrabber(outfields=['func', 'struct']),
name='datasource')
datasource.inputs.base_directory = feeds_da... |
pombreda/pyamg | Examples/ComplexSymmetric/one_D_helmholtz.py | Python | bsd-3-clause | 3,892 | 0.014132 | from numpy import array, zeros, ones, sqrt, ravel, mod, random, inner, conjugate
from scipy.sparse import csr_matrix, csc_matrix, coo_matrix, bmat, eye
from scipy import rand, mat, real, imag, linspace, hstack, vstack, exp, cos, sin, pi
from pyamg.util.linalg import norm
import pyamg
from scipy.optimize import fminboun... | reA = pyamg.gallery.poisson( (h,), format='csr')
reA = reA - mesh_h*mesh_h*omega*omega*\
eye(reA.shape[0], reA.shape[1], format='csr')
dimen = reA.shape[0]
# Construct Ima | ginary Operator
imA = csr_matrix( coo_matrix( (array([2.0*mesh_h*omega]), \
(array([0]), array([0]))), shape=reA.shape) )
# Enforce Radiation Boundary Conditions at first grid point
reA.data[1] = -2.0
# In order to maintain symmetry scale the first equation by 1/2
reA.data[... |
kawamon/hue | desktop/core/ext-py/celery-4.2.1/t/unit/backends/test_redis.py | Python | apache-2.0 | 23,661 | 0.000042 | from __future__ import absolute_import, unicode_literals
import random
import ssl
from contextlib import contextmanager
from datetime import timedelta
from pickle import dumps, loads
import pytest
from case import ANY, ContextMock, Mock, call, mock, patch, skip
from celery import signature, states, uuid
from celery.... |
x = RedisBackend(app=self.app)
assert loads(dumps(x))
def test_no_redis(self):
self. | Backend.redis = None
with pytest.raises(ImproperlyConfigured):
self.Backend(app=self.app)
def test_url(self):
self.app.conf.redis_socket_timeout = 30.0
self.app.conf.redis_socket_connect_timeout = 100.0
x = self.Backend(
'redis://:[email protected]:123//1', ... |
pddg/Qkou_kit | lib/add_db.py | Python | mit | 2,046 | 0 | # coding: utf-8
import db_info
import db_cancel
import db_news
import hashlib
from tweeter import format_info, format_cancel, format_news
import settings
log = settings.log
def add_info_to_queue(q, *args):
try:
# 更新した数をカウント
updated = 0
for lec_info in args:
id = db_info.add_in... | # キューに投入
| q.put(t)
updated += 1
else:
pass
else:
# 更新数を返す
return updated
except Exception as e:
log.exception(e)
def add_news_to_queue(q, *args):
try:
# 更新した数をカウント
updated = 0
for news in args:
... |
jimmyraywv/cloud-custodian | c7n/resources/account.py | Python | apache-2.0 | 35,461 | 0.00079 | # Copyright 2016-2017 Capital One Services, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... | rue) and recorders:
status = {s['name']: s for
s in client.describe_configuration_recorder_status(
)['ConfigurationRecordersStatus']}
resources[0]['c7n:config_status'] = status
recorders = [r for r in recorders if status[r['name']]['recording'] and
... | ame']]['lastStatus'].lower() in ('pending', 'success')]
if channels and recorders:
return []
return resources
@filters.register('iam-summary')
class IAMSummary(ValueFilter):
"""Return annotated account resource if iam summary filter matches.
Some use cases include, detecting root ... |
spandanb/horizon | openstack_dashboard/dashboards/admin/images/urls.py | Python | apache-2.0 | 1,311 | 0.000763 | # Cop | yright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights | Reserved.
#
# 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 ... |
slozier/ironpython2 | Tests/interop/net/loadorder/t3g1.py | Python | apache-2.0 | 833 | 0.004802 | # Licensed to the .NET Foundation under one or more agreements.
# The .NET Foundation licenses this file to you under the Apache 2.0 License.
# See the LICENSE file in the project root for more information.
| from iptest.assert_util import *
add_clr_assemblies("loadorder_3")
# namespace First {
# public class Generic1<K, V> {
# public static string Flag = typeof(Generic1<,>).FullName;
| # }
# }
import First
AreEqual(First.Generic1[int, int].Flag, "First.Generic1`2")
add_clr_assemblies("loadorder_3g")
# namespace First {
# public class Generic1<K, V> {
# public static string Flag = typeof(Generic1<,>).FullName + "_Same";
# }
# }
AreEqual(First.Generic1[int, int].Flag, "First.Ge... |
willre/homework | day21-22/source/app01/views.py | Python | gpl-2.0 | 2,803 | 0.013674 | # -*- coding:utf-8 -*-
from django.shortcuts import render
import models
# Create your views here.
class Pager(object):
def __init__(self,current_page):
self.current_page = current_page
@property
def start(self):
return (self.current_page-1)*10
@property
def end(self):
r... | %d </a>' % (base_url,i,i)
else:
temp = '<a href="%s% | d"> %d </a>' % (base_url,i,i)
page_list.append(temp)
if self.current_page>1:
pre_page = '<a href="%s%d"> 上一页 </a>' % (base_url,self.current_page-1)
else:
pre_page= temp = '<a href="javascript:void(0)"> 上一页 </a>'
if self.current_page>=all_page:
... |
thiagopa/thiagopagonha | wiki/models.py | Python | bsd-3-clause | 842 | 0.016687 | #-*- coding: utf-8 -*-
from django.db import models
from django.contrib import admin
from datetime import datetime, timedelta
import pytz
def default_now():
now = datetime.utcnow().replace(tzinfo=pytz.utc)
# Essa merda de UTC só funciona direito na versão 1.4 :(
# Era fazer essa gambi ou modificar o códig... | self.updated = default_now()
su | per(Page, self).save()
class PageAdmin(admin.ModelAdmin):
exclude = ('updated',)
admin.site.register(Page,PageAdmin) |
libcrack/iker | setup.py | Python | gpl-3.0 | 2,536 | 0.001972 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: [email protected]
# Date: Wed Jan 28 16:35:57 CET 2015
import re
import os
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def read(relpath):
"""
Return string containing the contents of the file at *relpat... | 'long_description': LONG_DESCRIPTION,
'author': AUTHOR,
'author_email': EMAIL,
'url': WEBSITE,
'license': LICENSE, |
'packages': PACKAGES,
'package_dir': PACKAGE_DIR,
#'scripts': SCRIPTS,
'entry_points': ENTRY_POINTS,
'provides': PROVIDES,
'requires': INSTALL_REQUIRES,
'install_requires': INSTALL_REQUIRES,
'classifiers': CLASSIFIERS,
}
setup(**PARAMS)
# vim:ts=4 sts=4 tw=79 expandtab:
|
google-research/prompt-tuning | prompt_tuning/train/__init__.py | Python | apache-2.0 | 572 | 0.001748 | # Copyright 2022 Google.
#
# Licensed under the Apache License, Version 2.0 (th | e "License");
# you may not use this file except in compliance with the | License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# S... |
Bristol-Braille/canute-ui | ui/buttons.py | Python | gpl-3.0 | 3,110 | 0 | import logging
from datetime import datetime
from .actions import actions
from .system_menu.system_menu import system_menu
from .library.buttons import library_buttons
from .book.buttons import book_buttons
from .go_to_page.buttons import go_to_page_buttons
from .bookmarks.buttons import bookmarks_buttons
from .languag... | help_menu(),
},
'long': {
'L': actions.close_menu(),
'>': actions.next_page(),
'<': actions.previous_page(),
'R': actions.toggle_help_menu(),
'X': actions.reset_display('start'),
},
},
'system_menu': {
'single': {
... | (),
'<': actions.previous_page(),
'L': actions.close_menu(),
},
'long': {
'R': actions.toggle_help_menu(),
'>': actions.next_page(),
'<': actions.previous_page(),
'L': actions.close_menu(),
'X': actions.reset_display('st... |
renesugar/arrow | dev/archery/archery/benchmark/compare.py | Python | apache-2.0 | 3,878 | 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... | self.baseline = baseline
self.threshold = threshold
self.suite_name = suite_name
@property
def name(self):
return self.baseline.name
@property
def less_is_better(self):
return self.ba | seline.less_is_better
@property
def unit(self):
return self.baseline.unit
@property
def change(self):
new = self.contender.value
old = self.baseline.value
if old == 0 and new == 0:
return 0.0
if old == 0:
return 0.0
return float... |
mahabs/nitro | nssrc/com/citrix/netscaler/nitro/resource/config/appfw/appfwarchive.py | Python | apache-2.0 | 6,303 | 0.039029 | #
# Copyright (c) 2008-2015 Citrix Systems, 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 l... | :
raise e
@classmethod
def | delete(cls, client, resource) :
""" Use this API to delete appfwarchive.
"""
try :
if type(resource) is not list :
deleteresource = appfwarchive()
if type(resource) != type(deleteresource):
deleteresource.name = resource
else :
deleteresource.name = resource.name
return deleteresourc... |
Bumpybox/pyblish-bumpybox | pyblish_bumpybox/plugins/nuke/validate_datatype.py | Python | lgpl-3.0 | 1,133 | 0 | from pyblish import api
from pyblish_bumpybox import inventory
class ValidateDatatype(api.InstancePlugin):
"""Validate output datatype matches with input."""
order = inventory.get_order(__file__, "ValidateDatatype")
families = ["write"]
label = "Datatype"
optional = True
targets = ["default", | "process"]
def process(self, instance):
# Only validate these channels
channels = [
"N_Object",
"N_World",
"P_Object",
"P_World",
"Pref",
"UV",
"velocity",
"cryptomatte"
| ]
valid_channels = []
for node_channel in instance[0].channels():
for channel in channels:
if node_channel.startswith(channel):
valid_channels.append(node_channel)
if valid_channels:
msg = (
"There are 32-bit cha... |
beni55/edx-platform | lms/djangoapps/courseware/management/commands/remove_input_state.py | Python | agpl-3.0 | 6,715 | 0.004319 | '''
This is a one-off command aimed at fixing a temporary problem encountered where input_state was added to
the same dict object in capa problems, so was accumulating. The fix is simply to remove input_state entry
from state for all problems in the affected date range.
'''
import json
import logging
from optparse im... | _hist_changed = 0
option_list = BaseCommand.option_list + (
make_option('--save',
action='store_true',
des | t='save_changes',
default=False,
help='Persist the changes that were encountered. If not set, no changes are saved.'),
)
def fix_studentmodules_in_list(self, save_changes, idlist_path):
'''Read in the list of StudentModule objects that might need fixing, and the... |
leandromet/Geoprocessamento---Geoprocessing | Palsar_HH_HV_to_RGB8bit.py | Python | mit | 4,323 | 0.018043 | """
#-------------------------------------------------------------------------------
# Name: ALOS HH, HV and RFDI on RGB 16signedint GEOTIFF
# Purpose: Calculates the RFDI , saves geotiff with HH, HV and RFDI layers
# in 8bit unsigned format, with values stretched for contrast enhancement.
# | Author: [email protected]
#
# Created: 06/07/2015
# Copyright: (c) leandro.biondo 2015
# Licence: GPL
#-------------------------------------------------------------------------------
"""
import glob
| import gdal
from gdalconst import *
import osr
import numpy as np
from struct import *
import array
from scipy import ndimage
import math
import os
def exporta_alos_geoTIFF(arquivo, destino, refer):
pos = arquivo.find(refer)-1
lat = -1*int(arquivo[pos+6:pos+8])
lon = -1*int(arquivo[pos+9:pos+12])
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.