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 |
|---|---|---|---|---|---|---|---|---|
hsharrison/history-queue | setup.py | Python | bsd-2-clause | 1,610 | 0.001242 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
import io
import re
from glob import glob
from os.path import basename
from os.path import dirname
from os.path import join
from os.path import splitext
from setuptools import find_packages
from setuptools import setup
def read(*names, **kwargs):
return io.open(
... | s',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Programming Language :: Python :: 3.5',
'Topic :: Utilities',
],
keywords=[
'asyncio', 'deque', 'queue', 'history',
],
extras_require={
'test': ['pytes | t', 'pytest-cov', 'hypothesis', 'toolz'],
}
)
|
Azure/azure-sdk-for-python | sdk/databox/azure-mgmt-databox/azure/mgmt/databox/v2020_11_01/_data_box_management_client.py | Python | mit | 3,173 | 0.001891 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | :vartype operations: azure.mgmt.databox.operations.Operations
:ivar jobs: JobsOperations operations
:vartype jobs: azure.mgmt.databox.operations.JobsOperations
:ivar service: ServiceOperations operations
:vartype service: azure.mgmt.databox.operations.ServiceOper | ations
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials.TokenCredential
:param subscription_id: The Subscription Id.
:type subscription_id: str
:param str base_url: Service URL
:keyword int polling_interval: Default waiting time b... |
parksandwildlife/borgcollector | tablemanager/migrations/0021_auto_20160219_0803.py | Python | bsd-3-clause | 2,007 | 0.003986 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.db.models.deletion
import re
import tablemanager.models
import django.utils.timezone
import borg_utils.resource_status
import django.core.validators
class Migration(migrations.Migration):
depen... | ld(help_text='Name of Publish', max_length=255, validators=[django.core.validators.RegexValidator(re.compile('^[a-z0-9_]+$'), 'Slug can | only contain lowercase letters, numbers and underscores', 'invalid')])),
('description', models.CharField(max_length=512, null=True, blank=True)),
('status', models.CharField(default=b'Enabled', max_length=32, choices=[(b'Enabled', b'Enabled'), (b'Disabled', b'Disabled')])),
... |
globocom/database-as-a-service | dbaas/physical/commands.py | Python | bsd-3-clause | 3,573 | 0 | class HostCommands(object):
def __new__(cls, host):
if host.is_ol6:
return HostCommandOL6(host)
if host.is_ol7:
return HostCommandOL7(host)
class HostBaseCommands(object):
def __init__(self, host):
self.host = host
self.infra = host.infra
self.e... | ervice_name='httpd',
action=action,
no_output=no_output
)
def heartbeat(self, action, no_output=False):
return self.exec_service_command(
service_name='pt-heartbeat',
action=action,
no_output=no_output
)
@property
def comm... | dError()
class HostCommandOL6(HostBaseCommands):
PRIMARY_SERVICE_NAME_BY_ENGINE = {
'mongodb': 'mongodb',
'redis': 'redis',
'mysql': 'mysql',
'mysql_percona': 'mysql'
}
SECONDARY_SERVICE_NAME_BY_ENGINE = {
'mongodb': 'mongodb',
'redis': 'sentinel',
'... |
StartupsPoleEmploi/labonneboite | labonneboite/importer/conf/development.py | Python | agpl-3.0 | 497 | 0.002012 | # --- job 1/8 & 2/8 : check_etablissements & extract_etablissements
DISTINCT_DEPARTEMENTS_HAVING_OFFIC | ES = 15
# --- job 5/8 : compute_scores
SCORE_COEFFICIENT_OF_VARIATION_MAX = 8
MINIMUM_OFFICES_REQUIRED_TO_TRAIN_MODEL = 0
MAXIMUM_ | COMPUTE_SCORE_JOB_FAILURES = 94 # 96 departements == 2 successes + 94 failures
RMSE_MAX = 300
# --- job 6/8 : validate_scores
SCORE_REDUCING_MINIMUM_THRESHOLD = 0
# SCORE_ALTERNANCE_REDUCING_MINIMUM_THRESHOLD = 0
DEPARTEMENTS_TO_BE_SANITY_CHECKED = ['14', '69']
|
rdespoiu/QTitan | QTitan/QTSurvey/Controllers/BaseDemographicForm.py | Python | gpl-3.0 | 214 | 0.023364 | from django import forms
from | ..models import BaseDemographic
class BaseDemographicForm(forms.ModelForm):
class Meta:
model = BaseDemographic
fields = ['first_name','last_n | ame','phone','dob']
|
erikr/howtostoreiosdata | howtostoreiosdata/wizard/code_samples.py | Python | mit | 1,995 | 0.002506 | # All the code samples below have one parameter, which is where the protection level name
# for that storage type will be inserted, e.g. NSDataWritingFileProtectionCompleteUnlessOpen
CODE_SAMPLE_CORE_DATA = """
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (persistentStoreCoordinator_ != nil) {
... | ags]
"""
CODE_SAMPLE_RAW_DATA = """
NSData *contents = [@"secret file contents" dataUsingEncoding:NSUTF8StringEncoding];
[contents writeToFile:path
options:%s
error:&error];
"""
CODE_SAMPLE_KEYCHAIN = """
// Note that metadata, like the account name, is no | t encrypted.
NSDictionary *item = @{
(__bridge id)kSecAttrAccount: account,
(__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,
(__bridge id)kSecAttrAccessible: (__bridge id)%s,
(__bridge id)kSecValueData: data,
};
OSStatus error = SecItemAdd((__bridge CFDictionaryRef)item, NULL);
"""
|
platinhom/CADDHom | python/basic/HHGeometry.py | Python | gpl-2.0 | 2,547 | 0.016097 | import __init__
import math
import numpy as np
class Point:
'''Point at 3D. Some method for it. '''
def __init__ (self, x=0.0, y=0.0 ,z=0.0):
self.x=x
self.y=y
self.z=z
def coors(self):
coor=(self.x,self.y,self.z)
return coor
def dist_to(self,a... |
# -------------------------------- Vertex -------------------------
# -------------------------------- Edge ---------------------------
# -------------------------------- Face ---------------------------
# -------------------------------- Box ----------------------------
# -------------------------------- Cubic --... | ------
# -------------------------------- Ball ---------------------------
# -------------------------------- Grid ---------------------------
# ----------------------------- MultiGrid -------------------------
# -------------------------- High Dimension ? --------------------- |
tailhook/tilenol | tilenol/widgets/groupbox.py | Python | mit | 3,880 | 0.000258 | from collections import namedtuple
from cairo import LINE_JOIN_ROUND
from zorro.di import di, dependency, has_dependencies
from tilenol.groups import GroupManager
from tilenol.commands import CommandDispatcher
from .base import Widget
from tilenol.theme import Theme
from tilenol.window import Window
GroupState = na... | )
| canvas.stroke()
if gs.urgent:
canvas.set_source(self.urgent_color)
elif gs.empty:
canvas.set_source(self.inactive_color)
else:
canvas.set_source(self.active_color)
canvas.move_to(x + self.padding.left,
... |
lucianopuccio/golem | golem/cli/commands.py | Python | mit | 8,682 | 0.001497 | import os
import sys
import golem
from golem.core import (utils, session, suite as suite_module, test,
settings_manager, test_directory)
from golem.core.project import Project, create_project
from golem.gui import gui_start
from golem.test_runner.execution_runner import ExecutionRunner
from gol... | execution_runner.run_test(norm_query)
else:
if test_query == '.':
test_query = ''
path = os.path.join(session.testdir, 'projects',
project, 'tests', test_query)
if ... | n_runner.run_directory(test_query)
else:
msg = ('golem run: error: the value {} does not match '
'an existing test, suite or directory'.format(test_query))
sys.exit(msg)
else:
print(messages.RU... |
webeng/DeepLearningTutorials | code/convolutional_mlp.py | Python | bsd-3-clause | 12,771 | 0.001175 | """This tutorial introduces the LeNet5 neural network architecture
using Theano. LeNet5 is a convolutional neural network, good for
classifying images. This tutorial shows how to build the architecture,
and comes with all the hyper-parameters you need to reproduce the
paper's MNIST results.
This implementation simpl... | s of the fully-connected sigmoidal layer
layer3 = LogisticRegression(input=layer2.output, n_in=500, n_out=10)
# the cost we minimize during training is the NLL of the model
cost = layer3.negative_log_likelihood(y)
# create a function to compute the mistakes that are made by the model
test_mode | l = theano.function(
[index],
layer3.errors(y),
givens={
x: test_set_x[index * batch_size: (index + 1) * batch_size],
y: test_set_y[index * batch_size: (index + 1) * batch_size]
}
)
validate_model = theano.function(
[index],
layer3.errors(... |
7anshuai/white | white/domain/storage.py | Python | gpl-2.0 | 2,170 | 0.001382 | #!/usr/bin/env python
# 2015 Copyright (C) White
#
# 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, version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
#... | me.strip()
if sitename:
config['sitename'] = sitename
description = description or description.strip()
if description:
config['description'] = descriptio | n
site_page = int(site_page)
if site_page >= 0:
config['site_page'] = site_page
posts_per_page = int(posts_per_page)
if posts_per_page:
config['posts_per_page'] = posts_per_page
auto_published_comments = bool(auto_published_c... |
JiahuiZHONG/Internship_Thread | tests/scripts/thread-cert/Cert_6_4_01_LinkLocal.py | Python | bsd-3-clause | 2,986 | 0.001005 | #!/usr/bin/python
#
# Copyright (c) 2016, Nest Labs, 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:
# 1. Redistributions of source code must retain the above copyright
# notice, thi... | E
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIAB... | F ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
import pexpect
import time
import unittest
import node
LEADER = 1
ED = 2
class Cert_6_4_1_LinkLocal(unittest.TestCase):
def setUp(self):
self.nodes = {}
for i in range(1,3):
self.nodes[i] = node.Node(i)
self.nodes[LEADER].set... |
joaormatos/anaconda | mmfparser/player/players.py | Python | gpl-3.0 | 6,005 | 0.006828 | # Copyright (c) Mathias Kaerlev 2012.
# This file is part of Anaconda.
# Anaconda 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.
# ... | self.items = items = []
for control in header.controls.items:
player = self.new(Player)
player.initialize(control)
items.append(player)
def reset(self, fr | ame = False):
for player in self.items:
player.reset(frame) |
stanographer/plover | plover_build_utils/testing/parametrize.py | Python | gpl-2.0 | 1,189 | 0.000841 | import inspect
import pytest
def parametrize(tests, arity=None):
'''Helper for parametrizing pytest tests.
Expects a list of lambdas, one | per test. Each lambda must return
the parameters for its respective test.
Test identifiers will be automatically generated, from the test
number and its lambda definition line (1.10, 2.12, 3.20, ...).
If arity is None, the arguments being | parametrized will be automatically
set from the function's last arguments, according to the numbers of
parameters for each test.
'''
ids = []
argvalues = []
for n, t in enumerate(tests):
line = inspect.getsourcelines(t)[1]
ids.append('%u:%u' % (n+1, line))
argvalues.appe... |
CuonDeveloper/cuon | Distributionen/CuonServer/cuon-simple-server-install.py | Python | gpl-3.0 | 21,083 | 0.014846 | #!/usr/bin/python2.7
# cuon_server install
import os, sys, platform
import subprocess, shlex, shutil
import commands
import locale
import pwd, grp
from gi.repository import Gtk
import ConfigParser
class cssi():
def __init__(self, user=None):
self.user = user
self.win = None
... | g", "python-imaging-sane"]}, {"reportlab":["python-reportlab"]} , {"twisted.web":["python-twisted-web" ]}, {"twisted.words":["python-twisted-words"]}, {"pygments":["python-pygments"]}, {"webkit":["python-webkit"]},{"pg":["python-pygresql"]} ]
self.python_installer_debian = []
self.OS_Installer = None
... | l", "xterm"]
self.Terminal = None
self.cpServer = ConfigParser.ConfigParser()
self.CUON_FS = "/etc/cuon"
self.dia = MessageDialogWindow()
def checkOS(self):
print "start check OS"
if sys.platform.startswith('linux'):
# Linux-specific code here...
... |
maartenq/ansible | test/units/modules/network/exos/test_exos_config.py | Python | gpl-3.0 | 10,664 | 0.001407 | #
# (c) 2018 Extreme Networks Inc.
#
# 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.
#
# Ans... | ays'))
self.execute_module(changed=True)
self.assertEqual(self.run_commands.call_count, 1)
self.assertEqual(self.get_config.call_count, 0)
self.assertEqual(self.load_config.call_count, 0)
args = self.run_commands.call_args[0][1]
self.assertIn('save configuration', args['c... | ds = ['configure ports 1 description-string "IDS"',
'configure snmp sysName "marble"']
self.execute_module(changed=True, commands=commands)
self.assertEqual(self.run_commands.call_count, 1)
self.assertEqual(self.get_config.call_count, 1)
self.assertEqual(self.load_con... |
ZhaoCJ/django | django/db/migrations/writer.py | Python | bsd-3-clause | 7,931 | 0.001891 | from __future__ import unicode_literals
import datetime
import types
import os
from importlib import import_module
from django.utils import six
from django.db import models
from django.db.models.loading import cache
from django.db.migrations.loader import MigrationLoader
from django.utils.encoding import force_text
fro... | me)
@classmethod
def serialize_deconstructed(cls, path, args, kwargs):
module, name = path.rsplit(".", 1)
if module == "django.db.models":
imports = set(["from django.db import models"])
name = "models.%s" % name
else:
imports = set(["import %s" % mod... | name = path
arg_strings = []
for arg in args:
arg_string, arg_imports = cls.serialize(arg)
arg_strings.append(arg_string)
imports.update(arg_imports)
for kw, arg in kwargs.items():
arg_string, arg_imports = cls.serialize(arg)
... |
Kryz/sentry | tests/sentry/metrics/test_datadog.py | Python | bsd-3-clause | 979 | 0 | from __future__ import absolute_import
from mock import patch
from datadog.util.hostname import get_hostname
from sentry.metrics.datadog import DatadogMetricsBackend
from sentry.testutils import TestCase
class DatadogMetricsBackendTest(TestCase):
def setUp(self):
self.backend = DatadogMetricsBackend(pr... | ert_called_once_with(
'sentrytest.foo', 1,
tags=['instance:bar'],
host=get_hostname(),
)
@patch('datadog.threadstats.base.ThreadStats.timing')
def test_timing(self, mock_timing):
self.backend.timing('foo', 30, instance='bar') |
mock_timing.assert_called_once_with(
'sentrytest.foo', 30,
sample_rate=1,
tags=['instance:bar'],
host=get_hostname(),
)
|
pluser/nikola_plugins | v7/wordpress_compiler/wordpress/wordpress.py | Python | mit | 11,780 | 0.002547 | # -*- coding: utf-8 -*-
# A WordPress compiler plugin for Nikola
#
# Copyright (C) 2014-2015 by Felix Fontein
# Copyright (C) by the WordPress contributors
#
# 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... | super(CompileWordpress, self).__init__()
self.__filters = dict()
self.__shortcodes = shortcodes.ShortCodes( | )
self.__default_wordpress_filters = default_filters.DefaultWordpressFilters(self.__shortcodes)
self.add_filter("the_content", lambda data, context: self.__default_wordpress_filters.wptexturize(data))
self.add_filter("the_content", lambda data, context: self.__default_wordpress_filters.convert_... |
OxES/k2sc | src/detrender.py | Python | gpl-3.0 | 7,258 | 0.012951 | from __future__ import division
import math as m
import numpy as np
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as pl
from scipy.optimize import fmin, fmin_powell, minimize
from numpy import (any, array, asarray, ones, ones_like, zeros, isfinite, inf, concatenate, arange, unique, delete,
... | 75, lw=1)
setp(ax, ylim=(0.999*(fmin-0.7*fptp), 1.001*fmax))
setp(ax, xlim=self.data.mt[[0,-1]], xlabel='Time', ylabel='Flux')
return ax
def plot_report(self, pv, tid, fname=None, maxpt=350):
| lmargin, rmargin = 0.12, 0.03
fig = pl.figure(figsize=(8.3,11.7))
fig.text(0.04, 0.965, 'EPIC {:9d}'.format(tid), va='top', size=24, color='w', weight='bold')
ax = fig.add_axes([0,0,1,1])
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
ax.set_zorder(-1000)
... |
MichaelSchreier/Kano | class_UI_aboutWindow.py | Python | gpl-3.0 | 4,429 | 0.029153 | # -*- coding: utf-8 -*-
"""
Created on Sat Sep 17 17:19:10 2016
@author: Michael
"""
from PyQt5 import QtWidgets
class AboutWindow(QtWidgets.QTextEdit):
def __init__(self, parent=None):
super().__init__(parent)
self.setReadOnly(True)
self.setHtml(
"""
<h1 id="kano">Kano</h1>
<p>Co... | id="fuzzywuzzy">FuzzyWuzzy</h3>
<blockquote>
<p>Copyright (c) 2017, SeatGeak <br>
All rights reserved.</p>
<p>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 ... | ption) any later version.</p>
<p>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 General Public License for more details.</p>
<p>You should have rec... |
benley/Mathics | mathics/builtin/physchemdata.py | Python | gpl-3.0 | 5,698 | 0.000527 | # -*- coding: utf8 -*-
"""
Physical and Chemical data
"""
from csv import reader as csvreader
from mathics.builtin.base import Builtin
from mathics.core.expression import (Expression, from_python, Symbol, String,
strip_context)
from mathics.settings import ROOT_DIR
def load_ele... | ("Missing", " | NotAvailable")
if result == "NOT_APPLICABLE":
return Expression("Missing", "NotApplicable")
if result == "NOT_KNOWN":
return Expression("Missing", "Unknown")
result = parse(result, evaluation.definitions)
if isinstance(result, Symbol):
result = Stri... |
mikewiebe-ansible/ansible | lib/ansible/plugins/action/nxos.py | Python | gpl-3.0 | 8,307 | 0.003732 | #
# (c) 2016 Red Hat Inc.
#
# 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 d... | ion either httpapi or ansible.netcommon.httpapi (whichever is applicable)'])
else:
return {'failed': True, 'msg': 'Connection type %s is not valid for this module' % self._play_context.connection}
result = super(ActionModule, self).run(task_vars=task_vars)
if warnings:
i... | @staticmethod
def nxapi_implementation(provider, play_context):
provider['transport'] = 'nxapi'
if provider.get('host') is None:
provider['host'] = play_context.remote_addr
if provider.get('port') is None:
if provider.get('use_ssl'):
provider['port'... |
jaggu303619/asylum | openerp/addons/auth_crypt/auth_crypt.py | Python | agpl-3.0 | 5,849 | 0.009574 | #
# Implements encrypting functions.
#
# Copyright (c) 2008, F S 3 Consulting Inc.
#
# Maintainer:
# Alec Joseph Rivera (agi<at>fs3.ph)
# refactored by Antony Lesuisse <al<at>openerp.com>
#
import hashlib
import hmac
import logging
from random import sample
from string import ascii_letters, digits
import openerp
from... | ncrypted_password(cr, uid, stored_password)
try:
return super(res_users, self).check_credentials(cr, uid, password)
except openerp.exceptions.AccessDenied:
# check md5crypt
if stored_password_crypt:
if stored_password_crypt[:len(magic_md5)] == magi | c_md5:
salt = stored_password_crypt[len(magic_md5):11]
if stored_password_crypt == md5crypt(password, salt):
return
elif stored_password_crypt[:len(magic_md5)] == magic_sha256:
salt = stored_password_crypt[len(magic_md5)... |
SANDEISON/The-Huxley | Python/Sorveteria Tropical,py.py | Python | gpl-3.0 | 351 | 0.005698 | sabor = input()
quantidade = int(input())
if sabor.lower() == "morango" or sabor.lower() == "cereja":
total = quantidade*4.50
elif sabor.lower() == "damasco" or sabor.lower() == "siriguela":
total = qu | antidade*3.80
else:
total = quantidade*2.75
print("%.2f"%total)
if quantidade > 2:
print ("COM CALDA")
else:
pr | int("SEM CALDA")
|
pimutils/todoman | todoman/__init__.py | Python | isc | 133 | 0 | from todoman import version # ty | pe: ignore
__version__ = version.version
__documentation__ | = "https://todoman.rtfd.org/en/latest/"
|
niccokunzmann/ledtable | python/ledtable/SerialLEDTable.py | Python | mit | 4,859 | 0.004322 | #!/usr/bin/python3
from . tkLEDTable import *
try:
import serial
except:
import sys
print("Install the serial module width '{} -m pip install PySerial'.".format(sys.executable))
raise
import threading
try:
from queue import Queue
except ImportError:
from Queue import Queue
import itertools
def... |
def __init__(self, led_table, file):
super(SerialLEDTable, self).__init__()
self.led_table = led_ | table
self.file = file
def run(self):
for line in self.file:
if not line.startswith(self.COMMAND_CHARACTER):
self.default_line(line)
else:
self.command_line(line[1:])
def default_line(self, line):
if line.endswith(b"\n"):
... |
Linhua-Sun/p4-phylogenetics | p4/Data.py | Python | gpl-2.0 | 31,372 | 0.005355 | from Alignment import Alignment
import sys,time,os
import pf,func
from Var import var
from Glitch import Glitch
class Data:
"""All the alignments that you want to work with, in one place.
Initialize this with one of
- nothing (or None),
- a list of Alignment objects, or
- a single Alignment... | If there is
more than one alignment, there is possibly more than one
datatype, and so this method will refuse to do it. Note that
the unconstrained log like of the combined data is not the sum
of t | he unconstrained log likes of the separate partitions.
See also calcUnconstrainedLogLikelihood2
"""
if len(self.alignments) > 1:
gm = ["Data.c |
Skreex/LPTHW | ex14.py | Python | mit | 529 | 0.00189 | from sys import argv
script, user_name = argv
prompt = '> '
print "Hi %s, I'm the %s script." % (user_name, script)
print "I'd like to ask you a few questions."
print "Do you like me %s?" % user_na | me
likes = raw_input(prompt)
print "Where do you live %s?" % user_name
lives = raw_input(prompt)
print "What kind of computer do you have?"
computer = raw_input(prompt)
print """
Alright, so you said %r about liking me.
You live in %r. Not sure where that is.
And you have a %r computer. Nice.
""" % (likes, lives, co... | |
dwilmer/rcpsp-testing-framework | dataset.py | Python | mit | 3,291 | 0.036159 | import string, copy
def joinHeaders(first, second, joined, on):
joined.headers = first.headers[:]
mappedHeaders = {}
for header in second.headers:
if header == on:
continue
i = 0
newHeader = header
while newHeader in first.headers:
newHeader = '{0}_{1}'.format(newHeader, i)
i += 1
if i > 0:
ma... | a new dataset.
The original datasets remain unchanged.
The third argument is t | he header on which to join"""
# check for correct join
if not (on in self.headers or on in other.headers):
print "Error: header '{0}' not found in both collections".format(on)
return None
# create new dataset
joined = Dataset()
# fill new dataset with combined data
mappedHeaders = joinHeaders(self... |
daviddrysdale/python-phonenumbers | python/phonenumbers/data/region_881.py | Python | apache-2.0 | 569 | 0.008787 | """Auto-generated file, do not edit by hand. 881 metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_ME | TADATA_881 = PhoneMetadata(id='001', country_code=881, international_prefix=None,
general_desc=PhoneNumberDesc(national_number_pattern='[0-36-9]\\d{8}', possible_length=(9,)),
mobile=PhoneNumberDesc(national_number_pattern='[0-36-9]\\d{8}', example_number='612345678', possible_length=(9,)),
number_format=[N... | 3', leading_digits_pattern=['[0-36-9]'])])
|
chessco/cursus | controllers/utils.py | Python | apache-2.0 | 25,293 | 0.000474 | # 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 ... | self.error(404)
return
handler = getattr(self, 'get_%s' % action)
if not handler:
self.error(404)
return
return handler()
def post(self):
"""Handles POST."""
action = self.request.get('action')
if not action or action not i... | st_%s' % action)
if not handler:
self.error(404)
return
# Each POST request must have valid XSRF token.
xsrf_token = self.request.get('xsrf_token')
if not XsrfTokenManager.is_xsrf_token_valid(xsrf_token, action):
self.error(403)
return
... |
ielnehc/ltmh | tools/get_public_ip.py | Python | mit | 610 | 0.02623 | #!/usr/bin/env python
import re,urllib2
class Get_public_ip:
def getip(self):
try:
myip = self.visit("http://www.whereismyip.com/")
except:
try:
myip = self.visit("http://www.ip138. | com/ip2city.asp")
| except:
myip = "So sorry!!!"
return myip
def visit(self,url):
opener = urllib2.urlopen(url)
if url == opener.geturl():
str = opener.read()
return re.search('\d+\.\d+\.\d+\.\d+',str).group(0)
if __name__ == "__main__":
getmyip = Get_public_ip()
pr... |
singularityhub/sregistry | shub/apps/base/sitemap.py | Python | mpl-2.0 | 917 | 0.001091 | """
Copyright (C) 2017-2021 Vanessa Sochat.
This Source Code Form is subject to the terms of the
Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed
with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
from django.contrib.sitemaps import Sitemap
from shub.apps.main.models imp... | ngefreq = "weekly"
def lastmod(self, obj):
return obj.build_date
def items(self):
return [x for x in Container.objects.all() if x.collection.priva | te is False]
class CollectionSitemap(BaseSitemap):
changefreq = "weekly"
def lastmod(self, obj):
return obj.modify_date
def items(self):
return [x for x in Collection.objects.all() if x.private is False]
|
AndreasAntener/mavlink | pymavlink/examples/__init__.py | Python | lgpl-3.0 | 88 | 0.011364 | '''This folder contains various examp | le scripts demonstrating | MAVLink functionality.'''
|
ThomasStivers/nvda-notepadPlusPlus | addon/appModules/notepad++/autocomplete.py | Python | gpl-2.0 | 210 | 0.033333 | from NVD | AObjects.IAccessible import IAccessible
import nvwave
import speech
import os
class AutocompleteList(IAccessible):
def event_selection(s | elf):
speech.cancelSpeech()
speech.speakText(self.name)
|
roy-boy/python_scripts | file_parser.py | Python | gpl-3.0 | 847 | 0 | """file_parser.py reads text file and parse the item into a list."""
def file_to_list(input_file):
data_list_trim = []
try:
with open(input_file) as in_put:
input_data = in_put.readlines()
if len(input_data) == 1:
print()
data_list = input_data[0... | trim = data_list.split(',')
elif len(input_data) > 1:
print()
for row in input_data:
row_list = row.replace('"', '').strip()
row_list_trim = row_list.split(',')
data_list_trim = data_list_trim + row_list_trim
... | SError as err:
print('Failed to open file', err)
return data_list_trim
|
iulian787/spack | var/spack/repos/builtin/packages/r-bigmemory-sri/package.py | Python | lgpl-2.1 | 708 | 0.00565 | # Copyright 2013-2020 Lawrence Livermore Nationa | l Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RBigmemorySri(RPackage):
"""This package provides a shared resource interface
for the bigmemory and synchronicity packages."""
... | https://cloud.r-project.org/src/contrib/Archive/bigmemory.sri"
version('0.1.3', sha256='55403252d8bae9627476d1f553236ea5dc7aa6e54da6980526a6cdc66924e155')
|
littlezz/ESL-Model | tests/test_ch4.py | Python | mit | 5,437 | 0.002391 | import pytest
from .utils import digit_float
import numpy as np
vowel_data_y_dimension = 11
@pytest.fixture
def vowel_data():
from esl_model.datasets import VowelDataSet
data = VowelDataSet()
return data.return_all()
@pytest.fixture
def SAHeart_data():
from esl_model.datasets import SAHeartDataSet... | a
lda = LDAModel(train_x=train_x, train_y=train_y, n_class=vowel_data_y_dimension)
lda.pre_processing()
lda.train()
print(lda.y_hat[:10])
print(lda.error_rate)
te = lda.test(test_x, test_y)
print(te.error_rate)
assert digit_float(lda.error_rate) == 0.316
assert digit_float(te.err... | 4.models import QDAModel
train_x, train_y, test_x, test_y, features = vowel_data
qda = QDAModel(train_x=train_x, train_y=train_y, n_class=vowel_data_y_dimension)
qda.pre_processing()
qda.train()
print(qda.y_hat[:10])
print(qda.error_rate)
te = qda.test(test_x, test_y).error_rate
print(... |
danfr/RemoteTV | Server/bin/Setup.py | Python | mit | 269 | 0.003717 | import os
import sys
from pathlib import Path
class Setup:
CONFIGURATION_FILE = os.path.join(Path(__file__).parents[1], "config", "server.cfg")
VLC_DEFAULT_COMMA | ND = "vlc -f"
POSIX = 'posix' in sys.builtin_module_na | mes
VLC_PLAYLIST_END = "vlc://quit"
|
likelyzhao/mxnet | example/rcnn/rcnn/symbol/proposal_target.py | Python | apache-2.0 | 3,893 | 0.002312 | """
Proposal Target Operator selects foreground and background roi and assigns label, bbox_transform to them.
"""
from __future__ import print_function
import mxnet as mx
import numpy as np
from distutils.util import strtobool
from rcnn.io.rcnn import sample_rois
DEBUG = False
class ProposalTargetOperator(mx.opera... | is(all_r | ois, fg_rois_per_image, rois_per_image, self._num_classes, gt_boxes=gt_boxes)
if DEBUG:
print("labels=", labels)
print('num fg: {}'.format((labels > 0).sum()))
print('num bg: {}'.format((labels == 0).sum()))
self._count += 1
self._fg_num += (labels > ... |
saketkc/statsmodels | statsmodels/tsa/statespace/tests/test_structural.py | Python | bsd-3-clause | 9,003 | 0.001666 | """
Tests for structural time series models
Author: Chad Fulton
License: Simplified-BSD
"""
from __future__ import division, absolute_import, print_function
import numpy as np
import pandas as pd
import os
import warnings
from statsmodels.datasets import macrodata
from statsmodels.tsa.statespace import structural
fr... | run_ucm('deterministic_constant')
def test_random_walk():
run_ucm('random_walk')
def test_local_level():
run_ucm('local_level')
def test_fixed_slope():
run_ucm('fixed_slope')
def test_fixed_slope():
warnings.simplefilter("always")
with warnings.catch_warnings(record=True) as w:
r... | (w[0].message), message)
def test_deterministic_trend():
run_ucm('deterministic_trend')
def test_random_walk_with_drift():
run_ucm('random_walk_with_drift')
def test_local_linear_deterministic_trend():
run_ucm('local_linear_deterministic_trend')
def test_local_linear_trend():
run_ucm('local_line... |
ifduyue/sentry | src/sentry/filters/localhost.py | Python | bsd-3-clause | 996 | 0.002008 | from __future__ import absolute_import
from .base import Filter
from six.moves.urllib.parse import urlparse
from sentry.utils.data_filters import FilterStatKeys
LOCAL_IPS = frozenset(['127.0.0.1', '::1'])
LOCAL_DOMAINS = frozenset(['127.0.0.1', 'localhost'])
class LocalhostFilter(Filter):
id = FilterStatKeys.LO... | .1``) and IPv6 (``::1``) addresses.'
def get_ip_address(self, data):
try:
return data['sentry.interfaces.User']['ip_address']
except KeyError:
return ''
def get_url(self, data):
try:
return data['sentry.interfaces.Http']['url'] or ''
except K... | get_domain(self, data):
return urlparse(self.get_url(data)).hostname
def test(self, data):
return self.get_ip_address(data) in LOCAL_IPS or self.get_domain(data) in LOCAL_DOMAINS
|
masom/Puck | server/controllers/root.py | Python | lgpl-3.0 | 2,450 | 0.002041 | '''
Puck: FreeBSD virtualization guest configuration server
Copyright (C) 2011 The Hotel Communication Network inc.
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 Lic... | def index(self):
return self.render("index.html", self.crumbs[:-1])
@cherrypy.expose
def login(self, **post):
if post:
self._login(post)
return self.render("login.html", self.crumbs[:-1])
@cherrypy.expose
def logout(self, **post):
cherrypy.session.delete()
... | ogin")
def add(self, route, cls):
self._routes[route] = cls
def load(self):
[setattr(self, route, self._routes[route](self._lookup)) for route in self._routes]
def _login(self, post):
fields = ['user.username', 'user.password']
for f in fields:
if n... |
LRGH/amoco | amoco/arch/avr/asm.py | Python | gpl-2.0 | 10,020 | 0.000499 | # -*- coding: utf-8 -*-
# This code is part of Amoco
# Copyright (C) 2014 Axel Tillequin (bdcht3@gmail.com)
# published under GPLv2 license
from amoco.arch.avr.env import *
from amoco.cas.mapper import mapper
# ------------------------------------------------------------------------------
# low level functions :
def... | ((a.bit(3)) & (b.bit(3)))
| ((b.bit(3)) & (~x.bit(3)))
| ((a.bit(3)) & (~x.bit(3)))
)
# flags for logical operations:
def __setflags__L(i, fmap, a, b, x):
fmap[zf] = x == 0
fmap[nf] = x.bit(7)
fmap[vf] = bit0
fmap[sf] = fmap[nf] ^ fmap[vf]
# flags for shift operations:
def ... | fmap[vf] = fmap[nf] ^ fmap[cf]
fmap[sf] = fmap[nf] ^ fmap[vf]
# ixxx is the translation of AVR instruction xxx.
# ------------------------------------------------------------------------------
@__pc
def i_NOP(i, fmap):
pass
def i_SLEEP(i, fmap):
fmap[pc] = ext("SLEEP", size=pc.size).call(fmap)
def i... |
glemaitre/protoclass | protoclass/data_management/t2w_modality.py | Python | gpl-2.0 | 8,496 | 0 | """T2W modality class."""
import warnings
import numpy as np
import SimpleITK as sitk
from .standalone_modality import StandaloneModality
from ..utils.validation import check_path_data
class T2WModality(StandaloneModality):
"""Class to handle T2W-MRI modality.
Parameters
----------
path_data : st... | .
"""
def __init__(self, path_data=None):
super(T2WModality, self).__init__(path_data=path_data)
def get_pdf(self, roi_data=None, nb_bins='auto'):
""" Extract the a list of pdf related with the data.
Parameters
----------
roi_data : tuple
Indices of el... | ogram.
The ROI is a 3D volume which will be used for each time serie.
nb_bins : list of int or str, optional (default='auto')
The numbers of bins to use to compute the histogram.
The possibilities are:
- If 'auto', the number of bins is found at fitting time.
... |
logston/python-dircmp | dircmppy/dircmpdel.py | Python | bsd-2-clause | 2,648 | 0.000755 | import os
import errno
def delete_file(file_name, dry=False):
if dry:
print(' DRY DELETED: {}'.format(file_name))
else:
os.remove(file_name)
try:
dirname = os.path.dirname(file_name)
os.rmdir(dirname)
print(' DELETED DIR: {}'.format(dirname))
... | format(file_name))
else:
if prompt:
while True:
resp = input(' Delete {}? '.format(file_name))
resp = resp.lower()
if resp not in ('yes', 'no'):
print('Please answer "ye... | break
elif resp == 'no':
print(' Not deleted: {}'.format(file_name))
break
else:
delete_file(file_name, dry=dry)
print()
if __name__ == '__main__':
import argparse
parser = a... |
exratione/thywill-python | thywill_server/src/thywill_server/database/__init__.py | Python | mit | 105 | 0.028571 | '''
This component package | and its subpa | ckages contain wrapper and glue code for database operations.
''' |
securestate/king-phisher | king_phisher/client/tabs/campaign.py | Python | bsd-3-clause | 32,510 | 0.027592 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# king_phisher/client/tabs/campaign.py
#
# 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
# not... | reeview,
selection_mode=Gtk.SelectionMode.MULTIPLE,
cb_delete=self._prompt_to_delete_row,
cb_refresh=self.load_campaign_information
)
self.treeview_manager.set_column_titles(
self.view_column_titles,
column_offset=1,
renderers=tuple(column.cell | _renderer() for column in self.view_columns)
)
for column in self.view_columns:
if isinstance(column, extras.ColumnDefinitionDatetime):
self.treeview_manager.column_views[column.title].set_fixed_width(150)
self.popup_menu = self.treeview_manager.get_popup_menu()
"""The :py:class:`Gtk.Menu` object which i... |
Sticklyman1936/workload-automation | wlauto/common/resources.py | Python | apache-2.0 | 1,635 | 0.001223 | # Copyright 2013-2015 ARM Limited
#
# 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... | format(self.owner, self.name, self.path or self.url)
class ExtensionAsset(File):
name = 'extension_asset'
def __init__(self, owner, path):
super(ExtensionAsset, self).__init__(owner, os.path.join(owner.name, path))
class Executable(FileResource):
name = 'executable'
def __init__(self, ow... | filename
def __str__(self):
return '<{}\'s {} {}>'.format(self.owner, self.platform, self.filename)
|
archatas/whoosh | whoosh/lang/lovins.py | Python | apache-2.0 | 12,657 | 0.003871 | """This module implements the Lovins stemming algorithm. Use the ``stem()``
function::
stemmed_word = stem(word)
"""
from whoosh.util.collections2 import defaultdict
# Conditions
def A(base):
# A No restrictions on stem
return True
def B(base):
# B Minimum stem length = 3
return len(base) >... | 1] != "e"
|
def F(base):
# F Minimum stem length = 3 and do not remove ending after e
return len(base) > 2 and base[-1] != "e"
def G(base):
# G Minimum stem length = 3 and remove ending only after f
return len(base) > 2 and base[-1] == "f"
def H(base):
# H Remove ending only after t or ll
c1, c2 = ba... |
cinderella/incubator-cloudstack | test/integration/component/test_snapshots.py | Python | apache-2.0 | 57,945 | 0.001778 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | "displayname": "TestVM",
"username": "root",
"password": "password",
"ssh_port": 22,
"hypervisor": 'XenServer',
... | 22,
"protocol": 'TCP',
},
"mgmt_server": {
"ipaddress": '192.168.100.21',
"username": "root",
"password": "fr3sca",
... |
ric2b/Vivaldi-browser | chromium/build/android/pylib/utils/argparse_utils.py | Python | bsd-3-clause | 1,695 | 0.00649 | # 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 argparse
class CustomHelpAction(argparse.Action):
'''Allows defining custom help actions.
Help actions can run even when the parser would oth... | action='custom_help',
custom_help_text='this is the help message',
help='What this helps with')
'''
# Derived from argparse._HelpAction fr | om
# https://github.com/python/cpython/blob/master/Lib/argparse.py
# pylint: disable=redefined-builtin
# (complains about 'help' being redefined)
def __init__(self,
option_strings,
dest=argparse.SUPPRESS,
default=argparse.SUPPRESS,
custom_help_text=No... |
skylines-project/skylines | tests/schemas/schemas/test_club.py | Python | agpl-3.0 | 1,722 | 0.000581 | import pytest
from marshmallow import ValidationError
from skylines.schemas import ClubSchema
def test_deserialization_fails_for_empty_name():
with pytest.raises(ValidationError) as e:
ClubSchema(only=("name",)).load(dict(name=""))
errors = e.value.messages
assert "name" in errors
assert "M... |
ClubSchema(partial=True).load(dict(website="foo"))
errors = e.value.messages
assert "website" in errors
assert "Not a valid URL." in errors.get( | "website")
def test_serialization_passes_for_invalid_website():
data = ClubSchema().dump(dict(website="foobar")).data
assert data["website"] == "foobar"
|
AsgerPetersen/QGIS | python/plugins/processing/algs/lidar/lastools/lasinfoPro.py | Python | gpl-2.0 | 5,416 | 0.001846 | # -*- coding: utf-8 -*-
"""
***************************************************************************
lasinfoPro.py
---------------------
Date : October 2014 and May 2016
Copyright : (C) 2014 by Martin Isenburg
Email : martin near rapidlasso point com
***... | commands = [os.path.join(LAStoolsUtils.LAStoolsPath(), "bin", " | lasinfo.exe")]
else:
commands = [os.path.join(LAStoolsUtils.LAStoolsPath(), "bin", "lasinfo")]
self.addParametersVerboseCommands(commands)
self.addParametersPointInputFolderCommands(commands)
if self.getParameterValue(lasinfoPro.COMPUTE_DENSITY):
commands.append("... |
merc-devel/merc | merc/application.py | Python | mit | 4,731 | 0.013316 | import asyncio
import datetime
import logging
import signal
import yaml
import passlib.context
from merc import config
from merc import config_format
from merc import channel
from merc import feature
from merc import server
from merc import user
from merc import util
logger = logging.getLogger(__name__)
class App... | return self.config["admin"]["name"]
@property
def admin_email(self):
return self.config["admin"]["email"]
def register_signal_handlers(self):
signal.signal(signal.SIGHUP, lambda signum, frame: self.rehash())
def run_hooks(self, hook_name, *args, **kwargs):
for hook in self.features.get_hooks(h... | .NAME].server_locals
def start(self):
logger.info("Welcome to merc-{}, running for {} ({}) on network {}.".format(
util.get_version(), self.config["server"]["name"],
self.config["server"]["sid"], self.config["server"]["network_name"]))
self.loop.run_until_complete(self.bind())
self._aut... |
anhstudios/swganh | data/scripts/templates/object/mobile/shared_dressed_deathstar_debris_cultist_hum_m_02.py | Python | mit | 464 | 0.047414 | #### 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_dressed_deathstar_debris_cultist_hum_m_02.iff"
result.attribute_template_id = 9
result.stfName("obj_n","unknown_creature | ")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
fjruizruano/ngs-protocols | divsum_analysis.py | Python | gpl-3.0 | 974 | 0.011294 | #!/usr/bin/python
import sys
print "divsum_analysis.py DivsumFile NumberOfNucleotides"
try:
file = sys.argv[1]
except:
file = raw_input("Introduce RepeatMasker's Divsum file: ")
try:
nucs = sys.argv[2]
except:
nucs = raw_input("Introduce number of analysed nucleotides: ")
nucs = int(nucs)
data = o... | el):
matrix[n][1].append(int(info[n]))
abs = open(file+".abs", "w")
rel = open(file+".rel", "w")
for n in range(0,n_el):
ab | s.write("%s\t%s\n" % (matrix[n][0], sum(matrix[n][1])))
rel.write("%s\t%s\n" % (matrix[n][0], round(1.0*sum(matrix[n][1])/nucs,100)))
|
metabrainz/listenbrainz-server | listenbrainz_spark/recommendations/recording/recommend.py | Python | gpl-2.0 | 19,039 | 0.004254 | """
This script is responsible for generating recommendations for the users. The general flow is as follows:
The best_model saved in HDFS is loaded with the help of model_id which is fetched from model_metadata_df.
`spark_user_id` and `recording_id` are fetched from top_artist_candidate_set_df and are given as input t... |
exc_info=True)
raise
def get_recording_mbids(params: Rec | ommendationParams, recommendation_df, users_df):
""" Get recording mbids corresponding to recommended recording ids sorted on rating.
Args:
params: RecommendationParams class object.
recommendation_df: Dataframe of spark_user_id, recording id and rating.
users_df : user_... |
BackupTheBerlios/namingmuse | tools/freedb-submit.py | Python | gpl-2.0 | 936 | 0.001068 | #!/usr/bin/env python
import os, re, sys
if len(sys.argv) < 2:
print "usage: %s <recordfile>" % sys.argv[0]
sys.exit(1)
# Read record
filename = sys.argv[1]
fd = file(filename)
record = fd.read()
fd.close()
# Update revision
newrecord = []
lbreak = "\r\n"
for line in record.splitlines():
if line.startsw... | .org'
ident = os.path.splitext(filename)[0]
if not re.search('^[a-z]+ [a-z0-9]{8}$', ident):
sys.exit(ident + " is not a valid freedb `discid genre' pair")
subject = "cddb %s" % ident
# Save updated record
fd = file(filena | me, "w")
fd.write(newrecord)
fd.close()
# Send mail
print "Subject:", subject
cmd = 'cat "%s" | mutt -s "%s" %s' % (filename, subject, address)
print "%", cmd
os.system(cmd)
|
teamtaverna/core | app/api/cruds/utils.py | Python | mit | 760 | 0.002632 | from graphql_relay.node.node import from_global_id
def get_errors(e):
# transform django errors to redux errors
# django: {"key1": [value1], {"key2": [value2]}}
# redux: ["key1", "value1", "key2", "value2"]
fields = e.message_dict.keys()
messages = ['; '.join(m) for m in e.message_dict.values()]
... |
def get_object(object_name, relayId, otherwise=None):
try:
return object_name.objects.get(pk=from_global_id(relayId)[1])
except:
return otherwise
def load_object(instance, args, exception=['id']):
if instance:
[setattr(instance, key, value) for key, val | ue in args.items() if key not in exception]
return instance
|
calancha/DIRAC | Resources/Computing/SSHComputingElement.py | Python | gpl-3.0 | 24,359 | 0.036332 | ########################################################################
# $HeadURL$
# File : SSHComputingElement.py
# Author : Dumitru Laurentiu, A.T.
########################################################################
""" SSH (Virtual) Computing Element: For a given IP/host it will send jobs directly through ... | xpect.EOF, 'assword: '] )
if i == 0: # Timeout
return S_OK( ( -1, child.before, 'SSH login failed' ) )
elif i == 1: # SSH does not have the public key. Just accept it.
child.sendline ( 'yes' )
child.expect ( 'ass | word: ' )
i = child.expect( [pexpect.TIMEOUT, 'assword: '] )
if i == 0: # Timeout
return S_OK( ( -1, str( child.before ) + str( child.after ), 'SSH login failed' ) )
elif i == 1:
child.sendline( self.password )
child.expect( pexpect.EOF )
ret... |
ebu/PlugIt | tests/helpers/pop_server/server.py | Python | bsd-3-clause | 4,827 | 0.001243 | """
Small POP server. Heavilly based on
pypopper: a file-based pop3 server (http://code.activestate.com/recipes/534131-pypopper-python-pop3-server/)
Useage:
python server.py
Will return all mail*.txt in the current folder as mail. Output is also printed.
"""
import logging
import socket
import glob
loggi... | lit("\r\n")
self.index = int(filename.split('mail')[1].split('.txt')[0])
f | inally:
msg.close()
def handleUser(data, msgs):
log.info("USER:%s", data.split()[1])
return "+OK user accepted"
def handlePass(data, msgs):
log.info("PASS:%s", data.split()[1])
return "+OK pass accepted"
def handleStat(data, msgs):
return "+OK %i %i" % (len(msgs), sum([msg.size for... |
sacharya/nova | nova/tests/api/openstack/compute/plugins/v3/test_admin_password.py | Python | apache-2.0 | 5,987 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack Foundation
# Copyright 2013 IBM Corp.
# 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
#... | request = '<change_password></change_password>'
expected = {'body': {'change_password': None}}
res = self.deserializer.default(request)
self.assertEqual(res, expected)
def test_change_pass_no_pass(self):
request = """<?xml version="1.0" encoding="UTF-8"?>
<change_pa... | .default(request)
expected = {
"change_password": None
}
self.assertEqual(request['body'], expected)
def test_change_pass_empty_pass(self):
request = """<?xml version="1.0" encoding="UTF-8"?>
<change_password
xmlns="http://docs.opensta... |
kubevirt/client-python | test/test_v1_i6300_esb_watchdog.py | Python | apache-2.0 | 927 | 0.001079 | # coding: utf-8
"""
KubeVirt API
This is KubeVirt API an add-on for Kubernetes.
OpenAPI spec version: 1.0.0
Contact: kubevirt-dev@googlegroups.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
import unittest
i... | _esb_watchdog.V1I6300ESB | Watchdog()
pass
if __name__ == '__main__':
unittest.main()
|
openstack/mistral | mistral/tests/unit/api/v2/test_cron_triggers.py | Python | apache-2.0 | 8,830 | 0 | # Copyright 2014 - Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | 3e4567-e89b-12d3-a456-426655440000', 'name': 'my_wf'})
TRIGGER = {
'id': '02abb422-55ef-4bb2-8cb9-217a583a6a3f',
'name': 'my_cron_trigger',
'pattern': '* * * * *',
' | workflow_name': WF.name,
'workflow_id': '123e4567-e89b-12d3-a456-426655440000',
'workflow_input': '{}',
'workflow_params': '{}',
'scope': 'private',
'remaining_executions': 42
}
trigger_values = copy.deepcopy(TRIGGER)
trigger_values['workflow_input'] = json.loads(
trigger_values['workflow_input... |
charismaticchiu/Robotics | ArNetworking/pythonExamples/drawingsExample.py | Python | gpl-2.0 | 6,718 | 0.018904 | """
MobileRobots Advanced Robotics Interface for Applications (ARIA)
Copyright (C) 2004, 2005 ActivMedia Robotics LLC
Copyright (C) 2006, 2007, 2008, 2009 MobileRobots 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 b... | ng with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
MobileRobots for information about a commercial version of ARIA at
robots@mobilerobots.com or
MobileRobots Inc, 10 C... | e server that shows how to draw arbitrary figures in a
# client (e.g. MobileEyes).
# These are callbacks that respond to client requests for the drawings'
# geometry data.
def exampleHomeDrawingNetCallback(client, requestPkt):
print "exampleHomeDrawingNetCallback"
reply = ArNetPacket()
# 7 Vertices
repl... |
rogeliorv/asuna | manage.py | Python | apache-2.0 | 250 | 0.004 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.envir | on.setdefault("DJANGO_SETTINGS_MODULE", "asuna.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys. | argv)
|
siouka/dmind | plugin.video.tvpor/resources/lib/unwise.py | Python | gpl-2.0 | 2,506 | 0.027933 | # -*- coding: latin-1 -*-
import re
import math
import urllib
from string import join
import traceback, sys
class JsUnwiser:
def unwiseAll(self, data):
try:
in_data=data
sPattern = 'eval\\(function\\(w,i,s,e\\).*?}\\((.*?)\\)'
wise_data=re.compile(sPattern).findall(in_... | ll1l)
ll11 = -1;
if ( ord(I1lI[ll1I]) % 2):
ll11 = 1;
#print 'val is ', lI1l[lIll: lIll+2]
l1ll.append(chr( int(lI1l[lIll: lIll+2], 36) - ll11));
ll1I+=1;
if (ll1I >= len(l1lI)):
| ll1I = 0;
ret=''.join(l1ll)
if 'eval(function(w,i,s,e)' in ret:
ret=re.compile('eval\(function\(w,i,s,e\).*}\((.*?)\)').findall(ret)[0]
return self.unwise(ret)
else:
return ret
|
saukrIppl/seahub | seahub/institutions/urls.py | Python | apache-2.0 | 391 | 0.002558 | from django.conf.urls import patterns, url
from .views import info, useradmin, user_info, user_remove
urlpatterns = patterns(
'',
url('^info/$', info, name="info"),
url('^useradmin/$', useradmin, | name="useradmin"),
url(r'^useradmin/info/(?P<email>[^/]+)/$', user_info, name='user_info'),
url(r'^useradmin/remove/(?P<email>[^/]+)/$', user_remove, name='use | r_remove'),
)
|
SMALLplayer/smallplayer-image-creator | storage/.xbmc/addons/script.module.urlresolver/lib/urlresolver/plugins/promptfile.py | Python | gpl-2.0 | 3,129 | 0.004155 | '''
urlresolver XBMC Addon
Copyright (C) 2013 Bstrdsmkr
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distri... | r = re.findall(r'type="hidden"\s*name="(.+?)"\s*value="(.*?)"', html)
for name, value in r:
| data[name] = value
html = self.net.http_POST(web_url, data).content
html = re.compile(r'clip\s*:\s*\{.*?url\s*:\s*[\"\'](.+?)[\"\']', re.DOTALL).search(html)
if not html:
raise Exception ('File Not Found or removed')
stream_url = html.group(1)
... |
shakamunyi/neutron-vrrp | neutron/tests/unit/linuxbridge/test_agent_scheduler.py | Python | apache-2.0 | 1,192 | 0.002517 | # Copyright (c) 2013 OpenStack Foundation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | s LbAgentSchedulerTestCase(
test_agent_scheduler.OvsAgentSchedulerTestCase):
plugin_str = test_linuxbridge_plugin.PLUGIN_NAME
l3_plugin = None
class LbL3AgentNotifierTestCase(
test_agent_scheduler.OvsL3AgentNotifierTestCase):
plugin_ | str = test_linuxbridge_plugin.PLUGIN_NAME
l3_plugin = None
class LbDhcpAgentNotifierTestCase(
test_agent_scheduler.OvsDhcpAgentNotifierTestCase):
plugin_str = test_linuxbridge_plugin.PLUGIN_NAME
|
bmya/pos-addons | pos_session_custom2/__openerp__.py | Python | lgpl-3.0 | 583 | 0.012007 | {
'name' : 'Custom pos session report (2)',
| 'version' : '1.0.0',
'author' : 'IT-Projects LLC, Ivan Yelizariev',
'license': 'GPL-3',
'category' : 'Custom',
'website' : 'https://yelizariev.github.io',
'description': """
Tested on Odoo 8.0 258a4cac82ef3b7e6a086f691f3bf8140d37b51c
""",
'data':[
'views/ses | sion_view.xml',
'views/pos_session_custom_report1.xml',
'views/report1.xml',
'views/layouts.xml',
],
'depends': ['base','point_of_sale'],
'init_xml': [],
'update_xml': [],
'installable': True,
}
|
uber/tchannel-python | tchannel/rw.py | Python | mit | 19,427 | 0 | # Copyright (c) 2016 Uber Technologies, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publ... | arg
"""
return ArgsReaderWriter(length_rw)
def len_prefixed_string(length_rw, is_binary=False):
"""Build a ReadWriter for strings prefixed with their length.
.. code-block:: python
len_prefixed_string(number(2 | )) # == str~2
:param length_rw:
ReadWriter for the length of the string
:param is_binary:
Whether the string is a binary blob. If this is False (the default),
the string will be encoded/decoded to UTF-8 before writing/reading.
"""
return LengthPrefixedBlobReadWriter(length_rw, ... |
redisca/django-redisca | redisca/frontend/urls.py | Python | mit | 246 | 0 | from django.conf.urls import url
from redisca.frontend import views
app_name = 'frontend'
urlpatterns = [
url(r'^$', | views.template_list, name='template_list'),
| url(r'^([a-zA-Z0-9_\./\-]+)$', views.static_template, name='template'),
]
|
ramansbach/cluster_analysis | clustering/scripts/gsdSubsample.py | Python | mit | 959 | 0.023983 | #open a gsd file and write out a subsampled version, keeping only every N | timesteps
#useful if you want to be analyzing a shorter trajectory
import gsd.hoomd
import argparse
import time
start = time.time()
parser = argparse.ArgumentParser(description='Subsamble GSD trajectory')
parser.add_argument('fname',metavar='input',type=str,help='trajectory file to be subsampled')
parser.add_argumen | t('ofname',metavar='output',type=str,help='where to write subsampled trajectory file')
parser.add_argument('N',metavar='N',type=int,help='keep frame each N timesteps')
args = parser.parse_args()
traj = gsd.hoomd.open(args.fname)
frame0 = traj[0]
newtraj = gsd.hoomd.open(args.ofname,'wb')
newtraj.append(frame0)
for i ... |
tobias47n9e/social-core | social_core/tests/backends/test_utils.py | Python | bsd-3-clause | 1,767 | 0 | import unittest2 as unittest
from ..models import TestStorage
from ..strategy import TestStrategy
from ...backends.utils import load | _backends, get_backend
from ...backends.github import GithubOAuth2
from ...exceptions import MissingBackend
class BaseBackendUtilsTest(unittest.TestCase):
def setUp(self):
self.strategy = TestStrategy(storage=TestStorage)
def tearDown(self):
self.strategy = None
class LoadBackendsTest(BaseB... | ds.facebook.FacebookOAuth2',
'social_core.backends.flickr.FlickrOAuth'
), force_load=True)
keys = list(loaded_backends.keys())
self.assertEqual(keys, ['github', 'facebook', 'flickr'])
backends = ()
loaded_backends = load_backends(backends, force_load=True)
se... |
dstansby/heliopy | heliopy/data/helios.py | Python | gpl-3.0 | 38,861 | 0 | """
Methods for importing Helios data.
"""
from datetime import date, time, datetime, timedelta
import os
import pathlib
import urllib.error
from urllib.error import URLError
from collections import OrderedDict
import warnings
import astropy.constants as constants
import astropy.units as u
import numpy as np
import pa... | = util.timefilter(distlist[key], starttime_orig, endtime)
return distlist
def integrated_dists_single(probe, year, doy, hour, minute, second):
"""
Returns the integrated distributions from experiments i1a and i1b in Helios
distribution function files.
The distributions are integrated over all an... | int, str
Helios probe to import data from. Must be 1 or 2.
year : int
Year
doy : int
Day of year
hour : int
Hour
minute : int
Minute.
second : int
Second
Returns
-------
i1a : pandas.DataFrame
i1a integrated distribution function.
... |
CanalTP/kirin | tests/mock_navitia/vj_bad_order.py | Python | agpl-3.0 | 13,166 | 0.000228 | # coding=utf-8
# Copyright (c) 2001, Canal TP and/or its affiliates. All rights reserved.
#
# This file is part of Navitia,
# the software to build cool stuff with public transport.
#
# Hope you'll enjoy and contribute to this project,
# powered by Canal TP (www.canaltp.fr).
# Help us simplify mobility and op... | r 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 should have received a copy of the GNU Affero Gener... | itter @navitia
# [matrix] channel #navitia:matrix.org (https://app.element.io/#/room/#navitia:matrix.org)
# https://groups.google.com/d/forum/navitia
# www.navitia.io
from tests.mock_navitia import navitia_response
response = navitia_response.NavitiaResponse()
response.queries = [
"vehicle_journeys/?filter=vehic... |
pierrelb/RMG-Py | rmgpy/quantityTest.py | Python | mit | 38,311 | 0.007021 | #!/usr/bin/env python
# encoding: utf-8
################################################################################
#
# RMG - Reaction Mechanism Generator
#
# Copyright (c) 2002-2009 Prof. William H. Green (whgreen@mit.edu) and the
# RMG Team (rmg_dev@mit.edu)
#
# Permission is hereby granted, free of cha... | self.assertEqual(q.units, "mol/m^3")
def test_moleculesperm3(self):
"""
Test the creation of an concentration quantity with units of molecules/m^3.
"""
q = quantity.Concentration(1.0,"molecules/m^3")
| self.assertAlmostEqual(q.value, 1.0, 6)
self.assertAlmostEqual(q.value_si*constants.Na, 1.0, delta=1e-6)
self.assertEqual(q.units, "molecules/m^3")
################################################################################
class TestEnergy(unittest.TestCase):
"""
Contains unit tests ... |
backmari/moose | python/TestHarness/testers/Tester.py | Python | lgpl-2.1 | 18,823 | 0.004835 | import re, os
import util
from InputParameters import InputParameters
from MooseObject import MooseObject
class Tester(MooseObject):
@staticmethod
def validParams():
params = MooseObject.validParams()
# Common Options
params.addRequiredParam('type', "The type of test of Tester to crea... | "A test that runs only if VTK is detected ('ALL', 'TRUE', 'FALSE')")
params.addParam('tecplot', ['ALL'], "A test that runs only if Tecplot is detected ('ALL', 'TRUE', 'FALSE')")
params.addParam('dof_id_bytes', ['ALL'], "A test that runs only if libmesh is configured --with-dof-id-bytes = a specif... | d with --with-debugging={0,1}, otherwise test always runs.")
params.addParam('curl', ['ALL'], "A test that runs only if CURL is detected ('ALL', 'TRUE', 'FALSE')")
params.addParam('tbb', ['ALL'], "A test that runs only if TBB is available ('ALL', 'TRUE', 'FALSE')")
params.addP... |
Winand/pandas | pandas/core/window.py | Python | bsd-3-clause | 68,740 | 0.000029 | """
provide a generic structure to support window functions,
similar to how we have a Groupby object
"""
from __future__ import division
import warnings
import numpy as np
from collections import defaultdict
from datetime import timedelta
from pandas.core.dtypes.generic import (
ABCSeries,
ABCDataFrame,
... | is_scalar)
from pandas.core | .base import (PandasObject, SelectionMixin,
GroupByMixin)
import pandas.core.common as com
import pandas._libs.window as _window
from pandas import compat
from pandas.compat.numpy import function as nv
from pandas.util._decorators import (Substitution, Appender,
... |
michalczaplinski/sudoku | sudoku_generator.py | Python | bsd-3-clause | 5,317 | 0.00583 | #!/usr/bin/env python
#### Sudoku generator ####
import random
import time
from collections import defaultdict
class Square(object):
'''Main class holding the attributes for each square of the sudoku'''
def __init__(self, x, y):
self.value = None
self.x = x
self.y = y
... | --+---+---#---+---+---#---+---+---#"
line_thick = "#####################################"
print line
for s in board:
if (s.getX() ) % 3 == 0:
print '# ',
elif random.random() > 0.3:
print '| ',
else:
print '| %d' %(s.getValue()),
if (s... | 0:
if (s.getY() + 1) % 3 == 0:
print '#\n', line_thick
else:
print '#\n', line
if __name__ == "__main__":
sudoku = CreateSudoku()
printSudoku(sudoku)
|
Jamlum/pytomo | test_http_server.py | Python | gpl-2.0 | 1,820 | 0.006044 | #!/usr/bin/env python
from __future__ import absolute_import
import urllib2
from pytomo import lib_youtube_download
from pytomo import start_pytomo
start_pytomo.configure_log_file('http_test')
ip_address_uri = ("http://173.194.5.107/videoplayback?sparams=id%2Cexpire%2Cip%2Cipbits%2Citag%2Calgorithm%2Cburst%2Cfactor... | 'content-type': 'video/x-flv',
'date': 'Fri, 29 Apr 2011 14:12:04 GMT',
'expires': 'Fri, 29 Apr 2011 19:55:00 GMT',
'last-modified': 'Fri, 18 Jun 2010 12:05:11 GMT',
'server': 'gvs 1.0',
'via': '1.1 goodway (NetCache | NetApp/6.1.1), 1.1 s-proxy (NetCache NetApp/ 5.6.2R2)',
'x-content-type-options': 'nosniff'}
def mock_response(req):
if req.get_full_url() == ip_address_uri:
mock_file = open('test_pytomo/OdF-oiaICZI.flv')
resp = urllib2.addinfourl(mock_file,info ,
req.ge... |
oswalpalash/OctaveCodeShare | scipy_central/filestorage/admin.py | Python | bsd-3-clause | 89 | 0 | from django. | contrib import admin
from models import FileSet
admin.site.registe | r(FileSet)
|
iancmcc/simplexmlapi | simplexmlapi/api.py | Python | mit | 3,090 | 0.002913 | from node import DotXMLDoc, AttributeParsingError
class SimpleXmlApi(object):
"""
The main API class, comprising a map of attributes to dotted path names.
Accessing an attribute that has been mapped to a dotted name will return
the text value of that node/attribute. If an attribute is passed that
... | nt and set it as this API's target.
@param source: A string containing an XML document.
@type source: str
@return: void
"""
self._doc = DotXMLDoc(source)
def load_map(self, map):
"""
Update the attribute registry with one or more mappings. Will not
r... | @type map: dict
@return: void
"""
self._map.update(map)
def del_mapping(self, name):
"""
Remove an attribute mapping from the registry.
@param name: The name of the attribute to remove from the registry.
@type name: str
@return: void
"""
... |
madzebra/BitSend | qa/rpc-tests/txn_doublespend.py | Python | mit | 6,649 | 0.004362 | #!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitsend Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test proper accounting with a double-spend conflict
#
from test_framework.test_framework import Bits... | arting balance, plus 50BSD for another
# matured block, minus 40, minus 20, and minus transaction fees:
expected = starting_balance + fund_foo_tx["fee"] + fund_bar_tx["fee"]
if self.options.mine_block: expected += 50
expected += tx1["amount"] + tx1["fee"]
expected += tx2["amount"... | accounts should be debited:
assert_equal(self.nodes[0].getbalance("foo", 0), 1219+tx1["amount"]+tx1["fee"])
assert_equal(self.nodes[0].getbalance("bar", 0), 29+tx2["amount"]+tx2["fee"])
if self.options.mine_block:
assert_equal(tx1["confirmations"], 1)
assert_equal(tx2["... |
atizo/braindump | brainstorming/migrations/0005_auto__add_field_idea_color.py | Python | mit | 4,031 | 0.007938 | # -*- 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
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Idea.color'
db.add_column(u'brainstorming_idea', 'color',... | 'creator_ip': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'details': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'id': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'primary_key': 'True'}),
'modified... | rue'}),
'question': ('django.db.models.fields.CharField', [], {'max_length': '200'})
},
u'brainstorming.brainstormingwatcher': {
'Meta': {'ordering': "['-created']", 'unique_together': "(('brainstorming', 'email'),)", 'object_name': 'BrainstormingWatcher'},
'brainstor... |
jyt109/gensim | gensim/test/test_models.py | Python | gpl-3.0 | 23,020 | 0.006125 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010 Radim Rehurek <radimrehurek@seznam.cz>
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
"""
Automated tests for checking transformation algorithms (the models package).
"""
import logging
import unittest
import os
import o... | Case):
def setUp(self):
self.corpus = mmcorpus.MmCorpus(datapath('testcorpus.mm'))
def testTransform(self):
# create the transformation model
numpy.random.seed(13) # HACK; set fixed seed so that we always get the same random matrix (and can compare against expected results)
mode... | cs=2)
# transform one document
doc = list(self.corpus)[0]
transformed = model[doc]
vec = matutils.sparse2full(transformed, 2) # convert to dense vector, for easier |
dunmatt/robobonobo | scripts/get_ready.py | Python | mit | 979 | 0 | #!/usr/bin/env python
"""Robobonobo setup script.
Usage:
./get_ready.py [options]
Options:
-h, --help Show this help screen
--version Show the version.
"""
from docopt import docopt
fro | m glob import glob
import os
GPIOS = [30, 31, 112, 113, 65, 27]
GPIO_BASE = "/sys/class/gpio"
SLOTS_GLOB = "/sys/devices/bone_capemgr.?/slots"
def write_gpio(filename, msg, pindir=""):
| with open(os.path.join(GPIO_BASE, pindir, filename), mode="w+") as ex:
ex.write(msg)
def setup_gpio(pin):
write_gpio("export", pin)
pindir = "gpio" + pin
write_gpio("direction", "out", pindir)
write_gpio("value", "0", pindir)
def setup_dto():
for match in glob(SLOTS_GLOB):
with ... |
hgl888/chromium-crosswalk | tools/gypv8sh.py | Python | bsd-3-clause | 2,927 | 0.012641 | #!/usr/bin/env python
# Copyright (c) 2012 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.
"""This script is used by chrome_tests. | gypi's js2webui action to maintain the
argument lists and to generate inlinable tests.
"""
import json
import optparse
import os
import subprocess
import sys
import shutil
def HasSameContent(fil | ename, content):
'''Returns true if the given file is readable and has the given content.'''
try:
with open(filename) as file:
return file.read() == content
except:
# Ignore all errors and fall back on a safe bet.
return False
def main ():
parser = optparse.OptionParser()
parser.set_usage(... |
dmwm/Docker | jenkins_python/scripts/PullRequestTestBegin.py | Python | apache-2.0 | 887 | 0.001127 | #! /usr/bin/env python
from __future__ import print_function
import os
import time
from github import Github
gh = Github(os.environ['DMWMBOT_TOKEN'])
codeRepo = os.environ.get('CODE_REPO', 'WMCore')
teamName = os.environ.get('WMCORE_REPO', 'dmwm')
repoName = '%s/%s' % (teamName, codeRepo)
issueID = None
if 'ghprb... | '
print("Looking for %s issue %s" % (repoName, issueID))
repo = gh.get_repo(repoName)
issue = repo.get_issue(int(issueID))
reportURL = os.environ['BUILD_URL']
lastCommit = repo.get_pull(int(issueID)).get_commits().get_page(0 | )[-1]
lastCommit.create_status(state='pending', target_url=reportURL,
description='Tests started at ' + time.strftime("%d %b %Y %H:%M GMT"))
|
jiaphuan/models | research/brain_coder/single_task/data.py | Python | apache-2.0 | 3,685 | 0.004071 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
"""Manage data for pretraining and RL tasks."""
import ast
from collections import namedtuple
from absl import logging
from single_task import code_tasks # brain coder
RLBatch = namedtuple('RLBatch', ['re... | logging.info('Task for this run: "%s"', self.task_name)
logging.info('config_for_iclr=True; do_code_simplification=%s',
do_code_simplification)
self.rl_task = code_tasks.make_task(
task_name=self.task_name,
override_kwargs=ast.literal_eval(env_config.task_kwargs),
max... | ation,
correct_bonus=env_config.task_manager_config.correct_bonus,
code_length_bonus=env_config.task_manager_config.code_length_bonus)
def sample_rl_batch(self):
"""Create reward functions from the current task.
Returns:
RLBatch namedtuple instance, which holds functions and informatio... |
softwaresaved/fat | lowfat/migrations/0021_blog_status.py | Python | bsd-3-clause | 627 | 0.001595 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-06-02 16:10
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migration | s.Migration):
dependencies = [
('lowfat', '0020_auto_20160602_1607'),
]
operations = [
migrations.AddField(
model_name='blog',
name='status',
field=models.CharField(choices=[('U', 'Unprocessed'), ('R', 'On Google Drive (for review)'), ('L', 'On pipeline ... | eclined'), ('O', 'Out of date')], default='U', max_length=1),
),
]
|
lamaisondub/lamaisondub-custom | website_forum_private/models/__init__.py | Python | agpl-3.0 | 21 | 0 | i | mport w | ebsite_forum
|
bulik/ldsc | setup.py | Python | gpl-3.0 | 577 | 0.005199 | from setuptools import setup
setup(name='ldsc',
version='1.0',
description='LD Score Regression (LDSC)',
url='http://github.c | om/bulik/ldsc',
author='Brendan Bulik-Sullivan and Hilary Finucane',
author_email='',
license='GPLv3',
packages | =['ldscore'],
scripts=['ldsc.py', 'munge_sumstats.py'],
install_requires = [
'bitarray>=0.8,<0.9',
'nose>=1.3,<1.4',
'pybedtools>=0.7,<0.8',
'scipy>=0.18,<0.19',
'numpy>=1.16,<1.17',
'pandas>=0.20,<0.21'
]
)
|
cloudera/ibis | ibis/backends/pyspark/tests/test_window_context_adjustment.py | Python | apache-2.0 | 13,958 | 0 | import pandas as pd
import pandas.testing as tm
import pyspark.sql.functions as F
import pytest
from pyspark.sql import Window
import ibis
@pytest.mark.parametrize(
('ibis_windows', 'spark_range'),
[
([(ibis.interval(hours=1), 0)], (-3600, 0)), # 1h back looking window
([(ibis.interval(hours... | table.mutate(
count=table['value'].count().over(ibis_windows[0])
).execute(timecontext=context)
spark_table = table.compile()
spark_window = (
Window.partitionBy('key')
.orderBy(F.col('time').cast('long'))
.rangeBetween(*spar | k_range)
)
expected = spark_table.withColumn(
'count',
F.count(spark_table['value']).over(spark_window),
).toPandas()
expected = expected[
expected.time.between(*(t.tz_convert(None) for t in context))
].reset_index(drop=True)
tm.assert_frame_equal(result_pd, expected)
@... |
steventimberman/masterDebater | venv/lib/python2.7/site-packages/disqus/wxr_feed.py | Python | mit | 9,430 | 0.007529 | import datetime
from django import template
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import Site
from django.contrib.syndication.views import Feed, add_domain
from django.utils import feedgenerator, tzinfo
from django.utils.encoding im... | item['comments'] is None:
return
handler.addQuickElement('title', item['title'])
handler.addQuickElement('link', item['link'])
handler.addQuickElement('content:encoded', item['description'])
handler.addQuickElement('dsq:thread_identifier', item['unique_id'])
handler.a... | (item['pubdate']).decode('utf-8'))
handler.addQuickElement('wp:comment_status', item['comment_status'])
self.write_comments(handler, item['comments'])
def add_comment_elements(self, handler, comment):
if USE_SINGLE_SIGNON:
handler.startElement('dsq:remote', {})
... |
schakrava/rockstor-core | src/rockstor/storageadmin/south_migrations/0001_initial.py | Python | gpl-3.0 | 36,999 | 0.00746 | # -*- 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
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Pool'
db.create_table(u'storageadmin_pool', (
... | f('django.db.models.fields.AutoField')(primary_key=True)),
('host_str', self.gf('django.db.models.fields.CharField')(max_length=4096)),
('editable', self.gf('django.db.models.fields.CharField')(default='ro', max_length=2)),
('syncable', self.gf('django.db.models.fields.CharField')(de... | lt='insecure', max_length=8)),
('nohide', self.gf('django.db.models.fields.BooleanField')(default=False)),
('enabled', self.gf('django.db.models.fields.BooleanField')(default=True)),
))
db.send_create_signal('storageadmin', ['NFSExportGroup'])
# Adding model 'NFSExport'
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.