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 |
|---|---|---|---|---|---|---|---|---|
lmazuel/azure-sdk-for-python | azure-mgmt-datalake-analytics/azure/mgmt/datalake/analytics/job/models/job_information.py | Python | mit | 6,107 | 0.000655 | # 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 ... | ey': 'priority', 'type': 'int'},
'submit_time': {'key': 'submitTime', 'type': 'iso-8601'},
'start_time': {'key': 'startTime', 'type': 'iso-8601'},
'end_time': {'key': 'endTime', 'type': 'iso-8601'},
'state': {'key': 'state', 'type': 'JobState'},
'result': {'key': 'result', 'type'... | 'log_file_patterns': {'key': 'logFilePatterns', 'type': '[str]'},
'related': {'key': 'related', 'type': 'JobRelationshipProperties'},
'tags': {'key': 'tags', 'type': '{str}'},
'error_message': {'key': 'errorMessage', 'type': '[JobErrorDetails]'},
'state_audit_records': {'key': 'stateAud... |
NiclasEriksen/importANT | pypf.py | Python | mit | 3,410 | 0 |
def neighbors(node, all_nodes):
dirs = [[0, 1], [1, 0], [-1, 0], [0, -1]]
ddirs = [[1, 1], [1, -1], [-1, 1], [-1, -1]]
result = set()
# cdef bool x
for dir in dirs:
nx, ny = node[0] + dir[0], node[1] + dir[1]
try:
all_nodes[nx][ny]
except IndexError:
... | 1 == r[1] and nx == r[0]:
y = True
if y and x:
result.add((nx, ny))
return result
def get_score(c, node, goal, heightmap):
score = c.score
if c.node[0] != node[ | 0] and c.node[1] != node[1]:
score += 14
else:
score += 10
gx = abs(goal[0] - c.node[0])
gy = abs(goal[1] - c.node[1])
score += (gx + gy) * 5
penalty = heightmap[c.node[0]][c.node[1]] * 1
# print(score, "penalty:", penalty)
score -= penalty
return score
class Candidate:... |
demisto/content | Packs/BitSight/Integrations/BitSightForSecurityPerformanceManagement/BitSightForSecurityPerformanceManagement_test.py | Python | mit | 2,406 | 0.003325 | import demistomock as demisto
from CommonServerPython import BaseClient
import BitSightForSecurityPerformanceManagement as bitsight
from datetime import datetime
def test_get_companies_guid_command(mocker):
# Positive Scenario
client = bitsight.Client(base_url='https://test.com')
res = {"my_company": {"g... |
def test_get_company_details_command(mocker):
inp_args = {'guid': '123'}
client = bitsight.Client(base_url='https://test.com')
res = {"name": "abc"}
mocker.patch.object(BaseClient, '_http_request', return_value=res)
_, outputs, _ = bitsight.get_company_details_command(client, inp_args)
ass... | s = {'guid': '123', 'first_seen': '2021-01-01', 'last_seen': '2021-01-02'}
client = bitsight.Client(base_url='https://test.com')
res = {"results": [{"severity": "severe"}]}
mocker.patch.object(BaseClient, '_http_request', return_value=res)
_, outputs, _ = bitsight.get_company_findings_command(client, ... |
cloudtools/awacs | awacs/mechanicalturk.py | Python | bsd-2-clause | 4,190 | 0.000716 | # Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from .aws import Action as BaseAction
from .aws import BaseARN
service_name = "Amazon Mechanical Turk"
prefix = "mechanicalturk"
class Action(BaseAction):
def __init__(self, action: str = None) -> ... | etReviewableHITs")
GrantBonus = A | ction("GrantBonus")
GrantQualification = Action("GrantQualification")
ListAssignmentsForHIT = Action("ListAssignmentsForHIT")
ListBonusPayments = Action("ListBonusPayments")
ListHITs = Action("ListHITs")
ListHITsForQualificationType = Action("ListHITsForQualificationType")
ListQualificationRequests = Action("ListQualif... |
Gitweijie/first_project | networking_cisco/db/migration/models/head.py | Python | apache-2.0 | 1,228 | 0 | # Copyright 2015 Cisco 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... | under the License.
from networking_cisco import backwards_compatibility as bc
from networking_cisco.plugins.cisco.db.device_manager import ( # noqa
hd_models)
from networking_cisco.plugins.cisco.db.l3 import ( # noqa
ha_db)
from networking_cisco.plugins.cisco.db.l3 imp | ort ( # noqa
l3_models)
from networking_cisco.plugins.ml2.drivers.cisco.n1kv import ( # noqa
n1kv_models)
from networking_cisco.plugins.ml2.drivers.cisco.nexus import ( # noqa
nexus_models_v2)
from networking_cisco.plugins.ml2.drivers.cisco.ucsm import ( # noqa
ucsm_model)
def get_metadata():
... |
AvadootNachankar/gstudio | gnowsys-ndf/gnowsys_ndf/ndf/management/commands/data_entry.py | Python | agpl-3.0 | 45,442 | 0.004577 | ''' -- imports from python libraries -- '''
import os
import csv
import json
import ast
import time
import datetime
''' imports from installed packages '''
from django.core.management.base import BaseCommand, CommandError
from mongokit import IS
try:
from bson import ObjectId
except ImportError: # old pymongo
f... |
json_file_content.append(row)
info_message = "\n- File '" + file_name + "' contains : " + str(total_rows) + " entries/rows (excluding top-header/column-names)."
print info_message
log_li... | json.dump(json_file_content,
json_file,
indent=4,
sort_keys=False)
if os.path.exists(json_file_path):
file_path = json_file_path
... |
CoderDojoSG/todo | todo1/application.py | Python | apache-2.0 | 1,472 | 0.007473 | from flask import Flask
from flask impo | rt make_response
from flask import request
from flask import | render_template
from flask import redirect
from flask import url_for
import logging
from logging.handlers import RotatingFileHandler
app = Flask(__name__)
@app.route('/')
def index():
app.logger.info('index')
username = request.cookies.get('username')
if (username == None):
return redirect(url_fo... |
jonathan-s/happy | happy/error.py | Python | apache-2.0 | 2,606 | 0.005372 | class EmptyResult(object):
'''
Null Object pattern to prevent Null reference errors
when there is no result
'''
def __init__(self):
self.status = 0
self.body = ''
self.msg = ''
self.reason = ''
def __nonzero__(self):
return False
class HapiError(ValueEr... | for key, val in data.items():
if not isinstance(val, basestring):
unicode_data[key] = unicod | e(val)
elif not isinstance(val, unicode):
unicode_data[key] = unicode(val, 'utf8', 'ignore')
else:
unicode_data[key] = val
return unicode_data
# Create more specific error cases, to make filtering errors easier
class HapiBadRequest(HapiError):
'''Er... |
DarkSand/Sasila | sasila/system_normal/processor/first_processor.py | Python | apache-2.0 | 1,026 | 0.000975 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from bs4 import BeautifulSoup as bs
from sasila.system_normal.spider.spider_core import SpiderCore
from sasila.system_normal.pipeline.console_pipeline import ConsolePipeline
from sasila.system_normal.processor.base_processor import BaseProcessor
from sasila.sys... | sponse.nice_join(a["href"])
yield {'url': url}
# if __name__ | == '__main__':
# spider = SpiderCore(FirstProcessor()).set_pipeline(ConsolePipeline()).start()
|
wrightjb/bolt-planar | transform.py | Python | bsd-3-clause | 12,182 | 0.002545 | #############################################################################
# Copyright (c) 2010 by Casey Duncan
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source c... | tor scaling
value scales the dimensions independently.
:type scaling: float or :class:`~planar.Vec2`
:rtype: Affine
"""
try:
sx = sy = float(scaling)
except TypeError:
sx, sy = scaling
return tuple.__new__(cls,
(sx, 0.0, 0.... | assmethod
def shear(cls, x_angle=0, y_angle=0):
"""Create a shear transform along one or both axes.
:param x_angle: Angle in degrees to shear along the x-axis.
:type x_angle: float
:param y_angle: Angle in degrees to shear along the y-axis.
:type y_angle: float
:rtyp... |
ARDivekar/SearchDistribute | other/Legacy/sqliteDefaults.py | Python | mit | 9,396 | 0.038314 | # Author: Abhishek Divekar, Jan 2016. Licence: Creative Commons.
import os
import sqlite3
import datetime
def get_conn(db_file_name):
#makes a new file if it does not exist
BASE_DIR = os.path.dirname(os.path.abspath(__file__)) #gets direcotry path in which file is stored.
db_path = os.path.join(BASE_DI... | print "%s is older than %s"%(table[i][1], table[j][1])
elif table[j][2]<table[i][2]:
print "%s is older than %s"%(table[j][1], table[i][1])
#OUTPUT:
# Emma is older than Stacy
"""
def insert_table_sqlite(conn, tablename, insert_params_list, tuple_values_list, commit=True):
insert_query= buil... | rt_params_list=insert_params_list, tuple_values_list=tuple_values_list)
# print insert_query
cursor=conn.cursor()
cursor.execute(insert_query)
if commit:
conn.commit()
# database_in_use(conn)
def insert_table_sqlite2(conn, tablename, parameters_tuple=(), tuple_values_list=[], commit=True, print_... |
lmazuel/azure-sdk-for-python | azure-mgmt-logic/azure/mgmt/logic/models/business_identity.py | Python | mit | 1,162 | 0 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License | .txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
cl... | ZZZ, 31, 32
:type qualifier: str
:param value: The user defined business identity value.
:type value: str
"""
_validation = {
'qualifier': {'required': True},
'value': {'required': True},
}
_attribute_map = {
'qualifier': {'key': 'qualifier', 'type': 'str'},
... |
woutdenolf/spectrocrunch | scraps/cod.py | Python | mit | 6,727 | 0.000743 | # -*- coding: utf-8 -*-
from peewee import *
import urllib
import tempfile
import os
from contextlib import contextmanager
from sshtunnel import SSHTunnelForwarder
import traceback
db = MySQLDatabase(
"cod", host="127.0.0.1", user="cod_reader", port=3308, connect_timeout=10000
)
# Get
# ssh wout@axil1.ua.ac.be... | and self.sat(self.celltemp)
)
@property
def filename(self):
return os.path.join("{}.cif".format(self.file))
@property
def path(self):
return os.path.join(tempfile.gettempdir(), "spec | trocrunch", "cif")
@property
def resourcename(self):
return os.path.join(self.path, self.filename)
@property
def url(self):
return "http://www.crystallography.net/cod/{}.cif".format(self.file)
def download(self):
filename = self.resourcename
if not os.path.isfile(f... |
TheLampshady/pascompiler | tests/test_variables.py | Python | apache-2.0 | 537 | 0.001862 | from tests.base import TestBase
from pascal.program import Program
class TestVariables(TestBase):
def test_pass_valid_var(self):
file_name = "tests/mock_pas/all_var.pas"
pascal_ | program = Program(file_name)
pascal_program.run()
self.assertEqual(len(pascal_program.symbol_table), 7)
self.assertEqual(pascal_program.symbol_addr | ess, 23)
def test_pass_assign(self):
file_name = "tests/mock_pas/variables.pas"
pascal_program = Program(file_name)
pascal_program.run()
|
plotly/plotly.py | packages/python/plotly/plotly/validators/cone/_showlegend.py | Python | mit | 404 | 0 | import _plotly_utils.basevalidators
class ShowlegendValidator(_plotly_utils.basevalidators.BooleanValidato | r):
def __init__(self, plotly_name="showlegend", parent_name="cone", **kwargs):
super(ShowlegendValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type= | kwargs.pop("edit_type", "style"),
**kwargs
)
|
Lucterios2/contacts | lucterios/mailing/docs/fr/conf.py | Python | gpl-3.0 | 9,330 | 0 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Lucterios mailing documentation build configuration file, created by
# sphinx-quickstart on Tue Dec 22 17:11:37 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in... | ries to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
# sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, stat... | tensions = []
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
# source_encodin... |
blockbomb/plover | plover/test_orthography.py | Python | gpl-2.0 | 4,487 | 0.002452 | # Copyright (c) 2013 Hesky Fisher
# See LICENSE.txt for details.
from orthography import add_suffix
import unittest
class OrthographyTestCase(unittest.TestCase):
def test_add_suffix(self):
cases = (
('artistic', 'ly', 'artistically'),
('cosmetic', 'ly', 'cosmetically'),
... | ennies'),
('pharmacy', 'ist', 'pharmacist'),
('melody', 'ist', 'melodist'),
('pacify', 'ist', 'pacifist'),
('geology', 'ist', 'geolo | gist'),
('metallurgy', 'ist', 'metallurgist'),
('anarchy', 'ist', 'anarchist'),
('monopoly', 'ist', 'monopolist'),
('alchemy', 'ist', 'alchemist'),
('botany', 'ist', 'botanist'),
('therapy', 'ist', 'therapist'),
('theory', 'ist', 'theor... |
weigq/pytorch-pose | example/main.py | Python | gpl-3.0 | 12,764 | 0.014964 | '''
chg1: first change to multi-person pose estimation
'''
from __future__ import print_function, absolute_import
import argparse
import time
import matplotlib.pyplot as plt
import os
import torch
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
import torchvision.datasets as datase... | curacy, AverageMeter, final_preds
from pose.utils.misc import save_checkpoint, save_pred, LRDecay
from pose.utils.osutils import mkdir_p, isfile, isdir, join
fro | m pose.utils.imutils import batch_with_heatmap
from pose.utils.transforms import fliplr, flip_back
import pose.models as models
import pose.datasets as datasets
model_names = sorted(name for name in models.__dict__
if name.islower() and not name.startswith("__")
and callable(models.__dict__[name]))
# to cala... |
emilybache/texttest-runner | src/main/python/storytext/bin/migrate_uimap.py | Python | mit | 1,119 | 0.004468 | #!/usr/bin/env python
from ConfigParser import ConfigParser
from ordereddict import O | rderedDict
import sys
def make_parser():
parser = ConfigParser(dict_type=OrderedDict)
parser.optionxform = str
return parser
def transform(sectionName):
sectionName = sectionName.replace(",Dialog=", ", Dialog=")
if sectionName.startswith("View="):
if | sectionName.endswith("Viewer"):
return "Type=Viewer, " + sectionName.split(", ")[0]
else:
parts = sectionName.split(",")
parts.reverse()
if len(parts) == 1:
parts.insert(0, "Type=View")
return ", ".join(parts)
else:
return s... |
bjodah/aqchem | chempy/_solution.py | Python | bsd-2-clause | 5,994 | 0.001835 | # -*- coding: utf-8 -*-
"""
"Sandbox" module for exploring API useful for digital labbooks.
Examples
--------
>>> from chempy.units import to_unitless, default_units as u
>>> s1 = Solution(0.1*u.dm3, {'CH3OH': 0.1 * u.molar})
>>> s2 = Solution(0.3*u.dm3, {'CH3OH': 0.4 * u.molar, 'Na+': 2e-3*u.molar, 'Cl-': 2e-3*u.mola... | :
return NotImplemented
return all(
[
getattr(self, k) == getattr(other, k)
for k in "volume concentrations substances solvent".split()
]
)
def __add__(self, other):
if self.solvent != other.solvent:
raise NotIm... | oncentrations * other.volume
)
tot_vol = self.volume + other.volume
return Solution(tot_vol, tot_amount / tot_vol, self.substances, self.solvent)
def dissolve(self, masses):
contrib = QuantityDict(
u.molar,
{
k: v / self.substances[k].molar_ma... |
kburts/django-playlist | django_playlist/auth/forms.py | Python | mit | 954 | 0.008386 | from django import forms
from django.contrib.auth.models import User
from django.forms.models import ModelForm
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from .models import UserProfile
class UserForm(ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
... | el = User
#fields = ('username', 'email', 'password')
## I really don't nee | d your email and you're safer not sharing it with me
fields = ('username', 'password')
helper = FormHelper()
helper.form_method = 'POST'
helper.add_input(Submit('post', 'post', css_class='btn-primary'))
class LoginForm(forms.ModelForm):
class Meta:
model = User
fields = ('usern... |
sre/rubber | src/latex_modules/ltxtable.py | Python | gpl-2.0 | 484 | 0.022727 | # This file is part of Rubber and thus covered by the GPL
# (c) Sebastian Reichel, 2012
"""
Dependency analysis for package 'ltxtable' in | Rubber.
"""
def setup (doc | ument, context):
global doc
doc = document
doc.hook_macro('LTXtable', 'aa', hook_ltxtable)
def hook_ltxtable (loc, width, file):
# If the file name looks like it contains a control sequence or a macro
# argument, forget about this \LTXtable.
if file.find('\\') < 0 and file.find('#') < 0:
doc.add_source(file)
|
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/boto/ec2/cloudwatch/dimension.py | Python | agpl-3.0 | 1,532 | 0 | # Copyright (c) 2006-2012 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modi... | ANTIES OF MERCHANTABIL- |
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
class Dime... |
HewlettPackard/oneview-ansible | library/oneview_sas_logical_jbod_attachment_facts.py | Python | apache-2.0 | 3,330 | 0.002402 | #!/usr/bin/python
# -*- coding: utf-8 -*-
###
# Copyright (2016-2017) Hewlett Packard Enterprise Development LP
#
# 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/licen... | .oneview import OneViewModuleBase
class SasLogicalJbodAttachmentFactsModule(OneViewModuleBase):
def __init__(self):
argument_spec = dict(
name=dict(required=False, type='str'),
params=dict(required=False, type='dict'),
)
| super(SasLogicalJbodAttachmentFactsModule, self).__init__(additional_arg_spec=argument_spec)
def execute_module(self):
if self.module.params['name']:
name = self.module.params['name']
resources = self.oneview_client.sas_logical_jbod_attachments.get_by('name', name)
e... |
ettrig/NIPAP | pynipap/pynipap.py | Python | mit | 37,369 | 0.003131 | """
pynipap - a Python NIPAP client library
=======================================
pynipap is a Python client library for the NIPAP IP address planning
system. It is structured as a simple ORM.
There are three ORM-classes:
* :class:`VRF`
* :class:`Pool`
* :class:`Prefix`
Each of... | L-RPC URI not specified')
| # creating new instance
self.connection = xmlrpclib.ServerProxy(xmlrpc_uri, allow_none=True,
use_datetime=True)
self._logger = logging.getLogger(self.__class__.__name__)
class Pynipap:
""" A base class for the pynipap model classes.
All Pynipap classes which maps ... |
estaban/pyload | module/plugins/hoster/FilepostCom.py | Python | gpl-3.0 | 6,081 | 0.00296 | # -*- coding: utf-8 -*-
"""
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License,
or (at your option) any later version.
This program is distributed in... | CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this progra | m; if not, see <http://www.gnu.org/licenses/>.
changelog:
0.27 - 2012-08-12 - hgg
fix "global name 'js_answer' is not defined" bug
fix captcha bug #1 (failed on non-english "captcha wrong" errors)
"""
import re
from time import time
from module.plugins.internal.SimpleHoster import Simp... |
PALab/PLACE | place/plugins/quanta_ray/qray_driver.py | Python | lgpl-3.0 | 21,278 | 0.001222 | """Driver module for Newport's Spectra-Physics Quanta-Ray INDI, PRO, and LAB
Series Nd:YAG lasers.
NOTE: the watchdog parameter is important! The laser will turn off if it does
not receive a command within the watchdog time period. Therefore, it is
advised to use a command like QRstatus().get_status() at regular int... | ode())
def set_watchdog(self, time=10):
"""Set range of watchdog. If the laser does not receive comm | unication
from the control computer within the specifiedc time, it turns off. If
disabled, the default time is zero. Time must be between 0 and 110
seconds.
"""
if time < 0 or time > 110:
raise ValueError('Invalid watchdog time. Choose value between 0 and 110 seconds.... |
Yukarumya/Yukarum-Redfoxes | testing/marionette/harness/marionette_harness/tests/unit/test_position.py | Python | mpl-2.0 | 664 | 0 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from marionette_driver.by import By
from marionette_harness import MarionetteTestCase
class TestPosition(MarionetteTe... | r2 = self.marionette.find_element(By.ID, "r2")
location = r2.re | ct
self.assertEqual(11, location['x'])
self.assertEqual(10, location['y'])
|
JohnVinyard/zounds | zounds/learn/test_meanstd.py | Python | mit | 1,301 | 0 | import unittest2
from zounds.util import simple_in_memory_settings
from .preprocess import MeanStdNormalization, PreprocessingPipeline
import featureflow as ff
import numpy as np
class MeanStdTests(unittest2.TestCase):
def _forward_backward(self, sha | pe):
@simple_in_memory_settings
class Model(ff.BaseModel):
meanstd = ff.PickleFeature(
MeanStdNormalization,
store=False)
pipeline = ff.PickleFeature(
| PreprocessingPipeline,
needs=(meanstd,),
store=True)
training = np.random.random_sample((100,) + shape)
_id = Model.process(meanstd=training)
model = Model(_id)
data_shape = (10,) + shape
data = np.random.random_sample(dat... |
smrmkt/online_learning_algorithms | exec_cw.py | Python | bsd-3-clause | 1,188 | 0.000842 | #!/usr/bin/env python
#-*-coding:utf-8-*-
from evaluator import Evaluator
from loader import Loader
import matplotlib.pyplot as plt
from confidence_weighted import ConfidenceWeighted
def graph_plot(plt_obj, show=False):
plt_obj.ylim(0, 1)
plt_obj.xlabel("Number of trials")
plt_obj.ylabel("Accuracy")
... | ve-aggressive model
cw = list()
cw.append(ConfidenceWeighted(123))
cw.append(ConfidenceWeighted(123, 0.30))
cw.append(ConfidenceWeighted(123, 0.50))
# training phase
loader = Loader('a1a', 123, 30956, 1605)
y_vec, feats_vec = loader.load_train()
| for i in range(len(cw)):
evaluator = Evaluator(cw[i], y_vec, feats_vec)
evaluator.update()
plt.plot(evaluator.accuracy)
graph_plot(plt)
# test phase
y_vec, feats_vec = loader.load_test()
for i in range(len(cw)):
evaluator = Evaluator(cw[i], y_vec, feats_vec)
eval... |
rika/dynamic-provisioning | statistics.py | Python | gpl-3.0 | 3,837 | 0.011207 | #!/usr/bin/env python
# coding: utf-8
import os
import csv
from schedule_entry import EntryStatus
from machine import MachineStatus
def dump_stat(path, data, headers):
with open(path, 'w') as out:
csv_out = csv.writer(out)
csv_out.writerow(headers)
for row in data:
csv_out.wri... |
for event in e.log.keys():
if e.log[event]:
self.entries.append((host_id, condor_slot, wf_id, dag_job_id, e.condor_id, event, e.log[event]))
if dag_job_id and 'EXECUTE' in e.log.keys() and 'JOB_TERMINATED' in e.log.keys() and 'SUBMIT' in e.log.ke... | d[jt] = [
(d[jt][0] if jt in d.keys() else 0) +1,
(d[jt][1] if jt in d.keys() else 0) +(e.log['JOB_TERMINATED'] - e.log['EXECUTE']).total_seconds(),
(d[jt][2] if jt in d.keys() else 0) +(e.log['EXECUTE'] - e.log['SUBMIT']).total_seconds(),... |
IBMStreams/streamsx.topology | test/python/topology/py36_types.py | Python | apache-2.0 | 6,604 | 0.011508 | # coding=utf-8
# Licensed Materials - Property of IBM
# Copyright IBM Corp. 2019
# Separated test code with Python 3.6 syntax.
import typing
import decimal
from streamsx.spl.types import int64
class NTS(typing.NamedTuple):
x: int
msg: str
class NamedTupleBytesSchema(typing.NamedTuple):
idx: str
msg... | upleWMap2>
class NamedTupleNestedMap3Schema(typing.NamedTuple):
s2: str
tupleWMap2: NamedTupleNestedMap2Schema
class TestSchema(typing.NamedTuple):
flag: bool
i64: int
class ContactsSchema(typing.NamedTuple):
mail: str
phone: str
nested_tuple: TestSchema
class AddressSchema(typing.NamedT... | name: str
age: int
address: AddressSchema
#tuple<int64 x_coord, int64 y_coord>
class Point2DSchema(typing.NamedTuple):
x_coord: int
y_coord: int
#tuple<int64 x_coord, int64 y_coord, int64 z_coord>
class Point3DSchema(typing.NamedTuple):
x_coord: int
y_coord: int
z_coord: int
#tuple<t... |
306777HC/libforensics | code/lf/win/shell/link/__init__.py | Python | lgpl-3.0 | 1,769 | 0.000565 | # Copyright 2010 Michael Murr
#
# This file is part of LibForensics.
#
# LibForensics is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later ver... | Block", "EnvironmentProps", "IconEnvironmentProps",
"KnownFolderProps", "PropertyStoreProps", "ShimProps",
"SpecialF | olderProps", "DomainRelativeObjId", "TrackerProps",
"VistaAndAboveIDListProps", "TerminalBlock", "ExtraDataBlockFactory",
"StringDataSet"
]
|
Trust-Code/trust-addons | trust_second_unit_of_measure/models/mrp_bom.py | Python | agpl-3.0 | 3,943 | 0 | # -*- encoding: utf-8 -*-
###############################################################################
# #
# Copyright (C) 2015 Trustcode - www.trustcode.com.br #
# ... | d=routing_id,
previous_products=previous_products,
master_bom=master_bom, context=context
| )
results = res[0] # product_lines
results2 = res[1] # workcenter_lines
indice = 0
for bom_line_id in bom.bom_line_ids:
line = results[indice]
line['largura'] = bom_line_id.largura
line['comprimento'] = bom_line_id.comprimento
li... |
kaeawc/django-auth-example | test/account.py | Python | mit | 1,507 | 0.000664 | # -*- coding: utf-8 -*
import uuid
import random
import string
from test import DjangoTestCase
class Account(object):
def __init__(self, email=None, password=None):
self.email = email
self.password = password
@staticmethod
def create_email():
return u"some.one+%s@example.com" % u... | data[u"password"] = password
if password_confirmation is not None:
data[u"password_confirmation"] = password_confirmation
response = self.http_post(u"/signup", data)
return Account(email=email, password=password), response
def login(self, email=None, password=None):... | return self.http_post(u"/login", data)
def logout(self, email=None, password=None):
data = {}
if email is not None:
data[u"email"] = email
if password is not None:
data[u"password"] = password
return self.http_post(u"/logout", data) |
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/testtools/tests/test_content_type.py | Python | agpl-3.0 | 2,543 | 0.001573 | # Copyright (c) 2008, 2012 testtools developers. See LICENSE for details.
from testtools import TestCase
from testtools.matchers import Equals, MatchesException, Raises
from testtools.content_type import (
ContentTy | pe,
JSON,
UTF8_TEXT,
)
class TestContentType(TestCase):
def test___init___None_errors(self):
raises_value_error = Raises(MatchesException(ValueError))
self.assertThat(lambda:ContentType(None, None), raises_value_error)
self.assertThat(lambda:ContentType(None, "traceback"),
... | tent_type = ContentType("foo", "bar")
self.assertEqual("foo", content_type.type)
self.assertEqual("bar", content_type.subtype)
self.assertEqual({}, content_type.parameters)
def test___init___with_parameters(self):
content_type = ContentType("foo", "bar", {"quux": "thing"})
s... |
astrofrog/astropy-helpers | astropy_helpers/utils.py | Python | bsd-3-clause | 6,917 | 0.000434 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import contextlib
import imp
import os
import sys
import inspect
# Python 3.3's importlib caches filesystem reads for faster imports in the
# general case. But sometimes it's necessary to manually invalidate those
# caches so that the import system can ... | fd, filename, ('.py', 'U', 1))
def find_mod_objs(modname, onlylocals=False):
""" Returns all the public attributes of a module referenced by name.
.. note::
The returned list *not* include subpackages or modules of
`modname`,nor does it include private attributes (those that
beginwit... | nly attributes that are either members of `modname` OR one of
its modules or subpackages will be included.
Returns
-------
localnames : list of str
A list of the names of the attributes as they are named in the
module `modname` .
fqnames : list of str
A list of the full ... |
ellipticaldoor/dfiid | project/dfiid/settings/base.py | Python | gpl-2.0 | 2,415 | 0.015735 | """
Django settings for dfiid project.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file_... | 'USER': get_env('DB_USER'),
'PASSWORD': get_env('DB_PASSWORD'),
'HOST': get_env('DB_HOST'),
'PORT': get_env('DB_PORT'),
}
}
LANGUAGE_CODE = get_env('LANGUAGE')
TIME_ZONE = 'Atlantic/Canary'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/s/'
STATICFILES_DIRS = ( os.path. | join(BASE_DIR, 'static'), )
STATIC_ROOT = os.path.join(BASE_DIR, 's')
MEDIA_URL = '/m/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'm')
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
AUTH_USER_MODEL = 'user.User'
LOGIN_URL = '/login'
LOGIN_REDIRECT_URL = '/'
STATICFILES_FINDERS = (
'django.contrib.staticfiles.... |
minimalparts/Tutorials | FruitFly/MEN.py | Python | mit | 989 | 0.034378 | #Evaluate semantic space against MEN dataset
import sys
import u | tils
from scipy import stats
import numpy as np
from math import sqrt
#Note: this is scipy's spearman, without tie adjustment
def spearman(x,y):
return stats.spearmanr(x, y)[0]
def readMEN(annotation_file):
pairs=[]
humans=[]
f=open(annotation_file,'r')
for l in f:
l=l.rstrip('\n')
items=l.split()
... | pairs, humans=readMEN(annotation_file)
system_actual=[]
human_actual=[]
count=0
for i in range(len(pairs)):
human=humans[i]
a,b=pairs[i]
if a in dm_dict and b in dm_dict:
cos=utils.cosine_similarity(dm_dict[a],dm_dict[b])
system_actual.append(cos)
... |
icarito/sugar | src/jarabe/journal/volumestoolbar.py | Python | gpl-3.0 | 13,211 | 0 | # Copyright (C) 2007, 2011, One Laptop Per Child
# Copyright (C) 2014, Ignacio Rodriguez
#
# 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) ... | p_documents_button()
volume_monitor = Gio.VolumeMonitor.get()
self._mount_added_hid = volume_monitor.connect('mount-added',
self.__mount_added_cb)
self._mount_removed_hid = volume_monitor.connect(
'mount-removed',
se... | cuments_button(self):
documents_path = model.get_documents_path()
if documents_path is not None:
button = DocumentsButton(documents_path)
button.props.group = self._volume_buttons[0]
button.set_palette(Palette(_('Documents')))
button.connect('toggled', sel... |
timm/timmnix | pypy3-v5.5.0-linux64/lib-python/3/lib2to3/pgen2/tokenize.py | Python | mit | 19,320 | 0.001967 | # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Python Software Foundation.
# All rights reserved.
"""Tokenization help for Python programs.
generate_tokens(readline) is a generator that breaks a stream of
text into Python tokens. It accepts a readline-like method which is called
repeatedly to get the next line o... | v_col = end
if tok_type in (NEWLINE, NL):
self.prev_row += 1
self.prev_col = 0
return "".join(self.tokens)
def compat(self, token, iterable):
startline = False
indents = []
toks_append = self.tokens.append
| toknum, tokval = token
if toknum in (NAME, NUMBER):
tokval += ' '
if toknum in (NEWLINE, NL):
startline = True
for tok in iterable:
toknum, tokval = tok[:2]
if toknum in (NAME, NUMBER):
tokval += ' '
if toknum == INDEN... |
hellsgate1001/graphs | hack_plot/migrations/0006_sshhackip_located.py | Python | mit | 444 | 0 | # -*- coding: u | tf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('hack_plot', '0005_auto_20150505_1940'),
]
operations = [
migrations.AddField(
model_name='sshhackip',
name='located... | lse),
preserve_default=True,
),
]
|
doughyde/fitbit-cal-sync | fitbit-cal-sync.py | Python | gpl-2.0 | 149 | 0.006711 | from trackers.fitbi | t_tracker import FitbitTracker
__aut | hor__ = 'doughyde'
# FitBit connection
f = FitbitTracker()
f.authenticate()
f.get_devices() |
lakshmi-kannan/st2 | st2tests/st2tests/action_aliases.py | Python | apache-2.0 | 4,628 | 0.003025 | # 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... | Error(msg)
elif len(matched_format_strings) > 1:
msg = ('Command "%s" matched multiple format strings: %s' %
(command, ', '.join(matched_format_strings)))
raise AssertionError(msg)
def assertExtractedParametersMatch(self, f | ormat_string, command, parameters):
"""
Assert that the provided command matches the format string.
In addition to that, also assert that the parameters which have been extracted from the
user input (command) also match the provided parameters.
"""
extracted_params = ext... |
kevinkepp/look-at-this | run_trainer.py | Python | mit | 121 | 0.008264 | fro | m sft.runner.Trainer import Trainer
import sft.config.exp
if __name__ == "__main__":
Trainer().r | un(sft.config.exp)
|
putrasattvika/ssidstat | ssidstat/common/models/ssid_traffic_history.py | Python | apache-2.0 | 3,044 | 0.031866 | import time
import sqlite3
from base_model import BaseModel
from datetime import datetime
from contextlib import contextmanager
class SSIDTrafficHistory(BaseModel):
def __init__(self, dbfile, table_name, time_limit):
super(SSIDTrafficHistory, self).__init__(dbfile, table_name)
self.time_limit = time_limit
de... | O {} (timestamp, adapter, ssid, rx, tx)
VALUES ( ?, ?, ?, ?, ? );
'''.format(self.table_name)
c.execute(query, (self.trunc | ate_time(timestamp), adapter, ssid, rx, tx))
def add(self, adapter, ssid, delta_rx, delta_tx, timestamp=None):
if not timestamp:
timestamp = time.time()
prev = self.query(adapter, ssid, timestamp=timestamp)
self.update(
adapter, ssid,
prev['rx']+delta_rx, prev['tx']+delta_tx,
timestamp=timestamp
... |
sp4x/osnf | osnf/connectors.py | Python | apache-2.0 | 1,423 | 0.026704 | ' | ''
Created on 28/set/2014
@author: Vincenzo Pirrone <pirrone.v@gmail.com>
'''
import serial, time
class Connector:
def readline(self):
| pass
def writeline(self, line):
pass
def close(self):
pass
class FakeSerial(Connector):
def __init__(self, port):
print 'opening fake serial on %s' % port
def readline(self):
time.sleep(2)
return 'TIME:%d' % int(time.time())
def wri... |
edx/course-discovery | course_discovery/apps/course_metadata/migrations/0097_degree_lead_capture_image.py | Python | agpl-3.0 | 772 | 0.001295 | # Generated by Django 1.11.15 on 2018-08-08 18:28
import django.db.models.deletion
import django_extensions.db.fields
import stdimage.models
from course_discovery.apps.course_metadata.u | tils import UploadToFieldN | amePath
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('course_metadata', '0096_degree_lead_capture_list_name'),
]
operations = [
migrations.AddField(
model_name='degree',
name='lead_capture_image',
fi... |
femmerling/backyard | builder/installer_tools.py | Python | mit | 1,906 | 0.028856 | import os.path
from subprocess import call
class InstallerTool | s(object):
@s | taticmethod
def update_environment(file_path,environment_path):
update_file = open(file_path, 'r')
original_lines = update_file.readlines()
original_lines[0] = environment_path+'\n'
update_file.close()
update_file = open(file_path, 'w')
for lines in original_lines:
update_file.write(lines)
update_fil... |
lgarren/spack | var/spack/repos/builtin/packages/r-protgenerics/package.py | Python | lgpl-2.1 | 1,699 | 0.001177 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | e received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple | Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class RProtgenerics(RPackage):
"""S4 generic functions needed by Bioconductor proteomics packages."""
homepage = "https://bioconductor.org/packages/ProtGenerics/"
... |
HoussemCharf/FunUtils | linked_lists/1_finding_middle_element_in_a_linked_list.py | Python | mit | 335 | 0.01194 | # Input:
# 2
# 5
# 1 2 | 3 4 5
# 6
# 2 4 6 7 5 1
#
# Output:
# 3
# 7
def findMid(head):
if head == None:
| return -1
fast, slow = head, head
while fast.next != None and fast.next.next != None:
fast = fast.next.next
slow = slow.next
if fast.next != None:
return slow.next
return slow
|
Eagles2F/sync-engine | tests/events/test_inviting.py | Python | agpl-3.0 | 2,071 | 0 | from tests.util.base import event
def test_invite_generation(event, default_account):
from inbox.events.ical import generate_icalendar_invite
event.sequence_number = 1
event.participants = [{'email': 'helena@nylas.com'},
{'email': 'myles@nylas.com'}]
cal = generate_icalendar... | l.lower().startswith('mailto:'):
email = email[7:]
assert email in ['h | elena@nylas.com', 'myles@nylas.com']
def test_message_generation(event, default_account):
from inbox.events.ical import generate_invite_message
event.title = 'A long walk on the beach'
event.participants = [{'email': 'helena@nylas.com'}]
msg = generate_invite_message('empty', event, default_account)
... |
briancurtin/python-openstacksdk | openstack/network/v2/service_profile.py | Python | apache-2.0 | 1,571 | 0 | # 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
# distributed under t... | et = True
allow_update = True
allow_delete = True
allow_list = True
_query_mapping = resource.QueryParameters(
'description', 'driver',
is_enabled='enabled',
project_id='tenant_id'
)
# P | roperties
#: Description of the service flavor profile.
description = resource.Body('description')
#: Provider driver for the service flavor profile
driver = resource.Body('driver')
#: Sets enabled flag
is_enabled = resource.Body('enabled', type=bool)
#: Metainformation of the service flavor... |
cvandeplas/plaso | plaso/formatters/mac_securityd.py | Python | apache-2.0 | 1,215 | 0.005761 | #!/usr/bin/python
# -*- coding | : utf-8 -*-
#
# Copyright 2014 The Plaso Project Authors.
# Please see the AUTHORS file for details on individual 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 to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions a... |
frappe/frappe | frappe/core/doctype/user_document_type/user_document_type.py | Python | mit | 212 | 0.009434 | # -*- coding: utf-8 -*-
# Copyright (c) 2021, Frappe Technologies and contributors
# License: MIT. See LI | CENSE
# import frappe
from frappe.mo | del.document import Document
class UserDocumentType(Document):
pass
|
SkyTruth/skytruth-automation-hub | gae/geofeed_api.py | Python | mit | 5,854 | 0.007345 | from protorpc import messages
from protorpc import message_types
from protorpc import remote
from google.appengine.api import taskqueue
import json
import endpoints
import urllib2
import logging, os
import settings
import inspect
from seqid import SeqidIssuer, seqid2str
from endpointshelper import EndpointsHelper
fr... | se(messages.Message):
"""response message for taskqueue.test"""
status = messages.StringField(1)
message = messa | ges.StringField(2)
info = messages.StringField(3)
class FeedItem(messages.Message):
topic = messages.StringField(1, required=True)
key = messages.StringField(2, required=True)
url = messages.StringField(3)
latitude = messages.FloatField(4)
longitude = messages.FloatField(5)
content = messag... |
Slezhuk/ansible | lib/ansible/module_utils/_text.py | Python | gpl-3.0 | 12,325 | 0.00211 | # This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may | assign their own license
# to the complete work.
#
# Copyright (c), Toshio Kuratomi <a.badger@gmail.com>, 2016
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the abo... | binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, ... |
joansalasoler/auale | src/auale/book/opening_book.py | Python | gpl-3.0 | 3,781 | 0.000794 | # -*- coding: utf-8 -*-
# Aualé oware graphic user interface.
# Copyright (C) 2014-2020 Joan Sala Soler <contact@joansala.com>
#
# 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... | ore = max(scores) if scores else -math.inf
min_score = max(max_score - self._min_score, -self._min_score)
offset = 0 if turn == game.SOUTH else 6
for move, score in enumerate(scores, offset):
if score >= min_score or score >= max_score:
moves.append(move)
re... | e given match position"""
code = self._compute_hash_code(match)
scores = self._scores.get(code, [])
return scores
def _load_opening_book(self, path):
"""Loads an opening book from a file"""
with open(path, 'rb') as file:
self._header = self._read_header(file)
... |
tensorflow/federated | tensorflow_federated/python/core/backends/mapreduce/__init__.py | Python | apache-2.0 | 12,271 | 0.000733 | # Copyright 2019, The TensorFlow Federated 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 o... | tff.federated_aggregate(client_updates[0], zero(), accumulate, merge,
report))
secure_agg = tff.secure_sum(client_updates[1], bitwidth())
global | _update = [simple_agg, secure_agg]
# Finally, the server produces a new state as well as server-side output to
# emit from this round.
new_server_state, server_output = (
tff.federated_map(update, [server_state, global_update]))
# The updated server state, server- and client-side outputs are returned as
... |
QuantumElephant/horton | horton/io/test/test_wfn.py | Python | gpl-3.0 | 19,258 | 0.002181 | # -*- coding: utf-8 -*-
# HORTON: Helpful Open-source Research TOol for N-fermion systems.
# Copyright (C) 2011-2017 The HORTON Development Team
#
# This file is part of HORTON.
#
# HORTON is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by th... | sis(np.arange(36, 57)) == np.arange(21)[::-1]) | .all()
assign = [23, 29, 32, 27, 22, 28, 35, 34, 26, 31, 33, 30, 25, 24, 21]
expect = [14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
assert (get_permutation_basis(np.array(assign)) == expect).all()
assert (get_per |
heplesser/nest-simulator | pynest/examples/clopath_synapse_spike_pairing.py | Python | gpl-2.0 | 6,051 | 0.003636 | # -*- coding: utf-8 -*-
#
# clopath_synapse_spike_pairing.py
#
# This file is part of NEST.
#
# Copyright (C) 2004 The NEST Initiative
#
# NEST 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 ... | , 130.0, 155.0, 180.0], # noqa
[ 50.0, 70.0, 90.0, 110.0, 130.0, 150.0]] # noqa
init_w = 0.5
syn_weights = []
resolution = | 0.1
##############################################################################
# Loop over pairs of spike trains
for s_t_pre, s_t_post in zip(spike_times_pre, spike_times_post):
nest.ResetKernel()
nest.resolution = resolution
# Create one neuron
nrn = nest.Create("aeif_psc_delta_clopath", 1, nrn... |
adamwiggins/cocos2d | test/test_schedule.py | Python | bsd-3-clause | 1,034 | 0.024178 | # This code is so you can run the samples without installing the package
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
#
import cocos
from cocos.director import director
from cocos.sprite import Sprite
import | pyglet
import random
class TestLayer(cocos.layer.Layer):
def __init__(self):
super( TestLayer, self ).__init__()
x,y = director.get_window_size()
self.sprite = Sprite('grossini.png')
self.sprite.position = x/2, y/2
self.add( self.sprite )
... | .sprite.x = random.random()*director.get_window_size()[0]
def change_y(self, dt):
self.sprite.y = random.random()*director.get_window_size()[1]
if __name__ == "__main__":
director.init()
test_layer = TestLayer ()
main_scene = cocos.scene.Scene (test_layer)
director.run (ma... |
sebastianwebber/pgconfig-api | common/util.py | Python | bsd-2-clause | 5,642 | 0.001241 | import tornado.web
import json
from tornado_cors import CorsMixin
from common import ParameterFormat, EnumEncoder
class DefaultRequestHandler(CorsMixin, tornado.web.RequestHandler):
CORS_ORIGIN = '*'
def initialize(self):
self.default_format = self.get_argument("format", "json", True)
self.s... | if parameter_comment != "NONE":
self.write_comment("conf", parameter_comment)
self.write("{} = {}\n".format(parameter["name"], config_value))
self.write("\n")
def write_alter_system(self, output_data):
| if float(self.pg_version) <= 9.3:
self.write("-- ALTER SYSTEM format it's only supported on version 9.4 and higher. Use 'conf' format instead.")
else:
if self.show_about is True:
self.write_about_stuff()
for category in output_data:
self.... |
lzuba-tgm/A05_SimplyGame | Ui_MainWindow.py | Python | gpl-3.0 | 13,842 | 0.003396 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'D:\github repos\Python\A05_SimplyGame\Binaries\MyView.ui'
#
# Created: Tue Oct 25 22:22:12 2016
# by: pyside-uic 0.2.15 running on PySide 1.2.2
#
# WARNING! All changes made in this file will be lost!
from PySide import QtCore... | tGui.QLabel(self.formLayo | utWidget)
self.label_10.setObjectName("label_10")
self.formLayout.setWidget(12, QtGui.QFormLayout.FieldRole, self.label_10)
self.gridLayoutWidget_2 = QtGui.QWidget(self.centralwidget)
self.gridLayoutWidget_2.setGeometry(QtCore.QRect(240, 390, 561, 161))
self.gridLayoutWidget... |
jucimarjr/IPC_2017-1 | lista08/lista08_lista02_questao16.py | Python | apache-2.0 | 799 | 0 | # ----------------------------------------------------------------------------------------------------------------------
# Introdução a Programação de Computadores - IPC
# Universidade do Estado do Amazonas - UEA
# Prof. Jucimar Jr
# Edson de Lima Barros 1715310043
# Ti | ago Ferreira Aranha 1715310047
# Vitor Simôes Azevedo 1715310025
# Roberta de Oliveira da Cruz 0825070169
# Uriel Brito Barros 1515120558
#
# 16. Faça um procedimento que recebe, por parâmetro,
# 2 vetores de 10 elementos inteiros e | que calcule e retorne,
# também por parâmetro, o vetor intersecção dos dois primeiros.
from lista08.ipc import vetor
vetor1 = vetor.cria_vetor(10)
vetor2 = vetor.cria_vetor(10)
vetor_interseccao = vetor.vetor_interseccao(vetor1, vetor2)
print(vetor_interseccao)
|
FoamyGuy/mcpi_with_espruino | examples/example2_led/example2_led.py | Python | unlicense | 1,489 | 0.003358 | import mcpi.minecraft as minecraft
import mcpi.block as Block
import seria | l
import time
# The location where redstone torch needs to spawn.
a0 = (-112, 0, 62) # <- YOU MUST SET THIS VALUE (x,y,z)
"""
Helper method: get_pin(pin)
Returns whether the minecraft pin is turned on or off (based on redstone torch type)
Block(76, 1) -> Redstone Toch ON
Block(75, 1) -> Redstone Toch OFF
"""
def ... |
elif block.id == 75:
return 0
else:
return -1
if __name__ == "__main__":
# My espruino was COM23, and I had to use value 22 here.
port = 22;
old_val = 0
ser = serial.Serial(port, timeout=1) # open first serial port
print ser.portstr # check which port was really u... |
flgiordano/netcash | +/google-cloud-sdk/lib/googlecloudsdk/gcloud_main.py | Python | bsd-3-clause | 7,025 | 0.00911 | #!/usr/bin/env python
#
# Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required... | 'This usually indicates corruption in your gcloud installation or '
'problems with your Python interpreter. | \n\n'
'Please verify that the following is the path to a working Python 2.7 '
'executable:\n'
' {2}\n'
'If it is not, please set the CLOUDSDK_PYTHON environment variable to '
'point to a working Python 2.7 executable.\n\n'
'If you are still experiencing problems,... |
shobute/go-slack | config.py | Python | isc | 1,009 | 0.001982 | DEBUG = False
USERNAME = 'hikaru'
CHANNEL = 'random'
VOCAB = {
'RANDOM': ['random', ':troll:', ':trollface:'],
'PASS': ['pass', 'skip'],
'RESIGN': ['resign', 'give up'],
'VOTE': ['vote', 'move', | 'play'],
'VOTES': ['votes', 'moves', 'voted', 'chance'],
'CAPTURES': ['captures'],
'SHOW': ['show', 'board'],
'YES': ['yes', 'yeah', 'ya', 'y', 'ja', 'please', 'ok', 'yep'],
'NO': ['no', 'nope', 'n', 'nee', "don | 't", 'cancel'],
}
RESPONSES = {
'RESIGN_CONFIRMATION': [
'Are you sure you want to resign?',
'Sure?',
],
'RESIGN_CANCELLED': [
'Ok.',
'Resignation cancelled.',
],
'UNKNOWN': [
"I don't know.",
'What do you mean?',
"That doesn't make any sense.... |
alexgorban/models | official/transformer/v2/transformer_test.py | Python | apache-2.0 | 2,619 | 0.001909 | # Copyright 2018 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... | def setUp(self):
self.params = params = model_params.TINY_PARAMS
params["batch_size"] = params["default_batch_size"] = 16
params["use_synthetic_data"] = True
params["hidden_size"] = 12
params["num_hidden_layers"] = 2
params["filter_size"] = 14
params["num_heads"] = 2
params["vocab_size" | ] = 41
params["extra_decode_length"] = 2
params["beam_size"] = 3
params["dtype"] = tf.float32
def test_create_model_train(self):
model = transformer.create_model(self.params, True)
inputs, outputs = model.inputs, model.outputs
self.assertEqual(len(inputs), 2)
self.assertEqual(len(outputs)... |
neuropycon/ephypype | ephypype/interfaces/__init__.py | Python | bsd-3-clause | 70 | 0.028571 | from . import mne # | noqa
from .mne.s | pectral import TFRmorlet # noqa
|
grnet/synnefo | snf-cyclades-app/synnefo/logic/management/commands/backend-update-status.py | Python | gpl-3.0 | 1,489 | 0 | # Copyright (C) 2010-2017 GRNET S.A.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed i... | pdate_backend_disk_templates(backend)
backend_mod.update_backend_resources(backend)
self.stdout.write("Successful | ly updated backend '%s'\n" % backend)
|
niosus/EasyClangComplete | plugin/utils/search_scope.py | Python | mit | 2,889 | 0 | """Defines all search scopes used in this project."""
from os import path
ROOT_PATH = path.abspath('/')
class TreeSearchScope:
"""Encapsulation of a search scope to search up the tree."""
def __init__(self,
from_folder=ROOT_PATH,
to_folder=ROOT_PATH):
"""Initialize ... | def __bool__(self):
"""Check | if the search scope is empty."""
return self.from_folder != ROOT_PATH
def __iter__(self):
"""Make this an iterator."""
self._current_folder = self._from_folder
return self
def __next__(self):
"""Get next folder to search in."""
current_folder = self._current_fol... |
cjauvin/python_algorithms | tests/basic/test_stack.py | Python | bsd-3-clause | 1,843 | 0.000543 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_stack
----------------------------------
Tests for `python_algorithms.stack` module.
"""
import unittest
from python_algorithms.basic.stack import Stack
class TestStack(unittest.TestCase):
def setUp(self):
self.empty_stack = Stack()
self.... | self.assertEqual(False, True)
def test_iterate_stack(self):
iter_seq = []
for curr in self.stack:
iter_seq.append(curr)
iter_seq.reverse()
self.assertEqual(iter_seq, self.seq)
def test_str_empty_stack(self):
self.assertEqual(str(self.empty_stack), "")
... | rtEqual(str(self.stack), " ".join([str(x) for x in self.seq]))
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main()
|
claudep/pootle | tests/search/units.py | Python | gpl-3.0 | 10,939 | 0 | # -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from pootle.core.delegate imp... | oject.models import Project
from pootle_statistics | .models import Submission, SubmissionTypes
from pootle_store.getters import get_search_backend
from pootle_store.constants import FUZZY, TRANSLATED, UNTRANSLATED
from pootle_store.models import Suggestion, Unit
from pootle_store.unit.filters import (
FilterNotFound, UnitChecksFilter, UnitContributionFilter, UnitSea... |
polyaxon/polyaxon | platform/polycommon/tests/test_options/test_feature.py | Python | apache-2.0 | 1,739 | 0 | #!/usr/bin/python
#
# Copyright 2018-2021 Polyaxon, 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 ... | uage governing permissions and
# limitations under the License.
from unittest import TestCase
from django.conf import settings
from polycommon.options.ex | ceptions import OptionException
from polycommon.options.feature import Feature
from polycommon.options.option import NAMESPACE_DB_OPTION_MARKER, OptionStores
class DummyFeature(Feature):
pass
class TestFeature(TestCase):
def test_feature_default_store(self):
assert DummyFeature.store == OptionStores... |
cheungpat/sqlalchemy-utils | tests/functions/test_make_order_by_deterministic.py | Python | bsd-3-clause | 3,482 | 0 | import sqlalchemy as sa
from sqlalchemy_utils.functions.sort_query import make_order_by_deterministic
from tests import assert_contains, TestCase
class TestMakeOrderByDeterministic(TestCase):
def create_models(self):
class User(self.Base):
__tablename__ = 'user'
id = sa.Column(sa.... | .where(Article.author_id == User.id)
.label('article_count')
)
self.User = User
self.Articl | e = Article
def test_column_property(self):
query = self.session.query(self.User).order_by(self.User.email_lower)
query = make_order_by_deterministic(query)
assert_contains('lower("user".name), "user".id ASC', query)
def test_unique_column(self):
query = self.session.query(self... |
comoga/gooddata-python | tests/examples/employee.py | Python | bsd-3-clause | 6,397 | 0.00766 | from gooddataclient.dataset import Dataset
from gooddataclient.columns import ConnectionPoint, Label, Reference
class Employee(Dataset):
employee = ConnectionPoint(title='Employee', folder='Employee')
firstname = Label(title='First Name', reference='employee', folder='Employee')
lastname = Label(ti... | <name>employee</name>
<title>Employee</title>
<ldmType>CONNECTION_POINT</ldmType>
<folder>Employee</folder>
</column>
<column>
<name>firstname</name>
<title>First Name</title>
<ldmType>LABEL</ldmType>
<reference>employee</reference>
<folder>Employee... | title>Last Name</title>
<ldmType>LABEL</ldmType>
<reference>employee</reference>
<folder>Employee</folder>
</column>
<column>
<name>department</name>
<title>Department</title>
<ldmType>REFERENCE</ldmType>
<reference>department</reference>
<schemaReferenc... |
keras-team/keras | keras/feature_column/dense_features_v2.py | Python | apache-2.0 | 6,123 | 0.00343 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | r.build and not _DenseFeaturesHelper.build.
# pylint: disable=protected-access
super(kfc._BaseFeaturesLayer, self).build(None) # pylint: disable=bad-super-call
class _StateManagerImplV2(tf.__internal__.feature_column.StateManager): # pylint: disable=pr | otected-access
"""Manages the state of DenseFeatures."""
def create_variable(self,
feature_column,
name,
shape,
dtype=None,
trainable=True,
use_resource=True,
in... |
autoprotocol/autoprotocol-utilities | autoprotocol_utilities/bio_calculators.py | Python | bsd-3-clause | 16,561 | 0 | from autoprotocol.unit import Unit
def dna_mass_to_mole(length, mass, ds=True):
"""
For the DNA Length and mass given, return the mole amount of DNA
Example Usage:
.. code-block:: python
from autoprotocol_utilities import dna_mass_to_mole
from autoprotocol.unit import Unit
... | onc(dna_length, dna_molarity)
Returns:
.. code-block:: python
Unit(33000.0, 'nanogram / microliter')
Parameters
----------
length: int
Length of DNA in bp
molar: str, Unit
Molarity of DNA in prefix-M
ds: bool, optional
True for ds | DNA, False for ssDNA
Returns
-------
mass_conc: Unit
Mass concentration of DNA in ng/uL
Raises
------
ValueError
If inputs are not of specified types
"""
if not isinstance(length, int):
raise ValueError(
"Length of DNA is of type %s, must be of type... |
alphagov/notifications-api | migrations/versions/0356_add_webautn_auth_type.py | Python | mit | 1,380 | 0.003623 | """
Revision ID: 0356_add_webautn_auth_type
Revises: 0355_add_webauthn_table
Create Date: 2021-05-13 12:42:45.190269
"""
from alembic import op
revision = '0356_add_webautn_auth_type'
down_revision = '0355_add_webauthn_table'
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.e... | ngrade():
# ### commands auto generated by Alembic - please adjust! ###
op.execute("UPDATE users SET auth_type = 'sms_auth' WHERE auth_type = 'webauthn_auth'")
op.execute("UPDATE invited_users SET auth_type = 'sms_auth' WHERE auth_type = 'webauthn_auth'")
op.drop_constraint('ck_user_has_mobile_or_other... | RAINT "ck_users_mobile_or_email_auth"
CHECK (auth_type = 'email_auth' or mobile_number is not null)
NOT VALID
""")
op.execute("DELETE FROM auth_type WHERE name = 'webauthn_auth'")
# ### end Alembic commands ###
|
fpoli/python-astexport | astexport/cli.py | Python | mit | 1,148 | 0 | import fileinput
import argparse
from astexport import __version__, __prog_name__
from astexport.parse import parse
from astexport.export import export_json
def create_parser():
parser = argparse.ArgumentParser(
prog=__prog_name__,
description="Python source code in, JSON AST out. (v{})".format(
... | --version",
action="store_true",
help="print version and exit"
)
return parser
def main():
"""Read source from stdin, parse and export the AST as JSON"""
parser = create_ | parser()
args = parser.parse_args()
if args.version:
print("{} version {}".format(__prog_name__, __version__))
return
source = "".join(fileinput.input(args.input))
tree = parse(source)
json = export_json(tree, args.pretty)
print(json)
|
MatiasSM/fcb | fcb/utils/trickle.py | Python | lgpl-3.0 | 1,657 | 0.001811 | from copy import deepcopy
from distutils.spawn import find_executable
class Settings(object):
_upload_limit = 0
def __init__(self, settings=None):
| if settings:
self._upload_limit = settings.up_kbytes_sec
@property
def upload_limit(self):
""" Returns the value as required by the t | rickle command (i.e. in KBytes) """
return self._upload_limit
def upload_limit_in_kbytes(self, upload_limit):
self._upload_limit = upload_limit if upload_limit is not None else 0
def to_argument_list(self):
"""
converts the setting in a list as required by the trickle command
... |
quantopian/pyfolio | pyfolio/tests/test_nbs.py | Python | apache-2.0 | 666 | 0 | #!/usr/bin/env python
"""
simple example script for running notebooks and reporting exceptions.
U | sage: `checkipnb.py foo.ipynb [bar.ipynb [...]]`
Each cell is submitted to the kernel, and checked for errors.
"""
import os
import glob
from runipy.notebook_runner import NotebookRunner
from pyfolio.utils import pyfolio_root
from pyfolio.ipycompat import read as read_notebook
def test_nbs():
path = os.path.joi... | _root(), 'examples', '*.ipynb')
for ipynb in glob.glob(path):
with open(ipynb) as f:
nb = read_notebook(f, 'json')
nb_runner = NotebookRunner(nb)
nb_runner.run_notebook(skip_exceptions=False)
|
rob-earwaker/rail | test_rail.py | Python | mit | 23,712 | 0 | import sys
import traceback
import unittest
import unittest.mock
import rail
class TestIdentity(unittest.TestCase):
def test_returns_input_value(self):
value = unittest.mock.Mock()
self.assertEqual(value, rail.identity(value))
class TestNot(unittest.TestCase):
def test_returns_inverse_for_b... | .mock.Mock())
)
self.assertEqual(expected_value, match(unittest.mock.Mock()))
def test_value_subclass_of_match_type(self):
expected_value = unittest.mock.Mock()
match = rail.match_type(
(bool, lambda _: unittest.mock.Mock()),
(object, lambda _: expected_value... | s TestMatchLength(unittest.TestCase):
def test_no_match_statements_provided(self):
value = unittest.mock.Mock()
with self.assertRaises(rail.UnmatchedValueError) as context:
rail.match_length()(value)
self.assertEqual(value, context.exception.value)
def test_value_unmatched_b... |
ratnania/pyccel | tests/warnings/codegen/is.py | Python | mit | 72 | 0 | a | d = 1.
# this statement will be ignored at the codegen
x = ad is Non | e
|
krasnoperov/django-formalizr | formalizr/tests/tests.py | Python | bsd-3-clause | 4,412 | 0.002947 | import json
from django.utils import unittest
from django.test.client import RequestFactory
from formalizr.tests.views import SimpleFormView, SimpleCreateView, SimpleUpdateView
from formalizr.tests.models import SimpleModel
class AjaxFormViewTest(unittest.TestCase):
view_class = SimpleFormView
VALUE = 1
... | content-type'].split(';')[0])
resp = json.loads(response.content)
self.assertEqual("error", resp["status"])
self.assertIn("value", resp["errors"])
return resp
def testAjaxResultRequest(self):
"""
Posts valid form through AJAX request.
Response with result m... | mViewTest.VALUE, "_return": "result"}
request = self.factory.post('/', data, HTTP_X_REQUESTED_WITH='XMLHttpRequest')
response = self.view_class.as_view()(request)
self.assertEqual(200, response.status_code)
self.assertEqual('application/json', response['content-type'].split(';')[0])
... |
HyechurnJang/acidipy | tools/ansible/acibuilder.py | Python | apache-2.0 | 1,055 | 0.010427 | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Created on 2016. 10. 11.
@author: "comfact"
'''
import yaml
from ansible.module_utils.basic import *
from acidipy import deployACI
DOCUMENTATION = '''
---
module: acibuilder
version_added: historical
short_description: acidipy ansible module.
description... |
- This is Acidipy Ansible Module named AciBuilder
options: {}
author: hyjang@cisco.com
'''
EXAMPLES = '''
# Test 'webservers' | status
ansible webservers -m ping
'''
def main():
module = AnsibleModule(
argument_spec = dict(
Controller=dict(required=True),
Option=dict(required=True),
Tenant=dict(required=True)
),
supports_check_mode = True
)
ctrl = yaml... |
CACTUS-Mission/TRAPSat | TRAPSat_cFS/cfs/cfe/tools/cFS-GroundSystem/Subsystems/cmdGui/GenericCommandDialog.py | Python | mit | 49,087 | 0.004339 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'GenericCommandDialog.ui'
#
# Created: Wed Mar 25 17:15:12 2015
# by: PyQt4 UI code generator 4.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
... | = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.itemLabelTextBrowser_1.sizePolicy().hasHeightForWidth())
self.itemLabelTextBrowser_1.setSizePolicy(sizePolicy)
... | ame(_fromUtf8("itemLabelTextBrowser_1"))
self.horizontalLayout_2.addWidget(self.itemLabelTextBrowser_1)
self.SendButton_1 = QtGui.QPushButton(self.scrollAreaWidgetContents)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)... |
pombredanne/pants | tests/python/pants_test/build_graph/test_subproject_integration.py | Python | apache-2.0 | 3,193 | 0.006577 | # coding=utf-8
# Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from contextlib impo... | pers'],
)
""",
'test | projects/src/python/subproject_test/subproject/BUILD':
"""
target(
name = 'local',
dependencies = [
':relative',
'//:absolute',
],
)
target(
name = 'relative',
)
target(
name = 'absolute',
)
""",
'testproject... |
henrynj/PMLMC | v0.0/config.py | Python | gpl-3.0 | 2,156 | 0.008813 | #!/usr/bin/env python
##################################################
# Parallel MLMC: Config class #
# #
# Jun Nie #
# Last modification: 19-09-2017 #
##########################################... | ngle' for serial
self.MULTIN = 1 # number of processes for fvm solver, 1 or multiples of 2
self.MULTIM = 4 # number of samplers (processor group)
self.MULTI_CORES = 0
# === update
self.update(config_file)
def update(self, config_file):
... | if __name__ == '__main__':
pass
|
zepheira/amara | lib/xslt/expressions/avt.py | Python | apache-2.0 | 1,540 | 0.001299 | ########################################################################
# amara/xslt/expressions/avt.py
"""
Implementation of XSLT attribute value templates
"""
from amara.xpath import datatypes
from amara.xpath.expressions import expression
from amara.xslt import XsltError
from amara.xslt.e | xpressions import _avt
_parse_avt = _avt.parser().parse
class avt_expression(expression):
__slots__ = ('_format', '_args')
def __init__(self, value):
| try:
# parts is a list of unicode and/or parsed XPath
parts = _parse_avt(value)
except _avt.error, error:
raise XsltError(XsltError.AVT_SYNTAX)
self._args = args = []
for pos, part in enumerate(parts):
if isinstance(part, unicode):
... |
earthchie/PokemonGo-Bot | setup.py | Python | mit | 355 | 0 | #!/usr/bin/env python
from distutils.cor | e import setup
from pip.req import parse_requirements
install_reqs = parse_requirements("requirements.txt", session=False)
reqs = [str(ir.req) for ir in install_reqs]
setup(name='pgoapi',
version='1.0',
url='https://github.com/tejado/pgoapi',
packages=['pgoapi'],
| install_requires=reqs)
|
sawdog/OraclePyDoc | oraclepydoc/oracleobjects/oraclejavasource.py | Python | gpl-2.0 | 261 | 0.007663 | from oracleplsqlsource i | mport OraclePLSQLSource
class OracleJavaSource(OraclePLSQLSource):
def __in | it__(self, name, source):
self.name = name
#debug_message("debug: generating java source ")
OraclePLSQLSource.__init__(self,source)
|
tscohen/chainer | cupy/math/misc.py | Python | mit | 4,772 | 0 | from cupy import elementwise
_id = 'out0 = in0'
# TODO(okuta): Implement convolve
_clip = elementwise.create_ufunc(
'cupy_clip',
('???->?', 'bbb->b', 'BBB->B', 'hhh->h', 'HHH->H', 'iii->i', 'III->I',
'lll->l', 'LLL->L', 'qqq->q', 'QQQ->Q', 'eee->e', 'fff->f', 'ddd->d'),
'out0 = min(in2, max(in1, i... | .. seealso:: :data:`numpy.absolute`
''')
# TODO(beam2d): Implement it
# fabs
_unsigned_sign = 'out0 = in0 > 0'
sign = elementwise.create_ufunc(
'cupy_sign',
('b->b', ('B->B', _unsigned_sign), 'h->h', ('H->H', _unsigned_sign),
'i->i', ('I->I', _unsigned_sign), 'l->l', ('L->L', _unsigned_sign),
... | ,
doc='''Elementwise sign function.
It returns -1, 0, or 1 depending on the sign of the input.
.. seealso:: :data:`numpy.sign`
''')
_float_maximum = \
'out0 = isnan(in0) ? in0 : isnan(in1) ? in1 : max(in0, in1)'
maximum = elementwise.create_ufunc(
'cupy_maximum',
('??->?', 'bb->b', 'BB-... |
pyroscope/auvyon | src/auvyon/config.py | Python | gpl-2.0 | 230 | 0 | """ Configuratio | n values.
"""
# Command paths (you can change these to e.g. absolute paths in calling code)
CMD_FLAC = "flac"
CMD_FFM | PEG = "ffmpeg"
CMD_IM_MONTAGE = "montage"
CMD_IM_MOGRIFY = "mogrify"
CMD_IM_CONVERT = "convert"
|
xunilrj/sandbox | courses/coursera-sandiego-algorithms/data-structures/assignment002/make_heap/build_heap.py | Python | apache-2.0 | 1,100 | 0.010909 | # python3
class HeapBuilder:
def __init__(self):
self._swaps = []
self._data = []
def ReadData(self):
n = int(input())
self._data = [int(s) for s in input().split()]
assert n == len(self._data)
def Wri | teResponse(self):
print(len(self._swaps))
for swap in self._swaps:
print(swap[0], swap[1])
def GenerateSwaps(self):
# The following naive implementation just sorts
# the given sequence using selection sort algorithm
# and saves the resulting sequence of swaps.
# This turns the given ar... |
for j in range(i + 1, len(self._data)):
if self._data[i] > self._data[j]:
self._swaps.append((i, j))
self._data[i], self._data[j] = self._data[j], self._data[i]
def Solve(self):
self.ReadData()
self.GenerateSwaps()
self.WriteResponse()
if __name__ == '__main__':
he... |
Som-Energia/invoice-janitor | Taxes/municipaltax.py | Python | agpl-3.0 | 9,574 | 0.004493 | # -*- coding: utf-8 -*-
import StringIO
import csv
from xml.etree.ElementTree import Element, SubElement, Comment, tostring
from xml.dom import minidom
import configdb
def prettify(elem):
"""Return a pretty-printed XML string for the Element.
"""
rough_string = tostring(elem, 'utf-8')
reparsed = mini... | for year, v in sorted(invoicing_by_date.items()):
| for quarter, v in sorted(invoicing_by_date[year].items()):
diff = v['total_client_amount'] - v['total_provider_amount']
writer_report.writerow([
year,
quarter,
round(v['total_provider_a... |
locksmith47/turing-sim-kivy | src/plyer_lach/platforms/android/camera.py | Python | mit | 2,169 | 0.000461 | import android
import android.activity
from os import unlink
from jnius import autoclass, cast
from plyer_lach.facades import Camera
from plyer_lach.platforms.android import activity
Intent = autoclass('android.content.Intent')
PythonActivity = autoclass('org.renpy.android.PythonActivity')
MediaStore = autoclass('andr... | .parse('file://' + filename)
parcelable = cast('android.os.Parcelable', uri)
intent.putExtra(MediaStore.EXTRA_OUTPUT, parcelable)
# 0 = low quality, suitable for MMS messages,
# 1 = high quality
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1)
activity.startActivityFor... | ntent):
if requestCode != 0x123:
return
android.activity.unbind(on_activity_result=self._on_activity_result)
if self.on_complete(self.filename):
self._unlink(self.filename)
def _unlink(self, fn):
try:
unlink(fn)
except:
pass
... |
getyourguide/fbthrift | build/fbcode_builder_config.py | Python | apache-2.0 | 449 | 0 | #!/usr/bin/env python
from __future__ | import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
'fbcode_builder steps to build Facebook Thrift'
import sp | ecs.fbthrift as fbthrift
def fbcode_builder_spec(builder):
return {
'depends_on': [fbthrift],
}
config = {
'github_project': 'facebook/fbthrift',
'fbcode_builder_spec': fbcode_builder_spec,
}
|
tnadeau/pybvc | setup.py | Python | bsd-3-clause | 1,243 | 0.000805 | from setuptools import setup
import pybvc
setup(
name='pybvc',
version=pybvc.__version__,
description='A python library for programming your network via the Brocade Vyatta Controller (BVC)',
long_description=open('README.rst').read(),
author='Elbrys Networks',
author_email='jeb@elbrys.com',
... | 'pybvc.openflowdev'
],
install_requires=['requests>=1.0.0',
'PyYAML',
'xmltodict'],
zip_safe=False,
include_package_data=True,
platforms='any',
license='BSD',
keywords='sdn nfv bvc brocade vyatta controller network vrouter',
... | Networking',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
]
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.