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 |
|---|---|---|---|---|---|---|---|---|
choderalab/FAHMunge | fahmunge/_version.py | Python | lgpl-2.1 | 18,449 | 0 |
# This file helps to compute a version number in source trees obtained from
# git-archive tarball (such as those provided by githubs download-from-tag
# feature). Distribution tarballs (built by setup.py sdist) and build
# directories (produced by setup.py build) will contain a much shorter file
# that just contains t... | tdirs = []
for i in range(3):
dirname = os.path.basename(root)
if dirname.startswith(parentdir_prefix):
return {"version": dirname[len(parentdir_prefix):],
"full-revisionid": None,
| "dirty": False, "error": None, "date": None}
else:
rootdirs.append(root)
root = os.path.dirname(root) # up a level
if verbose:
print("Tried directories %s but none started with prefix %s" %
(str(rootdirs), parentdir_prefix))
raise NotThisMethod("rootdir d... |
tfXYZ/tfXYZ | apps/classification.py | Python | gpl-3.0 | 4,593 | 0.014805 | # Import from standard libraries
from __future__ import division, absolute_import, print_function
import tensorflow as tf, importlib
from six import iteritems
# Import from our libraries
import core.losses
from core.common import Channel, get_debug_session
from core.evaluation import basic_stats_numpy, classification_... | ) == 1 else '{}_'.format(l)
ret.update({'{}UAR'.format(name_prefix): uar,
'{}acc'.format(name_prefix): acc,
'{}conf_mat'.format(name_prefix): conf_mat,
'{}auprc'. | format(name_prefix): auprc,
'{}acc@3'.format(name_prefix): acc_at_3,
'{}acc@5'.format(name_prefix): acc_at_5})
return ret
def top_layers(self, is_train, global_endpoints, module_endpoints):
inputs = module_endpoints['bottleneck']
# The top layers
for l, n in zip... |
irl/gajim | src/gajim-remote.py | Python | gpl-3.0 | 26,570 | 0.005608 | # -*- coding:utf-8 -*-
## src/gajim-remote.py
##
## Copyright (C) 2005-2006 Dimitur Kirov <dkirov AT gmail.com>
## Nikos Kouremenos <kourem AT gmail.com>
## Copyright (C) 2005-2014 Yann Leboulanger <asterix AT lagaule.org>
## Copyright (C) 2006 Junglecow <junglecow AT gmail.com>
## ... | , _('priority you want to give to the account'),
| True),
(Q_('?CLI:account'), _('change the priority of the given account. '
'If not specified, change status of all accounts that have'
' "sync with globa... |
apache/cloudstack-ec2stack | tests/utils.py | Python | apache-2.0 | 2,163 | 0 | #!/usr/bin/env python
# encoding: utf-8
#
# 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 Licens... | Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless | required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
c... |
archivsozialebewegungen/AlexandriaBase | tests/servicestests/test_database_upgrade_service.py | Python | gpl-3.0 | 1,154 | 0.006066 | '''
Created on 28.06.2016
@author: michael
'''
import unittest
from alexandriabase.services import DatabaseUpgradeService
from daotests.test_base import DatabaseBaseTest
from alexandriabase.daos import RegistryDao
class DatabaseUpgradeServiceTest(Da | tabaseBaseTest):
def setUp(self):
super().setUp()
self.upgrade_service = DatabaseUpgradeService(self.engine)
def tearDown(self):
super().tearDown()
def test | Upgrade(self):
self.assertTrue(self.upgrade_service.is_update_necessary())
self.upgrade_service.run_update()
self.assertFalse(self.upgrade_service.is_update_necessary())
def testFailingUpgrade(self):
registry_dao = RegistryDao(self.engine)
registry_dao.set('version', 'not_ex... |
treeform/pystorm | examples/helloworld.py | Python | mit | 147 | 0.006803 | # helloworld.py
#
# familiar test program, demonst | rating py2js conversion
def helloworld(suffix):
print "hello world"+suffix
helloworld("!")
| |
OpenDroneMap/WebODM | app/tests/test_app.py | Python | agpl-3.0 | 9,412 | 0.001381 | from django.contrib.auth.models import User, Group
from django.test import Client
from rest_framework import status
from app.models import Project, Task
from app.models import Setting
from app.models import Theme
from webodm import settings
from .classes import BootTestCase
from django.core.exceptions import Validatio... | {}/json/'.format(task.id))
self.assertTrue(res.status_code == expectedStatus)
test_public_views(c, status.HTTP_404_NOT_FOUND)
# Share task
task.public = True
task.save()
# Can now access URLs even as anonymous user
ac = Client()
test_public_views(ac... | tatus.HTTP_200_OK)
def test_admin_views(self):
c = Client()
c.login(username='testsuperuser', password='test1234')
settingId = Setting.objects.all()[0].id # During tests, sometimes this is != 1
themeId = Theme.objects.all()[0].id # During tests, sometimes this is != 1
# Ca... |
endlessm/chromium-browser | third_party/catapult/dashboard/dashboard/edit_bug_labels_test.py | Python | bsd-3-clause | 2,381 | 0.00168 | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import unittest
import webapp2
import webtest
... | ommon import testing_common
from dashboard.common import xsrf
from dashboard.models import bug_label_patterns
class EditBugLabelsTest(testing_common.TestCase):
def setUp(self):
super(EditBugLabelsTest, self).setUp()
app = webapp2.WSGIApplication(
| [('/edit_bug_labels', edit_bug_labels.EditBugLabelsHandler)])
self.testapp = webtest.TestApp(app)
# Set the current user to be an admin.
self.SetCurrentUser('[email protected]', is_admin=True)
def tearDown(self):
super(EditBugLabelsTest, self).tearDown()
self.UnsetCurrentUser()
def testBugLabe... |
tobiz/OGN-Flight-Logger_V3 | flogger3.py | Python | gpl-3.0 | 77,519 | 0.010359 | #
# FLOGGER
#
# This program reads records from the OGN network processing only
# those received from a specified site and registration marks, eg aircraft belonging to
# a specific club.
# It writes each record to a database and at the end of each day process
# them to determine the flight times of each flight for eac... | 2) Started developing using Eclipse Neon.2 (4.6.2)
#
import socket
#from libfap import *
#import flogger_settings
import string
import date | time
import time
import sqlite3
import pytz
from datetime import timedelta
import sys
from flarm_db import flarmdb
from pysqlite2 import dbapi2 as sqlite
from open_db import opendb
import ephem
#from flogger_process_log_old import process_log
#from flogger_process_log import process_log
import argparse
from flogger_du... |
JonathonReinhart/killerbee | killerbee/kbutils.py | Python | bsd-3-clause | 22,117 | 0.011439 | # Import USB support depending on version of pyUSB
try:
import usb.core
import usb.util
#import usb.backend.libusb01
#backend = usb.backend.libusb01.get_backend()
USBVER=1
except ImportError:
import usb
#print("Warning: You are using pyUSB 0.x, future deprecation planned.")
USBVER=0
imp... | _channel(self, channel):
'''
Based on sniffer capabilities, return if t | his is an OK channel number.
@rtype: Boolean
'''
if (channel >= 11 or channel <= 26) and self.check(self.FREQ_2400):
return True
elif (channel >= 1 or channel <= 10) and self.check(self.FREQ_900):
return True
return False
class findFromList(object):
'... |
JetStarBlues/Nand-2-Tetris | PlayArea/parallel/_99__parallelHelpers.py | Python | mit | 1,142 | 0.049037 | '''
As shown in this tutorial by Sentdex,
www.youtube.com/watch?v=NwH0HvMI4EA
And
https://pymotw.com/3/queue/
'''
import threading
from queue import Queue
class execInParallel():
def run( self, nThreads, fx, args ):
self.q = Queue()
self.action = fx
self.createJobs( args )
self.createThreads( nThr... |
t.start()
def createJobs( self, jobs ):
for job in jobs:
self.q.put( job )
# --------------------------------------------------------
# Example...
'''
s = list( "hello_ryden" )
def printChar | ( c ): print( c )
def printChar2( c ): print( c * 3 )
e = execInParallel()
e.run( 2, printChar, s )
e.run( 5, printChar2, s )
''' |
shadowoneau/skylines | skylines/commands/users/merge.py | Python | agpl-3.0 | 1,896 | 0.002637 | from flask_script import Command, Option
import sys
from skylines.database import db
from skylines.model import User, Club, IGCFile, Flight, TrackingFix
class Merge(Command):
""" Merge two user accounts """
option_list = (
Option('new_id', type=int, help='ID of the new user account'),
Optio... | ot old:
print >>sys.stderr, "No such user: %d" % old_id
if old.club != new.club:
print >>sys.stderr, "Different club;", old.club, new.club
sys.exit(1)
db.session.query(C | lub).filter_by(owner_id=old_id).update({'owner_id': new_id})
db.session.query(IGCFile).filter_by(owner_id=old_id).update({'owner_id': new_id})
db.session.query(Flight).filter_by(pilot_id=old_id).update({'pilot_id': new_id})
db.session.query(Flight).filter_by(co_pilot_id=old_id).update({'co_pilot... |
Nonse/monkeys | tests/test_models.py | Python | mit | 6,811 | 0 | import random
from monkeygod import models
def test_avatar(session):
"""Gravatar URL should be generated"""
m1 = models.Monkey(
name='monkey1',
age=10,
email='[email protected]'
)
session.add(m1)
session.commit()
avatar = m1.avatar(128)
expected = (
'http:... | fully'
assert m2.best_friend is None, 'Removing best friend succeeds'
assert m1.delete_friend(m2) is True, 'Can delete friend who is also best'
session.add_all([m1, m2, m3])
session.commit()
assert m1.best_friend is None, 'Deleting fro | m friends also clears best'
def test_friends_without_best(session):
m1 = models.Monkey(
name='monkey1',
age=10,
email='[email protected]'
)
m2 = models.Monkey(
name='monkey2',
age=20,
email='[email protected]'
)
m3 = models.Monkey(
name='... |
mattvonrocketstein/smash | smashlib/ipy3x/kernel/channelsabc.py | Python | mit | 2,319 | 0.000431 | """Abstract base classes for kernel client channels"""
# Copyright (c) IPython Development Team. |
# Distributed under the terms of the Modified BSD License.
import abc
from IPython.utils.py3compat import with_metaclass
class ChannelABC(with_metaclass(abc.ABCMeta, object)):
"""A base class for all channel ABCs."""
@abc.abstractmethod
def start(sel | f):
pass
@abc.abstractmethod
def stop(self):
pass
@abc.abstractmethod
def is_alive(self):
pass
class ShellChannelABC(ChannelABC):
"""ShellChannel ABC.
The docstrings for this class can be found in the base implementation:
`IPython.kernel.channels.ShellChannel`
... |
aziflaj/numberoid | src/matrix/pymatrix.py | Python | mit | 5,173 | 0.000773 | import math
import copy
def print_matrix(matrix):
"""
This function prettyprints a matrix
:param matrix: The matrix to prettyprint
"""
for i in range(len(matrix)):
print(matrix[i])
def transpose(matrix):
"""
This function transposes a matrix
:param matrix: The matrix to trans... | ][0] * const[1][0]) / (-coef[0][0] * coef[1][1] + coef[1][0] * coef[0][1])
x = (const[1][0] - coef[1][1] * y) / coef[1][0]
return [x, y | ]
return multiply(inverse(coef), const)
|
Tomsod/gemrb | gemrb/GUIScripts/pst/NewLife.py | Python | gpl-2.0 | 10,818 | 0.040858 | # -*-python-*-
# GemRB - Infinity Engine Emulator
# Copyright (C) 2003 The GemRB Project
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) ... | Wis, Dex, Con, Cha ]
# stat label controls
for i in range(len(Stats)):
StatLabels[i] = NewLifeWindow.GetControl(0x10000018 + i)
# individual stat buttons
for i in range(len(Stats)):
Button = NewLifeWindow.GetControl (i+2)
Button.SetFlags (IE_GUI_BUTTON_NO_IMAGE, OP_SET)
Button.SetEvent (IE_GUI_MOUSE_OVER... | (8)
Button.SetFlags(IE_GUI_BUTTON_RADIOBUTTON, OP_SET)
Button.SetState(IE_GUI_BUTTON_LOCKED)
Button.SetSprites("", 0, 0, 0, 0, 0)
Button.SetText(5025)
Button.SetEvent(IE_GUI_MOUSE_OVER_BUTTON, AcPress)
Button = NewLifeWindow.GetControl(9)
Button.SetFlags(IE_GUI_BUTTON_RADIOBUTTON, OP_SET)
Button.SetState(IE_GU... |
dssg/cincinnati2015-public | evaluation/webapp/views.py | Python | mit | 3,341 | 0.006286 | from io import BytesIO
from itertools import groupby
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from flask import make_response, render_template, abort
from webapp import app
from webapp.evaluation import *
from ... | importances = get_feature_importances(timestamp)
importance_fig = plot_feature_importances(features, importances)
return serve_matplotlib_fig(importance_fig)
@app.route("/<timestamp>/precision-recall")
def precision_recall(timestamp):
test_labels, test_predictions = get_labels_predictions(timestamp)
... | precision-cutoff")
def precision_cutoff(timestamp):
test_labels, test_predictions = get_labels_predictions(timestamp)
prec_cutoff_fig = plot_precision_cutoff(test_labels, test_predictions)
return serve_matplotlib_fig(prec_cutoff_fig)
@app.route("/<timestamp>/ROC")
def ROC(timestamp):
test_labels, test_... |
TinghuiWang/pyActLearn | docs/conf.py | Python | bsd-3-clause | 10,278 | 0.00574 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# pyActLearn documentation build configuration file, created by
# sphinx-quickstart on Mon Nov 14 10:34:33 2016.
#
# 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
#... | get('READTHEDOCS', None) == 'True'
if not on_rtd: # only import and set the theme if we're building docs locally
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
h | tml_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this direct... |
thenenadx/forseti-security | google/cloud/security/common/data_access/group_dao.py | Python | apache-2.0 | 3,871 | 0.000517 | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | """
all_members = []
queue = Queue()
group_id = self.get_group_id('group', group_email, timestamp)
queue.put(group_id)
while not queue.empty():
group_id = queue.get()
members = self.get_group_members('group_members', group_id,
| timestamp)
for member in members:
all_members.append(member)
if member.get('member_type') == 'GROUP':
queue.put(member.get('member_id'))
return all_members
|
bhanu-mnit/EvoML | evoml/subsampling/test_auto_segmentEG_FEGT.py | Python | gpl-3.0 | 1,004 | 0.022908 | import pandas as pd
from sklearn.datasets import load_boston
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
from sklearn.cross_validation import train_test_split
from sklearn.metrics import mean_squared_error
from .auto_segment_FEGT import BasicSegmenter_FEGT
... | == None:
boston = load_boston()
X = pd.DataFrame(boston.data)
y = pd.DataFrame(boston.target)
base_estimator = DecisionTreeRegressor(max_depth = 5)
X_train, X_test, y_tr | ain, y_test = train_test_split(X, y, test_size=test_size)
print X_train.shape
clf = BasicSegmenter_FEGT(ngen=30, init_sample_percentage = 1, n_votes=10, n = 10, base_estimator = base_estimator)
clf.fit(X_train, y_train)
print clf.score(X_test,y_test)
y = clf.predict(X_test)
print... |
lewislone/mStocks | packets-analysis/lib/XlsxWriter-0.7.3/examples/chart_scatter.py | Python | mit | 5,416 | 0.000923 | #######################################################################
#
# An example of creating Excel Scatter charts with Python and XlsxWriter.
#
# Copyright 2013-2015, John McNamara, [email protected]
#
import xlsxwriter
workbook = xlsxwriter.Workbook('chart_scatter.xlsx')
worksheet = workbook.add_worksheet()
bo... | 2.add_series({
'name': '=Sheet1!$B$1',
'categories': '=Sheet1!$A$2:$A$7',
'values': '=She | et1!$B$2:$B$7',
})
# Configure second series.
chart2.add_series({
'name': '=Sheet1!$C$1',
'categories': '=Sheet1!$A$2:$A$7',
'values': '=Sheet1!$C$2:$C$7',
})
# Add a chart title and some axis labels.
chart2.set_title ({'name': 'Straight line with markers'})
chart2.set_x_axis({'name': 'Test numb... |
miti0/mosquito | strategies/ai/scikitbase.py | Python | gpl-3.0 | 1,418 | 0.002116 | from abc import ABC
import configargparse
from sklearn.externals import joblib
from termcolor import colored
class ScikitBase(ABC):
"""
Base class for AI strategies
"""
arg_parser = configargparse.get_argument_parser()
arg_parser.add('-p', '--pipeline', help='trained model/pipeline (*.pkl file)', ... | e(args.pipeline)
if args.feature_names:
self.feature_names = self.load_pipeline(args.feature_names)
@staticmethod
def load_pipeline(pipeline_file):
"""
Loads scikit model/pipeline
"""
print(colored('Loading pipeline: ' + pipeline_file, 'green'))
retur... | file)
def fetch_pipeline_from_server(self):
"""
Method fetches pipeline from server/cloud
"""
# TODO
pass
def predict(self, df):
"""
Returns predictions based on the model/pipeline
"""
try:
return self.pipeline.predict(df)
... |
c3cashdesk/c6sh | src/postix/core/migrations/0005_auto_20160207_1138.py | Python | agpl-3.0 | 485 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-02-07 10:38
from __future__ import unicode | _literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0004_warningconstraint'),
]
operations = [
migrations.AlterField(
model_name='preorderposition',
name | ='secret',
field=models.CharField(db_index=True, max_length=254, unique=True),
),
]
|
wfg2af/cs3240-labdemo | MessagePassing.py | Python | mit | 2,813 | 0.01102 | __author__ = 'wfg2af'
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA256
from Crypto import Random
class userMessages:
#Each user will have the public key of any other user.
UserMap = {}
UserName = ""
def __init__(self, UserName = "", UserMap = {}, key = None):
self.UserMap = UserM... | ere and user 2 would be able to receive message at any time.
print("User1 sent: " + user_2.receive_message(sent))
elif prompt == "User2":
prompt = input("What message do you want to s | end?: ")
sent = user_2.send_message(prompt, "User1")
print("User2 sent: " + user_1.receive_message(sent))
else:
print("doing invalid signature test")
k3 = RSA.generate(1024, Random.new().read)
print("The message being sent to user1 is: hi")
... |
lechat/CouchPotato | app/lib/provider/movie/sources/theMovieDb.py | Python | gpl-3.0 | 5,746 | 0.006091 | from app.config.cplog import CPLog
from app.lib.provider.movie.base import movieBase
from imdb import IMDb
from urllib import quote_plus
from urllib2 import URLError
import cherrypy
import os
import urllib2
log = CPLog(__name__)
class theMovieDb(movieBase):
"""Api for theMovieDb"""
apiUrl = 'http://api.themo... | s')
if not os.path.isdir(imageCache):
os.mkdir(imageCache)
# Return old
imageFile = os.path.join(imageCache, destination)
if not os.path.isfile(imageFile):
try:
data = urllib2.urlopen(url, timeout = 10)
# Write file
... | % url)
return False
return 'cache/images/' + destination
def fillFeedItem(self, id, name, imdb, year):
item = self.feedItem()
item.id = id
item.name = self.toSaveString(name)
item.imdb = imdb
item.year = year
return item
def isDisabled... |
SlideAtlas/SlideAtlas-Server | slideatlas/__init__.py | Python | apache-2.0 | 74 | 0 | # coding= | utf-8
from slideatlas.core import create_app, create_celery_ap | p
|
keishi/chromium | ui/resources/resource_check/resource_scale_factors.py | Python | bsd-3-clause | 3,857 | 0.006222 | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Presubmit script for Chromium browser resources.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about t... | """Verifies the scale factors of resources being added or modified.
Returns:
An array of presubmit errors if any images were detected not
having the correct dimensions.
"""
def ImageSize(filename):
with open(filename, 'rb', buffering=0) as f:
data = f.read(24)
assert ... | NG\r\n\x1A\n' and data[12:16] == 'IHDR'
return struct.unpack('>ii', data[16:24])
# TODO(flackr): This should allow some flexibility for non-integer scale
# factors such as allowing any size between the floor and ceiling of
# base * scale.
def ExpectedSize(base_width, base_height, scale):
re... |
seraphln/chat2all | chat2all/sso/weibo/api.py | Python | gpl-2.0 | 3,381 | 0.001775 |
#!/usr/bin/env python
# coding=utf8
#
"""
Python SDK for Weibo
Simple wrapper for weibo oauth2
author: [email protected]
"""
import time
from utils.http import request
from utils.http import SDataDict
from utils.http import encode_params
from utils.const import WEIBO_DOMAIN
from utils.const import WEIBO_VERSION... | edirect_uri
if not redirect:
raise WeiboAPIError('21305', 'Parameter absent: redirect_uri', 'OAuth2 request')
kwargs = dict(client_id=self.client_i | d,
response_type='code',
display=display,
redirect_uri=redirect)
encoded_params, _ = encode_params('GET', **kwargs)
print encoded_params
return '%s%s?%s' % (self.auth_url, 'authorize', encoded_params)
def request_access_token... |
henare/parlparse | pyscraper/gettwittermps.py | Python | agpl-3.0 | 1,744 | 0.008601 | #!/usr/bin/python
import urllib2
import csv
import xml.sax
uri = "http://spreadsheets.google.com/tq?tqx=out:csv&key=0AjWA_TWMI4t_dFI5MWRWZkRWbFJ6MVhHQzVmVndrZnc&hl=en_GB"
f = urllib2.urlopen(uri)
csv_data = f.read()
lines = csv_data.split("\n")
rows = csv.reader(lines.__iter__(), delimiter=',', quotechar='"')
class... | ']] = self.current_person_id
def endElement(self,n | ame):
if name == 'person':
self.current_person_id = None
people_parser = PeopleParser()
people_parser.parse("../members/people.xml")
person_id_to_twitter_username = {}
output_filename = "../members/twitter-commons.xml"
fp = open(output_filename,"w")
fp.write('''<?xml version="1.0" encoding="ISO-8... |
batermj/algorithm-challenger | code-analysis/programming_anguage/python/source_codes/Python3.5.9/Python-3.5.9/Lib/test/test_email/test__header_value_parser.py | Python | apache-2.0 | 117,222 | 0.00564 | import string
import unittest
from | email import _header_value_parser as parser
from email import errors
from email i | mport policy
from test.test_email import TestEmailBase, parameterize
class TestTokens(TestEmailBase):
# EWWhiteSpaceTerminal
def test_EWWhiteSpaceTerminal(self):
x = parser.EWWhiteSpaceTerminal(' \t', 'fws')
self.assertEqual(x, ' \t')
self.assertEqual(str(x), '')
self.assertEq... |
rdeits/cryptics | pycryptics/crypticweb/server.py | Python | mit | 2,649 | 0.002643 | import web
from pycryptics.solve_clue import CrypticClueSolver, split_clue_text
import webbrowser
import re
# from fake_solve_clue import FakeCrypticClueSolver as CrypticClueSolver
# from fake_solve_clue import split_clue_text
SERVER = "http://localhost:8080/solve/"
class index:
def GET(self):
return rend... | else: |
return render.solver(None, "", "")
# class halt:
# def POST(self):
# print "trying to halt"
# solver.stop()
# raise web.seeother('/')
if __name__ == '__main__':
render = web.template.render('pycryptics/crypticweb/templates/')
urls = ('/', 'index',
'/solve... |
ActianCorp/dbmv | bin/driverTools.py | Python | apache-2.0 | 12,678 | 0.004417 | #!/usr/bin/env python
# -*- coding: utf-8 -*
# Copyright 2015 Actian Corporation
# 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
#... | else:
for node in xmldoc.getElementsByTagName(p_key1)[0].getElem | entsByTagName(p_key2):
if node.getAttribute("id") == p_key3:
for child in node.childNodes:
if child.nodeType == xml.dom.minidom.Node.TEXT_NODE:
result = child.data
return(result)
class dbconnector:
def __init__(self, p_db, connect = True)... |
cryvate/project-euler | project_euler/solutions/problem_41.py | Python | mit | 441 | 0 | from itertools import permutations
from ..library.number_theory.primes import is_prime
from ..library.base import list_to_number
def solve() -> int:
for n in range(9, -1, -1):
if sum(range(n + 1)) % 3 == 0:
continue # always divisible by 3
for permutation in permutations(range(n, 0... | number = list_to_number(permutation)
if is_prime(number):
return number
| |
vicnet/weboob | modules/ratp/test.py | Python | lgpl-3.0 | 1,363 | 0.002201 | # -*- coding: utf-8 -*-
# Copyright(C) 2017 Phyks (Lucas Verney)
#
# This file is part of a weboob module.
#
# This weboob module 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 o... | eboob.tools.test import BackendTest
class RATPTest(BackendTest):
MODULE = 'ratp'
def test_ | ratp_gauges(self):
l = list(self.backend.iter_gauges())
assert len(l) == 26
def test_ratp_gauges_filter(self):
l = list(self.backend.iter_gauges(pattern="T3A"))
assert len(l) == 1
def test_ratp_sensors(self):
l = list(self.backend.iter_sensors("ligne_metro_4"))
... |
mp4096/controlboros | controlboros/tests/test_state_space.py | Python | bsd-3-clause | 4,081 | 0 | """Tests for the LTI discrete-time systems."""
from controlboros import StateSpace
import numpy as np
import pytest
def test_dynamics_single_input():
"""Test dynamics equation with single input."""
a = np.array([[1.0, 2.0], [0.0, 1.0]])
b = np.array([[1.0], [3.0]])
c = np.zeros((1, 2))
s = StateS... | )
assert np.all(s.output([1.0, 1.0], [1.0, 1.0]) == np.array([7.0]))
def test_output_mimo():
"""Test output equation with multiple inputs, multiple outputs."""
a = np.zeros((2, 2))
b = np.zeros((2, 2))
c = np.eye(2)
d = np.eye(2)
s = StateSpace(a, b, c, d)
assert np.all(s.output([1.... | not square."""
a = np.zeros((2, 1))
b = np.zeros((2, 1))
c = np.zeros((1, 2))
with pytest.raises(ValueError) as excinfo:
StateSpace(a, b, c)
assert "Invalid matrix dimensions" in str(excinfo.value)
def test_invalid_input_matrix_dimensions():
"""Test exception if B and A have different... |
harishkrao/DSE200x | Week-1-Intro-new/customplot.py | Python | mit | 940 | 0.026596 | #
# First, let us create some utility functions for Plotting
#
def pd_centers(featuresUsed, centers):
from itertools import cycle, islice
from pandas.tools.plotting import parallel_coordinates
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
colNames = list(featuresUsed)
colNames.append(... | tertools import cycle, islice
from pandas.tools.plotting import parallel_coordinates
import matplotlib.pyplot as plt
my_colors = list(islice(cycle(['b', 'r | ', 'g', 'y', 'k']), None, len(data)))
plt.figure(figsize=(15,8)).gca().axes.set_ylim([-2.5,+2.5])
parallel_coordinates(data, 'prediction', color = my_colors, marker='o') |
cpennington/edx-platform | openedx/core/djangoapps/content/course_overviews/tests/factories.py | Python | agpl-3.0 | 1,152 | 0 |
from datetime import timedelta
import json
from django.utils import timezone
import factory
from factory.django import DjangoModelFactory
from opaque_keys.edx.locator import CourseLocator
from ..models import CourseOverview
class CourseOverviewFactory(DjangoModelFactory):
class Meta(object):
model = C... | lazy_attribute
def _location(self):
return self.id.make_usage_key('course', 'course')
@factory.lazy_attribute
def id(self):
return CourseLocator(self.org, 'toy', self | .run)
@factory.lazy_attribute
def display_name(self):
return "{} Course".format(self.id)
@factory.lazy_attribute
def start(self):
return timezone.now()
@factory.lazy_attribute
def end(self):
return timezone.now() + timedelta(30)
|
KevinGoodsell/sympy | sympy/simplify/simplify.py | Python | bsd-3-clause | 50,745 | 0.00335 | from sympy import SYMPY_DEBUG
from sympy.core import Basic, S, C, Add, Mul, Pow, Rational, Integer, \
Derivative, Wild, Symbol, sympify, expand, expand_mul, expand_func, \
Function, Equality
from sympy.core.numbers import igcd
from sympy.core.relational import Equality
from sympy.utilities import mak... | >>> together(1/x + | 1/y + 1/z)
(x*y + x*z + y*z)/(x*y*z)
>>> together(1/(x*y) + 1/y**2)
(x + y)/(x*y**2)
Or you can just denest multi-level fractional expressions:
>>> together(1/(1 + 1/x))
x/(1 + x)
It also perfect possible to work with symbolic powers or
exponential functions o... |
flavoi/diventi | diventi/accounts/migrations/0331_auto_20200612_0849.py | Python | apache-2.0 | 453 | 0 | # Generated by Django 2.2.13 on 2020-06-12 06:49
import | diventi.accounts.models
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('accounts', '0330_auto_20200612_0843'),
]
operations = [
migrations.AlterModelManagers(
name='d | iventiuser',
managers=[
('objects', diventi.accounts.models.DiventiUserManager()),
],
),
]
|
SickGear/SickGear | lib/imdbpie/constants.py | Python | gpl-3.0 | 292 | 0 | # -*- coding: utf-8 -*-
fr | om __future__ import absolute_import, unicode_literals
HOST = 'api.imdbws.com'
BASE_URI = 'https://{0}'.format(HOST)
SEARCH_BASE_URI = 'https: | //v2.sg.media-imdb.com'
USER_AGENT = 'IMDb/8.3.1 (iPhone9,4; iOS 11.2.1)'
APP_KEY = '76a6cc20-6073-4290-8a2c-951b4580ae4a'
|
Daverball/reconos | tools/python/mhstools.py | Python | gpl-2.0 | 7,320 | 0.016396 | #!/usr/bin/env python
# coding: utf8
# ____ _____
# ________ _________ ____ / __ \/ ___/
# / ___/ _ \/ ___/ __ \/ __ \/ / / /\__ \
# / / / __/ /__/ /_/ / / / / /_/ /___/ /
# ... | eturn s;
class MHSLine:
"""
This class represents a single line of a mhs file
fields: self.type : the first word on the line (eg. PARAMETER, PORT,...)
self.content: list containing key/value pairs
"""
def __init__(self, line, line_num = 0):
s = line.split()
... | self.line_num = line_num
for x in s:
y = map(lambda x: x.strip(), x.split("="))
if not len(y) == 2:
raise "parse error at line %i" % line_num
self.content.append((y[0],y[1]))
... |
mjmottram/snoing | packages/xrootd.py | Python | mit | 2,509 | 0.003587 | #!/usr/bin/env python
#
# XRootD
#
# XRootD package installer.
#
# Author M Mottram - 15/04/2016 <[email protected]> : First revision
#######################################################################
import localpackage
import os
import stat
import shutil
class XRootD(localpackage.LocalPackage):
""" Base ... | downloaded(self):
""" Check the tarball has been downloaded"""
return self._system.file_exists(self.get_tar_name())
| def _is_installed(self):
""" Check the script has been marked as executable."""
return self._system.file_exists("xrootd", os.path.join(self.get_install_path(), "bin")) and \
bool(os.stat(os.path.join(self.get_install_path(), "bin/xrootd")).st_mode & stat.S_IXUSR)
def _download(self):
... |
dovf/kitty | docs/source/conf.py | Python | gpl-2.0 | 9,549 | 0.005864 | # -*- coding: utf-8 -*-
#
# Kitty documentation build configuration file, created by
# sphinx-quickstart on Wed Jan 20 15:56:03 2016.
#
# 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
# autogenerated file.
#
# All... | p_warnings = False
# If true, `todo` and `todoL | ist` produce output, else they produce nothing.
todo_include_todos = True
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'sphinx_rtd_theme'
# Theme options are theme-spec... |
wbyne/QGIS | scripts/generate_test_mask_image.py | Python | gpl-2.0 | 6,625 | 0.004377 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
***************************************************************************
generate_test_mask_image.py
---------------------
Date : February 2015
Copyright : (C) 2015 by Nyall Dawson
Email : nyall dot daws... | k.png']
if len(filte | red_images) > 1:
error('Found multiple matching control images for {}'.format(path))
elif len(filtered_images) == 0:
error('No matching control images found for {}'.format(path))
found_image = filtered_images[0]
print('Found matching control image: {}'.format(found_image))
return found_... |
mikeckennedy/cookiecutter-course | src/ch8_sharing_your_template/show_off_web_app/show_off_web_app/__init__.py | Python | gpl-2.0 | 7,255 | 0.003584 | import datetime
import pkg_resources
import os
import sys
from pyramid.config import Configurator
# noinspection PyUnresolvedReferences
import show_off_web_app
import show_off_web_app.controllers.home_controller as home
import show_off_web_app.controllers.account_controller as account
import show_off_web_app.controller... | st run first
init_mode(config) # mode must go next
init_includes(config) # includes must go next
init_routing(co | nfig) # it's pretty much flexible from here on down
init_db(config)
init_mailing_list(config)
init_smtp_mail(config)
init_email_templates(config)
return config.make_wsgi_app()
def init_logging(config):
settings = config.get_settings()
log_level = settings.get('log_level')
log_filenam... |
decvalts/landlab | landlab/components/vegetation_ca/__init__.py | Python | mit | 106 | 0 |
import landlab.components.vegetation_ca.CA_V | eg
from landlab.components.vegetation_ca.CA_Veg import V | egCA
|
kleientertainment/ds_mod_tools | pkg/win32/Python27/Lib/pydoc.py | Python | mit | 95,949 | 0.002053 | #!/usr/bin/env python
# -*- coding: latin-1 -*-
"""Generate Python documentation in HTML or text for interactive use.
In the Python interpreter, do "from pydoc import help" to provide online
help. Calling help(thing) on a Python object documents the object.
Or, at the shell command line outside of Python:
... | ) # all your base are belong to us
for key in methods.keys():
methods[key] = | getattr(cl, key)
return methods
def _split_list(s, predicate):
"""Split sequence s via predicate, and return pair ([true], [false]).
The return value is a 2-tuple of lists,
([x for x in s if predicate(x)],
[x for x in s if not predicate(x)])
"""
yes = []
no = []
... |
DigitalCampus/django-oppia | api/resources/course.py | Python | gpl-3.0 | 9,945 | 0 | import json
import os
import re
import shutil
import xmltodict
import zipfile
from django.conf import settings
from django.conf.urls import url |
from django.core.exceptions import | MultipleObjectsReturned
from django.db.models import Q
from django.http import HttpResponse, Http404
from django.utils.translation import ugettext_lazy as _
from tastypie import fields
from tastypie.authentication import ApiKeyAuthentication, Authentication
from tastypie.authorization import ReadOnlyAuthorization, Auth... |
sporsh/jostedal | jostedal/utils.py | Python | mit | 185 | 0.016216 | import hashlib
def saslprep(string):
#TODO
| return string
def ha1(username, realm, password):
return hashlib.md5(':'.join((username, realm, saslprep(password)))).digest | ()
|
jabesq/home-assistant | tests/components/deconz/test_gateway.py | Python | apache-2.0 | 7,242 | 0 | """Test deCONZ gateway."""
from unittest.mock import Mock, patch
import pytest
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.components.deconz import errors, gateway
from tests.common import mock_coro
import pydeconz
ENTRY_CONFIG = {
"host": "1.2.3.4",
"port": 80,
"api_ke... | eway | .async_setup()
async def test_gateway_setup_fails():
"""Retry setup."""
hass = Mock()
entry = Mock()
entry.data = ENTRY_CONFIG
deconz_gateway = gateway.DeconzGateway(hass, entry)
with patch.object(gateway, 'get_gateway', side_effect=Exception):
result = await deconz_gateway.async_set... |
MJB47/Jokusoramame | joku/core/tagengine.py | Python | mit | 4,461 | 0.00269 | """
A Jinja2-based tag engine for tags.
"""
import asyncio
import inspect
import random
import string
from concurrent.futures import ThreadPoolExecutor
import discord
import functools
import lupa
from discord.abc import GuildChannel
from jinja2 import Template
from jinja2.sandbox import SandboxedEnvironment
from lupa... | lse,
unpack_returned_tuples=True,
attribute_handlers=(getter, setter))
# execute the sandbox preamble
sandbox = lua.execute(sandbox_preamble)
# call sandbox.run with `glob.sandbox, code`
# and unpack the variables
new = {}
... |
new[key] = lua.table_from(val)
_ = sandbox.run(luastr, lua.table_from(new))
if isinstance(_, bool):
# idk
return NO_RESULT
called, result = _
if lupa.lua_type(result) == 'table':
# dictify
result = dictify_table_recursively(... |
ryanlelek/SMORESGaitRecorder | proto/inertial_pb2.py | Python | gpl-3.0 | 4,116 | 0.001458 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: inertial.proto
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)
... | =[],
serialized_start=44,
serialized_end=179,
)
_INERTIAL.fields_by_name['pose'].message_type = pose_pb2._POSE
DESCRIPTOR.message_types_by_name['Inertial'] = _INERTIAL
class Inertial(_message.Message):
__metaclass__ = _reflection.GeneratedProtocolMessageTyp | e
DESCRIPTOR = _INERTIAL
# @@protoc_insertion_point(class_scope:gazebo.msgs.Inertial)
# @@protoc_insertion_point(module_scope)
|
VerstandInvictus/Spidergram | spidergram.py | Python | mit | 4,748 | 0.001053 | from bs4 import BeautifulSoup
import requests
import re
import os
import codecs
import unidecode
import arrow
import traceback
# disable warning about HTTPS
try:
requests.packages.urllib3.disable_warnings()
except:
pass
class instaLogger:
def __init__(self, logfile):
self.logfile = logfile
d... | raverse the script payload that apparently
is used to load Instagram pages completely on the fly. Pulls each
individual "page" - which is apparently 24 images by the user,
delineated by the "start_cursor" and "end_cursor" in the payload -
so that it can be parsed for images, and then us | es the ending cursor
to generate the link to the next "page".
"""
username = baseurl.split('/')[-2]
print "Downloaded {1} images. Scanning {0}...".format(
url, self.results['succeeded'])
payloadRaw = self.findWindowSharedData(url)
payloadRaw = re.sub('/', '', ... |
arvinddoraiswamy/LearnPython | 17.py | Python | mit | 867 | 0.013841 | import struct
''' Refer to docs for all the exact formats. There are many so check them out before converting things yourself '''
''' If there's a specific offset you want to do things from, use pack_into and unack_into from the docs '''
#Integer to string
i1= 1234
print "Int to string as 8 byte little endian", repr(... | npack("<i", s1)
print "String to 4 byte integer big en | dian", struct.unpack(">i", s1)
''' Whenever you want to convert to and from binary, think of binascii '''
import binascii
h1= binascii.b2a_hex(s1)
print "String to hex", h1
uh1= binascii.a2b_hex(h1)
print "Hex to string, even a binary string", uh1
|
ImmobilienScout24/crassus | src/unittest/python/output_converter_tests.py | Python | apache-2.0 | 5,826 | 0 | import json
import unittest
from crassus.deployment_response import DeploymentResponse
from crassus.output_converter import OutputConverter
from mock import call, patch
from utils import load_fixture_json
cfn_event = load_fixture_json('cfn_event.json')
cfn_event_different_termination = load_fixture_json(
'cfn_eve... | l hail the successful parsing, last parameter is StackName!
self.assertEqual(return_value['StackName'], 'crassus-karolyi-temp1')
# ... and the value should NOT have a closing quote.
self.assertNotEqual(
return_value['StackName'], 'crassus-karolyi-temp1\' | ')
self.assertEqual(return_value['ResourceProperties'], {
'Action': 'lambda:invokeFunction',
'SourceArn':
'arn:aws:sns:eu-west-1:123456789012:crassus-karolyi-temp1-'
'cfnOutputSnsTopic-KKF3Y90CS6SA',
'FunctionName':
'crassus-kar... |
benjaminjack/pinetree | tests/models/__init__.py | Python | mit | 18 | 0 | # f | rom . impor | t *
|
araichev/invoicing | invoicing/main.py | Python | mit | 10,632 | 0.005173 | """
CONVENTIONS:
- A timesheet object is a Pandas DataFrame object with at least the columns
* ``'date'``: date worked was done; datetime object
* ``'project'``: project the work is part of
* ``'duration'``: time spent on work; hours
- A biller is a univariate function that maps duration to cost (in some... | , end_date = f['date'].min(), f['date'].max()
f = f.groupby('project').agg({'duration': np.sum}
).reset_index()
f['start_date'] = start_date
f['end_date'] = end_date
return f[['start_date', 'end_date', 'project', 'duration']].copy()
#---------------------- | -----------------
# Billing
#---------------------------------------
def decompose(x, bins):
"""
Given a number x (the input ``x``)
and a list of numbers x_1, x_2, ..., x_n
(the input list ``bins``) whose sum is at least x and
whose last element may equal the non-number ``np.inf``
(which represe... |
nirs/vdsm | tests/virt/thinp_test.py | Python | gpl-2.0 | 5,860 | 0 | #
# Copyright 2017-2020 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed ... | onitoring_needed()
vm.drives.append(FakeDrive(False))
assert not mon.mon | itoring_needed()
vm.drives.append(FakeDrive(True))
assert mon.monitoring_needed()
vm.drives.append(FakeDrive(False))
assert mon.monitoring_needed()
mon.disable()
assert not mon.monitoring_needed()
mon.enable()
assert mon.monitoring_needed()
vm.drives[1].flag = False
assert n... |
richm/designate | designate/objects/tsigkey.py | Python | apache-2.0 | 756 | 0 | # Copyright (c) 2014 Rackspace Hosting
# All Rights Reserved.
# |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance wi | th the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either ... |
mgedmin/python-livereload | server.py | Python | bsd-3-clause | 173 | 0 | # coding: | utf-8
from livereload impor | t Server, shell
server = Server()
server.watch('docs/*.rst', shell('make html'))
server.serve(root='docs/_build/html', open_url=True)
|
sharadbhat/Video-Sharing-Platform | Client/client.py | Python | mit | 36,232 | 0.014186 | from flask import Flask, redirect, url_for, session, request, render_template_string, abort
import requests
import os
import ast
import base64
from nocache import nocache
#App config
ALLOWED_EXTENSIONS = set(['mp4'])
app = Flask(__name__)
app.secret_key = os.urandom(24)
@app.errorhandler(404)
@nocache
def error_40... | _error = request.args.get('u_error', False)
if 'user' not in session:
return redirect(url_for('login_form'))
is_admin = (requests.get(url='http://127.0.0.1:8080/is-admin/{}'.format(session['user'])).content).decode("utf-8") # Done
if is_admin == "True":
abort(403)
... | 0/html/{}'.format('password_update.html'))).content).decode("utf-8") # Done
if u_error == False:
return render_template_string(password_update_page)
else:
return render_template_string(password_update_page, update_error = True)
"""
In POST request
- Gets the old a... |
procangroup/edx-platform | cms/djangoapps/course_creators/tests/test_admin.py | Python | agpl-3.0 | 8,540 | 0.004567 | """
Tests course_creators.admin.py.
"""
import mock
import django
from django.contrib.admin.sites import AdminSite
from django.contrib.auth.models import User
from django.core import mail
from django.http import HttpRequest
from django.test import TestCase
from course_creators.admin import CourseCreatorAdmin
from cou... | ge_state(CourseCreator.DENIED, expect_sent_to_admin=False, expect_sent_to_user=True)
check_admin_message_state(CourseCreator.GRANTED, expect_sent_to_admin=False, expect_sent_to_user=Tr | ue)
check_admin_message_state(CourseCreator.PENDING, expect_sent_to_admin=True, expect_sent_to_user=True)
check_admin_message_state(CourseCreator.PENDING, expect_sent_to_admin=False, expect_sent_to_user=False)
check_admin_message_state(CourseCreator.DENIED, expect_sent_to_admin=False... |
kdlucas/pyrering | lib/pyreringconfig.py | Python | apache-2.0 | 10,508 | 0.003616 | #!/usr/bin/python
#
# Copyright 2008 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | lt name is pyrering.conf
project_name: The name of a project PyreRing will test on.
sendmail: a boolean value if PyreRing should send out email report or not.
default value is False. Note: there will be no email if all test
passed regardless of this flag.
email_recipients: comma ... | non_absulte path provided, the
the actual value will be os.path.join(ed) with
'<root_dir>/report'
default name is pyrering.log
file_errors: a boolean value that turns on filing the output of each none
passing testcase to a separate output file.
reset: ... |
securify/pref-finder | pref-calc.py | Python | apache-2.0 | 3,310 | 0.009063 | ## Flow for determining preferences
# Command line for prefs
## ex. fire, cold, phys, magi, asph, acid, pois, elec
# read for each file in directory and then create dict
# for line in test_file
# of lstrip starts with "if line.strip().startswith("replace: prefix-list") and list_name is None :"
## ex dict abbot {}
... | rip().startswith("/set TOTAL_ELEC="):
dictname['elec'] = line.strip().split(sep="=")[1]
elif line.strip().startswith("/set TOTAL_FIRE="):
dictname['fire'] = line.strip().split(sep="=")[1]
elif line.strip().startswith("/set TOTAL_MAGI=") | :
dictname['magi'] = line.strip().split(sep="=")[1]
elif line.strip().startswith("/set TOTAL_PHYS="):
dictname['phys'] = line.strip().split(sep="=")[1]
elif line.strip().startswith("/set TOTAL_POIS="):
dictname['acid'] = line.strip().split(sep="=")... |
pombredanne/re-core | test/test_utils.py | Python | agpl-3.0 | 3,251 | 0 | # Copyright (C) 2014 SEE AUTHORS FILE
#
# 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 License, or
# (at your option) any later version.
#
# This program is distr... | ('{"test": null}') == {'test': None}
self.assertRaises(ValueError, utils.load_json_str, "BAD DATA | ")
# Refacter merged the init_amql and the connect_mq functions
# together. Need to fix this unit test.
#
# def test_connect_mq(self):
# """
# Check that connect_mq follows the expected connection steps
# """
# with mock.patch(
# 'pika.BlockingConnection... |
leandro86/epubcreator | epubcreator/pyepub/pyepubreader/opf.py | Python | unlicense | 3,730 | 0.00429 | from lxml import etree
class Opf:
_OPF_NS = "http://www.idpf.org/2007/opf"
DC_NS = "http://purl.org/dc/elements/1.1/"
def __init__(self, opf):
self._opf = etree.parse(opf)
def getSpineItems(self):
return self._xpath(self._opf, "/opf:package/opf:spine/opf:itemref/@idref")
def get... | (self._opf, "/opf:package/opf:metadata/dc:date[@opf:event = 'publication']/text()")
return publicationDate[0] if publicationDate else None
def getPublisher(self):
publisher = self._xpath(self._opf, "/opf:package/opf:metadata/dc:publisher/text() | ")
return publisher[0] if publisher else None
def getSubject(self):
subject = self._xpath(self._opf, "/opf:package/opf:metadata/dc:subject/text()")
return subject[0] if subject else None
def getPathToToc(self):
return self._xpath(self._opf, "/opf:package/opf:manifest/opf:item[@... |
aguerra/python-stuff | stuff/collections.py | Python | bsd-2-clause | 604 | 0 | def | _iter(target, method, key):
iterable = target if method is None else getattr(target, method)()
iterator = iter(iterable)
if key is None:
return iterator
if not callable(key):
raise TypeError('{!r} is not callable'.format(type(key).__name__))
return (each for each in iterator if ke... | arget, method=None, key=key)
def iter_values(dict_, key=None):
return _iter(target=dict_, method='values', key=key)
def iter_items(dict_, key=None):
return _iter(target=dict_, method='items', key=key)
|
tieusangaka/datacollect | pdb_infotable/pdb_infotable.py | Python | gpl-3.0 | 4,974 | 0.008243 | #!/usr/bin/env python
# Tested in Python 3
# Sebastian Raschka, 2014
# An interactive command line app for
# creating a PDB file info table.
# For help, execute
# ./pdb_infotable.py --help
import bs4
import urllib
import pyprind
import pandas as pd
class Pdb(object):
def __init__(self, pdb_code):
self.c... | _argument('-i', '--input', help='A 1 | -column text file with PDB codes.')
parser.add_argument('-o', '--output', help='Filename for creating the output CSV file.')
parser.add_argument('-v', '--version', action='version', version='v. 1.0')
args = parser.parse_args()
if not args.output:
print('Please provide a filename for c... |
mjpost/sacreBLEU | sacrebleu/tokenizers/tokenizer_13a.py | Python | apache-2.0 | 985 | 0 | from functools import lru_cache
from .tokenizer_base import Bas | eTokenizer
from .tokenizer_re import TokenizerRegexp
class Tokenizer13a(BaseTokenizer):
def signature(self):
return '13a'
def __init__(self):
self._post_tokeni | zer = TokenizerRegexp()
@lru_cache(maxsize=2**16)
def __call__(self, line):
"""Tokenizes an input line using a relatively minimal tokenization
that is however equivalent to mteval-v13a, used by WMT.
:param line: a segment to tokenize
:return: the tokenized line
"""
... |
Zarthus/CloudBotRefresh | plugins/rottentomatoes.py | Python | gpl-3.0 | 1,312 | 0.001524 | from cloudbot import hook
from cloudbot.util import http
api_root = 'http://api.rottentomatoes.com/api/public/v1.0/'
movie_search_url = api_root + 'movies.json'
movie_reviews_url = api_root + 'movi | es/%s/reviews.json'
@hook.command('rt')
def rottentomatoes(inp, bot=None):
"""rt <title> -- gets ratings for <title> from Rotten Tomatoes"""
api_key = bot.config.get("api_keys", {}).get("rottentomatoes", None)
if not api_key:
| return "error: no api key set"
title = inp.strip()
results = http.get_json(movie_search_url, q=title, apikey=api_key)
if results['total'] == 0:
return 'No results.'
movie = results['movies'][0]
title = movie['title']
movie_id = movie['id']
critics_score = movie['ratings']['... |
RPGOne/Skynet | pytorch-master/torch/legacy/nn/VolumetricConvolution.py | Python | bsd-3-clause | 6,906 | 0.001158 | import math
import torch
from .Module import Module
from .utils import clear
class VolumetricConvolution(Module):
def __init__(self, nInputPlane, nOutputPlane, kT, kW, kH, dT=1, dW=1, dH=1, padT=0, padW=None, padH=None):
super(VolumetricConvolution, self).__init__()
self.nInputPlane = nInputPlan... | self._backend.library_state,
input,
gradOutput,
self.gradWeight,
self.gradBias,
self.finput,
self.fgradInput,
self.dT, self.dW, self.dH,
self.padT, self.padW, self.padH,
... | ale
)
else:
input, gradOutput = self._makeContiguous(input, gradOutput)
self._viewWeight()
self._backend.VolumetricConvolutionMM_accGradParameters(
self._backend.library_state,
input,
gradOutput,
self... |
ariddell/pystan | pystan/tests/test_utf8.py | Python | gpl-3.0 | 1,618 | 0.004988 | import unittest
from pystan import stanc, StanModel
from pystan._compat import PY2
class TestUTF8(unittest.TestCase):
desired = sorted({"status", "model_cppname", "cppcode", "model_name", "model_code", "include_paths"})
def test_utf8(self):
model_code = 'parameters {real y;} model {y ~ normal(0,1);}... | ))
self.assertEqual(result['status'], 0)
def test_utf8_multilinecomment(self | ):
model_code = u'parameters {real y;\n /*äöéü\näöéü*/\n} model {y ~ normal(0,1);}'
result = stanc(model_code=model_code)
self.assertEqual(sorted(result.keys()), self.desired)
self.assertTrue(result['cppcode'].startswith("// Code generated by Stan "))
self.assertEqual(result['sta... |
c4mb0t/django-setman | setman/helpers.py | Python | bsd-3-clause | 1,048 | 0 | from setman import settings
from setman.utils import is_settings_container
__all__ = ('get_config', )
def get_config(name, default=None):
"""
Helper function to easy fetch ``name`` from database or django settings and
return ``default`` value if setting key isn't found.
But if not ``default`` value... | ` function raises
``ValueError`` cause cannot to returns config value.
For fetching app setting use next definition:
``<app_name>.<setting_name>``.
"""
app_name = None
if '.' in name:
app_name, name = name.split('.', 1)
values = getattr(settings, app_name) if app_name else setting... | lues, name)
if is_settings_container(result):
raise ValueError('%r is settings container, not setting.' % name)
return result
|
mxmaslin/Test-tasks | django_test_tasks/old_django_test_tasks/apps/playschool/serializers.py | Python | gpl-3.0 | 721 | 0 | import base64
import imghdr
import six
import uuid
from django.core.files.base import ContentFile
from rest_framework import serializers
from .models import Scholar, Record
cl | ass ScholarSerializer(serializers.ModelSerializer):
class Meta:
model = Scholar
fields = (
'pk',
'photo',
'name',
'sex',
'birth_date',
'school_class',
'is_studying')
class RecordSerializer(serializers.ModelSeriali... | 'has_came_with',
'time_arrived',
'time_departed'
)
|
ayepezv/GAD_ERP | addons/account_voucher/models/account_voucher.py | Python | gpl-3.0 | 19,955 | 0.005362 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, api, _
import odoo.addons.decimal_precision as dp
from odoo.exceptions import UserError
class AccountVoucher(models.Model):
_name = 'account.voucher'
_description = 'Accounting... | ect=Tru | e, states={'draft': [('readonly', False)]},
copy=False, default=fields.Date.context_today)
account_date = fields.Date("Accounting Date",
readonly=True, select=True, states={'draft': [('readonly', False)]},
help="Effective date for accounting entries", copy=False, default=fields.Date.context_... |
aronsky/home-assistant | homeassistant/components/venstar/__init__.py | Python | apache-2.0 | 3,291 | 0.000608 | """The venstar component."""
import asyncio
from requests import RequestException
from venstarcolortouch import VenstarColorTouch
from homeassistant.const import (
CONF_HOST,
CONF_PASSWORD,
CONF_PIN,
CONF_SSL,
CONF_USERNAME,
)
from homeassistant.exceptions import ConfigEntryNotReady
from homeassis... | config):
"""Unload the config config and platforms."""
unload_ok = await hass.config_entries.async_unload_platforms(config, PLATFORMS)
if unload_ok:
hass.data[DOMAIN].pop(config.entry_id)
return unload_ok
class VenstarEn | tity(Entity):
"""Get the latest data and update."""
def __init__(self, config, client):
"""Initialize the data object."""
self._config = config
self._client = client
async def async_update(self):
"""Update the state."""
try:
info_success = await self.has... |
ehabkost/virt-test | qemu/tests/multi_vms_file_transfer.py | Python | gpl-2.0 | 6,006 | 0.002498 | import time, os, logging
from autotest.client import utils
from autotest.client.shared import error
from virttest import remote, utils_misc
@error.context_aware
def run_multi_vms_file_transfer(test, params, env):
"""
Transfer a file back and forth between multi VMs for long time.
1) Boot up two VMs .
... |
error.context(msg, logging.info)
t_begin = time.time()
remote.scp_between_remotes(src=ip_vm2, dst=ip_vm1, port=port,
s_passwd=password, d_passwd=password,
s_name=username, d_name=username,
... | timeout=transfer_timeout,
log_filename=log_vm1)
t_end = time.time()
throughput = filesize / (t_end - t_begin)
logging.info("File transfer VM2 -> VM1 succeed, "
"estimated throughput: %.2fMB... |
DrDub/nlg4patch | nlg4patch/unidiff/tests/test_parser.py | Python | gpl-3.0 | 1,824 | 0.000549 | # -*- coding: utf-8 -*-
# Author: Matías Bordese
"""Tests for the unified diff parser process."""
import os.path
import unittest2
from nlg4patch.unidiff import parser
class TestUnidiffParser(unittest2.TestCase):
"""Tests for Unified Diff Parser."""
def setUp(self):
samples_dir = os.path.dirname(o... | _file)
# one file in the patch
self.assertEqual(len(res), 1)
# three hunks
self.assertEqual(len(res[0]), 3)
# Hunk 1: five additions, no deletions, no modifications
self.assertEqual(res[0][0].added, 6)
self.assertEqual(res[0][0].modified, 0)
| self.assertEqual(res[0][0].deleted, 0)
# Hunk 2: no additions, 6 deletions, 2 modifications
self.assertEqual(res[0][1].added, 0)
self.assertEqual(res[0][1].modified, 2)
self.assertEqual(res[0][1].deleted, 6)
# Hunk 3: four additions, no deletions, no modifications
... |
Distrotech/reportlab | tests/test_source_chars.py | Python | bsd-3-clause | 3,375 | 0.008 | #!/usr/bin/env python
#Copyright ReportLab Europe Ltd. 2000-2012
#see license.txt for license details
"""This tests for things in source files. Initially, absence of tabs :-)
"""
from reportlab.lib.testutils import setOutDir,makeSuiteForClasses, outputfile, SecureTestCase, GlobDirectoryWalker, printLocation
setOutDir(... | es:
badLines = badLines + 1
badChars = badChars + spaces
if badChars != 0:
self.output.write("file %s contains %d trailing spaces, or %0.2f%% wastage\n" % (filename, badChars, 100.0*badChars/initSize))
def testFiles(self):
w = GlobDirectory | Walker(RL_HOME, '*.py')
for filename in w:
self.checkFileForTabs(filename)
self.checkFileForTrailingSpaces(filename)
def zapTrailingWhitespace(dirname):
"""Eliminates trailing spaces IN PLACE. Use with extreme care
and only after a backup or with version-controlled code."""
... |
jazzband/django-constance | tests/redis_mockup.py | Python | bsd-3-clause | 155 | 0 | class Connection(dict) | :
def set(self, key, value):
self[key] = value
def mget(self, keys):
return [ | self.get(key) for key in keys]
|
log2timeline/plaso | tests/parsers/sqlite_plugins/firefox_history.py | Python | apache-2.0 | 6,326 | 0.001265 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the Mozilla Firefox history database plugin."""
import collections
import unittest
from plaso.lib import definitions
from plaso.parsers.sqlite_plugins import firefox_history
from tests.parsers.sqlite_plugins import test_lib
class FirefoxHistoryPluginTest(... | 344',
'timestamp_desc': definitions.TIME_DESCRIPTION_ADDED}
self.CheckEventValues(storage_writer, events[1], expected_event_values)
# Check the second bookmark event.
expected_event_values = {
'data_type': 'firefox:places:bookmark',
'date_time': '2011-07-01 11:13:59.267198',
... | FILED_BOOKMARKS&folder=TOOLBAR&'
'sort=12&excludeQueries=1&excludeItemIfParentHasAnnotation=livemark'
'%2FfeedURI&maxResults=10&queryType=1'),
'timestamp_desc': definitions.TIME_DESCRIPTION_MODIFICATION,
'title': 'Recently Bookmarked',
'type': 'URL',
'url': (
... |
tshirtman/ultimate-smash-friends | usf/animations.py | Python | gpl-3.0 | 5,865 | 0.004433 | ################################################################################
# copyright 2008 Gabriel Pettier <[email protected]> #
# #
# This file is part of UltimateSmashFriends ... | gametime - self._start_time > self.duration/1000.0):
self.playing = 0
if self.repeat is not 0:
| #FIXME: repeat will not reset properly
self.repeat = max(-1, self.repeat - 1)
self.start(gametime)
else:
frame = self.frame(gametime - self._start_time)
self.image = frame.image
self.trails = frame.trails
... |
botswana-harvard/bcpp-subject | bcpp_subject/forms/medical_diagnoses_form.py | Python | gpl-3.0 | 622 | 0 | from bcpp_subject_form_validators import MedicalDiagno | sesFormValidator
from ..constants import ANNUAL
from ..models import MedicalDiagnoses
from .form_mixins import SubjectModelFormMixin
class MedicalDiagnosesForm (SubjectModelFormMixin):
form_validator_cls = MedicalDiagnosesFormValidator
optional_labels = {
ANNUAL: {'diagnoses': (
| 'Since we spoke with you at our last visit, '
'do you recall or is there a record '
'of having any of the following serious illnesses?'),
}
}
class Meta:
model = MedicalDiagnoses
fields = '__all__'
|
badloop/SickRage | sickbeard/image_cache.py | Python | gpl-3.0 | 13,572 | 0.003389 | # Author: Nic Wolfe <[email protected]>
# URL: https://sickrage.tv
# Git: https://github.com/SickRage/SickRage.git
#
# This file is part of SickRage.
#
# SickRage is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, ... | None
def _cache_image_from_file(self, image_path, img_type, indexer_id):
"""
Takes the image provided and copies it to the cache folder
:param image_path: path to the image we're caching
:param img_type: BANNER or POSTER or FANART
:param indexer_id: id of the show this imag... | e type & indexer_id
if img_type == self.POSTER:
dest_path = self.poster_path(indexer_id)
elif img_type == self.BANNER:
dest_path = self.banner_path(indexer_id)
elif img_type == self.FANART:
dest_path = self.fanart_path(indexer_id)
else:
log... |
0rmi/tyggbot | apiwrappers.py | Python | mit | 3,975 | 0.001006 | import urllib.parse
import urllib.request
import json
import logging
import requests
log = logging.getLogger('tyggbot')
class APIBase:
@staticmethod
def _get(url, headers={}):
try:
req = urllib.request.Request(url, None, headers)
response = urllib.request.urlopen(req)
| except Exception as e:
return None
try:
return response.read().decode('utf-8')
except Exception as e:
log.error(e)
return None
return None
@staticmethod
def _get_json(url, headers={}):
try:
data = APIBase._get(url,... | on.loads(data)
else:
return data
except Exception:
log.exception('Caught exception while trying to parse json data.')
return None
return None
def get_url(self, endpoints=[], parameters={}):
return self.base_url + '/'.join(endpoints) + (''... |
amm042/pywattnode | powerScout.py | Python | gpl-2.0 | 11,173 | 0.017632 | import pywattnodeapi as mdbus
import struct
import logging
import time
class PowerScoutClient(mdbus.SerialModbusClient):
reg_names = [i.strip() for i in """kWh System LSW
kWh System MSW
kW System
kW Demand System Max
kW Demand System Now
kW System Max
kW System Min
kVARh System LSW
kVARh System MSW
kVAR System... | 1,
| 1,
1]
PF_scalar = [0.01,
0.01,
0.01,
0.01,
0.01,
0.01]
kW_scalar = [0.00001,
0.001,
0.1,
1,
10,
100]
V_scalar = [0.1,... |
sinotradition/meridian | meridian/acupoints/xiajuxu441.py | Python | apache-2.0 | 241 | 0.034483 | #!/us | r/bin/python
#coding=utf-8
'''
@author: sheng
@license:
'''
SPELL=u'xiàjùxū'
CN=u'下巨虚'
NAME=u'xiajuxu441'
CHANNEL='stomach'
CHANNEL_FULLNAME='StomachChannelofFoot-Yangming'
S | EQ='ST39'
if __name__ == '__main__':
pass
|
dtulyakov/py | intuit/test7.py | Python | gpl-2.0 | 281 | 0.007117 | #! | /usr/bin/env python2
# -*- coding: utf-8 -*-
import os, sys
print 3 < 4 < 6, "3 < 4 < 6"
print 3 >= 5, "3 >= 5"
print 4 == 4, "4 == 4"
print 4 != 4, "4 != 4"
for i, j in (0, 0), (0, 1), (1, 0), (1, 1):
print i, j, ":", i & j, i | j | , i ^ j
pi = 3.1415926535897931
print pi ** 40
|
Pholey/vcfx | setup.py | Python | mit | 531 | 0 | #!/us | r/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
from imp import load_source
import sys
setup(
name='vcfx',
version=load_source('', 'vcfx/__version__.py').__version__,
description='A Python 3 Vcard parser.',
author='Cassidy Bridges',
author_email='cassidybridges@... | as_require={
'test': ['pytest']
},
)
|
adijo/rosalind | old/hamming_distance.py | Python | gpl-2.0 | 100 | 0.08 | def | hamming(s,t):
dist = 0
for x in range(len(s)):
if s[x]! | =t[x]:
dist+=1
return dist
|
ajwillia/mu | mu/resources/api.py | Python | gpl-3.0 | 40,706 | 0.005527 | """
Contains definitions for the MicroPython micro:bit related APIs so they can be
used in the editor for autocomplete and call tips.
Copyright (c) 2015-2016 Nicholas H.Tollervey and others (see the AUTHORS file).
Based upon work done for Puppy IDE by Dan Pope, Nicholas Tollervey and Damien
George.
This program is f... | libration() command.\ | nRun calibrate() to improve accuracy.",
"microbit.compass.get_x() \nReturn magnetic field detected along micro:bit's X axis.\nUsually, the compass returns the earth's magnetic field in micro-Tesla units.\nUnless...a strong magnet is nearby!",
"microbit.compass.get_y() \nReturn magnetic field detected along micr... |
eamontoyaa/pyCSS | validations/validation03-comparisonZhao.etal.,2014.py | Python | bsd-2-clause | 5,013 | 0.010575 | '''
# Description.
This is a minimal module in order to perform a circular arc slope stability
analysis by the limit equilibrium model by Fellenius and Bishop symplified
methods.
'''
#------------------------------------------------------------------------------
## Add functions directory
import sys
sys.pa... | ce
else:
automaticslipcircles(projectName, projectAuthor, projectDate, slopeHeight,\
slopeDip, crownDist, toeDist, wantAutomaticToeDepth, toeDepth, \
numCircles, radiusIncrement, numberIncrements, maxFsValueCont, \
wantWatertable, wtDepthAtCrown, toeUnderWatertable, waterUnitWeight, ... | lUnitWeight, frictionAngleGrad, cohesion, \
wantConstSliceWidthTrue, numSlices, nDivs, methodString, \
outputFormatImg)
'''
BSD 2 license.
Copyright (c) 2016, Universidad Nacional de Colombia, Ludger O.
Suarez-Burgoa and Exneyder Andrés Montoya Araque.
All rights reserved.
Redistribution ... |
mshafir/virtual-reality-camera | virtual_camera_server.py | Python | mit | 1,299 | 0.013857 | import sys
PI = len(sys.argv) == 1
if PI:
from VirtualCamera import VirtualCamera
import time
import flask
from flask import Flask
from flask import render_template
if PI:
camera = VirtualCamera()
sweep = camera.capture_sweep()
app = Flask(__name__)
if PI:
START = camera.motor_start
... | @app.route('/left/<pos>')
def left(pos):
global PI
pos = int | (pos)
if PI:
shot = get_shot(pos)[0]
return flask.send_file(shot, mimetype='image/jpeg')
else:
return flask.send_file('images/img'+str(19-pos)+'.jpg', mimetype='image/jpeg')
@app.route('/right/<pos>')
def right(pos):
global PI
pos = int(pos)
if PI:
shot = get_shot(pos)[1]
... |
shoyer/numpy | numpy/doc/basics.py | Python | bsd-3-clause | 11,252 | 0.000444 | """
============
Array basics
============
Array types and conversions between types
=========================================
NumPy supports a much greater variety of numerical types than Python does.
This section shows which are available, and how to modify an array's data-type.
The primitive types supported are t... | t`
- ``unsigned short``
- Platform-defined
* - `np.intc`
- ``int``
- Platform-defined
* - `np.uintc`
- ``unsig | ned int``
- Platform-defined
* - `np.int_`
- ``long``
- Platform-defined
* - `np.uint`
- ``unsigned long``
- Platform-defined
* - `np.longlong`
- ``long long``
- Platform-defined
* - `np.ulonglong`
- ``unsigned long long``
- Platform-defined
... |
pistruiatul/hartapoliticii | python/src/ro/vivi/youtube_crawler/gdata/spreadsheets/data.py | Python | agpl-3.0 | 9,070 | 0.009592 | #!/usr/bin/env python
#
# Copyright (C) 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | ted under t | he License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# This module is used for version 2 of the Google Data APIs.
"""Provides classes and consta... |
fogcitymarathoner/djfb | facebook_example/django_facebook/canvas.py | Python | bsd-3-clause | 728 | 0 | from django.http import QueryDict
from django_facebook import settings as facebook_settings
def generate_oauth_url(scope=facebook_settings.FACEBOOK_DEFAULT_SCOPE,
next=None, extra_data=None):
query_dict = QueryDict('', True)
canvas_page = (next if next is not None else
... | facebook_se | ttings.FACEBOOK_CANVAS_PAGE)
query_dict.update(dict(client_id=facebook_settings.FACEBOOK_APP_ID,
redirect_uri=canvas_page,
scope=','.join(scope)))
if extra_data:
query_dict.update(extra_data)
auth_url = 'https://www.facebook.com/dialog/oaut... |
mstriemer/amo-validator | validator/testcases/javascript/call_definitions.py | Python | bsd-3-clause | 12,988 | 0.000231 | import math
import re
import actions
import predefinedentities
from jstypes import JSArray, JSObject, JSWrapper
# Function prototypes should implement the following:
# wrapper : The JSWrapper instace that is being called
# arguments : A list of argument nodes; untraversed
# traverser : The current traverser object... | ents, traverser):
passed_args = [traverser._traverse_node(a) for a in arguments]
params = []
| if not nargs:
# Handle definite argument lists.
for type_, def_value in args:
if passed_args:
parg = passed_args[0]
passed_args = passed_args[1:]
passed_literal = parg.get_literal_value()
passed_li... |
noslenfa/tdjangorest | uw/lib/python2.7/site-packages/paramiko/dsskey.py | Python | apache-2.0 | 6,726 | 0.002081 | # Copyright (C) 2003-2007 Robey Pointer <[email protected]>
#
# This file is part of paramiko.
#
# Paramiko is free software; you can redistribute it and/or modify it under the
# terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 2.1 of the License, or (a... | if len(sstr) < 20:
sstr = '\x00' * (20 - len(sstr)) + sstr
m.add_string(rstr + sstr)
return m
def verify_ssh_sig(self, data, msg):
if len(str(msg)) == 40:
# spies.com bug: signature has no header
sig = str(msg)
else:
kind = msg.get_str... | et_string()
# pull out (r, s) which are NOT encoded as mpints
sigR = util.inflate_long(sig[:20], 1)
sigS = util.inflate_long(sig[20:], 1)
sigM = util.inflate_long(SHA.new(data).digest(), 1)
dss = DSA.construct((long(self.y), long(self.g), long(self.p), long(self.q)))
re... |
epeios-q37/epeios | other/exercises/basics/workshop/_/display.py | Python | agpl-3.0 | 1,654 | 0.011487 | # coding: utf-8
"""
MIT License
Copyright (c) 2019 Claude SIMON (https://q37.info/s/rmnmqd49)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limit... | ject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FI... | LITY, 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.
"""
import workshop._._ as _
_OUTPUT = "output"
def _dom():
return _.dom()
def clear():
_dom().setLayout(_OUTPUT, "<span/>")
def displ... |
hgrimelid/feincms | feincms/content/comments/models.py | Python | bsd-3-clause | 3,732 | 0.003215 | # ------------------------------------------------------------------------
# coding=utf-8
# ------------------------------------------------------------------------
#
# Created by Martin J. Laubach on 08.01.10.
# skyl wuz here (11.05.10)
#
# ------------------------------------------------------------------------
""... | r = f.help_text
r += u'<hr />'
for c in Comment.objects.for_model(parent.parent).order_by('-submit_date'):
r += | '<div class="form-row" style="margin-left: 60px"># %d <a href="/admin/comments/comment/%d/">%s</a> - %s</div>' % \
( c.id, c.id, c.comment[:80], c.is_public and _('public') or _('not public') )
f.help_text = r
cls.feincms_item_editor_form = CommentContentAdminFo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.