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 |
|---|---|---|---|---|---|---|---|---|
srmo/osmc | package/mediacenter-addon-osmc/src/script.module.osmccommon/resources/lib/osmc_comms.py | Python | gpl-2.0 | 3,448 | 0.032193 | # Standard modules
import os
import socket
import subprocess
import threading
# XBMC modules
import xbmc
import xbmcaddon
import xbmcgui
class OSMC_Communicator(threading.Thread):
''' Class to setup and manage the socket to allow communications between OSMC settings modules and external scripts.
For example, this... | ue
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect(self.address)
sock.send('exit')
sock.close()
self.sock.close()
self.log('Exit message sent to socket.')
except Exception, e:
self.log('Comms error trying to stop: | {}'.format(e))
def run(self):
self.log('Comms started')
while not xbmc.abortRequested and not self.stopped:
try:
# wait here for a connection
conn, addr = self.sock.accept()
except socket.timeout:
continue
except:
self.log('An error occured while waiting for a connection.')
brea... |
bartscheers/tkp | tkp/telescope/lofar/__init__.py | Python | bsd-2-clause | 211 | 0 | """
Functions for calculating LOFAR hardware specific properties.
"""
import tkp.telescope.lofar.antennaarrays
import tkp.telescope.lofar.beam
import tkp.telescope.lofar.nois | e
import tkp.tele | scope.lofar.quality
|
xunzhang/roraima | tools/mf.py | Python | apache-2.0 | 3,744 | 0.044605 | #! /usr/bin/python
# Basic Matrix factorization
import numpy as np
class bmf():
def __init__(self, k = 100, rounds = 50, alpha = 0.005, beta = 0.02, train_fn = '', validate_fn = '', pred_fn = '', output = ''):
self.k = k
self.rounds = rounds
self.alpha = alpha
self.beta = beta
self.train_fn = train_f... | (self.output, 'w')
for line in f1:
uid, iid = line.strip('\n').split(',')
u_indx = self.usr_dct[ui | d]
i_indx = self.item_dct[iid]
pred_rating = np.dot(self.p[u_indx, :], self.q[i_indx, :])
f2.write('%s,%s,%s\n' % (uid, iid, pred_rating))
f1.close()
f2.close()
def r(self, i, j):
return np.dot(self.p[i, :], self.q[j, :])
def kernel(self):
import time
# init parameters
self.... |
nolram/news_crawler | classificador/news_item.py | Python | mit | 3,574 | 0.001399 | import re
import string
import nltk
from bs4 import BeautifulSoup
__author__ = 'nolram'
class NewsItem:
def __init__(self, news, stop_words):
self.all_words = []
self.stop_words = stop_words
self.regex = re.compile('[%s]' % re.escape(string.punctuation))
if "titulo" in news and... | t2 in toks2:
t2s = t2.strip()
if len(t2s) > 1:
words.append(t2s.lower())
return words
def word_count(self):
return len(self.all_words)
def word_freq_dist(self):
freqs = nltk.FreqDist() # class nltk.probability.FreqDist
for w ... | freqs.inc(w, 1)
return freqs
def add_words(self, s):
words = self.normalized_words(s)
for w in words:
if w not in self.stop_words:
self.all_words.append(w)
def features(self, top_words):
word_set = set(self.all_words)
features = {... |
jpetto/olympia | src/olympia/amo/management/commands/fix_charfields.py | Python | bsd-3-clause | 1,744 | 0 | import itertools
from django.core.management.base import BaseCommand
from django.db import | models, connection
qn = connection.ops.quote_name
def fix(table_name, field):
d = {'tabl | e': table_name, 'field': qn(field.column), 'sql': sql(field)}
update = "UPDATE {table} SET {field}='' WHERE {field} IS NULL".format(**d)
alter = "MODIFY {sql}".format(**d)
return update, alter
def sql(field):
o = ['%s' % qn(field.column), field.db_type()]
if not field.null:
o.append('NOT N... |
sdgdsffdsfff/jumpserver | apps/users/serializers/group.py | Python | gpl-2.0 | 2,119 | 0.000944 | # -*- coding: utf-8 -*-
#
from django.utils.translation import u | gettext_lazy as _
from rest_framework import serializers
from common.fields import StringManyToManyField
from common.serializers import AdaptedBulkListSerializer
from orgs.mixins.serializers impor | t BulkOrgResourceModelSerializer
from ..models import User, UserGroup
from .. import utils
__all__ = [
'UserGroupSerializer', 'UserGroupListSerializer',
'UserGroupUpdateMemberSerializer',
]
class UserGroupSerializer(BulkOrgResourceModelSerializer):
users = serializers.PrimaryKeyRelatedField(
requ... |
slipguru/l1l2py | cuda/32bit/config.py | Python | gpl-3.0 | 1,967 | 0.006609 | # Configuration file example for L1L2Signature
# version: '0.2.2'
import l1l2py
#~~ Data Input/Output ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# * Data assumed csv with samples and features labels
# * All the path are w.r.t. config file path
data_matrix = 'data/gedm.csv'
labels = 'data/labels.csv'
de... | ange(1e-3, 1.0, 3) # * CORRELATION_FACTOR
lambda_range = l1l2py.tools.geometric_range(1e0, 1e4, 10)
#~~ Signature Parameters ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
frequency_threshold = 0.5
#~~ PPlus options ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
debug = True # | If True, the experiment runs only on the local pc cores
|
xbmc/xbmc-antiquated | xbmc/lib/libPython/Python/Demo/parser/test_parser.py | Python | gpl-2.0 | 1,193 | 0.004191 | #! /usr/bin/env python
# (Force the script to use the latest build.)
#
# test_parser.py
import parser, traceback
_numFailed = 0
def testChunk(t, file | Name):
global _numFailed
print '----', fileName,
try:
ast = parser.suite(t)
tup = parser.ast2tuple(ast)
# this discards the first AST; a huge memory savings when running
| # against a large source file like Tkinter.py.
ast = None
new = parser.tuple2ast(tup)
except parser.ParserError, err:
print
print 'parser module raised exception on input file', fileName + ':'
traceback.print_exc()
_numFailed = _numFailed + 1
else:
if tup... |
MediffRobotics/DeepRobotics | DeepLearnMaterials/tutorials/tensorflowTUT/tf12_plot_result/full_code.py | Python | gpl-3.0 | 2,272 | 0.004401 | # View more python learning tutorial on my Youtube and Youku channel!!!
# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
# Youku video tutorial: http://i.youku.com/pythontutorial
"""
Please note, this code is only for python 3+. If you are using python 2+, please modify the code acco... |
import numpy as np
import matplotlib.pyplot as plt
def add_layer(inputs, in_size, out_size, activation_function=None):
Weights = tf.Variable(tf.random_normal([in_size, out_size]))
biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)
Wx_plus_b = tf.matmul(inputs, Weights) + biases
if activation_function... | e:
outputs = activation_function(Wx_plus_b)
return outputs
# Make up some real data
x_data = np.linspace(-1, 1, 300)[:, np.newaxis]
noise = np.random.normal(0, 0.05, x_data.shape)
y_data = np.square(x_data) - 0.5 + noise
##plt.scatter(x_data, y_data)
##plt.show()
# define placeholder for inputs to networ... |
hfp/tensorflow-xsmm | tensorflow/python/keras/losses_test.py | Python | apache-2.0 | 48,998 | 0.002694 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | e_obj.reduction, losses_impl.ReductionV2.SUM)
def test_all_correct_unwei | ghted(self):
mse_obj = keras.losses.MeanSquaredError()
y_true = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3))
loss = mse_obj(y_true, y_true)
self.assertAlmostEqual(self.evaluate(loss), 0.0, 3)
def test_unweighted(self):
mse_obj = keras.losses.MeanSquaredError()
y_true = constant_op.... |
ashmastaflash/gwdetect | dependencies/netaddr-0.7.10/release.py | Python | mit | 5,263 | 0.00076 | #-----------------------------------------------------------------------------
# Copyright (c) 2008-2012, David P. D. Moss. All rights reserved.
#
# Released under the BSD license. See the LICENSE file for details.
#-----------------------------------------------------------------------------
import netaddr
name ... | anagement',
'Topic :: Security',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Software Development :: Quality Assurance',
'Topic | :: Software Development :: Testing',
'Topic :: Software Development :: Testing :: Traffic Generation',
'Topic :: System :: Benchmark',
'Topic :: System :: Clustering',
'Topic :: System :: Distributed Computing',
'Topic :: System :: Installation/Setup',
'Topic :: System :: Logging',
'Topic :... |
andialbrecht/crunchyfrog | utils/command/build_manpage.py | Python | gpl-3.0 | 4,464 | 0.000224 | # -*- coding: utf-8 -*-
"""build_manpage command -- Generate man page from setup()"""
import datetime
from distutils.command.build import build
from distutils.core import Command
from distutils.errors import DistutilsOptionError
import optparse
class build_manpage(Command):
description = 'Generate man page fro... | desc = self.distribution.get_ | long_description()
if long_desc:
ret.append('.SH DESCRIPTION\n%s\n' % self._markup(long_desc))
return ''.join(ret)
def _write_options(self):
ret = ['.SH OPTIONS\n']
ret.append(self._parser.format_option_help())
return ''.join(ret)
def _write_footer(self):
... |
andreastt/certtest | semiauto/tests/__init__.py | Python | mpl-2.0 | 411 | 0.002433 | # 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 thi | s file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
from test_sms import TestSms
def all(handler):
env = environment.get(InProcessTestEnvironment)
suite = unittest.TestSu | ite()
suite.addTest(TestSms("test_navigate", handler=handler))
return suite
|
jonhadfield/ansible-lookups | aws_rds_endpoint_port_from_instance_name.py | Python | mit | 1,218 | 0.004926 | # (c) 2015, Jon Hadfield <[email protected]>
"""
Description: This lookup takes an AWS region and an RDS instance
name and returns the endpoint port.
Example Usage:
{{ lookup('aws_rds_endpoint_port_from_instance_name', ('eu-west-1', 'mydb')) }}
"""
from __future__ import (absolute_import, division, print_function)
_... | ion.Session(region_name=region)
try:
rds_client=session.client('rds')
except botocore.exceptions.NoRegionError:
raise AnsibleError("AWS region not specified.")
result=rds_client.describe_db_instances(DBInstanceIdentifier=instance_name)
if result and result.get(... | dpoint').get('Port').encode('utf-8')]
return None
|
lavalamp-/ws-backend-community | wselasticsearch/models/services/ssl.py | Python | gpl-3.0 | 34,499 | 0.002058 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from OpenSSL import crypto
from .base import BaseNetworkServiceScanModel
from ..types import *
from ..mixin import DomainNameMixin, S3Mixin
from lib import ConversionHelper
class SslSupportModel(BaseNetworkServiceScanModel):
"""
This is an Elast... | ]
return to_populate
# Public Methods
# Protected Methods
# Private Methods
# Properties
# Representation and Comparison
class SslVulnerabilityModel(BaseNetworkServiceScanModel) | :
"""
This is an Elasticsearch model for representing the results of a single check for a single
SSL vulnerability.
"""
# Class Members
vuln_test_name = KeywordElasticsearchType(
help_text="A string depicting the name of the vulnerability test that was conducted.",
)
test_error... |
audreyr/opencomparison | package/signals.py | Python | mit | 82 | 0.012195 | import django.dispatch
signal_f | etch_latest_metadata = django.dispatch.Signal()
| |
bswartz/manila | manila/tests/scheduler/test_host_manager.py | Python | apache-2.0 | 43,579 | 0 | # Copyright (c) 2011 OpenStack, LLC
# Copyright (c) 2015 Rushil Chugh
# Copyright (c) 2015 Clinton Knight
# 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
#
# ... |
def test_choose_host_filters_not_found(self):
self.flags(scheduler_default_filters='FakeFilterClass3')
self.host_manager.filter_classes = [ | FakeFilterClass1,
FakeFilterClass2]
self.assertRaises(exception.SchedulerHostFilterNotFound,
self.host_manager._choose_host_filters, None)
def test_choose_host_filters(self):
self.flags(scheduler_default_filters=['FakeFilterClass... |
DomainGroupOSS/elasticsearch-snapshots | es_backup.py | Python | mit | 1,826 | 0.005476 | #!/usr/bin/env python
import time, logging, argparse, json, sys
from es_manager import ElasticsearchSnapshotManager, get_parser
from elasticsearch import exceptions
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('elasticsearch')
def take_snapshot(options):
esm = ElasticsearchSnapshotManager(o... | wait_for_completion=options.wait, request_timeout=7200)
# Housekeeping - delete old snapshots
snapshots = sh.get(repository=options.repository, snapshot="_all", request_timeout=120)['snapshots']
num_snaps = len(snapshots)
if num_snaps > options.keep:
up_to = num_snaps - opt... | gger.info('TOTAL: %d - Will delete 1 -> %d' % (num_snaps, up_to + 1))
for snap in snapshots[0:up_to]:
sh.delete(repository=options.repository, snapshot=snap['snapshot'], request_timeout=3600)
logger.info('Deleted snapshot %s' % snap['snapshot'])
except exceptions.Transpor... |
Vvucinic/Wander | venv_2_7/lib/python2.7/site-packages/Django-1.9-py2.7.egg/django/contrib/gis/measure.py | Python | artistic-2.0 | 12,272 | 0.002445 | # Copyright (c) 2007, Robert Coup <[email protected]>
# 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,
#... |
def __div__(self, other): # Python 2 compatibility
return type(self).__truediv__(self, other)
def __itruediv__(self, other):
if isinstance(other, NUMERIC_TYPES):
self.standard /= float(other)
| return self
else:
raise TypeError('%(class)s must be divided with number' % {"class": pretty_name(self)})
def __idiv__(self, other): # Python 2 compatibility
return type(self).__itruediv__(self, other)
def __bool__(self):
return bool(self.standard)
def __nonzero__(... |
larroy/mxnet | tests/python/gpu/test_gluon_transforms.py | Python | apache-2.0 | 4,081 | 0.003921 | # 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... | either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from __future__ import print_function
import os
import sys
import mxnet as mx
imp | ort mxnet.ndarray as nd
import numpy as np
from mxnet import gluon
from mxnet.base import MXNetError
from mxnet.gluon.data.vision import transforms
from mxnet.test_utils import assert_almost_equal, set_default_context
from mxnet.test_utils import almost_equal, same
curr_path = os.path.dirname(os.path.abspath(os.path.ex... |
HumanExposure/factotum | dashboard/tests/functional/test_datagroup_detail.py | Python | gpl-3.0 | 22,500 | 0.001244 | import json
import io
from lxml import html
from django.test import TestCase, tag
from celery_djangotest.unit import TransactionTestCase
from dashboard.tests.factories import (
DataGroupFactory,
DataDocumentFactory,
ExtractedHPDocFactory,
)
from dashboard.tests.loader import load_model_objects, fixtures_... | ot be gone until the task completes
self.assertEqual(
dg.get_products().count(),
| 0,
"Data Group doesn't have zero products after bulk delete",
)
def test_hp_docs_extraction_completed(self):
# Create a data group
dg = DataGroupFactory(group_type__code="HP")
# Create DataDocuments
# Unextracted document
DataDocumentFactory(dat... |
gouthambs/OpenData | src/longbeach_crime_stats.py | Python | mit | 10,310 | 0.022599 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 22 12:07:53 2014
@author: Gouthaman Balaraman
"""
import requests
import pandas as pd
from bs4 import BeautifulSoup
import re
import numpy as np
import os
#####################################################
# A bunch of constants used throught the script. #
########... | Convenient method to loop over all the pdf files. Calls create_html
file in a loop.
'''
for f in os.listdir(pdfdir):
if f.endswith('.pdf'):
create_html(os.path.join(pdfdir,f))
def _finalize | _dataframe(ddf):
'''
Does some clean-up, check sums to validate the data. This is a basic
check. Nothing is guaranteed!
'''
# do a checksum test
if 'TOTAL_PART1' in ddf.columns:
checksum = np.sum(\
np.power(
ddf[mptbltxt[1:14]].astype(int).sum(axis=1) -
... |
emmanuelol/pinguino-ide | qtgui/gide/bloques/widgets/control_slider.py | Python | gpl-2.0 | 2,130 | 0.001878 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/home/yeison/Documentos/python/developing/pinguino/pinguino-ide/qtgui/gide/bloques/widgets/control_slider.ui'
#
# Created: Wed Mar 4 01:39:58 2015
# by: pyside-uic 0.2.15 running on PySide 1.2.2
#
# WARNING! All changes made in this fi... | self.lineEdit_2.setMaximumSize(QtCore.QSize(46, 16777215))
font = QtGui.QFont()
font.setFamily("Ubuntu Mono")
font.setPointSize(15)
font.setWeight(75)
font.setBold(True)
self.lineEdit_2.setFont(font)
self.lineEdit_2.setStyleSheet("color: rgb(255, 255, 255);\n"... | self.lineEdit_2.setText("0000")
self.lineEdit_2.setFrame(False)
self.lineEdit_2.setReadOnly(True)
self.lineEdit_2.setObjectName("lineEdit_2")
self.gridLayout.addWidget(self.lineEdit_2, 0, 1, 1, 1)
self.horizontalSlider = QtGui.QSlider(Frame)
self.horizontalSlider.setCurs... |
thombashi/pytablewriter | test/writer/test_elasticsearch_writer.py | Python | mit | 6,308 | 0.001268 | """
.. codeauthor:: Tsuyoshi Hombashi <[email protected]>
"""
import collections
import datetime
import json
from decimal import Decimal
import elasticsearch
import pytest
import pytablewriter as ptw
from .._common import print_test_result
from ..data import headers, value_matrix
inf = Decimal("Infinity... | lass Test_ElasticsearchWriter_write_table:
@pytest.mark.parametrize(
["table", "header", "value", "expected"],
[[data.table, data.header, data.value, data.expected] for data in empty_test_data_lis | t],
)
def test_smoke_empty(self, table, header, value, expected):
writer = table_writer_class()
writer.stream = elasticsearch.Elasticsearch()
writer.table_name = table
writer.headers = header
writer.value_matrix = value
writer.write_table()
@pytest.mark.para... |
Lapin-Blanc/pythonbeid | beid.py | Python | gpl-3.0 | 5,421 | 0.011621 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from smartcard.CardMonitoring import CardObserver, CardMonitor
from smartcard.System import readers
import smartcard
from types import MethodType
from datetime import datetime
MAP_MOIS = {
"JANV" : "01",
"JAN" : "01",
"FEVR" : "02",
"FEV" : "02",
"M... | ndAD | PU(cmd)
if "%x"%sw1 == "6c":
cmd = [0x00, 0xB0, 0x00, 0x00, sw2]
data, sw1, sw2 = _sendADPU(cmd)
idx = 0
num_info = 0
infos = []
while num_info <= 12:
num_info = data[idx]
idx += 1
len_info = data[idx]
idx += 1
... |
samsu/neutron | openstack/common/policy.py | Python | apache-2.0 | 21,618 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2012 OpenStack Foundation.
# 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.... | tch = match
def __str__(self):
"""Return a string representation of this check."""
return "%s:%s" % (self.kind, self.match)
class NotCheck(BaseCheck):
"""
A policy check that inverts the result of another policy check.
Implements the "not" operator.
"""
def __init__(self, ru... | heck.
:param rule: The rule to negate. Must be a Check.
"""
self.rule = rule
def __str__(self):
"""Return a string representation of this check."""
return "not %s" % self.rule
def __call__(self, target, cred):
"""
Check the policy. Returns the logic... |
lorenzogil/yith-library-server | yithlibraryserver/user/__init__.py | Python | agpl-3.0 | 2,517 | 0.000397 | # Yith Library Server is a password storage server.
# Copyright (C) 2012-2013 Yaco Sistemas
# Copyright (C) 2012-2013 Alejandro Blanco Escudero <[email protected]>
# Copyright (C) 2012-2013 Lorenzo Gil Sanchez <[email protected]>
#
# This file is part of Yith Library Server.
#
# Yith Library Server is... | ig.add_request_method(get_user, 'user', reify=True)
config.add_request_method(get_google_analytics,
'google_analytics', reify=True)
config.add_request_method(get_gravatar, 'gravatar', reify=True)
config.add_route('login', '/login')
config.add_route('register_new_user', '/r... | ion', '/profile')
config.add_route('user_preferences', '/preferences')
config.add_route('user_identity_providers', '/identity-providers')
config.add_route('user_send_email_verification_code',
'/send-email-verification-code')
config.add_route('user_verify_email', '/verify-email')
... |
jasonwee/asus-rt-n14uhp-mrtg | src/lesson_data_structures/collections_deque_maxlen.py | Python | apache-2.0 | 349 | 0 |
import collections
import random
# Set the random seed so we see | the same output each time
# the script is run.
random.seed(1)
d1 = collections.deque(maxlen=3)
d2 = collections.deque(maxlen=3)
for i in range(5):
n = random.randint(0, 100)
print('n =', n)
d1.append(n)
d2.appendleft(n)
print('D1:', d1)
print('D2:', d | 2)
|
vrenaville/project-service | project_issue_baseuser/__openerp__.py | Python | agpl-3.0 | 1,603 | 0 | # -*- co | ding: utf-8 - | *-
##############################################################################
#
# Daniel Reis, 2013
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the L... |
oliverwreath/Wide-Range-of-Webs | Python/Battleship/15. Guess 4 turns.py | Python | agpl-3.0 | 1,187 | 0.005897 | from random import randint
board = []
for x in range(5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
print "Let's play Battleship!"
print_board(board)
def rando | m_row(board):
return randint(0, len(board) - 1)
def random_col(board):
return randint(0, len(board[0]) - 1)
ship_row = random_row(board)
ship_col = random_col(board)
print ship_row
print s | hip_col
# Everything from here on should go in your for loop!
# Be sure to indent four spaces!
for turn in range(4):
print "Turn", turn + 1
guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))
if guess_row == ship_row and guess_col == ship_col:
print "Congratul... |
juanantoniofm12/toonai | Zappa/zappa/async.py | Python | mit | 11,154 | 0.00251 | """
Zappa Async Tasks
Example:
```
from zappa.async import task
@task(service='sns')
def my_async_func(*args, **kwargs):
dosomething()
```
For SNS, you can also pass an `arn` argument to task() which will specify which SNS path to send it to.
Without `service='sns'`, the default service is 'lambda' which will c... | ion with args
"""
message = event
return run_message(message)
def route_sns_task(event, context):
"""
Gets SNS Message, deserialises the message,
imports the function, calls the function with args
"""
record = event['Records'][0]
message = json.loads(
record['Sns']['Mess... |
Runs a function defined by a message object with keys:
'task_path', 'args', and 'kwargs' used by lambda routing
and a 'command' in handler.py
"""
func = import_and_get_task(message['task_path'])
if hasattr(func, 'sync'):
return func.sync(
*message['args'],
**mess... |
romainstuder/evosite3d | convert_fasta2phylip.py | Python | gpl-3.0 | 1,829 | 0.001093 | #!/usr/bin/env python3
"""Convert FASTA to PHYLIP"""
import sys
from Bio import SeqIO
print("Convert FASTA to PHYLIP")
infile = sys.argv[1]
outfile = sys.argv[2]
sequence_list = [] # To keep order of sequence
sequence_dict = {}
for record in SeqIO.parse(open(infile, "rU"), "fasta"):
tab = record.id.split(" "... | equences:\t"+str(number_of_seq))
print("Alignment length:\t"+str(alignment_length))
print("Ratio =\t"+str(alignment_length/3))
if alignment_length%3 != 0:
print("Warning: Hum, your alignment didn't code for nucleotides")
# Length of gene id, can be changed by passing a third argument
name_length = 50
if len(sys.a... | nt in Phylip format
phyfile = open(outfile, "w")
phyfile.write(str(number_of_seq)+"\t"+str(alignment_length)+"\n")
for gene in sequence_list:
if len(gene) > name_length:
gene_name = gene[0:name_length].replace(" ", "")
if gene_name[-1] == "_":
gene_name = gene_name[0:-1]
# elif g... |
VishvajitP/django-tastypie | tastypie/resources.py | Python | bsd-3-clause | 84,667 | 0.001937 | from __future__ import with_statement
import logging
import warnings
import django
from django.conf import settings
from django.conf.urls.defaults import patterns, url
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned, ValidationError
from django.core.urlresolvers import NoReverseMatch, rev... | it]
resource | _name = ''.join(name_bits).lower()
new_class._meta.resource_name = resource_name
if getattr(new_class._meta, 'include_resource_uri', True):
if not 'resource_uri' in new_class.base_fields:
new_class.base_fields['resource_uri'] = fields.CharField(readonly=True)
eli... |
ckc6cz/osf.io | scripts/tests/test_approve_registrations.py | Python | apache-2.0 | 3,410 | 0.002053 | # -*- coding: utf-8 -*-
from datetime import datetime, timedelta
from nose.tools import * # noqa
from tests.base import OsfTestCase
from tests.factories import RegistrationFactory
from tests.factories import UserFactory
from scripts.approve_registrations import main
class TestApproveRegistrations(OsfTestCase):
... | approved)
main(dry_run=False)
assert_true(self.registration.is_registration_approved)
def test_registration_adds_to_parent_projects_log(self):
initial_project_logs = len(self.registration.registered_from.logs)
# RegistrationApproval#iniation_date is read only
self.registrat... | ion_approval,
(datetime.utcnow() - timedelta(days=365)),
safe=True
)
self.registration.registration_approval.save()
assert_false(self.registration.is_registration_approved)
main(dry_run=False)
assert_true(self.registration.is_registration_approved)
... |
gears/gears | gears/utils.py | Python | isc | 1,323 | 0 | import os
import re
from collections import Callable
missing = object()
class cached_property(object):
def __init__(self, func):
self.func = func
self.__name__ = func.__name__
self.__doc__ = func.__doc__
self.__module__ = func.__module__
def __get__(self, obj, type=None):
... |
i | f keyitem not in yielded:
yielded.add(keyitem)
yield item
def get_condition_func(condition):
if isinstance(condition, Callable):
return condition
if isinstance(condition, str):
condition = re.compile(condition)
return lambda path: condition.search(path)
|
coderjames/pascal | quex-0.63.1/quex/engine/generator/state/drop_out.py | Python | bsd-2-clause | 4,373 | 0.011891 | from quex.engine.generator.languages.address import Address
from quex.blackboard import E_EngineTypes, E_AcceptanceIDs, E_StateIndices, \
E_TransitionN, E_PostContextIDs, E_PreContextIDs, \
... | ement.position_register
else: register = None
case_list.append((LanguageDB.ACCEPTANCE(element.acceptance_id),
"%s %s" % \
(LanguageDB.POSITIONING(element.positioning, register),
Langua... | ment.acceptance_id))))
txt.extend(LanguageDB.SELECTION("last_acceptance", case_list))
|
ravrahn/HangoutsBot | hangupsbot/plugins/humor_hangoutcalls.py | Python | gpl-3.0 | 1,755 | 0.006838 | import time
import plugins
import hangups
def _initialise(bot):
plugins.register_handler(on_hangout_call, type="call")
def on_hangout_call(bot, event, command):
if event.conv_event._event.hangout_event.event_type == hangups.schemas.ClientHangoutEventType.END_HANGOUT:
las | tcall = bot.conversation_memory_get(event.conv_id, "lastcall")
if lastcall:
lastcaller = lastcall["caller"]
since = int(time.time() - lastcall["timestamp"])
if since < 120:
humantime = "{} seconds".format(since)
elif since < | 7200:
humantime = "{} minutes".format(since // 60)
elif since < 172800:
humantime = "{} hours".format(since // 3600)
else:
humantime = "{} days".format(since // 86400)
if bot.conversations.catalog[event.conv_id]["type"] == "ONE_TO_ONE... |
lacatus/TFM | bgsubtraction/__init__.py | Python | apache-2.0 | 305 | 0 | #!/usr/ | bin/env python
"""
The scripts that compose this module contains a set of functions
needed to process properly a background subtraction of each camera
of a dataset
"""
import cbackground
import cv2
import numpy as np
import sys
from gui import trackbar
from threedgeometry imp | ort frameretriever
|
1024jp/LensCalibrator | createimage.py | Python | mit | 6,006 | 0.000167 | #!/usr/bin/env python
"""
Undistort image.
(C) 2016-2018 1024jp
"""
import math
import os
import sys
import cv2
import numpy as np
from modules import argsparser
from modules.datafile import Data
from modules.undistortion import Undistorter
from modules.projection import Projector
# constants
SUFFIX = "_calib"
c... | fault)s)"
| )
script.add_argument('--stats',
action='store_true',
default=False,
help="display stats"
" (default: %(default)s)"
)
def add_suffix_to_path(path, suffix):
... |
cloudartisan/dojomaster | apps/attendance/models.py | Python | mit | 113 | 0 | from __ | future__ import unicode_literals
from django.db import models
class Attendance(models | .Model):
pass
|
chanjr/rheedsim | src/setup.py | Python | mit | 305 | 0.036066 | #1/usr/bin/env python3
import setuptools
setuptools.setup(
name = 'rheedsim',
version = '0.1.0',
packages = ['rheedsim'],
entry_points = {
'console_scripts':[
'rhee | dsim = rheedsim. | __main__:main'
]
},
)
|
Bristol-Braille/canute-ui | ui/book/help.py | Python | gpl-3.0 | 2,528 | 0.000396 | from ..braille import from_unicode
def _render(width, height, text):
# text must already be i18n-ed to Unicode.
data = []
lines = tuple(from_unicode(l) for l in text.split('\n'))
for line in lines:
data.append(line)
# pad page with empty rows
while len(data) % height:
data.a... | From the main menu you can access the library, \
insert a bookm | ark, return to a bookmark that was previously placed \
within a file, or navigate to a page within a book. You can select an \
item from the main menu by pressing the triangular line select button \
to the left of the menu item on the display.
You can choose a new book by pressing the line select button to the \
left ... |
tvenkat/askbot-devel | askbot/management/commands/send_accept_answer_reminders.py | Python | gpl-3.0 | 3,704 | 0.011609 | import datetime
from django.core.management.base import NoArgsCommand
from django.conf import settings as django_settings
from askbot import models
from askbot import const
from askbot.conf import settings as askbot_settings
from django.utils.translation import ugettext as _
from django.utils.translation import ungette... | thread__accepted_answer__isnull=True #answer_accepted = False
).order_by('-added_at')
#for all users, excluding blocked
#for each user, select a tag filtered subset
#format the email reminder and send it
for user in models.User.objec... | s.get_questions_needing_reminder(
activity_type = const.TYPE_ACTIVITY_ACCEPT_ANSWER_REMINDER_SENT,
user = user,
recurrence_delay = schedule.recurrence_delay
)
#todo: rewrite using query set filter
#may be a lot more efficient
... |
psychopy/psychopy | psychopy/tests/test_experiment/needs_wx/genComponsTemplate.py | Python | gpl-3.0 | 4,702 | 0.001489 | import sys
import os
import io
from pkg_resources import parse_version
import wx
if parse_version(wx.__version__) < parse_version('2.9'):
tmpApp = wx.PySimpleApp()
else:
tmpApp = wx.App(False)
from psychopy import experiment
from psychopy.experiment.components import getAllComponents
# usage: generate or com... |
# handle m | ulti-line default values, eg TextComponent.text.default
targetTag[t] += '\n' + line # previous t value
else:
outfile = open(relPath,'w')
param = experiment.Param('', '') # want its namespace
ignore = ['__doc__', '__init__', '__module__', '__str__', 'next']
if '--out' not in sys.argv:
# these are ... |
momentum/canteen | canteen/base/handler.py | Python | mit | 17,022 | 0.004935 | # -*- coding: utf-8 -*-
"""
handler base
~~~~~~~~~~~~
Presents a reasonable base class for a ``Handler`` object, which handles
responding to an arbitrary "request" for action. For example, ``Handler``
is useful for responding to HTTP requests *or* noncyclical realtime-style
requests, and acts as a base c... | nd injection side
__owner__, __metaclass__ = "Handler", injection.Compound
def __init__(self, environ=None,
| start_response=None,
runtime=None,
request=None,
response=None, **context):
""" Initialize a new ``Handler`` object with proper ``environ`` details and
inform it of larger world around it.
``Handler`` objects (much... |
CantemoInternal/pyxb | tests/trac/test-trac-0116.py | Python | apache-2.0 | 834 | 0.013189 | # -*- coding: utf-8 -*-
import logging
if __name__ == '__main__':
logging.basicConfig()
_log = logging.getLogger(__name__)
import pyxb.binding.generate
import pyxb.utils.domutils
from xml.dom import Node
import os.path
xsd='''<?xml version="1.0" encoding="utf-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLS... | Python(schema_text=xsd)
#open('binding0116.py', 'w').write(code)
rv = compile(code, 'test', 'exec')
eval(rv)
import unittest
class TestTrac0116 (unittest.TestCase):
xmls = '''<?xml version="1.0" encoding="utf-8"?><root foo='boo'/>'''
def testBasic (self):
self.assertRaises(pyxb.AttributeOnSimpleType... | = '__main__':
unittest.main()
|
kmike/funny-codes | setup.py | Python | mit | 712 | 0.009831 | #!/usr/bin/env python
from distutils.core import setup
version='1.0.1'
setup(
name='funny-codes',
version=version,
author='Mikhail Korobov',
author_email='[email protected]',
packages=['fu | nny_codes'],
url='https://bitbucket.org/kmike/funny-codes/',
license = 'MIT license',
description = "Generate randoms strings of a given pattern",
long_description = open('README.rst').read(),
classifiers=[
'Development Status :: 5 - Production/Stable',
| 'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
alecf/strava-raceways | raceways/handlers/homepage.py | Python | mit | 1,439 | 0.000695 | import json
from google.appengine.api import users
from raceways.handler import BaseHandler, using_template
from stravalib import unithelper
class HomepageHandler(BaseHandler):
@using_template('test.html')
def get(self):
# basic user login
strava_auth_uri = None
if self.user:
... | stream = []
print help(self.user)
print "User has: %s" % dir(self.user)
template_values = {
'strava_credentials': strav | a_credentials_json,
'strava_login_url': strava_auth_uri,
'logout_url': '/logout',
'login_url': '/login',
'user': self.user,
}
return template_values
|
Tima-Is-My-Association/TIMA | association/autocomplete_light_registry.py | Python | lgpl-3.0 | 694 | 0.010086 | import autocomplete_light
from association.models import | Word
from django.utils.translation import ugettext as _
class WordAutocomplete(autocomplete_light.AutocompleteModelBase):
search_fields=['name']
choice_html_format = '<span class="block os" data-value="%s">%s (%s)</span>'
attrs={
'placeholder': _('Filter'),
| 'data-autocomplete-minimum-characters': 1,
}
widget_attrs={
'data-widget-maximum-values': 6,
'class': 'modern-style',
}
def choice_html(self, choice):
return self.choice_html_format % (self.choice_value(choice), self.choice_label(choice), choice.language)
autocomplete_light.re... |
GoogleCloudPlatform/gsutil | gslib/tests/test_wrapped_credentials.py | Python | apache-2.0 | 4,593 | 0.003048 | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC. 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 require... | nce"], "foo")
self.assertEquals(json_values["_base"]["subject_token_type"], "bar")
self.assertEquals(json_values["_base"]["token_url"], "baz")
self.assertEquals(json_values["_base"]["credential_source"]["url"],
"www.google.com")
creds2 = WrappedCredentials.from_json(creds_json)
... | elf.assertIsInstance(creds2._base, identity_pool.Credentials)
self.assertEquals(creds2.client_id, "foo")
self.assertEquals(creds2.access_token, ACCESS_TOKEN)
self.assertEquals(creds2.token_expiry, creds.token_expiry)
|
sebastiandres/iwi131 | ipynb/06-Funciones/iwi131_code/es_primo_v1.py | Python | cc0-1.0 | 200 | 0 | n = int(raw_input('Ingrese n: '))
es_primo = True
d = 2
while d < n:
if n % d == 0:
| es_primo = False
d = d + 1
if es_primo:
print(n, 'es primo')
else:
print(n, | 'es compuesto')
|
titilambert/home-assistant | tests/components/zha/test_sensor.py | Python | apache-2.0 | 10,606 | 0.001037 | """Test zha sensor."""
from unittest import mock
import pytest
import zigpy.zcl.clusters.general as general
import zigpy.zcl.clusters.homeautomation as homeautomation
import zigpy.zcl.clusters.measurement as measurement
import zigpy.zcl.clusters.smartenergy as smartenergy
from homeassistant.components.sensor import D... | STORAGE_KEY] = {
"version": restore_state.STORAGE_VERSION,
"key": restore_state.STORAGE_KEY,
"data": [
{
"state": {
"entity_id": entity_id,
"state": str(state),
"attributes": {... | "context": {
"id": "3c2243ff5f30447eb12e7348cfd5b8ff",
"user_id": None,
},
},
"last_seen": now,
}
],
}
return
return _storage
@pytest.... |
masiqi/douquan | xiaoye.py | Python | mit | 1,068 | 0.005618 | from settings import *
import sys
from os.path import abspath, dirname, join
MEDIA_ROOT = '/home/xiaoye/workspace/douquan/site_media'
ADMIN_MEDIA_ROOT = '/home/xiaoye/workspace/douquan/admin_media/'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always ... | e paths.
'/home/xiaoye/workspace/douquan/templates',
) |
DATABASE_ENGINE = 'mysql' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = 'douquan' # Or path to database file if using sqlite3.
DATABASE_USER = 'douquan' # Not used with sqlite3.
DATABASE_PASSWORD = 'douquan' # Not used with sqlite3.
DAT... |
gwpy/gwpy.github.io | docs/v0.5/timeseries/plot-4.py | Python | gpl-3.0 | 137 | 0.007299 | h1hoft | = TimeSeries.fetch_open_data('H1', 'Sep 14 2015 09:50:29', 'Sep 14 2015 09:51:01')
ax = plot.gca()
ax.plot(h1hoft)
plot.refre | sh()
|
MingfeiPan/leetcode | stack/331.py | Python | apache-2.0 | 615 | 0.003252 | class Solution:
def isValidSerialization(self, preorder):
"""
:type preorder: str
:rtype: bool
"""
arr_pre_order = p | reorder.split(',')
stack = []
for node in arr_pre_order:
stack.append(node)
while len(stack) > 1 and stack[-1] == '#' and stack[-2] == '#':
stack.pop()
stack.pop()
| if len(stack) < 1:
return False
stack[-1] = '#'
if len(stack) == 1 and stack[0] == '#':
return True
return False
|
BdTNLM/SciMS | SciMs/settings.py | Python | mit | 3,325 | 0.001805 | """
Django settings for SciMs project.
Generated by 'django-admin startproject' using Django 1.10.3.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
... | tps://docs.djangoproject.com/en/1.10/topics/i18n/
LANGUAGE_ | CODE = 'en-us'
USE_I18N = True
USE_L10N = True
USE_TZ = True
TIME_ZONE = 'Europe/Paris'
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
'/var/www/static/',
]
LOGIN_REDIREC... |
blaiseli/p4-phylogenetics | share/Examples/W_recipes/sSim.py | Python | gpl-2.0 | 819 | 0.002442 | # Simulate data
if 0:
read("d.nex")
d = Data( | )
if 1:
nTax = 5
taxNames = list(string.uppercase[:nTax | ])
a = func.newEmptyAlignment(dataType='dna', taxNames=taxNames, length=200)
d = Data([a])
if 0:
read("t.nex")
t = var.trees[0]
#t.taxNames = taxNames
if 0:
read('(B:0.5, ((D:0.4, A:0.3), C:0.5), E:0.5);')
t = var.trees[0]
t.taxNames = taxNames
if 1:
t = func.randomTree(taxNames=tax... |
photoboard/photoboard-django | photoboard/wsgi.py | Python | mit | 398 | 0 | """
WSGI config for pho | toboard project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "photo... | ")
application = get_wsgi_application()
|
orlox/binary_tools | binary/tests/test_kicks.py | Python | gpl-3.0 | 32,399 | 0.019815 | #!/usr/bin/env python
from binary_tools.constants import *
from binary_tools.binary import kicks
from binary_tools.binary.orbits import *
import matplotlib.pyplot as plt
from scipy.stats import maxwell
from scipy.integrate import quad
import random as rd
import numpy as np
__author__ = "Kaliroe Pappas"
__credits__ = [... | plt.xlabel("phi value")
plt.ylabel("distribution")
plt.lege | nd(loc='upper right')
plt.show()
plt.close()
if save:
plt.hist(phi_array, bins=np.linspace(0,2*np.pi,nbins), alpha = 0.5, label = "function output")
plt.hist(test_array, bins=np.linspace(0,2*np.pi,nbins), alpha = 0.5, label = "expected value")
plt.title("phi distribution")
... |
keithroe/vtkoptix | Common/Core/Testing/Python/TestIterateCollection.py | Python | bsd-3-clause | 1,600 | 0.001875 | """Test iterating through a vtkCollection with the standard python syntax"""
import vtk
from vtk.test import Testing
class TestIterateCollection(Testing.vtkTest):
def setUp(self):
self.vtkObjs = [vtk.vtkObject() for _ in range(30)]
self.collection = vtk.vtkCollection()
for obj in self.vt... | dataArray = vtk.vtkIntArray()
dataArrayCollection = vtk.vtkDataArrayCollection()
dataArrayCollection.AddItem(dataArray)
self.assertEqual([obj for obj in dataArrayCollection],
[dataArray])
def testOperators(self):
self.assertTr | ue(self.vtkObjs[0] in self.collection)
self.assertEqual(list(self.collection), self.vtkObjs)
def testReferenceCounting(self):
initialReferenceCount = self.collection.GetReferenceCount()
list(self.collection)
self.assertEqual(self.collection.GetReferenceCount(), initialReferenceCount... |
enen92/script.screensaver.football.panel | resources/lib/common_addon.py | Python | gpl-2.0 | 2,346 | 0.005968 | # -*- coding: utf-8 -*-
'''
script.screensaver.football.panel - A Football Panel for Kodi
RSS Feeds, Livescores and League tables as a screensaver or
program addon
Copyright (C) 2016 enen92
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Gener... | .getSetting("tables-update-time"))
rss_update_time = int(addon.getSetting("rss-update-time"))
my_timezone = addon.getSetting("timezone")
my_location = pytz.timezone(pytz.all_timezones[int(my_timezone)])
hide_notstarted = addon.getSetting("hide-notstarted")
hide_finished = addon.getSetting("hide-finished")
show_alternat... | 32503
OPTIONS_PANEL = 6
OPTIONS_OK = 5
OPTIONS_CANCEL = 7
RSS_FEEDS = 32504
NO_GAMES = 32505
ACTION_LEFT = 1
ACTION_BACK1 = 10
ACTION_BACK2 = 92
def removeNonAscii(s):
return "".join(filter(lambda x: ord(x)<128, s))
def translate(text):
return addon.getLocalizedString(text).encode('utf-8')
|
matz-e/lobster | lobster/core/create.py | Python | mit | 5,617 | 0.00178 | from collections import defaultdict
import logging
import math
logger = logging.getLogger('lobster.algo')
class Algo(object):
"""A task creation algorithm
Attempts to be fair when creating tasks by making sure that tasks are
created evenly for every category and every workflow in each category
bas... | * how many tasks can still be created with the default size
Returns
-------
data : list
A list containing workflow label, how m | any tasks to create,
and the task taper adjustment.
"""
# Remaining workload
workloads = defaultdict(int)
for wflow, (complete, units, tasks) in remaining.items():
if not complete and tasks < 1.:
logger.debug("workflow {} has not enough units a... |
AlphaCluster/NewsBlur | utils/facebook_fetcher.py | Python | mit | 9,072 | 0.006944 | import re
import datetime
import dateutil.parser
from django.conf import settings
from django.utils import feedgenerator
from django.utils.html import linebreaks
from apps.social.models import MSocialServices
from apps.reader.models import UserSubscription
from utils import log as logging
from vendor.facebook import Gr... | facebook_api
def fetch_page_feed(self, facebook_user, page, | fields):
try:
stories = facebook_user.get_object(page, fields=fields)
except GraphAPIError, e:
message = str(e).lower()
if 'session has expired' in message:
logging.debug(u' ***> [%-30s] ~FRFacebook page failed/expired, disconnecting facebook: %s: %s... |
SuperDARNCanada/borealis | experiments/testing_archive/test_taps_not_list.py | Python | gpl-3.0 | 2,729 | 0.004397 | #!/usr/bin/python
# write an experiment that raises an exception
import sys
import os
BOREALISPATH = os.environ['BOREALISPATH']
sys.path.append(BOREALISPATH)
import experiments.superdarn_common_fields as scf
from experiment_prototype.experiment_prototype import ExperimentPrototype
from experiment_prototype.decimati... | scf.opts.site_id in ["sas", "pgr"]:
num_ranges = scf.STD_NUM_RANGES
slice_1 = { # slice_id = 0, there is only one slice.
"pulse_sequence": scf.SEQUENCE_7P,
"tau_spacing": scf.TAU_SPACING_7P,
"pulse_len": scf.PULSE_LEN_45KM,
"num_ranges": num_ranges,... | beams_to_use,
"scanbound": [i * 3.5 for i in range(len(beams_to_use))], #1 min scan
"txfreq" : scf.COMMON_MODE_FREQ_1, #kHz
"acf": True,
"xcf": True, # cross-correlation processing
"acfint": True, # interferometer acfs
}
self.add_slice(slice_... |
dperconti/hexwick_python | hexwick/views.py | Python | agpl-3.0 | 3,890 | 0 | from django.template import RequestContext
from django.shortcuts import render_to_response
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth.decorators import login_required
from datetime import datetime
from hexwick.forms i... | urn HttpResponse(status=201)
@login_required
def user_logout(request):
logout(request)
return HttpResponseRedirect('/')
def register(request):
if request.session.test_cookie_worked():
request.session.delete_test_cookie()
context = RequestContext(request)
registered = False
if requ... | UserForm(data=request.POST)
if user_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
registered = True
username = request.POST['username']
password = request.POST['password']
user = authent... |
bpshetty/erpnext | erpnext/setup/setup_wizard/setup_wizard.py | Python | gpl-3.0 | 18,648 | 0.030566 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe, copy
import os
import json
from frappe.utils import cstr, flt, getdate
from frappe import _
from frappe.utils.file_manager import save_f... | ):
frappe.get_doc({
"doctype":"Company",
'company_name':args.get('company_name' | ).strip(),
'abbr':args.get('company_abbr'),
'default_currency':args.get('currency'),
'country': args.get('country'),
'create_chart_of_accounts_based_on': 'Standard Template',
'chart_of_accounts': args.get('chart_of_accounts'),
'domain': args.get('domain')
}).insert()
#Enable shopping cart
enabl... |
gb1035/simple_nest | examples.py | Python | gpl-3.0 | 855 | 0.014035 | #!/usr/bin/env python
import nest
# Example of uses
def set_duration(duration=15):
if nest.get_variable('is_online') == True:
if nest,get_variable('has_fan') == True:
nest.get_variable('fan_timer_duration', duration)
return True
return False
def fan_on():
if nest.get_varia... |
return True
return False
def too_damn_hot():
if arrow. | get(get_timeout()) < arrow.now():
if not is_running():
set_duration()
fan_on()
if __name__ == '__main__':
print is_running()
|
Kami/munin_exchange | munin_exchange/apps/core/templatetags/navclass.py | Python | bsd-3-clause | 307 | 0.013029 | from django.template import Library, Node | , resolve_variable, TemplateSyntaxError
from django.core.urlresolvers import reverse
register = Library()
@register.simple_tag
def active(request, pattern):
import re
if re.search(pattern, request.get_full | _path()):
return 'active'
return '' |
rjschwei/azure-sdk-for-python | azure-mgmt-powerbiembedded/azure/mgmt/powerbiembedded/models/check_name_request.py | Python | mit | 1,018 | 0.001965 | # 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 ... | ------------------------------------------------------- | -------------
from msrest.serialization import Model
class CheckNameRequest(Model):
"""CheckNameRequest.
:param name: Workspace collection name
:type name: str
:param type: Resource type. Default value:
"Microsoft.PowerBI/workspaceCollections" .
:type type: str
"""
_attribute_map ... |
lulufei/youtube-dl | youtube_dl/options.py | Python | unlicense | 36,996 | 0.002054 | from __future__ import unicode_literals
import os.path
import optparse
import shlex
import sys
from .downloader.external import list_external_downloaders
from .compat import (
compat_expanduser,
compat_get_terminal_size,
compat_getenv,
compat_kwargs,
)
from .utils import (
preferredencoding,
w... | = []
for l in optionf:
res += shlex.split(l, comments=True)
finally:
optionf | .close()
return res
def _readUserConf():
xdg_config_home = compat_getenv('XDG_CONFIG_HOME')
if xdg_config_home:
userConfFile = os.path.join(xdg_config_home, 'youtube-dl', 'config')
if not os.path.isfile(userConfFile):
userConfFile = os.path.join(xdg_c... |
aristanetworks/arista-ovs-nova | nova/tests/test_metadata.py | Python | apache-2.0 | 17,823 | 0.000673 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compli... | 'b65cee2f-8c69-4aeb-be2f-f79742548fc2',
'name': 'fake',
'project_id': 'test',
'key_name': "mykey",
'key_data': "ssh-rsa AAAAB3Nzai....N3NtHw== someuser@somehost",
'host': 'test',
'launch_index': 1,
'instance_type': {'name': 'm1.tiny'},
'reservation_id': 'r-xxxxxxxx',
'user_d... | CODE_USER_DATA_STRING,
'image_ref': 7,
'vcpus': 1,
'fixed_ips': [],
'root_device_name': '/dev/sda1',
'info_cache': {'network_info': []},
'hostname': 'test.novadomain',
'display_name': 'my_displayname',
},
)
def return_non_existing_address(*args, **kwarg):
raise exception.Not... |
WilliamMayor/scytale.xyz | scripts/seed/seeder.py | Python | mit | 13,201 | 0.001667 | import os
from scytale import create_app
from scytale.ciphers import MixedAlphabet, Playfair, Fleissner, Trifid, Myszkowski
from scytale.models import db, Group, Message
from scytale.forms import MessageForm
def create_group(name):
print("Creating admin group ({})".format(name))
group = Group()
group.nam... | ield create_message(
group,
cipher=ciphers[1].name,
key=ciphers[1].key,
plaintext=pt,
ciphertext=ciphers[1].encrypt(pt))
pt = 'Lin | e three of the Trifid key is {}'.format(trifid.key[18:27])
yield create_message(
group,
cipher=ciphers[2].name,
key=ciphers[2].key,
plaintext=pt,
ciphertext=ciphers[2].encrypt(pt))
pt = 'CORRECT HORSE BATTERY STAPLE'
# Don't return this one, don't want it on the site... |
rutherford/mesa | TODO.py | Python | bsd-2-clause | 2,149 | 0.008841 | # mesa - toolkit for building dynamic python apps with zero downtime
# basis: package is inspected for all instances of specified abc and each added to internal mesa list
# Casa is a mesa obj is instantiated as holder of dynamic obj list, one for each abc type in specified package
# m = mesa.Casa(hideExceptions=False) ... | casa
# build casa, call method not in abc
# build casa with concrete class not implementing an abc method | |
dwiajik/twit-macet-mining-v2 | modules/location.py | Python | mit | 1,393 | 0.003589 | import os
import re
import nltk
from nltk.tag import tnt
from modules import cleaner
class Location:
def __init__(self):
train_data = []
with open(os.path.join(os.path.dirname(__file__), 'tagged_locations.txt'), 'r') as f:
for line in f:
train_data.append([nltk.tag.st... | if subtree.label() == 'LOC':
location = []
for leave in subtree.leaves():
location.append(leave[0])
locations.append(' '.join(location))
return locations
def is_first_loc_similar(self, text1, text2):
try:
loc1 = ... | 1)[0]
except IndexError as e:
loc1 = ''
try:
loc2 = self.get_locations(text2)[0]
except IndexError as e:
loc2 = ''
return loc1 == loc2 |
billingstack/python-fakturo | fakturo/core/cli/base.py | Python | apache-2.0 | 3,279 | 0 | #
# Author: Endre Karlson <[email protected]>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | return parser
def execute(self, parsed_args):
"""
Execute something, this is since we overload self.take_action()
| in order to format the data
:param parsed_args: The parsed args that are given by take_action()
"""
return self.app.provider_manager.execute(
self.method_name,
parsed_args,
self)
def post_execute(self, data):
"""
Format the results lo... |
smartforceplus/SmartForceplus | openerp/addons/tag_project_tasks/__openerp__.py | Python | agpl-3.0 | 311 | 0.009646 | {
'name': "Tag Project/Task View",
'version': "1.0",
'author': 'TAG Small Biz Community',
'website': 'http://www.smallbiz.community',
'category': "Tools",
'data': [ | 'task_view.xml','project_view.xml'
],
'demo': [],
| 'depends': ['project'],
'installable': True,
} |
westurner/pkgsetcomp | docs/conf.py | Python | bsd-3-clause | 8,492 | 0.005299 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# complexity documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# ... | in_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = T | rue
# If true, "Created using Sphinx" is shown in the HTML footer.
# Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer.
# Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages
# will contain a <link> tag... |
zwffff2015/stock | db/MysqlUtil.py | Python | mit | 850 | 0.002353 | # coding:utf-8
import os
from db.MysqlHelper import MySqlConnection
from common.JsonHelper import loadJsonConfig
MYSQLCONNECTION = None
def initMysql():
global MYSQLCONNECTION
config = loadJsonConfig(os.path.abspath(os.path.join(os.getcwd(), "../config/db.json")))
| MYSQLCONNECTION = MySqlConnection(config['host'], config['port'], config['user'], config['password'],
config['database'])
def execute(sql, parameter=None):
global MYSQLCONNECTION
MYSQLCONNECTION.execute(sql, parameter)
def select(sql, fetchall=True):
global MYSQL... | TION
MYSQLCONNECTION.batchInsert(sql, parameters)
def disconnect():
global MYSQLCONNECTION
MYSQLCONNECTION.disconnect()
|
aikramer2/spaCy | spacy/tests/stringstore/test_stringstore.py | Python | mit | 3,384 | 0.000887 | # coding: utf-8
from __future__ import unicode_literals
from ...strings import StringStore
import pytest
def test_string_hash(stringstore):
'''Test that string hashing is stable across platforms'''
ss = stringstore
assert ss.add('apple') == 8566208034543834098
heart = '\U0001f499'
print(heart)
... |
def test_stringstore_save_bytes(stringstore, text1, text2, text3):
key = stringstore.add(text1)
assert stringstore[text1] == key
assert stringstore[text2] != key
assert stringstore[text3] != key
@pytest.mark.parametrize('text1,text2,text3', [('Hello', 'goodbye', 'hello')])
def test_stringstore_save | _unicode(stringstore, text1, text2, text3):
key = stringstore.add(text1)
assert stringstore[text1] == key
assert stringstore[text2] != key
assert stringstore[text3] != key
@pytest.mark.parametrize('text', [b'A'])
def test_stringstore_retrieve_id(stringstore, text):
key = stringstore.add(text)
... |
clubcapra/Ibex | src/seagoatvision_ros/scripts/CapraVision/server/filters/implementation/mti880.py | Python | gpl-3.0 | 5,241 | 0.006487 | #! /usr/bin/env python
# Copyright (C) 2012 Club Capra - capra.etsmtl.ca
#
# This file is part of CapraVision.
#
# CapraVision 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 versio... | in self.observers:
obs()
def execute(self, image):
| image = cv2.cvtColor(image, cv2.cv.CV_BGR2HSV)
h, _, _ = cv2.split(image)
image[h < self.hue_min] *= 0
image[h > self.hue_max] *= 0
#image[image > 0] = 255
gray = cv2.cvtColor(image, cv.CV_BGR2GRAY)
cnt, _ = cv2.findContours(gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_... |
mmagnus/rna-pdb-tools | rna_tools/tools/mini_moderna3/moderna/fragment_library/SearchLIR.py | Python | gpl-3.0 | 21,344 | 0.014618 | #!/usr/bin/env python
#
# SearchLIR.py
#
# Searches a local LIR file for RNA fragments that fits.
#
# http://iimcb.genesilico.pl/moderna/
#
__author__ = "Magdalena Rother, Tomasz Puton, Kristian Rother"
__copyright__ = "Copyright 2008, The Moderna Project"
__credits__ = ["Janusz Bujnicki"]
__license__ = "GPL"
__maintai... | ng functions and advanced scoring functions.
"""
def __init__(self, scoring_mode = 'fast'):
if scoring_mode == 'fast': self.set_fast_scoring()
elif scoring_mode == 'advanced': self.set_advanced_scoring()
def set_fast_scoring(self, atom_distance = 10.0, seq_sim=0.0, secstruc=100.0):
... | goodness and sequence similarity.
RMSD, clashes and HBonds are always 0 for fast scoring.
"""
self.distance = atom_distance
self.seq_similarity = seq_sim
self.rmsd = 0
self.clashes = 0
self.secstruc = secstruc
def set_advanced_scoring(self, atom_dist... |
TaliesinSkye/evennia | src/commands/default/batchprocess.py | Python | bsd-3-clause | 24,488 | 0.002654 | """
Batch processors
These commands implements the 'batch-command' and 'batch-code'
processors, using the functionality in src.utils.batchprocessors.
They allow for offline world-building.
Batch-command is the simpler system. This reads a file (*.ev)
containing a list of in-game commands and executes them in sequence... | step_pointer, BatchSafeCmdSet
caller.ndb.batch_sta | ck = codes
caller.ndb.batch_stackptr = 0
caller.ndb.batch_batchmode = "batch_code"
caller.cmdset.add(BatchSafeCmdSet)
for inum in range(len(codes)):
print "code:", inum
caller.cmdset.add(BatchSafeCmdSet)
if not batch_code_exec(caller):
break
step_pointer(caller, 1)
print "leaving run ..."
"""
... |
julcollas/django-smokeping | smokeping/templatetags/repeat.py | Python | gpl-2.0 | 1,004 | 0.010956 | from django import template
register = template.Library()
class RepeatNode(template.Node | ):
def __init__(self, nodelist, count):
self.nodelist = nodelist
self.count = template.Variable(count)
def render(self, context):
output = self.nodelist.render(context)
return output * int(self.count.resolve(context) + 1)
def repeat(parser, token):
"""
Repeats the ... | o
repeat the enclosing content.
Example::
{% repeat 3 %}foo{% endrepeat %}
Yields::
foofoofoo
"""
bits = token.split_contents()
if len(bits) != 2:
raise template.TemplateSyntaxError('%r tag requires 1 argument.' % bits[0])
count = bits[1]... |
yamt/neutron | quantum/plugins/nec/db/api.py | Python | apache-2.0 | 7,759 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2012 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.or... | old_style):
if old_style:
return old_resource_map[resource]
else:
return resource_map[resource]
def initialize():
db.configure_db()
def clear_db(base=model_base.BASEV2):
db.clear_db(base)
def get_ofc_item(session, resource, quantum_id, old_style=False):
try:
model = _g... | ource, old_style)
return session.query(model).filter_by(quantum_id=quantum_id).one()
except sa.orm.exc.NoResultFound:
return None
def get_ofc_id(session, resource, quantum_id, old_style=False):
ofc_item = get_ofc_item(session, resource, quantum_id, old_style)
if ofc_item:
if old_st... |
pcu4dros/pandora-core | workspace/lib/python3.5/site-packages/werkzeug/debug/__init__.py | Python | mit | 17,737 | 0.000056 | # -*- coding: utf-8 -*-
"""
werkzeug.debug
~~~~~~~~~~~~~~
WSGI application traceback debugger.
:copyright: (c) 2014 by the Werkzeug Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import os
import re
import sys
import uuid
import json
import time... | ng of the pin system.
"""
def __init__(self, app, evalex=False, request_key='werkzeug.request',
console_path='/console', console_init_func=None,
show_hidden_frames=False, lodgeit_url=None,
pin_security=True, pin_logging=True):
if lodgeit_url is ... | nit_func:
console_init_func = None
self.app = app
self.evalex = evalex
self.frames = {}
self |
JamesMura/sentry | src/sentry/newsletter/base.py | Python | bsd-3-clause | 571 | 0 | from __future__ import absolute_import
class Newsletter(object):
__all__ = ('is_enabled', 'get_subscriptions', 'update_subscription',
| 'create_or_update_subscription')
DEFAULT_LIST_ID = 1
enabled = False
def is_enabled(self):
return self.enabled
def get_subscriptions(self, user):
return None
def update_subscription(self, user, **kwargs):
return None
def create_or_update_ | subscription(self, user, **kwargs):
kwargs['create'] = True
return self.update_subscription(user, **kwargs)
|
Eternali/synk | synk-pre/synk2cp2.py | Python | gpl-3.0 | 618 | 0 | """
"""
import diffl | ib
import hashlib
import math
import os
import socket
import time
# global variables
settings_filename = "/home/fa11en/.config/synk/synk-settings.conf"
server_ip_field = "server_ip"
server_port_field = "server_port"
local_project_loc_field = "local_project_location"
server_project_loc_field = "server_project_location... | on classes
class Server_conn(object):
def __init__(self, settings, attempts):
# get the relevent settings
self.server_ip = settings[server_ip_field]
|
bigswitch/nova | nova/tests/unit/api/openstack/compute/test_flavor_rxtx.py | Python | apache-2.0 | 3,454 | 0.000579 | # Copyright 2012 Nebula, 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 agree... | setUp(self):
super(FlavorRxtxTestV21, self).setUp()
ext = ('nova.api.openstack.compute.contrib'
'.flavor_rxtx.Flavor_ | rxtx')
self.flags(osapi_compute_extension=[ext])
fakes.stub_out_nw_api(self)
self.stubs.Set(flavors, "get_all_flavors_sorted_list",
fake_get_all_flavors_sorted_list)
self.stubs.Set(flavors,
"get_flavor_by_flavor_id",
fa... |
tbenthompson/codim1 | test/test_speed.py | Python | mit | 524 | 0.003817 | # This file is simply here to make sure that everything is running just as
# fast under the virtualbox as under the host | OS. There should be no
# performance degradation. This takes me (Ben) approximately 1.2sec outside my
# virtual machine and appx 1.15sec inside the virtual machine. WHY IT IS
# FASTER inside the VM?! WHY?
import time
def time_fnc():
a = range(1, 1000000)
for i in range(1, 200):
b = sum(a)
t0 = time.t... | time.time()
print("Required: " + str(t1 - t0) + " seconds.")
|
chrizzFTD/grill | grill/logger/model.py | Python | gpl-3.0 | 1,265 | 0 | # -*- coding: utf-8 -*-
"""
Grill logging module.
"""
# standard
from __future__ import annotations
import logging
from pathlib import Path
from naming import NameConfig
from grill.names import DateTimeFile
_LOG_FILE_SUFFIX = 'log'
class ErrorFilter(logging.Filter):
| """
Pass any message meant for stderr.
"""
def filter(self, record):
"""
If the record does is not logging.INFO, return True
"""
return record.levelno > logging.INFO
class OutFilter(logging.Filter):
"""
Pass any message meant for stderr.
"""
def filter(se... | DateTimeFile):
"""docstring for LogFile"""
config = dict(
log_name=r'[\w\.]+',
log_filter=r'\d+',
)
file_config = NameConfig(dict(suffix=_LOG_FILE_SUFFIX))
@property
def path(self):
return Path(r'~/grill').expanduser() / super().name
@property
def _defaults(self... |
tareqalam/plone.formbuilder | setup.py | Python | gpl-3.0 | 1,905 | 0 | # -*- coding: utf-8 -*-
"""Installer for the plone.formbuilder package."""
from setuptools import find_packages
from setuptools import setup
long_description = '\n\n'.join([
open('README.rst').read(),
open('CONTRIBUTORS.rst').read(),
open('CHANGES.rst').read(),
])
setup(
name='plone.formbuilder',
... |
extras_require={
'test': [
'plone.app.testing',
# Plone KGS does not use this version, because it would break
# Remove if your package shall be part of coredev.
# plone_coredev tests as of 2016-04-01.
'plone.testing>=5.0.0',
'plone.app... | _points="""
[z3c.autoinclude.plugin]
target = plone
""",
)
|
Tinkerforge/brickv | src/brickv/plugin_system/plugins/industrial_dual_analog_in/industrial_dual_analog_in.py | Python | gpl-2.0 | 9,465 | 0.002959 | # -*- coding: utf-8 -*-
"""
Industrial Dual Analog In Plugin
Copyright (C) 2015 Olaf Lüke <[email protected]>
Copyright (C) 2015-2016 Matthias Bolte <[email protected]>
industrial_dual_analog_in.py: Industrial Dual Analog In Plugin Implementation
This program is free software; you can redistribute it and/or... | oltage_ch0.value()/measured0
factor1 = self.spinbox_voltage_ch1.value()/measured1
gain0 = int((factor0 - 1) * 2 ** 23)
gain1 = int((factor1 - 1) * 2 ** 23)
if not is_int32(gain0) or not is_int32(gain1):
raise ValueError("Out of range")
except:
... | ng Calibration", "Calibration values are not in range.", QMessageBox.Ok)
return
self.parent.analog_in.set_calibration((self.current_offset0, self.current_offset1), (gain0, gain1))
self.update_calibration()
def get_calibration_async(self, cal):
self.current_offset0 = cal.offset[... |
Southpaw-TACTIC/TACTIC | src/tactic/ui/app/system_info_wdg.py | Python | epl-1.0 | 19,736 | 0.007499 | ###########################################################
#
# Copyright (c) 2010, Southpaw Technology
# All Rights Reserved
#
# PROPRIETARY INFORMATION. This software is proprietary to
# Southpaw Technology, and is not to be reproduced, transmitted,
# or disclosed in any way without written permi... | mailserver = Config.get_value("services", "mailserver")
has_mailserver = True
if mailserver:
table.add_cell( mailserver )
else:
table.add_cell("None configured")
has_mailserver = False
login = Login.get_by_login('admin')
login_email = logi... | .add_cell("From: ")
td.add_style("width: 150px")
text = TextWdg('email_from')
text.set_attr('size', '40')
text.set_value(login_email)
text.add_class('email_from')
table.add_cell(text)
table.add_row()
td = table.add_cell("To: ")
td.add_styl... |
anhstudios/swganh | data/scripts/templates/object/draft_schematic/structure/shared_generic_house_player_small_style_02_floorplan_02.py | Python | mit | 487 | 0.045175 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODI | FICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Intangible()
result.template = "object/draft_schematic/structure/shared_generic_house_player_small_style_02_floorplan_02.iff"
result.attribute_template_id = -1
r... | END MODIFICATIONS ####
return result |
sporkmonger/aws-nmap | awsnmap/__init__.py | Python | apache-2.0 | 930 | 0 | # Borrowed liberally from awscli.
"""
AWS-NMAP
----
A Universal Command Line Environment for Amazon Web Services.
"""
import os
__version__ = '0.0.1'
#
# Get our data path to be added to botocore's search path
#
_awscli_data_path = []
if 'AWS_DATA_PATH' in os.environ:
for path in os.environ['AWS_DATA_PATH'].split... | path = os.path.expanduser(path)
_awscli_data_path.append(path)
_awscli_data_path.append(
os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data')
)
| os.environ['AWS_DATA_PATH'] = os.pathsep.join(_awscli_data_path)
EnvironmentVariables = {
'ca_bundle': ('ca_bundle', 'AWS_CA_BUNDLE', None, None),
'output': ('output', 'AWS_DEFAULT_OUTPUT', 'json', None),
}
SCALAR_TYPES = set([
'string', 'float', 'integer', 'long', 'boolean', 'double',
'blob', 'time... |
DreamerBear/awesome-py3-webapp | www/core/template/jinja2/filters.py | Python | gpl-3.0 | 667 | 0 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date : 2017/10/19 12:52
# @Author : xxc727xxc ([email protected])
# @Version : 1.0.0
from datetime import datetime
import time
from core.template.jinja2.init import jinja_filter
@jinja_filter('datetime')
def datetime_filter(t):
delta = int( | time.time() - t)
if delta < 60:
return '1分钟前'
if delta < 3600:
return '%s分钟前' % (delta // 60)
if delta < 86400:
return '%s小时前' % (delta // 3600)
if delta < 604800:
return '%s天前' % (delta // 86400)
dt = datetime. | fromtimestamp(t)
return '%s年%s月%s日' % (dt.year, dt.month, dt.day)
|
urwid/urwid | urwid/escape.py | Python | lgpl-2.1 | 15,967 | 0.01691 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Urwid escape sequences common to curses_display and raw_display
# Copyright (C) 2004-2011 Ian Ward
#
# This library 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 ... | self.add(self.data, s, result)
def add(self, root, s, result):
assert type(root) == dict, "trie conflict detected"
assert len(s) > 0, "trie conflict detected"
if ord(s[0]) in root:
r | eturn self.add(root[ord(s[0])], s[1:], result)
if len(s)>1:
d = {}
root[ord(s[0])] = d
return self.add(d, s[1:], result)
root[ord(s)] = result
def get(self, keys, more_available):
result = self.get_recurse(self.data, keys, more_available)
if not r... |
andikleen/pmu-tools | knl_ratios.py | Python | gpl-2.0 | 2,582 | 0.005035 | import metrics
import node
import slm_ratios as slm
version = "1.0"
slm.set_clks_event_name("CPU_CLK_UNHALTED.THREAD")
smt_enabled = False
class CyclesPerUop(slm.CyclesPerUop):
server = True
# LEVEL 1
class FrontendBound(slm.FrontendBound):
server = True
class BackendBound(slm.BackendBound):
server = ... | e nodes as required to be able to specify their
# references
# L3 objects
icache_misses = ICacheMisses()
itlb_misses = ITLBMisses()
ms_cost = MSSwitches()
#L1 objects
frontend = FrontendBound()
bad_speculation = BadSpeculation()
retiring = Retiri... | ackend = BackendBound(retiring=retiring,
bad_speculation=bad_speculation,
frontend=frontend)
# L2 objects
frontend_latency = FrontendLatency(icache_misses=icache_misses,
itlb=itlb_misses,
... |
koala-ai/tensorflow_nlp | nlp/ner/idcnn/run.py | Python | apache-2.0 | 3,000 | 0.009333 | # -*- coding:utf-8 -*-
import argparse
from nlp.ner.idcnn.train import train
from nlp.ner.idcnn.predict import predict
def main(args):
if args.train:
train(args)
else:
predict(args)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--train', type=boo... | e=int, default=100, help="Embedding size for characters")
parser.add_argument('--lstm_dim', type=int, default=100, help="Num | of hidden units in LSTM, or num of filters in IDCNN")
parser.add_argument('--tag_schema', type=str, default="iobes", help="tagging schema iobes or iob")
parser.add_argument('--clip', type=int, default=5, help="Gradient clip")
parser.add_argument('--dropout', type=float, default=0.5, help="Dropout rate")
... |
deepjets/deepjets | deepjets/tests/test_preprocessing.py | Python | bsd-3-clause | 1,088 | 0 |
from nose.tools import (raises, assert_raises, assert_true,
assert_equal, assert_not_equal, assert_almost_equal)
import numpy as np
from numpy.testing import assert_array_equal, assert_array_almost_equal
from deepjets.preprocessing import zoom_image, pixel_edges
def test_zoom():
edges =... | ixel_size=(0.1, 0.1), border_size=0.25)
assert_equal(edges[0].shape, (26,))
assert_equal(edges[1].shape, (26,))
image, _, _ = np.histogram2d(
np.random.normal(0, 1, 1000), np.random.normal(0, 1, 1000),
bins=(edges[0], edges[1 | ]))
assert_true(image.sum() > 0)
assert_equal(image.shape, (25, 25))
# zooming with factor 1 should not change anything
image_zoomed = zoom_image(image, 1, out_width=25)
assert_array_almost_equal(image, image_zoomed)
assert_raises(ValueError, zoom_image, image, 0.5)
# test out_width
a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.