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 |
|---|---|---|---|---|---|---|---|---|
raeeschachar/edx-e2e-mirror | regression/pages/studio/logout_studio.py | Python | agpl-3.0 | 384 | 0 | """
Logout Page for Studio
"""
from bok_choy.page_object import PageObject
from regression.pages.s | tudio import BASE_URL
class StudioLogout(PageObject):
"""
Logged Out Page for Studio
"""
url = BASE_URL
d | ef is_browser_on_page(self):
"""
Checks if we are on the correct page
"""
return self.q(css='.wrapper-text-welcome').present
|
flyingfish007/tempest | tempest/scenario/test_network_basic_ops.py | Python | apache-2.0 | 32,963 | 0 | # Copyright 2012 OpenStack Foundation
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# 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
#
# ht... | et_resources
from tempest import test
CONF = config.CONF
LOG = logging.getLogger(__name__)
Floating_IP_tuple = collections.namedtuple('Floating_IP_tuple',
['floating_ip', 'server'])
class TestNetworkBasicOps(manager.NetworkScenarioTest):
"""
This smok | e test suite assumes that Nova has been configured to
boot VM's with Neutron-managed networking, and attempts to
verify network connectivity as follows:
There are presumed to be two types of networks: tenant and
public. A tenant network may or may not be reachable from the
Tempest host. A publ... |
1tush/reviewboard | reviewboard/settings.py | Python | mit | 12,734 | 0.000393 | # Django settings for reviewboard project.
from __future__ import unicode_literals
import os
import re
import sys
import djblets
from django.core.urlresolvers import reverse
# Can't import django.utils.translation yet
_ = lambda s: s
DEBUG = True
ADMINS = (
('Example Joe', '[email protected]')
)
MANAGERS =... | s
# them to the user's time zone in templates and forms.
USE_TZ = True
# Local time zone for this installation. All choices can be found here:
# http://www.postgresql.org/docs/8.1/static/datetime-keywords.html#DATETIME-TIMEZONE-SET-TABLE
# When USE_TZ is enabled, this is used as the default time zone for datetime
# ob... | und here:
# http://www.w3.org/TR/REC-html40/struct/dirlang.html#langcodes
# http://blogs.law.harvard.edu/tech/stories/storyReader$15
LANGUAGE_CODE = 'en-us'
# This should match the ID of the Site object in the database. This is used to
# figure out URLs to stick in e-mails and related pages.
SITE_ID = 1
# The prefix... |
luiscberrocal/homeworkpal | homeworkpal_project/employee/views.py | Python | mit | 3,567 | 0.001962 | from braces.views import LoginRequiredMixin
from django.contrib.auth.models import User, Group
from django.shortcuts import render
# Create your views here.
from django.views.generic import ListView, DetailView, CreateView, UpdateView
from rest_framework import viewsets
from employee.forms import CoachingSessionForm
f... | joined')
serializer_class = UserSerializer
class GroupViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows groups to be viewed or edited.
"""
queryset = Group.objects.all()
serializer_class = GroupSerializer
class EmployeeListView(LoginRequiredMixin, ListView):
model = Employee
... | def get_queryset(self):
qs = Employee.objects.from_group(self.kwargs['group_slug'])
return qs
class EmployeeProjectsView(LoginRequiredMixin, DetailView):
model = Employee
context_object_name = 'employee'
template_name = 'employee/employee_projects.html'
class EmployeeGoalsView(LoginRequi... |
gthank/pytips | docs/source/conf.py | Python | isc | 7,815 | 0.00755 | # -*- coding: utf-8 -*-
#
# PyTips documentation build configuration file, created by
# sphinx-quickstart on Mon Dec 26 20:55:10 2011.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All ... | iles (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'PyTipsdoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The fon | t size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'PyTips.tex', u'PyTips D... |
lento/cortex | python/IECoreMaya/VectorParameterUI.py | Python | bsd-3-clause | 4,276 | 0.029467 | ##########################################################################
#
# Copyright (c) 2010, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistribu... | for i in range(0, self.__dim) :
self.__fields.append(
self.__fieldType()(
value = parameter.getTypedValue()[i]
)
)
maya.cmds.setParent("..")
self.replace( self.node(), self.parameter )
def replace( self, node, parameter ) :
IECoreMaya.ParameterUI.replace( self, node, parameter )
plug = ... | nectControl( self.__fields[i], childPlugName )
self._addPopupMenu( parentUI = self.__fields[i], attributeName = childPlugName )
def __fieldType( self ):
if self.parameter.isInstanceOf( IECore.TypeId.V2iParameter ) or self.parameter.isInstanceOf( IECore.TypeId.V3iParameter ):
return maya.cmds.intField
else:... |
ipapusha/amnet | tests/test_smt.py | Python | bsd-3-clause | 32,730 | 0.002383 | import numpy as np
import amnet
import z3
from numpy.linalg import norm
import sys
import unittest
import itertools
VISUALIZE = True # output graphviz drawings
if VISUALIZE:
import amnet.vis
class TestSmt(unittest.TestCase):
@classmethod
def setUpClass(cls):
print 'Setting up test floats.'
... | inspace(-5., 5., 10)),
axis=0
)
cls.floatvals2 = np.concatenate(
(np.linspace(-5., 5., 3), np.linspace(-.5, .5, 2)),
axis=0
)
cls.floatvals3 = np.linspace(-5., 5., 3)
cls.FPTOL = 1e-8
# set up global z3 parameters
# parameters ... | case_split', 5)
#z3.set_param('smt.relevancy', 2)
def validate_outputs(self, phi, onvals, true_f=None, verbose=False):
# encode phi using default context and solver
enc = amnet.smt.SmtEncoder(phi=phi, solver=None)
# tap the input and output vars
invar = enc.var_of_input()
... |
harikishen/addons-server | src/olympia/stats/tasks.py | Python | bsd-3-clause | 12,766 | 0 | import datetime
import httplib2
import itertools
from django.conf import settings
from django.db import connection
from django.db.models import Sum, Max
from apiclient.discovery import build
from elasticsearch.helpers import bulk_index
from oauth2client.client import OAuth2Credentials
import olympia.core.logger
from... | nloads=var['sum']))
def get_profile_id(service, domain):
"""
Fetch the profile ID for the given domain.
"""
accounts = service.management().accounts().list().execute()
account_ids = [a['id'] for a in acc | ounts.get('items', ())]
for account_id in account_ids:
webproperties = service.management().webproperties().list(
accountId=account_id).execute()
webproperty_ids = [p['id'] for p in webproperties.get('items', ())]
for webproperty_id in webproperty_ids:
profiles = serv... |
queria/my-tempest | tempest/services/data_processing/v1_1/client.py | Python | apache-2.0 | 11,290 | 0 | # Copyright (c) 2013 Mirantis 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 ... | ter template."""
uri = 'cluster-templates/%s' % tmpl_id
return self._request_check_and_parse_resp(self.get,
uri, 200, 'cluster_template')
def create_cluster_template(self, name, | plugin_name, hadoop_version,
node_groups, cluster_configs=None,
**kwargs):
"""Creates cluster template with specified params.
It supports passing additional params using kwargs and returns created
object.
"""
uri =... |
yavdr/yavdr-ansible | plugins/callbacks/auto_tags.py | Python | gpl-3.0 | 1,950 | 0.004615 | """
This module implements an Ansible plugin that is triggered at the start of a playbook.
The plugin dynamically generates a tag for each role. Each tag has the same name as its role.
The advantage of this is that it saves you some boilerplate, because you don't have to wrap
all tasks of a role in an additional block... | llowing two lines to your `ansible.cfg` file:
callback_plugins = plugins/callbacks
callback_whitelist = auto_tags
"""
from __future__ import pri | nt_function
from ansible.plugins.callback import CallbackBase
class CallbackModule(CallbackBase):
"""
Ansible supports several types of plugins. We are using the *callback* type here, since
it seemed the best choice for our use case, because it allows you to hook into the start
of a playbook.
"""
... |
srlang/void-tool | void.py | Python | gpl-2.0 | 1,552 | 0.00451 | #
# void.py
# Python-written helper tool to Void Linux's xbps-* tools
# Written for personal ease of use, not robustness.
#
# Copyright (c) 2014Sean R. Lang <[email protected]>
#
from subprocess import call # for external shell ca | lls
from sys import argv # for command line arguments
##########################################################################
# xbps subcommands
def void_install(args):
'''Install the specified package atoms.'''
pass
def void_remove(args):
'''Remove the specified package atoms.'''
pass
... | void_query(args):
'''Perform a search operation for a package atom'''
pass
def find_command(cmd):
if "-I" in cmd:
return void_install
elif "-Q" in cmd:
return void_query
elif "-R" in cmd:
return void_remove
else:
return usage()
###################################... |
SylvainTakerkart/vobi_one | lib/python2.5/site-packages/oidata/oisession_preprocesses.py | Python | gpl-3.0 | 15,602 | 0.016152 | # Author: Philippe Katz <[email protected]>,
# Flavien Garcia <[email protected]>,
# Sylvain Takerkart <[email protected]>
# License: BSD Style.
try:
from neuroProcesses import *
except:
print 'Impossible to import neurProcesses'
def print_fonc(string,context=None):... | If used in BrainVISA graphical mode
def warning_fonc(string,context=None):
"""Warning function for BrainVISA
Warning function for BrainVISA.
Print :
* a string in bash when context is None (for a use in bash mode)
* a warning message in BrainVISA user interface when context is BrainVISA context
... | int
context : brainvisa context, optional
Can be None for a use in bash mode or the BrainVISA context for a use in BrainVISA graphical mode
"""
if context is None: # If no context, for a use in BrainVISA shell
print string
else:
context.warning(_t_(string)) # If used in BrainVISA... |
Itxaka/st2 | st2actions/tests/unit/test_paramiko_ssh.py | Python | apache-2.0 | 9,657 | 0.000207 | # 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 use ... | t.org',
'look_for_keys': False,
'key_filename': 'id_rsa',
'port': 22}
mock.client.connect.assert_called_once_with(**expected_conn)
@patch('paramiko.SSHClient', Mock)
def test_create_without_creden | tials(self):
"""
Initialize object with no credentials.
Just to have better coverage, initialize the object
without 'password' neither 'key'.
"""
conn_params = {'hostname': 'dummy.host.org',
'username': 'ubuntu'}
mock = ParamikoSSHClient(**... |
Samweli/inasafe | safe/utilities/test/test_gis.py | Python | gpl-3.0 | 13,312 | 0.000075 | # coding=utf-8
"""Test for GIS utilities functions."""
import unittest
import numpy
from os.path import join
# noinspection PyUnresolvedReferences
import qgis # pylint: disable=unused-import
from PyQt4.QtCore import QVariant
from os.path import join
from safe.utilities.gis import (
layer_attribute_names,
is_... | 'resolution': (
0.0083333333333333003,
| 0.0083333333333333003)}
# Verify relevant metada is ok
H = read_layer(hazard_path)
E = read_layer(exposure_path)
hazard_bbox = H.get_bounding_box()
assert numpy.allclose(hazard_bbox, haz_metadata['bounding_box'],
rtol=1.0e-12, atol=1.0e-12)
... |
csparpa/django-httpbin | django_httpbin/urls.py | Python | mit | 148 | 0.006757 | from django.conf.urls import patterns, include
urlpatterns = | patterns('',
(r'^django-httpbin', include('django_httpbin.httpbin | .endpoints')),
)
|
bevpy/pcvilag-dl | pcvilag-dl.py | Python | gpl-3.0 | 5,648 | 0.010979 | #!/usr/bin/env python
# coding: utf-8
"""
pcvilag.muskatli.hu downloader
Copyright (C) 2015 Gyulai Gergő
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 yo... |
try:
urllib.urlretrieve(element,path+str(i)+"."+element.split("/")[-1].split(".")[-1])
| e=None
except IOError,e:
print "Error: This file is no longer available"
i-=1
if e==None:
print "DONE"
i+=1
global PICS
PICS = i-1
print "ALL PICTURES DOWNLOADED"
#call bash/cmd with ImageMagick convert method
def convertToPDF(path,u_nam... |
google/makani | analysis/system_design/site.py | Python | apache-2.0 | 3,837 | 0.004431 | # Copyright 2020 Makani Technologies LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | [0.0, 10.0, 20.0],
'probability': [0.2, 0.6, 0.2]
}
else:
self._velocity_distribution = velocity_distribution
if shear_distribution is None:
self._shear_distribution = {
' | shear_coefficient': [0.0, 0.1, 0.2],
'probability': [0.0, 0.9, 0.1]
}
else:
self._shear_distribution = shear_distribution
self._capital_costs = 1.0 if capital_costs is None else capital_costs
@property
def site_name(self):
return self._site_name
@property
def velocity_distri... |
ranog/coursera_python | buzz.py | Python | gpl-3.0 | 155 | 0 | #!/usr/bin/env python3
numero = i | nt(input("Digite um número inteiro: "))
resto = numero % 5
if(resto == 0):
print( | "Buzz")
else:
print(numero)
|
araisrobo/linuxcnc | src/emc/usr_intf/axis/scripts/linuxcnctop.py | Python | lgpl-2.1 | 7,389 | 0.012451 | #!/usr/bin/env python2
# This is a component of AXIS, a front-end for linuxcnc
# Copyright 2004, 2005, 2006 Jeff Epler <[email protected]>
# and Chris Radek <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GN... | pt Tcl | Error:
anchor_point = None
t.delete("0.0", "end")
first = True
for k in dir(s):
if k.startswith("_"): continue
if maps.has_key(k) and maps[k] == None: continue
v = getattr(s, k)
if maps.has_key(k):
m = maps[k]
... |
rpufky/trafficserver | tests/tools/sessionvalidation/session.py | Python | apache-2.0 | 1,826 | 0.001643 | '''
'''
# 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");... | oftware
# distributed under the Lic | ense 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 and
# limitations under the License.
import sessionvalidation.transaction as transaction
class Session(object):
''' Session encap... |
dbjohnson/advent-of-code | solutions/day18/solution.py | Python | mit | 1,625 | 0.001231 | class Automata(object):
def __init__(self, row, col, state):
self.row = row
self.col = col
self.init_state = state
self.state = state
self.neighbors = []
def connect(self, neighbor):
self.neighbors.append(neighbor)
def calc_next_state(self):
on_count... | duce(lambda x, y: x + y, world)
for step in xrange(1 | 00):
for a in everyone:
a.calc_next_state()
for a in everyone:
a.update()
print 'part 1', sum(1 if a.state else 0 for a in everyone)
working = []
for a in everyone:
if a.row in (0, 99) and a.col in (0, 99):
a.state = True
else:
a.reset()
working.append(a)
for s... |
JeremyGrosser/quisk | src/softrock/hardware_usb.py | Python | gpl-2.0 | 8,270 | 0.013785 | # Please do not change this hardware control module for Quisk.
# It provides USB control of SoftRock hardware.
import struct, threading, time, traceback, math
from quisk_hardware_model import Hardware as BaseHardware
import _quisk as QS
# All USB access is through control transfers using pyusb.
# byte_array = ... | # Since we're starting with max hsdiv, this can only happen if
# freq was larger than we can handle
if n1 > 128:
c | ontinue
if dco < SI570_MIN_DCO or dco > SI570_MAX_DCO:
# This really shouldn't happen
continue
if not dco_new or dco < dco_new:
dco_new = dco
hsdiv_new = hsdiv
n1_new = n1
if not dco_new:
# For some reason, we were unable to calculate a frequency.
# Pr... |
hsdistefa/MarketQuotes | symbol_downloader.py | Python | mit | 1,466 | 0.002729 | import urllib.request
import json
# This URL returns all stock tickers in JSON format
TICKER_URL = 'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.industry%20where%2 | 0id%20in%20%28select%20industr | y.id%20from%20yahoo.finance.sectors%29&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys'
OUTPUT_FILE = 'symbols.txt'
class TickerDownloader:
def get_symbols(self):
self.download_url()
self.parse()
def download_url(self, url=TICKER_URL):
request = urllib.request.Request... |
wtsi-hgi/irobot | irobot/precache/db/_dbi.py | Python | gpl-3.0 | 6,897 | 0.00203 | """
Copyright (c) 2017 Genome Research Ltd.
Author: Christopher Harrison <[email protected]>
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 ... | ul, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
Public License for more details.
You should have received a copy of the GNU General Public License along
with this | program. If not, see <http://www.gnu.org/licenses/>.
"""
from collections import OrderedDict
from inspect import Parameter, signature
from typing import Any, Dict, Iterator, List, Optional, Sequence, Tuple, Type, Union
import apsw
from irobot.precache.db._types import Adaptor, Convertor, SQLite
from irobot.precache.... |
cwebber314/pyqt_db | setup.py | Python | mit | 1,320 | 0.019697 | """
To build cx_Freeze executable:
python setup.py bdist_msi
"""
from cx_Freeze import setup, Executable
# Dependencies are automatically detected, but it might need
# fine tuning.
buildOptions = dict(packages = [], excludes = [])
import PyQt5
from glob import glob
import sys, os
import os.path as osp
base = 'Wi... | ['images\logo.png']),
#('i | mages', ['images\shannon.png']),
],
options = {
'py2exe': {
'bundle_files': 1,
'includes': ['sip', 'PyQt5.QtCore'],
}
},
executables = executables)
|
leighpauls/k2cro4 | native_client/tests/gdb/print_symbol.py | Python | bsd-3-clause | 694 | 0.012968 | # -*- python -*-
# Copyright (c) 2012 The Native Client 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 gdb_test import AssertEquals
import gdb_test
d | ef test(gdb):
gdb.Command('break set_global_var')
AssertEquals(gdb.ResumeCommand('continue')['reason'], 'breakpoint-hit')
AssertEquals(gdb.Eval('global_var'), '2')
AssertEquals(gdb.Eval('arg'), '1')
AssertEquals(gdb.ResumeCommand('finish')['reason'], 'func | tion-finished')
AssertEquals(gdb.Eval('global_var'), '1')
AssertEquals(gdb.Eval('local_var'), '3')
gdb.Quit()
if __name__ == '__main__':
gdb_test.RunTest(test, 'print_symbol')
|
plumgrid/plumgrid-nova | nova/ipv6/__init__.py | Python | apache-2.0 | 698 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2011 OpenStack Foundati | on
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may ob | tain
# 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 th... |
mozilla/popcorn_maker | popcorn_gallery/users/urls.py | Python | bsd-3-clause | 294 | 0 | from django.con | f.urls.defaults import patterns, url
urlpatterns | = patterns(
'popcorn_gallery.users.views',
url(r'^edit/$', 'edit', name='users_edit'),
url(r'^delete/$', 'delete_profile', name='users_delete'),
url(r'^(?P<username>[\w-]+)/$', 'profile', name='users_profile'),
)
|
jr-garcia/Engendro3D | e3d/gui/FontRendering/japanese_range.py | Python | mit | 6,858 | 0 | # coding=utf-8
jchars = u'。々ゝヽゞヾーぁァあアぃィいイぅゥうウヴぇェえエぉォおオヵかカがガきキぎギくクぐグヶけケげゲこコごゴさサざザしシじジすスず' \
u'ズせセぜゼそソぞゾたタだダちチぢヂっッつツづヅてテでデとトどドなナにニぬヌねネのノはハばバぱパひヒびビぴピふフぶブぷプへ' \
u'ヘべベぺペほホぼボぽポまマみミむムめメもモゃャやヤゅュゆユょョよヨらラりリるルれレろロゎヮわワゐヰゑヱをヲんン一丁七万-' \
u'下不与丑且世丘丙両並中丸丹主久乏乗乙九乱乳乾亀了予争事二互五井亜亡交亥亨享-亭人仁今介仏仕他付仙代-以仮仰仲件任企伊伏-休' \
... | 斥断新方施旅旋族旗既日旧-早旬昆昇昌明易昔星映春昨昭是昼時晩普景晴晶暁暇暑暖暗暦暫暮暴' \
u'曇曜曲更書曹替最月有服朕朗望朝期木未-札朱朴机朽杉材村束条来杯東松板析林枚果枝枠枢枯架柄某染柔柱柳査栄栓校株核根格栽桃案桑' \
u'桜桟梅 | 械棄棋棒棚棟森棺植検業極楼楽概構様槽標模権横樹橋機欄欠次欧欲欺款歌歓止正武歩歯歳歴死殉-残殖殴段殺殻殿母毎毒比毛氏民' \
u'気水氷永汁求汎汗汚江池決汽沈沖没沢河沸油治沼沿況泉泊泌法泡-泣泥注泰泳洋洗洞津洪活派流浄浅浜浦浪浮浴海浸消涙涯液涼淑淡深混' \
u'添清渇-渉渋渓減渡渦温測港湖湯湾-満源準溝溶滅滋滑滝滞滴漁漂漆漏演漠漢漫漬漸潔潜潟潤潮澄激濁濃濫濯瀬火灯灰災炉炊炎炭点為烈' \
u'無焦然焼煙照煩煮熟熱燃燥爆爵父片版牙牛牧物牲特犠犬犯状狂狩独狭猛猟猪猫献猶猿獄獣獲玄率玉王珍珠班現球理琴環璽瓶甘甚生産用田' \
u'-申男町画界畑畔留畜畝略番異畳疎疑疫疲... |
enormandeau/ngs_genotyping | scripts/10_genotype_from_blast_results.py | Python | gpl-3.0 | 2,437 | 0.004514 | #!/usr/bi | n/python
"""Use files with frequency counts of blasts on possible alleles (see format
below) to genotype individuals.
Usage:
genotype_from_blast_results.py file_list threshold_file output_file
- file_list is a file containing the path to the individual summary file | s. the
file_list format is as follows:
individual_summary/MID100-02_cleaned_aligned.fasta.blasts_summary
individual_summary/MID100-03_cleaned_aligned.fasta.blasts_summary
individual_summary/MID100-04_cleaned_aligned.fasta.blasts_summary
...
individual_summary/MID102-03_cleaned_aligned.fasta.blasts_summary
- The indiv... |
idan/oauthlib | oauthlib/openid/connect/core/endpoints/userinfo.py | Python | bsd-3-clause | 3,847 | 0.00052 | """
oauthlib.openid.connect.core.endpoints.userinfo
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This module is an implementation of userinfo endpoint.
"""
import json
import logging
from oauthlib.common import Request
from oauthlib.oauth2.rfc6749 import errors
| from oauthlib.oauth2.rfc6749.endpoints.base import (
BaseEndpoint, catch_errors_and_unavailability,
)
| from oauthlib.oauth2.rfc6749.tokens import BearerToken
log = logging.getLogger(__name__)
class UserInfoEndpoint(BaseEndpoint):
"""Authorizes access to userinfo resource.
"""
def __init__(self, request_validator):
self.bearer = BearerToken(request_validator, None, None, None)
self.request_... |
GeoCat/QGIS | python/plugins/processing/algs/qgis/DensifyGeometriesInterval.py | Python | gpl-2.0 | 2,510 | 0.000797 | # -*- coding: utf-8 -*-
"""
***************************************************************************
DensifyGeometriesInterval.py by Anita Graser, Dec 2012
based on DensifyGeometries.py
---------------------
Date : October 2012
Copyright : (C) 2012 by Victor Olaya
... | (C) 2012, Anita Graser'
# This will get replaced with a git S | HA1 when you do a git archive
__revision__ = '$Format:%H$'
from qgis.core import (QgsProcessingParameterNumber)
from processing.algs.qgis.QgisAlgorithm import QgisFeatureBasedAlgorithm
class DensifyGeometriesInterval(QgisFeatureBasedAlgorithm):
INTERVAL = 'INTERVAL'
def group(self):
return self.t... |
solent-eng/solent | solent/eng/engine.py | Python | lgpl-3.0 | 20,491 | 0.003416 | # // license
# Copyright 2016, Free Software Foundation.
#
# This file is part of Solent.
#
# Solent 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)
... | #
self.mempool = Mempool()
self.clock = Clock()
self.action_pool = A | ctionPool()
self.sid_to_metasock = od()
self.spins = od()
#
self.activity = Activity()
self.b_debug_eloop = False
self.sid_counter = 0
self.default_timeout = 0.2
self.b_nodelay = False
#
self.cb_ms_close = None
self.cs_ms_close = Cs... |
taschini/morepath | morepath/tests/test_security.py | Python | bsd-3-clause | 16,352 | 0 | # -*- coding: utf-8 -*-
import morepath
from morepath.request import Response
from morepath.authentication import Identity, NO_IDENTITY
from .fixtures import identity_policy
import base64
import json
from webtest import TestApp as Client
try:
from cookielib import CookieJar
except ImportError:
from http.cookiej... | path.App):
pass
class Model(object):
def __init__(self, id):
self.id = id
class Permission(object):
pass
@app.path(model=Model, path='{id}',
variables=lambda mod | el: {'id': model.id})
def get_model(id):
return Model(id)
@app.permission_rule(model=Model, permission=Permission, identity=None)
def get_permission(identity, model, permission):
if model.id == 'foo':
return True
else:
return False
@app.view(model=Model,... |
TooAngel/sensorviewer | tests/tester_tests.py | Python | apache-2.0 | 588 | 0.001701 | i | mport tester
import unittest
from mock import Mock, patch, Magi | cMock
class WorkerTestCase(unittest.TestCase):
@patch('tester.requests')
def test_post_error(self, requests):
tester.post()
self.assertTrue(requests.post.called)
@patch('tester.requests')
def test_get_error(self, requests):
tester.get()
self.assertTrue(requests.get.ca... |
Jozhogg/iris | lib/iris/tests/unit/analysis/maths/test_add.py | Python | lgpl-3.0 | 1,586 | 0 | # (C) British Crown Copyright 2014, Met Office
#
# This file is part of Iris.
#
# Iris is free software: you can redistribute it and/or mo | dify 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 version.
#
# Iris is distributed | in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Iris. If n... |
Alwnikrotikz/marinemap | lingcod/layers/migrations/0003_auto__add_field_privatelayerlist_name__add_field_privatelayerlist_prio.py | Python | bsd-3-clause | 5,965 | 0.008215 | # 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 'PrivateLayerList.name'
db.add_column('layers_privatelayerlist', 'name', self.gf('django.db... | fields.FloatField', [], {'default': '0.0'}),
'sharing_groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['au | th.Group']", 'null': 'True', 'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'layers.publiclayerlist': {
'Meta': {'object_name': 'PublicLayerList'},
'active': ('django.db.models.fields.BooleanField', [], {'d... |
yeleman/snisi | snisi_reprohealth/models/__init__.py | Python | mit | 540 | 0.007407 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4 nu
from __future__ import (unicode_literals, absolute_import,
divisio | n, print_function)
from snisi_reprohealth.models.PFActivities import (PFActiv | itiesR, AggPFActivitiesR)
# from snisi_reprohealth.models.ChildrenMortality import (ChildrenDeathR, AggChildrenDeathR)
# from snisi_reprohealth.models.MaternalMortality import (MaternalDeathR, AggMaternalDeathR)
# from snisi_reprohealth.models.Commodities import (RHProductsR, AggRHProductsR)
|
Auzzy/pyinq | setup.py | Python | isc | 915 | 0.002186 | from setuptools import setup
setup(
name='PyInq',
version='0.2.1',
author='Austin Noto-Moniz',
author_email='[email protected]',
url='http://auzzy.github.io/pyinq/',
packages=['pyinq', 'pyinq.asserts', 'pyinq.tags', 'pyinq.printers', 'pyinq.printers.html', 'pyinq.printers.cli', 'pyinq.printe... | rogramming Language :: Python',
'Programming Language :: Python :: 2.7',
| 'Topic :: Software Development :: Testing'
]
)
|
leviroth/praw | praw/models/inbox.py | Python | bsd-2-clause | 9,119 | 0 | """Provide the Front class."""
from ..const import API_PATH
from .listing.generator import ListingGenerator
from .base import PRAWBase
from .util import stream_generator
class Inbox(PRAWBase):
"""Inbox is a Listing class that represents the Inbox."""
def all(self, **generator_kwargs):
"""Return a Lis... | x message as uncollapsed.
:param items: A list containing instances of :class:`.Message`.
Requests are batched at 25 items (reddit limit).
For example, to uncollapse all unread Messages, try:
.. code:: python
from praw.models import Message
unread_messages = ... | tance(item, Message):
unread_messages.append(item)
reddit.inbox.uncollapse(unread_messages)
.. seealso::
:meth:`.Message.collapse`
"""
while items:
data = {"id": ",".join(x.fullname for x in items[:25])}
self._reddit.post(API_... |
ericmjl/bokeh | bokeh/io/__init__.py | Python | bsd-3-clause | 2,128 | 0.011748 | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2020, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-------------------------------------------------------------------... | '''
#-----------------------------------------------------------------------------
# Boilerplate
#-----------------------------------------------------------------------------
import logging # isort:skip
log = logging.getLogger(__name__)
#-----------------------------------------------------------------------------
#... | --------------------------------
# Bokeh imports
from .doc import curdoc
from .export import export_png, export_svgs
from .notebook import install_jupyter_hooks, install_notebook_hook, push_notebook
from .output import output_file, output_notebook, reset_output
from .saving import save
from .showing import show
#----... |
cosmicAsymmetry/zulip | analytics/tests/test_views.py | Python | apache-2.0 | 2,009 | 0.006471 | from django.utils.timezone import get_fixed_timezone
from zerver.lib.test_classes import ZulipTestCase
from analytics.lib.counts import CountStat
from analytics.views import time_range
from datetime import datetime, timedelta
class TestTimeRange(ZulipTestCase):
def test_time_range(self):
# type: () -> No... | +DAY, CountStat.DAY, None),
[ce | iling_day, ceiling_day+DAY])
# test min_length
self.assertEqual(time_range(ceiling_hour, ceiling_hour+HOUR, CountStat.HOUR, 4),
[ceiling_hour-2*HOUR, ceiling_hour-HOUR, ceiling_hour, ceiling_hour+HOUR])
self.assertEqual(time_range(ceiling_day, ceiling_day+DAY, CountStat.... |
srslynow/legal-text-mining | bow_cnn.py | Python | gpl-3.0 | 2,108 | 0.005218 | from __future__ import print_function
import numpy as np
np.random.seed(1337) # for reproducibility
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_... | size = (3, 3)
X_train = np.load("train_data.npy")
y_train = np.load("train_label.npy")
X_test = np.load("test_data.npy")
y_test = np.load("test_label.npy")
X_train = X_train[..., np.newaxis]
X_test = X_te | st[..., np.newaxis]
samples = X_train.shape[0]
X_train = np.reshape(X_train, (samples, 100, 50))
samples = X_test.shape[0]
X_test = np.reshape(X_test, (samples, 100, 50))
X_train = X_train[..., np.newaxis]
X_test = X_test[..., np.newaxis]
X_train = X_train.astype('float32')
X_test = X_test.astype('float32... |
sergey-dryabzhinsky/dedupsqlfs | dedupsqlfs/app/mkfs.py | Python | mit | 11,069 | 0.004517 | # -*- coding: utf8 -*-
"""
@todo: Update argument parser options
"""
# Imports. {{{1
import sys
# Try to load the required modules from Python's standard library.
try:
import os
import argparse
from time import time
import hashlib
except ImportError as e:
msg = "Error: Failed to load one of the r... | which guarantees that data is written to disk immediately, because it slows down the file system too much (this means you might lose data when the mount point isn't cleanly unmounted).")
# Dynamically check for supported hashing algorithms.
msg = "Specify the hashing algorithm that will be used to recognize d... | nged on the fly."
hash_functions = list({}.fromkeys([h.lower() for h in hashlib.algorithms_available]).keys())
hash_functions.sort()
work_hash_funcs = set(hash_functions) & constants.WANTED_HASH_FUCTIONS
msg %= ', '.join('%r' % fun for fun in work_hash_funcs)
defHash = 'md5' # Hope it will be there ... |
matthewayne/evernote-sdk-python | sample/all_methods/findNoteCounts.py | Python | bsd-3-clause | 2,735 | 0.012066 | # Import the Evernote client
from evernote.api.client import EvernoteClient
# Import the Evernote note storetypes to get note datatypes
# to properly get note/tag counts (note filter)
import evernote.edam.notestore.ttypes as NoteStoreTypes
# Define access token either:
# Developer Tokens (https://dev.evernote.com/do... | m %s noteboo | ks" % len(note_counts.notebookCounts)
for notebook in note_counts.notebookCounts:
print " Notebook with GUID %s has %s note(s) that match the filter" % (notebook, note_counts.notebookCounts[notebook])
if note_counts.tagCounts != None:
print "Found results from %s tags" % len(note_counts.notebookCounts)
for tag... |
nginx/unit | test/unit/check/chroot.py | Python | apache-2.0 | 748 | 0 | import json
from unit.http import TestHTTP
from unit.option import option
http = TestHTTP() |
def che | ck_chroot():
available = option.available
resp = http.put(
url='/config',
sock_type='unix',
addr=option.temp_dir + '/control.unit.sock',
body=json.dumps(
{
"listeners": {"*:7080": {"pass": "routes"}},
"routes": [
{
... |
atizo/djangojames | djangojames/templatetags/truncate.py | Python | gpl-2.0 | 2,021 | 0.005443 | # -*- coding: utf-8 -*-
#
# ITerativ GmbH
# http://www.iterativ.ch/
#
# Copyright (c) 2012 ITerativ GmbH. All rights reserved.
#
# 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 ... | ing(value, arg):
"""
Truncates the string after a number of characters. It respects word boundaries and keeps newlines.
Argument: Number of characters.
"""
try:
length = int(arg)
except ValueError: # If the argument is not | a valid integer.
return value # Fail silently.
return truncate_chars(value, length)
truncatestring.is_safe = True |
bzamecnik/sms-tools | lectures/01-Introduction/plots-code/even-odd.py | Python | agpl-3.0 | 599 | 0.003339 | # matplotlib without any blocking GUI
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as | plt
import numpy as np
N = 500
k = 3
plt.figure(1)
s = np.exp(1j * 2 * np.pi * k / N * np.arange(-N / 2, N / 2))
plt.subplot(1, 2, 1)
plt.plot(np.arange(-N / 2, N / 2), np.real(s), lw=2)
plt.axvline(0, color='g', lw=2)
plt.axis([-N / 2, N / 2, -1, 1])
plt. | title('cosine (even)')
plt.subplot(1, 2, 2)
plt.plot(np.arange(-N / 2, N / 2), np.imag(s), lw=2)
plt.axvline(0, color='g', lw=2)
plt.axis([-N / 2, N / 2, -1, 1])
plt.title('sine (odd)')
plt.tight_layout()
plt.savefig('even-odd.png')
|
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/sympy/functions/special/tests/test_tensor_functions.py | Python | agpl-3.0 | 698 | 0.010029 | from sympy import symbols, Dij, LeviCivita
x, y = symbols('x,y')
def test_Dij():
assert Dij(1, 1) == 1
assert Dij(1, 2) == 0
assert Dij(x, x) == 1
assert Dij(x**2-y**2, x**2-y**2) == 1
def test_levicivita():
assert LeviCivita(1, 2, 3) == 1
assert LeviCivita(1, 3, 2) == -1
assert LeviCivit... | False)
assert LeviCivita(i, j, i) == 0
assert LeviCivita(1, i, i) == 0
assert LeviCivita(i, j, k).doit() == (j - i)*(k - i)*(k - j)/2
assert LeviCivita(1, 2, 3, 1) == 0
assert LeviCivita(4, 5, 1, 2, 3) == 1
asser | t LeviCivita(4, 5, 2, 1, 3) == -1
|
devinbalkind/eden | tests/unit_tests/modules/s3/s3gis/GeoJSONLayer.py | Python | mit | 812 | 0.025862 |
s3gis_tests = load_module("tests.unit_tests.modules.s3.s3gis")
def test_GeoJSONLayer():
s3gis_tests.layer_test(
db,
db.gis_layer_geojson,
dict(
name = "Test GeoJSON",
| description = "Test GeoJSON layer",
enabled = True,
created_on = datetime.datetime.now(),
modified_on = datetime.datetime.now(),
url = "test://test_ | GeoJSON",
),
"S3.gis.layers_geojson",
[
{
"marker_height": 34,
"marker_image": u"gis_marker.image.marker_red.png",
"marker_width": 20,
"name": u"Test GeoJSON",
"url": u"test://test_GeoJSON"
... |
koery/win-sublime | Data/Packages/Package Control/package_control/package_cleanup.py | Python | mit | 15,806 | 0.003416 | import threading
import os
import sublime
from .show_error import show_error
from .console_write import console_write
from .unicode import unicode_from_os
from .clear_directory import clear_directory, delete_directory, clean_old_files
from .automatic_upgrader import AutomaticUpgrader
from .package_manager import Pack... | em from another computer and the settings file
# being synced.
| if self.remove_orphaned and package_name not in self.original_installed_packages and package_file_exists(package_name, 'package-metadata.json'):
# Since Windows locks the .sublime-package files, we must
# do a dance where we disable the package first, which has
... |
mayl/dotfiles | t/setup.py | Python | gpl-3.0 | 346 | 0.00289 | t | ry:
from setuptools import setup
except:
from distutils.core import setup
setup( |
name='t',
version='1.2.0',
author='Steve Losh',
author_email='[email protected]',
url='http://bitbucket.org/sjl/t',
py_modules=['t'],
entry_points={
'console_scripts': [
't = t:_main',
],
},
)
|
eriksore/sdn | Old/OpenDaylight.py | Python | mit | 14,381 | 0.005285 | """
OpenDaylight REST API
Copyright 2013 The University of Wisconsin Board of Regents
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
... | der 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 and
limitations under the License.
Written by: Dale W. Carder, dwcarder@wi | sc.edu
Network Services Group
Division of Information Technology
University of Wisconsin at Madison
This material is based upon work supported by the National Science Foundation
under Grant No. 1247322.
"""
from __future__ import print_function
import json
import requests
from requests.auth import HTTPBasicAuth... |
sandeepkrjha/pgmpy | pgmpy/tests/test_sampling/test_continuous_sampling.py | Python | mit | 8,100 | 0.005556 | import unittest
import numpy as np
from pgmpy.factors.continuous import JointGaussianDistribution as JGD
from pgmpy.sampling import (HamiltonianMC as HMC, HamiltonianMCDA as HMCda, GradLogPDFGaussian, NoUTurnSampler as NUTS,
NoUTurnSamplerDA as NUTSda)
class TestHMCInference(unittest.Tes... | 10161 | )
samples = self.nuts_sampler.generate_sample(initial_pos=[-0.4, 1, 3.6], num_adapt=0, num_samples=10000)
samples_array = np.array([sample for sample in samples])
sample_covariance = np.cov(samples_array.T)
self.assertTrue(np.linalg.norm(sample_covariance - self.test_model.covariance) < ... |
alcemirfernandes/irobotgame | lib/data.py | Python | gpl-3.0 | 788 | 0.006345 | # I Robot? - a dancing robot game for pyweek
#
# Copyright: 2008 Hugo Ruscitti
# License: GPL 3
# Web: http://www.losersjuegos.com.ar
'''Simple data loader module.
Loads data files from the "data" directory shipped with a game.
Enhancing this to h | andle caching etc. is left as an exercise for the reader.
'''
import os
#data_py = os.path.abspath(os.path.dirname(__file__))
#data_dir = os.path.normpath(os.path.join(data_py, '..', 'data'))
data_dir = 'data'
def filepath(filename):
'''Determine the path to a file in the data directory.
'''
return os.pa... | os.path.join(data_dir, filename), mode)
|
zentralopensource/zentral | zentral/contrib/inventory/compliance_checks.py | Python | apache-2.0 | 5,942 | 0.003366 | import logging
import threading
import time
from django.utils.functional import cached_property, SimpleLazyObject
import jmespath
from zentral.core.compliance_checks import register_compliance_check_class
from zentral.core.compliance_checks.compliance_checks import BaseComplianceCheck
from zentral.core.compliance_check... | d", flat=True)
)
if not check_tag_set.intersection(machine_tag_set):
# tags mismatch
continue
# default to unknown status
status = Status.UNKNOWN
try:
result = jmespath_parsed_expr.search(tree... | status = Status.OK
elif result is False:
status = Status.FAILED
else:
logger.warning("JMESPath check %s result is not a boolean", jmespath_check.pk)
compliance_check_statuses.append((jmespath_check.compliance_check, sta... |
twitter/pants | tests/python/pants_test/jvm/jvm_task_test_base.py | Python | apache-2.0 | 2,419 | 0.004961 | # coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
import os
from pants.backend.jvm.subsystems.resolve_subsystem import JvmResolveSubsystem... | safe_file_dump(os.path.join(classpath_dir, rel_path), content)
# Add to the classpath.
runtime_classpath.add_for_target(tgt, [('default', classpath_dir)])
def get_runtime_classpath(self, context):
"""
:API: publ | ic
"""
return context.products.get_data('runtime_classpath', init_func=ClasspathProducts.init_func(self.pants_workdir))
|
sysbio-curie/NaviCell | bindings/python/setup.py | Python | lgpl-3.0 | 340 | 0.002941 | from distutils.core import setup
setup(
name='curie',
| version='0.1.1',
author='Eric Viara',
author_email='[email protected]',
packages=['curie'],
url='http://pypi.python.org/pypi/TowelStuff/',
license='LICENSE.txt',
description='NaviCell | Python Binding',
long_description=open('README.txt').read()
)
|
rdhyee/osf.io | website/addons/s3/tests/test_model.py | Python | apache-2.0 | 3,529 | 0.00255 | from nose.tools import * # noqa
import mock
from boto.s3.connection import * # noqa
from tests.base import OsfTestCase, get_default_metaschema
from tests.factories import ProjectFactory
from framework.auth import Auth
from website.addons.base.testing import models
from website.addons.s3.model import S3NodeSettings
... | .node, self.user)
assert_false(message)
def test_before_register_settings_and_auth(self):
message = self.node_settings.before_register(self.node, self.user)
assert_true(message)
@mock.patch('website.archiver.tasks.archive')
def test_does_not_get_copied_to_registrations(self, mock_a... | _node(
schema=get_default_metaschema(),
auth=Auth(user=self.user),
data='hodor',
)
assert_false(registration.has_addon('s3'))
## Overrides ##
def test_serialize_credentials(self):
self.user_settings.external_accounts[0].oauth_key = 'key-11'
s... |
overplumbum/bugsnag-python | example/django/bugsnag_demo/wsgi.py | Python | mit | 399 | 0.002506 | """
WSGI config for bugsnag_demo project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bugsnag_demo.settings")
from dja... | cati | on = get_wsgi_application()
|
PolyJIT/benchbuild | tests/environments/domain/test_model.py | Python | mit | 2,780 | 0 | """
Describe usage of our default container/image domain.
"""
from typing import Hashable
from benchbuild.environments.domain import model
def describe_layers():
def from_is_hashable():
layer = model.FromLayer('a')
assert isinstance(layer, Hashable)
def add_is_hashable():
layer = mo... | er(('a', 'b', 'c'), 'd'),
model.CopyLayer(('a', 'b', 'c'), 'd'),
model.RunLayer('cmd', ('a', 'b', 'c'), dict(a='a', b='b', c='c')),
model.ContextLayer(lambda: None),
model.UpdateEnv(dict(a='a', b='b', c='c')),
model.WorkingDirectory('a'),
model.Ent... | nce(img, Hashable)
|
nachandr/cfme_tests | cfme/automate/dialogs/__init__.py | Python | gpl-2.0 | 4,517 | 0.000443 | from widgetastic.widget import Text
from widgetastic.widget import View
from widgetastic_patternfly import Button
from widgetastic_patternfly import Dropdown
from widgetastic_patternfly import Input
from cfme.common import BaseLoggedInPage
from widgetastic_manageiq import Accordion
from widgetastic_manageiq import Dia... | anageiq import DialogElement
from widgetastic_manageiq import DragandDropElements
from widgetastic_manageiq import ManageIQTree
class AutomateCustomizationView(BaseLoggedInPage):
@property
def in_customization(self):
return (
self.logged_in_as_current_user and
self.navigation.c... | "Customization"]
)
@property
def is_displayed(self):
return self.in_customization and self.configuration.is_displayed
@View.nested
class service_dialogs(Accordion): # noqa
ACCORDION_NAME = 'Service Dialogs'
tree = ManageIQTree()
configuration = Dropdown('Configur... |
neilLasrado/frappe | frappe/patches/v7_1/set_backup_limit.py | Python | mit | 303 | 0.013201 | from __future__ import unicode_literals
from frappe.ut | ils import cint
import frappe
def execute():
backup_limit = frappe.db.ge | t_single_value('System Settings', 'backup_limit')
if cint(backup_limit) == 0:
frappe.db.set_value('System Settings', 'System Settings', 'backup_limit', 3)
|
HurricaneLabs/check_splunk | splunk.py | Python | mit | 13,554 | 0.003984 | import datetime
import requests
import time
import xml.etree.ElementTree as ET
class TimeoutError(Exception):
pass
class ApiError(Exception):
pass
def parse_skey(skey):
if len(skey) == 0:
# Just a value
value = skey.text
else:
child = skey[0] # Should only have one child
... | h(self, search, as_list=False, **kwargs):
| url = "{0}{1}".format(self.server, "/services/search/jobs")
data = dict()
data.update(kwargs)
data["search"] = "search {0}".format(search)
# Get the search ID
r = self.session.post(url, data=data, verify=False)
xml = ET.fromstring(r.text)
#print r.text
... |
honahursey/pyFDA | pyfda/filter_design/cheby1.py | Python | apache-2.0 | 9,053 | 0.016792 | # -*- coding: utf-8 -*-
"""
Design Chebychev 1 filters (LP, HP, BP, BS) with fixed or minimum order, return
the filter design in zpk (zeros, poles, gain) format
Attention:
This class is re-instantiated dynamically everytime the filter design method
is selected, calling the __init__ method.
Author: Christian Münker
""... | 1':'Chebychev 1'}
# common messages for all man. / min. filter order response types:
msg_man = ("Enter the filter order <b><i>N</i></b> and the critical frequency "
" or frequencies <b><i>F<sub>C</sub></i></b> where the gain first drops below "
"the maximum ripple "
| "<b><i>-A<sub>PB</sub></i></b> allowed below unity gain in the "
" passband.")
msg_min = ("Enter maximum pass band ripple <b><i>A<sub>PB</sub></i></b>, "
"minimum stop band attenuation <b><i>A<sub>SB</sub> </i></b>"
" and the corresponding corner f... |
redsh/Tasks-In-A-Bottle | examples/dummy.py | Python | mit | 641 | 0.095164 | import ltask,json
from ltask import pset
class Task(ltask.Task):
#def __init__(self,params):
#super(ltask.Task,self).__init__(self,params)
def transform_params(self,p): #called in ltask.Task processed_params
return p
def out_dir(self):
return './examples/out/'
def kill(self)... |
P = pset('a',[1,2,3,4,5,6,7])*pset('b',['a','b' | ,'c','d','e']) + pset('x',[1000,10001])
P.name = 'dummy1'
return P
|
jiaphuan/models | research/object_detection/builders/hyperparams_builder.py | Python | apache-2.0 | 6,261 | 0.004951 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | raining: Whether the models is in training mode.
Returns:
A dictionary containing batch_norm parameters.
"""
batch_norm_params = {
'decay': batch_norm.decay,
'center': batch_norm.center,
'scale': batch_norm.scale,
'epsilon': batch_ | norm.epsilon,
'is_training': is_training and batch_norm.train,
}
return batch_norm_params
|
cisba/cloudsignaturebot | cloudsignaturebot.py | Python | lgpl-3.0 | 20,001 | 0.00945 | """This is the Cloud Signature Bot based on Time4Mind and Telegram
It allow to sign documents using a Telegram chat and a Time4Mind account
"""
import sys
import os
import yaml
import logging
import time
import datetime
import uuid
import urllib.request
import shutil
import re
import magic
import json
from threading... | if user_id not in acl:
return None
return acl[user_id]
# queue consumer
def proces | s_queue(args):
(queue, bot, acl_set_status) = args
while True:
q_msg = queue.get()
logging.info('queue.get() : ' + repr(q_msg))
# auth transaction
if q_msg['type'] == "authorization":
transaction = q_msg['content']
acl_set_status(q_msg['chat_id'],"authori... |
tdyas/pants | src/python/pants/help/scope_info_iterator_test.py | Python | apache-2.0 | 2,564 | 0.00039 | # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import unittest
from pants.help.scope_info_iterator import ScopeInfoIterator
from pants.option.global_options import GlobalOptions
from pants.option.scope import GLOBAL_SCOPE, ScopeInfo
f... | ASK),
S | copeInfo("goal1.task12", ScopeInfo.TASK, Goal1Task2),
ScopeInfo("subsys1.goal1.task12", ScopeInfo.SUBSYSTEM, Subsys1),
ScopeInfo("goal2", ScopeInfo.INTERMEDIATE),
ScopeInfo("goal2.task21", ScopeInfo.TASK),
ScopeInfo("goal2.task22", ScopeInfo.TASK),
ScopeInfo("... |
disqus/pgshovel | src/main/python/pgshovel/replication/validation/__init__.py | Python | apache-2.0 | 1,442 | 0.000693 | from pgshovel.interfaces.replication_pb2 import (
State,
StreamState,
)
from pgshovel.replication.validation.bootstrap import validate_bootstrap_state
from pgshovel.replication.validation.consumers import validate_consumer_state
from pgshovel.replication.validation.transactions import validate_transaction_state... | idators
def __call__(self, state, *args, **kwargs):
states = {}
for name, validator in self.validators.items():
if state is not None and state.HasField(name):
value = ge | tattr(state, name)
else:
value = None
result = validator(value, *args, **kwargs)
if result is not None:
states[name] = result
return self.message(**states)
validate_state = MultipleStateValidator(State, {
'bootstrap_state': validate_boots... |
diogocs1/comps | web/addons/account/wizard/account_validate_account_move.py | Python | apache-2.0 | 3,203 | 0.005932 | # -*- coding: utf-8 -*-
############# | #################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# ... | ware Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero Gene... |
phobson/bokeh | examples/howto/interactive_bubble/gapminder.py | Python | bsd-3-clause | 4,269 | 0.002577 | import pandas as pd
from jinja2 import Template
from bokeh.embed import file_html
from bokeh.layouts import column
from bokeh.models import (ColumnDataSource, Plot, Circle, Range1d, LinearAxis,
HoverTool, Text, SingleIntervalTicker, CustomJS, Slider)
from bokeh.models.annotations import Title... | x for x in years]))
js_source_array = str(dictionary_of_sources).replace("'", "")
xdr = Range1d(1, 9)
ydr = Range1d(20, 100)
plot = Plot(
x_range=xdr,
y_range=ydr,
title=Title(text=''),
plot_width=800,
plot_height=400,
outline_line_color=None,
toolbar_location=None,
min_border=20,
)
A... | one,
major_tick_in=None,
major_label_text_font_size="10pt",
major_label_text_font_style="normal",
axis_label_text_font_size="10pt",
axis_line_color='#AAAAAA',
major_tick_line_color='#AAAAAA',
major_label_text_color='#666666',
major_tick_line_cap="round",
axis_line_cap="round",
... |
fedebell/Laboratorio3 | relazione2/scriptVecchi/bode.py | Python | gpl-3.0 | 1,939 | 0.016503 | import uncertainties
from uncertainties import ufloat
import math
import numpy
import numpy
import pylab
from scipy.optimize import curve_fit
import math
import scipy.stats
#Misuro a mano con il tester i valori che poi vado a mettere nel file, posso anche lasciare lo sfasamento vuoto
def linear(x, a, b):
return a*x+... | _o)
dB_o = 8.7*dA_o/A_o
logf_o = pylab.log10(f_o)
dlogf_o = (1/pylab.log(10))*df_o/f_o
print(dlogf_o)
print(dB_o)
pylab.figure(1)
pylab.title('Bode diagram of low-pass RC filter')
pylab.xlabel('frequency [kHz]')
pylab. | ylabel('gain [dB]')
pylab.ylim(-50, 2)
pylab.xlim(1, 7)
pylab.grid(color = "gray")
pylab.grid(color = "gray")
pylab.errorbar(logf_o, B_o, dB_o, dlogf_o, "o", color="black")
init = numpy.array([0.0, 0.0])
par_o, cov_o = curve_fit(linear, logf_o, B_o, init, pylab.sqrt(dB_o*dB_o+20.0*dlogf_o*dlogf_o))
print(par_o, cov_o... |
fusion809/python-scripts | SLE/Airy_root_finder.py | Python | gpl-3.0 | 292 | 0.034247 | #!/usr/bin/env python3
from scipy.special import airy
from numpy import abs
def f(xinput):
| x0=xinput
xoutput=x0
Ai=abs(airy(-xoutput)[0])
while Ai>1e-12:
ai=abs(airy(-xoutput))
Ai=ai[0]
Aip=ai[1]
xoutput=xoutput+Ai/Aip
return Ai, xo | utput |
rtts/connect-forever | streaming_api/socket_client.py | Python | gpl-3.0 | 337 | 0.008902 | #!/usr/bin/env python
import sys
from socket import socket
BUFSIZE = 1024
HOST, PORT = 'l | ocalhost', 8888
socket = socke | t()
socket.connect((HOST, PORT))
print "[Connected to server]"
try:
while True:
print socket.recv(BUFSIZE),
socket.send(sys.stdin.readline())
except KeyboardInterrupt:
socket.close()
print "\nGoodbye"
|
hedin/paraboard-back | paraboard/boards/migrations/0004_auto_20150415_1513.py | Python | apache-2.0 | 594 | 0.001684 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('boards', '0003_board_channel'),
]
operations = [
migrations.AlterModelOptions(
name='post',
options=... | ),
| migrations.AddField(
model_name='board',
name='color',
field=models.CharField(max_length=7, default='#FFFFFF', verbose_name='color'),
preserve_default=True,
),
]
|
naparuba/opsbro | data/core-configuration/packs/core-functions/module/node.py | Python | mit | 2,773 | 0.002524 | from opsbro.evaluater import export_evaluater_function
from opsbro.gossip import gossiper
FUNCTION_GROUP = 'gossip'
@export_evaluater_function(function_group=FUNCTION_GROUP)
def is_in_group(group):
"""**is_in_group(group)** -> return True if the node have the group, False otherwise.
* group: (string) group to ... | ef compliance_get_state_of_rule(rule_name):
"""**compliance_ | get_state_of_rule(rule_name)** -> return the state of the rule with the name rule_name
* rule_name: (string) name of the rule to get. If wrong, state will be UNKNOWN.
<code>
Example:
compliance_get_state_of_rule('Install mongodb')
Returns:
'COMPLIANT'
</code>
"""
from opsbro.complian... |
hholzgra/maposmatic | www/maposmatic/migrations/0005_auto_20170521_0103.py | Python | agpl-3.0 | 453 | 0.002208 | # -*- coding: utf-8 -*-
from __future__ impor | t unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('maposmatic', '0004_maprenderingjob_track'),
]
operations = [
migrations.AlterField(
model_name='maprenderingjob',
name='track',
field... | (null=True, upload_to=b'upload/tracks/', blank=True),
),
]
|
awsdocs/aws-doc-sdk-examples | python/example_code/iot/thing_performance.py | Python | apache-2.0 | 5,845 | 0.006501 | # Copyright 2010-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# This file is licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# This file is ... | TPythonSDK.core")
logger.setLevel(logging.DEBUG)
streamHandler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(nam | e)s - %(levelname)s - %(message)s')
streamHandler.setFormatter(formatter)
logger.addHandler(streamHandler)
# Runs the performance shadow client with user arguments.
if __name__ == "__main__":
parser = configureParser()
args = parser.parse_args()
if (args.enableLogging):
configureLogging()
... |
fusionbox/django-widgy-blog | widgy_blog/admin.py | Python | bsd-2-clause | 5,267 | 0.001709 | from functools import partial
from django.co | ntrib import admin
from django.core.exceptions import ObjectDoesNotExist
from django.forms.models import modelform_factory
from django.contrib.admin.views.main import ChangeList
from django.forms.models import model_to_dict
from django.contrib.auth import get_user_model
from widgy.admin import WidgyAdmin
from widgy.fo... | widgy.models import Node
from .models import Blog, BlogLayout, Tag
User = get_user_model()
class IsPublishedListFilter(admin.SimpleListFilter):
title = 'Published'
parameter_name = 'is_published'
model = BlogLayout
def lookups(self, request, model_admin):
return (
('0', 'No'),
... |
schleichdi2/OpenNfr_E2_Gui-6.0 | lib/python/Plugins/Extensions/MediaPortal/additions/mediatheken/atv.py | Python | gpl-2.0 | 8,745 | 0.029052 | # -*- coding: utf-8 -*-
###############################################################################################
#
# MediaPortal for Dreambox OS
#
# Coded by MediaPortal Team (c) 2013-2017
#
# This plugin is open source but it is NOT free software.
#
# This plugin may only be distributed to and executed... | ').replace('blocked-','')
Streampart = "Teil %s" % str(len(Linkliste)+1)
Linkliste.append((Streampart, Link))
self.keyLocked = False
if len(Linkliste) == 1:
self.session.open(SimplePlayer, [(Name, Linkliste[0][1])], showPlaylist=False, ltype='atv')
elif len(Linkliste) >= 1:
self.session.open(atvPa... | f __init__(self, session, Name, Linkliste):
self.Linkliste = Linkliste
self.Name = Name
MPScreen.__init__(self, session, skin='MP_PluginDescr')
self["actions"] = ActionMap(["MP_Actions"], {
"0" : self.closeAll,
"ok" : self.keyOK,
"cancel": self.keyCancel,
"up" : self.keyUp,
"down" : self.keyDow... |
drakeloud/louderdev | louderdev/bin/explode.py | Python | mit | 2,470 | 0.000405 | #!/Users/Drake/dev/LouderDev/louderdev/bin/python3
#
# The Python Imaging Library
# $Id$
#
# split an animation into a number of frame files
#
from __future__ import print_function
from PIL import Image
import os
import sys
class Interval(object):
def __init__(self, interval="0"):
self.setinterval(int... | t(outfile)
outfile = file + "%03d" + ext
ix = 1
im = Image.open(infile)
if html:
file, ext = os.path.splitext(outfile)
html = open(file+".html", "w")
html.write("<html>\n<body>\n")
while True:
if frames[ix]: |
im.save(outfile % ix)
print(outfile % ix)
if html:
html.write("<img src='%s'><br>\n" % outfile % ix)
try:
im.seek(ix)
except EOFError:
break
ix += 1
if html:
html.write("</body>\n</html>\n")
|
provoke-vagueness/reststore | setup.py | Python | mit | 2,099 | 0.002382 | #!/usr/bin/env python
from setuptools import setup
import re
import platform
import os
import sys
install_requires = ["bottle>=0.11",
"requests>=1.1.0",
"pyyaml>=0.0",
"czipfile>=1.0.0",
"prometheus-client"]
def load_version(filename='.... | Michael Dorman",
author_email | ="[email protected]",
url="https://github.com/provoke-vagueness/reststore",
description="RESTful datastore. A simple way to store large amounts of average sized files.",
long_description=open('README.rst').read(),
license="Apache Software Licence",
install_requires = install_requires,
... |
alex/invoke | tests/loader.py | Python | bsd-2-clause | 2,196 | 0.000911 | import os
import sys
from spec import Spec, skip, eq_, raises
from invoke.loader import Loader
from invoke.collection import Collection
from invoke.exceptions import CollectionNotFound
from _utils import support
class Loader_(Spec):
def exposes_discovery_root(self):
root = '/tmp/'
eq_(Loader(ro... | "Doesn't insert self.root if it's already in the path"
new_path = self.l.update_path([self.l.root | ])
eq_(len(new_path), 1) # not 2
|
dreamibor/Algorithms-and-Data-Structures-Using-Python | practice/implementation/stack_and_queue/reverse_substrings_between_each_pair_of_parentheses.py | Python | gpl-3.0 | 1,483 | 0.005394 | """
Stack - Reverse Substrings Between Each Pair of Parentheses (medium) |
You are given a string `s` that consists of lower case English letters and
brackets.
Reverse the strings in each pair of matching parentheses, starting from the
innermost one.
Your result should not contain any brackets.
Example 3:
Input: s = "(ed(et(oc))el)"
Output: "leetcode"
Explanation: First, we reverse the... | tcode-cn.com/problems/reverse-substrings-between-each-pair-of-parentheses
"""
def reverse_substring(s: str) -> str:
""" Stack
Time Complexity - O(N) - Iterate through the string only once.
Space Complexity - O(N) - For the stack.
"""
stack = []
for i, char in enumerate(s):
# Whence w... |
jamesthechamp/zamboni | mkt/webapps/indexers.py | Python | bsd-3-clause | 19,607 | 0 | from operator import attrgetter
from django.core.urlresolvers import reverse
from django.db.models import Min
import commonware.log
from elasticsearch_dsl import F
from elasticsearch_dsl.filter import Bool
import mkt
from mkt.constants import APP_FEATURES
from mkt.constants.applications import DEVICE_GAIA
from mkt.p... | },
# Name for sorting.
'name_sort': cls.string_not_analyzed(doc_values=T | rue),
# Name for suggestions.
'name_suggest': {'type': 'completion', 'payloads': True},
'owners': {'type': 'long'},
'package_path': cls.string_not_indexed(),
'premium_type': {'type': 'byte'},
'preview... |
uccser/cs4hs | generate.py | Python | gpl-3.0 | 3,361 | 0.002678 |
""" CS4HS Website Generator
AUTHOR: Jack Morgan
REQUIRES: Python >= 3.4.1
"""
CURRENT_DIRECTORY = '.'
OUTPUT_DIRECTORY = './output/'
TEXT_FOLDER = './text/'
FOLDERS_TO_COPY = ['css', 'files', 'img', 'js']
"""Check and install dependencies"""
import pip
# Update pip if needed and install dependencies
pip.main(['insta... | stall', 'jinja2>=2.7.3'])
import os
import os.path
import shutil
import argparse
from jinja2 import Environment, FileSystemLoader
class WebsiteGenerator:
"""Object for generating CS4HS website"""
def __init__(self):
# Load files from this folder and templates folder
self.env = Environment(loa... | er()
def write_html(html, file):
"""Render each file to output folder"""
file_name = os.path.join(OUTPUT_DIRECTORY, file)
try:
with open(file_name, 'w', encoding='utf8') as output_file:
output_file.write(html)
print('Created {}'.format(file))
os.chmod(file_name,... |
agdsn/sipa | sipa/model/pycroft/user.py | Python | mit | 13,407 | 0.001492 | # -*- coding: utf-8 -*-
import logging
from sipa.model.user import BaseUser
from sipa.model.finance import BaseFinanceInformation
from sipa.model.fancy_property import active_prop, connection_dependent, \
unsupported_prop, ActiveProperty, UnsupportedProperty, Capabilities
from sipa.model.misc import PaymentDetails... | erfaces) == 1
status, result = api.change_mac(self.user_data.id, self._tmp_password,
self.user_data.interfaces[0].id,
new_mac, host_name)
if status == 401:
raise PasswordInvalid
elif status == 400:
... | elf):
return {'value': len(self.user_data.interfaces) > 0,
'tmp_readonly': len(self.user_data.interfaces) > 0
or not self.has_property('network_access')
or self.user_data.room is None}
@network_access_active.setter
def netw... |
KaGeN101/mantl | roles/calico/files/neutron_port_update.py | Python | apache-2.0 | 4,467 | 0.003134 | #!/usr/bin/env python
# This script updates the allowed address pairs in Neutron with the
# 'neutron port-update' command. This is required by Calico in OpenStack,
# otherwise BGP will not be working. We query OpenStack API directly to prevent
# installing any dependencies such as python-neutronclient.
#
# USAGE: scrip... | public_url):
"""List Neutron ports"""
headers = {'X-Auth-Token': token}
auth_url = public_url + "v2.0/ports"
r = requests.get(auth_url, headers=headers)
if r.text:
parsed_json = json.loads(r.text)
return parsed_json['ports']
else:
sys.stderr.write("ERROR: Unable to ret... | lic_url, port_id, mac_address, calico_network):
"""Update Neutron port with the allowed address pairs"""
headers = {'Content-Type': 'application/json', 'X-Auth-Token': token}
payload = {
"port": {
"allowed_address_pairs": [
{
... |
DoubleNegativeVisualEffects/gaffer | python/GafferUI/VectorDataPlugValueWidget.py | Python | bsd-3-clause | 3,631 | 0.031121 | ##########################################################################
#
# Copyright (c) 2011-2012, Image Engine Design Inc. All rights reserved.
# Copyright (c) 2012, John Haddon. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provi... | ) ) :
self.getPlug().setValue( self.__dataWidget.getData()[0] )
GafferUI.PlugValueWidget.registerType( Gaffer.BoolVectorDataPlug.staticTyp | eId(), VectorDataPlugValueWidget )
GafferUI.PlugValueWidget.registerType( Gaffer.IntVectorDataPlug.staticTypeId(), VectorDataPlugValueWidget )
GafferUI.PlugValueWidget.registerType( Gaffer.FloatVectorDataPlug.staticTypeId(), VectorDataPlugValueWidget )
GafferUI.PlugValueWidget.registerType( Gaffer.StringVectorDataPlug.... |
madssj/django-longer-username-and-email | longerusernameandemail/__init__.py | Python | bsd-3-clause | 288 | 0 | from django.conf import settings
def MAX_USERNAME_LENGTH( | ):
return getattr(settings, "MAX_USERNAME_LENGTH", 255)
def MAX_EMAIL_LENGTH():
return getattr(se | ttings, "MAX_EMAIL_LENGTH", 255)
def REQUIRE_UNIQUE_EMAIL():
return getattr(settings, "REQUIRE_UNIQUE_EMAIL", True)
|
ruibarreira/linuxtrail | usr/lib/python2.7/dist-packages/numpy/core/tests/test_numeric.py | Python | gpl-3.0 | 65,826 | 0.004922 | from __future__ import division, absolute_import, print_function
import sys
import platform
from decimal import Decimal
import warnings
import itertools
import numpy as np
from numpy.core import *
from numpy.random import rand, randint, randn
from numpy.testing import *
from numpy.core.multiarray import dot as dot_
... | assert_(isnan(std([])))
| assert_(w[0].category is RuntimeWarning)
def test_var(self):
A = [[1, 2, 3], [4, 5, 6]]
assert_almost_equal(var(A), 2.9166666666666665)
assert_almost_equal(var(A, 0), array([2.25, 2.25, 2.25]))
assert_almost_equal(var(A, 1), array([0.66666667, 0.66666667]))
with ... |
misnyo/searx | tests/unit/engines/test_google_news.py | Python | agpl-3.0 | 4,340 | 0.00023 | # -*- coding: utf-8 -*-
from collections import defaultdict
import mock
from searx.engines import google_news
from searx.testing import SearxTestCase
class TestGoogleNewsEngine(SearxTestCase):
def test_request(self):
query = 'test_query'
dicto = defaultdict(dict)
dicto['pageno'] = 1
... | wn="return rwt(this,'','','','12','AFQjCNHObfH7sYmLWI1SC-YhWXKZFRzRjw','','0ahUKEwjB58OR54HWAhWnKJoKHSQhAMY4ChCpAgglKAAwAQ','','',event)">Example title 2</a>
</h3>
<div class="slp">
<span class="_OHs _PHs">
Golem... | nsa _QHs">
Oct 4, 2016</span>
</div>
<div class="st">Example description 2</div>
</div>
</div>
</div>
</div>
</div>
</div>
""" # noqa
response = mock.Mock(text=... |
HUGG/NGWM2016-modelling-course | Lessons/02-Physics-of-heat-transfer/scripts/1D_intrusion.py | Python | mit | 3,951 | 0.033662 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# 1D_intrusion.py
#
# This script plots the cooling of a 1D intrusion with time
#
# dwhipp 09.13
#--- User-defined input values ------------------------------------------------#
Ti=700. # Intrusion tempe... | # km -> m
w=w*1000. # km -> m
t1=t1*365.25*24*3600
t2=t2*365.25*24*3600
t3= | t3*365.25*24*3600
t4=t4*365.25*24*3600
t5=t5*365.25*24*3600
t6=t6*365.25*24*3600
# Parameter ranges
x=pylab.linspace(-w,w,numpts);
# Temperature calculation
T1=Tb+((Ti-Tb)/2)*(scipy.special.erf((0.5*l-x)/(scipy.sqrt(4*kappa*t1)))+scipy.special.erf((0.5*l+x)/(scipy.sqrt(4*kappa*t1))))
T2=Tb+((Ti-Tb)/2)*(scipy.special.... |
ChinaMassClouds/copenstack-server | openstack/src/ceilometer-2014.2.2/ceilometer/alarm/storage/impl_sqlalchemy.py | Python | gpl-2.0 | 12,576 | 0 | #
# Author: John Tran <[email protected]>
# Julien Danjou <[email protected]>
#
# 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
#
# Unl... | type: meter type
unit: meter unit
}
- sample
- the raw incoming data
- { id: sample id
meter_id: meter id (->meter.id)
user_id: user uuid
project_id: project uuid
resource_id: resource | uuid
source_id: source id
resource_metadata: metadata dictionaries
volume: sample volume
timestamp: datetime
message_signature: message signature
message_id: message uuid
}
"""
CAPABILITIES = utils.update_nested(ba... |
PaloAltoNetworks/minemeld-core | minemeld/ft/dag.py | Python | apache-2.0 | 20,185 | 0.000149 | # Copyright 2015 Palo Alto Networks, 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 agre... | elf._user_id(cmd=msg)
def _init_resync(self):
ctags = collections.defaultdict(set)
while True:
op, address, value = self.q.get()
if op == 'EOI':
break
if op != 'init':
raise RuntimeError(
'DevicePusher %s - wro... | s' % (self.prefix, self.watermark))
for t in self._tags_from_value(value):
ctags[address].add(t)
LOG.debug('%s', ctags)
register = collections.defaultdict(list)
unregister = collections.defaultdict(list)
for a, atags in self._get_all_registered_ips():
... |
pyro-ppl/numpyro | numpyro/contrib/einstein/steinvi.py | Python | apache-2.0 | 18,091 | 0.001879 | # Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
from collections import namedtuple
import functools
from functools import partial
from itertools import chain
import operator
from typing import Callable
import jax
import jax.numpy as jnp
import jax.random
from jax.tree_util import t... | init_params = {
name: extract_info(site)
for name, site in inner_guide_trace.items()
if site.get("type") == "param"
}
return init_params
def _svgd_loss_and_grads(self, rng_key, unconstr_params, *args, **kwargs):
# 0. Separate model and guide paramete... | n unconstr_params.items()
if p not in self.guide_param_names or self.classic_guide_params_fn(p)
}
stein_uparams = {
p: v for p, v in unconstr_params.items() if p not in classic_uparams
}
# 1. Collect each guide parameter into monolithic particles that capture corr... |
lcy-seso/Paddle | python/paddle/fluid/tests/book_memory_optimization/test_memopt_machine_translation.py | Python | apache-2.0 | 5,038 | 0.000397 | # Copyright (c) 2018 PaddlePaddle 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 app... | seq_lens:
cur_len += l
lod.append(cur_len)
flattened_data = np.concatenate(data, axis=0).astype("int64")
flattened_data = flattened_data.reshape([len(flattened_data), 1])
res = core.LoDTensor()
res.set(flattened_data, place)
res.set_lod([lod])
ret | urn res
def main():
rnn_out = encoder_decoder()
label = layers.data(
name="target_language_next_word", shape=[1], dtype='int64', lod_level=1)
cost = layers.cross_entropy(input=rnn_out, label=label)
avg_cost = fluid.layers.mean(cost)
optimizer = fluid.optimizer.Adagrad(learning_rate=1e-4)
... |
wujuguang/motor | motor/motor_gridfs.py | Python | apache-2.0 | 19,133 | 0.003084 | # Copyright 2011-2015 MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | __ import unicode_literals, absolute_import
"""GridFS implementation for Motor, an asynchronous driver for MongoDB."""
import textwrap
import | gridfs
import pymongo
import pymongo.errors
from gridfs import grid_file
from motor.core import (AgnosticBaseCursor,
AgnosticCollection,
AgnosticDatabase,
PY35)
from motor.docstrings import *
from motor.metaprogramming import (AsyncCommand,
... |
marco-lilek/musiClr | src/utils/modifyTag.py | Python | mit | 835 | 0.037126 | import taglib
import os
TEMP_FILENAME = "temp.mp3"
class TagWrapper:
def __init__(self, fileName):
self.fileName = fileName
try:
| self.tag = taglib.MP3(fileName)
except:
self.tag = None
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
if self.tag != None:
| del self.tag
def hasTags(self):
return self.tag.artist is not None and self.tag.name is not None
def getData(self):
return self.tag.artist, self.tag.name
def modify(self, artist, name):
if self.tag == None:
raise TypeError
self.tag.artist = artist
self.tag.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.