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 |
|---|---|---|---|---|---|---|---|---|
contentful/contentful.py | contentful/locale.py | Python | mit | 1,165 | 0.002575 | from .resource import Resource
"""
contentful.locale
~~~~~~~~~~~~~~~~~
This module implements the Locale class.
API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/localization
:copyright: (c) 2016 by Contentful GmbH.
:license: MIT, see LICENSE for more details.
"""
... | self.default = item.get('default', False)
self.optional = item.get('optional', False)
def __repr__(self):
return "<Locale[{0}] code='{1}' default={2} fallback_code={3} optional={4}>".format(
self.name, |
self.code,
self.default,
"'{0}'".format(
self.fallback_code
) if self.fallback_code is not None else 'None',
self.optional
)
|
updownlife/multipleK | dependencies/biopython-1.65/Tests/test_KEGG.py | Python | gpl-2.0 | 2,438 | 0 | # Copyright 2001 by Tarjei Mikkelsen. All rights reserved.
# Revisions copyright 2007 by Michiel de Hoon. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""Tests the basic funct... | sting Bio.KEGG.Enzyme on " + file + "\n\n")
records = Enzyme.parse(fh)
for record in records:
print(record)
print("\n")
| fh.close()
def t_KEGG_Compound(testfiles):
"""Tests Bio.KEGG.Compound functionality."""
for file in testfiles:
fh = open(os.path.join("KEGG", file))
print("Testing Bio.KEGG.Compound on " + file + "\n\n")
records = Compound.parse(fh)
for record in records:
prin... |
sapfo/medeas | src/old_scripts/main_simul_eigenvalues_distribution.py | Python | gpl-3.0 | 7,741 | 0.027774 | #!/usr/bin/env python
"""
Created Wed Oct 7 15:04:36 CEST 2015
@author: sapfo
"""
import matplotlib
#matplotlib.use('Agg')
import simul_ms
import python_cmdscale
#import python_pca
import exp
import sys
import numpy as np
import pylab as py
from scipy.stats import norm
'''
We want to pick n1, n2, D, T?
Simulate ... | #(D1<D)
nreps = 1000
## simulate data
rescaling = 2.0
verbose = False
########### 1 population ##############
print "########## | # 1 population ##############"
## expected tree length for one population
exp_tree_length = 0
for i in range(2,n+1):
exp_tree_length += 2./(i-1)
nsnps = [100]
T_mds = {}
T_pca = {}
Eigenvalues_mds = []
Distances_noise = []
Expected_Delta = np.zeros((n,n))
for kk in range(1,n):
Expected_Delta += np.eye(n,k=k... |
xxdede/SoCo | soco/core.py | Python | mit | 72,281 | 0 | # -*- coding: utf-8 -*-
# pylint: disable=C0302,fixme, protected-access
""" The core module contains the SoCo class that implements
the main entry to the SoCo functionality
"""
from __future__ import unicode_literals
import socket
import logging
import re
import requests
from .services import DeviceProperties, Conte... | ueue
add_to_queue -- Add a track to the end of the queue
remove_from_queue -- Remove a track from the queue
clear_queue -- Remove all tracks from queue
get_favorite_radio_shows -- Get favorite radio shows from Sonos'
Radio app.
get_favorite_rad... | nos_playlist -- Create a new empty Sonos playlist
create_sonos_playlist_from_queue -- Create a new Sonos playlist
from the current queue.
add_item_to_sonos_playlist -- Adds a queueable item to a Sonos'
playlist
ge... |
zacherytapp/wedding | weddingapp/apps/registry/migrations/0001_initial.py | Python | bsd-3-clause | 1,051 | 0.001903 | # - | *- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Registry',
fields=[
('id', models.AutoField(verbos... | els.DateTimeField(auto_now_add=True)),
('modified', models.DateTimeField(auto_now=True)),
('display_order', models.IntegerField()),
('visibility', models.CharField(default=b'Unpusblished', max_length=20, choices=[(b'Published', b'Published'), (b'Unpusblished', b'Unpusblis... |
GabrielBrascher/cloudstack | test/integration/component/test_stopped_vm.py | Python | apache-2.0 | 58,065 | 0.000224 | # 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... | .account]
return
def tearDown(self):
try:
self.debug("Cleaning up the resources")
cleanup_resources(self.apiclient, self.cleanup)
| self.debug("Cleanup complete!")
except Exception as e:
self.debug("Warning! Exception in tearDown: %s" % e)
@attr(tags=["advanced", "eip", "advancedns"], required_hardware="false")
def test_01_deploy_vm_no_startvm(self):
"""Test Deploy Virtual Machine with no startVM parameter
... |
SOM-st/RPySOM | src/rtruffle/base_node_2.py | Python | mit | 229 | 0 | from rtruff | le.abstract_node import AbstractNode, NodeInitializeMetaClass
class BaseNode(AbstractNode):
__me | taclass__ = NodeInitializeMetaClass
_immutable_fields_ = ['_source_section', '_parent']
_child_nodes_ = []
|
Ban3/Limnoria | plugins/Misc/plugin.py | Python | bsd-3-clause | 27,456 | 0.001603 | ###
# Copyright (c) 2002-2005, Jeremiah Fincher
# Copyright (c) 2009, James McCoy
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyr... | r the name of
# contributors to this software may be used to endorse or promote products
# derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, TH... | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVIC... |
leosartaj/credit | credit/tests/main_tests/test_total_all_net.py | Python | mit | 1,235 | 0.00081 | #!/usr/bin/env python2
import os
from credit import main, exce
from credit import jsonhelper as jh
from credit.tests import testData as td
import unittest
class Test_total_all_net(unittest.TestCase):
def setUp(self):
self.fnum = 10
self.days = 10
self.startname = 'test_display'
s... | f.write(jh.dict_to_json(fakeDict))
def test_total_all(self):
num_files = 0
totals = 0
for sheetname, total in main.total_all():
self.assertTrue((sheetname + main.SHEETEXT) in self.files)
num_files += 1
totals += total
self.assertEqual... | .net() - self.bal) < td.ERROR)
def tearDown(self):
for name in self.files:
os.remove(name)
|
adrienpacifico/openfisca-france | openfisca_france/model/caracteristiques_socio_demographiques/demographie.py | Python | agpl-3.0 | 9,098 | 0.024722 | # -*- coding: utf-8 -*-
from ..base import * # noqa
build_column('idmen', IntCol(is_permanent = True, label = u"Identifiant du ménage"))
build_column('idfoy', IntCol(is_permanent = True, label = u"Identifiant du foyer"))
build_column('idfam', IntCol(is_permanent = True, label = u"Identifiant de la famille"))
build... | :
"""couple = 1 si couple marié sinon 0 TODO: faire un choix avec couple ?"""
# Note : Cette variable est "instantanée" : quelque soit la période demandée, elle retourne la valeur au premier
# jour, sans changer la période.
statmarit_holder = simulation.compute('statmarit', period)
... | ole(statmarit_holder, role = CHEF)
return period, statmarit == 1
class concub(Variable):
column = BoolCol(default = False)
entity_class = Familles
label = u"Indicatrice de vie en couple"
def function(self, simulation, period):
'''
concub = 1 si vie en couple TODO: pas très he... |
madhuni/AstroBox | src/ext/makerbot_driver/GcodeProcessors/AnchorProcessor.py | Python | agpl-3.0 | 5,212 | 0.002686 | from __future__ import absolute_import
import re
import math
import contextlib
from .LineTransformProcessor import LineTransformProcessor
import makerbot_driver
class AnchorProcessor(LineTransformProcessor):
def __init__(self):
super(AnchorProcessor, self).__init__()
self.is_bundleable = True
... | ne(
start_position)[0] # Where the Bot is moving from
end_movement_codes = makerbot_driver.Gcode.parse_line(end_position)[0] # Where the bot is moving to
# Construct the next G1 command based on where the bot is moving | to
anchor_command = "G1 "
for d in ['X', 'Y', 'Z']:
if d in end_movement_codes:
part = d + str(end_movement_codes[d]) # The next [XYZ] code
anchor_command += part
anchor_command += ' '
anchor_command += 'F%i ' % (self.speed)
e... |
yfdyh000/pontoon | pontoon/base/tests/test_utils.py | Python | bsd-3-clause | 644 | 0 | from django_nose.tools import assert_false, assert_true
from pontoon.base.tests import TestCase
from pontoon.base.utils import extension_in
class UtilsTests(TestCase):
def test_extension_in(self):
assert_true(ex | tension_in('filename.txt', ['bat', 'txt']))
assert_true(extension_in('filename.biff', ['biff']))
assert_true(extension_in('filename.tar.gz', ['gz']))
assert_false(extension_in('filename.txt', ['png', 'jpg | ']))
assert_false(extension_in('.dotfile', ['bat', 'txt']))
# Unintuitive, but that's how splitext works.
assert_false(extension_in('filename.tar.gz', ['tar.gz']))
|
ManiacalLabs/BiblioPixel | bibliopixel/animation/strip.py | Python | mit | 543 | 0.001842 | from . animation import Animation
from .. layout import | strip
class Strip(Animation):
LAYOUT_CLASS = strip.Strip
LAYOUT_ARGS = 'num',
def __init__(self, layout, start=0, end=-1, **kwds):
super().__init__(layout, **kwds)
self._start = max(start, 0)
self._end = end
if self._end < 0 or self._end >= self.layout.numLEDs:
... | start + 1
from .. import deprecated
if deprecated.allowed():
BaseStripAnim = Strip
|
wwitzel3/awx | awx/main/tests/functional/api/test_job_runtime_params.py | Python | apache-2.0 | 26,351 | 0.004326 | import mock
import pytest
import yaml
import json
from awx.api.serializers import JobLaunchSerializer
from awx.main.models.credential import Credential
from awx.main.models.inventory import Inventory, Host
from awx.main.models.jobs import Job, JobTemplate, UnifiedJobTemplate
from awx.api.versioning import reverse
@... | h=on_off,
ask_verbosity_on_launch=on_off,
)
jt.credentials.add(machine_credential)
return jt
return rf
@pytest.fixture
def job_template_prompts_null(project):
return JobTemplate.objects.create(
job_type='run',
project=project,
| inventory=None,
name='deploy-job-template',
ask_variables_on_launch=True,
ask_tags_on_launch=True,
ask_skip_tags_on_launch=True,
ask_job_type_on_launch=True,
ask_inventory_on_launch=True,
ask_limit_on_launch=True,
ask_credential_on_launch=True,
... |
Vongo/anna | src/talk/db.py | Python | gpl-2.0 | 5,871 | 0.027764 | from py2neo.server import GraphServer
from py2neo import Node,Relationship
HISTO_LENGTH = 5
def insert(sentence, tokensAndType):
"""
Take a sentence and it's associate tokens and type and store all of it in the db as the last sentence of the dialogue
@type sentence: string
@param sentence: The inser... | oken in tokensAndType[0]:
print token
tokenNode = graph.find_one("TokenHisto",
property_key="token",
| property_value = token[0])
if tokenNode is None:
tokenNode = Node("TokenHisto", token=token[0], pos=token[1])
is_composed_of = Relationship(sentence, "is_composed_of", tokenNode)
graph.create(is_composed_of)
# Delete the potential existing historic of dialogue before starting a new one
def clean_histo():... |
JakeColtman/bartpy | bartpy/diagnostics/features.py | Python | mit | 8,265 | 0.00363 | from collections import Counter
from typing import List, Mapping, Union, Optional
import numpy as np
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
from bartpy.runner import run_models
from bartpy.sklearnmodel import SklearnModel
ImportanceMap = Mapping[int, float]
ImportanceDistribut... | null_distributions)
for row in df.iter_rows():
q_s.append(np.max(row))
threshold = np.percentile(q_s, percentile)
return {feature: threshold for feature in null_distributions}
def kept_features(feature_proportions: Mapping[int, float], thresholds: Mapping[int, float]) -> List[int]:
"""
Ext... | Lookup from variable to % of splits in the model that use that variable
thresholds: Mapping[int, float]
Lookup from variable to required % of splits in the model to be kept
Returns
-------
List[int]
Variable selected for inclusion in the final model
"""
return [x[0] for x in zi... |
congpc/DjangoExample | mysite/polls/tests.py | Python | bsd-2-clause | 5,010 | 0.001198 | import datetime
from django.utils import timezone
from django.test import TestCase
from django.urls import reverse
from .models import Question
class QuestionMethodTests(TestCase):
def test_was_published_recently_with_future_question(self):
"""
was_published_recently() should return False for qu... | n the future.
"""
time = timezone.now() + datetime.timedelta(days=30)
future_question = Question(pub_date=time)
self.assertIs(future_question.was_published_recently(), False)
def test_was_published_recently_with_old_question(self):
"""
was_published_recently() should... | time)
self.assertIs(old_question.was_published_recently(), False)
def test_was_published_recently_with_recent_question(self):
"""
was_published_recently() should return True for questions whose
pub_date is within the last day.
"""
time = timezone.now() - datetime.tim... |
heyf/cloaked-octo-adventure | leetcode/0103_binary-tree-zigzag-level-order-traversal.py | Python | mit | 1,261 | 0.008723 | #
# @lc app=leetcode id=103 lang=python3
#
# [103] Binary Tree Zigzag Level Order Traversal
#
from typing import List
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# @lc code=start
class Solution:
def zigzagL... | ode.left)
if node.right:
new_child.append(node.right)
child = new_child
if current_layer:
if flag:
ret.append(current_layer)
else:
ret.append(current_layer[::-1])
flag ... | Node(3)
a.left.left = TreeNode(4)
a.right.right = TreeNode(5)
s = Solution()
print(s.zigzagLevelOrder(a))
|
LaveyD/spider | spider/items.py | Python | gpl-3.0 | 957 | 0.003135 | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
from scrapy.item import | Item, Field
class SpiderItem(Item):
# define the fields for your item here like:
# name = scrapy.Field()
brand = Field()
name = Field()
type = Field()
category = Field()
shopname = Field()
productionName = Field()
| productId = Field()
url = Field()
price = Field()
promotionInfo = Field()
monthlySalesVolume = Field()
evaluationNum = Field()
#goodEvaluationNum = Field()
date = Field()
commentCount = Field()
averageScore = Field()
goodCount = Field()
goodRate = Field()
generalCount... |
nextgis/entels_front_demo | entels_demo_tornado/__init__.py | Python | gpl-2.0 | 548 | 0 | fr | om sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
)
from zope.sqlalchemy import ZopeTr | ansactionExtension
import tornado.web
from handlers.index import IndexHandler
from handlers.sensors import SensorsHandler
import logging
logging.getLogger().setLevel(logging.DEBUG)
app = tornado.web.Application([
(r'/', IndexHandler),
(r'/sensors', SensorsHandler)
])
DBSession = scoped_session(sessionmaker(... |
evangelistalab/forte | tests/pytest-methods/detci/test_detci-4.py | Python | lgpl-3.0 | 986 | 0.002028 | import pytest
from forte.solvers import solver_factory, HF, ActiveSpaceSolver
def test_detci_4():
"""CASCI test of Forte DETCI using the SparseList algorithm to build the sigma vector"""
ref_hf_energy = -99.977636678461636
ref_fci_energy = -100.113732484560970
xyz = """
F
H 1 1.0
"""
... | fci.run()
# check results
assert hf.value('hf energy') == pytest.approx(ref_hf_energy, 1.0e-10)
assert fci.value('active space energy')[state] == pytest.approx([ref_fci_energy], 1.0e-10)
if | __name__ == "__main__":
test_detci_4()
|
udoprog/mimeprovider | mimeprovider/__init__.py | Python | gpl-3.0 | 5,322 | 0 | import logging
from mimeprovider.documenttype import get_default_document_types
from mimeprovider.client import get_default_client
from mimeprovider.exceptions import MimeException
from mimeprovider.exceptions import MimeBadRequest
from mimeprovider.mim | erenderer import MimeRenderer
from m | imeprovider.validators import get_default_validator
__all__ = ["MimeProvider"]
__version__ = "0.1.5"
log = logging.getLogger(__name__)
def build_json_ref(request):
def json_ref(route, document=None, **kw):
ref = dict()
ref["$ref"] = request.route_path(route, **kw)
rel_default = None
... |
basnijholt/holoviews | holoviews/tests/plotting/matplotlib/testpointplot.py | Python | bsd-3-clause | 15,100 | 0.002318 | import numpy as np
from holoviews.core.overlay import NdOverlay
from holoviews.core.spaces import HoloMap
from holoviews.element import Points
from .testplot import TestMPLPlot, mpl_renderer
from ..utils import ParamLogStream
try:
from matplotlib import pyplot
except:
pass
class TestPointPlot(TestMPLPlot):... | ig_rcparams={'text.usetex': True})
points = Points(([0, 1], [0, 3])).opts(plot=opts)
m | pl_renderer.get_plot(points)
self.assertFalse(pyplot.rcParams['text.usetex'])
def test_points_rcparams_used(self):
opts = dict(fig_rcparams={'grid.color': 'red'})
points = Points(([0, 1], [0, 3])).opts(plot=opts)
plot = mpl_renderer.get_plot(points)
ax = plot.state.axes[0]
... |
tgroh/incubator-beam | sdks/python/apache_beam/io/range_trackers.py | Python | apache-2.0 | 14,379 | 0.00918 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | start == -1:
raise ValueError(
'The first record [starting at %d] must be at a split point' %
record_start)
if (split_point and self._offset_of_last_split_point != -1 and
record_start == self._offset_of_las | t_split_point):
raise ValueError(
'Record at a split point has same offset as the previous split '
'point: %d' % record_start)
if not split_point and self._last_record_start == -1:
raise ValueError(
'The first record [starting at %d] must be at a split point' %
r... |
wagtail/wagtail | wagtail/admin/views/pages/utils.py | Python | bsd-3-clause | 339 | 0 | from django.utils.http import url_has_allowed_host_and_scheme
def get_valid_next_url_from_request(request):
next_url = request.POST. | get("next") or request.GET.get("next")
if not next_url or not url_has_allowed_host_and_scheme(
url=next_url, allowed_hosts= | {request.get_host()}
):
return ""
return next_url
|
xiaonanln/myleetcode-python | src/683. K Empty Slots.py | Python | apache-2.0 | 479 | 0.043841 |
from bisect import bisect_ | left
class Solution(object):
def kEmptySlots(self, flowers, k):
"""
:type flowers: List[int]
:type k: int
:rtype: int
"""
S = []
for ithday, n in enumerate(flowers):
idx = bisect_left(S, n)
if idx > 0 and n - S[idx-1] == k+1:
return ithday + 1
elif idx < len(S) and S[idx] - n == k+1:
re... | ], 1)
|
badbytes/pymeg | meg/grid.py | Python | gpl-3.0 | 2,412 | 0.01534 | # grid.py
#
# Copyright 2009 danc <quaninux@gmail.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 2 of the License, or
# (at... | )/2.
cgrid = cube(location, gridsize, spacing)
print cgrid.shape, location
e = np.zeros(np.size(cgrid,1))
g = np.copy(e)
for i in range(0,np.size(cgrid,1)):
#e[:,i] = euclid.dist(location[0],cgrid[0][i],location[1],cgrid[1][i],location[2],cgrid[2][i])
e[i] = euclid.dist(location,cgri... | eter', e.max(), 'mm'
sgrid = cgrid[:,e < radius].reshape([3,np.size(cgrid[:,e < radius])/3])
#cgrid[e > radius].reshape([3,np.size(cgrid[e > radius])/3]) == 0
return sgrid#,cgrid
|
rob-nn/python | first_book/maitre_d.py | Python | gpl-2.0 | 377 | 0.007958 | # Maitre D'
# Demonstrates treating a value as a condition
print("Welcome to the Chateau D' Food")
print("It seems we are quite full this evening.\n")
money = int(input("How many dollars do you slip the Maitre D'"))
if money:
print("Ah, I am reminded of a table. R | ight this way.")
else:
print("Please, sit. It may be a while.")
input("\n\nPr | ess the enter key to exit.")
|
caskdata/cdap | cdap-docs/_common/tabbed-parsed-literal.py | Python | apache-2.0 | 30,649 | 0.00757 | # -*- coding: utf-8 -*-
# Copyright © 2016 Cask Data, 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 la... | :langu | ages: console,shell-session
:tabs: "Linux or OS/X",Windows
.. Linux
$ cdap-cli.sh start flow HelloWorld.WhoFlow
Successfully started flow 'WhoFlow' of application 'HelloWorld' with stored runtime arguments '{}'
$ curl -o /etc/yum.repos.d/cask.repo http://repository.cask.co/centos/6/x86_64... |
TobiasLundby/UAST | Module6/build/simulation/catkin_generated/pkg.develspace.context.pc.py | Python | bsd-3-clause | 377 | 0 | # generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INC | LUDE_DIRS = "".split(';') if "" != "" else []
PROJECT_CATKIN_DEPENDS = "".replace(';', ' ')
PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else []
PROJECT_NAME = "simulation"
PROJECT_SPACE_DIR = "/home/stagsted/UAST/Module6/devel"
PROJECT_VERS | ION = "0.0.0"
|
sdake/pacemaker-cloud | src/pcloudsh/openstack_deployable.py | Python | gpl-2.0 | 4,878 | 0.001845 | #
# Copyright (C) 2011 Red Hat, Inc.
#
# Author: Angus Salkeld <asalkeld@redhat.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 2
# of the License, or (at your option) any ... | a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
#
import os
import time
import libxml2
import exceptions
import uuid
import subprocess
import shutil
from pwd import getpwnam
from nova import flags
from nova import log
from nova import exception
from nova... | import utils
from nova.auth import manager
from pcloudsh import pcmkconfig
from pcloudsh import deployable
from pcloudsh import assembly
from pcloudsh import assembly_factory
FLAGS = flags.FLAGS
FLAGS.logging_context_format_string = ' %(levelname)s %(message)s'
FLAGS.logging_default_format_string = ' %(levelname)s %(... |
FireBladeNooT/Medusa_1_6 | lib/fake_useragent/__init__.py | Python | gpl-3.0 | 36 | 0 | from .fake | import UserAgent # noqa
| |
alihanniba/tornado-awesome | scrapy/taobaomm.py | Python | apache-2.0 | 3,677 | 0.004402 | #_*_coding: utf-8 _*_
#__author__ = 'Alihanniba'
import urllib.request
# from urllib.request import urlopen
import urllib.error
import re
import os
import taobaotool
import time
class Spider:
def __init__(self):
self.siteUrl = 'http://mm.taobao.com/json/request_top_list.htm'
self.tool = taobaotool... | turn True
else:
return False
def savePageInfo(self, pageIndex):
contents = self.getContents(pageIndex)
for item in contents:
detailURL = item[0]
detailPage = self.getDetailPage(detailURL)
brief = self.getBrie | f(detailPage)
images = self.getAllImg(detailPage)
self.mkdir(item[2])
self.saveBrief(brief, item[2])
self.saveIcon(item[1], item[2])
self.saveImgs(images, item[2])
def savePagesInfo(self, start, end):
for i in range(start, end + 1):
se... |
jasonwee/asus-rt-n14uhp-mrtg | src/lesson_algorithms/itertools_repeat_zip.py | Python | apache-2.0 | 96 | 0.010417 | from it | ertools import *
for i, s in zip(count(), repeat('over | -and-over', 5)):
print(i, s)
|
sbremer/hybrid_rs | evaluation/evaluation.py | Python | apache-2.0 | 5,761 | 0.002083 | from typing import Dict, List
import numpy as np
import hybrid_model
from evaluation import evaluation_metrics
from evaluation import evaluation_parting
metrics_rmse = {'rmse': evaluation_metrics.Rmse()}
metrics_rmse_prec = {'rmse': evaluation_metrics.Rmse(),
'prec@5': evaluation_metrics.Precis... | BinningItem(n_bins, i) for i in range(n_bins)})
return parting
class Evaluation:
def __init__(self,
metrics: Dict[str, evaluation_metrics.Metric] = metrics_rmse_prec,
parts: Dict[str, evaluation_parting.Parting] = parting_full):
self.metrics = metrics
self.p... | esultHybrid':
result = EvaluationResultHybrid()
result.cf = self.evaluate(model.model_cf, x_test, y_test)
result.md = self.evaluate(model.model_md, x_test, y_test)
return result
def evaluate(self, model: 'hybrid_model.models.AbstractModel', x_test: List[np.ndarray], y_test: np.ndar... |
andrei14vl/cubrid | contrib/python/samples/sample_CUBRIDdb.py | Python | gpl-3.0 | 872 | 0.006912 | # -*- encoding:utf-8 -*-
# sample_CUBRIDdb.py
import CUBRIDdb
con = CUBRIDdb.connect('CUBRID:localhost:33000:demodb:::', 'public')
cur = con.cursor()
cur.execute('DROP TABLE IF EXISTS test_cubrid')
cur.execute('CREATE TABLE test_cubrid (id NUMERIC AUTO_INCREMENT(2009122350, 1), name VARCHAR(50))')
cur.execute("... | into test_cubrid (name) values (?), (?)", ['中文zh-cn', 'John'])
cur.execute("insert into test_cubrid | (name) values (?)", ['Tom',])
cur.execute('select * from test_cubrid')
# fetch result use fetchone()
row = cur.fetchone()
print(row)
print('')
# fetch result use fetchmany()
rows = cur.fetchmany(2)
for row in rows:
print(row)
print("")
rows = cur.fetchall()
for row in rows:
print(row)
cur.close()
con.clos... |
ccherrett/oom | share/pybridge/examples/addtrack.py | Python | gpl-2.0 | 930 | 0.025806 | """
//=========================================================
// OOMidi
// OpenOctave Midi and | Audio Editor
// (C) Copyright 2009 Mathias Gyllengahm (lunar_shuttle@users.sf.net)
//=========================================================
"""
import Pyro.core
import time
oom=Pyro.core.getProxyForURI('PYRONAME://:Default.oom')
for j in range(0,5):
for i in range(0,30):
oom.addMidiTrack("amid... | ):
print i
oom.addMidiTrack("amiditrack")
oom.addWaveTrack("awavetrack")
oom.addOutput("anoutput")
oom.addInput("aninput")
oom.setMute("aninput", False)
oom.setAudioTrackVolume("aninput",1.0)
oom.deleteTrack("amiditrack")
oom.deleteTrack("awavetrack")
oom.dele... |
jj1bdx/bdxlog | scripts/logsc.py | Python | mit | 1,491 | 0.022133 | #!/usr/local/bin/python
#$Id: logsc.py,v 1.7 2013/11/15 15:07:06 kenji Exp $
from sqlite3 import dbapi2 as sqlite
import sys
# change integer to string if found
def int2str(p):
if type(p) == int:
return str(p)
else:
return p
if __name__ == '__main__':
con = sqlite.connect("/home/kenji/txt/hamradio/LOGS... | 1]
print "my_call: ", row[2]
print "call: ", row[3]
print "band: ", row[4 | ]
print "mode: ", row[5]
print "rst_sent: ", row[6]
print "qsl_sent: ", row[7]
print "qsl_via: ", row[8]
print "comment: ", row[9]
print "my_qso_id: ", row[10]
cur.close()
|
Metaswitch/calico-nova | nova/tests/unit/api/openstack/compute/contrib/test_extended_evacuate_find_host.py | Python | apache-2.0 | 4,623 | 0.000649 | # Copyright 2013 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | s.wsgi_app(fake_auth_context=ctxt)
req = webob.Request.blank('/v2/fake/s | ervers/%s/action' % self.UUID)
req.method = 'POST'
req.body = jsonutils.dumps({
'evacuate': {
'onSharedStorage': 'False',
'adminPass': 'MyNewPass'
}
})
req.content_type = 'application/json'
res = req.get_response(app)
... |
idle-code/ContextShell | tests/functional/ShellTestsBase.py | Python | mit | 1,673 | 0 | import unittest
from abc import ABC, abstractmethod
from contextshell.action impo | rt ActionExecutor, Executor
from contextshell.backends.node import NodeTreeRoot
from contextshell.backends.virtual import VirtualTree
from contextshell.command import CommandInterpreter
from contextshell.path import NodePath
from contextshell.shell import Shell
class ShellScriptTestsBase(unit | test.TestCase, ABC):
@abstractmethod
def create_shell(self) -> Shell:
raise NotImplementedError()
class TreeRootTestsBase(ShellScriptTestsBase):
@abstractmethod
def create_tree_root(self):
raise NotImplementedError()
def create_shell(self):
self.tree_root = self.create_tre... |
rohitranjan1991/home-assistant | tests/components/mqtt/test_climate.py | Python | mit | 64,945 | 0.000939 | """The tests for the mqtt climate component."""
import copy
import json
from unittest.mock import call, patch
import pytest
import voluptuous as vol
from homeassistant.components import climate
from homeassistant.components.climate import DEFAULT_MAX_TEMP, DEFAULT_MIN_TEMP
from homeassistant.components.climate.const ... | arametrize(
"parameter,config_value",
[
| ("away_mode_command_topic", "away-mode-command-topic"),
("away_mode_state_topic", "away-mode-state-topic"),
("away_mode_state_template", "{{ value_json }}"),
("hold_mode_command_topic", "hold-mode-command-topic"),
("hold_mode_command_template", "hold-mode-command-template"),
("ho... |
undeath/joinmarket-clientserver | test/test_full_coinjoin.py | Python | gpl-3.0 | 6,442 | 0.001242 | #! /usr/bin/env python
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import * # noqa: F401
'''Runs a full joinmarket pit (using `nirc` miniircd servers,
with `nirc` options specified as an option to pytest),in
bitcoin regtest mode with 3 maker... | th 1
assert oldbal + | newbal + (40000 - 2000) + taker.total_txfee == 600000000
if fromtx == "unconfirmed":
#If final entry, stop *here*, don't wait for confirmation
if taker.schedule_index + 1 == len(taker.schedule):
reactor.stop()
final_checks()
return
... |
antoinecarme/pyaf | tests/model_control/detailed/transf_Quantization/model_control_one_enabled_Quantization_ConstantTrend_Seasonal_MonthOfYear_LSTM.py | Python | bsd-3-clause | 171 | 0.046784 | import tests.model_control.test_ozone_custom_models_enabled as testmod |
testmod.build_model( ['Quantization'] , ['ConstantTrend'] , ['Seasonal_MonthOfYear'] , ['LSTM'] ); | |
UAVCAN/pyuavcan | pyuavcan/transport/udp/_session/__init__.py | Python | mit | 729 | 0.002743 | # Copyright (c) 2019 UAVCAN Consortium
# This software is distributed under the terms of the MIT License.
# Author: Pavel Kirienko <pavel@uavcan.org>
from ._input import UDPInputSession as UDPInputSession
from ._input import PromiscuousUDPInputSession as PromiscuousUDPInputSession
from ._input import SelectiveUDPInput... | ssionStatistics
from ._input import SelectiveUDPInputSessionStatistics as SelectiveUDPInputSessionStatistics
from ._output im | port UDPOutputSession as UDPOutputSession
from ._output import UDPFeedback as UDPFeedback
|
boltnev/iktomi | iktomi/cli/lazy.py | Python | mit | 1,023 | 0.001955 | from iktomi.utils import cached_property
from .base import Cli
class LazyCli(Cli):
'''
Wrapper for creating lazy command digests.
Sometimes it is not needed to i | mport all of application parts to start
a particular command. LazyCli allows you to define all imports in a
function called only on the command::
@LazyCli
def db_command():
import admin
from admin.environment import db_maker
from models import initial
... | aker, initial=initial.install)
# ...
def run(args=sys.argv):
manage(dict(db=db_command, ), args)
'''
def __init__(self, func):
self.get_digest = func
@cached_property
def digest(self):
return self.get_digest()
def description(self, *args, **kwargs):
... |
AltSchool/django-allauth | allauth/socialaccount/providers/disqus/tests.py | Python | mit | 2,347 | 0 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.contrib.auth.models import User
from django.test.utils import override_settings
from allauth.account import app_settings as account_settings
from allauth.account.models import EmailAddress
from allauth.socialaccount.models im... | ame,
password='test')
self.login(self.get_mocked_response(), process='connect')
# Check if we connected...
self.assertTrue(SocialAccount.objects.filter(
user=user,
provider=DisqusProvider.id).exists())
# For now, we do not pick up any new... | email=email).count(), 1)
|
hsoft/pdfmasher | ebooks/epub/output.py | Python | gpl-3.0 | 3,361 | 0.005356 | # Copyright 2009, Kovid Goyal <kovid@kovidgoyal.net>
# Copyright 2013 Hardcoded Software (http://www.hardcoded.net)
#
# This software is licensed under the "GPL v3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.hardcoded.net/lic... | size=flow_size*1024)
split(oeb)
cm = CoverManager(no_default_cover=no_default_epub_cover, no_svg_cover=no_svg_cover,
preserve_aspect_ratio=preserve_cover_aspect_ratio)
cm(oeb)
if oeb.toc.count() == 0:
logging.warn('This EPUB file has no Table of Contents. Creating a default TOC')
| first = next(iter(oeb.spine))
oeb.toc.add('Start', first.href)
identifiers = oeb.metadata['identifier']
uuid = None
for x in identifiers:
if x.get(OPF('scheme'), None).lower() == 'uuid' or str(x).startswith('urn:uuid:'):
uuid = str(x).split(':')[-1]
break
if ... |
karelklic/flashfit | task.py | Python | gpl-3.0 | 695 | 0.004317 | from PyQt4 import QtCore, QtGui
class Task(QtCore.QThread):
messageAdded = QtCore.pyqtSignal(QtCore.QString)
def __ini | t__(self, mainWindow, parent = None):
super(Task, self).__init__(parent)
self.mainWindow = mainWindow
self.finished.connect(self.postRun)
self.terminated.connect(self.postTerminated)
def run(self):
"""
The code in this method is run in another thread.
"""
... | def postTerminated(self):
"""
The code in this method is run in GUI thread.
"""
pass
|
genialis/django-rest-framework-reactive | src/rest_framework_reactive/api_urls.py | Python | apache-2.0 | 133 | 0.007519 | from djang | o.urls import path
from . | import views
urlpatterns = [path('unsubscribe', views.QueryObserverUnsubscribeView.as_view())]
|
NoiSek/whisper | whisper/models/whisperkey.py | Python | gpl-2.0 | 5,369 | 0.017322 | import nacl.encoding
import nacl.public
import nacl.utils
class WhisperKey():
def __init__(self, key=None):
if key is None:
self.generate_keypair()
else:
if isinstance(key, bytes) or isinstance(key, str):
try:
self._private_key = nacl.public.PrivateKey(key, encoder=nacl.encodin... | y = self._private_key.encode(encoder=nacl.encoding.Base64Encoder)
file_contents += private_key
return file_contents
else:
return self._private_key
def get_public_key(self, stringify=False):
public_key = self._private_key.public_key
if stringify:
return (
public_key
... | def encrypt_message(self, message, public_key, nonce=None):
# Verify that we can convert the public_key to an nacl.public.PublicKey instance
if isinstance(public_key, nacl.public.PublicKey):
pass
elif isinstance(public_key, str) or isinstance(public_key, bytes): # pragma: no cover
public_key = ... |
factorlibre/l10n-spain | l10n_es_pos/models/ir_sequence.py | Python | agpl-3.0 | 890 | 0 | # Copyright | 2018 David Vidal <david.vidal@tecnativa.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import _, api, models
from odoo.exceptions import UserError
class IrSequence(models.Model):
_inherit = 'ir.sequence'
@api.constrains('prefix', 'code')
def check_simplified_invoice_uni... | lambda x: x.code == 'pos.config.simplified_invoice'):
if self.search_count([
('code', '=', 'pos.config.simplified_invoice'),
('prefix', '=', sequence.prefix)]) > 1:
raise UserError(_('There is already a simplified invoice '
... |
mettadatalabs1/oncoscape-datapipeline | setup.py | Python | apache-2.0 | 191 | 0 |
# just listing list of requires | . will create a set | up using these
"""
airflow>=1.7.1,
numpy>=1.1,
requests>=2.1,
pymongo==3.4.0,
pytest>=3.0,
simplejson==3.10.0,
tox==2.6
PyYAML==3.12
"""
|
KaranToor/MA450 | google-cloud-sdk/lib/surface/compute/regions/list.py | Python | apache-2.0 | 965 | 0.005181 | # Copyright 2014 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 t | he 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 spe... |
cwmartin/rez | src/rez/cli/selftest.py | Python | lgpl-3.0 | 3,095 | 0.000323 | '''
Run unit tests.
'''
import inspect
import os
import rez.vendor.argparse as argparse
from pkgutil import iter_modules
cli_dir = os.path.dirname(inspect.getfile(inspect.currentframe()))
src_rez_dir = os.path.dirname(cli_dir)
tests_dir = os.path.join(src_rez_dir, 'tests')
all_module_tests = []
def setup_parser(par... | :
module = importer.find_module(name).load_module(name)
name_ = name[len(prefix):]
all_module_tests.append(name_)
tests.append((name_, module))
# create argparse entry for each module's unit test
for name, module in sorted(tests):
parser.add_argument(
... | action=AddTestModuleAction, nargs=0,
dest="module_tests", default=[],
help=module.__doc__.strip().rstrip('.'))
def command(opts, parser, extra_arg_groups=None):
import sys
from rez.vendor.unittest2.main import main
os.environ["__REZ_SELFTEST_RUNNING"] = "1"
if opts.only_shel... |
matyro/Cor-RC | Website/site_rawPacket.py | Python | mit | 1,137 | 0.024626 | from Website.site_base import BaseHandler
import tornado.web
import tornado
import SQL.table_simulation as SQLsim
class RawPacketHandler(BaseHandler):
@tornado.web.authenticated
def get(self):
if self.current_user is None:
self.redirect('login.html?next=edit')
| return
if self.current_user.permission < 9000:
self.redirect('/')
return
sim = self.database.query(SQLsim.Simulation).filter( SQLsim.Simulation.status==1 ).all()
print('Sim: ' + str(sim))
... |
def post(self):
print(str(self.request))
print('Message: ' + str( self.get_argument('message', '')))
print('Client: ' + str( self.get_argument('client', '')))
print('header: ' + str( self.get_argument('header', '')))
self.redire... |
NicovincX2/Python-3.5 | Théorie des nombres/Nombre/Nombre aléatoire/random_points_on_a_circle.py | Python | gpl-3.0 | 691 | 0 | # -*- coding: utf-8 -*-
import os
from collections import defaultdict
from random import choice
world = defaultdict(int)
possiblepoints = [(x, y) for x in range(-15, 16)
for y in range(-15, 16)
if 10 <= abs(x + y * 1j) <= 15]
for i in range(100):
world[choice(possiblepoints)] +... |
print(''.join(str(min | ([9, world[(x, y)]])) if world[(x, y)] else ' '
for y in range(-15, 16)))
os.system("pause")
|
achadwick/mypaint | gui/layerswindow.py | Python | gpl-2.0 | 14,745 | 0.001695 | # This file is part of MyPaint.
# Copyright (C) 2014 by Andrew Chadwick <a.t.chadwick@gmail.com>
# Copyright (C) 2009 by Ilya Portnov <portnov@bk.ru>
#
# 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 Founda... | (label=_('Mode:'))
label.set_tooltip_text(
_("Blending mode: how the current layer combines with the "
"layers underneath it."))
label.set_alignment(0, 0.5)
label.set_hexpand(False)
grid.attach(label, 0, row, 1, 1)
store = Gtk.ListStore(int, str, bool)
... | modes = lib.layer.STACK_MODES + lib.layer.STANDARD_MODES
for mode in modes:
label, desc = lib.layer.MODE_STRINGS.get(mode)
store.append([mode, label, True])
combo = Gtk.ComboBox()
combo.set_model(store)
combo.set_hexpand(True)
cell = Gtk.CellRendererTex... |
daniel-bell/google-codejam-2014 | qualification/a_magic_trick.py | Python | mit | 802 | 0.032419 | import sys
file_name = sys.argv[1]
with open(file_name, "r") as f:
num = int(f.readline())
for i in range(num):
first_row = int(f.readline()) - 1
first_board = list()
for x in range(4):
raw_line = f.readline()
line = [int(x) for x in raw_line.split(" ")]
first_board.append(line)
|
second_row = int(f.readline()) - 1
second_board = list()
for x in range(4):
raw_line = f.readline()
line = [int(x) for x in raw_line.split(" ")]
second_board.append(line)
common_values = [x for x in first_board[first_row] if x in second_board[second_row]];
if not common_ | values:
case_string = "Volunteer cheated!"
elif len(common_values) > 1:
case_string = "Bad magician!"
else:
case_string = str(common_values[0])
print("Case #" + str(i + 1) + ": " + case_string) |
daisychainme/daisychain | daisychain/channel_facebook/tests/test_base.py | Python | mit | 2,078 | 0.001444 | from django.contrib.auth.models import User
from django.test import TestCase
from django.test.client import Client
from django.utils import timezone
from channel_facebook. | channel import FacebookChannel
from channel_facebook.models import FacebookAccount
from core import models
class FacebookBaseTestCase(TestCase):
fixtures = ['core/fixtures/initial_data.json','channel_facebook/fixtures/initial_data.json']
class MockResponse:
def __init__(self, json_data | , status_code, ok):
self.json_data = json_data
self.status_code = status_code
self.ok = ok
def json(self):
return self.json_data
def setUp(self):
self.time = timezone.now()
self.user = self.create_user()
self.facebook_account = self.c... |
naparuba/kunai | opsbro/module.py | Python | mit | 3,141 | 0.013372 | from .parameters import ParameterBasedType
from .log import LoggerFactory
from .packer import packer
from .misc.six import add_metaclass
TYPES_DESCRIPTIONS = {'generic' : 'Generic module', 'functions_export': 'Such modules give functions that are useful by evaluation rules',
'connector': 'Suchs ... | ''
module_type = 'generic'
@classmethod
def get_sub_class(cls):
return cls.__inheritors__
def __init__(self):
ParameterBasedType.__init__(self)
self.daemon = None
# Global logger for this part
self.logger = LoggerFactory.create_logger(... | name'):
self.pack_directory = packer.get_pack_directory(self.pack_level, self.pack_name)
else:
self.pack_directory = ''
def get_info(self):
return {'configuration': self.get_config(), 'state': 'DISABLED', 'log': ''}
def prepare(self):
return
... |
inmagik/contento | contento/tests/__init__.py | Python | mit | 220 | 0.004545 | from django.test import TestCase
class Anima | lTestCase(TestCase):
def setUp(self):
print 2
def test_animals_can_speak(sel | f):
"""Animals that can speak are correctly identified"""
print 3
|
YzPaul3/h2o-3 | h2o-py/h2o/connection.py | Python | apache-2.0 | 29,700 | 0.015354 | """
An H2OConnection represents the latest active handle to a cloud. No more than a single
H2OConnection object will be active at any one time.
"""
from __future__ import print_function
from __future__ import absolute_import
import requests
import math
import tempfile
import os
import re
import sys
import time
import s... | path_to_jar = os.path.exists(jar_path)
if path_to_jar:
if not ice_root:
ice_root = tempfile.mkdtemp()
cld = self._start_local_h2o_jar(max_mem_size, min_mem_size, enable_assertions, license, ice_root, jar_path, nthreads)
else:
print("No | jar file found. Could not start local instance.")
print("Jar Paths searched: ")
for jp in jarpaths:
print("\t" + jp)
print()
raise
__H2OCONN__._cld = cld
if strict_version_check and os.environ.get('H2O_DISABLE_STRICT_VERSION_CHECK') is None:
ver_h2o = cld['versio... |
mcdeoliveira/ctrl | examples/rc_motor_control.py | Python | apache-2.0 | 4,210 | 0.024703 | #!/usr/bin/env python3
def main():
# import python's standard math module and numpy
import math, numpy, sys
# import Controller and other blocks from modules
from pyctrl.rc import Controller
from pyctrl.block import Interp, Logger, Constant
from pyctrl.block.system import System, Differen... | the controller
bbb.add_timer('stop',
Constant(value = 0),
None, ['is_running'],
period = 6, repeat = False)
# print controller info
print(bbb.info('all'))
try:
# run the controller
| print('> Run the controller.')
# set speed_reference
#bbb.set_signal('speed_reference', 5)
# reset clock
bbb.set_source('clock', reset = True)
with bbb:
# wait for the controller to finish on its own
bbb.join()
print('> Done ... |
egeland/agodaparser | agodaparser.py | Python | gpl-3.0 | 2,962 | 0.005402 | #!/usr/bin/env python3
# pylint: disable=C0103, C0325, C0301
"""
Zipped Agoda Hotel Data File Parser
-----------------------------------
This utility unzips and parses the Agoda hotel data file, in-memory,
and makes the data available
"""
import csv
import zipfile
import io
import sys
class AgodaParser(object):
... | as datafh:
datafh.read(3) # strips the BOM
csvReader = csv.DictReader(io.TextIOWrapp | er(datafh), delimiter=',', quotechar='"')
self.result = []
for row in csvReader:
if not float == type(row['rates_from']):
try:
rates_from = float(row['rates_from'])
except ValueError:
#print(... |
OsirisSPS/osiris-sps | client/data/extensions/148B613D055759C619D5F4EFD9FDB978387E97CB/scripts/oml/rotator.py | Python | gpl-3.0 | 610 | 0.04918 | import os
import osiris
import globalvars
class OmlRotator(osiris.OMLHtmlWrapper):
def __init__(self, tag):
osiris.OMLHtmlWrapper.__init__(self, tag, "div", False, "", "", "")
def processHtml(self, item, context):
extensionID = globalvars.extension.getID().getString()
context.page.addJav | ascript("/htdocs/js/oml/rotator.js")
item.setParam("id","rotator_" + osiris.UniqueID.generat | e().getString())
script = "<script type=\"text/javascript\">Rotator.init('" + item.getParam("id") + "');</script>";
return osiris.OMLHtmlWrapper.processHtml(self, item, context) + script;
|
jasonrollins/shareplum | shareplum/__init__.py | Python | mit | 360 | 0 | # SharePlum
# This library simplfies the code necessary
# to automate interactions with a SharePoint
# server using python
from .office365 import Office365 # noqa: F401
from .site imp | ort Site # noqa: F401
from .version import __version__ # noqa: F | 401
__all__ = ["site", "office365"]
__title__ = "SharePlum SharePoint Library"
__author__ = "Jason Rollins"
|
nicko96/Chrome-Infra | appengine/crbuild/gerrit/test/client_test.py | Python | bsd-3-clause | 3,159 | 0.001266 | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from mock import Mock
from gerrit import GerritClient
from test import CrBuildTestCase
SHORT_CHANGE_ID = 'I7c1811882cf59c1dc55018926edb6d35295c53b8'
CHANGE... | , REVISION, message='Hi!', labels=labels)
client._fetch.assert_called_with(req_path, method='POST', body={
'message': 'Hi!',
'labels': labels,
})
# Test with "notify" parameter.
client.set_review(CHANGE_ID, REVISION, message='Hi!', labels=labels,
notify='all')
... | nt._fetch.assert_called_with(req_path, method='POST', body={
'message': 'Hi!',
'labels': labels,
'notify': 'ALL',
})
with self.assertRaises(AssertionError):
client.set_review(CHANGE_ID, REVISION, notify='Argh!')
|
chapmanb/cloudbiolinux | cloudbio/custom/versioncheck.py | Python | mit | 2,864 | 0.003142 | """Tool specific version checking to identify out of date dependencies.
This provides infrastructure to check version strings against installed
tools, enabling re-installation if a version doesn't match. This is a
lightweight way to avoid out of date dependencies.
"""
from __future__ import print_function
from distuti... | ag,
stdout_index)
if not iversion:
return False
else:
return LooseVersion(iversion) == LooseVersion(version)
def get_installed_version(env, cmd, version, args=None, stdout_flag=None,
stdout_index=-1):
"""Check if the given comma... | ovided version.
"""
if shared._executable_not_on_path(cmd):
return False
if args:
cmd = cmd + " " + " ".join(args)
with quiet():
path_safe = ("export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:{s}/lib/pkgconfig && "
"export PATH=$PATH:{s}/bin && "
... |
sendgrid/sendgrid-python | sendgrid/helpers/stats/__init__.py | Python | mit | 29 | 0 | fr | om .stats import * # no | qa
|
schnapptack/gskompetenzen | features/gsaudit/migrations/0011_auto__add_field_pupil_birthday.py | Python | agpl-3.0 | 12,951 | 0.006486 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Pupil.birthday'
db.add_column('gsaudit_pupil', 'birthday',
self.gf('dj... | 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content | _type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.... |
liqiangnlp/LiNMT | scripts/hint.aware/chunk/eng/LiNMT-postprocess-text-chunking-rmNP.py | Python | mit | 2,875 | 0.017043 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: Qiang Li
# Email: liqiangneu@gmail.compile
# Time: 10:27, 03/30/2017
import sys
import codecs
import argparse
import random
from io import open
argparse.open = open
reload(sys)
sys.setdefaultencoding('utf8')
if sys.version_info < (3, 0):
sys.stderr = codecs.g... | =sys.stdin,
metavar='PATH', help='Input text (default: standard input).')
parser.add_argument(
'--outword', '-w', type=argparse.FileType('w'), required=True,
metavar='PATH', help='Output word file')
| parser.add_argument(
'--outlabel', '-l', type=argparse.FileType('w'), required=True,
metavar='PATH', help='Output label file')
return parser
def pos_postprocess(ifobj, owfobj, olfobj, ologfobj):
line_word = ''
line_label = ''
total_words = 0
reserved_words = 0
remove_words = 0
for line in ifo... |
ankitshah009/High-Radix-Adaptive-CORDIC | Testbench Generation code/Testbench Files/test_sin,sinh.py | Python | apache-2.0 | 3,601 | 0.064149 | import math,sys
from math import pi
def ieee754 (a):
rep = 0
#sign bit
if (a<0):
rep = 1<<31
a = math.fabs(a)
if (a >= 1):
#exponent
exp = int(math.log(a,2))
rep = rep|((exp+127)<<23)
#mantissa
temp = a / pow(2,exp) - 1
i = 22
while i>=0:
temp = temp * 2
if temp > 1:
rep = rep | (1... | or[1]
x_processor = str(x_processor)
y_processor = 0.5 + 0.01*time
y_processor = float(y_processor)
y_processor = ieee754(y_processor)
y_processor = hex(y_proce | ssor)
y_processor = y_processor.split('x')
y_processor = y_processor[1]
y_processor = str(y_processor)'''
x_processor = str(00000000);
y_processor = str(00000000);
z_processor = time*pi/180
z_float1 = float(z_processor)
z_processor = ieee754(z_float1)
z_processor = hex(z_processor)
z_processor = z_p... |
agry/NGECore2 | scripts/expertise/expertise_sm_path_inside_information_1.py | Python | lgpl-3.0 | 199 | 0.030151 | import sys
def addAbiliti | es(core, actor, player):
actor.addAbility("sm_inside_information")
return
def removeAbilities(core, acto | r, player):
actor.removeAbility("sm_inside_information")
return
|
chartbeat-labs/mongomock | mongomock/collection.py | Python | bsd-3-clause | 39,269 | 0.006239 | import collections
import copy
import functools
import itertools
import json
import time
import warnings
from sentinels import NOTHING
from .filtering import filter_applies, iter_key_candidates
from . import ObjectId, OperationFailure, DuplicateKeyError
from .helpers import basestring, xrange, print_deprecation_warning... | subdocument = None
for k, v in iteritems(document):
if k == '$set':
positional = False
for key in iterkeys(v):
if '$' in key:
positional = True
break
... | nue
self._update_document_fields(existing_document, v, _set_updater)
elif k == '$setOnInsert':
if not was_insert:
continue
positional = any('$' in key for key in iterkeys(v))
if positional:
... |
jdhp-sap/data-pipeline-standalone-scripts | datapipe/optimization/objectivefunc/tailcut_delta_psi.py | Python | mit | 6,676 | 0.004046 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2016 Jérémie DECOCK (http://www.jdhp.org)
# This script is provided under the terms and conditions of the MIT license:
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (th... | max_num_img=self.max_num_img)
score_list = []
# Read and compute results from output_dict
| for image_dict in output_dict["io"]:
# POST PROCESSING FILTERING #######################################
# >>>TODO<<<: Filter images: decide wether the image should be used or not ? (contained vs not contained)
# TODO: filter these images *before* cleaning them to ... |
JackDanger/sentry | src/sentry/south_migrations/0077_auto__add_trackeduser__add_unique_trackeduser_project_ident.py | Python | bsd-3-clause | 22,623 | 0.008222 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'TrackedUser'
db.create_table('sentry_trackeduser', (
('id', self.gf('sentry.db.m... | '128'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_ty... | 0'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'sentry.affecteduse... |
cawka/pybindgen | pybindgen/typehandlers/pyobjecttype.py | Python | lgpl-2.1 | 2,516 | 0.001192 | # docstrings not neede here (the type handler doubleerfaces are fully
# documented in base.py) pylint: disable-msg=C0111
from .base import ReturnValue, Parameter, \
ReverseWrapperBase, ForwardWrapperBase
class PyObjectParam(Parameter):
DIRECTIONS = [Parameter.DIRECTION_IN]
CTYPES = ['PyObject*']
d... | thon(self, wrapper):
assert isinstance(wrapper, ReverseWrapperBase)
if self.transfer_ownership:
wrapper.build_params.add_parameter('N', [self.value])
else:
wrapper.build_params.add_parameter('O', [self.value])
def convert_python_to_c(self, wrapper):
assert is... | 'O', ['&'+name], self.name)
wrapper.call_params.append(name)
if self.transfer_ownership:
wrapper.before_call.write_code("Py_INCREF((PyObject*) %s);" % name)
class PyObjectReturnValue(ReturnValue):
CTYPES = ['PyObject*']
def __init__(self, ctype, caller_owns_return, is_const=False... |
oscaro/django | tests/middleware/tests.py | Python | bsd-3-clause | 32,964 | 0.001335 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import gzip
from io import BytesIO
import random
import re
from unittest import skipIf
import warnings
from django.conf import settings
from django.core import mail
from django.db import (transaction, connections, DEFAULT_DB_ALIAS,
... | uest), None)
@override_settings(APPEND_SLASH=True)
def test_append_slash_quoted(self):
"""
Tests that URLs which require quoting are redirected to their slash
version ok.
"""
request = self._get_request('needsquoting#')
r = CommonMiddleware().process_re | quest(request)
self.assertEqual(r.status_code, 301)
self.assertEqual(
r.url,
'http://testserver/needsquoting%23/')
@override_settings(APPEND_SLASH=False, PREPEND_WWW=True)
def test_prepend_www(self):
request = self._get_request('path/')
r = CommonMiddlewa... |
Sezzh/tifis_platform | tifis_platform/groupmodule/migrations/0001_initial.py | Python | gpl-2.0 | 711 | 0.001406 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('usermodule', '0002_auto_20151108_2019'),
]
operations = [
migrations.CreateModel(
name | ='Period',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_creat | ed=True, primary_key=True)),
('name', models.CharField(max_length=10)),
('start_date', models.DateField()),
('end_date', models.DateField()),
('professor', models.ForeignKey(to='usermodule.Professor')),
],
),
]
|
rokj/django_newsletter | newsletter/admin.py | Python | mit | 1,249 | 0.008006 | # -*- coding: utf-8 -*-
import datetime
from django.contrib import admin
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from newsletter.models import Newsletter, NewsletterSubscription
from newsletter.views import send_mass_email
def send_emails(newsletter, emails):
if s... | ent_to = ';'.join(emails)
newsletter.save()
def send_newsletter(modeladmin, request, queryset):
for q in queryset:
newsletter_subscriptions = NewsletterSubscri | ption.objects.filter(subscribed=True)
emails = [ns.email for ns in newsletter_subscriptions]
send_emails(q, emails)
send_newsletter.short_description = _(u"Send newsletter")
class NewsletterAdmin(admin.ModelAdmin):
list_display = ['title', 'txt', 'html', 'datetime_sent']
ordering = ['-datetime... |
AEDA-Solutions/matweb | backend/Database/Models/Periodo.py | Python | mit | 742 | 0.074124 | from Database.Controllers.Curso import Cu | rso
class Periodo(object):
def __init__(self,dados=None):
if dados is not None:
| self.id = dados ['id']
self.id_curso = dados ['id_curso']
self.periodo = dados ['periodo']
self.creditos = dados ['creditos']
def getId(self):
return self.id
def setId_curso(self,id_curso):
self.id_curso = id_curso
def getId_curso(self):
return self.Id_curso
def getCurso(self):
return... |
kamyarg/enfame | metuly/urls.py | Python | gpl-2.0 | 489 | 0.010225 | from django.conf.urls import pa | tterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'metuly.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^accounts/l | ogin/$', 'django.contrib.auth.views.login'),
url(r'^accounts/logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}),
url(r'', include('meddit.urls')),
)
|
mwhooker/jones | jones/web.py | Python | apache-2.0 | 5,362 | 0.000559 | """
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 ... | methods=ALL_METHODS)
@app.route('/service/<string:service>/<path:env>/', methods=ALL_METHODS)
def services(service, env):
jones = Jones(service, get_zk())
environment = Env(env)
return SERVICE[request.method.lower()](environment, jones)
@app.route('/service/<string:service>/association/<string:assoc>... | ET':
if request_wants('application/json'):
return jsonify(jones.get_config(assoc))
if request.method == 'PUT':
jones.assoc_host(assoc, Env(request.form['env']))
return service, 201
elif request.method == 'DELETE':
jones.delete_association(assoc)
return service... |
archivsozialebewegungen/AlexandriaBase | tests/servicestests/test_creator_service.py | Python | gpl-3.0 | 732 | 0.008197 | '''
Created on 12.03.2016
@author: michael
'''
import unit | test
from unittest.mock import MagicMock
from alexandriabase.daos import CreatorDao
from alexandriabase.domain import Creator
from alexandriabase.services import CreatorService
class CreatorServiceTest(unittest.TestCase):
def testFindVisible(self):
dao = MagicMock | (spec=CreatorDao)
dao.find_all_visible.return_value = [Creator(34), Creator(35)]
service = CreatorService(dao)
result = service.find_all_active_creators()
self.assertEqual(35, result[1].id)
dao.find_all_visible.assert_called_once_with()
if __name__ == "__main_... |
kou/arrow | python/pyarrow/tests/parquet/test_encryption.py | Python | apache-2.0 | 20,329 | 0 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | QUET_NAME)
def test_encrypted_parquet_read_schema_no_decryption_c | onfig(
tempdir, data_table):
"""Write an encrypted parquet, verify it's encrypted,
but then try to read its schema without decryption properties."""
test_encrypted_parquet_write_read(tempdir, data_table)
with pytest.raises(IOError, match=r"no decryption"):
pq.read_schema(tempdir / PARQUE... |
kashefy/caffe_sandbox | nideep/datasets/twoears/label_utils.py | Python | bsd-2-clause | 798 | 0.017544 | '''
Created on Apr 25, 2017
@author: kashefy
'''
import numpy as np
import h5py
from nideep.iow.file_system_utils import gen_paths, filter_is_h5
def id_loc_to_loc(fpath_src, key_dst, key_src='label_id_loc', has_void_bin=True):
with h5py.File(fpath_src, 'r+') as h:
if has_void_bin:
l = np.... | lter_is_ | h5(fpath):
id_loc_to_loc(fpath, key_dst)
return True # otherwise gen_paths won't append to list
flist = gen_paths(dir_src, func_filter=runner)
return flist
if __name__ == '__main__':
pass |
drpngx/tensorflow | tensorflow/contrib/predictor/contrib_estimator_predictor.py | Python | apache-2.0 | 3,274 | 0.003054 | # Copyright 2016 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... | =====================================================
"""A `Predictor constructed from a `tf.contrib.learn.Estimator`."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.learn.python.learn.utils import saved_model_ex | port_utils
from tensorflow.contrib.predictor import predictor
from tensorflow.python.framework import ops
from tensorflow.python.training import monitored_session
from tensorflow.python.training import saver
class ContribEstimatorPredictor(predictor.Predictor):
"""A `Predictor constructed from a `tf.contrib.learn.E... |
dbbhattacharya/kitsune | vendor/packages/translate-toolkit/translate/convert/test_xliff2po.py | Python | bsd-3-clause | 8,448 | 0.00071 | #!/usr/bin/env python
from translate.convert import xliff2po
from translate.misc import wStringIO
from translate.storage.test_base import headerless_len, first_translatable
class TestXLIFF2PO:
xliffskeleton = '''<?xml version="1.0" ?>
<xliff version="1.1" xmlns="urn:oasis:names:tc:xliff:document:1.1">
<file ori... | polosa</target>
</trans-unit>
<trans-unit id="2" approved="no">
<source>verb</source>
<target state="needs-review-translation">lediri</target>
</trans-unit>'''
pofile | = self.xliff2po(minixlf)
assert pofile.translate("nonsense") == "matlhapolosa"
assert pofile.translate("verb") == "lediri"
assert pofile.translate("book") is None
assert pofile.translate("bla") is None
assert headerless_len(pofile.units) == 3
#TODO: decide if this one sho... |
openstack/keystone | keystone/common/sql/migrations/versions/yoga/contract/e25ffa003242_initial.py | Python | apache-2.0 | 835 | 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 the License is distributed on... | F ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Initial no-op Yoga contract migration.
Revision ID: e25ffa003242
Revises: 27e647c0fad4
Create Date: 2022-01-21 00:00:00.000000
"""
# revision identifiers, used by Alembic.
... |
tum-i22/indistinguishability-obfuscation | obfusc8/test/test_bp.py | Python | apache-2.0 | 5,366 | 0.063362 | import unittest
from itertools import product
from obfusc8.circuit import *
from obfusc8.bp import *
#enable testing of 'private' module member functions, somewhat sloppy style but I prefer it to any alternative
from obfusc8.bp import _matrix2cycle
class TestBranchingProgram(unittest.TestCase):
def setUp(self):
... | h)):
test = list(test)
circuitResult = self.circuit.evaluate(test)
bpResult = self.bp.evaluate(test)
self.assertEqual(circuitResult, bpResult, 'Wrong evaluation on input %s. Was %s instead of %s'%(test, circuitResult, bpResult))
class TestPrecalculatedMappings(unittest.TestCase):
def setUp(self):
self.... | for id, perm in zip(range(len(self.id2permList)), self.id2permList):
correct = dot(dot(_ni2n(), dot(perm, _normalInv())), _ni2n())
mappedResult = self.id2permList[self.mappings[0][id]]
self.assertTrue((correct == mappedResult).all(), 'Mapping 0 not correct on input %s. Was %s instead of %s.'%(perm, mappedResul... |
harterj/moose | test/tests/fvkernels/mms/advective-outflow/test.py | Python | lgpl-2.1 | 7,075 | 0.005936 | import mms
import unittest
from mooseutils import fuzzyAbsoluteEqual
class TestOutflow(unittest.TestCase):
def test(self):
df1 = mms.run_spatial('advection-outflow.i', 7, y_pp=['L2u', 'L2v'])
fig = mms.ConvergencePlot(xlabel='Element Size ($h$)', ylabel='$L_2$ Error')
fig.plot(df1,
... | label=['L2u'],
marker='o',
| markersize=8,
num_fitted_points=3,
slope_precision=1)
fig.save('quick-limiter.png')
for label,value in fig.label_to_slope.items():
self.assertTrue(fuzzyAbsoluteEqual(value, 2., .05))
class KTLimitedCD(unittest.TestCase):
def test(self):
df1 =... |
mtekel/digitalmarketplace-buyer-frontend | app/main/suppliers.py | Python | mit | 2,705 | 0 | # coding=utf-8
from string import ascii_uppercase
import flask_featureflags
from app.main | import main
from flask import render_template, request
from app.helpers.search_helpers import get_template_data
from app import data_api_client
import re
try:
from urlparse import urlparse, parse_qs
except ImportError:
from urllib.parse import urlparse, parse_qs
def process_prefix(prefix):
if prefix == ... | efix):
return prefix[:1].upper()
return "A" # default
def process_page(page):
reg = "^[1-9]{1}$" # valid page
if re.search(reg, page):
return page
return "1" # default
def is_alpha(character):
reg = "^[A-Za-z]{1}$" # valid prefix
return re.search(reg, character)
def par... |
openstack/sahara-dashboard | sahara_dashboard/test/integration_tests/tests/test_sahara_image_registry.py | Python | apache-2.0 | 2,572 | 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 re | quired 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 i | mplied. See the
# License for the specific language governing permissions and limitations
# under the License.
from openstack_dashboard.test.integration_tests import helpers
from openstack_dashboard.test.integration_tests.regions import messages
from sahara_dashboard.test.integration_tests.helpers import Sahara... |
westerncapelabs/django-wcl-skel | {{cookiecutter.repo_name}}/{{cookiecutter.project_name}}/urls.py | Python | bsd-3-clause | 536 | 0.001866 | import os
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.site.site_header = os.environ.get('{{cookiecutter.env_prefix}}_TITLE', '{{cookiecutter.project_name}} Admin')
urlpatterns | = patterns(
'',
url(r'^admin/', include(admin.site.urls)),
url(r'^api/auth/',
include('rest_framework.urls', namesp | ace='rest_framework')),
url(r'^api/token-auth/',
'rest_framework.authtoken.views.obtain_auth_token'),
url(r'^', include('{{cookiecutter.app_name}}.urls')),
)
|
kret0s/gnuhealth-live | tryton/server/trytond-3.8.3/trytond/modules/account_invoice_stock/stock.py | Python | gpl-3.0 | 1,091 | 0.001833 | # This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
from trytond.model import fields
from trytond.pool import Pool, PoolMeta
__all__ = [' | StockMove']
__metaclass__ = PoolMeta
class StockMove:
__name__ = 'stock.move'
invoice_lines = fields.Many2Many('account.invoice.line-stock.move',
'stock_move', 'invoice_line', 'Invoice Lines')
@property
def invoiced_quantity(self):
'The quantity from linked invoice lines in move unit'... | ice_line in self.invoice_lines:
quantity += Uom.compute_qty(invoice_line.unit,
invoice_line.quantity, self.uom)
return quantity
@classmethod
def copy(cls, moves, default=None):
if default is None:
default = {}
else:
default = default.c... |
spencerahill/aospy-obj-lib | aospy_user/calcs/gms.py | Python | apache-2.0 | 4,514 | 0 | """Gross moist stability-related quantities."""
from aospy.constants import c_p, grav, L_v
from aospy.utils.vertcoord import to_pascal
from indiff.deriv import EtaCenDeriv, CenDeriv
import numpy as np
from .. import PLEVEL_STR
from . import horiz_divg, vert_divg
from .thermo import dse, mse, fmse
def field_vert_int_... | x(horiz_divg(u, v, radius, dp), dp)
def vert_divg_vert_int_max(omega, p, dp):
"""Maximum magnitude of integral from surface up of vertical divergence."""
return field_vert_int_max(vert_divg(omega, p, dp), dp)
def gms_like_ratio(weights, tracer, dp) | :
"""Compute ratio of integrals in the style of gross moist stability."""
# Integrate weights over lower tropospheric layer
dp = to_pascal(dp)
denominator = field_vert_int_max(weights, dp)
# Integrate tracer*weights over whole column and divide.
numerator = np.sum(weights*tracer*dp, axis=-3) / g... |
KGerring/RevealMe | data/tested.py | Python | mit | 6,442 | 0.0104 | from email import message_from_file
from pkg_resources import working_set as WS
import path
from pathlib import Path
from pkg_resources import *
from pkg_resources import DistInfoDistribution, Distribution
import distutils.dist
import pkg_resources
import dpath
import sys, os, re
from distutils.errors import *
from dis... | r:
items = line.split(',')
record.add(items)
file_dict['RECORD']= record
else:
file_dict[file.name] = None
return file_dict
| |
Hackplayers/Empire-mod-Hpys-tests | lib/modules/python/collection/osx/prompt.py | Python | bsd-3-clause | 3,830 | 0.006005 | class Module:
def __init__(self, mainMenu, params=[]):
# metadata info about the module, not modified during runtime
self.info = {
# name for the module that will appear in module menus
'Name': 'Prompt',
# list of one or more authors for the module
... | eeds administrative privileges
'NeedsAdmin' : False,
# True if the method doesn't touch disk/is reasonably opsec safe
'OpsecSafe' : False,
# the module language
'Language' : 'python',
# the minimum language version needed
'MinLanguag... | omments': [
"https://github.com/fuzzynop/FiveOnceInYourLife"
]
}
# any options needed by the module, settable during runtime
self.options = {
# format:
# value_name : {description, required, default_value}
'Agent' : {
... |
sunweaver/ganetimgr | apply/migrations/0005_add_application_network_field.py | Python | gpl-3.0 | 8,911 | 0.008753 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'InstanceApplication.network'
db.add_column('apply_instanceapplication', 'network', sel... | ory': ('django.db.models.fields.IntegerField', [], {}),
'network': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['ganeti.Network']", 'null': 'True', 'blank': 'True'}),
'operating_system': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'organization... | s.fields.related.ForeignKey', [], {'to': "orm['apply.Organization']"}),
'status': ('django.db.models.fields.IntegerField', [], {}),
'vcpus': ('django.db.models.fields.IntegerField', [], {})
},
'apply.organization': {
'Meta': {'object_name': 'Organization'},
... |
hydratk/hydratk | src/hydratk/lib/install/command.py | Python | bsd-3-clause | 6,457 | 0.004337 | # -*- coding: utf-8 -*
"""HydraTK installation commands
.. module:: lib.install.command
:platform: Unix
:synopsis: HydraTK installation commands
.. moduleauthor:: Petr Rašek <bowman@hydratk.org>
"""
from subprocess import call, Popen, PIPE
from os import path, environ
from sys import exit
from hydratk.lib.syst... |
dst (str): destination path
Returns:
none
"""
create_dir(dst)
print ('Copying file {0} to {1}'.format(src, dst))
cmd = 'cp {0} {1}'.format(src, dst)
result, _, err = shell_exec(cmd, True)
if (result != 0):
print('Failed to copy {0} to {1}'.format(src, dst))
... | ile
Args:
src (str): source path
dst (str): destination path
Returns:
none
"""
print('Moving file {0} to {1}'.format(src, dst))
cmd = 'mv {0} {1}'.format(src, dst)
result, _, err = shell_exec(cmd, True)
if (result != 0):
print('Failed to move {0} to {1}'.form... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.