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 |
|---|---|---|---|---|---|---|---|---|
nirea/collardata | freebielist.py | Python | gpl-2.0 | 4,787 | 0.005849 | from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from model import FreebieItem, Distributor, Contributor
import datetime
import logging
head = '''
<html>
<head>
<title>%s</title>
<script src="/static/sorttable.js"></script>
<style>
body {
background-c... | i = -1
else:
i = record.freebie_texture_update
content += ['<td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%d</td>\n' % (owner, record.freebie_giver, record.freebie_name, record.freebie_version, record.freebie_timedate, record.freeb... | ord.freebie_texture_key, record.freebie_texture_serverkey, i)]
content = sorted(content)
for i in range(0,len(content)):
message += '<tr><td>%d</td>%s' % (i+1, content[i])
message += "</table>"
self.response.out.write((head % 'Freebie Items List') + message + e... |
ales-erjavec/anyqt | AnyQt/_backport/QtDesigner.py | Python | gpl-3.0 | 30 | 0.033333 | from Py | Qt5.QtDesigner import * | |
sandan/sqlalchemy | lib/sqlalchemy/orm/persistence.py | Python | mit | 51,786 | 0.000019 | # orm/persistence.py
# Copyright (C) 2005-2016 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""private module containing functions used to emit INSERT, UPDATE
and DELETE sta... | update = _collect_update_commands(
uowtransaction, table, states_to_update)
_emit_update_statements(base_mapper, uowtransaction,
| cached_connections,
mapper, table, update)
_emit_insert_statements(base_mapper, uowtransaction,
cached_connections,
mapper, table, insert)
_finalize_insert_update_commands(
bas... |
AnoopAlias/XtendWeb | scripts/hhvm_ghost_hunter.py | Python | gpl-3.0 | 3,290 | 0.004863 | #!/usr/bin/env python
import yaml
import pwd
import sys
import subprocess
import json
import os
__author__ = "Anoop P Alias"
__copyright__ = "Copyright Anoop P Alias"
__license__ = "GPL"
__email__ = "anoopalias01@gmail.com"
installation_path = "/opt/nDeploy" # Absolute Installation Path
if __name__ == "__main_... | subprocess.call(['systemctl', 'stop', 'ndeploy_hhvm@'+cpaneluser+'.service'])
subprocess.call(['systemctl', 'disable', 'ndeploy_hhvm@'+cpaneluser+'.service'])
if os.path.isfile(installation_path+"/conf/ndeploy_cluster.yaml"):
subprocess.call('ansible -i /opt/... | "', shell=True)
|
rain1024/underthesea | underthesea/corpus/corpus.py | Python | gpl-3.0 | 87 | 0 | cla | ss Corpus:
"""Interface for corpus
"""
def __init_ | _(self):
pass
|
jptomo/rpython-lang-scheme | rpython/memory/gc/test/test_object_pinning.py | Python | mit | 38,271 | 0.001698 | import py
from rpython.rtyper.lltypesystem import lltype, llmemory, llarena
from rpython.memory.gc.incminimark import IncrementalMiniMarkGC, WORD
from test_direct import BaseDirectGCTest
T = lltype.GcForwardReference()
T.become(lltype.GcStruct('pinning_test_struct2',
('someInt', lltype.Signed)... | assert self.gc.pinned_objects_in_nursery == 0
assert self.gc.pin(pinned_adr)
assert self.gc.pinned_objects_in_nursery == 1
collect_func()
assert self.gc.pinned_objects_in_nursery == 1
self.gc.unpin(pinned_adr)
assert self.gc.pinned_objects_in_nursery == 0
collect_... | tion)
def test_pin_unpin_pinned_object_count_major_collection(self):
self.pin_unpin_pinned_object_count(self.gc.collect)
def pinned_obj_in_stackroot(self, collect_func):
# scenario: a pinned object that is part of the stack roots. Check if
# it is not moved
#
ptr = sel... |
coolbombom/CouchPotatoServer | couchpotato/core/plugins/automation/main.py | Python | gpl-3.0 | 1,352 | 0.016272 | from couchpotato.core.event import addEvent, fireEvent
from couchpotato.core.logger import CPLog
from couchpotato.core.plugins.base import Plugin
from couchpotato.environment import Env
log = CPLog(__name__)
class Automation(Plugin):
| def __init__(self):
addEvent('app.load', self.setCrons)
if not Env.get('dev'):
addEvent('app.load', self.addMovies)
addEvent('setting.save.automation.hour.after', self.setCrons)
def setCrons(self):
fireEvent('schedule.interval', 'automation.add_movies', self.addMovi... | f):
movies = fireEvent('automation.get_movies', merge = True)
movie_ids = []
for imdb_id in movies:
prop_name = 'automation.added.%s' % imdb_id
added = Env.prop(prop_name, default = False)
if not added:
added_movie = fireEvent('movie.add', pa... |
GastonLab/ddb-scripts | specialist/scan_multi-gene_annotated_snpEff.py | Python | mit | 1,956 | 0.00409 | #!/usr/bin/env python
# Standard packages
import sys
import cyvcf2
import argparse
import geneimpacts
from cyvcf2 import VCF
def get_effects(variant, annotation_keys):
effects = []
effects += [geneimpacts.SnpEff(e, annotation_keys) for e in variant.INFO.get("ANN").split(",")]
return effects
def get_t... | elp="File for output information")
args = parser.parse_args()
sys.stdout.write("Parsing VCFAnno VCF with CyVCF2\n")
reader = cyvcf2.VCFReader(args.annotated_vcf)
desc = reader["ANN"]["Description"]
annotation_keys = [x.strip("\"'") for x in re.split("\s*\|\s*", desc.split(":", 1)[1].strip('" '))]
... | d_vcf)
for variant in vcf:
effects = get_effects(variant, annotation_keys)
top_impact = get_top_impact(effects)
gene_effects = dict()
for effect in effects:
if effect.gene not in gene_effects.keys():
if effect.transcript is not None:
|
MrPablozOne/kaira | ptp/base/analysis.py | Python | gpl-3.0 | 6,178 | 0.003561 | #
# Copyright (C) 2013 Stanislav Bohm
#
# This file is part of Kaira.
#
# Kaira 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 3 of the License, or
# (at your option) any later versi... | ted only in variables and bulk inscriptions
if inscription.expr not in overtaken_variables:
overtaken_variables.add(inscription.expr)
bulk_overtake.append(inscription.uid)
for inscription in inscriptions_out:
for variable in inscription.get_other_variables():
if ... | le_sources and \
variable not in variable_sources_out:
variable_sources_out[variable] = None
tr.inscriptions_in = inscriptions_in
tr.inscriptions_out = inscriptions_out
tr.variable_sources = variable_sources
tr.reuse_tokens = reuse_tokens
tr.variable_sources_out = var... |
tsl143/addons-server | src/olympia/ratings/tests/test_tasks.py | Python | bsd-3-clause | 3,772 | 0 | import mock
from olympia.amo.tests import addon_factory, TestCase, user_factory
from olympia.ratings.models import Rating
from olympia.ratings.tasks import addon_rating_aggregates
class TestAddonRatingAggregates(TestCase):
# Prevent <Rating>.refresh() from being fired when setting up test data,
# since it'd ... | addon=addon, rating=1, user=user, is_latest=False, body=u'old')
new_rating = Rating.objects.create(addon=addon, rating=3, us | er=user,
body=u'new')
Rating.objects.create(addon=addon, rating=3, user=user_factory(),
body=u'foo')
Rating.objects.create(addon=addon, rating=2, user=user_factory())
Rating.objects.create(addon=addon, rating=1, user=user_f... |
WladimirSidorenko/CGSA | cgsa/dl/base.py | Python | mit | 20,205 | 0.000099 | #!/usr/bin/env python
# -*- mode: python; coding: utf-8 -*-
##################################################################
# Documentation
##################################################################
# Imports
from __future__ import absolute_import, unicode_literals, print_function
try:
from cPickle im... | **self._fit_params)
self._model.load_weights(ofname)
| self._finish_training()
finally:
os.remove(ofname)
self._logger.debug("%s trained", self.name)
def predict_proba(self, msg, yvec):
wseq = self._tweet2wseq(msg)
embs = np.array(
self._pad(len(wseq), self._pad_value)
+ [self.get_test_w_emb(w) ... |
mzdaniel/oh-mainline | vendor/packages/kombu/kombu/transport/pyamqplib.py | Python | agpl-3.0 | 9,517 | 0.002102 | """
kombu.transport.pyamqplib
============ | =============
amqplib transport.
:copyright: (c) 2009 - 2011 by Ask Solem.
:license: BSD, see LICENSE for more details.
"""
import socket
try:
from ssl import SSLError
except ImportError:
class SSLError(Exception): # noqa
pass
from amqplib import client_0_8 as amqp
from amqplib.client_0_8 import t... | client_0_8.exceptions import AMQPConnectionException
from amqplib.client_0_8.exceptions import AMQPChannelException
from kombu.transport import base
from kombu.utils.encoding import str_to_bytes
DEFAULT_PORT = 5672
# amqplib's handshake mistakenly identifies as protocol version 1191,
# this breaks in RabbitMQ tip, w... |
MiningTheDisclosures/conflict-minerals-data | conflict_minerals_data/edgar/migrations/0008_edgardocumentcontent_urls.py | Python | mit | 628 | 0.001592 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-08-14 06:27
from __future__ import unicode_literals
import django.contrib.postgres.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('edgar', '0007_auto_20170706_2215'),
]
operati... | 'edgardocumentcontent',
name='urls',
field=django.contrib.postgres.fields.ArrayF | ield(base_field=models.TextField(blank=True), blank=True, help_text='URL we parsed out of the content', null=True, size=None),
),
]
|
hydrogen18/fairywren | tracker.py | Python | mit | 8,937 | 0.053933 | import vanilla
import urlparse
import fnmatch
import base64
import bencode
import struct
import socket
import peers
import posixpath
from eventlet.green import zmq
import cPickle as pickle
import eventlet.queue
import fairywren
import itertools
import logging
import array
def sendBencodedWsgiResponse(env,start_respons... | yteCount):
byteCount = int(byteCount)
if byteCount < 0:
raise ValueError('byte count cannot be negative')
return byteCount
params.append(('port',None,validatePort))
params.append(('uploaded',None,validateByteCount))
params.append(('downloa | ded',None,validateByteCount))
params.append(('left',None,validateByteCount))
#If the client doesn't specify the compact parameter, it is
#safe to assume that compact responses are understood. So a
#default value of 1 is used. Additionally, any non zero
#value provided assumes the client wants a compact respon... |
daniestevez/gr-satellites | python/components/deframers/yusat_deframer.py | Python | gpl-3.0 | 2,570 | 0 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2021-2022 Daniel Estevez <daniel@destevez.net>
#
# This file is part of gr-satellites
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
from gnuradio import gr, digital
import pmt
from ...hier.sync_to_pdu_packed import sync_to_pdu_packed
from ...hdlc_deframer ... | cdr(msg_pmt)
if not pmt.is_u8vector(msg):
print('[ERROR] Received invalid message type. Expected u8vector')
return
packet = pmt.u8vector_elements(msg)
start = 0
while True:
try:
idx = packet[start:].index(0x7e)
except ValueE... | dx + 1
p = packet[:idx]
if self.crc_check.fcs_ok(p):
p = p[:-2]
self.message_port_pub(
pmt.intern('out'),
pmt.cons(pmt.PMT_NIL, pmt.init_u8vector(len(p), p)))
return
class yusat_deframer(gr.hier_block2):
... |
ngageoint/geoq | geoq/accounts/migrations/0001_initial.py | Python | mit | 3,881 | 0.004638 | # Generated by Django 3.0.5 on 2020-04-17 14:12
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import easy_thumbnails.fields
import userena.models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_... | , models.ForeignKey(blank=True, help_text="If '------', no Organization records share the email domain.", null=True, on_delete=django.db.models.deletion.PROTECT, to='accounts.Organization')),
| ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='user')),
],
options={
'permissions': (('view_profile', 'Can view profile'),),
'abstract': False,
'default_permissions': ('add', ... |
barseghyanartur/django-admin-tools-stats | admin_tools_stats/migrations/0001_initial.py | Python | mit | 3,865 | 0.004398 | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2015-12-13 11:29
from __future__ import unicode_literals
from django.db import migrations, models
import jsonfield.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
... | name='DashboardStatsCriteria',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_na | me='ID')),
('criteria_name', models.CharField(db_index=True, help_text='it needs to be one word unique. Ex. status, yesno', max_length=90, verbose_name='criteria name')),
('criteria_fix_mapping', jsonfield.fields.JSONField(blank=True, help_text='a JSON dictionary of key-value pairs that ... |
Hybrid-Cloud/Hybrid-Cloud-Patches-For-Tricircle | hybrid-cloud/neutron/plugins/openvswitch/common/config.py | Python | gpl-2.0 | 5,912 | 0.000507 | # Copyright 2012 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... | polling by monitoring ovsdb for interface "
"changes.")),
cfg.IntOpt('ovsdb_monitor_respawn_interval',
default=constants.DEFAULT_OVSDBMON_RESPAWN,
help=_("The number of seconds to wait before respawning the "
"ovsdb monitor after losing comm... |
cfg.ListOpt('tunnel_types', default=DEFAULT_TUNNEL_TYPES,
help=_("Network types supported by the agent "
"(gre and/or vxlan).")),
cfg.IntOpt('vxlan_udp_port', default=p_const.VXLAN_UDP_PORT,
help=_("The UDP port to use for VXLAN tunnels.")),
cfg.IntOpt(... |
congthuc/androguard-2.0-custom | database/DataUtils.py | Python | apache-2.0 | 4,034 | 0.008676 | #author CongThuc 12/13/2015
import MySQLdb
from database.DBHelper import DBHelper
from database.DBConnectManager import DBConnectManager
from resourcefactories.AnalysisInitDefaultValue import AnalysisInitDefaultValue
db_helper = DBHelper()
class DataUtils:
def __init__(self):
print "init DataUtils"
... | except Exception as e:
print e
return permissions
def get_Permissio | nFromXML(self, db_connector):
permissions = []
if db_connector is not None:
try:
query = "select * from permissions_from_xml"
permissions = db_helper.get_Data(db_connector, db_connector.cursor(), query);
except Exception as e:
print e
... |
miketheman/opencomparison | package/migrations/0015_auto__del_repo__del_field_package_repo.py | Python | mit | 10,959 | 0.008304 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting model 'Repo'
db.delete_table('package_repo')
# Deleting field 'Package.repo'
d... | ateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'package': ('django.d... | },
'package.package': {
'Meta': {'ordering': "['title']", 'object_name': 'Package'},
'category': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['package.Category']"}),
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datet... |
jennyb/amsDecode | processBinFiles.py | Python | gpl-2.0 | 451 | 0.046563 | #!/usr/bin/python
import os, subprocess
amsDecode = "/usr/local/bin/amsDecode"
| path = "/usr/local/bin"
specDataFile = "specData.csv"
f = open("processFile.log", "w")
if os.p | ath.exists(specDataFile):
os.remove(specDataFile)
for fileName in os.listdir('.'):
if fileName.endswith('.bin'):
#print 'file :' + fileName
cmnd = [amsDecode,
fileName,
"-t -95",
"-b",
"68",
"468" ]
subprocess.call(cmnd,stdout=f)
f.close
|
Taapat/enigma2-openpli-vuplus | lib/python/Components/Converter/PliExtraInfo.py | Python | gpl-2.0 | 12,757 | 0.031199 | # shamelessly copied from pliExpertInfo (Vali, Mirakels, Littlesat)
from enigma import iServiceInformation, iPlayableService
from Components.Converter.Converter import Converter
from Components.Element import cached
from Components.config import config
from Tools.Transponder import ConvertToHumanReadable, getChannelNu... | ))
else:
return str(int(frequency / 1000 + 0.5))
return ""
def createChannelNumber(self, fedata, feraw):
return "DVB-T" in feraw.get("tuner_type") and fedata.get("channel") or ""
def createSymbolRate(self, fedata, feraw):
if "DVB-T" in feraw.get("tu | ner_type"):
bandwidth = fedata.get("bandwidth")
if bandwidth:
return bandwidth
else:
symbolrate = fedata.get("symbol_rate")
if symbolrate:
return str(symbolrate / 1000)
return ""
def createPolarization(self, fedata):
return fedata.get("polarization_abbreviation") or ""
def createFEC(self, ... |
crate/crate-python | src/crate/client/sqlalchemy/tests/bulk_test.py | Python | apache-2.0 | 2,714 | 0 | # -*- coding: utf-8; -*-
#
# Licensed to CRATE Technology GmbH ("Crate") under one or more contributor
# license agreements. See the NOTICE file distributed with this w | ork for
# additional information regarding copyright | ownership. Crate licenses
# this file to you 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 writi... |
danfairs/django-lazysignup | lazysignup/utils.py | Python | bsd-3-clause | 570 | 0 | def is_lazy_user(user):
""" Return True if the passed user is a lazy user. """
# Anonymous users are not lazy.
if user.is_anonymous:
r | eturn False
# Check the user backend. If the lazy signup backend
# authenticated them, then the user is lazy.
backend = getattr(user, 'backend', None)
if backend == 'lazysignup.backends.LazySignupBackend':
return True
# Otherwise, we have to fall back to checking the database.
from laz... | |
strogo/djpcms | tests/regression/routes/tests.py | Python | bsd-3-clause | 741 | 0.026991 | from djpcms import test
from djpcms.core.exceptions import AlreadyRegistered
import djpcms
class TestSites(test.TestCase):
def testMake(self):
self.assertRaises(AlreadyRegistered,djpcms. | MakeSite,__file__)
site = djpcms.MakeSite(__file__, route = '/extra/')
self.assertEqual(site.route,'/extra/')
def testClenUrl(self):
p = self.makepage(bit = 'test')
self.assertEqual(p.url,'/test/')
res = self.get('/test', status = 302, response = True)
... | ion'],'http://testserver/test/')
res = self.get('/test////', status = 302, response = True)
self.assertEqual(res['location'],'http://testserver/test/')
|
laurent-george/weboob | modules/prixcarburants/pages.py | Python | agpl-3.0 | 2,744 | 0.001094 | # -*- coding: utf-8 -*-
# Copyright(C) 2012 Romain Bignon
#
# This file is part of weboob.
#
# weboob 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 License, or
# (at your opti... | #choix_carbu ul li'):
input = li.find('input')
label = li.find('label')
product = Product(input.attrib['value'])
product.name = unicode(label.text.strip())
if '&' in product.name:
# "E10 & SP95" produces a non-supported table.
| continue
yield product
class ComparisonResultsPage(Page):
def get_product_name(self):
th = self.document.getroot().cssselect('table#tab_resultat tr th')
if th and len(th) == 9:
return u'%s' % th[5].find('a').text
def iter_results(self, product=None):
pri... |
qbuat/rootpy | rootpy/memory/deletion.py | Python | gpl-3.0 | 3,682 | 0.000543 | # Copyright 2012 the rootpy developers
# distributed under the terms of the GNU General Public License
"""
This module supports monitoring TObject deletions.
.. warning::
This is not recommended for production
"""
from __future__ import absolute_import
from weakref import ref
import ctypes
from ctypes import CFUN... | eanuplog.show_stack()
# Add python to the include path
C.add_python_includepath()
C.register_code("""
#ifndef __CINT__
#include <Python.h>
#endif
#include <TObject.h>
#include <TPython.h>
class RootpyObjectCleanup : public TObject {
public:
typedef void (*CleanupCallba | ck)(PyObject*);
CleanupCallback _callback;
RootpyObjectCleanup(CleanupCallback callback) : _callback(callback) {}
virtual void RecursiveRemove(TObject* object) {
// When arriving here, object->ClassName() will _always_ be TObject
// since we're called by ~TObject, and v... |
zznn/futu-openAPI | app/mainapp.py | Python | apache-2.0 | 6,014 | 0.02758 | # -*- coding: utf-8 -*-
from flask import Flask, jsonify, request, abort, make_response
from futu_server_api import *
from db import save_update_token
from db import delete_tokens
from db import list_cards
import logging
import logging.config
import json
app = Flask(__name__)
logging.config.fileConfig('./conf/log.ini... | .getLogger()
def check_parameters(pjson):
if not pjson or not 'app_account' in pjson or not 'card' in pjson or not 'appid' in pjson:
no_db_logger.info('No Parameter')
abort(400)
cli = {'account':pjson['app_account'], 'card':pjson['card'], 'appid':pjson['appid']}
return client(cli['account'], cli['card'], cli['a... | turn 'FAIL ,REASON OF FAILURE:%s ,PARAMETER:%s' % (myjson['error_msg'], request.json)
@app.route('/')
def hello_world():
no_db_logger.info('server start#####')
return 'hello 22222222 world!'
@app.route('/api/v1/tradetoken', methods=['POST'])
def trade_token():
trade_pswd = request.json['trade_pswd']
account = r... |
LordSprit/Laser | main.py | Python | gpl-2.0 | 2,036 | 0.000983 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Modulos
import sys
import pygame
from pygame.locals import *
# Constantes
venx = 640
veny = 448
# Clases
class Pieza(pygame.sprite.Sprite): # 64x64 px tamaño
def __init__(self, tipo):
pygame.sprite.Sprite.__init__(self) |
if tipo == 0:
self.image = load_image("tablero.png", True)
elif tipo == 1:
self.image = load_image("laser.png", True)
elif tipo == 2:
self.image = load_image("diana.png", True)
elif tipo == 3:
self.image = load_image("diana_espejo.png", Tr... | self.image = load_image("espejo.png", True)
elif tipo == 5:
self.image = load_image("espejotraves.png", True)
elif tipo == 6:
self.image = load_image("tunel.png", True)
elif tipo == 7:
self.image = load_image("bloqueo.png", True)
elif tipo == 8... |
jeroanan/Nes2 | Tests/OpCodeTests/TestNopOpCode.py | Python | bsd-3-clause | 306 | 0.003268 | from Chip import OpCodeDefinitions
from Tests.OpCodeTests.OpCodeTestBase import OpCodeTestBase
cla | ss TestNopOpCode(OpCodeTestBase):
def test_nop_implied_command_calls_nop_method(self):
self.assert_opcode | _execution(OpCodeDefinitions.nop_implied_command, self.target.get_nop_command_executed)
|
lochiiconnectivity/boto | tests/integration/dynamodb2/test_cert_verification.py | Python | mit | 1,511 | 0 | # Copyright (c) 2012 Mitch Garnaat http://garnaat.org/
# Copyright (c) 2012 Amazon.com, Inc. or its affiliates.
# All rights reserved.
#
# 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 withou... | PURPOSE AND NONINFRINGEMENT. IN NO EV | ENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
"""
Check that all of the certs on all service endpoints validate.
"""
import uni... |
HiSPARC/sapphire | sapphire/tests/analysis/test_process_events.py | Python | gpl-3.0 | 15,851 | 0.002713 | import operator
import os
import shutil
import tempfile
import unittest
import warnings
import tables
from mock import Mock
from numpy import array
from numpy.testing import assert_array_equal
from sapphire.analysis import process_events
TEST_DATA_FILE = 'test_data/process_events.h5'
DATA_GROUP = '/s501'
class Pr... | ce, 200), 1)
self.assertEqual(self.proc._reconstruct_time_from_trace(trace, 210), -999)
class ProcessEventsWithTriggerOffsetTests(ProcessEv | entsTests):
def setUp(self):
warnings.filterwarnings('ignore')
self.data_path = self.create_tempfile_from_testdata()
self.data = tables.open_file(self.data_path, 'a')
self.proc = process_events.ProcessEventsWithTriggerOffset(self.data, DATA_GROUP, progress=False)
def test__recon... |
nassan/sefaria-embedded | constants.py | Python | gpl-3.0 | 1,909 | 0 | SEFARIA_API_NODE = "https://www.sefaria.org/api/texts/"
CACHE_MONITOR_LOOP_DELAY_IN_SECONDS = 86400
CACHE_LIFETIME_SECONDS = 604800
category_colors = {
"Commentary": "#4871bf",
"Tanakh": "#004e5f",
"Midrash": "#5d956f",
"Mishnah": "#5a99b7",
"Talmud": "#c... | "#c7a7b4",
"Other": "#073570",
"Quoti | ng Commentary": "#cb6158",
"Sheets": "#7c406f",
"Community": "#7c406f",
"Targum": "#7f85a9",
"Modern Works": "#7c406f",
"Modern Commentary": "#7c406f",
}
platform_settings = {
"twitter": {
"font_size": 29,
"additional_line_spacing_he": 5,
"a... |
darcyliu/storyboard | home/models.py | Python | mit | 2,582 | 0.013555 | #!/usr/bin/env python
# encoding: utf-8
"""
models.py
Created by Darcy Liu on 2012-03-03.
Copyright (c) 2012 Close To U. All rights reserved.
"""
from django.db import models
from django.contrib.auth.models import User
# class Setting(models.Model):
# sid = models.AutoField(primary_key=True)
# option = model... | els.AutoField(primary_key=True)
name = models.CharField(max_length=256,verbose_name='name')
slug = models.CharField(unique=True,max_length=128,verbose_name='slug')
meta = models.TextField(blank=True, verbose_name='meta')
description = models.TextField(blank=True, verbose_name='description')
author =... | dels.DateTimeField(auto_now=True,verbose_name='updated')
def __unicode__(self):
result = self.name
return unicode(result)
class Page(models.Model):
key = models.AutoField(primary_key=True)
name = models.CharField(max_length=256,verbose_name='name')
slug = models.CharField(max_le... |
compas-dev/compas | src/compas/datastructures/network/complementarity.py | Python | mit | 1,442 | 0.001387 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from itertools import combinations
__all__ = [
'network_complement'
]
def network_complement(network, cls=None):
"""Generate the complement network of a network.
The complement of a graph G is ... | not network.has_edge(u, v, directed=False)]
retur | n cls.from_nodes_and_edges(nodes, edges)
|
ee08b397/panda3d | direct/src/tkpanels/Inspector.py | Python | bsd-3-clause | 15,271 | 0.00681 | """Inspector | s allow you to visually browse through the members of
various python objects. To open an inspector, import this module, and
execute inspector.inspect(anObject) I start IDLE with this command
line: idle.py -c "from insp | ector import inspect"
so that I can just type: inspect(anObject) any time."""
__all__ = ['inspect', 'inspectorFor', 'Inspector', 'ModuleInspector', 'ClassInspector', 'InstanceInspector', 'FunctionInspector', 'InstanceMethodInspector', 'CodeInspector', 'ComplexInspector', 'DictionaryInspector', 'SequenceInspector', 'S... |
CAES-Python/CAES_Kivy_Garden | garden.light_indicator/example.py | Python | mit | 229 | 0.026201 | #example
from kivy.base import runTouchApp
from kivy.lang import Builder
fro | m kivy.garden.light_indicator impo | rt Light_indicator
from kivy.uix.button import Button
# LOAD KV UIX
runTouchApp(Builder.load_file('example.kv'))
|
brainiak/brainiak | brainiak/eventseg/event.py | Python | apache-2.0 | 26,617 | 0 | # Copyright 2020 Princeton University
#
# 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... | mean_pat[i, :, :] = X[i].dot(seg_prob[i])
mean_pat = np.mean(mean_pat, axis=0)
# Based on the current mean patterns, compute the event
# segmentation
self.ll_ = np.append(self.ll_, np.empty((1, n_train)), axis=0)
for i in range(n_train):
... | = self._forward_backward(logprob)
if step > 1 and self.split_merge:
curr_ll = np.mean(self.ll_[-1, :])
self.ll_[-1, :], log_gamma, mean_pat = \
self._split_merge(X, log_gamma, iteration_var, curr_ll)
# If log-likel |
JustinAzoff/splunk-scripts | bubble.py | Python | mit | 1,305 | 0.010728 | """bubble - re-emit a log record with superdomain
| bubble [field=host] [parts=3]
adds 'superhost' field
"""
import sys,splunk.Intersplunk
import re
ipregex = r"(?P<ip>((25[0-5]|2[0-4]\d|[01]\d\d|\d?\d)\.){3}(25[0-5]|2[0-4]\d|[01]\d\d|\d?\d))"
ip_rex = re.compile(ipregex)
def super_domain(host, output_parts)... | = int(options.get('parts', 2))
results,dummyresults,settings = splunk.Intersplunk.getOrganizedResults()
results = list(add_superhost(results, field, num_parts))
except:
import traceback
stack = traceback.format_exc()
result | s = splunk.Intersplunk.generateErrorResults("Error : Traceback: " + str(stack))
splunk.Intersplunk.outputResults( results )
|
moonfruit/yyfeed | lib/yyfeed/util/cache.py | Python | apache-2.0 | 1,274 | 0.000785 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
import cPickle as pickle
except ImportError:
import pickle
import os.path
class FileCache(dict):
def __init__(self, filename):
self.filename = os.path.abspath(filename)
try:
self.update(pickle.load(open(self.filename)))
... | def __getitem__(self, key):
return self.cache.get(key)
def __setitem__(self, key, value):
self.cache.set(key, value)
def get(self, key):
return self.cache.get(key)
def set(self, key, value):
self.cach | e.set(key, value)
|
prescott66/mypaint | gui/inktool.py | Python | gpl-2.0 | 28,795 | 0.000903 | # This file is part of MyPaint.
# Copyright (C) 2015 by Andrew Chadwick <a.t.chadwick@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your ... | fo = None # (button, zone)
self._current_override_cursor = None
# Button pressed while drawing
# Not every device sends button presses, but evde | v ones
# do, and this is used as a workaround for an evdev bug:
# https://github.com/mypaint/mypaint/issues/223
self._button_down = None
self._last_good_raw_pressure = 0.0
self._last_good_raw_xtilt = 0.0
self._last_good_raw_ytilt = 0.0
def _reset_nodes(self):
... |
cedriclaunay/gaffer | python/GafferUI/ApplicationMenu.py | Python | bsd-3-clause | 5,283 | 0.038236 | ##########################################################################
#
# Copyright (c) 2011-2012, John Haddon. All rights reserved.
# Copyright (c) 2011, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided ... | ABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE 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
#... | NCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
##########################################################################
import os
import weakref
import IECore
import Gaffer
import GafferUI
def appendDefinitions( menuD... |
Salamek/git-deploy | git_deploy/database.py | Python | gpl-3.0 | 3,246 | 0.021873 | from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
db = SQLAlchemy()
class BaseTable(db.Model):
__abstract__ = True
updated = db.Column(db.DateTime, default=func.now(), onupdate=func.current_timestamp())
created = db.Column(db.DateTime, default=func.... |
status = db.Column(db.Enum('ERROR', 'WARNING', 'OK', 'UNKNOWN', 'RUNNING', name='deploy_status_type'))
runtime = db.Column(db.Integer)
commit_id = db.Column(db.In | teger, db.ForeignKey('commit.id'))
log = relationship("Log", order_by="Log.id", backref="deploy")
class Log(BaseTable):
__tablename__ = 'log'
id = db.Column(db.Integer, primary_key=True)
data = db.Column(db.String(1024))
status = db.Column(db.Enum('ERROR', 'WARNING', 'OK', 'UNKNOWN', name='log_status_type'))... |
drbitboy/SpiceyPy | spiceypy/__init__.py | Python | mit | 1,313 | 0 | """
The MIT License (MIT)
Copyright (c) [2015-2018] [Andrew Annex]
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, modif... | N THE
SOFTWARE.
"""
from .spiceypy import *
from .utils import support_types
__author__ = 'AndrewAnnex'
# Default setting for error reporting so that programs don't just exit out!
erract("set", 10, "return")
errdev("s | et", 10, "null")
|
julienc91/ShFlickr | main.py | Python | mit | 6,714 | 0.004319 | #!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = "Julien Chaumont"
__copyright__ = "Copyright 2014, Julien Chaumont"
__licence__ = "MIT"
__version__ = "1.0.2"
__contact__ = "julienc91 [at] outlook.fr"
import flickrapi
import os, sys
import re
from config import *
class ShFlickr:
##
# Connexion to F... | is_family=VISIBLE_FAMILY,
is_friend=VISIBLE_FRIEND)
except KeyboardInterrupt:
print "Exit by user request"
return
except:
n... | print "5 failed uploads in a row, aborting."
return
else:
print "Error, retrying upload (%s/%s)" % (nb_errors, MAX_RETRIES)
else:
photo_id = response.find('photoid').text
... |
Ecotrust/PEW-EFH | mp/visualize/views.py | Python | apache-2.0 | 11,227 | 0.004186 | # Create your views here.
from django.contrib.auth.models import Group
from django.core.validators import URLValidator
from django.core.exceptions import ValidationError
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestConte... | template, RequestContext(request, context))
def show_mobile_map(request, project=None, template='mobile-map.html'):
try:
if project:
mp_settings = MarinePlannerSettings.objects.get(slug_name=project)
else:
mp_settings = MarinePlannerSettings.objects.get(active=True)
... | t_logo = mp_settings.project_logo
print project_name
print project_logo
# try:
# if project_logo:
# url_validator = URLValidator(verify_exists=False)
# url_validator(project_logo)
# except ValidationError, e:
# project_logo ... |
polyanskiy/refractiveindex.info-scripts | scripts/Rakic 1998 - Au (LD model).py | Python | gpl-3.0 | 2,100 | 0.028529 | # -*- coding: utf-8 -*-
# Author: Mikhail Polyanskiy
# Last modified: 2017-04-02
# Original data: Rakić et al. 1998, https://doi.org/10.1364/AO.37.005271
import numpy as np
import matplotlib.pyplot as plt
# Lorentz-Drude (LD) model parameters
ωp = 9.03 #eV
f0 = 0.760
Γ0 = 0.053 #eV
f1 = 0.024
Γ1 = 0.241 #eV
ω1 = 0.... |
ε += f3*ωp**2 / ((ω3**2-ω**2)-1j*ω*Γ3)
ε += f4*ωp**2 / ((ω4**2-ω**2)-1j*ω*Γ4)
ε += f5*ωp**2 / ((ω5**2-ω**2)-1j*ω*Γ5)
return ε
ev_min=0.2
ev_max=5
npoints=200
eV = np.logspace(np.log10(ev_min), np.log10(ev_max), npoints)
μm = 4.13566733e-1*2.99792458/eV
ε = LD(eV)
n = (ε**.5).real
k = (ε**.5).imag
#... | {:.4e} {:.4e} {:.4e}'.format(μm[i],n[i],k[i]))
file.close()
#=============================== PLOT =====================================
plt.rc('font', family='Arial', size='14')
plt.figure(1)
plt.plot(eV, -ε.real, label="-ε1")
plt.plot(eV, ε.imag, label="ε2")
plt.xlabel('Photon energy (eV)')
plt.ylabel(... |
andreaso/ansible | lib/ansible/modules/network/nxos/nxos_overlay_global.py | Python | gpl-3.0 | 8,884 | 0.0009 | #!/usr/bin/python
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your | option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTAB | ILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['pr... |
uglyDwarf/evdevshift | scafold2.py | Python | mit | 4,502 | 0.026877 | #!/usr/bin/env python3
#
import re
import evdev
import subprocess
import time
import argparse
def process_test_line(line, controls):
tmp = line.strip()
fields = tmp.split()
operation = fields[1].lower()
if operation == 'receive':
target = fields[2].lower()
if target == 'syn':
return (... | :
buttons.append(ctrl_id)
else:
axes.append((ctrl_id, evdev.AbsInfo(0, 255, 0, 15, 0, 0)))
# sort the arrays
axes.sort()
buttons.sort()
cap = {}
if axes:
cap[evdev.ecodes.EV_ABS] = axes;
if buttons:
cap[evd | ev.ecodes.EV_KEY] = buttons;
return cap
def find_device(name):
patt = re.compile(name)
devices = [evdev.InputDevice(fn) for fn in evdev.list_devices()]
for device in devices:
if patt.match(device.name):
return device
parser = argparse.ArgumentParser(description = 'Test evdevshift using sp... |
popen2/he_dns | update_he_dns.py | Python | mit | 4,258 | 0.005636 | #!/usr/bin/env python
import os
import re
import sys
import socket
import httplib
import urlparse
from urllib import urlencode
from urllib2 import urlopen
from argparse import ArgumentParser
from collections import OrderedDict
def _get_discover_url(given_discover_url, update_type):
if update_type == '4':
r... | ates,'
print >>sys.stderr, 'and that the password used is the update key (not your account password).'
raise SystemExit(5)
elif key == 'nochg':
print >>sys.stderr, 'no update required (IP is {})'.format(value)
elif key == 'no | ipv6':
print >>sys.stderr, 'cannot update ipv6 for this hostname'
elif key == 'good':
print >>sys.stderr, 'update complete: {}'.format(value)
def main():
parser = ArgumentParser()
parser.add_argument('hostname', help='The hostname (domain name) to be updated. Make sure this domain has been ... |
390910131/Misago | misago/threads/urls/privatethreads.py | Python | gpl-2.0 | 5,045 | 0.008523 | from django.conf.urls import patterns, include, url
from misago.threads.views.privatethreads import PrivateThreadsView
urlpatterns = patterns('',
url(r'^private-threads/$', PrivateThreadsView.as_view(), name='private_threads'),
url(r'^private-threads/(?P<page>\d+)/$', PrivateThreadsView.as_view(), name='priva... | d+)/hide/$', HidePostView.as_view(), name='hide_private_post'),
url(r'^private-post/(?P<post_id>\d+)/delete/$', DeletePostView.as_view(), name='delete_private_post'),
url(r'^private-post/(?P<post_id>\d+)/report/$', Repor | tPostView.as_view(), name='report_private_post'),
)
# events view
from misago.threads.views.privatethreads import EventsView
urlpatterns += patterns('',
url(r'^edit-private-event/(?P<event_id>\d+)/$', EventsView.as_view(), name='edit_private_event'),
)
# posting views
from misago.threads.views.privatethreads im... |
billvsme/videoSpider | webs/douban/tasks/down_celebrity_images.py | Python | mit | 1,702 | 0 | # -*- coding: utf-8 -*-
import ast
import os
import requests
import models
from config import config, sqla
from gevent.pool import Pool
from helpers import random_str, down
base_path = config.get('photo', 'path')
base_path = os.path.join(base_path, 'celebrity')
cookies = {
'bid': ''
}
def create_down(str_u... | ver_url = celebrity.thumbnail_cover
photos_url = celebrity.photos
thumbnail_photos_url = celebrity.thumbnail_photos
down(
cover_url,
cookies,
os.path.join(base_path, 'cover'),
str(douban_id)+'_'+cover_url.split('/')[-1].strip('?')
)
down(
thumbnail_cover_url,... | )
)
create_down(photos_url, douban_id, 'photos')
create_down(thumbnail_photos_url, douban_id, 'thumbnail_photos')
def task(douban_ids, pool_number):
pool = Pool(pool_number)
for douban_id in douban_ids:
pool.spawn(
create_requests_and_save_datas,
douban_id=douban_... |
rhefner1/ghidonations | gaesessions/__init__.py | Python | apache-2.0 | 21,922 | 0.002144 | """A fast, lightweight, and secure session WSGI middleware for use with GAE."""
import datetime
import hashlib
import hmac
import logging
import os
import pickle
import threading
import time
from Cookie import CookieError, SimpleCookie
from base64 import b64decode, b64encode
from google.appengine.api import memcache
f... | expiration()).strftime(COOKIE_DATE_FMT)
else:
ed = ''
cookies = [fmt % (i, cv[i * m:i * m + m], ed) for i in xrange(num_cookies)]
# expire old cookies which aren't needed anymore
old_cookies = xrange(num_cookies, len(self.cookie_k | eys))
key = COOKIE_NAME_PREFIX + '%02d'
cookies_to_ax = [EXPIRE_COOKIE_FMT % (key % i) for i in old_cookies]
return cookies + cookies_to_ax
def is_active(self):
"""Returns True if this session is active (i.e., it has been assigned a
session ID and will be or has been persist... |
Jonathanliu92251/watson-conversation | wechat/watson-wechat.py | Python | apache-2.0 | 1,140 | 0.032456 | import itchat, time, re
from itchat.content import *
import urllib2, urllib
import json
from watson_developer_cloud import ConversationV1
response={'context':{}}
@i | tchat.msg_register([TEXT])
def text_reply(msg):
global response
request_text = msg['Text'].encode('UTF-8')
conversation = ConversationV1(
username='9c359fba-0692-4afa-afb1-bd5bf4d7e367',
password='5Id2zfapBV6e',
version='2017-04-21')
# replace with your own worksp | ace_id
workspace_id = 'd3e50587-f36a-4bdf-bf3e-38c382e8d63a'
print "request ==>", request_text
try:
type(eval(response))
except:
print "first call"
response = conversation.message(workspace_id=workspace_id, message_input={
'text': request_text}, context=response['context'])
else:
print "continue... |
yamateh/robotframework | src/robot/running/arguments/argumentvalidator.py | Python | apache-2.0 | 2,829 | 0.000353 | # Copyright 2008-2013 Nokia Siemens Networks Oyj
#
# 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... | onals(named, spec)
if not spec.minargs <= count <= spec.maxargs:
self._ra | ise_wrong_count(count, spec)
def _named_positionals(self, named, spec):
if not spec.supports_named:
return 0
return sum(1 for n in named if n in spec.positional)
def _raise_wrong_count(self, count, spec):
minend = plural_or_not(spec.minargs)
if spec.minargs == spec.... |
karanjeets/CSCI-544 | Experimental/classifier/tweet_can_es.py | Python | apache-2.0 | 5,270 | 0.009298 | # -*- coding: utf-8 -*-
import nltk
import csv
import random
import codecs
import re
from nltk.corpus import stopwords
stopset = list(set(stopwords.words('spanish')))
hil_tweets = []
trump_tweets = []
bernie_tweets = []
cruz_tweets = []
classes = {}
def transform(temp):
if temp == "imo":
return "opinion"... | ces":
return "price"
elif temp == "say":
return "says"
elif temp == "shocked" or temp == "shocker" or temp == "shocking":
return "shock"
#elif temp == "sooooo" or temp == "soooo" or temp == "sooo" or temp == "soo":
# return "so"
return temp
def getPureWord(word):
#if ... | lower()
if str.startswith(temp,"http"):
return ""
temp = ''.join(e for e in temp if e.isalpha())
#if temp not in stop_words and temp !='':
if temp not in stopset and temp !='':
return transform(temp)
else:
return ""
def purifyText(input):
output = input.replace('\r','')... |
UManPychron/pychron | pychron/media_storage/ftp_storage.py | Python | apache-2.0 | 2,366 | 0.000423 | # ===============================================================================
# Copyright 2016 ross
#
# 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/LICE... | erver')
return
return ssh.open_sft | p()
def _close_client(self, client):
client.close()
def _put(self, client, src, dest):
client.put(src, dest)
# ============= EOF =============================================
|
pacoqueen/cican | utils/gmapcatcher/gmapcatcher/pyGPSD/nmea/serial/win32.py | Python | gpl-3.0 | 9,044 | 0.006634 | from ctypes import *
from ctypes.wintypes import HANDLE
from ctypes.wintypes import BOOL
from ctypes.wintypes import LPCWSTR
_stdcall_libraries = {}
_stdcall_libraries['kernel32'] = WinDLL('kernel32')
from ctypes.wintypes import DWORD
from ctypes.wintypes import WORD
from ctypes.wintypes import BYTE
INVALID_HANDLE_VAL... | rror
ClearCommError.restype = BOOL
ClearCommError.argtypes = [HANDLE, LP | DWORD, LPCOMSTAT]
SetupComm = _stdcall_libraries['kernel32'].SetupComm
SetupComm.restype = BOOL
SetupComm.argtypes = [HANDLE, DWORD, DWORD]
EscapeCommFunction = _stdcall_libraries['kernel32'].EscapeCommFunction
EscapeCommFunction.restype = BOOL
EscapeCommFunction.argtypes = [HANDLE, DWORD]
GetCommModemStatus = _stdc... |
pjdelport/django-analytical | analytical/tests/test_tag_gauges.py | Python | mit | 2,359 | 0 | """
Tests for the Gauges template tags and filters.
"""
from django.http import HttpRequest
from django.template import Context
from django.test.utils import override_settings
from analytical.templatetags.gauges import GaugesNode
from analytical.tests.utils import TagTestCase
from analytical.utils import AnalyticalEx... | uges-tracker';
t.setAttribute('data-site-id', '1234567890abcdef0123456789');
t.src = '//secure.gaug.es/track.js';
var s = document.getElementsByTagName('s | cript')[0];
s.parentNode.insertBefore(t, s);
})();
</script>
""", self.render_tag('gauges', 'gauges'))
def test_node(self):
self.assertEqual(
"""
<script type="text/javascript">
var _gauges = _gauges || [];
(function() {
var t = document.createEle... |
tosh1ki/pyogi | doc/sample_code/get_ki2_list.py | Python | mit | 741 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
def get_ki2_list(parser):
parser.add_argument('-p', '--path_2chkifu',
default='~/data/shogi/2chkifu/',
help='2chkifu.zipを展開したディレクトリ')
args = parser.parse_args()
path_2chkifu = args.path_2chkifu
s... | path_2chkifu, sub_dir))
ki2files = os.listdir(path_dir)
for ki2file in ki2files:
path_ki2_list.append(os.path.join(path_dir, ki2file))
| return sorted(path_ki2_list)
|
ridindirtyatl/truffle-api | routes.py | Python | agpl-3.0 | 261 | 0 | from flask import Blueprint, jsonify, request |
routes_api = Blueprint('ro | utes_api', __name__)
@routes_api.route('/v1/routes', methods=['GET'])
def routes_get():
'''
Get a list of routes
It is handler for GET /routes
'''
return jsonify()
|
ewandor/home-assistant | homeassistant/components/alarm_control_panel/manual.py | Python | apache-2.0 | 10,887 | 0 | """
Support for manual alarms.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/alarm_control_panel.manual/
"""
import copy
import datetime
import logging
import voluptuous as vol
import homeassistant.components.alarm_control_panel as alarm
import homeas... | now():
if self._disarm_after_trigger:
return STATE_ALARM_DISARMED
else:
self._state = self._previous_state
return self._state
if self._state in SUPPORTED_PENDING_STATES and \
self._within_pending_time(se... | ate == STATE_ALARM_PENDING:
return self._previous_state
else:
return self._state
def _pending_time(self, state):
pending_time = self._pending_time_by_state[state]
if state == STATE_ALARM_TRIGGERED:
pending_time += self._delay_time_by_state[self._previous_... |
3dfxsoftware/cbss-addons | lunch/__openerp__.py | Python | gpl-2.0 | 2,636 | 0.006084 | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2012 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the G... | t to save your employees' time and avoid them to always have coins in their pockets, this module is essential.
""",
'data': [
'security/lunch_security.xml',
'lunch_view.xml',
'wizard/lunch_order_view.xml',
'wizard/lunch_validation_view. | xml',
'wizard/lunch_cancel_view.xml',
'lunch_report.xml',
'report/report_lunch_order_view.xml',
'security/ir.model.access.csv',
'views/report_lunchorder.xml',
'views/lunch.xml',
],
'images': ['images/new_order.jpeg','images/lunch_account.jpeg','images/order_by_sup... |
toopy/django-mon-premier-projet | src/mon_premier_projet/apps/vcard/templatetags/vcard.py | Python | mit | 901 | 0.006659 | from django import forms, template
from django.core.cache import cache
from repertoire_telephonique.models import Phone
register = template.Library()
@register.simple_tag
def simple_add(a, b):
return a + b
@register.inclusion_tag('vcard/tags/form_phone.html')
def get_form_phone(contact_id):
# | get from cache
cache_key = 'phone_choices_%s' % con | tact_id
choices = cache.get(cache_key)
# not in cache generate choices
if not choices:
choices = [(_p.id, '%s %s' % (_p.prefix, _p.value))
for _p in Phone.objects.filter(contact_id=contact_id)]
# cache update
cache.set(cache_key, choices)
# dynam... |
martynovp/edx-platform | lms/djangoapps/courseware/tests/test_submitting_problems.py | Python | agpl-3.0 | 51,827 | 0.001777 | # -*- coding: utf-8 -*-
"""
Integration tests for submitting problem responses and getting grades.
"""
import json
import os
from textwrap import dedent
from django.conf import settings
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test.client import RequestFactor... | key
response_dict = {(answer_key_prefix + k): v for k, v in responses.items()}
resp = self.client.post(modx_url, response_dict)
retu | rn resp
def look_at_question(self, problem_url_name):
"""
Create state for a problem, but don't answer it
"""
location = self.problem_location(problem_url_name)
modx_url = self.modx_url(location, "problem_get")
resp = self.client.get(modx_url)
return resp
... |
chiehwen/logbook | logbook/testsuite/__init__.py | Python | bsd-3-clause | 2,534 | 0.001579 | # -*- coding: utf-8 -*-
"""
logbook.testsuite
~~~~~~~~~~~~~~~~~
The logbook testsuite.
:copyright: (c) 2010 by Armin Ronacher, Georg Brandl.
:license: BSD, see LICENSE for more details.
"""
import sys
import unittest
import logbook
_skipped_modules = []
_missing = object()
_func_ident = lambda f... | d_modules:
return _func_none
try:
__import__(name)
except ImportError:
_skipped_modules.append(name)
return _func_none
return _func_ident
def missing(name):
def decorate(f):
def wrapper(*args, **kwargs):
old = sys.modules.get(name, _missing)
... | del sys.modules[name]
else:
sys.modules[name] = old
return wrapper
return decorate
def suite():
loader = unittest.TestLoader()
suite = LogbookTestSuite()
suite.addTests(loader.loadTestsFromName('logbook.testsuite.test_regular'))
if sys.version... |
shafiquejamal/easyframes | easyframes/test/test_statamerge.py | Python | apache-2.0 | 4,184 | 0.032744 | import unittest
import pandas as pd
from pandas.util.testing import assert_series_equal
import numpy as np
from easyframes.easyframes import hhkit
class TestStataMerge(unittest.TestCase):
def setUp(self):
"""
df_original = pd.read_csv('sample_hh_dataset.csv')
df = df_original.copy()
print(df.to_dict())
... | 3: 1, 4: 1, 5: 2, 6: 1, 7: 2, 8: 5}
})
# @unittest.skip("demonstrating skipping")
def test_new_columns_added_merging_hh_level(self):
myhhkit = hhkit(self.df_master)
# myhhkit.from_dict(self.df_master)
myhhkit_using_hh = hhkit(self.df_using_hh)
# myhhkit_using_hh.from_dict(self.df_using_hh)
... | that the values are correct
correct_values = pd.Series([np.nan, np.nan, np.nan, 1, np.nan, np.nan, 0, 0, 0, 0, 1, 1, 0])
assert_series_equal(correct_values, myhhkit.df['has_fence'])
# @unittest.skip("demonstrating skipping")
def test_new_columns_added_merging_ind_level(self):
myhhkit = hhkit(self.df_master)... |
slashdd/sos | sos/cleaner/archives/insights.py | Python | gpl-2.0 | 1,284 | 0 | # Copyright 2021 Red Hat, Inc. Jake Hunsaker <jhunsake@redhat.com>
# This file is part of the sos project: https://github.com/sosreport/sos
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the | terms and conditions of
# version 2 of the GNU General Public License.
#
# See the LICENSE file in the source distribution for further information.
from sos.cleaner.archives import SoSObfuscationArchive
import tarfile
class InsightsArchive(SoSObfuscationArchive):
"""This class represents archives generated by ... | RHEL systems.
"""
type_name = 'insights'
description = 'insights-client archive'
prep_files = {
'hostname': 'data/insights_commands/hostname_-f',
'ip': 'data/insights_commands/ip_addr',
'mac': 'data/insights_commands/ip_addr'
}
@classmethod
def check_is_type(cls, a... |
project-asap/IReS-Platform | asap-tools/imr-code/imr_workflow_spark/operators/imr_tools.py | Python | apache-2.0 | 5,668 | 0.000706 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
tools for imr datasets
@author: Chris Mantas
@contact: the1pro@gmail.com
@since: Created on 2016-02-12
@todo: custom formats, break up big lines
@license: http://www.apache.org/licenses/LICENSE-2.0 Apache License
"""
from ast import literal_eval
from collections impor... | from_line(line):
"""
Given a text line it returns
a) o | nly the last element of the tuple if the line is a tuple.
That element we assume to be a list of features.
b) the line's elements if the line is not a tuple
:param line:
:return:
"""
from ast import literal_eval
entry = literal_eval(line)
return entry[-1] if isinstance(entry, tuple)... |
dougbeal/google-apis-client-generator | src/googleapis/codegen/utilities/json_expander.py | Python | apache-2.0 | 1,809 | 0.008292 | #!/usr/bin/python2.7
# Copyright 2012 Google Inc. All Rights Reserved.
"""Support for simple JSON templates.
A JSON template is a dictionary of JSON data in which string values
may be simple templates in string.Template format (i.e.,
$dollarSignEscaping). By default, the template is expanded against
its own data, op... | ditional context.
"""
imp | ort json
from string import Template
import sys
__author__ = 'smulloni@google.com (Jacob Smullyan)'
def ExpandJsonTemplate(json_data, extra_context=None, use_self=True):
"""Recursively template-expand a json dict against itself or other context.
The context for string expansion is the json dict itself by defaul... |
lptorres/noah-inasafe | web_api/third_party/raven/transport/exceptions.py | Python | gpl-3.0 | 498 | 0 | """
raven.transport.exceptions
~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010 by the Sentry Team, see AUTHORS for more d | etails.
:license: BSD, see LICENSE for more details.
"""
class InvalidScheme(ValueError):
"""
Raised when a transport is constructed using a URI which is not
handled by the transport
"""
class DuplicateScheme(StandardError):
"""
Raised when registering a handler for a particula... |
"""
|
wasit7/tutorials | arduino_python/02_python_serial/readUno.py | Python | mit | 669 | 0.019432 | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 07 13:58:49 2015
@author: Wasit
"""
import serial
import re
import datetime
#ser = serial.Serial('/dev/tty.usbserial', 9600)
#ser = serial.Serial('COM7', 9600)
#ser = serial.Serial(0) # open first serial port
ser=None
for i in xrange(10):
try:
ser = serial.Se... | +ser.name
endTime = datetime.datetime.now() + datetime.timedelta(seconds=5)
while True:
if datetime.datetime.now() >= endTime:
br | eak
record=re.split(',',ser.readline())
record = map(int, record)
print record
ser.close() |
cloudify-cosmo/cloudify-manager | rest-service/manager_rest/test/endpoints/test_execution_schedules.py | Python | apache-2.0 | 8,636 | 0 | from datetime import datetime, timedelta
from manager_rest.test.base_test import BaseServerTestCase
from cloudify_rest_client.exceptions import CloudifyClientError
class ExecutionSchedulesTestCase(BaseServerTestCase):
DEPLOYMENT_ID = 'deployment'
fmt = '%Y-%m-%dT%H:%M:%S.%fZ'
an_hour_from_now = \
... | elf.assertRaisesRegex(
CloudifyClientError,
recurrence_error,
self.client.execution_schedules.create,
'no-recurrence-no-count', self.deployment_id, ' | uninstall',
since=self.an_hour_from_now, weekdays=['su', 'mo', 'tu'],
)
self.client.execution_schedules.create(
'no-recurrence-count-1', self.deployment_id, 'install',
since=self.an_hour_from_now, count=1,
)
self.assertRaisesRegex(
Cloudify... |
bardes/sonitus | tools/tone_gen.py | Python | mit | 1,271 | 0.02203 | #!/usr/bin/env python
from sys import argv, stderr
usage = \
"""
Usage: {program} <sample rate> <A4 freq.> [octaves=8]
e.g.: {program} 64000 442.0 5
""".format(program=argv[0])
if len(argv) < 3 or len(argv) > 4 :
print(usage, file = stderr)
| exit(1)
A4 = 0
sample_rate = 0
octaves = 8
try:
A4 = float(argv[2])
except:
print("Error, invalid argument: Freq. must be a number!", file = stderr)
print(usage, file = stderr)
exit(1)
try:
sample_rate = int(argv[1])
except:
print("Error, invalid argume | nt: Sample rate must be an integer!", \
file = stderr)
print(usage, file = stderr)
exit(1)
if len(argv) == 4 :
try:
octaves = int(argv[3])
except:
print("Error, invalid argument: Octaves must be an integer!", \
file = stderr)
print(usage, file = stde... |
BirkbeckCTP/janeway | src/press/migrations/0002_auto_20170727_1504.py | Python | agpl-3.0 | 979 | 0.003064 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.13 on 2017-07-27 15:04
from __future__ import unicode_literals
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('press', '0001_initial'),
]
operations = [
mig... | alse, help_text='If set, passwords must include one number.'),
),
migrations.AddField(
model_name='press',
name='password_upper',
f | ield=models.BooleanField(default=False, help_text='If set, passwords must include one upper case.'),
),
]
|
Exanis/cannelloni | backend/filters/count_column.py | Python | mit | 662 | 0.003026 | # -*- coding: utf8 -*-
"CountColumn filter"
from .abstract import AbstractFilter
class CountColumn(AbstractFilter):
"Count a flux's column and put the result in a variable"
name = 'Compter colonnes'
description = "Compte le nombre de col | onnes d'un flux et met le résultat dans une variable"
node_in = ['cible']
parameters = [
{
'name': 'Variable',
'key': 'target',
'type': 'integer'
}
]
def run(self):
"Execute the filter"
target = self._model.config('target')
v... | lue)
|
BWallet/sx | src/obelisk/models.py | Python | agpl-3.0 | 3,035 | 0.003295 | import bitcoin
import struct
import serialize
class BlockHeader:
def __init__(self):
self.height = None
@classmethod
def deserialize(cls, raw):
assert len(raw) == 80
self = cls()
self.version = struct.unpack('<I', raw[:4])[0]
self.previous_block_hash = raw[4:36][::... | %s>' % (self.hash.encode("hex"),)
class OutPoint(object):
def __init__(self):
self.hash = None
self.index = None
def is_null(self):
return (len(self.hash) == 0) and (self.index == 0xffffffff)
def __repr__(self):
return "OutPoint(hash=%s, index=%i)" % (self.hash.encode("he... | erialize(self):
return serialize.ser_output_point(self)
@staticmethod
def deserialize(bytes):
return serialize.deser_output_point(bytes)
class TxOut(object):
def __init__(self):
self.value = None
self.script = ""
def __repr__(self):
return "TxOut(value=%i.%08i ... |
pmitche/it3105-aiprogramming | project1/common/constraintnet.py | Python | mit | 304 | 0.009868 | __author__ = 'sondredyvik | '
class ConstraintNet:
def __init__(self):
self.constraints = {}
def add_constraint(self,key,constraint):
if key in self.constraints:
self.constraints[key].append(constraint)
else:
self.constraints[ | key] = [constraint]
|
FreedomCoop/valuenetwork | valuenetwork/api/schemas/ProcessClassification.py | Python | agpl-3.0 | 887 | 0.002255 | #
# Graphene schema for exposing ProcessClassification model
#
import graphene
from valuenetwork.valueaccounting.models import ProcessType
from valuenetwork.api.types.Process import ProcessClassification
from valuenetwork.api.types.EconomicEvent import Action
from django.db.models import Q
class Query(object): #gra... | id=graphene.Int())
all_process_classifications = graphene.List(ProcessClassification)
def resolve_process_classification(self, args, *rargs):
id = args.get('id')
if id is not None:
pt = ProcessType.objects.get(pk=id)
if pt:
retur | n pt
return None
def resolve_all_process_classifications(self, args, context, info):
return ProcessType.objects.all()
|
FlaskGuys/Flask-Imagine | flask_imagine/adapters/filesystem.py | Python | mit | 4,244 | 0.001178 | """
This module implement a filesystem storage adapter.
"""
from __future__ import unicode_literals
import errno
import logging
import os
from flask import current_app
from .interface import ImagineAdapterInterface
from PIL import Image
LOGGER = logging.getLogger(__name__)
class ImagineFilesystemAdapter(ImagineAdapt... | d on path "%s" with error: %s' % (item_path, str(err)))
return False
else:
return False
def check_cached_item(self, p | ath):
"""
Check for cached resource item exists
:param path: str
:return: bool
"""
item_path = '%s/%s/%s' % (
current_app.static_folder,
self.cache_folder,
path.strip('/')
)
if os.path.isfile(item_path):... |
picoCTF/picoCTF-Platform-2 | api/api/app.py | Python | mit | 2,943 | 0.008155 | """
Flask routing
"""
from flask import Flask, request, session, send_from_directory, render_template
from werkzeug.contrib.fixers import ProxyFix
app = Flask(__name__, static_path="/")
app.wsgi_app = ProxyFix(app.wsgi_app)
import api
import json
import mimetypes
import os.path
from datetime import datetime
from ap... | .register_blueprint(api.routes.admin.blueprint, url_prefix="/api/admin")
app.register_blueprint(api.routes.group.blueprint, url_prefix="/api/group")
app.register_blueprint(api.routes.problem.blueprint, url_prefix="/api/problems")
| app.register_blueprint(api.routes.achievements.blueprint, url_prefix="/api/achievements")
api.logger.setup_logs({"verbose": 2})
return app
@app.after_request
def after_request(response):
response.headers.add('Access-Control-Allow-Methods', 'GET, POST')
response.headers.add('Access-Control-Allow-Creden... |
MIT-Model-Open-Data-and-Identity-System/SensibleData-Platform | sensible_data_platform/sensible_data_platform/settings.py | Python | mit | 6,429 | 0.004977 | # Django settings for sensible_data_platform project.
import os
import LOCAL_SETTINGS
from utils import SECURE_platform_config
DEBUG = True
TEMPLATE_DEBUG = DEBUG
MAINTENANCE_MODE = False
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
BASE_DIR = LOCAL_SETTINGS.BASE_DIR
ROOT_DIR = LOCA... | (
('da', 'Danish'),
('en', 'English'),
)
SITE_ID = 1
# If you set this to False, Django will make some optimizati | ons so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem ... |
SandStormHoldings/ScratchDocs | pg.py | Python | mit | 12,792 | 0.021029 | from __future__ import print_function
from builtins import object
import psycopg2
import psycopg2.extras
from gevent.lock import BoundedSemaphore as Semaphore
from gevent.local import local as gevent_local
from config import PG_DSN,DONESTATES
from gevent import sleep
# migration stuff
import json,re
from datetime impo... | cat)!=str:
cat = cat.strftime('%Y-%m-%dT%H:%I:%S')
if k not in rt: rt[k]={'created_at':cat}
#print('about to compare',type(rt[k]['created_at']),'with',type(cat))
if rt[k]['created_at']<=cat:
rt[k]['created_at'] | =cat
rt[k]['value']=v
return rt
def validate_save(C,tid,fetch_stamp,exc=True):
C.execute("select changed_at,changed_by from tasks where id=%s",(tid,))
res = C.fetchone()
if res and fetch_stamp and res['changed_at'] and res.get('changed_by')!='notify-trigger':
eq = res['changed_a... |
imk1/IMKTFBindingCode | makeSequenceInputsKMerMotifCounts.py | Python | mit | 12,089 | 0.020928 | import sys
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Alphabet import generic_dna
from Bio import SeqIO
import numpy
import math
import itertools as it
MATERNALFASTAFILENAMELISTFILENAME = sys.argv[1]
PATERNALFASTAFILENAMELISTFILENAME = sys.argv[2]
PEAKHEIGHTFILENAME = sys.argv[3]
... | CB = int(peakHeightLineElements[peakHeightColB]) - int(peakHeightLineElement | s[peakHeightColA])
for i in range(8):
# Record the fold change from individual B to individual A 8 times for the 8 examples
valueFile.write(str(FCB) + "\n")
def makeReverseComplements(seqRecordMaternalA, seqRecordPaternalA, seqRecordMaternalB, seqRecordPaternalB):
# Make the reverse complements of all of... |
moble/spherical_functions | spherical_functions/SWSH_grids/utilities.py | Python | mit | 2,746 | 0.006191 | # Copyright (c) 2020, Michael Boyle
# See LICENSE file for details: <https://github.com/moble/spherical_functions/blob/master/LICENSE>
### NOTE: The functions in this file are intended purely for inclusion in the Grid class. In
### particular, they assume that the first argument, `self` is an instance of Grid. They ... | "This is to ensure that scalars do not operate on individual "
"grid va | lues; they must operate on all simultaneously.\n"
"If that is the case and you still want to broadcast, add more "
"dimensions before this object's first dimension.")
try:
if reverse:
np.broadcast(array, self[..., 0, 0])
... |
nijel/weblate | weblate/metrics/apps.py | Python | gpl-3.0 | 906 | 0 | #
# Copyright © 2012–2022 Michal Čihař <michal@cihar.com>
#
# This file is part of Weblate <https://weblate.org/>
#
# 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 Foundat | ion, either version 3 of the Licen | se, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a ... |
RayleighChen/Improve | Project/python/PyLDA-Apriori/m3.py | Python | mit | 2,169 | 0.033195 | # -*- coding: utf-8 -*-
import sys
#Éú³ÉºòÑ¡¼¯C1
#return£º×Öµäkey=item;value=item³öÏֵĴÎÊý
def getC1(srcdata):
c1 = {}
for transaction in srcdata:
for item in transaction:
key = frozenset(set([item])) #frozenset²Å¿ÉÒÔ×÷Ϊ×ÖµäµÄkey
#¼ÆÊýitem
if key in c1:
... | == "__main__":
if len(sys.argv) == 3:
#Usage: apri.py filename surpport
items = Apriori(sys.argv[1], int(sys.argv[2]))
for key in [item for item in items if items[item] < int(sys.argv[2])]:
del items[key]
ap = {}
for itor in items:
#print items[ito... | ord in itor:
strword += word + " "
ap[strword.strip(' ')] = items[itor]
linelst = sorted(ap.items(), lambda x, y: cmp(x[1], y[1]), reverse=True)
for i in range(len(linelst)):
print "#" + str(linelst[i][1]) + " " + linelst[i][0]
#for (k, v) in ap.items():
... |
ringcentral/python-sdk | demo_sms.py | Python | mit | 609 | 0.00821 | #!/usr/bin/env python
# encoding: utf-8
import urllib
from config | import USERNAME, EXTENSION, PASSWORD, APP_KEY, APP_SECRET, SERVER, MOBILE
from ringcentral import SDK
def main():
sdk = SDK(APP_KEY, APP_SECRET, SERVER)
platform = sdk.platform()
platform.login(USERNAME, EXTENSION, PASSWORD)
to_numbers = | "1234567890"
params = {'from': {'phoneNumber': USERNAME},'to': [{'phoneNumber': to_number}],'text': "SMS message"}
response = platform.post('/restapi/v1.0/account/~/extension/~/sms', params)
print 'Sent SMS: ' + response.json().uri
if __name__ == '__main__':
main()
|
jemromerol/apasvo | apasvo/gui/views/loaddialog.py | Python | gpl-3.0 | 5,689 | 0.000879 | # encoding: utf-8
'''
@author: Jose Emilio Romero Lopez
@copyright: Copyright 2013-2014, Jose Emilio Romero Lopez.
@license: GPL
@contact: jemromerol@gmail.com
This file is part of APASVO.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Pu... | Visible(False)
self.groupBox_2.setVisible(True)
self.SampleFrequencySpinBox.setVisible(True)
self.SampleFrequencyLabel.setVisible(True)
else:
self.DataTypeComboBox.setVisible(False)
self.DataTypeLabel.setVisible(False)
self.ByteOrderComboBo... | f.ByteOrderLabel.setVisible(False)
self.groupBox_2.setVisible(False)
self.SampleFrequencySpinBox.setVisible(False)
self.SampleFrequencyLabel.setVisible(False)
self.groupBox.adjustSize()
self.adjustSize()
def load_preview(self):
"""Shows a preview of loade... |
mackorone/euler | src/025.py | Python | mit | 155 | 0.006452 | from fibonacci import Fibonacci
def ans():
return Fibonacci.index(Fibonacci.after(int('9' * 999))) |
if __name__ == '__main__':
pr | int(ans())
|
kdani3/searx | utils/fetch_currencies.py | Python | agpl-3.0 | 4,394 | 0.009558 | # -*- coding: utf-8 -*-
import json
import re
import unicodedata
import string
from urllib import urlencode |
from requests import get
languages = {'de', 'en', 'es', 'fr', 'hu', 'it', 'nl', 'jp'}
url_template = 'https://www.wikidata.org/w/api.php?action=wbgetentities&format=json&{query}&props=labels%7Cdatatype%7Cclaims%7Caliases&languages=' + '|'.join(languages)
url_wmflabs_template = 'http://wdq.wmflabs.org/api?q='
url_... | tle&{query}'
wmflabs_queries = [
'CLAIM[31:8142]', # all devise
]
db = {
'iso4217' : {
},
'names' : {
}
}
def remove_accents(data):
return unicodedata.normalize('NFKD', data).lower()
def normalize_name(name):
return re.sub(' +',' ', remove_accents(name.lower()).repla... |
timj/scons | test/Variables/ListVariable.py | Python | mit | 5,013 | 0.000798 | #!/usr/bin/env python
#
# __COPYRIGHT__
#
# 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, publish,
... | ])
expect = "shared = 'all'"+os.linesep+"listvariable = 'all'"+os.linesep
test.must_match(test.workpath('scons.variables'), expect)
| check(['all', '1', 'gl ical qt x11', 'gl ical qt x11',
"['gl ical qt x11']"])
test.run(arguments='shared=none')
check(['none', '0', '', '', "['']"])
test.run(arguments='shared=')
check(['none', '0', '', '', "['']"])
test.run(arguments='shared=x11,ical')
check(['ical,x11', '1', 'ical x11', 'ical x11',
"... |
mcansky/cabotapp | cabot/urls.py | Python | mit | 6,860 | 0.008017 | from django.conf.urls import patterns, include, url
from django.conf import settings
from cabot.cabotapp.views import (
run_status_check, graphite_api_data, checks_run_recently,
duplicate_icmp_check, duplicate_graphite_check, duplicate_http_check, duplicate_jenkins_check,
duplicate_instance, acknowledge_ale... | viceDeleteView,
UserProfileUpdateView, ShiftListView, subscriptions)
from cabot import rest_urls
from django.contrib import admin
from django.views.generic.base import RedirectView
from django.contrib.auth.views import login, logout, password_rese | t, password_reset_done, password_reset_confirm
admin.autodiscover()
from importlib import import_module
import logging
logger = logging.getLogger(__name__)
urlpatterns = patterns('',
url(r'^$', view=RedirectView.as_view(url='services/', permanent=False),
name='dashboard'),
url(r'^subscriptions... |
sosuke-k/cornel-movie-dialogs-corpus-storm | mdcorpus/tests/test_orm.py | Python | mit | 4,351 | 0.002758 | """Testing for ORM"""
from unittest import TestCase
import nose
from nose.tools import eq_
from sets import Set
from mdcorpus.orm import *
class ORMTestCase(TestCase):
def setUp(self):
self.store = Store(create_database("sqlite:"))
self.store.execute(MovieTitlesMetadata.CREATE_SQL)
self... |
movie.characters.add(bianca)
movie.characters.add(bruce)
movie.characters.add(cameron)
url.movie = movie
line_id_list = [194, 195, 196, 197]
for (i, line_id) in enumerate(line_id_list):
line = self.store.find(MovieLine, MovieLine.id == line_id).one()
... | conversation.lines.add(line)
self.store.commit()
def tearDown(self):
print "done"
class MovieTitlesMetadataTestCase(ORMTestCase):
@nose.with_setup(ORMTestCase.setUp, ORMTestCase.tearDown)
def test_url(self):
movie = self.store.find(MovieTitlesMetadata, MovieTitlesMetadata.id =... |
patricklaw/pants | src/python/pants/core/register.py | Python | apache-2.0 | 1,821 | 0.000549 | # Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
"""Core rules for Pants to operate correctly.
These are always activated and cannot be disabled.
"""
from pants.core.goals import check, fmt, lint, package, publish, repl, run, tailor, t... | FilesGeneratorTarget,
FileTarget,
GenericTarget,
RelocatedFiles,
ResourcesGeneratorTarget,
ResourceTarget,
)
from pants.core.target_types import rules as target_type_rules
from pants.core.util_rules import (
archive,
config_files,
distdir,
external_tool,
filter_empty_sources,
... | mport source_root
def rules():
return [
# goals
*check.rules(),
*fmt.rules(),
*lint.rules(),
*package.rules(),
*publish.rules(),
*repl.rules(),
*run.rules(),
*tailor.rules(),
*test.rules(),
# util_rules
*anonymous_tele... |
botswana-harvard/microbiome | microbiome/apps/mb_maternal/managers/maternal_arv_post_mod_manager.py | Python | gpl-2.0 | 736 | 0.002717 | from django.db import models
class MaternalArvPostModManager(models.Manager):
def get_by_natural_key(
self, arv_code, report_datetime, visit_instance, appt_status,
visit_definition_code, subject_identifier_as_pk):
MaternalVisit = models.get_model('mb_maternal', 'MaternalVisit')
... | ct_identifier_as_pk)
maternal_arv_post = MaternalArvPost.objects.get(maternal_visit= | maternal_visit)
return self.get(arv_code=arv_code, maternal_arv_post=maternal_arv_post)
|
alexryndin/ambari | ambari-server/src/main/resources/stacks/BigInsights/4.2/services/HIVE/package/scripts/hcat.py | Python | apache-2.0 | 2,284 | 0.011384 | #!/usr/bin/env python
"""
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");... | and
limitations under the License.
"""
from resource_management import *
import sys
from ambari_commons.os_family_impl import OsFamilyFuncImpl, OsFamilyImpl
from ambari_commons import OSConst
@OsFamilyFuncImpl(os_family=OSConst.WINSRV_FAMILY)
def hcat():
import params
XmlConfig("hive-site.xml",
con... | configurations = params.config['configurations']['hive-site'],
owner=params.hive_user,
configuration_attributes=params.config['configuration_attributes']['hive-site']
)
@OsFamilyFuncImpl(os_family=OsFamilyImpl.DEFAULT)
def hcat():
import params
Directory(params.hive_conf_dir,
... |
django-id/website | app_forum/tests/test_forms.py | Python | mit | 685 | 0.008759 | from django.test import TestCase
from app_forum.models import Forum, Comment
from app_forum. | forms import CommentForm, ThreadForm
# test for forms
class CommentFormTest(TestCase):
def test_comment_forms(self):
form_data = {
'comment_content' : 'comment'
}
form = CommentForm(data=for | m_data)
self.assertTrue(form.is_valid())
class ThreadFormTest(TestCase):
def test_thread_forms(self):
thread_data = {
'forum_title' : 'title',
'forum_category' : 'category',
'forum_content' : 'content'
}
thread = ThreadForm(data=thread_data)
... |
olivierverdier/homogint | homogint/homogint.py | Python | mit | 1,957 | 0.00511 | #!/usr/bin/env python
# coding: UTF-8
from __future__ import division
import numpy as np
def left_multiplication(g, x):
"""
Multiplication action of a group and a vector.
"""
return np.dot(g, x)
def trans_adjoint(g, x):
return np.dot(np.dot(g,x),g.T)
class RungeKutta(object):
def __init__(... | def compute_vectors(self, movement_field, stages):
""" |
Compute the Lie algebra elements for the stages.
"""
return np.array([movement_field(stage) for stage in stages])
def get_iterate(self, movement_field, action):
def evol(stages):
new_stages = stages.copy()
for (i,j, transition) in self.method.edges:
... |
taejoonlab/taejoonlab-toolbox | PopGen/phy2bmp.py | Python | gpl-3.0 | 248 | 0.008065 | from ete3 import Tree,TreeStyle,TextFace
t = Tree('tagfrog.phy')
for node in t.traverse():
node.img_style['size'] = 3
if node.is_leaf(): |
name_face = TextFace(node.name)
ts = TreeStyle()
ts.show_scale = True
t.render('tag | frog.pdf')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.