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 |
|---|---|---|---|---|---|---|---|---|
FreeON/spammpack | src-charm/tools/process_scaling_data.py | Python | bsd-3-clause | 16,233 | 0.030863 | #!/usr/bin/env python
class scaling_data:
def __init__ (self, filename):
import re
self.data = []
self.N_chunk = 0
self.N_basic = 0
fd = open(filename)
for line in fd:
if self.N_chunk == 0:
result = re.compile("^running.* -N ([0-9]+) -b ([0-9]*) ").search(line)
if res... | mplexity")
plt.ylabel("parallel speedup")
if not options.no_title:
plt.title("N = {:d}, N_basic = {:d}".format(data.N_chunk, data.N_basic))
if options.output:
plt.savefig(options.output + "_ | walltime_vs_complexity.png")
def plot_walltime_vs_tolerance (data, options):
import matplotlib.pyplot as plt
plt.figure(
figsize = (
options.width/100.0,
options.height/100.0
),
dpi = 100
)
tolerance_values = data.get_tolerance()
if options.thread:
thread_values ... |
ShaftesburySchoolDorset/PythonChallenges | algorithm_identification/1.py | Python | gpl-3.0 | 334 | 0.038922 | #!/usr/local/bi | n/python3
def one(alist):
for passnum in range(len(alist)-1,0,-1):
for i in range(passnum):
if alist[i]>alist[i+1]:
temp = alist[i]
| alist[i] = alist[i+1]
alist[i+1] = temp
alist = [54,26,93,17,77,31,44,55,20]
print(alist)
one(alist)
print(alist) |
terzeron/FeedMakerApplications | study/_spring/capture_item_link_title.py | Python | gpl-2.0 | 1,528 | 0.001309 | #!/usr/bin/env | python
import sys
import re
import getopt
from feed_maker_util import IO
def main():
state = 0
url_prefix = "https://spring.io"
result_list = []
num_of_recent_feeds = 1000
optlist, _ = getopt.getopt(sys.argv[1:], "n:")
for o, a in optlist:
if o | == '-n':
num_of_recent_feeds = int(a)
for line in IO.read_stdin_as_line_list():
if state == 0:
if re.search(r'<h2 class="blog--title">', line):
state = 1
elif state == 1:
m = re.search(r'<a href="(?P<link>[^"]+)">(?P<title>.*)</a>', line)
... |
yutian2011/IPProxy | proxy.py | Python | gpl-3.0 | 5,041 | 0.011902 | # -*- coding: utf-8 -*-
from queue import Queue
from lxml import etree
import requests
import random
from settings import *
import time
import socket
from pybloom_live import BloomFilter
from settings import log
import os
from settings import REFRESH_BF
from settings import MIN_NUM
import redis
import threading
import... | = None or ty == None:
raise ValueError("current page "+str(ips)+str(ports)+str(ty))
for i in range(len(ips)):
ret = {}
str = "%s:%s"
| ret["ip_port"] = str%(ips[i].text,ports[i].text)
#print(url, ret["ip_port"], ty[i].text)
if ty[i].text.find("http") >= 0:
ret["type"] = 0
elif ty[i].text.find("https") >= 0:
ret["type"] = 1
else:
log.error("PID:%d page:%s can not get proxy type... |
santiavenda2/griffith | lib/plugins/movie/PluginMovieIMDB-pt.py | Python | gpl-2.0 | 7,570 | 0.004761 | # -*- coding: UTF-8 -*-
__revision__ = '$Id$'
# Copyright (c) 2011 Ivo Nunes
#
# 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 later ... | 2.1">', u'</div>')
self.plot = gutils.strip_tags(self.plot)
self.plot = self.plot.encode(self.encode)
def get_year(self):
self.year = gutils.trim(self.page, u' (', u')</title>')
def get_runtime(self):
self.runtime = gutils.trim(self.page, u'<h5>Duração:</h5><div class="info-con... | elf.genre = gutils.strip_tags(self.genre)
self.genre = string.replace(self.genre, " | ", ", ")
self.genre = self.genre.encode(self.encode)
def get_cast(self):
self.cast = ''
self.cast = gutils.trim(self.cast_page, '<table class="cast">', '</table>')
if self.cast == '':
... |
RTHMaK/RPGOne | deep_qa-master/deep_qa/models/__init__.py | Python | apache-2.0 | 3,009 | 0.00432 | from .entailment.decomposable_attention import DecomposableAttention
from .memory_networks.differentiable_search import DifferentiableSearchMemoryNetwork
from .memory_networks.memory_network import MemoryNetwork
from .memory_networks.softmax_memory_network import SoftmaxMemoryNetwork
from .multiple_choice_qa.decomposab... | nsion.attention_sum_reader import AttentionSumReader
from .reading_comprehension.gated_attention_reader import GatedAttentionReader
from .reading_comprehension.bidirectional_attention import BidirectionalAttentionFlow
from .text_classification.true_false_model import TrueFalseModel
from ..training import concrete_ | pretrainers
from .memory_networks.pretrainers.attention_pretrainer import AttentionPretrainer
from .memory_networks.pretrainers.snli_pretrainer import SnliAttentionPretrainer, SnliEntailmentPretrainer
from .text_pretrainers.encoder_pretrainer import EncoderPretrainer
concrete_models = { # pylint: disable=invalid-name... |
jmesteve/saas3 | openerp/addons_extra/l10n_es_fiscal_year_closing/wizard/__init__.py | Python | agpl-3.0 | 1,141 | 0.001753 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (c) 2009 Zikzakmedia S.L. (http://zikzakmedia.com) All Rights Reserved.
# Jordi Esteve <jesteve@zikzakmedia.com>
# $Id$
#
# Th... | # (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You shoul... | ################################################################
"""
Spanish Fiscal Year Closing Wizards
"""
import wizard_run
|
smallyear/linuxLearn | salt/salt/utils/openstack/neutron.py | Python | apache-2.0 | 33,523 | 0.00006 | # -*- coding: utf-8 -*-
'''
Neutron class
'''
# Import python libs
from __future__ import absolute_import, with_statement
import logging
# Import third party libs
import salt.ext.six as six
# pylint: disable=import-error
HAS_NEUTRON = False
try:
from neutronclient.v2_0 import client
from neutronclient.shell ... | ound.")
else:
return ret[0]
def _find_port_id(self, resource):
re | source = self._fetch_port(resource)
return resource['id']
def _find_network_id(self, resource):
resource = self._fetch_network(resource)
return resource['id']
def _find_subnet_id(self, resource):
resource = self._fetch_subnet(resource)
return resource['id']
def _fi... |
avih/treeherder | treeherder/perfalert/perfalert/__init__.py | Python | mpl-2.0 | 5,173 | 0.000773 | def analyze(data, weight_fn=None):
"""Returns the average and sample variance (s**2) of a list of floats.
`weight_fn` is a function that takes a list index and a window width, and
returns a weight that is used to calculate a weighted average. For example,
see `default_weights` or `linear_weights` belo... | t the current point is at the
# start of the window.
| jw.reverse()
di.historical_stats = analyze(jw)
di.forward_stats = analyze(kw)
if len(jw) >= j:
di.t = abs(calc_t(jw, kw, linear_weights))
else:
# Assume it's ok, we don't have enough data
di.t = 0
goo... |
Yaco-Sistemas/django-autoreports | autoreports/urls.py | Python | lgpl-3.0 | 1,686 | 0.021945 | # Copyrig | ht (c) 2010 by Yaco Sistemas <pmartin@yaco.es>
#
# This program 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) an | y 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 Lesser General Public License for more details.
#
# You should have received a copy of the GN... |
PUNCH-Cyber/stoq-plugins-public | mongodb/setup.py | Python | apache-2.0 | 364 | 0 | from setuptools import setup, find_packages
setup(
name="mongo | db",
version="3.0.1",
author="Marcus LaFerrera (@mlaferrera)",
url="https://github.com/PUNCH-Cyber/stoq-plugins-public",
license="Apache License 2.0",
description="Save results and archive payloads using MongoDB",
packages=find_packa | ges(),
include_package_data=True,
)
|
ggilestro/majordomo | actors/__init__.py | Python | mit | 42 | 0 | # -*- codin | g: utf-8 -*-
__all__ = ["mpd | "]
|
MichaelDoyle/Diamond | src/collectors/mysqlstat/mysql55.py | Python | mit | 8,223 | 0 | # coding=utf-8
"""
Diamond collector that monitors relevant MySQL performance_schema values
For now only monitors replication load
[Blog](http://bit.ly/PbSkbN) announcement.
[Snippet](http://bit.ly/SHwYhT) to build example graph.
#### Dependencies
* MySQLdb
* MySQL 5.5.3+
"""
from __future__ import division
... | x',
'wait/synch/rwlock':
'rwlocks',
'wait/io':
'other_io',
},
'slave_io': {
'wait/io/file/sql/relaylog_index': |
'relaylog_index',
'wait/synch/mutex/sql/MYSQL_RELAY_LOG::LOCK_index':
'relaylog_index_lock',
'wait/synch/mutex/sql/Master_info::data_lock':
'master_info_lock',
'wait/synch/mutex/mysys/IO_CACHE::append_buffer_lock':
... |
yochow/autotest | client/bin/harness.py | Python | gpl-2.0 | 2,286 | 0.006124 | """The harness interface
The interface between the client and the server when hosted.
"""
__author__ = """Copyright Andy Whitcroft 2006"""
import os, sys
import common
class harness(object):
"""The NULL server harness
Properties:
job
The job object for this job
"""
... | pass
def run_complete(self):
"""A run within this job is completing (all done)"""
pass
def run_test_complete(self):
"""A test run by this job is complete. Note that if multiple
tests are run in parallel, this will only be called when all
of the parallel runs complet... | def test_status(self, status, tag):
"""A test within this job is completing"""
pass
def test_status_detail(self, code, subdir, operation, status, tag):
"""A test within this job is completing (detail)"""
pass
def select(which, job):
if not which:
which = 'standalone'... |
ksh/gpirecertification | controllers/assessments.py | Python | apache-2.0 | 11,743 | 0.007153 | # Copyright 2012 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | 'type': 'assessment-%s' % assessment_name,
'values': new_answers, 'location': 'AnswerHandler'}))
return student
def post(self):
"""Handles POST requests."""
student = self.personal | ize_page_and_get_enrolled()
if not student:
return
if not self.assert_xsrf_token_or_fail(self.request, 'assessment-post'):
return
course = self.get_course()
assessment_type = self.request.get('assessment_type')
assessment_name = self.request.get('assessm... |
underlost/GamerNews | gamernews/apps/news/fields.py | Python | mit | 3,543 | 0.005927 | import re
from django.db.models import fields
from django.template.defaultfilters import slugify
def _unique_slugify(instance, value, slug_field_name='slug', queryset=None, slug_separator='-'):
slug_field = instance._meta.get_field(slug_field_name)
slug_len = slug_field.max_length
# Sort out the initial s... | te_from: Must be assigned to list of field names which
are used to prepopulate automatica | lly.
:type prepopulate_from: sequence
"""
self.prepopulate_separator = kwargs.get("prepopulate_separator", u"-")
self.prepopulate_from = prepopulate_from
kwargs["blank"] = True
super(fields.SlugField, self).__init__(*args, **kwargs)
def pre_sav... |
unikmhz/npui | netprofile_bills/netprofile_bills/views.py | Python | agpl-3.0 | 3,005 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# NetProfile: Bills module - Views
# Copyright © 2017 Alex Unigovsky
#
# This file is part of NetProfile.
# NetProfile is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General Public
# License as published by the Free Software... | None,
'stateful': False,
'hideColumns': ('type',),
'extraParamProp': 'btypeid',
'createControllers': 'NetProfile.core.controlle | r.RelatedWizard'
})
@register_hook('core.dpanetabs.entities.Entity')
@register_hook('core.dpanetabs.entities.PhysicalEntity')
@register_hook('core.dpanetabs.entities.LegalEntity')
@register_hook('core.dpanetabs.entities.StructuralEntity')
@register_hook('core.dpanetabs.entities.ExternalEntity')
def _dpane_ent... |
david81brs/seaport | week6/l5_hipotenusas.py | Python | gpl-2.0 | 632 | 0.022152 | #!/usr/bin/python3
def soma_hipotenusas(n):
chipotenusa=1
somahipot=[]
while chipotenusa <=n:
cat1 = 1
while ca | t1 <=n:
cat2=1
cat1+=1
while cat2 <=n:
if (cat1**2 + cat2**2) == chipotenusa**2:
if chipotenusa not in somahipot:
somahipot.append(chipotenusa)
# print(cat1, cat2, chipotenusa, somahipot)
c... | range(0,len(somahipot)):
acumulador=acumulador+somahipot[i]
return acumulador
|
fs714/drcontroller | drcontroller/recovery/base.py | Python | apache-2.0 | 2,725 | 0.008807 | import logging
import json
from ansible.runner import Runner
from taskflow.patterns import linear_flow, unordered_flow
from taskflow.task import Task
shell_task = Runner(
host_list=['eselnlx1453'],
pattern= '*',
module_name = 'shell',
module_args='echo "Hello World"')
c... | selnlx1277'],
pattern='*',
module_name='copy',
module_args='src=/home/ejjacci/ansible/example.py dest=/home/ejjacci/tmp/example.py')
class AnsibleTask(Task):
def __init__(self, name, host_list, module_name, module_args, pattern='*', inject=None):
super(AnsibleTask, self... | the results to engine.storage
self.name = name
self.host_list = host_list
self.logger = logging.getLogger("RecoveryHandler:Base")
self.runner = Runner(
host_list = host_list,
pattern = pattern,
module_name = module_name,
... |
bastibl/gr-ieee802-15-4 | python/css_analyze_tx_signal.py | Python | gpl-3.0 | 6,539 | 0.029209 | #! /usr/bin python
import numpy as np
import matplotlib.pyplot as plt
if __ | name__ == "__main__":
print("Generate and demodulate IEEE 802.15.4 compliant CSS baseband signal")
slow_rate = False
phy_packetsize_bytes = 38
nframes = 40
chirp_number = 2
m = css_mod.modulator(slow_rate=slow_rate, phy_packetsize_bytes=phy_packetsize_bytes, nframes=nframes, chirp_number=chirp_number)
[payload,... | ow_rate=slow_rate, phy_packetsize_bytes=phy_packetsize_bytes, nframes=nframes, chirp_number=chirp_number)
payload_rx = d.demodulate(baseband)
print("RX BER:", sum(abs(payload - payload_rx))/len(payload))
print("samples in one...")
print("-> subchirp: ", css_constants.n_sub)
print("-> average chirp sequence:", cs... |
VladimirVystupkin/AMRParsing1.x | smatch_v1_0/smatch-table.py | Python | gpl-2.0 | 12,971 | 0.046334 | #!/usr/bin/env python
import amr
import sys
import subprocess
import smatch_modified
import os
import random
import time
#import optparse
#import argparse #argparse only works for python 2.7. If you are using older versin of Python, you can use optparse instead.
#import locale
ERROR_LOG=sys.stderr
verbose=False
isi... | os.walk(file_dir):
# print path
if get_sub==False:
total_list=subdir[:]
get_sub=True
else:
break
for user in total_list:
#print user
has_file=True
for file in files:
# print file
file_path=file_dir+user+"/"+file+".txt"
# print file_path
if not os.path.e... | >> ERROR_LOG,"********Error: Cannot find any user who completes the files*************"
return name_list
"""
Compute the smatch scores for a file list between two users
Args:
user1: user 1 name
user2: user 2 name
file_list: file list
dir_pre: the file location prefix
start_num: the number of restar... |
DONIKAN/django | tests/postgres_tests/array_default_migrations/0001_initial.py | Python | bsd-3-clause | 654 | 0.003058 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import django.contrib.postgres.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
]
o | perations = [
| migrations.CreateModel(
name='IntegerArrayDefaultModel',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('field', django.contrib.postgres.fields.ArrayField(models.IntegerField(), size=None)),
... |
deathglitch/metarigging | python/metaui/__init__.py | Python | mit | 1,252 | 0.009585 | import os
import sys
import inspect
_module = sys.modules[__name__]
_sa | fe_import_list = [_x.__name__ for _x in _module, os, sys, inspect]
for mod in [m for m in sys.modules.keys() if m != __name__ and sys.modul | es[m] != None and m.startswith(__name__) and len(m.split(__name__ + ".")[-1].split(".")) == 1 and (not sys.modules[m].__file__.split(os.path.sep)[-1].startswith("__init__"))]:
del(sys.modules[mod])
from example_ui import *
#deleting classes, function, modules not in module
for _function_name in [_member[0] fo... |
arnedesmedt/dotfiles | .config/sublime-text-3/Packages.symlinkfollow/mdpopups/st3/mdpopups/st_color_scheme_matcher.py | Python | mit | 23,380 | 0.003208 | """
color_scheme_matcher.
Licensed under MIT.
Copyright (C) 2012 Andrew Gibson <agibsonsw@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limit... | nd trim precision zeros."""
string = str(
decimal.Decimal(f).quantize(decimal.Decimal('0.' + ('0' * p) | if p > 0 else '0'), decimal.ROUND_HALF_UP)
)
m = FLOAT_TRIM_RE.match(string)
if m:
string = m.group('keep')
if m.group('keep2'):
string += m.group('keep2')
return string
def alpha_dec_normalize(dec):
"""Normailze a deciaml alpha value."""
temp = float(dec)
if ... |
liqd/a4-meinberlin | tests/topicprio/dashboard_components/test_views_module_topics.py | Python | agpl-3.0 | 3,141 | 0 | import pytest
from django.urls import reverse
from adhocracy4.dashboard import components
from adhocracy4.test.helpers import assert_template_response
from adhocracy4.test.helpers import redirect_target
from adhocracy4.test.helpers im | port setup_phase
from meinberlin.apps.topicprio.models import Topic
from meinberlin.apps.topic | prio.phases import PrioritizePhase
component = components.modules.get('topic_edit')
@pytest.mark.django_db
def test_edit_view(client, phase_factory, topic_factory):
phase, module, project, item = setup_phase(
phase_factory, topic_factory, PrioritizePhase)
initiator = module.project.organisation.initi... |
Captain-Coder/tribler | Tribler/Test/Core/test_sqlitecachedbhandler_torrents.py | Python | lgpl-3.0 | 13,903 | 0.002374 | import os
import struct
from binascii import unhexlify
from shutil import copy as copyfile
from twisted.internet.defer import inlineCallbacks
from Tribler.Core.CacheDB.SqliteCacheDBHandler import TorrentDBHandler, MyPreferenceDBHandler, ChannelCastDBHandler
from Tribler.Core.CacheDB.sqlitecachedb import str2bin
from ... | e()
old_tracker_size = self.tdb._db.size('TrackerInfo')
s_infohash = unhexlify('44865489ac16e2f34ea0cd3043cfd970cc24ec09')
m_infohash = unhexlify('ed81da94d21ad1b305133f2726cdaec5a57fed98')
single_torrent_file_path = os.path.join(self.getStateDir(), 'single.torrent')
multiple_t... | BACKUP, multiple_torrent_file_path)
single_tdef = TorrentDef.load(single_torrent_file_path)
self.assertEqual(s_infohash, single_tdef.get_infohash())
multiple_tdef = TorrentDef.load(multiple_torrent_file_path)
self.assertEqual(m_infohash, multiple_tdef.get_infohash())
self.tdb.a... |
geolovic/TProfiler | Tools/debug/Chi_Map_QGIS_testing_suite.py | Python | gpl-3.0 | 6,907 | 0.000869 | # -*- coding: iso-8859-15 -*-
#
# Testing Suite for >> Get_Channels.py [QGIS Version]
#
# Copyright (C) 2017 J. Vicente Perez, Universidad de Granada
#
# 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 ... | tance, thetaref=thetaref)
fin = time.time()
print("Test finalizado en " + str(fin - inicio) + " segundos")
print("Resultado en " + | out_shp)
print("Generado tambien" + os.path.splitext(out_shp)[0] + ".dat")
print("=" * 40)
test_00()
test_01()
test_02()
test_03()
test_04()
test_05()
test_06()
|
pauldardeau/cloud-jukebox | jukebox_db.py | Python | bsd-3-clause | 18,366 | 0.000436 | import sqlite3
import jukebox
from song_metadata import SongMetadata
from file_metadata import FileMetadata
class JukeboxDB:
def __init__(self, metadata_db_file_path=None, debug_print=False):
self.debug_print = debug_print
self.db_connection = None
if metadata_db_file_path is not None and... | able = "CREATE TABLE album (" + \
"album_uid TEXT UNIQUE NOT NULL," + \
"album_name TEXT UNIQUE NOT NULL," + \
"album_description TEXT," | + \
"artist_uid TEXT NOT NULL REFERENCES artist(artist_uid)," + \
"genre_uid TEXT REFERENCES genre(genre_uid))"
create_song_table = "CREATE TABLE song (" + \
"song_uid TEXT UNIQUE NOT NULL," + \
... |
lrosengreen/cloudberry | server.py | Python | gpl-3.0 | 2,533 | 0.006711 | #!/usr/bin/env python
from __future__ import division, print_function
# cloudberryCam v0 copyright (c) 2013-2015 Lars Rosengreen
# 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 ... | config first so we get a log if errors occur.
cherrypy.config.update({'environment': 'production',
'log.error_file': 'site.log',
'log.screen': False})
conf = {'/previews': {'tools.staticdir.on' | : True,
'tools.staticdir.dir': '/mnt/ramdisk/previews'},
'/static': {'tools.staticdir.on': True,
'tools.staticdir.dir': os.path.join(current_dir, 'static')}}
cherrypy.server.socket_host = '0.0.0.0'
#cherrypy.server.socket_host = '::' # for Mac (uses IPV6)
... |
vfulco/twilio_server | twiml_server/common/util.py | Python | gpl-3.0 | 541 | 0 | import types
from flask import jsonify
from werkzeug.excep | tions import default_exceptions
from werkzeug.exceptions import HTTPException
from twiml_server import app
def make_json_app():
def make_json_error(ex):
response = jsonify(message=str(ex))
response.status_code = (ex.code
if isinstance(ex, HTTPException)
... | code] = make_json_error
|
badele/home-assistant | tests/components/light/test_mqtt.py | Python | mit | 5,134 | 0 | """
tests.components.light.test_mqtt
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Tests mqtt light.
config for RGB Version with brightness:
light:
platform: mqtt
name: "Office Light RGB"
state_topic: "office/rgb1/light/status"
command_topic: "office/rgb1/light/switch"
brightness_state_topic: "office/rgb1/brightness/s... | ss = ha.HomeAssistant()
self.mock_publish = mock_mqtt_component(self.hass)
def tearDown(self): # pylint: disable=invalid-name
""" Stop down s | tuff we started. """
self.hass.stop()
def test_controlling_state_via_topic(self):
self.assertTrue(light.setup(self.hass, {
'light': {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'test_light_rgb/status',
'command_topi... |
yslin/tools-zodlin | ubuntu/vim/.vim/lang/all/ultisnips/test/test_Mirror.py | Python | apache-2.0 | 8,787 | 0.000114 | from test.vim_test_case import VimTestCase as _VimTest
from test.constant import *
class TextTabStopTextAfterTab_ExpectCorrectResult(_VimTest):
snippets = ('test', '$1 Hinten\n$1')
keys = 'test' + EX + 'hallo'
wanted = 'hallo Hinten\nhallo'
class TextTabStopTextBeforeTab_ExpectCorrectResult(_VimTest):
... | + JF + 'end'
wanted = 'ha stdin stdinend'
class MirrorRealLifeExample_ExpectCorrectResult(_VimTest):
snippets = (
('for', 'for(size_t ${2:i} = 0; $2 < ${1:count}; ${3:++$2})'
'\n{\n\t${0:/* code */}\n}'),
)
keys = 'for' + EX + '100' + JF + 'avar\b\b\b\ba_variable' + JF + \
'a... | nothing'
wanted = """for(size_t a_variable = 0; a_variable < 100; a_variable *= 2)
{
\t// do nothing
}"""
class Mirror_TestKill_InsertBefore_NoKill(_VimTest):
snippets = 'test', '$1 $1_'
keys = 'hallo test' + EX + 'auch' + ESC + \
'wihi' + ESC + 'bb' + 'ino' + JF + 'end'
wanted = 'hallo noauc... |
GoogleCloudPlatform/python-docs-samples | functions/billing/main.py | Python | apache-2.0 | 7,657 | 0.000522 | # Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | _stop]
# [END functions_billing_limit]
# [END functions_billing_limit_appengine]
# [END functions_billing_slack]
# [START functions_billing_limit]
# [START functions_billing_limit_appengine]
# [START functions_billing_stop]
from googleapiclient import discovery
# [END functions_billing_stop]
# | [END functions_billing_limit]
# [END functions_billing_limit_appengine]
# [START functions_billing_slack]
import slack
from slack.errors import SlackApiError
# [END functions_billing_slack]
# [START functions_billing_limit]
# [START functions_billing_stop]
PROJECT_ID = os.getenv('GCP_PROJECT')
PROJECT_NAME = f'projec... |
JohnRandom/django-aggregator | dasdocc/conf/staging.py | Python | bsd-3-clause | 29 | 0.034483 | from dasdocc.conf import b | ase | |
austinwagner/sublime-sourcepawn | watchdog/events.py | Python | mit | 18,129 | 0.006619 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2011 Yesudeep Mangalapilly <yesudeep@gmail.com>
# Copyright 2012 Google, 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
#
# ... | (class_name)s: src_path=%(src_path)s>" %\
dict(class_name=self.__class__.__name__,
src_path=self.src_path)
class FileMovedEvent(FileSystemMovedEvent):
"""File system event representing file movement on the file system."""
def __init__(self, src_path, dest_path):
super(FileMovedEven... | is_directory=False)
def __repr__(self):
return "<%(class_name)s: src_path=%(src_path)s, \
dest_path=%(dest_path)s>" %\
dict(class_name=self.__class__.__name__,
src_path=self.src_path,
dest_path=self.dest_path)
# Directory events.
class DirDe... |
thonkify/thonkify | src/lib/libpasteurize/fixes/fix_kwargs.py | Python | mit | 6,066 | 0.001813 | u"""
Fixer for Python 3 function parameter syntax
This fixer is rather sensitive to incorrect py3k syntax.
"""
# Note: "relevant" parameters are parameters following the first STAR in the list.
from lib2to3 import fixer_base
from lib2to3.fixer_util import token, String, Newline, Comma, Name
from libfuturize.fixer_uti... | urr_idx += 1
continue
if prev_item is not None and prev_item.type == token.DOUBLESTAR:
break
name = curr_item.value
nxt = curr_item.next_sibling
if nxt is not None and nxt.type == token.EQUAL:
default_value = nxt.next_sibling
curr_idx += 2
... | params, kwargs_default=_kwargs_default_name):
u"""
Removes all keyword-only args from the params list and a bare star, if any.
Does not add the kwargs dict if needed.
Returns True if more action is needed, False if not
(more action is needed if no kwargs dict exists)
"""
assert raw_params[0]... |
txomon/vdsm | vdsm/network/tc/qdisc.py | Python | gpl-2.0 | 4,910 | 0 | # Copyright 2014 Red Hat, Inc.
#
# 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 later version.
#
# This program is distributed in the ... | mmand = ['qdisc', 'replace', 'dev', dev]
if kind != 'ingress':
if parent is None:
command.append('root')
else:
command += ['parent', parent]
if handle is not None:
command += ['handle', handle]
command.append(kind)
for key, value in opts.items():
c... | mmand += ['dev', dev]
return _wrapper.process_request(command)
def parse(tokens):
"""Takes a token generator and returns a dictionary of general qdisc
attributes and kind (kernel's TCA_KIND) specific attributes"""
kind = next(tokens)
data = {'kind': kind, 'handle': next(tokens)}
for token in t... |
adexin/Python-Machine-Learning-Samples | Logistic_regression/Ecommerce_logpredict/logistic.py | Python | mit | 495 | 0.00202 | import numpy as np
import matplotlib.pyplot as plt
N = 200
D = 2
X = np.random.randn(N, D)
# Bias term
ones = np.array([[1]*N]).T
# Concatenate with input X
Xb = np.concatenate((ones, X), axis=1)
# Randomly initialize w
w = np.random.randn(D)
z = X.dot(w | )
def sigmoid(z):
return 1/(1 + np.exp(-z))
def hypertan(z):
return (np.exp(z) - np.exp(-z))/(np.exp(z) + np.exp(-z))
print(sigmoid(z))
plt.plot(sigmoid(z))
plt.show()
print(hypertan(z))
plt.plot(hypertan(z))
p | lt.show()
|
apple/coremltools | coremltools/converters/mil/mil/passes/test_noop_elimination.py | Python | bsd-3-clause | 13,225 | 0.001966 | # Copyright (c) 2020, Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can be
# found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
import itertools
import numpy as np
import pytest
from coremltools.converters.mil.mil import Builder... | =(2, 4))])
def prog(x):
r1 = mb.reshape(x=x, shape=[1, 8])
r2 = mb.reshape(x=r1, shape=[1, 8])
return mb.relu(x=r1)
prev_prog, prev_block, block = apply_pass_and_basic_check(
prog, "common::noop_elimination"
)
assert get_op_types_in_program(prev_prog) == ["reshape", "res... | ts[0].name: (1, 8)},
)
def test_oneway_split_elimination():
@mb.program(input_specs=[mb.TensorSpec(shape=(2, 4))])
def prog(x):
r1 = mb.split(x=x, num_splits=1, axis=-1)
return mb.relu(x=r1)
prev_prog, prev_block, block = apply_pass_and_basic_check(
prog, "common::noop_elimin... |
sixpearls/wagtail-storageimage | storageimage/models.py | Python | bsd-2-clause | 2,687 | 0.00521 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.db.models.fields.files import ImageFieldFile, ImageField
from django.utils.translation import ugettext_lazy as _
from django.db.models.signals import pre_save, pre_delete
from PIL import Image as PILImage
from storageimage import settings
class StorageImageFie... | self._dimensions_cache
class StorageImageField(ImageField):
attr_class = StorageImageFieldFile
def storage_save(self,*args,**kwargs):
fix_save = True
if self.pk:
instance_ref = self.__class__.objects.get(pk=self.pk)
if instance_ref.file == self.file:
# This is a bad way of che... | avail_name = get_upload_to(self, self.file.name)
reopen = not self.file.file.closed
if reopen:
file_loc = self.file.file.tell()
stored = self.file.storage.save(name=avail_name, content=self.file.file)
self.file = self.file.storage.open(stored)
if reopen:
... |
calatre/epidemics_network | models/other/ep2.py | Python | apache-2.0 | 3,929 | 0.000509 | # Universidade de Aveiro - Physics Department
# 2016/2017 Project - Andre Calatre, 73207
# "Simulation of an epidemic" - 25/3/2017
# The following code has been based on:
# Forest Fire Model from http://scipython.com/blog/the-forest-fire-model/
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import... | x, dy in neighbourhood:
if X[iy + dy, | ix + dx] == SICK and np.random.random() <= c:
X1[iy, ix] = SICK
break
# and once in a while, diseases appear out of nowhere
else:
if np.random.random() <= d:
X1[iy, ix] = SICK
... |
dunkhong/grr | grr/server/grr_response_server/flows/general/registry_init.py | Python | apache-2.0 | 1,568 | 0 | #!/usr/bin/env python
"""Load all flows so that they are visible in the registry."""
from __future__ import absolute_import
fro | m __future__ import division
from __future__ import unicode_literals
# pylint: disable=unused-imp | ort
# These imports populate the Flow registry
from grr_response_server.flows.general import administrative
from grr_response_server.flows.general import apple_firmware
from grr_response_server.flows.general import artifact_fallbacks
from grr_response_server.flows.general import ca_enroller
from grr_response_server.flo... |
rananda/cfme_tests | cfme/tests/containers/test_relationships.py | Python | gpl-2.0 | 4,007 | 0.002496 | from random import shuffle
import pytest
from utils import testgen
from utils.version import current_version
from cfme.web_ui import paginator, summary_title
from cfme.containers.pod import Pod, paged_tbl as pod_paged_tbl
from cfme.containers.provider import ContainersProvider, paged_tbl as provider_paged_tbl,\
... | _(self, obj, paged_tbl, polarion_id):
self.obj = obj
self.paged_tbl = paged_tbl
pytest.mark.polarion(polarion_id)(self)
TEST_OBJECTS = [
DataSet(ContainersProvider, provider_paged_tbl, 'CM | P-9851'),
DataSet(Container, container_paged_tbl, 'CMP-9947'),
DataSet(Pod, pod_paged_tbl, 'CMP-9929'),
DataSet(Service, service_paged_tbl, 'CMP-10564'),
DataSet(Node, node_paged_tbl, 'CMP-9962'),
DataSet(Replicator, replicator_paged_tbl, 'CMP-10565'),
DataSet(Image, image_paged_tbl, 'CMP-9980')... |
lmazuel/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2018_01_01/models/frontend_ip_configuration_py3.py | Python | mit | 4,846 | 0.003921 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | ion.
:type private_ip_address: str
:param private_ip_allocation_method: The Private IP allocation method.
Possible values are: 'Static' and 'Dynamic'. Possible values include:
'Static', 'Dynamic'
:type private_ip_allocation_method: str or
~azure.mgmt.network.v2018_01_01.models.IPAllocationMet... | of the subnet resource.
:type subnet: ~azure.mgmt.network.v2018_01_01.models.Subnet
:param public_ip_address: The reference of the Public IP resource.
:type public_ip_address:
~azure.mgmt.network.v2018_01_01.models.PublicIPAddress
:param provisioning_state: Gets the provisioning state of the publi... |
mc3k/graph-stats | datagen.py | Python | mit | 433 | 0.027714 | #!/usr/bin/env python
import sys, os, logging, urllib, datetime
def fetchtemp():
cmd = '/opt/vc/bin/vcgencmd measure_temp'
line = os.popen(cmd).readline().strip()
output = line.split('=')[1].split("' | ")[0]#+' C'
return output
format = "%Y-%m-%d,%H:%M:%S"
today = datetime.datetime.today()
s = today.strftime(format)
output = s+' '+fetchtemp()+'\n'
wit | h open('/home/pi/bin/plottemp/tempdata.dat', 'a') as f:
f.write(output)
|
robmcmullen/peppy | peppy/plugins/spelling.py | Python | gpl-2.0 | 958 | 0.004175 | # peppy Copyright (c) 2006-2010 Rob McMullen
# Licenced under the GPLv2; see http://peppy.flipturn.org for mo | re info
"""Spell checking provider
"""
import os, sys
import wx
from wx.lib.pubsub import Publisher
from peppy.yapsy.plugins import *
from peppy.lib.stcspellcheck import *
class SpellCheck(IPeppy | Plugin):
"""Plugin for spell check provider
This simple plugin provides the spelling checker for Fundamental mode.
"""
def activateHook(self):
Publisher().subscribe(self.getProvider, 'spelling.provider')
Publisher().subscribe(self.defaultLanguage, 'spelling.default_language')
d... |
MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-3.1/Lib/test/test_fileinput.py | Python | mit | 8,498 | 0.004001 | '''
Tests for fileinput module.
Nick Mathewson
'''
import unittest
from test.support import verbose, TESTFN, run_unittest
from test.support import unlink as safe_unlink
import sys, re
from io import StringIO
from fileinput import FileInput, hook_encoded
# The fileinput module has 2 interfaces: the FileInput class whi... | es(t1, t2, t3, t4)
def buffer_size_test(self, t1, t2, t3, t4, bs=0, round=0):
pat = re.compile(r'LINE (\d+) O | F FILE (\d+)')
start = 1 + round*6
if verbose:
print('%s. Simple iteration (bs=%s)' % (start+0, bs))
fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs)
lines = list(fi)
fi.close()
self.assertEqual(len(lines), 31)
self.assertEqual(lines[4], 'Line 5 of ... |
Chilledheart/chromium | tools/telemetry/telemetry/internal/platform/tracing_agent/chrome_tracing_agent.py | Python | bsd-3-clause | 3,194 | 0.007514 | # Copyright 2015 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.
import os
import shutil
import stat
import tempfile
from telemetry.internal.platform import tracing_agent
from telemetry.internal.platform.tracing_agent imp... | tartup_tracing.cc
_CHROME_TRACE_CONFIG_DIR_ANDROID = '/data/local/'
_CHROME_TRACE_CONFIG_FILE_NAME = 'chrome-trace-config.json'
class ChromeTracingAgent(tracing_agent.TracingAgent):
def __init__(self, platform_backend):
super(ChromeTracingAgent, self).__init__(platform_backend)
self._chrome_devtools_tracing... | _config_file = None
@property
def trace_config_file(self):
return self._trace_config_file
@classmethod
def RegisterDevToolsClient(cls, devtools_client_backend, platform_backend):
(chrome_devtools_tracing_backend.ChromeDevtoolsTracingBackend
.RegisterDevToolsClient(devtools_client_backend, plat... |
Orav/kbengine | kbe/src/lib/python/Lib/distutils/unixccompiler.py | Python | lgpl-3.0 | 13,419 | 0.00149 | """distutils.unixccompiler
Contains the UnixCCompiler class, a subclass of CCompiler that handles
the "typical" Unix-style command-line C compiler:
* macros defined with -Dname[=value]
* macros undefined with -Uname
* include search directories specified with -Idir
* libraries specified with -lllib
| * library search directories specified with -Ldir
* compile handled by 'cc' (or similar) executable with -c option:
compiles .c to .o
* link static library handled by 'ar' command (p | ossibly with 'ranlib')
* link shared library handled by 'cc -shared'
"""
import os, sys, re
from distutils import sysconfig
from distutils.dep_util import newer
from distutils.ccompiler import \
CCompiler, gen_preprocess_options, gen_lib_options
from distutils.errors import \
DistutilsExecError... |
sixhobbits/CorpusBuilder | corpusbuilder.py | Python | apache-2.0 | 1,608 | 0.00995 | #
# corpusbuilder.py
# Builds and extends a news corpus stored in SQLite
# Gareth Dwyer, 2016
# # # # # # # # # # # # # #
# standard imports
# third party imports
import newspaper
# local imports
import config
from article import Article
from common import log
from dbhelper import DBHelper
from publisher import Pu... | onfig.publishers_file)
def add_publishers(self, csv_file):
with open(csv_file) as f:
for line in f.read().strip().split("\n"):
try:
name, key, url = line.split(",")
publisher = Publisher(url.strip(), None, name.strip(),
| key.strip())
self.db.add_publisher(publisher)
except Exception as e:
log(e)
continue
return True
def process_article(self, a, publisher):
db = DBHelper(self.dbname)
article = Art... |
agry/NGECore2 | scripts/mobiles/tatooine/razorback_felspur.py | Python | lgpl-3.0 | 1,656 | 0.02657 | import sys
from services.spawn import MobileTemplate
from services.spawn import WeaponTemplate
from resources.datatables import WeaponType
from resources.datatables import Difficulty
from resources.datatables import Options
from java.util import Vector
def addTemplate(core):
mobileTemplate = MobileTemplate()
mobi... | nt(40)
mobileTemplate.setBoneType("Animal Bone")
mobileTemplate.setHideAmount(25)
mobileTemplate.setSocialGroup("zucca Boar")
mobileTemplate.setAssistRange(6)
mobileTemplate.setStalker(False)
mobileTemplate.setOptionsBitmask(Options.ATTACKABLE)
templates = Vector()
templates.add | ('object/mobile/shared_zucca_boar.iff')
mobileTemplate.setTemplates(templates)
weaponTemplates = Vector()
weapontemplate = WeaponTemplate('object/weapon/melee/unarmed/shared_unarmed_default.iff', WeaponType.UNARMED, 1.0, 6, 'kinetic')
weaponTemplates.add(weapontemplate)
mobileTemplate.setWeaponTemplateVector(weap... |
madmax983/h2o-3 | h2o-py/tests/testdir_algos/glrm/pyunit_benign_glrm.py | Python | apache-2.0 | 663 | 0.022624 | import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
from h2o.estimators.glrm import H2OGeneralizedLowRankEstimator
def glrm_benign():
print "Importing benign.csv data..."
benignH2O = h2o.upload_file(pyunit_utils.locate("smalldata/logreg/benign.csv"))
benignH2O.describe()
for i... | lrm_h2o.show()
if __name__ == "__main__":
pyunit_utils.standalone_test(glrm_ben | ign)
else:
glrm_benign()
|
raymondnijssen/QGIS | tests/src/python/test_core_additions.py | Python | gpl-2.0 | 1,581 | 0.000633 | # -*- coding: utf-8 -*-
"""QGIS Unit tests for core additions
.. note:: 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 later version.
"""
__a... | aEnumFromValue(1, QgsTolerance, False))
# do not provide an int
| with self.assertRaises(TypeError):
metaEnumFromValue(1)
# QgsMapLayer.LayerType is not a Q_ENUM
with self.assertRaises(ValueError):
metaEnumFromValue(QgsMapLayer.LayerType)
if __name__ == "__main__":
unittest.main()
|
catapult-project/catapult | dashboard/dashboard/services/issue_tracker_service_test.py | Python | bsd-3-clause | 11,440 | 0.002535 | # Copyright 2015 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 __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from six.moves import http_client
import json
i... | cess_NewBugReturnsId(self):
| service = issue_tracker_service.IssueTrackerService(mock.MagicMock())
service._ExecuteRequest = mock.Mock(return_value={'id': 333})
response = service.NewBug('Bug title', 'body', owner='someone@chromium.org')
bug_id = response['bug_id']
self.assertEqual(1, service._ExecuteRequest.call_count)
sel... |
uhuramedia/django-experiments | experiments/signals.py | Python | mit | 124 | 0.008065 | from django.dispatch import Signal
us | er_enr | olled = Signal(providing_args=['experiment', 'alternative', 'user', 'session'])
|
eLBati/odoo | addons/website_sale/models/sale_order.py | Python | agpl-3.0 | 10,830 | 0.006833 | # -*- coding: utf-8 -*-
import random
from openerp import SUPERUSER_ID
from openerp.osv import osv, orm, fields
from openerp.addons.web.http import request
class payment_transaction(orm.Model):
_inherit = 'payment.transaction'
_columns = {
# link with the sale order
'sale_order_id': fields.m... | ency', string='Default pricelist'),
}
def sale_product_domain(self, cr, uid, ids, context=None):
return [("sale_ok", "=", True)]
def sale_get_order(self, cr, uid, ids, force_create=False, code=None, update_pricelist=None, context=None):
sale_order_obj = self.po | ol['sale.order']
sale_order_id = request.session.get('sale_order_id')
sale_order = None
# create so if needed
if not sale_order_id and (force_create or code):
# TODO cache partner_id session
partner = self.pool['res.users'].browse(cr, SUPERUSER_ID, uid, context=... |
bradneuman/BlameOverTime | blameDBQuery.py | Python | mit | 8,282 | 0.006762 | # Copyright (c) 2014 Brad Neuman
# Common place to put useful re-usable queries into the blame database
def GetCurrentBlame(cursor):
"return a list of tuples of (filename, author, num_lines) that represents"
"the current count of lines from git blame, excluding merges"
cursor.execute('''
select * fro... | commitWork = repos[repo][topoOrder][2]
for author in commitWork:
# update the currentWork for this repo
currentWork[repo][author] = commitWork[author]
# now create the return data by summing up the current work
sumWork = {}
for sumRepo in currentWork:
... | sumWork[author] = ac + currentWork[sumRepo][author]
ret.append( (ts, repo, sha, sumWork) )
# increment index, and delete it if its not there anymore
repoIdx[repo] += 1
if repoIdx[repo] not in repos[repo]:
# print "finished merging %s" % repo
del repoIdx[r... |
pli3/Openwebif | plugin/controllers/views/web/sleeptimer.py | Python | gpl-2.0 | 5,627 | 0.01244 | #!/usr/bin/env python
##################################################
## DEPENDENCIES
import sys
import os
impo | rt os.path
try:
import builtins as builtin
except ImportError:
import __builtin__ as builtin
from os.path import getmtime, exists
import time
import types
from Cheetah.Version import MinCompatibleVersion as RequiredCheetahVersion
from Cheetah.Version import MinCompatibleVersionTuple as RequiredCheetahVersionTup... | import *
from Cheetah.NameMapper import NotFound, valueForName, valueFromSearchList, valueFromFrameOrSearchList
from Cheetah.CacheRegion import CacheRegion
import Cheetah.Filters as Filters
import Cheetah.ErrorCatchers as ErrorCatchers
##################################################
## MODULE CONSTANTS
VFFSL=value... |
mvaled/sentry | src/sentry/south_migrations/0425_auto__add_index_pullrequest_organization_id_merge_commit_sha.py | Python | bsd-3-clause | 107,666 | 0.008053 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
from sentry.utils.db import is_postgres
class Migration(SchemaMigration):
# Flag to indicate if this migration is too risky
# to run online and... | d_origins': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'client_id': ('django.db.models.fields.CharField', [], {'default': "'b5e160fcd8514738a779f4479d08838e12 | ad800c2f584169bc6952846c658eb4'", 'unique': 'True', 'max_length': '64'}),
'client_secret': ('sentry.db.models.fields.encrypted.EncryptedTextField', [], {'default': "'aa93f3afd028426d8faacc03cf4c1286c3e7629ac0d5492ab6035186a3f895f5'"}),
'date_added': ('django.db.models.fields.DateTimeField', [], ... |
iledarn/addons-yelizariev | res_users_signature/__openerp__.py | Python | lgpl-3.0 | 445 | 0.01573 | {
| 'name' : 'Signature templates for user emails',
'version' : '1.0.0',
'author' : 'IT-Projects LLC, Ivan Yelizariev',
'license': 'LGPL-3',
'category' : 'Social Network',
'website' : 'https://yelizariev.github.io',
'depends' : ['base'],
'data':[
'res_users_signature_views.xml',
... | ': False
}
|
takluyver/readthedocs.org | readthedocs/restapi/utils.py | Python | mit | 4,957 | 0.001412 | import hashlib
import logging
import requests
from builds.models import Version
from projects.utils import slugify_uniquely
from search.indexes import PageIndex, ProjectIndex, SectionIndex
from betterversion.better import version_windows, BetterVersion
log = logging.getLogger(__name__)
def sync_versions(project, ... | rsions.filter(verbose_name__in=verbose_names).update(type=type)
old_versions = {}
old_version_values = project.versions.values('identifier', 'verbose_name')
for vers | ion in old_version_values:
old_versions[version['verbose_name']] = version['identifier']
added = set()
# Add new versions
for version in versions:
version_id = version['identifier']
version_name = version['verbose_name']
if version_name in old_versions.keys():
if... |
Locu/chronology | metis/metis/core/execute/spark/executor.py | Python | mit | 8,583 | 0.009321 | # XXX(usmanm): PySpark in sensitive to modifying Python objects in functions
# like `map`. Please be wary of that! Using deepcopy everywhere will always
# work, but obviously is going to slow things down.
import json
import os
import re
import sys
import tempfile
import types
import zipfile
from copy import deepcopy
... | ils import get_properties_accessed_by_value
from metis.core.execute.utils import get_value
from metis.core.query.condition import Condition
IGNORE_FILES_RE = re.compile('^.*\.pyc$', re.I)
def _copy_lib_for_spark_workers(file_path):
zip_file = zipfile.ZipFile(file_path, 'w')
# TODO(usmanm): Zip only the minimum s... |
# Don't copy .pyc files to the lib file.
if IGNORE_FILES_RE.match(file_name):
continue
zip_file.write(os.path.join(root, file_name),
os.path.join(root.replace(app.config['PATH'], 'metis'),
file_name))
zip_file.close()
def _setup_pyspa... |
harshilasu/LinkurApp | y/google-cloud-sdk/lib/googlecloudsdk/compute/subcommands/snapshots/__init__.py | Python | gpl-3.0 | 353 | 0.002833 | # Copyright 2014 Google Inc. All Rights Reserved.
"""Commands for reading and manipulating snapshots."""
from googlecloudsdk.calliope import base
class Snapsh | ots(base.Group):
"""List, describe, and delete Google Compute Engine snapshots."""
Snapshots.detailed_help = {
'brief': 'List, describe, and delete Google Co | mpute Engine snapshots',
}
|
mycodeday/crm-platform | website_twitter/controllers/main.py | Python | gpl-3.0 | 1,936 | 0.006198 | from openerp.addons.web import http
from openerp.addons.web.http import request
from openerp.tools.translate import _
import json
class Twitter(http.Controller):
@http.route(['/twitter_reload'], type='json', auth="user", website=True)
def twitter_reload(self):
return request.website.fetch_favorite_twe... | tweets(self, limit=20):
key = request.website.twitter_api_key
secret = request.website.twitter_api_secre | t
screen_name = request.website.twitter_screen_name
cr, uid = request.cr, request.uid
debug = request.registry['res.users'].has_group(cr, uid, 'base.group_website_publisher')
if not key or not secret:
if debug:
return {"error": _("Please set the Twitter API Ke... |
jakobj/binary_network | meanfield.py | Python | bsd-2-clause | 6,477 | 0.000772 | # global imports
import numpy as np
import scipy.special as scsp
import scipy.optimize as scop
# local imports
import helper as bhlp
"""
ref Helias14:
Helias, Tetzlaff, Diesmann (2014) The Correlation Structure of
Local Neuronal Networks Intrinsically Results from Recurrent Dynamics
PLoS Comput Biol 10(1): e1003428
D... | c = np.linalg.solve(M, rhs)
C = np.array([[c[0], c[1]],
[c[1], c[2]]])
return C
def get_m_c_iter(self, mu0):
"""Calculate mean activity and mean correlations in a recurrent
network iteratively, using the improved meanfield approach from
Helias14
... | """
if np.shape(mu0) != (2,):
raise ValueError('Initial guess for mean activity needs to be given for both populations.')
Dmu = 1e10
Dc = 1e10
mu = mu0
C = self.C
while Dmu > 1e-15 and Dc > 1e-15:
mu_old = np.sum(mu)
c_old = np.sum(C)
... |
benjaminrigaud/django | tests/urlpatterns_reverse/tests.py | Python | bsd-3-clause | 37,955 | 0.003478 | # -*- coding: utf-8 -*-
"""
Unit tests for reverse URL lookups.
"""
from __future__ import unicode_literals
import sys
import unittest
import warnings
from django.contrib.auth.models import User
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured, ViewDoesNotExist
from django.core... | t-view', views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}),
('/other2/inner/42/37/', 'urlobject-view', 'nodefault', 'other-ns2', 'other-ns2:urlobject-view', views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}),
('/other1/inner/42/37/', 'urlobject-view', 'nodefault | ', 'other-ns1', 'other-ns1:urlobject-view', views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}),
# Nested namespaces
('/ns-included1/test3/inner/42/37/', 'urlobject-view', 'testapp', 'inc-ns1:test-ns3', 'inc-ns1:test-ns3:urlobject-view', views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}),
('/ns-... |
peguin40/zulip | zerver/lib/push_notifications.py | Python | apache-2.0 | 10,547 | 0.005404 | from __future__ import absolute_import
import random
from six import text_type
from typing import Any, Dict, Optional, SupportsInt
from zerver.models import PushDeviceToken, UserProfile
from zerver.models import get_user_profile_by_id
from zerver.lib.timestamp import timestamp_to_datetime
from zerver.decorator import... | ken
from zerver.lib.redis_utils import get_redis_client
from apns import APNs, Frame, Payload, SENT_BUFFER_QTY
import gcmclient
from django.conf import settings
import base64, binascii, logging, os, time
from functools import partial
# APNS error codes
ERROR_CODES = {
1: 'Processing error',
2: 'Missing devi... | in the certificate, looks like certificate is wrong. bail out.
4: 'Missing payload', # bail out, our message looks like empty
5: 'Invalid token size', # current token has wrong size, skip it and retry
6: 'Invalid topic size', # can not happen, we do not send topic, it is part of certificate. bail out.
... |
nens/qgispluginreleaser | setup.py | Python | gpl-3.0 | 1,483 | 0.000674 | from setuptools import setup
version = '1.2.dev0'
long_description = '\n\n'.join([
open('README.rst').read(),
open('CREDITS.rst').read(),
open('CHANGES.rst').read(),
])
install_requires = [
'setuptools',
'zest.releaser',
],
tests_require = [
'coverage',
'mock',
'nose',
]
... | ': [
],
'zest.releaser.releaser.after_checkout': [
'release_plugin = qgispluginreleaser.entry_point:create_zipfile',
],
'zest.releaser.prereleaser.middle': [
'prerelease_plugin = qgispluginreleaser.entry_point:fix_version',
],
'zest... | gin = qgispluginreleaser.entry_point:fix_version',
],
})
|
lowitty/eeep | quotation/migrations/0006_orderingcompany.py | Python | mit | 542 | 0.001845 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('quotation', '0005_auto_2015 | 0828_2207'),
]
operations = [
migrations.CreateModel(
name='Orderingcompany',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_ | created=True, primary_key=True)),
('name', models.CharField(max_length=1024)),
],
),
]
|
pmlrsg/arsf_tools | las13/las13.py | Python | gpl-3.0 | 9,486 | 0.013388 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
###########################################################
# This file has been created by ARSF Data Analysis Node and
# is licensed under the GPL v3 Licence. A copy of this
# licence is available to download with this file.
#################################################... | ['time','nreturns','nsamples','origin','offset','scanangle','classification','returnlocs','disint']
if keyword == 'time':
return pulse.time()
elif keyword == 'nreturns':
return pulse.nreturns()
elif keyword == 'nsamples':
r | eturn pulse.nsamples()
elif keyword == 'origin':
return list(pulse.originXYZ())
elif keyword == 'offset':
return list(pulse.offsetXYZ())
elif keyword == 'scanangle':
return pulse.scanangle()
elif keyword == 'classification':
return list(pul... |
pczerkas/tempest | tempest/api/compute/keypairs/base.py | Python | apache-2.0 | 1,347 | 0 | # Copyright 2015 Deutsche Telekom AG
# 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 requi... | ibuted 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.
from tempest.api.compute import base
class BaseK | eypairTest(base.BaseComputeTest):
"""Base test case class for all keypair API tests."""
_api_version = 2
@classmethod
def setup_clients(cls):
super(BaseKeypairTest, cls).setup_clients()
cls.client = cls.keypairs_client
def _delete_keypair(self, keypair_name):
self.client.d... |
mahabs/nitro | nssrc/com/citrix/netscaler/nitro/resource/config/aaa/aaagroup_vpntrafficpolicy_binding.py | Python | apache-2.0 | 7,121 | 0.037073 | #
# Copyright (c) 2008-2015 Citrix Systems, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | eption as e:
raise e
@classmethod
def get_filtered(cls, service, groupname, filter_) :
""" Use this API to fetch filtered set of aaagroup_vpntrafficpolicy_binding resources.
Filter string should be i | n JSON format.eg: "port:80,servicetype:HTTP".
"""
try :
obj = aaagroup_vpntrafficpolicy_binding()
obj.groupname = groupname
option_ = options()
option_.filter = filter_
response = obj.getfiltered(service, option_)
return response
except Exception as e:
raise e
@classmethod
def count(cls, s... |
steveandroulakis/mytardis | tardis/tardis_portal/templatetags/experimentstats.py | Python | bsd-3-clause | 497 | 0 | # | !/usr/bin/python
# -*- coding: utf-8 -*-
from django import template
from tardis.tardis_portal.models import Dataset_File
from django.db.models import Sum
register = template.Library()
@register.filter
def experiment_file_count(value):
return Dataset_File.objects.filter(dataset__experiments__pk=value).count()
#... | eriment_file_size(value):....
# return Dataset_File.objects.filter(dataset__experiment__pk=value).
# aggregate(Sum('size'))['size__sum']
|
cjellick/rancher | tests/validation/tests/v3_api/test_vmwarevsphere_driver.py | Python | apache-2.0 | 7,582 | 0.000396 | import pytest, copy
from .common import * # NOQA
RANCHER_VSPHERE_USERNAME = os.environ.get("RANCHER_VSPHERE_USERNAME", "")
RANCHER_VSPHERE_PASSWORD = os.environ.get("RANCHER_VSPHERE_PASSWORD", "")
RANCHER_VSPHERE_VCENTER = os.environ.get("RANCHER_VSPHERE_VCENTER", "")
RANCHER_VSPHERE_VCENTER_PORT = \
os.environ.g... | lse}
vsphereConfig = {
"cfgparam": ["disk.enableUUID=TRUE"],
"cloneFrom": CLONE_FROM,
"clo | udinit": "",
"contentLibrary": "",
"cpuCount": "4",
"creationType": "vm",
"customAttribute": ["203=CustomA", "204=CustomB"],
"datacenter": "/RNCH-HE-FMT",
"datastore": "",
"datastoreCluster": "",
"diskSize": "20000",
"folder": "/",
"hostsystem": "",
"memorySize": "16000",
... |
ArvinDevel/incubator-pulsar | pulsar-functions/instance/src/test/python/test_python_instance.py | Python | apache-2.0 | 2,008 | 0.00498 | #
# 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... | nguage governing permissions and limitations
# under the License.
#
# DEPENDENCIES: unittest2,mock
from contextimpl import ContextImpl
from python_instance import InstanceConfig
from mock import Mock
import Function_pb2
import log
import os
import unittest
class TestContextImpl(unittest.TestCase):
def setUp(s | elf):
log.init_logger("INFO", "foo", os.environ.get("PULSAR_HOME") + "/conf/functions-logging/console_logging_config.ini")
def test_context_publish(self):
instance_id = 'test_instance_id'
function_id = 'test_function_id'
function_version = 'test_function_version'
function_details = Function_pb2.F... |
Schizo/MediaBrowser | python/Temp/sandboxSignalMapper.py | Python | mit | 1,120 | 0.002679 | from PyQt4 import QtGui, QtCore
class Window(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.mapper = QtCore.QSignalMapper(self)
self.toolbar = self.addToolBar('Foo')
self.toolbar.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly)
for text in 'One... | t = 'Do Other'
self.edit.setText(t | ext)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.resize(300, 60)
window.show()
sys.exit(app.exec_()) |
tkf/railgun | tests/test_simple_copy.py | Python | mit | 1,929 | 0 | import copy
import unittest
from numpy.testing import assert_equal
from test_simobj import VectCalc
from arrayaccess import DefaultArrayAccess
class TestCopy(unittest.TestCase):
simclass = VectCalc
copyfunc = staticmethod(copy.copy)
clone_v1 = [20] * 10
def check_copy(self, name, value):
o... | 'v2', 'v3', 'some_random_attr']
def check_attrs_identity(self, name, clone, orig):
msg = 'clone.{0} is orig.{0}'.format(name)
assert getattr(clone, name) is getattr(orig, name), msg
class TestDeepCopy(TestCopy):
| copyfunc = staticmethod(copy.deepcopy)
clone_v1 = [10] * 10
def check_attrs_identity(self, name, clone, orig):
msg = 'clone.{0} is not orig.{0}'.format(name)
assert getattr(clone, name) is not getattr(orig, name), msg
class MixinTestCopy3D(object):
simclass = DefaultArrayAccess
check_... |
gislab-npo/gislab-web | server/webgis/mapcache/management/commands/mapcache_clean.py | Python | gpl-2.0 | 3,659 | 0.004646 | import os
import re
import hashlib
import datetime
from django.conf import settings
from django.core.management.base import BaseCommand
from webgis.mapcache import Disk
from webgis.app.models import Project_registry
from webgis.map.metadata_parser import MetadataParser
from webgis.map.project import get_last_project_... | stdir(project_cache_dir)
if project_publications:
for publish_tag in project_publications:
if int(publish_tag) != int(last_publish):
publish_pretty = datetime.datetime.fromtimestamp(int(publish_tag)).strftime("%d.%m.... | try:
cache.delete_project_cache(project_hash, publish_tag)
except:
cache_dir = os.path.join(project_cache_dir, publish_tag)
self.stderr.write("Failed to delete ... |
zsiciarz/variablestars.net | stars/models.py | Python | mit | 6,165 | 0.000162 | from django.db import models
from django.db.models import Count
from django.db.models.query import QuerySet
from django.urls import reverse
from django.utils.translation import ugettext_lazy as _
from model_utils import Choices
from observations.models import Observation
from observations.utils import jd_now
CONSTE... | (_("Maximum brightness"), null=True)
min_magnitude = models.FloatField(_("Minimum brightness"), null=True)
epoch = models.FloatFiel | d(_("Epoch"), null=True)
period = models.FloatField(_("Period"), null=True)
# denormalization
observations_count = models.PositiveIntegerField(default=0, editable=False)
objects = StarQuerySet.as_manager()
class Meta:
verbose_name = _("Variable star")
verbose_name_plural = _("Vari... |
TimothyBest/Django_Boilerplate | mysite/mysite/settings.py | Python | mit | 6,250 | 0.00192 | """
Django settings for composersCouch project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ... | re.context_processors.static',
'django.core.context_processors.tz',
'django.contrib.messages.context_processors.messages',
)
# over ride user defaults
ABSOLUTE_URL_OVERRIDES = {
'auth.user': lambda u: "/redirect/%s/" % u.username,
}
PIPELINE_ENABLED= True
PIPELINE_JS_COMPRESSOR = 'pipeline.compressors.yug... | ipts/foundation.min.js',
),
'output_filename': 'scripts/scripts.min.js',
'extra_context': {
'async': True,
},
}
}
ROBOTS_SITEMAP_URLS = [
'http://www.composerscouch.com/sitemap.xml',
]
GEOIP_DATABASE = os.path.join(STATIC_ROOT, 'GeoLiteCity.dat')
try:
# import ... |
appsembler/edx-platform | openedx/core/djangoapps/appsembler/multi_tenant_emails/tests/test_account_change_email.py | Python | agpl-3.0 | 5,779 | 0.004326 | """
Test cases to cover Accounts change email related to APPSEMBLER_MULTI_TENANT_EMAILS.
"""
import json
from unittest.mock import patch, Mock
from rest_framework import status
from rest_framework.test import APITestCase
from django.urls import reverse
from student.models import PendingEmailChange
from .test_utils... | mail=john_email, password=self.PASSWORD)
# John decides to use his corporate email address on Blue University as well.
self.assert_change_email(blue_john, red_john.email) # Use corporate email in anot | her organization
self.assert_confirm_change(blue_john, red_john.email) # Reuse Ahmed's email in another organization
|
TriumphLLC/FashionProject | modules/operators/wires/basic.py | Python | gpl-3.0 | 916 | 0.010804 | import bpy
# from math im | port pi, sin, cos
# from bpy_extras.view3d_utils import location_3d_to_region_2d
# from bgl import glEnable, glDisable, glBegin, glEnd, glVertex2f, | glVertex3f, glColor4f, glLineWidth, GL_LINE_STRIP, GL_LINE_STIPPLE, GL_BLEND, GL_LINE_LOOP, GL_POLYGON
# from fashion_project.modules.utils import mouse, get_point_abs_location
# from fashion_project.modules.utils.mathlib import deg2rad
from .proto import FP_WireProto
class FP_BasicWire(bpy.types.Operator, FP_Wire... |
morelab/weblabdeusto | server/src/weblab/exc.py | Python | bsd-2-clause | 550 | 0.010929 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2005 onwards University of Deusto
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
# This software consists of | contributions made by many individuals,
# listed below:
#
# Author: Pablo Orduña <pablo@ordunya.com>
#
from __future__ import print_function, unicode_literals
class WebLabError(Exception):
def __init_ | _(self,*args,**kargs):
Exception.__init__(self,*args,**kargs)
|
tkerola/chainer | tests/chainerx_tests/unit_tests/routines_tests/test_indexing.py | Python | mit | 8,519 | 0 | import unittest
import numpy
import pytest
from chainerx_tests import array_utils
import chainer.testing
import chainerx
import chainerx.testing
from chainerx_tests import dtype_utils
from chainerx_tests import op_utils
@op_utils.op_test(['native:0', 'cuda:0'])
@chainer.testing.parameterize_pytest('shape,indices',... | (-2, None, -1), slice(0, 3))),
((2, 3), (slice(-2, None, -1), slice(-3, None, -1))),
((2, 3), (slice(-2, None, -1), slice(None, None, -2))),
((2, 3), (slice(1, 2), slice(None, None, 1))),
((2, 3), (slice(1, 2), slice(None, None, 2))),
((2, 3, 4), (slice(1), slice(-2, 3), slice(1, None, -1))),
# ... | ng
((), (chainerx.newaxis,)),
((3,), (chainerx.newaxis,)),
((2, 3), (chainerx.newaxis, chainerx.newaxis)),
# mixed indexing - tuple indexing
((2, 3), (0, slice(1, 3))),
((4, 3), (slice(1, 3), 1)),
((2, 3, 4), (1, slice(2,), slice(1, 3))),
((2, 3), (1, chainerx.newaxis, slice(1, 3))),
... |
editorsnotes/editorsnotes | editorsnotes/auth/utils.py | Python | agpl-3.0 | 1,133 | 0.000883 | from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.conf import settings
from django.core.mail import send_mail
from django.core.urlresolvers import reverse
from django.utils.http import urls | afe_base64_encode
def send_activation_email(request, user):
b64uid = urlsafe_base64_encode(str(user.id).encode())
token_generator = PasswordResetTokenGenerator()
token = token_generator.make_token(user)
if user.is_active:
raise Exception('Will not send activation key to active user')
send... | Activate your Editors\' Notes account',
'This email was used to create an account at {site_url}.\n\n'
'To activate your account, visit the following link:\n\n'
'\t{activation_url}\n\n'
'If you did not request an account, please ignore this email.'.format(
site_url=request.bu... |
anhstudios/swganh | data/scripts/templates/object/mobile/shared_skreeg_hue.py | Python | mit | 576 | 0.041667 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
| from swgpy.object import *
def create(kernel):
result = Creature()
result.template = "object/mobile/shared_skreeg_hue.iff"
result.attribute_template_id = 9
result.stfName("monster_name","skreeg")
#### BEGIN MODIFICATIONS ####
result.setStringAttribute("radial_filename", "radials/player_pet.py")
result.opt... | result |
yukaritan/qtbot3 | qtbot3_service/plugins/4chan.py | Python | gpl-3.0 | 1,490 | 0.004027 | import re
import json
import requests
from util import irc
from util.handler_utils import cmdhook, authenticate, get_target
from qtbot3_common.types.message import Message
def scrape(board: str, filtertext: str):
try:
data = requests.get("http://boards.4chan.org/{board}/catalog".format(board=board)).tex... | et(message, nick)
r | eturn [irc.chat_message(target, line) for line in lines[:3]]
|
Aeva/voice | voice/engines/__init__.py | Python | gpl-3.0 | 650 | 0 |
# This file is part of Voice
#
# Voice is free sof | tware: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Voice is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without e... | URPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Waterworks. If not, see <http://www.gnu.org/licenses/>.
|
toni-heittola/pelican-btex | scholar/__init__.py | Python | mit | 23 | 0 | from | .scholar im | port *
|
dc3-plaso/plaso | tests/output/xlsx.py | Python | apache-2.0 | 5,608 | 0.010342 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""Tests for the XLSX output module."""
import os
import unittest
import zipfile
from xml.etree impor | t ElementTree
from plaso.containers import events
from plaso.formatters import interface as formatters_interface
from plaso.fo | rmatters import manager as formatters_manager
from plaso.lib import eventdata
from plaso.lib import timelib
from plaso.output import xlsx
from tests import test_lib as shared_test_lib
from tests.output import test_lib
class TestEvent(events.EventObject):
"""Event object used for testing."""
DATA_TYPE = u'test:xl... |
Enjoying-Learning/Enjoying | docs/config/jupyter_notebook_config.py | Python | mit | 22,055 | 0.002222 | # Configuration file for jupyter-notebook.
#------------------------------------------------------------------------------
# Configurable configuration
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
# Logg... | rmatters for %(asctime)s
# c.Application.log_datefmt = '%Y-%m-%d %H:%M | :%S'
# The Logging format template
# c.Application.log_format = '[%(name)s]%(highlevel)s %(message)s'
# Set the log level by value or name.
# c.Application.log_level = 30
#------------------------------------------------------------------------------
# JupyterApp configuration
#--------------------------------------... |
ajosephau/psma-gnaf-loader | main.py | Python | gpl-3.0 | 6,393 | 0.003441 | import logging, os
import psycopg2
# settings
database_name = 'postgres_database'
user = 'postgres_user'
password = 'some_password_here_lol'
port = 5432
host = 'postgres_host_normally_localhost'
path_to_gnaf_data = '/path/to/gnaf/data/'
# setup
logging.basicConfig(format='%(asctime)s %(levelname)s:%(message)s', leve... | name in enumerate(filenames):
absolute_path = os. | path.join(standard_data_path, filename)
standard_data_suffix = psv_file_suffix
table_name = filename.split('_', 1)[-1]
table_name = table_name.replace(standard_data_suffix, "")
logging.info("Importing file " + str(index + 1) + " of " + num_files + ": " + filename + " -... |
mitodl/lore | importer/tasks.py | Python | agpl-3.0 | 2,045 | 0.001956 | """
Celery tasks for import module.
"""
from __future__ import unicode_literals
import json
import logging
from django.conf import settings
import requests
from statsd.defaults.django import statsd
from lore.celery import async
from learningresources.api import update_xanalytics
from xanalytics import send_request, ... | uest(settings.XANALYTICS_URL + "/create", course_id)
check_for_results.apply_async(
kwargs={"token": token, "wait": 5, "a | ttempt": 1}, countdown=5)
@async.task
def check_for_results(token, wait, attempt):
"""
Check for xanalytics results for a course.
Args:
token (string): Token received from xanalytics server.
wait (int): Seconds to wait before repository.
attempt (int): Attempt number, so we don't t... |
cepheidxa/python | selinux_check/test_type.py | Python | gpl-3.0 | 4,408 | 0.002949 | import unittest
from type import Type
class TestType(unittest.TestCase):
def setUp(self):
self.__statement1 = [
'type name, attri1;',
' type name,attri1 ;',
'type name , attri1; ',
' type name ,attri1 ; ',
]
self.__statement2 = [
... | for statement in self.__statement1:
t = Type(statement)
self.ass | ertEqual(t.dump_statement(), 'type name, attri1;')
for statement in self.__statement2:
t = Type(statement)
self.assertEqual(t.dump_statement(), 'type name, attri1, attri2;')
for statement in self.__statement3:
t = Type(statement)
self.assertEqual(t.dump_st... |
hfp/tensorflow-xsmm | tensorflow/contrib/lookup/lookup_ops_test.py | Python | apache-2.0 | 106,863 | 0.011922 | # 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... | PythonArrays(self):
with self.cached_session():
default_val = -1
keys = ["brain", "salad", "surgery"]
values = [0, 1, 2]
table = lookup.HashTable(
lookup.KeyValueTensorInitializer(
keys, values, value_dtype=dtypes.int64),
default_val)
table.initializer... | n()
self.assertAllEqual(3, table.size().eval())
input_string = constant_op.constant(["brain", "salad", "tank"])
output = table.lookup(input_string)
result = output.eval()
self.assertAllEqual([0, 1, -1], result)
def testHashTableInitWithNumPyArrays(self):
with self.cached_session(... |
googlearchive/appengine-sqlite-guestbook-python | main.py | Python | apache-2.0 | 5,760 | 0.000174 | """A guestbook sample with sqlite3."""
import logging
import os
import jinja2
import sqlite3
import webapp2
from google.appengine.api import app_identity
from google.appengine.api import modules
from google.appengine.api import runtime
from google.appengine.api import users
from google.appengine.ext import ndb
JINJ... | s.path.dirname(__file__)),
extensions=['jinja2.ext.autoescape'])
DB_FILENAME = os.path.join('/tmp', 'guestbook.sqlite')
CREATE_TABLE_SQL = """\
CREATE TABLE IF NOT EXISTS guestbook
(id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, content VARCHAR)"""
SELECT_SQL = 'SELECT * FROM guestbook ORDER BY id DESC LIMI... | ""A hook function for de-registering myself."""
logging.info('shutdown_hook called.')
instance_id = modules.get_current_instance_id()
ndb.transaction(
lambda: ActiveServer.get_instance_key(instance_id).delete())
def get_connection():
"""A function to get sqlite connection.
Returns:
... |
GarmanGroup/RABDAM | rabdam/Subroutines/CalculateBDamage.py | Python | lgpl-3.0 | 35,945 | 0.001641 |
# RABDAM
# Copyright (C) 2020 Garman Group, University of Oxford
# This file is part of RABDAM.
# RABDAM 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... | _start = '%s%s' % (PDBdirec | tory, PDBcode)
pathToInput = '%s%s.cif' % (PDBdirectory, PDBcode)
# If directory with same name as PDBdirectory already exists in
# 'Logfiles' directory, user input is requested ('Do you want to
# overwrite the existing folder?'):
# yes = old PDBdirectory is ... |
ed-/solum | solum/objects/sqlalchemy/infrastructure_stack.py | Python | apache-2.0 | 1,686 | 0 | # Copyright 2014 - Numergy
#
# 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, s... | ss InfrastructureStack(sql.Base, abstract.InfrastructureStack):
"""Represent an infrastructure_stack in sqlalchemy."""
__tablename__ = 'infrastructure_stack'
__resource__ = 'infrastructure/stacks'
__table_args__ = sql.table_args()
id = sa.Column(sa.Integer, primary_key=True, autoincrement=True)
... | sa.String(36))
heat_stack_id = sa.Column(sa.String(36))
name = sa.Column(sa.String(100))
description = sa.Column(sa.String(255))
tags = sa.Column(sa.Text)
class InfrastructureStackList(abstract.InfrastructureStackList):
"""Represent a list of infrastructure_stacks in sqlalchemy."""
@classmeth... |
TomBaxter/waterbutler | tests/server/api/v0/test_zip.py | Python | apache-2.0 | 919 | 0.001088 | import io
import zipfile
from tornado import testing
from waterbutler.core import streams
from waterbutler.core.utils import AsyncIterator
from tests import utils
class TestZipHandler(utils.HandlerTestCase):
HOOK_PATH = 'waterbutler.server.api.v0.zip.ZipHandler._send_hook'
@testing.gen_test
def test_... | zipstream = streams.ZipStreamReader(AsyncIterator([('file.txt', stream)]))
self.mock_provider.zip = utils.MockCoroutine(return_value=zipstream)
resp = yield self.http_client.fetch(
self.get_url('/zip?provider=queenhub&path=/freddie.png' | ),
)
zip = zipfile.ZipFile(io.BytesIO(resp.body))
assert zip.testzip() is None
assert zip.open('file.txt').read() == data
|
raildo/nova | nova/tests/functional/api_sample_tests/test_floating_ips_bulk.py | Python | apache-2.0 | 3,805 | 0.000526 | # Copyright 2014 IBM Corp.
#
#
# 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... | def test_floating_ips_bulk_create(self):
response = self._do_post('os-floating-ips-bulk',
'floating-ips-bulk-create-req',
| {"ip_range": "192.168.1.0/24",
"pool": CONF.default_floating_pool,
"interface": CONF.public_interface})
subs = self._get_regexes()
self._verify_response('floating-ips-bulk-create-resp', subs,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.