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 |
|---|---|---|---|---|---|---|---|---|
zzqcn/wireshark | tools/wireshark_gen.py | Python | gpl-2.0 | 100,934 | 0.003616 | # -*- python -*-
#
# wireshark_gen.py (part of idl2wrs)
#
# Author : Frank Singleton ([email protected])
#
# | Copyright (C) 2001 Frank Singleton, Ericsson Inc.
#
# This file is a backend to "omniidl", used to generate "Wireshark"
# dissectors from CORBA IDL descriptions. The output language generated
# is "C". It will generate code to use the GIOP/IIOP get_CDR_XXX API.
#
# Please see packet-giop.h in Wireshark distro for A... | ttps://www.wireshark.org/
#
# Omniidl is part of the OmniOrb distribution, and is available at
# http://omniorb.sourceforge.net
#
# SPDX-License-Identifier: GPL-2.0-or-later
# Description:
#
# Omniidl Back-end which parses an IDL list of "Operation" nodes
# passed from wireshark_be2.py and generates "C" code f... |
conikuvat/shoottikala | shoottikala/__init__.py | Python | mit | 61 | 0 | default_app | _config = 'shoottikala.apps.ShoottikalaApp | Config'
|
micahflee/securedrop | securedrop/journalist_app/col.py | Python | agpl-3.0 | 3,437 | 0 | # -*- coding: utf-8 -*-
from flask import (Blueprint, redirect, url_for, render_template, flash,
request, abort, send_file, current_app)
from flask_babel import gettext
from | sqlalchemy.orm.exc import NoResultFound
import crypto_util
import store
from db import db_session, Submission
from journalist_app.decorators import login_required
from | journalist_app.forms import ReplyForm
from journalist_app.utils import (make_star_true, make_star_false, get_source,
delete_collection, col_download_unread,
col_download_all, col_star, col_un_star,
col_delete)
def ma... |
thorwhalen/ut | ml/feature_extraction/sequential_var_sets.py | Python | mit | 5,117 | 0.000782 | import itertools
import re
class PVar:
p = re.compile('^(.+)-(\d+)$|^(.+)$')
def __init__(self, var: str, i: int = 0):
self.var = var
self.i = i
def _tuple_for_ordering(self):
return (self.i, self.var)
def __eq__(self, other):
return self._tuple_for_ordering().__eq__... | def tuples(varnames, tuple_size: int = 2):
return map(VarSet, itertools.combinations(map(PVar, varnames), tuple_size))
@staticmethod
def markov_pairs(varnames):
return map(lambda v: VarSet(PVar(v[0], -1), PVa | r(v[1], 0)), itertools.product(varnames, varnames))
@staticmethod
def from_str(s):
return VarSet(*map(PVar.from_str, list(s[1:-1].split(','))))
# @classmethod
# def pairs(cls, vars):
# return list(itertools.combinations(vars, 2))
def extract_kps(df, kps):
# keep only elements of ... |
rasata/ansible | test/units/vars/test_variable_manager.py | Python | gpl-3.0 | 10,563 | 0.002083 | # (c) 2012-2014, Michael DeHaan <[email protected]>
#
# This file is part of Ansible
#
# Ansible 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) an... | ) with different
objects to modify the context under which variables are merged.
'''
v = VariableManager()
v._fact_cache = defaultdict(dict)
fake_loader = DictDataLoader({
# inventory1
'/etc/ansible/inventory1': """
[group2:children]
... | group_var = group_var_from_inventory_group1
[group2:vars]
group_var = group_var_from_inventory_group2
""",
# role defaults_only1
'/etc/ansible/roles/defaults_only1/defaults/main.yml': """
default_var: "default_var_from_defaults_only1"
... |
deepnn/coffee | covfefe/frameworks/torch/objectives.py | Python | mit | 1,703 | 0.014093 | from __future__ import absolute_import
from __future__ import print_function
import torch.nn as nn
def l1_loss(size_ave=True):
return nn.L1Loss(size_average=size_ave)
def mse_loss(size_ave=True):
return nn.MSELoss(size_average=size_ave)
def ce_loss(loss_weight=None, size_ave=True):
return nn.CrossEntrop... | ze_average=size_ave)
def smoothl1_loss(size_ave=True):
return nn.SmoothL1Loss(size_average=size_ave)
def sm_loss(size_ave=True):
return nn.SoftMarginLoss(size_average=size_ave)
def mlsm_loss(loss_weight=None, size_ave=True):
return nn.MultiLabelSoftMarginLoss(weight=loss_weight,size_average=size_ave)
de... | _ave=True):
return nn.MultiMarginLoss(p=p, margin=margin,
weight=loss_weight,size_average=size_ave)
|
IIITS/iiits.ac.in | iiits/migrations/0026_auto_20160426_1232.py | Python | mit | 1,265 | 0.003162 | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-04-26 12:32
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('iiits', '0025_auto_20160425_1937'),
]
operations = [
... | Field(max_length=100)),
('photo', models.ImageField | (upload_to='iiits/static/iiits/images/staff')),
('email', models.EmailField(max_length=254)),
],
),
migrations.CreateModel(
name='StaffDesignation',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, ... |
mviitanen/marsmod | mcp/runtime/getchangedsrc.py | Python | gpl-2.0 | 1,420 | 0.002817 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 3 02:10:23 2011
@author: IxxI
@version: v1.0
"""
import sys
import logging
from optparse import OptionParser
from commands import Commands, CLIENT, SERVER
from mcp import getchangedsrc_side
def main():
parser = OptionParser(version='MCP %s' % Commands.fullversion... | ', help='additional configuration file')
options, _ = parser.parse_args()
getchangedsrc(options.config, options.only_client, options.only_server)
def getchangedsrc(co | nffile, only_client, only_server):
try:
commands = Commands(conffile)
# client or server
process_client = True
process_server = True
if only_client and not only_server:
process_server = False
if only_server and not only_client:
process_client ... |
goll/flask_app | provisioning/files/wsgi.py | Python | mit | 109 | 0 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
from | dr import app
if __name | __ == '__main__':
app.run()
|
RRCKI/pilot | HPC/HPCJob.py | Python | apache-2.0 | 1,933 | 0.005691 |
import argparse
import logging
import os
import sys
from mpi4py import MPI
from pandayoda.yodacore import Yoda
from pandayoda.yodaexe import Droid
import logging
logging.basicConfig(level=logging.DEBUG)
def main(globalWorkDir, localWorkDir):
comm = | MPI.COMM_WORLD
mpirank = comm.Get_rank()
# Create separate working directory for each rank
| from os.path import abspath as _abspath, join as _join
curdir = _abspath (localWorkDir)
wkdirname = "rank_%s" % str(mpirank)
wkdir = _abspath (_join(curdir,wkdirname))
if not os.path.exists(wkdir):
os.makedirs (wkdir)
os.chdir (wkdir)
if mpirank==0:
yoda = Yoda.Yoda(globalWork... |
saurabh6790/frappe | frappe/desk/form/save.py | Python | mit | 1,676 | 0.03043 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe, json
from frappe.desk.form.load import run_onload
@frappe.whitelist()
def savedocs(doc, action):
"""save / submit / update doclist"""
try:
doc = frappe.get_doc... | ne):
"""cancel a doclist"""
try:
doc = frappe.get_doc(doctype, name)
if workflow_state_fieldname and workflow_state:
doc.set(workflow_state_field | name, workflow_state)
doc.cancel()
send_updated_docs(doc)
frappe.msgprint(frappe._("Cancelled"), indicator='red', alert=True)
except Exception:
frappe.errprint(frappe.utils.get_traceback())
raise
def send_updated_docs(doc):
from .load import get_docinfo
get_docinfo(doc)
d = doc.as_dict()
if hasattr(do... |
onespacemedia/cms-redirects | redirects/migrations/0002_auto_20160805_1654.py | Python | mit | 907 | 0.002205 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration | ):
dependencies = [
('redirects', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='redirect',
name= | 'regular_expression',
field=models.BooleanField(default=False, help_text=b"This will allow using regular expressions to match and replace patterns in URLs. See the <a href='https://docs.python.org/2/library/re.html' target='_blank'>Python regular expression documentation for details."),
),
m... |
denisenkom/django-sqlserver | tests/select_related_onetoone/tests.py | Python | mit | 11,118 | 0.001979 | from __future__ import unicode_literals
import django
from django.core.exceptions import FieldError
from django.test import SimpleTestCase, TestCase
from .models import (
AdvancedUserStat, Child1, Child2, Child3, Child4, Image, LinkedList,
Parent1, Parent2, Product, StatDetails, User, UserProfile, UserStat,
... | at.user.username, 'bob')
def test_follow_inheritance(self):
with self.assertNumQueries(1):
stat = UserStat.objects.select_related('user', 'advanceduserstat').get(posts=200)
self.assertEqual(stat.advanceduserstat.posts, 200)
self.assertEqual(stat.user.username, 'bob')
... | le_relation(self):
im = Image.objects.create(name="imag1")
p1 = Product.objects.create(name="Django Plushie", image=im)
p2 = Product.objects.create(name="Talking Django Plushie")
with self.assertNumQueries(1):
result = sorted(Product.objects.select_related("image"), key=lamb... |
wschoenell/chimera_imported_googlecode | src/chimera/core/tests/test_log.py | Python | gpl-2.0 | 1,086 | 0.007366 |
from chimera.core.chimeraobject import ChimeraObject
from chimera.core.manager import Manager
from chimera.core.exceptions import ChimeraException
from nose.tools import assert_raises
import chimera.core.log
import logging
log = logging.getLogger("chimera.test_log")
class TestLog (object):
def test_l... | self.log.exception("from except: wow, exception caught.")
raise ChimeraException("I'm a new Exception, sorry again")
manager = Manager()
manager.addClass(Simple, "simple")
simple = ma | nager.getProxy(Simple)
try:
simple.answer()
except ChimeraException, e:
assert e.cause != None
log.exception("wow, something wrong")
manager.shutdown()
|
google-research/tiny-differentiable-simulator | python/examples/whole_body_control/torque_stance_leg_controller.py | Python | apache-2.0 | 10,138 | 0.011442 | # Lint as: python3
"""A torque based stance controller framework."""
from __future__ import absolute_import
from __future__ import division
#from __future__ import google_type_annotations
from __future__ import print_function
import os
import sys
import inspect
currentdir = os.path.dirname(os.path.abspath(inspect.get... | #foot_positions_base_frame
self._friction_coeffs, #foot_friction_coeffs
desired_com_position, #desired_com_position
desired_com_velocity, #desired_com_velocity
desired_com | _roll_pitch_yaw, #desired_com_roll_pitch_yaw
|
DLR-SC/prov2bigchaindb | prov2bigchaindb/version.py | Python | apache-2.0 | 48 | 0 | __version__ | = '0.4.1'
__short_version__ = ' | 0.4'
|
intuition-io/insights | insights/sources/live/currencies.py | Python | apache-2.0 | 1,793 | 0.000558 | # -*- coding: utf-8 -*-
# vim:fenc=utf-8
'''
Insights Forex live source
--------------------------
:copyright (c) 2014 Xavier Bruhiere
:license: Apache 2.0, see LICENSE for more details.
'''
import time
import pandas as pd
import dna.logging
import intuition.data.forex as forex
log = dna.logging.logger(__n... | get('retry', 10)
self.forex = forex.TrueFX(pairs=pairs)
self.forex.connect()
def get_data(self, sids):
| while True:
rates = self.forex.query_rates()
if len(rates.keys()) >= len(sids):
log.debug('Data available for {}'.format(rates.keys()))
break
log.debug('Incomplete data ({}/{}), retrying in {}s'.format(
len(rates.keys()), len(sids),... |
PXke/invenio | invenio/legacy/bibauthorid/templates.py | Python | gpl-2.0 | 91,185 | 0.007052 | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2011, 2013 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your opt... | s.append(CFG_BIBAUTHORID_AUTHOR_TICKET_ADMIN_EMAIL)
message = self._(transaction_message_dict[key] % tuple(args))
h('<div id="aid_notification_' + key + '" class="ui-widget ui-alert">')
h(' <div style="%s margin-top: 20px; padding: 0pt 0.7em;" class="ui-state-highlight ui-corner-a... | an style="float: left; margin-right: 0.3em;" class="ui-icon ui-icon-info"></span>')
h(' <strong>%s</strong> %s' % (teaser, message))
if show_close_btn:
h(' <span style="float:right; margin-right: 0.3em;"><a rel="nofollow" href="#" class="aid_close-notify" style="border-sty... |
OCA/partner-contact | partner_contact_address_default/tests/test_partner_contact_address_default.py | Python | agpl-3.0 | 1,714 | 0.00175 | # Copyright 2020 Tecnativa - Carlos Dauden
# Copyright 2020 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo.tests import common
class TestPartnerContactAddressDefault(common.TransactionCase):
def setUp(self):
super().setUp()
self.Partner = ... | )
def test_contact_address_default(self):
self.partner.partner_delivery_id = self.partner
self.partner.partner_invoice_id = self.partner
res = self.partner.address_get()
self.assertEqual(res["delivery"], self.partner.id)
self.ass | ertEqual(res["invoice"], self.partner.id)
self.partner_child_delivery2.partner_delivery_id = self.partner_child_delivery2
self.partner_child_delivery2.partner_invoice_id = self.partner_child_delivery2
res = self.partner_child_delivery2.address_get()
self.assertEqual(res["delivery"], sel... |
mulkieran/blivet | blivet/formats/prepboot.py | Python | gpl-2.0 | 3,650 | 0.001644 | # prepboot.py
# Format class for PPC PReP Boot.
#
# Copyright (C) 2009 Red | Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program i | s distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties 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... |
bckwltn/SickRage | sickbeard/processTV.py | Python | gpl-3.0 | 20,557 | 0.006227 | # Author: Nic Wolfe <[email protected]>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of SickRage.
#
# SickRage 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,... | if not process_method:
process_method = sickbeard.PROCESS_METHOD
re | sult.result = True
#Don't Link media when the media is extracted from a rar in the same path
if process_method in ('hardlink', 'symlink') and videoInRar:
result.result = process_media(path, videoInRar, nzbName, 'move', force, is_priority, result)
delete_files(path, rarContent, result)
f... |
zjuela/LapSRN-tensorflow | tensorlayer/files.py | Python | apache-2.0 | 33,051 | 0.003906 | #! /usr/bin/python
# -*- coding: utf8 -*-
import tensorflow as tf
import os
import numpy as np
import re
import sys
import tarfile
import gzip
import zipfile
from . import visualize
from . import nlp
import pickle
from six.moves import urllib
from six.moves import cPickle
from six.moves import zip
from tensorflow.pyt... | xpected in main().
# (It doesn't matter how we do this as long as we can read them again.)
X_train = np.asarray(X_train, dtype=np.float32)
y_train = np.a | sarray(y_train, dtype=np.int32)
X_val = np.asarray(X_val, dtype=np.float32)
y_val = np.asarray(y_val, dtype=np.int32)
X_test = np.asarray(X_test, dtype=np.float32)
y_test = np.asarray(y_test, dtype=np.int32)
return X_train, y_train, X_val, y_val, X_test, y_test
def load_cifar10_dataset(shape=(-1, ... |
TheBatUNT/thebat | tts1.py | Python | apache-2.0 | 9,411 | 0.025183 | #!/usr/bin/python
from espeak import espeak
import MySQLdb
import serial
import time
import os.path
import math
from espeak import core as espeak_core
timerSeconds = 2 #Time between command repeats itself in seconds
timerProximity = 1
wallElapsed = 0 #starting value for elapsed
objectElapsed = 0
openingBothElapsed = ... | stanceL > 144 and distanceR > 144 :
if openingBothElapsed == 0:
say("Opening o | n the right and Left")
openingBothTimerStart = time.time()
openingBothElapsed = 1
else:
openingBothElapsed = time.time() - openingBothTimerStart
if openingBothElapsed > timerSeconds:
openingBothElapsed = 0
if distanceL > 144 and distanceR < 120 :
... |
vinegret/youtube-dl | youtube_dl/extractor/umg.py | Python | unlicense | 3,414 | 0.000879 | # coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import (
int_or_none,
parse_filesize,
parse_iso8601,
)
class UMGDeIE(InfoExtractor):
IE_NAME = 'umg:de'
IE_DESC = 'Universal Music Deutschland'
_VALID_URL = r'https?://(?:www\.)?universal-mu... | t_or_none(f.get('width')),
'h | eight': int_or_none(f.get('height')),
'filesize': parse_filesize(f.get('fileSize')),
}
f_type = f.get('type')
if f_type == 'Image':
thumbnails.append(fmt)
elif f_type == 'Video':
format_id = f.get('formatId')
... |
hlange/LogSoCR | .waf/waflib/Errors.py | Python | agpl-3.0 | 1,682 | 0.032105 | #!/usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2010-2016 (ita)
"""
Exceptions used in the Waf code
"""
import traceback, sys
class WafError(Exception):
"""Base class for all Waf errors"""
def __init__(self, msg='', ex=None):
"""
:param msg: error message
:type msg: string
:param ex: exception causi... | ts the error messages from the tasks that failed"""
lst = ['Build failed']
for tsk in self.tasks:
txt | = tsk.format_error()
if txt: lst.append(txt)
return '\n'.join(lst)
class ConfigurationError(WafError):
"""Configuration exception raised in particular by :py:meth:`waflib.Context.Context.fatal`"""
pass
class TaskRescan(WafError):
"""Task-specific exception type signalling required signature recalculations"""
... |
lene/tavsiye | test_recommender.py | Python | gpl-3.0 | 6,800 | 0.000735 | from compare_sets import jaccard_coefficient, similarity_matrix, similar_users, recommendations
from alternative_methods import asymmetric_similarity, minhash_similarity, minhashed
from read_file import read_file
from minhash import minhash
import unittest
from functools import reduce
__author__ = 'lene'
class Test... | {1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0, 5: 1.0}
}
)
def test_similar_users(self):
similarity = similarity_matrix({1: {'a'}, 2: {'a'}})
sel | f.assertEqual(similar_users(1, similarity, 0.2), [2])
self.assertEqual(similar_users(2, similarity, 0.2), [1])
self.assertEqual(similar_users(1, similarity, 1.0), [2])
similarity = similarity_matrix({1: {'a'}, 2: {'b'}})
self.assertEqual(similar_users(1, similarity, 0.2), [])
s... |
aquametalabs/django-snailtracker | django_snailtracker/utils.py | Python | bsd-3-clause | 965 | 0.001036 | import logging
from django.db.models.signals import post_init, post_save, post_delete
from django_snailtracker.models import (snailtracker_post_init_hook,
snailtracker_post_save_hook, snailtracker_post_delete_hook)
from django_snailtracker.he | lpers import snailtracker_enabled
from django_snailtracker.sites import snailtracker_site
logger = logging.getLogger(__name__)
def register(obj_def):
if snailtracker_enabled():
if obj_def._meta.db_table not in snailtracker_site.registry:
| logger.debug('Registering %s' % obj_def._meta.db_table)
post_init.connect(snailtracker_post_init_hook, sender=obj_def,)
post_save.connect(snailtracker_post_save_hook, sender=obj_def,)
post_delete.connect(snailtracker_post_delete_hook, sender=obj_def,)
snailtracker_si... |
azumimuo/family-xbmc-addon | plugin.video.salts/salts_lib/kodi.py | Python | gpl-2.0 | 4,540 | 0.007489 | """
SALTS XBMC Addon
Copyright (C) 2015 tknorris
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
T... | path(path):
return xbmc.translatePath(path).decode('utf-8')
def set_setting(id, value):
if not isinstance(value, basestring): value = str(value)
addon.setSetting(id, value)
def get_version():
return addon.getAddonInfo('version')
def get_id():
return addon.getAddonInfo('id')
def get_name():
r... | rlencode(queries)
except UnicodeEncodeError:
for k in queries:
if isinstance(queries[k], unicode):
queries[k] = queries[k].encode('utf-8')
query = urllib.urlencode(queries)
return sys.argv[0] + '?' + query
def end_of_directory(cache_to_disc=True):
xbmcplugin.end... |
yokose-ks/edx-platform | common/lib/logsettings.py | Python | agpl-3.0 | 5,212 | 0 | import os
import platform
import sys
from logging.handlers import SysLogHandler
LOG_LEVELS = ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']
def get_logger_config(log_dir,
logging_env="no_env",
tracking_filename="tracking.log",
edx_filename="edx.log... | f local_loglevel not in LOG_LEVELS:
local_loglevel = 'INFO'
if console_loglevel is None or console_loglevel not in LOG_LEVELS:
console_loglevel = 'DEBUG' if debug else 'INFO'
if service_variant is None:
# default to a blank string so that if SERVICE_VARIANT is not
# set we will... | hostname = platform.node().split(".")[0]
syslog_format = ("[service_variant={service_variant}]"
"[%(name)s][env:{logging_env}] %(levelname)s "
"[{hostname} %(process)d] [%(filename)s:%(lineno)d] "
"- %(message)s").format(service_variant=service_vari... |
Glorfindelrb/pyBPMN20engine | HumanInteraction/models.py | Python | mit | 3,637 | 0.005784 | # -*- coding: utf-8 -*-
# The MIT License (MIT)
# Copyright (c) 2014 Roland Bettinelli
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... | is a typical “workflow” Task where a human performer performs the Task with the assistance of a
software application. The lifecycle of the Task is managed by a software component (called task manager) and is
typically executed in the context of a Process.
'''
def __init__(self, id , implementation='##u... | )
This attribute specifies the technology that will be used to implement the User Task.
Valid values are "##unspecified" for leaving the implementation technology open, "##WebService"
for the Web service technology or a URI identifying any other technology or coordination protocol.
... |
JuliBakagianni/CEF-ELRC | metashare/repository/editor/manual_admin_registration.py | Python | bsd-3-clause | 11,138 | 0.004669 | '''
This file contains the manually chosen admin forms, as needed for an easy-to-use
editor.
'''
from django.contrib import admin
from django.conf import settings
from metashare.repository.editor import admin_site as editor_site
from metashare.repository.editor.resource_editor import ResourceModelAdmin, \
LicenceM... | nInfoType_model, metadataInfoType_model, \
communicationInfoType_model, validationInfoType_model, \
relationInfoType_model, foreseenUseInfoType_model, \
corpusMediaTypeType_model, corpusTextInfoType_model, \
corpusVideoInfoType_model, textNumericalFormatInfoType_model, \
videoClassificationInfoType_... | extNumericalInfoType_model, \
corpusTextNgramInfoType_model, languageDescriptionInfoType_model, \
languageDescriptionTextInfoType_model, actualUseInfoType_model, \
languageDescriptionVideoInfoType_model, \
languageDescriptionImageInfoType_model, \
lexicalConceptualResourceInfoType_model, \
lexic... |
ujenmr/ansible | lib/ansible/plugins/doc_fragments/aws_credentials.py | Python | gpl-3.0 | 1,170 | 0.001709 | # -*- coding: utf-8 -*-
# Copyright: (c) 2017, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
class ModuleDocFragment(object):
# inventory cache
DOCUMENTATION = r'''
options:
aws_profile:
description: The AWS profile
type: str
alia... | EY
aws_secret_key:
description: The AWS secret key that corresponds to the access key.
type: str
env:
- name | : AWS_SECRET_ACCESS_KEY
- name: AWS_SECRET_KEY
- name: EC2_SECRET_KEY
aws_security_token:
description: The AWS security token if using temporary access and secret keys.
type: str
env:
- name: AWS_SECURITY_TOKEN
- name: AWS_SESSION_TOKEN
- name: EC2_SECURITY_TOKEN
region:
... |
dyninc/dyn-python | dyn/mm/session.py | Python | bsd-3-clause | 3,590 | 0 | # -*- coding: utf-8 -*-
"""This module implements an interface to a DynECT REST Session. It provides
easy access to all other functionality within the dynect library via
methods that return various types of DynECT objects which will provide their
own respective functionality.
"""
import locale
# API Libs
from dyn.core ... | lf, args, method, uri):
"""Prepare MM arguments which need to be packaged differently depending
on the specified HTTP method
"""
a | rgs, content, uri = super(MMSession, self)._prepare_arguments(args,
method,
uri)
if 'apikey' not in args:
args['apikey'] = self.apikey
if method == '... |
nagyistoce/devide | modules/writers/stlWRT.py | Python | bsd-3-clause | 2,674 | 0.006358 | # $Id$
from module_base import ModuleBase
from module_mixins import FilenameViewModuleMixin
import module_utils
import vtk
class stlWRT(FilenameViewModuleMixin, ModuleBase):
def __init__(self, module_manager):
# call parent constructor
ModuleBase.__init__(self, module_manager)
# need to... | self._writer = vtk.vtkSTLWriter()
self._writer.SetInput(self._tf.GetOutput())
# sorry about this, but the files get REALLY big if we write them
# in ASCII - I'll make this a gui option later.
#self._writer.SetFileTypeToBinary()
# following is the standard way of connecting up th... | ld do this for all objects in
mm = self._module_manager
for textobj in (('Cleaning data', self._cleaner),
('Converting to triangles', self._tf),
('Writing STL data', self._writer)):
module_utils.setup_vtk_object_progress(self, textobj[1... |
LuckyGeck/dedalus | worker/engine.py | Python | mit | 5,052 | 0.002375 | import os
import traceback
from threading import Thread, Event
from common.models.task import TaskInfo
from common.models.state import TaskState
from worker.backend import WorkerBackend
from worker.executor import ExecutionEnded, Executors
from worker.resource import Resources
class TaskExecution(Thread):
def __... | resources:
if self.user_stop.is_set():
break
try:
resource.ensure()
except Exception as ex:
print(ex)
prep_error = str(ex)
break
task_info = self.backend.read_task_info(self.task_id)
task_... | _stop.is_set()
)
self.backend.write_task_info(self.task_id, task_info)
return prep_error is None
def execute_task(self):
task_info = self.backend.read_task_info(self.task_id)
task_info.exec_stats.start_execution()
self.backend.write_task_info(self.task_id, task_info)... |
jmckib/soundcurl | setup.py | Python | apache-2.0 | 490 | 0.002041 | f | rom setuptools import setup
setup(
name='soundcurl',
version='0.1.0',
description='A command line utility for downloading songs from SoundCloud.',
author='Jeremy McKibben-Sanders',
author_email='[email protected]',
url='https://github.com/jmckib/soundcurl',
package_dir={'': 'src'}... | l_requires=['beautifulsoup4==4.2.1', 'mutagen==1.21'],
)
|
thaim/ansible | lib/ansible/module_utils/hetzner.py | Python | mit | 4,484 | 0.002453 | # -*- coding: utf-8 -*-
# This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own lic... | headers = {"Content-type": "application/x-www-form-urlencoded"}
data = dict(
active_server_ip=value,
)
result, erro | r = fetch_url_json(
module,
url,
method='POST',
timeout=timeout,
data=urlencode(data),
headers=headers,
accept_errors=['FAILOVER_ALREADY_ROUTED']
)
if error is not None:
return value, False
else:
return r... |
SaturdayNeighborhoodHealthClinic/osler | referral/models.py | Python | gpl-3.0 | 6,199 | 0 | """Data models for referral system."""
from __future__ import unicode_literals
from builtins import map
from django.db import models
from django.core.urlresolvers import reverse
from pttrack.models import (ReferralType, ReferralLocation, Note,
ContactMethod, CompletableMixin,)
from followup... | for referral in referrals)
if all_successful:
referral_status_output = (dict(Referral.REFERRAL_STATUSES)
| [Referral.STATUS_SUCCESSFUL])
else:
# Determine referral status based on the last FQHC referral
referral_status_output = (dict(Referral.REFERRAL_STATUSES)
[referrals.last().status])
else:
referral_st... |
bdusell/romaji-cpp | test/run_test.py | Python | mit | 1,881 | 0.00638 | #!/usr/bin/env python
import sys, re, subprocess
def usage():
print '''\
Usage: %s <program name> <test file>
''' % sys.argv[0]
def escape(s, code):
return '\033[%sm%s\033[0m' % (code, s)
def red(s):
return escape(s, 91)
def green(s):
return escape(s, 92)
def main():
try:
prog_name, fi... | raw_out.rstrip()))
| failures += 1
elif expected_out == actual_out:
test_pass('%s: %s == %s' % (text_in, expected_out, actual_out))
passes += 1
else:
test_fail('%s: %s != %s' % (text_in, expected_out, actual_out))
... |
ilveroluca/pydoop | pydoop/test_support.py | Python | apache-2.0 | 3,704 | 0 | # BEGIN_COPYRIGHT
#
# Copyright 2009-2015 CRS4.
#
# 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 ... | turn "number of keys differs"
keys = sorted(c1)
if sorted(c2) != keys:
return "key lists are different"
for k in keys:
if c1[k] != c2[k]:
return "values are different for key %r (%r != %r)" % (
k, c1[k], c2[k]
| )
class LocalWordCount(object):
def __init__(self, input_path, min_occurrence=0):
self.input_path = input_path
self.min_occurrence = min_occurrence
self.__expected_output = None
@property
def expected_output(self):
if self.__expected_output is None:
... |
byDimasik/Magic_Ping | client.py | Python | gpl-3.0 | 2,642 | 0.002027 | import socket
import argparse
import sys
import magic_ping
import os
import settings
import signal
import logging
import struct
logging.basicConfig(format=u'%(levelname)-8s [%(asctime)s] %(message)s', level=logging.DEBUG, filename=u'client.log')
# Обработка CTRL+C
def signal_handler(signal, frame):
print("\nSTOP... | d_ping(s, address, ID, bytes(0), packet_number=0)
logging.debug("Packets sent: %d" % packet_number)
print("send:", packet_number)
file.close()
client_address, packet_number, checksum = magic_ping.receive_ping(s, ID, {}) # проверяем корректность передачи
if checksum and settings.md5_checksum(file_n... | cksum.decode():
logging.warning("Файл передался с ошибками!!!")
print("Файл передался с ошибками!!!")
s.close()
|
ganmk/python-prctice | py-日志.py | Python | mit | 411 | 0 | import logging
from logging.handlers import TimedRotatingFileHandler
log = logging.getLogger()
file_nam | e = "./test.log"
logformatter = logging.Formatter('%(asctime)s [%(levelname)s]|%(message)s')
loghandle = TimedRotatingFileHandler(file_name, 'midnight', 1, 2)
loghandle.setFormatter(logformatter)
loghandle.suffix = '%Y%m%d'
log.addHandler(loghandle)
log.setLevel(logging.DEBUG)
log.debug("init successf | ul")
|
youfoh/webkit-efl | Tools/Scripts/webkitpy/layout_tests/port/qt.py | Python | lgpl-2.1 | 8,302 | 0.00265 | # Copyright (C) 2010 Google 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:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the ... | e case of building with CONFIG+=force_static_libs_as_shared.
if self.operating_system() == 'mac':
frameworks = glob.glob(os.path.join(self._build_path('lib'), '*.framework'))
return [os.path.join(framework, os.path.splitext(os.path.basename(framework))[0]) for fr | amework in frameworks]
else:
suffix = 'dll' if self.operating_system() == 'win' else 'so'
return glob.glob(os.path.join(self._build_path('lib'), 'lib*.' + suffix))
@memoized
def qt_version(self):
version = ''
try:
for line in self._executive.run_comma... |
pylover/timesheet | timesheet/commands/start.py | Python | mit | 1,244 | 0.002412 | # -*- coding: utf-8 -*-
from timesheet.commands import Command
from timesheet.models import Subject, Task, DBSession
from timesheet.commands.completers import subject_completer, task_completer
import argparse
__author__ = 'vahid'
class StartCommand(Command):
name = 'start'
description = 'Starts a task'
@... | REMAINDER, metavar='task', default=[], choices=[],
help="Task title.").completer = task_completer
def do_job(self):
active_task = Task.get_active_task()
if active_task:
print('You have an active task: %s' % active_task)
answer | = input("Do you want to terminate the currently active task ([y]/n)? ")
if not answer or answer.lower() == 'y':
active_task.end()
else:
return
subject = Subject.ensure(self.args.subject)
task = Task(title=' '.join(self.args.task))
subject.... |
yangdongsheng/autotest | client/base_sysinfo.py | Python | gpl-2.0 | 15,544 | 0.002059 | import os, shutil, re, glob, subprocess, logging, gzip
from autotest.client.shared import log, software_manager
from autotest.client.shared.settings import settings
from autotest.client import utils
_LOG_INSTALLED_PACKAGES = settings.get_value('CLIENT', 'log_installed_packages',
... | FAULT_COMMA | NDS_TO_LOG_PER_TEST = []
_DEFAULT_COMMANDS_TO_LOG_PER_BOOT = [
"lspci -vvn", "gcc --version", "ld --version", "mount", "hostname",
"uptime",
]
_DEFAULT_COMMANDS_TO_LOG_BEFORE_ITERATION = []
_DEFAULT_COMMANDS_TO_LOG_AFTER_ITERATION = []
_DEFAULT_FILES_TO_LOG_PER_TEST = []
_DEFAULT_FILES_TO_LOG_PER_BOOT = [
... |
michaelBenin/sqlalchemy | test/orm/test_unitofworkv2.py | Python | mit | 55,891 | 0.004938 | from sqlalchemy.testing import eq_, assert_raises, assert_raises_message
from sqlalchemy import testing
from sqlalchemy.testing import engines
from sqlalchemy.testing.schema import Table, Column
from test.orm import _fixtures
from sqlalchemy import exc
from sqlalchemy.testing import fixtures
from sqlalchemy import Inte... | 1'), Address(email_address='a2')
u1 = User(name='u1', addresses=[a1, a2])
sess.add(u1)
sess.flush()
sess.delete(u1)
self.assert_sql_execution(
testing.db,
sess.flush,
CompiledSQL(
| "UPDATE addresses SET user_id=:user_id WHERE "
"addresses.id = :addresses_id",
lambda ctx: [{'addresses_id': a1.id, 'user_id': None}]
),
CompiledSQL(
"UPDATE addresses SET user_id=:user_id WHERE "
"addresses... |
oostende/blackhole-2 | mytest.py | Python | gpl-2.0 | 17,187 | 0.026473 | import sys, os
if os.path.isfile("/usr/lib/enigma2/python/enigma.zip"):
sys.path.append("/usr/lib/enigma2/python/enigma.zip")
from Tools.Profile import profile, profile_final
profile("PYTHON_START")
import Tools.RedirectOutput
import enigma
import eConsoleImpl
import eBaseImpl
enigma.eTimer = eBaseImpl.eTimer
enigma... | elf.current_dialog.returnValue
if self.current_dialog.isTmp:
self.current_dialog.doClose()
# dump(self.current_dialog)
del self.current_dialog
else:
del self.current_dialog.callback
self.popCurrent()
if callback is not None:
callback(*retval)
def execBegin(self, firs | t=True, do_show = True):
assert not self.in_exec
self.in_exec = True
c = self.current_dialog
# when this is an execbegin after a execend of a "higher" dialog,
# popSummary already did the right thing.
if first:
self.instantiateSummaryDialog(c)
c.saveKeyboardMode()
c.execBegin()
# when execBegin ... |
google-code/billreminder | src/lib/scheduler.py | Python | mit | 2,973 | 0.003027 | # -*- coding: utf-8 -*-
import time, datetime
from lib import i18n
SC_ONCE = _("Once")
SC_WEEKLY = _("Weekly")
SC_MONTHLY = _("Monthly")
def time_from_calendar(calendar):
''' Return a time object representing the date. '''
day = calendar[2]
month = calendar[1] + 1
year = calendar[0]
# Create date... | % 12 + 1
nextMonthYear = year + ((month) / 12)
goback = datetime.timedelta(seconds=1)
# Create datetime object with a timestamp corresponding the end of day
| nextMonth = datetime.datetime(nextMonthYear, nextMonth, 1, 0, 0, 0)
ret = nextMonth - goback
# Convert to timestamp
ret = timestamp_from_datetime(ret)
return ret
def get_alarm_timestamp(alertDays, alertTime, origDate=None):
''' Calculate alarm timestamp. '''
if not origDate:
origDate... |
danille/ClothesAdvisor-server | main/scripts/color.py | Python | apache-2.0 | 354 | 0.002825 | class Color:
def __init__(self, name, hue, saturation, value):
self.name = name
self.hue = hue
self.saturation = saturation
self.value = value
| def __str__(self):
return 'Hue: {0}, Saturation: {1}, Value: {2}'.format(self.hue, self.saturation, self.value)
de | f get_name(self):
return self.name
|
brooksc/bugherd | setup.py | Python | mit | 4,028 | 0.005214 | from setuptools import setup, find_packages # Always prefer setuptools over distutils
from code | cs import open # To use a consistent encoding
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the relevant file
# with open(path.join(here, 'DESCRIPTION.rst'), encoding='utf-8') as f:
with | open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name = 'bugherd',
# Versions should comply with PEP440. For a discussion on single-sourcing
# the version across setup.py and the project code, see
# https://packaging.python.org/en/latest/development.h... |
bzzzz/cython | Cython/Compiler/Symtab.py | Python | apache-2.0 | 80,141 | 0.00594 | #
# Symbol Table
#
import re
from Cython import Utils
from Errors import warning, error, InternalError
from StringEncoding import EncodedString
import Options, Naming
import PyrexTypes
from PyrexTypes import py_object_type, unspecified_type
import TypeSlots
from TypeSlots import \
pyfunction_signature, pymethod_... | me = None
func_modifiers = []
doc = None
init_to_none = | 0
as_variable = None
xdecref_cleanup = 0
in_cinclude = 0
as_module = None
is_inherited = 0
pystring_cname = None
is_identifier = 0
is_interned = 0
used = 0
is_special = 0
defined_in_pxd = 0
is_implemented = 0
api = 0
utility_code = None
is_overridable = 0
... |
ryandougherty/mwa-capstone | MWA_Tools/build/matplotlib/lib/mpl_examples/pylab_examples/scatter_profile.py | Python | gpl-2.0 | 556 | 0.010791 | #!/usr/bin/env python |
# -*- noplot -*-
"""
N Classic Base renderer Ext renderer
20 0.22 0.14 0.14
100 0.16 0.14 0.13
1000 0.45 0.26 0.17
10000 3.30 1.31 0.53
50000 19.30 6.53 1.98
"""
from pylab import *... | (N)
y = 0.9*rand(N)
s = 20*rand(N)
scatter(x,y,s)
print '%d symbols in %1.2f s' % (N, time.time()-tstart)
|
FAForever/client | src/fa/factions.py | Python | gpl-3.0 | 1,836 | 0 | import random
from enum import Enum, unique
@unique
class Factions(Enum):
"""
Enum to represent factions. Numbers match up with faction identification
ids from the game.
"""
UEF = 1
AEON = 2
CYBRAN = 3
SERAPHIM = 4
# Shall remain the last element: not a real faction number.
RA... | rn ran | dom.choice(possibilities)
@staticmethod
def from_name(name):
name = name.lower()
if name == "uef":
return Factions.UEF
elif name == "aeon":
return Factions.AEON
elif name == "cybran":
return Factions.CYBRAN
elif name == "seraphim":
... |
ConPaaS-team/conpaas | conpaas-services/src/conpaas/services/mysql/manager/config.py | Python | bsd-3-clause | 4,854 | 0.006799 | # -*- coding: utf-8 -*-
"""
:copyright: (C) 2010-2013 by Contrail Consortium.
"""
from conpaas.core.log import create_logger
from conpaas.core.node import ServiceNode
E_ARGS_UNEXPECTED = 0
E_CONFIG_READ_FAILED = 1
E_CONFIG_NOT_EXIST = 2
E_UNKNOWN = 3
E_ARGS_MISSING = 4
E_ARGS_INVALID = 5
E_STATE_ERROR = 6
E_STR... | elf):
return [serviceNode.ip for serviceNode in self.serviceNodes.values()]
def get_nodes(self):
""" Returns the list of MySQL nodes."""
return [serviceNode for serviceNode in self.serviceNodes.values()]
def get_glb_nodes(self):
''' Returns the list of GLB nodes'''
retu... | n self.glb_service_nodes.values()]
def getMySQLNode(self, id):
if self.serviceNodes.has_key(id):
node = self.serviceNodes[id]
else:
node = self.glb_service_nodes[id]
return node
def addGLBServiceNodes(self, nodes):
'''
Add new GLB Node to the se... |
ZTH1970/alcide | init.d/alcide-conf.py | Python | agpl-3.0 | 143 | 0.006993 | backlog = 2048
debug | = False
workers = 12
loglevel = "info"
secure_scheme_headers = {'X-FORWARDED-PROTOCOL': 'https | ', 'X-FORWARDED-SSL': 'on'}
|
Spotipo/spotipo | unifispot/ext/development.py | Python | agpl-3.0 | 902 | 0 | # coding: utf-8
def configure(app):
if app.config.get('DEBUG_TOOLBAR_ENABLED'):
try:
from flask_debugtoolbar import DebugToolbarExtension
DebugToolbarExtension(app)
except ImportError:
app.logger.info('flask_debugtoolbar is not in | stalled')
if app.config.get('OPBEAT'):
try:
from opbeat.contrib.flask import Opbeat
Opbeat(
app,
logging=app.config.ge | t('OPBEAT', {}).get('LOGGING', False)
)
app.logger.info('opbeat configured!!!')
except ImportError:
app.logger.info('opbeat is not installed')
if app.config.get('SENTRY_ENABLED', False):
try:
from raven.contrib.flask import Sentry
app.sent... |
tody411/InverseToon | inversetoon/core/project_normal_3d.py | Python | mit | 2,601 | 0.003076 |
# -*- coding: utf-8 -*-
## @package inversetoon.core.project_normal_3d
#
# inversetoon.core.project_normal_3d utility package.
# @author tody
# @date 2015/08/12
import numpy as np
from inversetoon.np.norm import normalizeVectors
from inversetoon.core.smoothing import smoothing
def projectTangent3D(ta... | D
def projectNormals(L, I, tangents_3D, normals):
normals_smooth = np.array(normals)
num_points = len(normals)
| for i in range(num_points):
T = tangents_3D[i]
N = normals[i]
NdL = np.dot(N, L)
dN_L = (I - NdL) * L
NdT = np.dot(N, T)
dN_T = - NdT * T
normals_smooth[i] = N + dN_L + dN_T
normals_smooth = normalizeVectors(normals_smooth)
return normals_smooth
def ... |
mdaif/LDAP-Manager | ldap_manager/settings.py | Python | gpl-2.0 | 2,724 | 0.000367 | """
Django settings for ldap_manager project.
Generated by 'django-admin startproject' using Django 1.8.3.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build... | [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_pr | ocessors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'ldap_manager.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DA... |
chintal/tendril-fs-server | setup.py | Python | mit | 1,119 | 0.000894 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptool | s import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_fi | le.read()
requirements = [
'twisted',
'fs',
]
test_requirements = [
# TODO: put package test requirements here
]
setup(
name='tendril-server-fs',
version='0.2.9',
description="XML-RPC Filesystem Server using Twisted and Pyfilesystems for Tendril",
long_description=readme,
author="Chin... |
lr292358/connectomics | run.py | Python | bsd-2-clause | 17,790 | 0.0181 | import cPickle
import gzip
import time
import os
import sys
import cPickle as pickle
import gc
import numpy as np
from time import sleep
import auc
import theano
import theano.tensor as T
from theano.tensor.signal import downsample
from theano.tensor.nnet import conv
from theano.ifelse import ifelse
import theano.print... | aminacW = np.amin(Ti[1000,:])
amaxacW = np.amax(Ti[1000,:])
print aminW, amaxW, ami | nacW, amaxacW
Ti[1000,:] = (Ti[1000,:] - aminacW) / (amaxacW - aminacW)
astdacW = np.std(Ti[1000,:])
ameanacW = np.mean(Ti[1000,:])
Ti[1000,:] = (Ti[1000,:] - ameanacW) / astdacW
ile__ = len(TOList)
ileList = np.zeros(ile__)
for titer in range(len(TOList)):
print np.mean(TOLis... |
FBSLikan/Cetico-TCC | thirdparty/illuminants/sourcecode/trainingSVM.py | Python | gpl-3.0 | 12,867 | 0.042745 | import numpy as np
import sys
import os
from sklearn import svm
from sklearn.externals import joblib
from sklearn import preprocessing
from sklearn.grid_search import GridSearchCV
import getSpaceChannelName as sc
def readTrainingTestFiles(outfile):
ofid = open(outfile,'rt')
ofid.seek(0)
lines = ofid.readli... | cale(trainingMatrixF)
#Scale features between [-1,1]
max_abs_scaler = preprocessing.MaxAbsScaler()
trainingMatrixFScaled = max_abs_scaler.fit_transform(trainingMatrixF)
# Make grid search for best set of parameters
#Cs = np.logspace(-6, -1, 10)
#svc = svm.SVC(kernel='rbf',class_weight={'1':we... | 1':weightFake})
svc = svm.SVC()
#clf = GridSearchCV(svc,dict(C=Cs),n_jobs=-1,param_grid={'C': [1, 10, 100, 1000], 'gamma': [0.001, 0.0001], 'kernel': ['rbf']})
clf = GridSearchCV(svc,n_jobs=-1,param_grid={'C': list(range(1,1000,10)), 'gamma': np.arange(0.0001, 0.001,0.001), 'kernel': ['rbf'], 'class_weight... |
halbbob/dff | modules/viewer/hexedit/hexView.py | Python | gpl-2.0 | 7,468 | 0.00549 | # DFF -- An Open Source Digital Forensics Framework
# Copyright (C) 2009 ArxSys
#
# This program is free software, distributed under the terms of
# the GNU General Public License Version 2. See the LICENSE file
# at the top of the source tree.
#
# See http://www.digital-forensic.org for more information about this
# ... | ove(self.heditor.pageSize / self.heditor.bytesPerLine, 0)
elif keyEvent.matches(QKeySequence.MoveToNextWord):
print "Next Word"
elif keyEvent.matches(QKeySequence.MoveToPreviousWord):
print "Pre | vious word"
elif keyEvent.matches(QKeySequence.MoveToNextLine):
print "Next Line"
elif keyEvent.matches(QKeySequence.MoveToPreviousLine):
print "Previous Line"
|
tensorflow/text | tensorflow_text/python/ops/mst_ops_test.py | Python | apache-2.0 | 5,182 | 0.006561 | # coding=utf-8
# Copyright 2022 TF.Text Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | 0],
[0, 0, 0, 3]],
[[7, 0, 0, 0],
[0, 0, 7, 0],
| [7, 0, 0, 0],
[0, 0, 0, 0]]]) # pyformat: disable
@test_util.run_deprecated_v1
def testMaximumSpanningTreeGradientError(self):
"""Numerically validates the max score gradient."""
with self.test_session():
# The maximum-spanning-tree-score function, as a max of linear... |
fmca/ctxpy | ctx/toolkit.py | Python | mit | 2,280 | 0.001754 | from abc import abstractmethod
from threading import Timer
from ctx.uncertainty.measurers import clear_dobson_paddy
class Event:
def __init__(self, typ | e, **kwargs):
self.type = type
self.properties = kwargs
class Observer:
def update(self):
raise NotImplementedError("Not implemented")
class Observable:
def __init__(self):
self._observers = | []
def register(self, observer):
self._observers.append(observer)
def notify(self, event):
event.source = self
for observer in self._observers:
observer.update(event)
class Widget(Observable, Observer):
@abstractmethod
def update(self, event):
pass
d... |
brycepg/cave-dweller | tests/exploratory/sdl_render.py | Python | gpl-3.0 | 680 | 0.010294 | """I got sys_register_SDL_renderer to work!"""
import time
import sy | s
import os
sys.path.append("../../cave_dweller")
import libtcodpy as libtcod
from ctypes import *
import draw_text
def render(surface):
draw_text.draw_text("it works!", surface, 25, 25)
#sdl.fill_circle(surface, 1, 1, 5, 5)
|
libtcod.console_set_custom_font(os.path.join('../../fonts', 'dejavu12x12_gs_tc.png'), libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD)
libtcod.console_init_root(90,40, 'test', False, libtcod.RENDERER_SDL)
# Set font size, init ttf
draw_text.set_font(pt_size=12)
libtcod.sys_register_SDL_renderer(render)
libtcod.... |
shanzhenren/PLE | Classifier/PLSVM.py | Python | gpl-3.0 | 4,745 | 0.002529 | from __future__ import division
__author__ = 'wenqihe'
import sys
import random
import math
class PLSVM:
def __init__(self, feature_size, label_size, type_hierarchy, lambda_reg=0.1, max_iter=5000, threshold=0.5, batch_size=100):
self._feature_size = feature_size
self._label_size = label_size
... | (self._label_size):
# L2 = 0
for j in xrange(self._feature_size):
self._weight[i][j] = self._weight[i][j]*(1-eta_t*self._lambda_reg) + eta_t*dW[i][j]/m
# L2 += self._weight[i][j] * self._weight[i][j]
# if L2>0:
# factor = min(1, 1/(math... | if factor < 1:
# for j in xrange(self._feature_size):
# self._weight[i][j] *= factor
@staticmethod
def inner_prod(weight, x):
result = 0
for feature in x:
result += weight[feature]
return result
@staticmethod
def kerne... |
LE-GO-LE-STOP/Robocup-Junior-Rescue-2016 | src/python/ev3dev/ev3.py | Python | gpl-3.0 | 6,266 | 0.002713 | # -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
# Copyright (c) 2015 Eric Pascual
#
# 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 w... | estriction, includi | ng without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
#... |
D8TM/railtracker | scripts/retrieve_dc_incidents.py | Python | apache-2.0 | 2,130 | 0.005164 | from django.conf import settings
from railtracker.mapfeed.models import Incident, MapCity, MapLine
from pprint import pprint
import twitter, httplib, urllib, base64, json
#Functions
def loa | dIncidents():
city = MapCity.objects.get(city_name="Washington D.C.").id
lines = MapLine.objects.filter(map=city)
try:
conn.request("GET", "/Incidents.svc/json/Incidents?%s" % params, "", headers)
response = conn.getresponse()
data = response.read()
conn.close()
except Ex... | ase
for incident in decoded_inc['Incidents']:
obj_date = incident['DateUpdated'].replace('T', ' ')
obj_desc = incident['Description']
num_results = Incident.objects.filter(incident_date=obj_date).filter(description=obj_desc).count()
if num_results < 1:
inc_model = Inciden... |
xchen101/analysis-preservation.cern.ch | cap/modules/experiments/permissions/lhcb.py | Python | gpl-2.0 | 1,489 | 0.000672 | # -*- coding: utf-8 -*-
#
# This file is part of CERN Analysis Preservation Framework.
# Copyright (C) 2016 CERN.
#
# CERN Analysis Preservation Framework 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... | ranted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""CAP LHCb permissions"""
from invenio_access import DynamicPermission
from cap.modules.experiments.permissions.common import get_collaboration_group_needs, get_superuser_needs
lhcb_group_need = set(... | rmission(*lhcb_group_need)
|
zhimin711/nova | nova/tests/unit/test_api_validation.py | Python | apache-2.0 | 50,677 | 0.000335 | # Copyright 2013 NEC Corporation. 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 ... | deepcopy(schema_v21_int)
schema_v20_str['properties']['foo'] = {'type': 'string'}
@validation.schema(schema_v20_str, '2.0', '2.0')
@validation.schema(schema_v21_int, '2.1')
def post(req, body):
return 'Validation succeeded.'
self.post = post
def test_validate_v... | ={'foo': 'bar'}, req=req),
'Validation succeeded.')
detail = ("Invalid input for field/attribute foo. Value: 1. "
"1 is not of type 'string'")
self.check_validation_error(self.post, body={'foo': 1},
expected_detail=detail, re... |
engineer0x47/SCONS | engine/SCons/Platform/irix.py | Python | mit | 1,605 | 0.000623 | """SCons.Platform.irix
Platform-specific initialization for SGI IRIX systems.
There normally shouldn't be any need to import this module directly. It
will usually be imported through the generic SCons.Platform.Platform()
selection method.
"""
#
# Copyright (c) 2001 - 2014 The SCons Foundation
#
# Permission is here... | mitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit | persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUD... |
vsc-squared/FileShareHeroku | FileShare/urls.py | Python | mit | 2,578 | 0.001552 | from django.conf.urls import include, url
from django.contrib.auth.views import log | in
from registration.views import *
from groupmanagement.views import *
from reports.views import *
from message.views import *
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns | = [
url(r'^$', login),
url(r'^logout/$', logout_page),
url(r'^accounts/login/$', login),
url(r'^register/$', register),
url(r'^register/success/$', register_success),
url(r'^home/$', home),
url(r'^createGroup/$', createGroup),
url(r'^admin/', admi... |
JonSeijo/filelines-measurer | filelines.py | Python | gpl-3.0 | 3,504 | 0.006564 | import subprocess
import re
import matplotlib.pyplot as plt
import argparse
import os
outfile_git_name = "tmp_git.txt"
outfile_format_name = "tmp_formatted.txt"
git_log_constant = "1 file changed, " # Used for grep, do not modify
diff_list = []
total_list = []
# Parse arguments passed by command line
parser = argp... | rent = total_list[-1]
# pl | ot
if (use_point):
plt.plot([i for i in range(1, len(total_list) + 1)], total_list, 'bo')
else:
plt.plot(total_list)
plt.grid()
plt.title(filepath)
plt.ylabel('File lines')
plt.xlabel('Commits')
# Plot max line
plt.axhline(y=total_max, color='r', linestyle='-')
plt.t... |
tensorflow/probability | spinoffs/fun_mc/fun_mc/using_jax.py | Python | apache-2.0 | 1,013 | 0 | # Copyright 2021 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================... | ds import rewrite
from fun_mc.dynamic.backend_jax import api # pytype: disable=import-error
# pylint: disable=wildcard-import
from fun_mc.dynamic.backend_jax.api import * # pytype: disable=import-error
del rewrite
__all__ = api.__all__
|
mokieyue/mopidy | mopidy/listener.py | Python | apache-2.0 | 1,658 | 0 | from __future__ import absolute_import, unicode_literals
import logging
import pykka
logger = logging.getLogger(__name__)
def send(cls, event, **kwargs):
listeners = pykka.ActorRegistry.get_by_class(cls)
logger.debug('Sending %s to %s: %s', event, cls.__name__, kwargs)
for listener in listeners:
... |
class Listener(object):
def on_event(self, event, **kwargs):
"""
Called on all events.
*MAY* be implemented by actor. By default, this method forwards the
event to the specific event methods.
:param event: the event name
:type event: string
:param kwargs: ... | tion:
# Ensure we don't crash the actor due to "bad" events.
logger.exception(
'Triggering event failed: %s(%s)', event, ', '.join(kwargs))
|
x8lucas8x/python-zeroless | tests/test_client_server.py | Python | lgpl-2.1 | 483 | 0.004141 | import pytest |
from zeroless import (Server, Client)
class TestClientServer:
def test_server_port_property(self):
port = 1050
server = Server(port=port)
assert server.port == port
def test_client_addresses_property(self):
client = Client()
addresses = (('10.0.0.1', 1567), ('10.0.0.... | |
reviewboard/rbtools | rbtools/commands/land.py | Python | mit | 16,983 | 0 | from __future__ import unicode_literals
import logging
import six
from rbtools.api.errors import APIError
from rbtools.clients.errors import MergeError, PushError
from rbtools.commands import Command, CommandError, Option, RB_MAIN
from rbtools.utils.commands import (build_rbtools_cmd_argv,
... | True
needs_scm_client = True
needs_repository = True
args = '[<branch-name>]'
option_list = [
Option('--dest',
dest='destination_branch',
default=None,
config_key='LAND_DEST_BRANCH',
help='Specifies the destination branch to land chan... | help='Specifies the review request ID.'),
Option('--local',
dest='is_local',
action='store_true',
default=None,
help='Forces the change to be merged without patching, if '
'merging a local branch. Defaults to true unless '
... |
viswimmer1/PythonGenerator | data/python_files/28486514/util_threadpool.py | Python | gpl-2.0 | 9,770 | 0.011157 | import sys, traceback
import Queue as queue
import threading
import collections
theVmIsGILFree = False
if sys.platform == 'cli':
theVmIsGILFree = True
# perhaps "unladen swallow will goes GIL free.
if sys.platform == 'cli':
# workaround for IronPython
import System
theAvailableNativeThrea... | one,
keepEmptyResults=False, printStackTrace=False):
assert workerCount > 0
assert queueSize is None or queueSize >= workerCount
self.__printStackTrace = printStackTrace
if queueSize is None:
queueSize = workerCount
if queueSize... | = collections.deque() # deque is thread safe in both CPython and IronPython.
self.__workerThreads = []
for _ in xrange(workerCount):
t = threading.Thread(target=self.__worker_func)
t.setDaemon(True)
t.start()
self.__workerThreads.append(t)
... |
zodiac/incubator-airflow | airflow/configuration.py | Python | apache-2.0 | 26,596 | 0.000263 | # -*- coding: utf-8 -*-
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
... | r the web server. When both are
# provided SSL will be enabled. This does not change the web server | port.
web_server_ssl_cert =
web_server_ssl_key =
# Number of seconds the gunicorn webserver waits before timing out on a worker
web_server_worker_timeout = 120
# Number of workers to refresh at a time. When set to 0, worker refresh is
# disabled. When nonzero, airflow periodically refreshes webserver workers by
# br... |
hassaanm/stock-trading | src/pybrain/rl/learners/directsearch/policygradient.py | Python | apache-2.0 | 4,200 | 0.001905 | __author__ = 'Thomas Rueckstiess, [email protected]'
from pybrain.rl.learners.directsearch.directsearch import DirectSearchLearner
from pybrain.rl.learners.learner import DataSetLearner, ExploringLearner
from pybrain.utilities import abstractMethod
from pybrain.auxiliary import GradientDescent
from pybrain.rl.explore... | ):
return self.gd.alpha
learningRate = property(_getLearningRate, _setLearningRate)
def _setModule(self, module):
""" initialize gradient descender with module parameters and
the loglh dataset with the outd | im of the module. """
self._module = module
# initialize explorer
self._explorer = NormalExplorer(module.outdim)
# build network
self._initializeNetwork()
def _getModule(self):
return self._module
module = property(_getModule, _setModule)
def _setExplorer... |
dracos/QGIS | python/plugins/processing/algs/qgis/GeometryConvert.py | Python | gpl-2.0 | 9,841 | 0.001219 | # -*- coding: utf-8 -*-
"""
***************************************************************************
Gridify.py
---------------------
Date : May 2010
Copyright : (C) 2010 by Michael Minn
Email : pyqgis at michaelminn dot com
*****************************... | rom %s to %s', geomType, newType))
elif geomType in [QGis.WKBMultiLineString, QGis.WKBMultiLineString25D]:
if newType == QGis.WKBPoint and splitNodes:
lines = geom.asMultiPolyline()
for line in lines:
for p in line:
... |
writer.addFeature(feat)
elif newType == QGis.WKBPoint:
feat = QgsFeature()
feat.setAttributes(f.attributes())
feat.setGeometry(geom.centroid())
writer.addFeature(feat)
elif newTyp... |
litex-hub/litex-boards | litex_boards/platforms/xilinx_kv260.py | Python | bsd-2-clause | 1,483 | 0.005394 | #
# This file is part of LiteX-Boards.
#
# Copyright (c) 2022 Ilia Sergachev <[email protected]>
# SPDX-License-Identifier: BSD-2-Clause
from litex.build.generic_platform import *
from litex.build.xilinx import XilinxPlatform, VivadoProgrammer
# IOs -------------------------------------------------------------------... | rrent_design]", ]
self.default_clk_freq = 1e9 / self.default_clk_period |
def create_programmer(self):
return VivadoProgrammer()
def do_finalize(self, fragment, *args, **kwargs):
XilinxPlatform.do_finalize(self, fragment, *args, **kwargs)
self.add_period_constraint(self.lookup_request("pmod_hda16_cc", loose=True), 1e9/100e6)
|
kpeiruza/incubator-spot | spot-ingest/pipelines/proxy/worker.py | Python | apache-2.0 | 2,534 | 0.02131 | #!/bin/env python
import os
import logging
import json
from common.utils import Util
class Worker(object):
def __init__(self,db_name,hdfs_app_path,kafka_consumer,conf_type,processes):
self._initialize_members(db_name,hdfs_app_path,kafka_consumer,conf_type,processes)
def _initialize_members(self,db... | "--num-executors {1} | "
"--conf spark.executor.memory={2} "
"--conf spark.executor.cores={3} "
"--jars {4}/common/spark-streaming-kafka-0-8-assembly_2.11-2.0.0.jar "
"{5}/{6} "
"-zk {7} "
"-t {8} "
... |
Answers4AWS/backup-monkey | backup_monkey/cli.py | Python | apache-2.0 | 5,890 | 0.004754 | # Copyright 2013 Answers for AWS 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 w... | verbose)
log.debug("CLI p | arse args: %s", args)
if args.region:
region = args.region
else:
# If no region was specified, assume this is running on an EC2 instance
# and work out what region it is in
log.debug("Figure out which region I am running in...")
instance_metadata = get_instance_metadata(... |
thijsmie/imp_flask | imp_flask/middleware.py | Python | mit | 3,368 | 0.002672 | """Flask middleware definitions. This is also where template filters are defined.
To be imported by the application.current_app() factory.
"""
from logging import getLogger
import os
from flask import current_app, render_template, request
from markupsafe import Markup
import simplejson as json
from imp_... | NS.
exception_name = e.__class__.__name__
view_module = request.endpoint
send_exception('{} exception in {}'.format(exception_name, view_module))
return render_template('{}.html'.format(code)), code
# Template filters.
@current_app.template_filter()
|
def whitelist(value):
"""Whitelist specific HTML tags and strings.
Positional arguments:
value -- the string to perform the operation on.
Returns:
Markup() instance, indicating the string is safe.
"""
translations = {
'&quot;': '"',
'&#39;': '''... |
koduj-z-klasa/pylab | zadania/fun2_z04.py | Python | agpl-3.0 | 517 | 0 | #! /us | r/bin/env python
# -*- coding: utf-8 -*-
# ZADANIE: wykonaj wykres funkcji f(x), gdzie x = <-10;10> z krokiem 0.5
# f(x) = x/-3 + a dla x <= 0
# f(x) = x*x/3 dla x >= 0
import pylab
x = pylab.arange(-10, 10.5, 0.5) # lista argumentów x
a = int(raw_input("Podaj współczynnik a: "))
y1 = [i / -3 + a for i in x if i <=... | True)
pylab.show()
|
HulaSamsquanch/1100d_lantern | contrib/indy/parse_lens60.py | Python | gpl-2.0 | 1,632 | 0.028186 | #parse LENS00.BIN
import sys
from struct import unpack
from binascii import unhexlify, hexlify
def getLongLE(d, a):
return unpack('<L',(d)[a:a+4])[0]
def getShortLE(d, a):
return unpack('<H',(d)[a:a+2])[0]
f = open(sys.argv[1], 'rb')
m = f.read()
f.close()
base = 0x850
print 'filesize=%d' % len(m)
print 'bas... | 7c:0x37c+6]), hexlify(val[0x37c+6:0x38c])
for t in range(0x38c,0x38c+12*16,12):
print hexlify(val[t:t+12]),
print
print hexlify(val[0x44c:0x44c+4])
print hexlify(val[0x450:0x452]), hexlify(val[0x452:0x454]), hexlify(val[0x454:0x456]),hexlify(val[0x456:0x458]),
print hexlify(val[0x458:0x458+10]... | :t+8])
for x in range(t+8, t+8+16*24, 24):
print hexlify(val[x:x+24]),
print
print hexlify(val[0xa8c:0xa90])
i = i + 16 |
iwm911/plaso | plaso/winreg/cache_test.py | Python | apache-2.0 | 1,609 | 0.001865 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2013 The Plaso Project Authors.
# Please see the AUTHORS file for details on individual authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the L... | ITIONS OF ANY KIND, either e | xpress or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for the Windows Registry objects cache."""
import unittest
from plaso.winreg import cache
from plaso.winreg import test_lib
from plaso.winreg import winregistry
class CacheTest(test_lib... |
tangentlabs/django-fancypages | sandbox/settings/common.py | Python | bsd-3-clause | 4,089 | 0.000489 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
import os
import django
import fancypages as fp
from configurations import Configuration, values
class Common(Configuration):
DEBUG = True
TEMPLATE_DEBUG = DEBUG
SECRET_KEY = values.Value('insecure secret key')
ADMINS ... | ngo.core.context_pro | cessors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.contrib.messages.context_processors.messages"]
MIDDLEWARE_CLASSES = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
... |
sjdv1982/seamless | docs/archive/spyder-like-silk/typeparse/macros/enum.py | Python | mit | 520 | 0.005769 | # Copyright 2016, Sjoerd de Vries
from ...exceptions import SilkSyntaxError
def macro_enum(name, content):
if name != "Enum":
return
c = content.strip()
| lparen = c.find("(")
if lparen == -1:
raise SilkSyntaxError("'%s': missing ( in Enum" % content)
rparen = c.rfind(")")
if rparen == -1:
raise SilkSyntaxError("'%s': missing ) in Enum" % | content)
enum = c[lparen+1:rparen]
return "String " + c[:lparen] + c[rparen+1:] \
+ "\nenum {\n " + enum + "\n}\n" \
|
stwb/pywinux | ls.py | Python | mit | 2,725 | 0.022018 | #!/usr/bin/env python3
import os, sys, argparse, stat, time, copy
# From StackOverflow :: http://stackoverflow.com/a/1094933
def sizeof_fmt(num, suffix='B'):
for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f%... | args.target):
if not os.path.exists(directory):
print(os.path.basename(sys.argv[0]) + ': cannot access adsf: No such file or directory')
continue
output = list()
if len(args.target) > 1:
print(('\n' if i > 0 else '') + directory + ':')
for aFile in os.listdir(directory):
line = l... | output.append(list(line))
# Format output in columns
if args.long:
lengths = list(map(lambda x: list(map(len, x)), output))
if len(lengths) == 0:
continue
col_sizes = list(map(lambda i: max(l[i] for l in lengths) + 2, range(len(lengths[0])-1)))
col_sizes[0] -= 2 # Don't n... |
dunkhong/grr | grr/server/grr_response_server/gui/selenium_tests/settings_view_test.py | Python | apache-2.0 | 2,790 | 0.005018 | #!/usr/bin/env python
""" | Tests for GRR settings-related views."""
from __future__ import absolute_ | import
from __future__ import division
from __future__ import unicode_literals
from absl import app
from grr_response_server.gui import gui_test_lib
from grr_response_server.gui.api_plugins import config_test as api_config_test
from grr.test_lib import test_lib
class TestSettingsView(gui_test_lib.GRRSeleniumTest):
... |
sunlightlabs/emailcongress | emailcongress/settings/production.py | Python | mit | 856 | 0 | from emailcongress.settings.shared import *
ALLOWED_HOSTS += CONFIG_DICT['django']['allowed_hosts']
# see http://developer.yahoo.com/performance/rules.html#expires
AWS_HEADERS = {
'Expires': 'Thu, 31 Dec 2099 20:00:00 GMT',
'Cache-Control': 'max-age=94608000',
}
AWS_ACCESS_KEY_ID = CONFIG_DICT['aws']['access... | o/boto/issues/2836
AWS_S3_CALLING_FORMAT = 'boto.s3.connection.OrdinaryCallingFormat'
AWS_S3_CUSTOM_DOMAIN = CONFIG_DICT['aws']['cloudfront_url']
STATICFILES_STORAGE = 'emailcongress.settings.MyS3BotoStorage'
SESSION_COOKIE_SEC | URE = True
CSRF_COOKIE_SECURE = True
PROTOCOL = CONFIG_DICT.get('protocol', 'https')
SECRET_KEY = CONFIG_DICT['django']['secret-key']
|
antoinecarme/sklearn2sql_heroku | tests/databases/test_client_pgsql.py | Python | bsd-3-clause | 740 | 0.016216 |
import pickle, json, requests, base64
from sklearn import datasets
iris = datasets.load_iris()
X = iris.data
Y = iris.target
# print(iris.DESCR)
from sklearn.neural_network import ML | PClassifier
clf = MLPClassifier()
clf.fit(X, Y)
def test_ws_sql_gen(pickle_data):
WS_URL="https://sklearn2sql.herokuapp.com/model"
b64_data = base64.b64encode(pickle_data).decode('utf-8')
data={"Name":"model1", "PickleData":b64_data , "SQLDialect":"postgresql"}
r = requests.post(WS_URL, json=data)
... |
pickle_data = pickle.dumps(clf)
lSQL = test_ws_sql_gen(pickle_data)
print(lSQL)
|
kumarvaradarajulu/prboard | prboard/tests/unit/test_hub.py | Python | gpl-3.0 | 2,446 | 0.004906 | import unittest
import mock
import github
from github import Requester
from prboard import utils, filters, settings, hub
class TestGithub(unittest.TestCase):
def setUp(self):
pass
def test_github_init(self):
""" Test if Github gets instantiated with addditional methods """
g = hub.... | ][2], "/users/{0}/repos".format("kumar"))
self.assertEqual(repos, data)
@mock.patch.object(github.PaginatedList, "PaginatedList")
def test_github_get_org_repos_pass(self, mock_paginated_list):
""" Test if Github.get_org_repos raises assertion error if since is not a valid value """
args... | [github.Repository.Repository(*args), github.Repository.Repository(*args), github.Repository.Repository(*args)]
mock_paginated_list.return_value = data
g = hub.Github()
repos = g.get_org_repos("kumar")
# Cannot use assert_called_once_with as the requester object gets an instance
... |
atmark-techno/atmark-dist | user/python/Doc/tools/refcounts.py | Python | gpl-2.0 | 2,236 | 0 | """Support functions for loading the reference count data file."""
__version__ = '$Revision: 1.2 $'
import os
import string
import sys
# Determine the expected location of the reference count file:
try:
p = os.path.dirname(__file__)
except NameError:
p = sys.path[0]
p = os.path.normpath(os.path.join(os.getcw... | %s:"
if entry.result_refs is None:
r = ""
else:
r = entry.result_refs
prin | t s % (entry.result_type, "", r)
for t, n, r in entry.args:
if r is None:
r = ""
print s % (t, n, r)
def main():
d = load()
dump(d)
if __name__ == "__main__":
main()
|
mlewe/trueskill_kicker | trueskill_kicker/test_trueskill.py | Python | apache-2.0 | 1,198 | 0 | from trueskill import Rating, rate
import scraper
class test:
def __init__(self):
self.locker_room = {}
_, results = scraper.scrape_matches(history=True)
for result in reversed(results):
line = []
line.extend(result[0].split(' / '))
line.extend(result[... | players[i]) for i in range(2, 4) | ]
ranks = [score[1] > score[0], score[1] < score[0]]
t1, t2 = rate([t1, t2], ranks=ranks)
for i in range(2):
locker_room[players[i]] = t1[i]
locker_room[players[i + 2]] = t2[i]
tr = test()
i = iter(tr.locker_room.items())
for score, player in reversed(sorted((v.mu - 3 ... |
dochang/ansible-modules-core | cloud/amazon/ec2_asg.py | Python | gpl-3.0 | 34,382 | 0.005381 | #!/usr/bin/python
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed... | required: false
version_added: "1.8"
default: None
lc_check:
description:
- Check to make sure instances that are being replaced with replace | _instances do not aready have the current launch_config.
required: false
version_added: "1.8"
default: True
vpc_zone_identifier:
description:
- List of VPC subnets to use
required: false
default: None
tags:
description:
- A list of tags to add to the Auto Scale Group. Optiona... |
blaquee/androguard | androguard/core/bytecodes/dvm.py | Python | apache-2.0 | 256,233 | 0.016434 | # This file is part of Androguard.
#
# Copyright (C) 2012/2013/2014, Anthony Desnos <desnos at t0t0.fr>
# 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://... | ,
}
FIELD_READ_DVM_OPCODES = [ ".get" ]
FIELD_WRITE_DVM_OPCODES = [ ".put" ]
BREAK_DVM_OPCODES = [ "invoke.", "move.", ".put", "if." ]
BRANCH_DVM_OPCODES = [ "throw", "throw.", "if.", "goto", "goto.", "return", "return.", "packed-switch$", "sparse-switch$" ]
def clean_name_instruction( instruct... | ic_operand_instruction( instruction ):
buff = ""
if isinstance(instruction, Instruction):
# get instructions without registers
for val in instruction.get_literals():
buff += "%s" % val
op_value = instruction.get_op_value()
if op_value == 0x1a or op_value == 0x1b:
buff += ... |
protonyx/labtronyx-gui | labtronyxgui/application/include/ManagerPages.py | Python | mit | 2,751 | 0.011996 | import Tkinter as Tk
import tkMessageBox
class a_ConnectToHost(Tk.Toplevel):
def __init__(self, master, cb_func):
Tk.Toplevel.__init__(self, master)
# Store reference to parent window callback function
self.cb_func = cb_func
self.wm_title('Connect to host...')... | )
Tk.Label(self, text='Resource ID').grid(row=1, column=0)
self.lst_controller = Tk.OptionMenu(self, self.controller, *controllers)
self.lst_controller.grid(row=0, column=1, columnspan=2)
self.txt_resID = Tk.Entry(self)
self.txt_resID.grid(row=1, column=1, columnspan=2)
T... | f, text='Cancel', command=lambda: self.cb_Cancel()).grid(row=2, column=1)
Tk.Button(self, text='Connect', command=lambda: self.cb_Add()).grid(row=2, column=2)
# Make this dialog modal
#self.focus_set()
#self.grab_set()
def cb_Add(self):
controller = self... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.