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 |
|---|---|---|---|---|---|---|---|---|
kamyu104/LeetCode | Python/count-univalue-subtrees.py | Python | mit | 917 | 0.003272 | # Time: O(n)
# Space: O(h)
#
# 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
# @return {integer}
def countUnivalSubtrees(self, root):
[is_uni, ... | alSubtrees(self, root, count):
if not root:
return [True, count]
[left, count] = self.isUnivalSubtrees(root.left, count)
[right, count] = self.isUnivalSubtrees(root.right, count)
if self.isSame(root, root.left, left) and \
| self.isSame(root, root.right, right):
count += 1
return [True, count]
return [False, count]
def isSame(self, root, child, is_uni):
return not child or (is_uni and root.val == child.val)
|
varun-suresh/Clustering | evaluation.py | Python | mit | 1,895 | 0.000528 | # Script to evaluate the performance of the clustering algorithm.
import argparse
from itertools import combinations
from collections im | port defaultdict
def count_correct_pairs(cluster, labels_lookup):
"""
Given a cluster, count the number of pairs belong to the same label and
the total number of pairs.
"""
total_pairs = 0
correct_pairs = 0
pairs = combinations(cluster, 2)
for f1, f2 in pairs:
if labels_lookup[... | orrect_pairs += 1
total_pairs += 1
return correct_pairs, total_pairs
def calculate_pairwise_pr(clusters, labels_lookup):
"""
Given a cluster, return pairwise precision and recall.
"""
correct_pairs = 0
total_pairs = 0
# Precision
for cluster in clusters:
cp, tp = count_... |
dydek/django | tests/admin_custom_urls/tests.py | Python | bsd-3-clause | 6,103 | 0.003113 | from __future__ import unicode_literals
import datetime
from django.contrib.admin.utils import quote
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.template.response import TemplateResponse
from django.test import TestCase, override_settings
from .models import A... | Equal(Car.objec | ts.count(), 0)
response = self.client.post(
reverse('admin_custom_urls:admin_custom_urls_car_add'), post_data)
cars = Car.objects.all()
self.assertEqual(len(cars), 1)
self.assertRedirects(
response, reverse('admin_custom_urls:admin_custom_urls_car_history', args=[... |
eallovon/xivo-provd-plugins | plugins/xivo-cisco-sccp/9.0.3/entry.py | Python | gpl-3.0 | 989 | 0 | # -*- coding: utf-8 -*-
# Copyright (C) 2013-2014 Avencall
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This p... | le_('common.py', common)
MODELS = [
u'7906G',
u'7911G',
u'7931G',
u'7941G' | ,
u'7942G',
u'7961G',
u'7962G',
]
class CiscoSccpPlugin(common['BaseCiscoSccpPlugin']):
IS_PLUGIN = True
pg_associator = common['BaseCiscoPgAssociator'](MODELS)
|
gsarma/PyOpenWorm | examples/test_bgp.py | Python | mit | 1,886 | 0.00053 | """
Examples of loading all information about an object or set of objects from the
database.
"""
from __future__ import absolute_import
from __future__ import print_function
import PyOpenWorm as P
from PyOpenWorm.connection import Connection
from PyOpenWorm.neuron import Neuron
from PyOpenWorm.context import Context
f... | ata import BIO_ENT_NS
P.connect('default.conf')
def pp_connection(conn):
print(conn.pre_cell(), conn.post_cell(), conn.syntype(), conn.synclass(), conn.number())
try:
ctx = Context(ident=BIO_ENT_NS['worm0']).stored
query_object = ctx(Connection) | (pre_cell=ctx(Neuron)(name='AVAL'))
print('STARTING WITH AVAL')
for x in query_object.load():
pp_connection(x)
print()
print('STARTING WITH PVCL')
query_object = ctx(Connection)(pre_cell=ctx(Neuron)(name='PVCL'))
for x in query_object.load():
pp_connection(x)
print()
pri... |
bmaia/rext | modules/misc/arris/tm602a_password_day.py | Python | gpl-3.0 | 4,890 | 0.003888 | # Name:Arris password of the day generator
# File:tm602a_password_day_py
#Author:Ján Trenčanský
#License: GNU GPL v3
#Created: 29.3.2015
#Last modified: 29.3.2015
#Shodan Dork:
#Description: The Accton company builds switches, which are rebranded and sold by several manufacturers.
# Based on work of Raul Pe... | [13, 14, 27, 32, 10],
[29, 14, 32, | 29, 24],
[23, 32, 24, 29, 29],
[14, 29, 10, 21, 29],
[34, 27, 16, 23, 30],
[14, 22, 24, 17, 13]]
table2 = [[0, 1, 2, 9, 3, 4, 5, 6, 7, 8],
[1, 4, 3, 9, 0, 7, 8, 2, 5, 6],
[7, 2, 8, 9, 4, 1, 6, 0, 3, 5],
... |
ergoithz/browsepy | browsepy/__main__.py | Python | mit | 6,489 | 0.000154 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import sys
import os
import os.path
import argparse
import warnings
import flask
from . import app
from . import __meta__ as meta
from .compat import PY_LEGACY, getdebug, get_terminal_size
from .transform.glob import translate
class HelpFormatter(argparse.Raw... | self.add_argument(
'--plugin', metavar='MODULE',
action=self.plugin_action_class,
default=[],
help='load plugin module (multiple)')
self.add_argument(
'--debug', action='store_true',
help=argparse.SUPPRESS)
def _path(self, arg):
... | bspath(arg)
def _file(self, arg):
path = self._path(arg)
if os.path.isfile(path):
return path
self.error('%s is not a valid file' % arg)
def _directory(self, arg):
path = self._path(arg)
if os.path.isdir(path):
return path
self.error('%s ... |
SCPR/accountability-tracker | cali_water/management/commands/usage_tasks.py | Python | gpl-2.0 | 597 | 0.0067 | fro | m __future__ import division
from django.conf import settings
from django.core.management.base import BaseCommand
import time
import datetime
import logging
from cali_water.usage_data_tasks import TasksForMonthlyWaterUseReport
logger = logging.getLogger("accountability_tracker")
class Command(BaseCommand):
help =... | rUseReport()
task_run._init()
self.stdout.write("\nTask finished at %s\n" % str(datetime.datetime.now()))
|
pratikmallya/heat | heat/tests/test_stack_lock.py | Python | apache-2.0 | 10,326 | 0.000097 | #
# 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
# ... | self.assertRaises(exception.ActionInProgress, slock.acquire)
mock_create.assert_has_calls(
[mock.call(self.stack_id, self.engine_id)] * 2)
mock_steal.assert_has_calls(
[mock.call(self.stack_id, 'fake-engine-id', self.engine_id)] * 2)
def test_thread_lock_context_mgr... | slock = stack_lock.StackLock(self.context, self.stack_id,
self.engine_id)
def check_thread_lock():
with slock.thread_lock():
self.assertEqual(1,
stack_lock_object.StackLock.create.call_count)
r... |
openstack/watcher-dashboard | watcher_dashboard/content/goals/panel.py | Python | apache-2.0 | 715 | 0 | # Copyright (c) 2016 b<>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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softw... |
# implied.
# See the License for the specific language governing permissions and
# limitations under t | he License.
from django.utils.translation import ugettext_lazy as _
import horizon
class Goals(horizon.Panel):
name = _("Goals")
slug = "goals"
|
fim/subfinder | setup.py | Python | bsd-2-clause | 391 | 0.025575 | #!/usr/bin/en | v python
from distutils.core import setup
execfile('modules/subfinder/version.py')
setup(name='subfinder',
version=__version__,
description='Tool to fetch subs from OpenSubtitles',
author=__maintainer__,
download_url='https://github.com/fim/subfinder/tarball/master',
package_dir = {'': 'modules'}... | =['subfinder'],
scripts=['subfinder']
)
|
psychomugs/lcars_probe | app/screens/mainOriginal.py | Python | mit | 4,771 | 0.011528 | from datetime import datetime
import pygame
from pygame.mixer import Sound
from ui import colours
from ui.widgets.background import LcarsBackgroundImage, LcarsImage
from ui.widgets.gifimage import LcarsGifImage
from ui.widgets.lcars_widgets import LcarsText, LcarsButton, LcarsBlockHuge, LcarsBlockLarge, LcarsBlockSmal... | layer=1)
all_sprites.add(LcarsBlockHuge(colours.PEACH, (249, 16), "EXPLORE", self.exploreHandler),
layer=1)
all_sprites.add(LcarsElbow(colours.BEIGE, (400, 16), "MAIN"),
layer=1)
# Sounds
| self.beep1 = Sound("assets/audio/panel/201.wav")
#Sound("assets/audio/panel/220.wav").play()
#-----Screens-----#
# Main Screen
all_sprites.add(LcarsText(colours.WHITE, (265, 458), "WELCOME", 1.5),
layer=3)
all_sprites.add(LcarsText(colours... |
beratdogan/arguman.org | web/premises/mixins.py | Python | mit | 1,086 | 0.000921 | from django.db.models import signals
from django.db import models
from datetime import datetime
class FormRenderer(object):
def as_p(self):
"Returns this form rendered as HTML <p>s."
return self._html_output(
normal_row='<p%(html_class_attr)s>%(label)s %(field)s%(help_text)s</p>',
... | iv>',
errors_on_separate_row=True)
class DeletePreventionMixin(models.Model):
is_deleted = models.BooleanField(default=False)
deleted_at = models.DateTimeField(null=True, blank=True)
class Meta:
abstract = True
def delete(self, using=None):
# prepare
signals.pre_... | ted
self.is_deleted = True
self.deleted_at = datetime.now()
self.save(using=using)
# trigger
signals.post_delete.send(
sender=self.__class__,
instance=self
)
|
CaseyNord/Treehouse | Build a Social Network with Flask/form_view/models.py | Python | mit | 710 | 0.004225 | import datetime
from flask.ext.bcrypt import generate_password_hash
from flask.ext.login import UserMixin
from peewee import *
DATABASE = SqliteDatabase(':memory:')
class User(Model):
email = CharField(unique=True)
pass | word = CharField(max_length=100)
join_date = DateTimeField(default=datetime.datetime.now)
bio = CharField(default='')
class Meta:
database = DATABASE
@classmethod
def new(cls, email, password):
cls.create(
email=email,
password=generate_pa... | e():
DATABASE.connect()
DATABASE.create_tables([User], safe=True)
DATABASE.close() |
sql-machine-learning/sqlflow | python/runtime/xgboost/train.py | Python | apache-2.0 | 8,174 | 0 | # Copyright 2020 The SQLFlow 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 applicable law o... | watchlist.append((dvalidate, "validate"))
re = dict()
bst = xgb.train(model_params,
per_batch_dmatrix,
evals=watchlist,
evals_result=re,
| xgb_model=bst,
**train_params)
print("Evaluation result: %s" % re)
if rank == 0:
# TODO(sneaxiy): collect features and label
metadata = collect_metadata(original_sql=original_sql,
select=select,
... |
popazerty/enigma2 | lib/python/Screens/LogManager.py | Python | gpl-2.0 | 19,571 | 0.030201 | from Screens.Screen import Screen
from Components.GUIComponent import GUIComponent
from Components.VariableText import VariableText
from Components.ActionMap import ActionMap
from Components.Label import Label
from Components.Button import Button
from Components.FileList import FileList
from Components.ScrollLabel imp... | f createTrashJob(self):
job = Components.Task.Job(_("LogManager"))
task = Components.Task.PythonTask(job, _("Checking Logs..."))
task.work = self.JobTrash
task.weighting = 1
return job
def openFiles(self, ctimeLimit, allowedBytes):
ctimeLimit = ctimeLimit
allowedBytes = allowedBytes
def JobTrim(self):... | e * 1024 * 1024):
fh = open(filename, 'rb+')
fh.seek(-(config.crash.debugloglimit.value * 1024 * 1024), 2)
data = fh.read()
fh.seek(0) # rewind
fh.write(data)
fh.truncate()
fh.close()
except:
pass
self.TrimTimer.startLongTimer(3600) #once an hour
def JobTrash(self):
ctime... |
kug3lblitz/Heat-Replay | src/code/settings/regexify.py | Python | mit | 1,045 | 0 | from re import compile
# ----------------- Local variables ----------------- #
__reCompiles = []
# ----------------- Global methods ----------------- #
def compileTitleRe():
"""Generates and compiles regex patterns"""
rePats = [
r'[\{\(\[].*?[\)\]\}/\\]',
r'^.*?\(',
r'[\)\]\}\-\'\"... | """Applies regular expression methods and trims whitespace to the specified
format
title: the string to be regexified
"""
return __reCompiles[3].sub( # replace multiple \s with one \s
' ', __reCompiles[2].sub( # replace excess punctuations with one | \s
'', __reCompiles[1].sub( # remove everything before '('
'', __reCompiles[0].sub( # remove everything between brackets
'', title.lower() # convert to lower case first
)
)
).rstrip().lstrip() # strip whitespace from beginning and ... |
Inboxen/Inboxen | inboxen/views/styleguide.py | Python | agpl-3.0 | 3,472 | 0.00144 | ##
# Copyright (C) 2017 Jessica Tallon, Matt Molyneaux
#
# This file is part of Inboxen.
#
# Inboxen 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
# ... | itForm
from inboxen.tickets.models import Question
class Form(forms.Form):
text = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Placeholder'}) | )
checkbox = forms.BooleanField()
dropdown = forms.ChoiceField(choices=((0, "Thing"), (1, "Other thing")))
radio = forms.ChoiceField(widget=forms.RadioSelect, choices=((0, "Thing"), (1, "Other thing")))
@require_GET
def styleguide(request):
now = timezone.now() + timedelta(-1)
domain = mock.Mock(d... |
cdriehuys/chmvh-website | chmvh_website/gallery/__init__.py | Python | mit | 50 | 0 | default_app_config = "gallery.apps.Gal | leryConfig | "
|
wjladams/youth-isahp | DevAHP/ahptree.py | Python | mit | 3,219 | 0.009009 | '''
Created on Dec 5, 2016
@author: wjadams
'''
import numpy as np
class AhpNode(object):
def __init__(self, parent_tree, name, nalts, pw=None):
self.children = []
self.name = name
self.alt_scores = np.zeros([nalts])
self.nalts = nalts
self.parent_tree = parent_tree
... | n pw.alt_names:
self.add_child(alt_name)
def add_child(self, alt_name):
self.children.append(AhpNode(self.parent_tree, alt_name, self.nalts))
def add_alt(self):
self.alt_scores = np.append(self.alt_scores, 0 | )
self.nalts += 1
for child in self.children:
child.add_alt()
def set_alt_scores_old(self, new_scores):
if (len(new_scores)!=self.nalts):
raise NameError("Wrong length for new alt scores")
self.alt_scores = np.array(new_scores)
self.alt_sc... |
G-Node/python-gnode-client | setup.py | Python | lgpl-2.1 | 1,334 | 0 | from setuptools import setup, find_packages
with open("README.rst") as f:
description_text = f.read()
with open("LICENSE.txt") as f:
license_text = f.read()
setup(
name="gnodeclient",
version="0.4.0",
author="A. Stoewer, A. Sobolev",
author_email="adrian.stoewer@rz.ifi.lmu.de",
packages=f... | ramming Language :: Python",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.1",
"Programm | ing Language :: Python :: 3.2",
],
package_data={"gnodeclient": [license_text, description_text]},
include_package_data=True,
zip_safe=False,
)
|
FRidh/seapy | seapy/components/acoustical2d.py | Python | bsd-3-clause | 1,060 | 0.001887 | """
Room 2D
-------
Classes describing a two-dimensional cavity.
.. autoclass:: seapy.components.acoustical2d.Component2DAcoustical
Subsystems
++++++++++
.. autoclass:: seapy.components.acoustical2d.SubsystemLong
"""
import numpy as np
from .acoustical import ComponentAcoustical
from ..subsystems import SubsystemA... | component.area
)
class Component2DAcoustical(ComponentAcoustical):
"""
Component for a fluid in a 2D cavity.
| """
SUBSYSTEMS = {"subsystem_long": SubsystemLong}
|
aurora-pro/apex-sigma | sigma/plugins/searches/urbandictionary/ud.py | Python | gpl-3.0 | 1,053 | 0.003817 | import aiohttp
import discord
from config import MashapeKey
async def ud(cmd, message, args):
ud_input = ' '.join(args)
url = "https://mashape-community-urban-dictionary.p.mashape.com/define?term=" + ud_input
headers = {'X-Mashape-Key': MashapeKey, 'Accept': 'text/plain'}
async with aiohttp.ClientSes... |
definition = definition[:750] + '...'
example = str((response['list'][0]['example']))
embed = discord.Embed(color=0x1abc9c, title='🥃 Urban Dictionary | Definition For `' + ud_input + '`')
embed.add_field(name='Definition', value='```\n' + definition + '\n```')
embed.add_field(name='Usage Example', value='```\n' + example + '\n```')
await message.channel.send(None, embed=embed)
|
Lilykos/invenio | invenio/modules/documents/config.py | Python | gpl-2.0 | 1,292 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2014 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 option) any later... | rage')
DOCUMENTS_SQLALCHEMYSTORAGE = {
'model': 'invenio.modules.documents.models:Document'
}
DOCUME | NTS_MONGODBSTORAGE = {
'model': 'Document',
'host': "localhost",
'port': 27017,
'database': config.CFG_DATABASE_NAME,
}
|
ndawe/rootpy | rootpy/stats/correlated_values.py | Python | bsd-3-clause | 2,219 | 0.000901 | from __future__ import absolute_import
import uncertainties as U
from .. import asrootpy
__all__ = [
'as_ufloat',
'correlated_values',
]
def as_ufloat(roorealvar):
"""
Cast a `RooRealVar` to an `uncertainties.ufloat`
"""
if isinstance(roorealvar, (U.AffineScalarFunc, U.Variable)):
r... | s useful for numerically computing the uncertainties for expressions
using correlated values arising from a fit.
Parameters
----------
param_names: list of strings
A list of pa | rameters to extract from the result. The order of the names
is the order of the return value.
roofitresult : RooFitResult
A RooFitResult from a fit.
Returns
-------
list of correlated values from the uncertainties package.
Examples
--------
.. sourcecode:: python
... |
xaviablaza/course-catalog-api | cu_coursecatalog_spider/spiders/schmidcatalogspider.py | Python | mit | 10,386 | 0.025713 | # -*- coding: utf-8 -*-
# import the necessary packages
from cu_coursecatalog_spider.items import Course, Major, Minor
import scrapy
import json
# Spider used to crawl through the webpage and get info
class SchmidCatalogSpider(scrapy.Spider):
# Name of the spider
name = "schmid-catalog-spider"
# URLs of each scho... | to be | added
description = sel.xpath('text()').extract()
# Array containing subjects, or description with or without links that come after the subHeading
tableTxt = sel.xpath('tr/td')
# If there are links then they must be put into the description
if links != empty:
descs.append(info)
# Subhea... |
Mozu/mozu-python-sdk | mozurestsdk/commerce/catalog/storefront/shipping.py | Python | apache-2.0 | 1,607 | 0.04107 |
"""
This code was generated by Codezu.
Changes to this file may cause incorrect behavior and will be lost if
the code is regenerated.
"""
from mozurestsdk.mozuclient import default as default_client
from mozurestsdk.mozuurl import MozuUrl;
from mozurestsdk.urllocation import UrlLocation
from mozure... | ields (string) - Use this field to include those fields which are not included by default.
Returns:
| RatesResponse
Raises:
| ApiException
"""
url = MozuUrl("/api/commerce/catalog/storefront/shipping/request-rates?responseFields={responseFields}", "POST", UrlLocation.TenantPod, False)... | eturn self.client.result();
|
ecthros/pina-colada | capabilities/arp/arpDos.py | Python | mit | 2,614 | 0.009564 | from util_arp import *
import os
from capability import *
#masq_ip: ip we masquerade as.
#masc_mac: Masqueraded mac address
#source_mac: Our mac address
#Dest IP: target ip
#Dest Mac: target mac address
#ex: arpSpoof("10.0.0.1", "00:0c:29:5f:e7:50", "b8:27:eb:c2:1c:52", "10.0.0.57", "00:0c:29:08:45:1a")
class arpDos(C... | )))
self.source_ip = self.exec_command("SELECT IP FROM COMPUTERS WHERE ID = '{0}'".format(self.get_value("source")))
self.source_mac = self.exec_command("SELECT MAC FROM COMPUTERS WHERE ID = '{0}'".format(self.get_value("source")))
self.dest_ip = self.exec_command("SELECT IP FROM COMPUTERS WHERE... | ".format(self.get_value("dest")))
def arpGo(self):
os.system("echo 0 > /proc/sys/net/ipv4/ip_forward")
return arpBegin(self.masq_ip, self.masq_mac, self.source_mac, self.dest_ip, self.dest_mac)
def restore(self):
self.getVars()
self.proc.terminate()
arpEnd(self.masq_... |
fran-bravo/pylogic-module | test/test_knowledge_base2.py | Python | mit | 1,776 | 0.006194 | import pytest, sys, os
sys.path.append(os.path.dirname(os.path.realpath(__file__)) + "/../")
from unittest import TestCase
from pylogic.case import Case
from pylogic.knowledge_base import KnowledgeBase
from pylogic.functions import _, count_answers
class TestKnowledgeBase2(TestCase):
base2 = KnowledgeBase(3)
... | rlos", 4, True) == False
def test_tally7(self):
assert self.base2.tally("default", _, 4, _) == [("Nombre", 4, True), ("Apellido", 4, False)]
def test_tally_all(self):
assert self.base2.tally("default", _, _, _) == [("Nombre", 4, True), ("Apellido", 4, False), ("Apellido", 5, True), (object, li... |
assert self.base2.tally(_, _, _, _) == [("Nombre", 4, True), ("Apellido", 4, False), ("Apellido", 5, True), (object, list, 4), (True, "premio", 3)]
def test_amount_of_answers_empty(self):
assert count_answers(_, _, _) == 3
def test_amount_of_answers_full(self):
assert count_answers("... |
wjlei1990/EarlyWarning | nn.linear/nn_cuda.py | Python | gpl-3.0 | 9,359 | 0.001282 | from __future__ import print_function, division
import os
import sys
import time
import h5py
import torch
from torch import nn
from torch.autograd import Variable
import torch.nn.functional as F
import torch.utils.data as Data
import numpy as np
import json
from sklearn.metrics import mean_squared_error
from obspy.sign... | rint("Time used in reading data: %.2f sec" % (t2 - t1))
print("train x and y shape: ", train_x.shape, train_y.shape)
print("test x and y shape: ", test_x.shape, test_y.shape)
print("train d and test d shape: ", train_d.shape, test_d.shape)
return {"train_x": train_x, "train_y": train_y,
"tes... | orch_dataset = Data.TensorDataset(data_tensor=xs, target_tensor=ys)
loader = Data.DataLoader(dataset=torch_dataset, batch_size=1,
shuffle=True)
return loader
def predict_on_test(net, test_x):
print("Predict...")
pred_y = []
for idx in range(len(test_x)):
x = te... |
ybonjour/nuus | services/newsletter/Service.py | Python | mit | 1,883 | 0.007435 | __author__ = 'Yves Bonjour'
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../common"))
from WerkzeugService import create_status_error_response
from WerkzeugService import create_status_ok_response
from WerkzeugService import WerkzeugService
from werkzeug.routing import Map, Rule
f... | t ValueError:
print(usage)
quit()
service = create_newsletter_service(sys.argv[1 | ], port)
service.run() |
IsaacYangSLA/nuxeo-drive | nuxeo-drive-client/alembic/versions/4630af827798_adding_last_filter_date_to_server_.py | Python | lgpl-2.1 | 809 | 0.004944 | """Adding last_filter_date to server_bindings, and filters table
Revision ID: 4630af827798
Revises: 511f0b83a413
Create Date: 2014-05-22 12:10:02.930332
"""
# revision identifiers, used by Alembic.
revision = '4630af827798'
down_revision = '511f0b83a413'
from alembic import op
import sqlalchemy as sa
fro | m nxdrive.logging_config import get_logger
from nx | drive.engine.dao.model import ServerBinding
log = get_logger(__name__)
def upgrade():
op.add_column(ServerBinding.__tablename__, sa.Column('last_filter_date',
sa.Integer()))
# The table filters should create itself
def downgrade():
log.info("As S... |
SMTG-UCL/galore | docs/source/api_demo_pdos_broadening.py | Python | gpl-3.0 | 614 | 0.004886 | #! /usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
plt.style.use("seaborn-colorblind")
import galore
import galore.plot
vasprun = | './test/MgO/vasprun.xml.gz'
xmin, xmax = (-10, 2)
fig = plt.figure()
for i, l in enumerate(np.arange(0.05, 0.50, 0.05)):
ax = fig.add_subplot(3, 3, i + 1)
ax.set_title("$\gamma = {0:4.2f}$".format(l))
plotting_data = galore.process_pdos(input=[vasprun], lorentzian=l,
... | le(False)
fig.tight_layout()
plt.show()
|
txtsd/Plight-Rising | classes/FRAccount.py | Python | gpl-3.0 | 7,336 | 0.00368 | # ---------------------------------------------------------------------
# ------------------------- Plight Rising -----------------------------
# -----------------------------txtsd-----------------------------------
# ---------------------------------------------------------------------
"""Handles the account, login, ... | 'p': 'hoard',
},
headers={
'Referer': 'http://www1.flightrising.com/'
},
| timeout=90
)
if re.search(self.un, self.result2.text):
# self.ID = self.session.cookies['userid']
self.ID = re.search('clan-profile\/(\d+)">Clan Profile', self.result.text).group(1)
print(... |
wfxiang08/sqlalchemy | test/engine/test_execute.py | Python | mit | 92,658 | 0.000183 | # coding: utf-8
from sqlalchemy.testing import eq_, assert_raises, assert_raises_message, \
config, is_, is_not_, le_
import re
from sqlalchemy.testing.util import picklers
from sqlalchemy.interfaces import ConnectionProxy
from sqlalchemy import MetaData, Integer, String, INT, VARCHAR, func, \
bindparam, selec... | n this test. (1.2.2b3,
# 1.2.2c1, 1.2.2)
@testing.skip_if(
lambda: testing.against('mysql+mysqldb'), 'db-api flaky') |
@testing.fails_on_everything_except(
'postgresql+psycopg2', 'postgresql+psycopg2cffi',
'postgresql+pypostgresql', 'mysql+mysqlconnector',
'mysql+pymysql', 'mysql+cymysql')
def test_raw_python(self):
def go(conn):
conn.execute(
'insert into users (user... |
wangjinyu/api_server | api_server/settings.py | Python | mit | 3,284 | 0.00335 | """
Django settings for api_server project.
Generated by 'django-admin startproject' using Django 1.11.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import... | e.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware' | ,
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'api_server.urls'
AUTH_USER_MODEL = 'api.UserInfo'
TEMPLATES = [
{
'BACKEND': 'django.template.backend... |
MPjct/PyMP | mysql_proto/com/refresh.py | Python | mit | 710 | 0 | # coding=utf-8
from ..packet | imp | ort Packet
from ..proto import Proto
from ..flags import Flags
class Refresh(Packet):
__slots__ = ('flags', ) + Packet.__slots__
def __init__(self):
super(Refresh, self).__init__()
self.flags = 0x00
def getPayload(self):
payload = bytearray()
payload.extend(Proto.build_b... |
tsheasha/fullerite | src/diamond/utils/classes.py | Python | apache-2.0 | 5,182 | 0.000579 | # coding=utf-8
import os
import sys
import logging
import inspect
import traceback
from diamond.util import load_class_from_name
from diamond.collector import Collector
def load_include_path(paths):
"""
Scan for and add paths to the include path
"""
for path in paths:
# Verify the path is va... | % modname)
if isinstance(err, SystemExit):
sys.exit(err.code)
raise KeyboardInterrupt
except:
| # Log error
log.error("Failed to import module: %s. %s",
modname,
traceback.format_exc())
continue
# Find all classes defined in the module
for attrname in dir(mod):
... |
rhettg/JoeTraffic | LogReader/read_job.py | Python | lgpl-2.1 | 4,327 | 0.001618 | # JoeTraffic - Web-Log Analysis Application utilizing the JoeAgent Framework.
# Copyright (C) 2004 Rhett Garber
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as publ | ished by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WA | RRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc... |
spatialaudio/python-sounddevice | examples/rec_unlimited.py | Python | mit | 2,826 | 0 | #!/usr/bin/env python3
"""Create a recording with arbitrary duration.
The soundfile module (https://PySoundFile.readthedocs.io/) has to be installed!
"""
import argparse
import tempfile
import queue
import sys
import sounddevice as sd
import soundfile as sf
import numpy # Make sure NumPy is loaded before it is used... | args.filename = tempfile.mktemp(prefix='delme_rec_unlimited_',
suffix='.wav', dir='')
# Make sure the file is opened before recording anything:
with sf.SoundFile(args.filename, mode='x', samplerate=args.samplerate,
channels=args.channels, su... | channels=args.channels, callback=callback):
print('#' * 80)
print('press Ctrl+C to stop the recording')
print('#' * 80)
while True:
file.write(q.get())
except KeyboardInterrupt:
print('\nRecording finished: ' + repr(args.filename))
parser.ex... |
mgiger/MobilePerformance | mobile/models.py | Python | mit | 1,874 | 0.056564 | from __future__ import unicode_literals
from django.db import models
class Device(models.Model):
app_label = 'devices'
name = models.CharField(max_length=128, primary_key=True)
last_update = models.DateTimeField(auto_now=True)
modelNames = {
'x86_64':'iPhone Simulator',
'iPhone1,1':'iPhone 1G',
'iPhone1,2':... | 'iPod3,1':'iPod Touch 3G',
'iPod4,1':'iPod Touch 4G',
'iPod5,1':'iPod Touch 5G',
'iPad1,1':'iPad 1',
'iPad2,1':'iPad 2 (WiFi)',
'iPad2,2':'iPad 2 (GSM)',
'iPad2,3':'iPad 2 (CDMA)',
'iPad2,4':'iPad 2 (WiFi)',
'iPad2,5':'iPad Mini (WiFi)',
'iPad2,6':'iPad Mini (GSM)',
'iPad2,7':'iPad Mini (GSM+CDMA)'... | WiFi)',
'iPad3,2':'iPad 3 (GSM+CDMA)',
'iPad3,3':'iPad 3 (GSM)',
'iPad3,4':'iPad 4 (WiFi)',
'iPad3,5':'iPad 4 (GSM)',
'iPad3,6':'iPad 4 (GSM+CDMA)',
'iPad4,1':'iPad Air (WiFi)',
'iPad4,2':'iPad Air (GSM+CDMA)',
'iPad4,4':'iPad Mini Retina (WiFi)',
'iPad4,5':'iPad Mini Retina (GSM+CDMA)'
}
class P... |
rammie/pdfjinja | setup.py | Python | mit | 799 | 0 | #!/usr/bin/env python
""" Package install script. """
import os
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
f = open(os.path.join(os.path.dirname(__file__), "README.rs | t"))
readme = f.read()
f.close()
setup(
name="pdfjinja",
version="1.1.0",
author="Ram Mehta",
author_email="ram.mehta@gmail.com",
url="http://github.com/rammie/pdfjinja/",
description='Use jinja templates to fill and sign pdf forms.',
long_description=readme,
py_modules=["pdfjinja"],
... | "Pillow>=3.2.0",
"PyPDF2>=1.25.1",
"reportlab>=3.3.0"
])
|
zakandrewking/cobrapy | cobra/solvers/coin.py | Python | lgpl-2.1 | 4,311 | 0 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from cobra.core.solution import LegacySolution
from cylp.cy import CyClpSimplex
from cylp.cy.CyCoinPackedMatrix import CyCoinPackedMatrix
from cylp.py.modeling.CyLPModel import CyLPArray
solver_name = "coin"
_status_translation = {"primal infeasible": "i... | @property
def objectiveValue_(self):
return self.cbc.objectiveValue if self.cbc else self.objectiveValue
def create_pro | blem(cobra_model, objective_sense="maximize", **kwargs):
m = cobra_model.to_array_based_model(deepcopy_model=True)
lp = Coin()
v = lp.addVariable("v", len(m.reactions))
for i, rxn in enumerate(m.reactions):
if rxn.variable_kind == "integer":
lp.setInteger(v[i])
S = m.S
v.lowe... |
waseem18/oh-mainline | vendor/packages/zope.interface/src/zope/interface/common/tests/test_import_interfaces.py | Python | agpl-3.0 | 928 | 0.00431 | ##############################################################################
#
# Copyright (c) 2006 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOF... | ##################################################
import doctest
import unittest
def test_interface_import():
"""
>>> import zope.interface.common.interfaces
"""
def test_suite():
return unittest.TestSuite((
doctest.DocTestSuite(),
))
if __name__ == '__main__':
unittest.main(defa... | _suite')
|
SMALLplayer/smallplayer-image-creator | storage/.xbmc/addons/script.module.urlresolver/lib/urlresolver/plugins/novamov.py | Python | gpl-2.0 | 3,302 | 0.005451 | """
urlresolver XBMC Addon
Copyright (C) 2011 t0mm0
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
... | r
from urlresolver.plugnplay.interfaces import PluginSettings
from urlresolver.plugnplay import Plugin
from lib import unwise
#SET ERROR_LOGO# THANKS TO VOINAGE, BSTRDMKR, ELDORADO
error_logo = os.path.join(comm | on.addon_path, 'resources', 'images', 'redx.png')
class NovamovResolver(Plugin, UrlResolver, PluginSettings):
implements = [UrlResolver, PluginSettings]
name = "novamov"
def __init__(self):
p = self.get_setting('priority') or 100
self.priority = int(p)
self.net = Net()
def get... |
cybertron/tripleo-auto-abandon | doc/source/conf.py | Python | apache-2.0 | 2,468 | 0.00081 | # -*- 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... | ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the Licens | e.
import os
import sys
sys.path.insert(0, os.path.abspath('../..'))
# -- General configuration ----------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = [
'sp... |
django-crispy-forms/django-crispy-forms | crispy_forms/templatetags/crispy_forms_tags.py | Python | mit | 10,238 | 0.001954 | from functools import lru_cache
from django import template
from django.conf import settings
from django.forms.formsets import BaseFormSet
from django.template.loader import get_template
from crispy_forms.helper import FormHelper
from crispy_forms.utils import TEMPLATE_PACK, get_template_pack
register = template.Lib... | rs.get("formset_error_title", None),
"help_text_inline": attrs.get("help_text_inline", False),
"include_media": attrs.get("include_media", True),
"inputs": attrs.get("inputs", []),
"is_formset": is_for | mset,
"label_class": attrs.get("label_class", ""),
"template_pack": self.template_pack,
}
# Handles custom attributes added to helpers
for attribute_name, value in attrs.items():
if attribute_name not in response_dict:
response_dict[attribute_... |
wavefrontHQ/python-client | test/test_source_api.py | Python | apache-2.0 | 2,945 | 0 | # coding: utf-8
"""
Wavefront REST API
<p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.</p><p>When you make REST API calls outside the Wavefront REST ... | ce # noqa: E501
"""
pass
def test_ | remove_source_tag(self):
"""Test case for remove_source_tag
Remove a tag from a specific source # noqa: E501
"""
pass
def test_set_description(self):
"""Test case for set_description
Set description associated with a specific source # noqa: E501
"""
... |
D4wN/brickv | src/build_data/windows/OpenGL/GL/ATI/separate_stencil.py | Python | gpl-2.0 | 689 | 0.013062 | '''OpenGL extension ATI.separate_stencil
This module customises the behaviour of the
OpenGL.raw.GL.ATI.separate_stencil to provide a more
Python-friendly API
Overview (from the spec)
This extension provides the ability to modify the stencil buffer
differently based on the facing direction of the primitive that
... | ailable here:
http://www.opengl.org/registry/specs/ | ATI/separate_stencil.txt
'''
from OpenGL import platform, constants, constant, arrays
from OpenGL import extensions, wrapper
from OpenGL.GL import glget
import ctypes
from OpenGL.raw.GL.ATI.separate_stencil import *
### END AUTOGENERATED SECTION |
polarise/breeze | breeze/splice_mapping.py | Python | gpl-2.0 | 3,421 | 0.062555 | # -*- encoding: utf-8 -*-
import sys
import os
import os.path
import glob
import logging
from utils import *
def splice_mapping( T, configs, audit ):
logging.debug( "Splice mapping..." )
# create the destination for splice alignments if not exists
try:
os.mkdir( configs['SPLICED_ALIGNER_PATH'] )
except OSError... | s ), \
| configs['SPLICED_ALIGNER_THREADS'], \
configs['GTF_PATH' + s], \
configs['EBWT_PATH' + s], \
trimmed_files[0], \
trimmed_files[1] )
elif configs['SPOT_TYPE'] == "single":
# spliced aligner
sa_cmd = "%s %s --output-dir %s --num-threads %s --GTF %s %s %s" % (
configs['SPLICED_ALIGNER'], ... |
lamblin/fuel | fuel/utils.py | Python | mit | 3,208 | 0 | import collections
import six
# See http://python3porting.com/differences.html#buffer
if six.PY3:
buffer_ = memoryview
else:
buffer_ = buffer # noqa
def lazy_property_factory(lazy_property):
"""Create properties that perform lazy loading of attributes."""
def lazy_property_getter(self):
if... | y_property)
# Iterators would lose their state
if isinstance(attr, collections.Iterator):
raise ValueError("Iterators can't be lazy loaded")
serializable_state.pop('_' + lazy_property, None)
return serializab | le_state
setattr(cls, '__getstate__', __getstate__)
return cls
return wrap_class
|
ibanner56/OtherDave | otherdave/commands/ignore.py | Python | mit | 2,051 | 0.005363 | import pickledb
import re
import yaml
from datetime import *
_ignoreUsage = "Sorry, I don't understand. The correct usage is '!ignore <-me | @user> [minutes]'."
_dmsUsage = "Sorry, I dom't understand. The correct usage is '!dms <-enable | -disable>'."
with open("./conf.yaml") as conf | :
config = yaml.load(conf, Loader=yaml.BaseLoader)
ignoreDb = pickledb.load("./data/ignore.db", True)
slideDb = pickledb.load("./data/slide.db", True)
async def ignore(ctx, args):
if (len(args) < 1 or len(args) > 2 | ):
return _ignoreUsage
try:
if (len(args) == 2):
mins = int(args[1])
else:
mins = 5
except ValueError:
return _ignoreUsage
ignoreTime = datetime.now() + timedelta(minutes=mins)
if (args[0] == "-me"):
ignoreDb.set(str(ctx.author.i... |
joejcollins/CaptainScarlet | web_app/main.py | Python | mit | 2,641 | 0.004544 | ''' Controller for the application '''
import logging
import sys
import traceback
import forms
from models import Settings
from flask import Flask, render_template
from google.appengine.api import app_identity # pylint: disable=E0401
from google.appengine.api import mail # pylint: disable=E0401
from google.appengine.ap... | = 'Message from Bagbatch W | ebsite'
message.to = Settings.get('EMAIL')
message.body = """From: {}\n\n<<BEGINS>>\n\n{}\n\n<<ENDS>>""".format(their_email, their_message)
message.send()
@app.errorhandler(500)
def server_error(error):
''' Log any errors to the browser because you are too lazy to look at the console
The Flask DEB... |
DevHugo/zds-site | zds/utils/migrations/0001_initial.py | Python | gpl-3.0 | 8,591 | 0.004656 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import easy_thumbnails.fields
from django.conf import settings
import zds.utils.models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL... | eTimeField(verbose_name=b'Date de publication', db_index=True)),
('author', models.ForeignKey(related_name='alerts', verbose_name=b'Auteur', to=settings.AUTH_USER_MODEL)),
],
options={
'verbose_name': 'Alerte',
'verbose_name_ | plural': 'Alertes',
},
bases=(models.Model,),
),
migrations.CreateModel(
name='Category',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('title', models.CharField... |
endthestart/tinsparrow | tinsparrow/tinsparrow/importer.py | Python | mit | 6,020 | 0.001661 | import acoustid
import logging
import os
from . import utils
from .models import Artist, Album, Song
from beets.mediafile import MediaFile, FileTypeError, UnreadableFileError
#LOSSY_MEDIA_FORMATS = ["mp3", "aac", "ogg", "ape", "m4a", "asf", "wma"]
LOSSY_MEDIA_FORMATS = ["mp3", "ogg", "m4a"]
LOSSLESS_MEDIA_FORMATS =... | hould only need to do this once per folder/album
album, album_created = Album.objects.get_or_create(
artist=artist,
title=media_dict['album']
)
song, song_created = Song.objects.get_or_create(
... | defaults={
'album': album,
'artist': artist,
'title': media_dict['title'],
'track': media_dict['track'],
'content_type': CONTENT_TYPES.get(media_file.type, 'mp3'),
... |
sthenc/pyKAM | Signal.py | Python | apache-2.0 | 2,314 | 0.013397 | #!/usr/bin/python3
################################################################################
#
# Copyright 2014 Stjepan Henc <sthenc@gmail.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 Lic... | self.fs = fs
self.sLength, self.nChans = self.s.shape
def __init__(self, *args):
#signal properties
self.singlePrecision = 0
self.s = np.array([])
self.fs = 441 | 00
self.sLength = 0
self.nChans = 0
self.weightingFunction = np.hamming #FIXME
#STFT properties
self.S = np.array([])
self.windowLength = 60
self.nfft = 0
self.nfftUtil = 0
self.overlapRatio = 0.5
self.framesPositions = np.array([]... |
greenteaphd/MaxCalester | MaxCalesterChipotleGreedy.py | Python | gpl-3.0 | 5,182 | 0.006368 | # MaxCalester Program - Chipotle
# Developed By: Andy Han
# Data Provided By: Ibrahima Dieye and Lang Li
# April 26th, 2017
# Macalester College
# COMP 221 - Algorithm Design and Analysis
# Questions? Contact us at dhan@macalester.edu
import csv
chipotle_best_combo = {}
chipotle_best_combo_price_calorie... | atios of said items.
chipotle_item_list = [] # The list of items you should buy to maximize caloric count. Items will be added soon.
# Below are the lines of code that are responsible for the importing of csv data into data points Python can work with.
# The program goes through a lot of sorting to ensure the greedy... | ted in the program.
# The csv file is a list of items. Each row has a item name, item's price, and item's calorie.
# Items are added to three different lists based on the csv import.
# CSV File Import
with open('final_chipotle.csv', 'r') as f:
reader = csv.reader(f, delimiter=',')
for row in reader:
... |
hafen/R-Box | box/__init__.py | Python | mit | 565 | 0.00177 | from .namespace import RBoxNameSpaceListener
from | .completion import RBoxCompletionListener, RBoxAutoComplete
from .popup import RBoxPopupListener, RBoxShowPopup
from .main_menu import RBoxMainMenuListener, RBoxPackageSendCodeCommand
from .render import RBoxRenderRmarkdownCommand, RBoxSweaveRnwCommand, RBoxKnitRnwCommand
from .source_prompt import RBoxSourcePromptComm... | from .extract_function import RBoxExtractFunctionCommand
from .utils import RBoxReplaceSelectionCommand
from .linter import install_linter_spec
|
theirc/ServiceInfo | service_info_cms/management/commands/change_cms_site.py | Python | bsd-3-clause | 2,125 | 0.001882 | from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.contrib.sites.models | import Site
from service_info_cms.uti | ls import change_cms_site
class Command(BaseCommand):
""" Similar: cms/management/commands/subcommands/copy_site.py """
help = 'Move the CMS pages from one site to another'
args = '< --from original_site_domain --to new_site_domain | --list >'
option_list = BaseCommand.option_list + (
make_o... |
google/parallel_accel | parallel_accel/Analysis/benchmarks/acyclic_graphs/quick_sim_acyclic_graphs/acyclic_graph_q28c0d14.py | Python | apache-2.0 | 110,293 | 0.002684 | # Copyright 2021 The ParallelAccel 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 appl... | 374620052682681*np.pi).on(q[23]),
linear_algebra.rotate_z_axis(rads=-0.6761129911991415*np.pi).on(q[24]),
linear_algebra.rotate_z_axis(rads=0.7477194843354747*np.pi).on(q[25]),
[linear_algebra.imaginary_swap(q[2], q[3])**-1.0083249302125585, linear_algebra.cond_flip_z(q[2], q[3])**-0.15792203777075314],
... | q[5])**1.821258607384058],
[linear_algebra.imaginary_swap(q[7], q[8])**-1.011139535097931, linear_algebra.cond_flip_z(q[7], q[8])**-0.15961800888489716],
[linear_algebra.imaginary_swap(q[9], q[10])**-0.9833734447968242, linear_algebra.cond_flip_z(q[9], q[10])**-0.16547385220334815],
[linear_algebra.imagina... |
rafamanzo/colab | colab/plugins/jenkins/data_api.py | Python | gpl-2.0 | 138 | 0 | from colab | .plugins.utils.proxy_data_api import ProxyDataAPI
class JenkinsDataAPI(ProxyDataAPI):
def fetch_data(self):
pass
| |
NoneGG/aredis | aredis/commands/keys.py | Python | mit | 11,719 | 0.000597 | import datetime
import time as mod_time
from aredis.exceptions import (ResponseError,
RedisError,
DataError)
from aredis.utils import (merge_result,
NodeFlag,
first_key,
b, dict_me... | _keys_to_dict,
list_keys_to_dict)
def sort_return_tuples(response, **options):
"""
If ``groups`` is specified, return the response as a | list of
n-element tuples with n being the value found in options['groups']
"""
if not response or not options['groups']:
return response
n = options['groups']
return list(zip(*[response[i::n] for i in range(n)]))
def parse_object(response, infotype):
"""Parse the results of an OBJECT ... |
odoousers2014/LibrERP | l10n_it_sale_group/__init__.py | Python | agpl-3.0 | 1,004 | 0.001992 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2010 Associazione OpenERP Italia
# (<http://www.openerp-italia.org>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero G... | our 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 Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
######################... |
ipab-rad/perf_ros | src/tool/problem.py | Python | mit | 12,503 | 0.009118 |
import model as Model
NODES_PER_ROBOT = 6
ROBOT_CPU_CAPACITY = 100
SERVER_CAPACITY = 400 # for greedy_2 the value must be 0
ALGORITHM = 'greedy_1' # greedy_2
###################################################################################################
def generate(num_computers, num_robots, num_cameras):
... | if ALGORITHM == 'greedy_1':
setting_min = Model.Setting(node, 59, 100, [], 'S1')
setting_max = Model.Setting(node, 17, 20, [], 'S2')
node.settings = [setting_min, setting_max]
elif ALGORITHM == 'greedy_2':
setting = Model.Setting(node, 39, 70, [], 'S1')
... | 3.64
num_node += 1
# Planner
id = 'N' + str(num_node)
planner_node = Model.Node(id, [], None)
setting = Model.Setting(planner_node, 1, 1, [], 'S1')
planner_node.settings = [setting]
nodes[planner_node.id] = planner_node
planner_node.formula = 'x'
... |
rohitranjan1991/home-assistant | tests/components/unifiprotect/test_select.py | Python | mit | 19,520 | 0.000205 | """Test the UniFi Protect select platform."""
# pylint: disable=protected-access
from __future__ import annotations
from copy import copy
from datetime import timedelta
from unittest.mock import AsyncMock, Mock, patch
import pytest
from pyunifiprotect.data import Camera, Light
from pyunifiprotect.data.devices import ... | t,
viewer: Viewer,
):
"""Test select entity setup for light devices."""
entity_registry = er.async_get(hass)
description = VIEWER_SELECTS[0]
unique_id, entity_id = ids_from_device_description(
Platform.SELECT, viewer, description
)
entity = entity_registry.async_get(entity_id)
... | e
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
async def test_select_setup_camera_all(
hass: HomeAssistant,
camera: Camera,
):
"""Test select entity setup for camera devices (all features)."""
entity_registry = er.async_get(hass)
expected_values = ("Always", "Auto", "Defau... |
miptliot/edx-platform | lms/djangoapps/class_dashboard/tests/test_views.py | Python | agpl-3.0 | 4,059 | 0.002956 | """
Tests for class dashboard (Metrics tab in instructor dashboard)
"""
import json
from django.test.client import RequestFactory
from mock import patch
from nose.plugins.attrib import attr
from class_dashboard import views
from student.tests.factories import AdminFactory
from xmodule.modulestore.tests.django_utils i... | self.request.user = instructor
response = views.all_sequential_open_distrib(self.request, course.id.to_deprecated_string())
self.assertEqual('[]', response.content)
response = views.all_problem_grade_distribution(self.request, course.id.to_deprecated_st | ring())
self.assertEqual('[]', response.content)
response = views.section_problem_grade_distrib(self.request, course.id.to_deprecated_string(), 'no section')
self.assertEqual('{"error": "error"}', response.content)
|
rednaxelafx/apache-spark | python/pyspark/sql/tests/test_types.py | Python | apache-2.0 | 42,348 | 0.002197 | # -*- encoding: utf-8 -*-
#
# Licen | sed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this wor | k 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 this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unles... |
lheido/lheidoEdit | extend.py | Python | gpl-3.0 | 2,501 | 0.035186 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import re
import os
import sys
from inspect import isclass
class Extend(object):
def __init__(self, **kwargs):
self.lang = kwargs["lang"]
self.override = kwargs["over"]
self.name = kwargs["name_"]
self.obj = kwargs["obj_"]
def extend(language=None, override=None, ... | e(value, Extend):
user_extensions.append(value)
if mth: # obj is methode
obj_name = obj.__name__
def wrapper(self, **kwargs):
funs = {ext.lang: ext.obj for ext in user_extensions if ext.override and ext.name == obj_name}
if hasattr(self, "lang") and self.lang in funs: funs[self.lang](self, **... | s:
if isclass(ext.obj) and issubclass(ext.obj, obj):
return ext.obj
return obj
return decorator
|
fengkaicnic/traffic | traffic/openstack/common/cfg.py | Python | apache-2.0 | 55,915 | 0.000054 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#... | ', '--debug', '/tmp/mything']
i.e. argument parsing is stopped at the first non-option argument.
Options may be declared as required so that an error is raised if the user
does not supply a value for the option.
Options may be declared as secret so that their values are not leaked into
log files:
opts = [
... | tains a global instance of the CommonConfigOpts class
in order to support a common usage pattern in OpenStack:
from openstack.common import cfg
opts = [
cfg.StrOpt('bind_host' default='0.0.0.0'),
cfg.IntOpt('bind_port', default=9292),
]
CONF = cfg.CONF
CONF.register_opts(opts)
def start(server, ... |
mocacinno/mocacoin | qa/rpc-tests/test_framework/comptool.py | Python | mit | 18,040 | 0.004545 | #!/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 .mininode import *
from .blockstore import BlockStore, TxStore
from .util import p2p_port
'''
This is a tool for comparing two or more mocacoinds... | a] = RejectResult(message.code, message.reason)
if message.message == b'block':
| self.block_reject_map[message.data] = RejectResult(message.code, message.reason)
def send_inv(self, obj):
mtype = 2 if isinstance(obj, CBlock) else 1
self.conn.send_message(msg_inv([CInv(mtype, obj.sha256)]))
def send_getheaders(self):
# We ask for headers from their last t... |
trosa/forca | gluon/contrib/rss2.py | Python | gpl-2.0 | 14,669 | 0.001023 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""PyRSS2Gen - A Python library for generating RSS 2.0 feeds."""
__name__ = 'PyRSS2Gen'
__version__ = (1, 0, 0)
__author__ = 'Andrew Dalke <dalke@dalkescientific.com>'
_generator_name = __name__ + '-' + '.'.join(map(str, __version__))
import datetime
import cStringIO
#... | type
def publish(self, handler):
_element(handler, 'enclosure', None,
{'url': self.url, 'length': str(self.length), 'type': self.type})
class Source:
"""Publish the item's original source, used by aggre | gators"""
def __init__(self, name, url):
self.name = name
self.url = url
def publish(self, handler):
_element(handler, 'source', self.name, {'url': self.url})
class SkipHours:
"""Publish the skipHours
This takes a list of hours, as integers.
"""
element_attrs = {}
... |
googleapis/python-compute | google/cloud/compute_v1/services/global_public_delegated_prefixes/pagers.py | Python | apache-2.0 | 3,216 | 0.001555 | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
request (google.cloud.compute_v1.types.ListGlobalPublicDelegatedPrefixesRequest):
| The initial request object.
response (google.cloud.compute_v1.types.PublicDelegatedPrefixList):
The initial response object.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method... |
mscuthbert/abjad | abjad/tools/stringtools/is_lower_camel_case.py | Python | gpl-3.0 | 652 | 0.001534 | # - | *- encoding: utf-8 -*-
import re
import six
lowercamelcase_regex = re.compile(
'^([a-z,0-9]+([A-Z,0-9]+[a-z,0-9]*)*)?$',
re.VERBOSE,
)
def is_lower_camel_case(expr):
r'''Is true when `expr` is a string and is lowercamelcase.
.. container:: example
::
>>> stringtools.is_lo... | ::
>>> stringtools.is_lower_camel_case('FooBar')
False
Returns boolean.
'''
if not isinstance(expr, six.string_types):
return False
return bool(lowercamelcase_regex.match(expr)) |
valentine20xx/portal | portal/settings.py | Python | gpl-3.0 | 4,119 | 0.000486 | import os
from django.contrib.messages import constants
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECR... | True
},
},
]
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"django.contrib.admindocs",
"conver... | "django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.auth.middleware.SessionAuthenticationMiddleware",
"django.contrib.messages.m... |
RobMcZag/python-algorithms | sort/sortTest.py | Python | apache-2.0 | 2,502 | 0.009992 | import unittest
import random
import sort
class SortTest(unittest.TestCas | e):
def testLessOnStrings(self):
self.assertEqual(True, "a" < "b")
def testSwapOnNonEmptyList(self):
l = [1, 2, 3]
sort.swap(l, 1, 2)
self.assertEqual(l, [1, 3, 2])
def testSwapOnNonEmptyListOfStrings(self):
l = ["a", "b", "c"]
sort.swap(l, 1, 2)
se... | "c", "b"])
def testInsertionSort(self):
l = [2, 3, 1]
sort.insertion(l)
self.assertEqual(l, [1, 2, 3])
def testMergeSort(self):
l = [2, 3, 1]
sort.mergesort(l)
self.assertEqual(l, [1, 2, 3])
def testMergeSort2(self):
l = [2, 3, 1, 7, 8, 1 , 8 , 8, 2... |
kashif/scikit-learn | sklearn/externals/joblib/my_exceptions.py | Python | bsd-3-clause | 3,690 | 0.000271 | """
Exceptions
"""
# Author: Gael Varoquaux < gael dot varoquaux at normalesup dot org >
# Copyright: 2010, Gael Varoquaux
# License: BSD 3 clause
import sys
from ._compat import PY3_OR_LATER
class JoblibException(Exception):
"""A simple exception with an error message that you can get to."""
def __init__(se... | )
__str__ = __repr__
class TransportableException(JoblibException):
"""An exception containing all t | he info to wrap an original
exception and recreate it.
"""
def __init__(self, message, etype):
# The next line set the .args correctly. This is needed to
# make the exception loadable with pickle
JoblibException.__init__(self, message, etype)
self.message = message
... |
lmazuel/azure-sdk-for-python | azure-mgmt-cosmosdb/azure/mgmt/cosmosdb/models/operation_display.py | Python | mit | 1,519 | 0.000658 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | Description of operation
:type description: str
"" | "
_attribute_map = {
'provider': {'key': 'Provider', 'type': 'str'},
'resource': {'key': 'Resource', 'type': 'str'},
'operation': {'key': 'Operation', 'type': 'str'},
'description': {'key': 'Description', 'type': 'str'},
}
def __init__(self, provider=None, resource=None, op... |
ionutbalutoiu/ironic | ironic/drivers/fake.py | Python | apache-2.0 | 11,459 | 0 | # -*- encoding: utf-8 -*-
#
# Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# 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
#
# ... | rom ironic.drivers.modules import wol
from ironic.drivers import utils
class FakeDriver(base.BaseDriver):
"""Example implementation of a Driver."""
def __init__(self):
self.power = fake.FakePower()
self.deploy = fake.FakeDeploy()
self.boot = fake.FakeBoot()
self.a = fake.Fake... | self.a,
'second_method': self.b,
'third_method_sync': self.b}
self.vendor = utils.MixinVendorInterface(self.mapping)
self.console = fake.FakeConsole()
self.management = fake.FakeManagement()
self.inspect = fake.FakeInspect()
self.ra... |
miltonlab/course-python-datascience-ms | DAT210x/Module2/assignment3.py | Python | apache-2.0 | 1,286 | 0.012442 | import pandas as pd
# TODO: Load up the dataset
# Ensuring you set the appropriate header column names
#
# .. your code here ..
df = pd.read_csv('~/courses/course-python-datascience-ms/DAT210x/Module2/Datasets/servo.data',
names=['motor', 'screw', 'pgain', 'vgain', 'class'])
# TODO: Create a slice ... | #
# .. your code here ..
samples2 = df[(df['motor'] == 'E') & (df['screw'] == 'E')]
print (le | n(samples2))
# TODO: Create a slice that contains all entries
# having a pgain equal to 4. Use one of the
# various methods of finding the mean vgain
# value for the samples in that slice. Once
# you've found it, print it:
#
# .. your code here ..
samples3 = df[df.pgain == 4]
mean = samples3.vgain.mean()
print (mea... |
custode/reviewboard | reviewboard/scmtools/evolutions/__init__.py | Python | mit | 433 | 0 | from __future__ import unicode_literals
SEQUENCE = [
'bugzilla_url_charfield',
'repository_raw_file_url',
'repository_visible',
'repository_path_length_255',
'localsite',
'repository_access_control',
'group_site',
'repository_hosting_accounts',
'repository_ex | tra_data_null',
'unique_together_baseline',
'repository_archi | ve',
'repository_hooks_uuid',
'repository_raw_password',
]
|
lcpt/xc | verif/tests/preprocessor/sets/sets_boolean_operations_01.py | Python | gpl-3.0 | 1,078 | 0.047354 | # -*- coding: utf-8 -*-
CooMax= 10
import xc_base
import geom
import xc
import math
from model.sets import sets_mng a | s sUtils
__author__= "Luis C. Pérez Tato (LCPT)"
__copyright__= "Copyright 2014, LCPT"
__license__= "GPL"
__version__= | "3.0"
__email__= "l.pereztato@gmail.com"
feProblem= xc.FEProblem()
preprocessor= feProblem.getPreprocessor
points= preprocessor.getMultiBlockTopology.getPoints
pt1= points.newPntIDPos3d(1,geom.Pos3d(0.0,0.0,0.0))
pt2= points.newPntIDPos3d(2,geom.Pos3d(CooMax/2,CooMax/2,CooMax/2))
pt3= points.newPntIDPos3d(3,geom.Po... |
jasonamyers/h4cn-index | app/surveys/views.py | Python | mit | 1,285 | 0.000778 | from flask import Blueprint, request, render_template, redirect, url_for
from app import db
from app.surveys.models import Surveys, Questions
from app.surveys.forms import SurveyForm, QuestionForm
mod = Blueprint('surveys', __name__, url_prefix='/surveys')
@mod.route('/')
def surveys():
surveys = Surveys.query.... | st.method == 'GET':
return render_template('surveys/create.html', form=form)
elif request.method == 'POST':
survey = Surveys(form.name.data, form.desc.data, form.active.data)
db.session.add(survey)
db.session.commit()
return redirect(url_for('surveys.surveys_show', id=survey.... | tml', survey=survey)
@mod.route('/<int:id>/questions/add/')
def question_add(id):
if request.method == 'POST':
question = Questions(request.form['question_text'])
db.session.add(question)
db.session.commit()
return {'success': 'The question was added'}
|
jbedorf/tensorflow | tensorflow/python/keras/callbacks.py | Python | apache-2.0 | 59,212 | 0.006283 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | ce.
model: Model being trained.
do_v | alidation: Whether or not validation loop will be run.
batch_size: Number of samples per batch.
epochs: Number of epoch to train.
steps_per_epoch: Number of batches to run per training epoch.
samples: Number of training samples.
verbose: int, 0 or 1. Keras logging verbosity to pass to Prog... |
pollen/pyrobus | pyluos/modules/unknown.py | Python | mit | 5,986 | 0.002339 | from .module import Module
class Unknown(Module):
possible_events = {'changed', 'pressed', 'released'}
# control modes
_PLAY = 0
_PAUSE = 1
_STOP = 2
_REC = 4
def __init__(self, id, alias, device):
Module.__init__(self, 'Unknown', id, alias, device)
self._control = 0
... | power_ratio = s
self._push_value("power_ratio",s)
@property
def lux(self):
""" Light in lux. """
| return self._lux
@property
def load(self):
""" force """
return self._load
@property
def volt(self):
""" Voltage in volt. """
return self._volt
@volt.setter
def volt(self, new_val):
self._volt = new_val
self._push_value('volt', new_val)
|
burunduk3/t.sh | verdict.py | Python | gpl-2.0 | 2,357 | 0.014001 | #!/usr/bin/env python3
#
# t.py: utility for contest problem development
# Copyright (C) 2009-2017 Oleg Davydov
#
# 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... | LIMIT_MEMORY: 'ML',
}[result.value], test), False, **kwargs)
@classmethod
def fail_checker ( cls, test, result, comment, **kwargs ):
if result.value is RunResult.RUNTIME and result.exitcode == 1:
return cls ("WA/%d" % test, False, comment, **kwargs)
if result.value is RunRes... | def ok ( cls, **kwargs ):
return cls ("OK", True, **kwargs)
|
ct-23/home-assistant | homeassistant/components/emulated_hue/upnp.py | Python | apache-2.0 | 5,032 | 0 | """Provides a UPNP discovery method that mimicks Hue hubs."""
import threading
import socket
import logging
import select
from aiohttp import web
from homeassistant import core
from homeassistant.components.http import HomeAssistantView
_LOGGER = logging.getLogger(__name__)
class DescriptionXmlView(HomeAssistantVi... | e-bridgeid: 1234
ST: urn:schemas-upnp-org:device:basic:1
USN: uuid:Socket-1_0-221438K0100073::urn:schemas-upnp-org:device:basic:1
"""
self.upnp_response = resp_template.format(
advertise_ip, advertise_port).replace("\n", "\r\n") \
.encode('utf-8')
def ... | st address
ssdp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ssdp_socket.setblocking(False)
# Required for receiving multicast
ssdp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
ssdp_socket.setsockopt(
socket.SOL_IP,
socket.IP... |
ayepezv/GAD_ERP | openerp/tools/convert.py | Python | gpl-3.0 | 37,832 | 0.004864 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import cStringIO
import csv
import logging
import os.path
import re
import sys
import time
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
import pytz
from lxml import etree, b... | ode:
return_val = _eval_xml(self, n, env)
if return_val is not None:
args.append(return_val)
model = env[node.get('model', '')]._model
method = node.get('name')
# this one still depends on the old API
res = getattr(model, method)(env.cr, env.uid, *... | return res
elif node.tag == "test":
return node.text
class xml_import(object):
@staticmethod
def nodeattr2bool(node, attr, default=False):
if not node.get(attr):
return default
val = node.get(attr).strip()
if not val:
return default
return ... |
ammarkhann/FinalSeniorCode | lib/python2.7/site-packages/kombu/async/aws/__init__.py | Python | mit | 358 | 0 | # -*- coding: utf-8 -*-
from __future__ import absol | ute_import, unicode_literals
def connect_sqs(aws_access_ | key_id=None, aws_secret_access_key=None, **kwargs):
"""Return async connection to Amazon SQS."""
from .sqs.connection import AsyncSQSConnection
return AsyncSQSConnection(
aws_access_key_id, aws_secret_access_key, **kwargs
)
|
dhuang/incubator-airflow | kubernetes_tests/test_kubernetes_pod_operator_backcompat.py | Python | apache-2.0 | 23,072 | 0.001344 | # 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... | arguments=["echo 10"],
labels={"foo": "bar"},
name="test",
task_id="task",
in_cluster=False,
do_xcom_push=False,
)
context = create_context(k)
k.exe | cute(context)
actual_pod = self.api_client.sanitize_for_serialization(k.pod)
assert self.expected_pod['spec'] == actual_pod['spec']
assert self.expected_pod['metadata']['labels'] == actual_pod['metadata']['labels']
def test_pod_node_selectors(self):
node_selectors = {'beta.kubernete... |
mathturtle/tomviz | acquisition/tests/mock/mock_api.py | Python | bsd-3-clause | 1,036 | 0 | import time
from PIL import Image
from . import test_image, test_black_image, angle_to_page
from tomviz.acquisition.utility import tobytes
img = Image.open(test_image())
black = test_black_image().read()
connected = False
current_frame = None
def connect():
global connected
connected = True
return conne... |
return current_params
def preview_scan():
data = black
if current_frame:
img.seek(current_frame)
data = tobytes(img)
time.sleep(2)
return data
def stem_acq | uire():
data = black
if current_frame:
img.seek(current_frame)
data = tobytes(img)
time.sleep(3)
return data
|
mferenca/HMS-ecommerce | ecommerce/extensions/catalogue/migrations/0014_alter_couponvouchers_attribute.py | Python | agpl-3.0 | 991 | 0 | # -*- coding: utf-8 -*-
from | __future__ import unicode_liter | als
from django.db import migrations
from oscar.core.loading import get_model
ProductAttribute = get_model("catalogue", "ProductAttribute")
def alter_couponvouchers_attribute(apps, schema_editor):
"""Change the coupon_vouchers product attribute to be required."""
coupon_vouchers = ProductAttribute.objects.g... |
piyueh/PyFR-Cases | utils/batch_conversion.py | Python | mit | 6,025 | 0.000332 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2016 Pi-Yueh Chuang <pychuang@gwu.edu>
#
# Distributed under terms of the MIT license.
"""convert the output file in a batch"""
import os
import os.path as op
import sys
import argparse
if os.getenv("PyFR") is None:
raise Environmen... | h, ifile, ofile, degree)
def output_vtu(mesh, iFile, oFile, g=True, p="double", d=0):
"""convert a single .pyfrs file to .vtu file using PyFR's converter
Args:
mesh: mesh file (must end with .pyfrm)
input: input file name (must end with .pyfrs)
output: output file name (must end with ... | p: precision, either "single" or "double"
d: degree of the element (set this according the order of the polynimal)
"""
writerArgs = argparse.Namespace(
meshf=mesh, solnf=iFile, outf=oFile, precision=p,
gradients=g, divisor=d)
writer = pyfr.writers.get_writer_by_extn(".vtu",... |
pierce403/EmpirePanel | lib/modules/situational_awareness/host/get_proxy.py | Python | bsd-3-clause | 2,838 | 0.011276 | from lib.common import helpers
class Module:
def __init__(self, mainMenu, params=[]):
self.info = {
'Name': 'Get-Proxy',
'Author': ['@harmj0y'],
'Description': ("Enumerates the proxy server and WPAD conents for the current user. Part of PowerView."),
'Ba... | t:
print helpers.color("[!] Could not read module source path at: " + str(moduleSource))
return ""
moduleCode = f.read()
f.close()
# get just the code needed for the specified function
script = helpers.generate_dynamic_powershell_script(moduleCode, moduleName)
... | iteritems():
if option.lower() != "agent":
if values['Value'] and values['Value'] != '':
if values['Value'].lower() == "true":
# if we're just adding a switch
script += " -" + str(option)
else:
... |
joshvillbrandt/ArchitectClient | Architect/urls.py | Python | apache-2.0 | 334 | 0.005988 | from django.conf.urls import patterns, incl | ude, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'Architect.views.home'),
# Include an application:
# url(r'^app_name/', include('app_name.urls', namespace="app_name")),
url(r'^admin/', include(admin.site.urls)),
)
| |
easycoin-core/Easycoin | share/rpcuser/rpcuser.py | Python | mit | 1,111 | 0.006301 | #!/usr/bin/env python2
# Copyright (c) 2015 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
import hashlib
import sys
import os
from random import SystemRandom
import base64
import hmac
if len(sys.a... | equence))
salt = "".join([ | x[2:] for x in hexseq])
#Create 32 byte b64 password
password = base64.urlsafe_b64encode(os.urandom(32))
digestmod = hashlib.sha256
if sys.version_info.major >= 3:
password = password.decode('utf-8')
digestmod = 'SHA256'
m = hmac.new(bytearray(salt, 'utf-8'), bytearray(password, 'utf-8'), digestmod)
result... |
Wajihulhassan/SelfContainedPrevirt | tools/occam/occam/targets/interface.py | Python | bsd-3-clause | 5,659 | 0.003005 | # ------------------------------------------------------------------------------
# OCCAM
#
# Copyright © 2011-2012, SRI International
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redis... | t=True)
x = interface.parseInterface(tf.name)
progress = interface.joinInterfaces(iface, x) or progress
interface.writeInterface(iface, tf.name)
tf.unlink(tf.name)
return iface
def shallow(libs, iface):
tf = tempfile.NamedTemporaryFile(suffix='.iface', delete=False)
... | ace.emptyInterface()
for l in libs:
passes.interface(l, tf.name, [tf.name], quiet=True)
x = interface.parseInterface(tf.name)
interface.joinInterfaces(iface, x)
tf.unlink(tf.name)
return iface
def parse(fn):
if fn == '@main':
return interface.mainInterface()
else:
... |
MatheusDMD/InGodWeTruss | truss.py | Python | gpl-3.0 | 6,558 | 0.011741 | # -*- coding: utf-8 -*-
__author__ = "Matheus Marotzke"
__copyright__ = "Copyright 2017, Matheus Marotzke"
__license__ = "GPLv3.0"
import numpy as np
class Truss:
"""Class that represents the Truss and it's values"""
def __init__(self, nodes, elements):
self.nodes = nodes # List... | displacement in Y
else:
self.nodes[n / 2].fd_x.reaction = reaction_matrix[index][0]# Fill the spots with displacement in X
index += 1
return reaction_matrix
def calc_elements_stress(self):
# Method that calculates and sets stress values for Elements
... | # Iterates throw the elements and Calculate Stress
def calc_elements_strain(self):
# Method that calculates and sets strain values for Elements
for element in self.elements:
element.calc_element_strain() # Iterates throw the elements and Calculate ... |
chillinc/Flask-CQLEngine | testapp/app.py | Python | apache-2.0 | 682 | 0.001466 | import os
import sys
import traceback
from flask import Flask, redirect, render_template, request, url_for
from flask.ext.cqlengine import CQLEngine
from datetime import datetime
import sett | ings
# Initialize simple Flask application
app = Flask(__name__)
app.config.from_object(settings)
# This engages cqlengine so that the model works.
cqlengine = CQLEngine(app)
@app.route('/')
def home():
"""
Create a row in Cassandra and show count of rows
"""
from models import Foo
Foo.create(ki... | template('index.html', count=Foo.objects.count())
if __name__ == '__main__':
app.run()
|
attilaborcs/dnn-visualization | model.py | Python | mit | 3,922 | 0.002805 | # !/usr/bin/python
# @package model
# @author Attila Borcs
#
# Class for the deep neural net. Each class function wrapped with
# a decorator function using python @property for unifying
# the DNN functionalities when tensorflow graph initializer
# called (tf.global_variables_initializer())
import functools
impor... | e executed once. Subsequent calls to it will directly
return the result so that operations are added to the graph only once.
|
The operations added by the function live within a tf.variable_scope(). If
this decorator is used with arguments, they will be forwarded to the
variable scope. The scope name defaults to the name of the wrapped function.
credits: ttps://danijar.github.io/structuring-your-tensorflow-models
"""
a... |
philiparvidsson/pymake2 | src/pymake2/core/exceptions.py | Python | mit | 626 | 0.007987 | """
Contains the exception and error classes.
"""
#---------------------------------------
# CLASSES
#---------------------------------------
class NoSuchTargetError(Exception):
"""
An | attempt was made to make a target that does not exist.
"""
#---------------------------------------
# CONSTRUCTOR
#---------------------------------------
def __init__(self, target_name):
"""
Initializes the exception.
:param target_name: | Name of the missing target.
"""
super(NoSuchTargetError, self).__init__("no such target")
self.target_name = target_name
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.