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
PetterKraabol/Twitch-Chat-Downloader
tcd/arguments.py
Python
mit
3,199
0.001876
from typing import Optional, Dict, Union, List from .singleton import Singleton class Arguments(metaclass=Singleton): """ Arguments singleton """ class Name: SETTINGS_FILE: str = 'settings_file' SETTINGS: str = 'settings' INIT: str = 'init' VERBOSE: str = 'verbose' ...
f.log: bool = arguments[Arguments.Name.LOG] # Optional or prompted arguments self.client_id: Optional[str] = arguments[Arguments.Name.CLIENT_ID] self.client_se
cret: Optional[str] = arguments[Arguments.Name.CLIENT_SECRET] self.oauth_token: Optional[str] = None self.first: Optional[int] = arguments[Arguments.Name.FIRST] self.timezone: Optional[str] = arguments[Arguments.Name.TIMEZONE] self.includes: Optional[str] = arguments[Arguments.Name.INCLU...
thempel/adaptivemd
adaptivemd/mongodb/base.py
Python
lgpl-2.1
9,063
0.00011
############################################################################## # adaptiveMD: A Python Framework to Run Adaptive Molecular Dynamics (MD) # Simulations on HPC Resources # Copyright 2017 FU Berlin and the Authors # # Authors: Jan-Hendrik Prinz # Contributors: # # `adaptiveMD` is free software: ...
lf): """ Return the base class Returns ------- type the base class See Also -------- :func:`base()` """ return self.base() @classmethod
def descendants(cls): """ Return a list of all subclassed objects Returns ------- list of type list of subclasses of a storable object """ return cls.__subclasses__() + \ [g for s in cls.__subclasses__() for g in s.descendants()] @st...
frankeen/163_Opencourse_download
163_download.py
Python
mit
2,432
0.033838
# -*- coding: utf-8 -*- #抓取网易公开课链接并下载对应的相视频名称和视频格式 #By : obnjis@163.com #Python 2.7 + BeautifulSoup 4 #2014-12-18 #断点续传功能等待下一版本 #eg: python 163—video.py http://v.163.com/special/opencourse/ios7.html from bs4 import BeautifulSoup import re import sys,os import urllib import codecs #显示百分比 def rpb(blocknum, blocksize, to...
ven']}) for i in detail: #获取课程名称 linkurl=i.find('td',{"class" : "u-ctitle"}) dow
nLink=linkurl.a['href'] fileName=linkurl.contents[0].strip() .lstrip() .rstrip('>') + linkurl.a.string.strip() .lstrip() .rstrip('<') print fileName print downLink #L=[] #L.append(fileName) if not os.path.exists(fileName): downLink1=parser(downLink) ...
mdasifhasan/Experiments_HTN_Planner
PyHop/exp_1.py
Python
gpl-3.0
6,445
0.007913
""" The "travel from home to the park" example from my lectures. Author: Dana Nau <nau@cs.umd.edu>, May 31, 2013 This file should work correctly in both Python 2.7 and Python 3.2. """ import pyhop import random import sys from utils_plan import * from util_plot import * # state variables state1 = pyhop.State('state'...
if state.variables.affect.frustration < 3: return [('ask_true_false_on_concept', c)] return [] def ques
t_on_relation(state, r): if state.relations_heard_count[state.relations.index(r)] > 0: if state.variables.affect.frustration < 3: return [('ask_true_false_on_relation', r)] return [] def get_random_entry(collection): return collection[random.randint(0, len(collection)-1)] def next_step...
yamanakahirofumi/mokobot
Scraping4blog/run.py
Python
mit
323
0.01548
# -*- coding: utf-8 -*- from Scraping4blog import Scraping4blog import sys,os sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../util') from settings import SettingManager def main(): conf =
SettingManager() instance = Scraping4blog(conf) instance.run() if __name_
_ == "__main__": main()
stack-of-tasks/rbdlpy
tutorial/lib/python2.7/site-packages/OpenGL/GLES1/OES/blend_subtract.py
Python
lgpl-3.0
768
0.009115
'''OpenGL extension OES.blend_subtract This module customises
the behaviour of the OpenGL.raw.GLES1.OES.blend_subtract to provide a more Python-friendly API The official definition of this extension is available here: http://www.opengl.org/registry/specs/OES/blend_subtract.txt ''' from OpenGL import platform, constant, arrays from OpenGL import extensions, wrapper import ctyp...
_subtract import * from OpenGL.raw.GLES1.OES.blend_subtract import _EXTENSION_NAME def glInitBlendSubtractOES(): '''Return boolean indicating whether this extension is available''' from OpenGL import extensions return extensions.hasGLExtension( _EXTENSION_NAME ) ### END AUTOGENERATED SECTION
addition-it-solutions/project-all
addons/l10n_vn/__openerp__.py
Python
agpl-3.0
1,696
0.008255
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # This module is Copyright (c) 2009-2013 General Solutions (http://gscom.vn) All Rights Reserved. # # This program is free software: you can redistribute it and/or...
(at your option) any later versio
n. # # 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 copy of the GNU General Pub...
copasi/COPASI
copasi/bindings/python/unittests/Test_CReport.py
Python
artistic-2.0
3,011
0.026901
# -*- coding: utf-8 -*- # Copyright (C) 2019 - 2020 by Pedro Mendes, Rector and Visitors of the # University of Virginia, University of Heidelberg, and University # of Connecticut School of Medicine. # All rights reserved. # Copyright (C) 2017 - 2018 by Pedro Mendes, Virginia Tech Intellectual # Properties, Inc.,...
sert_(reportDefinition!=None) self.assert_(reportDefini
tion.__class__==COPASI.CReportDefinition) def test_setReportDefinition(self): listOfReportDefinitions=self.datamodel.getReportDefinitionList() reportDefinition=listOfReportDefinitions.createReportDefinition("MyReportDefinition","No Comment") self.assert_(reportDefinition!=None) self.report.setReportD...
Sth0nian/aurora
index.py
Python
mit
2,289
0.046308
import os, sys from mod_python import util, Cookie def _path(): return '/'.join(os.path.realpath(__file__).split('/')[:-1]) if _path() not in sys.path: sys.path.insert(0, _path()) def _load(req, page, dev= False): """ if not dev: branch= 'html' page= 'maintenance' f= open('%s/%s/%s.html' %(_path(), branch, p...
) return html def header(req): return _load(req, 'header') def footer(req): return _load(req, 'footer') def register(req): return _load(req, 'register') def registered(req): return _load(req, 'registered') def login(req): return _load(req, 'login') def token(req): return _load(req, 'token') def request(req): ret...
'change') def changed(req): return _load(req, 'changed') def driver(req): return _load(req, 'driver') def panel(req): return _load(req, 'panel') def campaign(req): return _load(req, 'campaign') def counter(req): return _load(req, 'counter') def counter_(req): import urllib, json form= util.FieldStorage(req, kee...
palful/yambopy
tutorial/mos2/proj_mos2.py
Python
bsd-3-clause
2,375
0.026947
# # Author: Henrique Pereira Coutada Miranda # Example script to plot the weigth of the atomic species in the bandstructure # from qepy import * import sys import argparse import matplotlib.pyplot as plt folder = 'bands' npoints = 20 p = Path([ [[0.0, 0.0, 0.0],'G'], [[0.5, 0.0, 0.0],'M'], [[1....
gs.calc: f = open('proj.in','w') projwfc = ProjwfcIn('mos2') projwfc.write(folder=folder) projwfc.run(folder=folder) if args.analyse: pxml = ProjwfcXML('mos2',path=folder) # obtain the list of orbitals and quantum numbers print pxml print "Writting projections" pxml.write_proj() ...
xrange(16)) #list containing the indexes of all the orbitals of mo s = list(xrange(16,48)) #list containing the indexes of all the orbitals of s fig = plt.figure(figsize=(30,10)) for n,(orb,title) in enumerate(zip([mo,s,mo+s],['mo','s','mos2'])): ax = plt.subplot(1,3,n+1) plt.title(ti...
fametrano/BitcoinBlockchainTechnology
tests/bip32/__init__.py
Python
mit
417
0
#!/usr/bin/env python3 # Copyright (C) 20
20-2021 The btclib developers # # This file is part of btclib. It is subject to the license terms in the # LICENSE file found in the top-level directory of this distribution. # # No part of btclib including this file, may be copied, modified, propagated, # or distributed except according to
the terms contained in the LICENSE file. """btclib.bip32 non-regression tests."""
caioau/caioau-personal
fluxos/lista 2/grafo-3.py
Python
gpl-3.0
1,558
0.032734
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sun Mar 27 01:20:46 2016 @author: caioau """ import matplotlib.pyplot as plt import networkx as nx from networkx.drawing.nx_agraph import graphviz_layout def main(): G = nx.DiGraph() # G eh um grafo direcionado # gera o grafo apartir de suas are...
alo) # TODO: desativar isso? nx.draw_networkx_edges(G,pos, edge_color=colors) # desenha as arestas nx.draw_networkx_labels(G,pos) # desenha os labels das arestas nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels) # desenha os labels
dos nos nx.draw_networkx_nodes(G,pos,node_color='w') # desenha os nos plt.axis('off') # desativa os eixos plt.savefig(pngfilename) plt.close("all") if __name__ == "__main__": main()
github/codeql
python/ql/test/library-tests/frameworks/stdlib-py3/CodeExecution.py
Python
mit
115
0
impor
t builtins # exec being part of builtins is Python 3 only buil
tins.exec("print(42)") # $getCode="print(42)"
molmod/molmod
molmod/examples/003_internal_coordinates/b_bending_angles.py
Python
gpl-3.0
1,360
0.000735
#!/usr/bin/env python from __future__ import print_function from molmod import * # 0) Load the molecule and set the default graph mol = Molecule.from_file("dopamine.xyz") mol.set_default_graph() # 1) Build a list of atom indexes involved in angles. angles = [] # First loop over all atoms on the molecule. for i1 in ...
l find all bending angles centered at the current # atom. For this we construct (an ordered!) list of all bonded neighbors. n = list(mol.graph.neigh
bors[i1]) # The second loop iterates over all neighbors. The enumerate function is # used to assign a counter value to the variable index. for index, i0 in enumerate(n): # The third loop iterates over all other neighbors that came before i1. for i2 in n[:index]: # Each triple is ...
FrodeSolheim/fs-uae-launcher
fsgamesys/input/devicemanager.py
Python
gpl-2.0
2,793
0
import sys from typing import List from .device import Device from .enumeratehelper import EnumerateHelper class DeviceManager(object): __instance = None @classmethod def instance(cls): if cls.__instance is None: helper = EnumerateHelper() cls.__instance = cls(helper) ...
return self.add_mouse_device(event) elif event["type"] == "keyboard-device-added": return self.add_keyboard_device(event) else: assert False def add_jo
ystick_device(self, event): device = Device() device.axes = event["axes"] device.balls = event["balls"] device.hats = event["hats"] device.buttons = event["buttons"] device.name = event["name"] device.id = event["id"] device.type = Device.TYPE_JOYSTICK ...
nagyistoce/devide
module_kits/vtk_kit/mixins.py
Python
bsd-3-clause
13,612
0.002424
# $Id$ """M
ixins that are useful for classes using vtk_kit. @author: Charl P. Botha <http://cpbotha.net/> """ from external.vtkPipeline.ConfigVtkObj import ConfigVtkObj from external.vtkPipeline.vtkMethodParser import VtkMethodParser from module_base import ModuleBase from module_mixins import IntrospectModuleMixin # temporary ...
ort re import types import utils ######################################################################### class PickleVTKObjectsModuleMixin(object): """This mixin will pickle the state of all vtk objects whose binding attribute names have been added to self._vtkObjects, e.g. if you have a self._imageMath,...
ac769/continuum_technologies
software/ble_live_read_graphical.py
Python
mit
2,073
0.002894
from bluepy.btle import * import time import serial from pyqtgraph.Qt import QtGui, QtCore import pyqtgraph as pg start_time = time.time() data = [] data2 = [] data3 = [] data4 = [] angles = [] pg.setConfigOption('background', 'w') pg.setConfigOption('foreground', 'k') pen = pg.mkPen('k', width=8) app = QtGui.QAppl...
otItem.getAxis('bottom').setPen(pen
) curve = plotWidget.plot(pen=pen) plotWidget.setYRange(20, 210) data = [0] ser = serial.Serial("/dev/rfcomm0", 9600, timeout=0.5) t = [0] # from calibration arm_straight = 957 arm_bent = 987 class MyDelegate(DefaultDelegate): def __init__(self): DefaultDelegate.__init__(self) def handleNotification...
simplegeo/SimpleGeo.framework
scripts/update-sg-categories.py
Python
bsd-3-clause
4,093
0.007085
import os import urllib2 import json import re ##### Convert a name to a variable name def cleanName(name): return re.sub('[\W_]+', '', name.replace('&','And')) ##### Load the categories endpoint file = urllib2.urlopen('http://api.simplegeo.com/1.0/features/categories.json') contents = json.loads(file.read()) ...
subcat in fsubcats: output += '#define SGFeatureSubcategory' + cleanName(subcat) + ' @\"' + subcat + '\"\n' # Feature categories (Places 1.0) output += '\n#pragma mark Place Categories (Places 1.0)\n\n' for cat in pcats: output += '#define SGPlaceCategory' + cleanName(cat) + ' @\"' + cat + '\"\n' for subcat i...
##### Write file output = '\ //\n\ // SGCategories.h\n\ // SimpleGeo.framework\n\ //\n\ // Copyright (c) 2010, SimpleGeo Inc.\n\ // All rights reserved.\n\ //\n\ // Redistribution and use in source and binary forms, with or without\n\ // modification, are permitted provided that the following conditions are met:...
VerstandInvictus/ReddWall
reddwall.py
Python
mit
3,528
0.003118
import praw import codecs import unidecode import os import requests import datetime import regex as re from collections import Counter import RAKE Rake = RAKE.Rake('foxstoplist.txt') try: requests.packages.urllib3.disable_warnings() except: pass subreddits = ["earthporn", "japanpics"] class redditLogger: ...
requests.get(imgurl) with open(imgwrite, "wb") as code: code.write(r.content) self.logger.logEntry(('downloaded ' + imgname), 'progress') self.results['succeeded'] += 1 return True else: self.logger.logEntry...
self.results['skipped'] += 1 return True except: self.logger.logEntry('failed to get: {0} from {1}'.format( imgurl, imgname), 'verbose') self.results['failed'] += 1 return None if __name__ == "__main__": dt = datetime.date.today().strftim...
pjdelport/feincms
feincms/views/cbv/urls.py
Python
bsd-3-clause
278
0.003597
from __future__ import a
bsolute_import from django.conf.urls import patterns, include, url from .views import Handler handler = Handler
.as_view() urlpatterns = patterns('', url(r'^$', handler, name='feincms_home'), url(r'^(.*)/$', handler, name='feincms_handler'), )
PaulieC/sprint2-Council
AvailableGames/RockPaperScissors.py
Python
apache-2.0
2,006
0.001994
#TODO replace RPSGame with this class(for clarity) __author__ = "Paul Council, Joseph Gonzoph, Anand Patel" __version__ = "sprint1" __credits__ = ["Greg Richards"] # imports from ServerPackage import Game class RockPaperScissors(Game.Game): """ this class simulates two players playing a game of rock, paper, sci...
lt: the tuple of moves that were played if they were legal :rtype: tuple """ player_one_move, player_two_move = moves move_one_legal = self.is_legal(player_one_move) move_two_legal = self.is_legal(player_two_move) if move_one_legal and move_two_legal: if play...
player_one_move == 0 and player_two_move != 1) \ or (player_one_move == 1 and player_two_move != 2) \ or (player_one_move == 2 and player_two_move != 0): # result is tuple with points each player has earned respectively result = (1, 0) ...
ishikawa/modipyd
examples/widget/002/widget.py
Python
mit
491
0.004073
import os import sys class Widget(object):
""" Widget is a User Interface (UI) component object. A widget object claims a rectagular region of its content, is responsible for all drawing within that region. """ def __init__(self, name, width=50, height=50): self.name = name self.resize(width, height) def size(self)...
t
PrashntS/miRmap
mirmap/vienna.py
Python
gpl-3.0
2,499
0.008003
# -*- coding: utf-8 -*- # # Copyright (C) 2011-2012 Charles E. Vejnar # # This is free software, licensed under the GNU General Public License v3. # See /LICENSE for more information. # """ Interface classes with the `Vienna RNA <http://www.tbi.univie.ac.at/RNA>` executable programs. """ import re import subprocess ...
ich except ImportError: #: Workaround for Pyt
hon2. #: http://stackoverflow.com/a/9877856 import os def which(pgm): path = os.getenv('PATH') for p in path.split(os.path.pathsep): p = os.path.join(p, pgm) if os.path.exists(p) and os.access(p, os.X_OK): return p class RNAvienna(object): """Interface class for RNA programs from ...
imanolarrieta/RL
tests/test_representations/test_IndependentDiscretization.py
Python
bsd-3-clause
1,739
0.008626
from rlpy.Representations import IndependentDiscretization from rlpy.Domains import GridWorld, InfiniteTrackCartPole import numpy as np from rlpy.Tools import __rlpy_location__ import os def test_number_of_cells(): """ Ensure create appropriate # of cells (despite ``discretization``) """ mapDir = os.path.join(...
domain = GridWorld(mapname=mapname) rep = IndependentDiscretization(domain) for r in np.arange(4): for c in np.arange(5): phiVec = rep.phi(np.array([r,c]), terminal=False) assert sum(phiVec) == 2 # 1 for each dimension assert phiVec[r] == 1 # correct row activat...
correct discretization in continuous state spaces """ # NOTE - if possible, test a domain with mixed discr/continuous domain = InfiniteTrackCartPole.InfTrackCartPole() #2 continuous dims rep = IndependentDiscretization(domain, discretization=20) assert rep.features_num == 40 rep = IndependentDiscre...
pirata-cat/mieli
agora/api/user.py
Python
agpl-3.0
1,722
0.005226
from mieli.api import organization from django.db import transaction from django.conf import settings from agora.api import link @transaction.atomic def create(user, **kwargs): org = organization.get_by_username(user.username) if org == None: raise Ex
ception("unknown organization for user '%s'" % user.user
name) lnk = link.get(organization=org, user='agora') if lnk == None: raise Exception("no Agora Voting's admin link for organization '%s'" % org.domain) kwargs = {} kwargs['username'] = get_agora_username(user) kwargs['password1'] = kwargs['password2'] = settings.AGORA_DEFAULT_KEY kwargs[...
mayavanand/RMMAFinalProject
build/lib/azimuth/local_multiprocessing.py
Python
bsd-3-clause
821
0.003654
import multiprocessing import numpy as np def configure(num_jobs=8, TEST=False, subtract=0, num_proc=None, num_thread_per_proc=None): ''' num_jobs is typically the # of genes we are parallelizing over ''' if num_proc is None: num_proc = multiprocessing.cpu_count() - subtract if num_jobs >...
threads each" % (num_jobs, num_thread_
per_proc) return num_jobs
ArcherSys/ArcherSys
Lib/test/test_copy.py
Python
mit
67,430
0.002625
<<<<<<< HEAD <<<<<<< HEAD """Unit tests for the copy module.""" import copy import copyreg import weakref import abc from operator import le, lt, ge, gt, eq, ne import unittest from test import support order_comparisons = le, lt, ge, gt equality_comparisons = eq, ne comparisons = order_comparisons + equality_compari...
py.error) self.assertTrue(issubclass(copy.Error, Exception)) # The copy() method def test_copy_basic(self): x = 42 y = copy.copy(x) self.asser
tEqual(x, y) def test_copy_copy(self): class C(object): def __init__(self, foo): self.foo = foo def __copy__(self): return C(self.foo) x = C(42) y = copy.copy(x) self.assertEqual(y.__class__, x.__class__) self.assertEqu...
xtiankisutsa/MARA_Framework
tools/enjarify/enjarify/hashtests.py
Python
lgpl-3.0
1,384
0.000723
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
.join('tests', name) rawdex = read(os.path.join(dir, 'classes.dex'), 'rb') for bits in
range(256): opts = options.Options(*[bool(bits & (1 << b)) for b in range(8)]) classes, errors = translate(rawdex, opts=opts) assert not errors for cls in classes.values(): print('{:08b}'.format(bits), hashlib.sha256(cls).hexdigest()) fullhash = hashlib.sha256(fu...
schleichdi2/OPENNFR-6.3-CORE
bitbake/lib/bb/ui/knotty.py
Python
gpl-2.0
29,579
0.002874
# # BitBake (No)TTY UI Implementation # # Handling output to TTYs or files (no TTY) # # Copyright (C) 2006-2012 Richard Purdie # # SPDX-License-Identifier: GPL-2.0-only # from __future__ import division import os import sys import xmlrpc.client as xmlrpclib import logging import progressbar import signal import bb.ms...
new) curses.setupterm() if curses.tigetnum("colors") > 2: format.enable_color() self.ed = curses.tigetstr("ed") if self.ed: self.cuu = curses.tigetstr("cuu") try: self._sigwinch_default = signal.getsignal(signal...
ndle) except: pass self.rows, self.columns = self.getTerminalColumns() except: self.cuu = None if not self.cuu: self.interactive = False bb.note("Unable to use interactive mode for this terminal, using fallback") ret...
erlehmann/noise-invaders
pyspaceinvaders_noise.py
Python
gpl-2.0
371
0.013477
import pygame import numpy def add_noise(surface): mask = surface.copy() mask.set_colorkey((255,255,255)) screen
_array = pygame.surfarray.pixels3d(surface) noise = n
umpy.random.random((surface.get_width(), surface.get_height())) * 255 screen_array *= noise[:, :, numpy.newaxis] del screen_array surface.blit(mask, (0,0)) surface = mask
AjayMT/minopt
minopt_vows.py
Python
mit
1,187
0
from pyvows import Vows, expect from minopt import minopt @Vows.batch class Minopt(Vows.Context): def topic(self): return minopt(['--baz', 'hello', '--foo', 'bar', '-baz', '--riff=wobble', '--hey', '-ho', 'world'], {'string': ['a', 'hey', 'w'], ...
expected = (True, True) expect((topic['b'], topic['z'])).to_equal(expected) def should_parse_booleans(self, topic): expect(topic['baz']).to_be_true() expect(topic['h']).to_be_true() expect(topic['o']).to_be_true() def should_parse_strings(self, topic): expect(topic['a']...
hould_parse_unnamed_args(self, topic): expect(topic['_']).to_equal(['hello', 'world']) def should_set_all_args(self, topic): expected = ('', False) expect((topic['w'], topic['q'])).to_equal(expected)
smartanthill/smartanthill1_0
smartanthill/test/test_litemq.py
Python
mit
4,944
0
# Copyright (C) Ivan Kravets <me@ikravets.com> # See LICENSE for details. # pylint: disable=W0212,W0613 from twisted.internet.defer import Deferred, DeferredList from twisted.python.failure import Failure from twisted.trial.unittest import TestCase import smartanthill.litemq.exchange as ex from smartanthill.exceptio...
ck(m, p): self.g_resent_nums += 1 return 1/0 def _errback(result): self.assertNotIsInstance(result, Failure) self.assertIsInstance(result, bool) self.assertEqual(result, False) self.assertEqual(self.g_resent_nums, 1) q = ex.Queue(...
{"foo": "bar"}) self.assertIsInstance(d, Deferred) d.addBoth(_errback) return d def test_exchange_direct(self): message, properties = "Test message", {"foo": "bar"} def _callback(m, p): self.assertEqual(m, message) self.assertEqual(p, properties) ...
kichkasch/pisi
modules/contacts_opimd.py
Python
gpl-3.0
12,467
0.010588
""" Syncronize with OPIMD General information about opimd is available here (L{http://wiki.openmoko.org/wiki/Opimd}). This file is part of Pisi. Pisi 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 vers...
= '' if type(atts[attName]) == list: # return values may be lists when returned; in case simply go for first entry atts[attName] = atts[attName][0] def load(self): """ Loads all attributes for all contact entries from the OPIMD backend For each entry a new L{
contacts.contacts.Contact} instance is created and stored in the instance dictionary L{contacts.AbstractContactSynchronizationModule._allContacts}. """ pisiprogress.getCallback().verbose("OPIMD: Loading") bus = dbus.SystemBus(mainloop = e_dbus.DBusEcoreMainLoop()) dbusObject = bus.get_...
sharmer/sixtalk
stkserver/python/stksocket.py
Python
gpl-2.0
8,920
0.042377
#!/usr/bin/env python import socket import struct import stkuser from stkutil import running, socklist, updateinfo STK_SERVER_PORT = 9007 STK_MAX_CLIENTS = 30 STK_MAX_PACKET_SIZE = 65535 STK_MAGIC = 'ST' STK_VERSION = 0x0001 STK_CLIENT_FLAG = 0x00 STK_SERVER_FLAG = 0x01 STK_END = 0x07 COMMANDS =...
urn True def get_stk_uid(self): return self.sp['uid'] def
get_stk_cmd(self): return self.sp['cmd'] def get_stk_sid(self): return self.sp['sid'] def get_stk_len(self): return self.sp['length'] def get_stk_data(self): return self.sp['data'] def show_stk_head(self): print 'Magic: %s' % self.sp['magic'] print 'Version: 0x%04x' % self.sp['version'] print 'Com...
meddius/yubisaslauthd
yubico/yubico.py
Python
bsd-3-clause
11,064
0.001085
# -*- coding: utf-8 -*- # # Name: Yubico Python Client # Description: Python class for verifying Yubico One Time Passwords (OTPs). # # Author: Tomaž Muraus (http://www.tomaz-muraus.info) # License: BSD #
# Requirements: # - Python >= 2.5 import re import os import sys import time import socket import urllib import urllib2 import hmac import base64 import hashlib import threading import logging import traceback from otp import OTP from yubico_exceptions import * try: import httplib_ssl except ImportError: htt...
logging.getLogger('face') FORMAT = '%(asctime)-15s [%(levelname)s] %(message)s' logging.basicConfig(format=FORMAT) API_URLS = ('api.yubico.com/wsapi/2.0/verify', 'api2.yubico.com/wsapi/2.0/verify', 'api3.yubico.com/wsapi/2.0/verify', 'api4.yubico.com/wsapi/2.0/verify', ...
spatialdev/PMT
Database/Installation/executeSql.py
Python
apache-2.0
539
0.040816
#!/usr/bin/python # -*- coding: utf-8 -*- import psycopg2 import json import urllib import urllib2 import sys con = None con = psycopg2.connect("host='54.227.245.32' port='5432'
dbname='pmt' user='postgres' password='postgres'") cnt = 0 sqlFile = sys.argv[1] print 'Argument List:', str(sys.argv[1]) try: cur = c
on.cursor() for line in file(sqlFile, 'r'): cnt = cnt + 1 cur.execute(line.strip()) print cnt con.commit() except Exception, e: print 'Error %s' % e finally: if con: con.close()
coder-james/mxnet
example/image-classification/symbols/resnet-v1.py
Python
apache-2.0
8,907
0.010666
''' Adapted from https://github.com/tornadomeet/ResNet/blob/master/symbol_resnet.py (Original author Wei Wu) by Antti-Pekka Hynninen Implementing the original resnet ILSVRC 2015 winning network from: Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun. "Deep Residual Learning for Image Recognition" ''' import mxnet as ...
units in each stage num_stages : i
nt Number of stage filter_list : list Channel size of each stage num_classes : int Ouput size of symbol dataset : str Dataset type, only cifar10 and imagenet supports workspace : int Workspace used in convolution operator """ num_unit = len(units) asse...
rebost/django
tests/regressiontests/forms/tests/util.py
Python
bsd-3-clause
3,188
0.008475
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.core.exceptions import ValidationError from django.forms.util import flatatt, ErrorDict, ErrorList from django.test import TestCase from django.utils.safestring import mark_safe from django.utils.translation import ugettext_lazy class FormsU...
>') # Can take a mixture in a list. self.assertHTMLEqual(str(ErrorList(ValidationError(["First error.", "Not \u03C0.", ugettext_lazy("Error.")]).messages)), '<ul class="errorlist"><li>First error.</li><li>Not π.</li><li>Error.</li></ul>') class VeryBadError:
def __unicode__(self): return "A very bad error." # Can take a non-string. self.assertHTMLEqual(str(ErrorList(ValidationError(VeryBadError()).messages)), '<ul class="errorlist"><li>A very bad error.</li></ul>') # Escapes non-safe input but not input marked saf...
npuichigo/ttsflow
third_party/tensorflow/tensorflow/python/grappler/layout_optimizer_test.py
Python
apache-2.0
3,838
0.010422
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
urn random_ops.truncated_normal(shape, seed=0, stddev=0.1) def bias(shape): """bias generates a bias of a given shape.""" return constant_op.constant(0.1, shape=shape) def conv2d(x, w): """conv2d returns a 2d convolution layer with full stride.""" return nn.conv2d(x, w, strides=[1, 1, 1, 1], padding='SAME')...
wnsamples a feature map by 2X.""" return nn.max_pool( x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') # Taken from tensorflow/examples/tutorials/mnist/mnist_deep.py def two_layer_model(): random_seed.set_random_seed(0) x = random_ops.truncated_normal([1, 784], seed=0) x_image = array_ops.re...
wesm/statsmodels
scikits/statsmodels/datasets/macrodata/data.py
Python
bsd-3-clause
3,085
0.004538
"""United States Macroeconomic data""" __docformat__ = 'restructuredtext' COPYRIGHT = """This is public domain.""" TITLE = __doc__ SOURCE = """ Compiled by Skipper Seabold. All data are from the Federal Reserve Bank of St. Louis [1] except the unemployment rate which was taken from the National Bureau of...
- End of the quarter consumer price index for all urban consumers: all items (1982-84 = 100, seasonally adjusted). m1 - End of the quarter M1 nominal money stock (Seasonally adjusted) tbilrate - Quarterly monthly aver
age of the monthly 3-month treasury bill: secondary market rate unemp - Seasonally adjusted unemployment rate (%) pop - End of the quarter total population: all ages incl. armed forces over seas infl - Inflation rate (ln(cpi_{t}/cpi_{t-1}) * 400) realint ...
spiceqa/virt-test
qemu/tests/kexec.py
Python
gpl-2.0
4,019
0
import logging import os from autotest.client.shared import error from virttest import data_dir @error.context_aware def run_kexec(test, params, env): """ Reboot to new kernel through kexec command: 1) Boot guest with x2apic cpu flag. 2) Check x2apic enabled in guest if need. 2) Install a new kern...
if not x2apic_enabled: raise error.TestFail("x2apic is not enabled in guest.") def install_new_kernel(): error.context("Install a new kernel in guest", logging.info) try: # pylint: disable=E0611 from qemu.tests import rh_kernel_update rh_kernel_...
a new kernel in " "guest: %s" % detail) vm = env.get_vm(params["main_vm"]) vm.verify_alive() login_timeout = int(params.get("login_timeout", 360)) session = vm.wait_for_login(timeout=login_timeout) cmd_timeout = int(params.get("cmd_timeout", 360)) check_x2apic...
coreboot/chrome-ec
extra/tigertool/ecusb/tiny_servod.py
Python
bsd-3-clause
1,767
0.00283
# Copyright 2020 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # # Ignore indention messages, since legacy scripts use 2 spaces instead of 4. # pylint: disable=bad-indentation,docstring-section-indent # pylint: disable...
f.close()
self._init() def close(self): """Close out the connection and release resources. Note: if another TinyServod process or servod itself needs the same device it's necessary to call this to ensure the usb device is available. """ self.suart.close()
oihane/odoo-addons
resource_time/models/resource_calendar.py
Python
agpl-3.0
2,606
0
# Copyright 2019 Oihane Crucelaegui - AvanzOSC # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from datetime import datetime, timedelta from pytz import timezone, utc from odoo import api, fields, models class ResourceCalendar(models.Model): _inherit = 'resource.calendar' hour_gap = f...
_to') def _compute_hour_gap(self): today
= fields.Date.context_today(self) year, week_num, day_of_week = today.isocalendar() start_dt = datetime.strptime( '{}-W{}-1'.format(year, week_num-1), "%Y-W%W-%w").replace( tzinfo=utc) end_dt = start_dt + timedelta(days=7, seconds=-1) for record in self: ...
onaio/kpi
kpi/forms.py
Python
agpl-3.0
1,879
0.000532
# coding: utf-8 from django import forms from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ from registration import forms as registration_forms from kobo.static_lists import SECTORS, COUNTRIES USERNAME_REGEX = r'^[a-z][a-z0-9_]+$' USERNAME_MAX_LENGTH = 30 USERNAME_INV...
country = forms.ChoiceField( label=_('Country'), required=False, choices=(('', ''),) + COUNTRIES, ) class Meta: model = User fields = [ 'name', 'organization', 'username', 'email', 'sector', 'countr...
priestc/MultiExplorer
multiexplorer/wallet/migrations/0003_auto_20160423_0502.py
Python
mit
456
0
#
-*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-04-23 05:02 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('wallet', '0002_auto_20160418_0334'), ] operations = [ migrations.RenameField( ...
]
meteoswiss-mdr/monti-pytroll
scripts/demo_satpy_ndvi_decorate.py
Python
lgpl-3.0
7,498
0.015071
#from satpy import Scene from satpy.utils import debug_on debug_on() #from glob import glob #base_dir="/data/COALITION2/database/meteosat/radiance_HRIT/case-studies/2015/07/07/" #import os #os.chdir(base_dir) #filenames = glob("*201507071200*__") #print base_dir #print filenames ##global_scene = Scene(reader="hrit_ms...
array[ls
mask[:,:,0]==0]=np.nan local_scene["ndvi"].data = da.from_array(ndvi_numpyarray, chunks='auto') #local_scene["ndvi"].data = local_scene["ndvi"].data.where(lsmask!=0) colorized=True if not colorized: #local_scene.save_dataset('ndvi', './ndvi_'+area+'.png') local_scene.save_dataset('ndvi', './ndvi_'+area+'.pn...
sjsucohort6/openstack
python/venv/lib/python2.7/site-packages/keystoneauth1/loading/base.py
Python
mit
3,953
0
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
name): """Retrieve a plugin class by its entrypoint name. :param str name: The name of the object to get. :returns: An auth plugin class. :rtype: :py:class:`keystoneauth1.loading.BaseLoader` :raises keystonauth.exceptions.NoMatchingPlugin: if a plugin cannot be ...
rManager(namespace=PLUGIN_NAMESPACE, invoke_on_load=True, name=name) except RuntimeError: raise exceptions.NoMatchingPlugin(name) return mgr.driver def get_plugin_options(name): """Get the options for a specific plugin. ...
samiWaheed/nvme-cli
tests/nvme_compare_test.py
Python
gpl-2.0
3,106
0
# Copyright (c) 2015-2016 Western Digital Corporation or its affiliates. # # 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 versio...
txt" self.write_file = self.test_log_dir + "/" + self.write_file self.create_data_file(self.write_file, self.data_size, "15") self.create_data_file(self.compare_file, self.data_size,
"25") def __del__(self): """ Post Section for TestNVMeCompareCmd """ TestNVMeIO.__del__(self) def nvme_compare(self, cmp_file): """ Wrapper for nvme compare command. - Args: - cmp_file : data file used in nvme compare command. - Returns: ...
Karaage-Cluster/karaage-admin
manage.py
Python
gpl-3.0
201
0
#!/usr/bin/env python import os from django.core import managem
ent os.environ['DJANG
O_SETTINGS_MODULE'] = 'kgadmin.conf.settings' if __name__ == "__main__": management.execute_from_command_line()
qisanstudio/qsapp-riitc
src/riitc/panel/channel.py
Python
mit
2,269
0
# -*- coding: utf-8 -*- from __future__ import unicode_litera
ls from wtforms import validators from jinja2 import Markup from studio.core.engines import db from riitc.mod
els import NaviModel, ChannelModel from .base import BaseView from .forms import CKTextAreaField class Navi(BaseView): column_labels = {'name': '名称', 'channels': '频道列表'} column_list = ['id', 'name', 'channels', 'date_created'] def _list_channels(self, context, model, name): lis = '' for...
IQSS/miniverse
dv_apps/ingest/apps.py
Python
mit
128
0
from __future__ import unicode_literals from django.apps import AppCo
nfig
class IngestConfig(AppConfig): name = 'ingest'
onshape-public/onshape-clients
python/onshape_client/oas/models/btp_literal_boolean255.py
Python
mit
9,062
0.00011
# coding: utf-8 """ Onshape REST API The Onshape REST API consumed by all clients. # noqa: E501 The version of the OpenAPI document: 1.113 Contact: api-support@onshape.zendesk.com Generated by: https://openapi-generator.tech """ from __future__ import absolute_import import re # noqa: F401 im...
), # noqa: E501 "space_before": (btp_space10.BTPSpace10,), # noqa: E501 "space_default": (bool,), # noqa: E501 "start_source_location": (int,), # noqa: E501 } @staticmethod def discriminator(): return None attribute_map = { "bt_type": "btType...
E501 "atomic": "atomic", # noqa: E501 "documentation_type": "documentationType", # noqa: E501 "end_source_location": "endSourceLocation", # noqa: E501 "node_id": "nodeId", # noqa: E501 "short_descriptor": "shortDescriptor", # noqa: E501 "space_after": "spaceAfter", ...
tp81/openmicroscopy
components/tools/OmeroPy/src/omero/install/jvmcfg.py
Python
gpl-2.0
15,795
0.000253
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2014 Glencoe Software, Inc. All Rights Reserved. # Use is subject to license terms supplied in LICENSE.txt # # 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 # th...
urn # No way to strip if smaller if key[0:psz] == prefix and key[ksz-ssz:] == suffix: newk
ey = key[psz:ksz-ssz] if len(newkey) == limit: newkey = ".".join(newkey) rv[newkey] = v for k, v in map.items(): __strip_dict(k, v, prefix, suffix, rv) return rv class StrategyRegistry(dict): def __init__(self, *args, **kwargs): super(dict, sel...
icaoberg/cellorganizer-galaxy-tools
datatypes/converters/fasta_to_len.py
Python
gpl-3.0
1,377
0.02106
#!/usr/bin/env python """ Input: fasta, int Output: tabular Return titles with lengths of corresponding seq """ import sys assert sys.version_info[:2] >= ( 2, 4 ) def compute_fasta_length( fasta_file, out_file, keep_first_char, keep_first_word=False ): infile = fasta_file out = open( out_file, 'w') keep...
st_char ], seq_len ) ) else: first_entry = False fasta_title = line seq_len = 0 else: seq_len += len(line) # last fasta-entry if keep_first_word: fasta_title = fasta_title.split()[0] out.write( "%s\t%d\n" % ( fasta_title[ 1:kee...
v[1], sys.argv[2], sys.argv[3], True )
sanchopanca/rcblog
rcblog/user.py
Python
mit
509
0
class User(object): _instance = None
def __new__(cls, *args): if not cls._instance: cls._instance = super(User, cls).__new__(cls, *args) return cls._instance @property def is_authenticated(self): return True @property def is_active(self): return True @property def is_anonymous(self)...
return User()
NicolasBi/super_converter
sconv/lib/gui/convertwidget/speed.py
Python
gpl-3.0
631
0
import tkinter as tk from .convertwidget import ConvertWidget class SpeedWidget(ConvertWidget): ""
"Widget used to convert weight and mass units Attributes: root The Frame parent of the widget. """ def __init__(self, root): super(SpeedWidget, self).__init__(root) self.root = root self._init_frames()
self._init_binds() def _init_frames(self): # Creation of the main frame f_main = tk.Frame(self.root) f_main.pack(fill="both", expand="yes", side=tk.TOP) def _init_binds(self): pass if __name__ == '__main__': pass
xiaolihope/PerfKitBenchmarker-1.7.0
perfkitbenchmarker/data/__init__.py
Python
apache-2.0
6,390
0.007355
# Copyright 2014 PerfKitBenchmarker Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
dir(path): loaders.append(FileResourceLoader(path)) loaders.extend(DEFAULT_RESOURCE_LOADERS) return loaders def ResourcePath(resource_name, search_user_paths=T
rue): """Gets the filename of a resource. Loaders are searched in order until the resource is found. If no loader provides 'resource_name', an exception is thrown. If 'search_user_paths' is true, the directories specified by "--data_search_paths" are consulted before the default paths. Args: resource...
datalogics/scons
test/Rpcgen/RPCGEN.py
Python
mit
4,064
0.000984
#!/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, ...
run() output = "myrpcgen.py %s -o %s rpcif.x\nmyrpcgen.py\n" expect_clnt = output % ('-l', test.workpath('rpcif_clnt.c')) expect_h = output % ('-h', test.workpath('rpcif.h')) expect_svc = output % ('-m', test.workpath('rpcif_svc.c')) expect_xdr = output
% ('-c', test.workpath('rpcif_xdr.c')) test.must_match('rpcif_clnt.c', expect_clnt) test.must_match('rpcif.h', expect_h) test.must_match('rpcif_svc.c', expect_svc) test.must_match('rpcif_xdr.c', expect_xdr) rpcgen = test.where_is('rpcgen') if rpcgen: test.subdir('do_rpcgen') test.write('SConstruct', """\...
fabricehong/zim-desktop
zim/gui/templateeditordialog.py
Python
gpl-2.0
5,701
0.029118
# -*- coding: utf-8 -*- # Copyright 2012 Jaap Karssenberg <jaap.karssenberg@gmail.com> import gtk from zim.fs import TrashNotSupportedError from zim.config import XDG_DATA_HOME, data_file from zim.templates import list_template_categories, list_templates from zim.gui.widgets import Dialog, BrowserTreeView, Button, ...
nsitive if only a default custom, default = self.view.get_selected() for butto
n in self._buttonbox.get_children(): button.set_sensitive(custom is not None) if custom is None: return if not custom.exists(): self._delete_button.set_sensitive(False) def on_view(self, *a): # Open the file, witout waiting for editor to return custom, default = self.view.get_selected() if custom...
im0rtel/OpenBazaar
tests/test_migrations_util.py
Python
mit
1,060
0.000943
im
port unittest from db.migrations import migrations_util class TestMigrationUtil(unittest.TestCase): """Test the CLI API.""" @classmethod def setUpClass(cls): cls.db_path = '/some/random/path/file.db' def setUp(self): self.parser = migrations_util.make_argument_parser(self.db_path) ...
options = self.parser.parse_args(['upgrade']) self.assertEqual(options.path, self.db_path) self.assertEqual(options.action, 'upgrade') def test_cli_parser_user(self): other_db_path = '/some/other/path/file.db' options = self.parser.parse_args([ 'downgrade', ...
Cloudzero/cloudzero-reactor-aws
reactor/features/cloudtrail_event_source/ingest_plugins/ec2/network_interface.py
Python
bsd-3-clause
2,385
0.002935
# -*- coding: utf-8 -*- # Copyright (c) 2016-present, CloudZero, Inc. All rights reserved. # Licensed under the BSD-style license. See LICENSE file in the project root for full license information. """ Plugin used to extract all contextual information we can from EC2 network-interface (ENI) Cloudtrail Events. """ imp...
: """ Given a partially-normalized CZ-NEF event, extract all useful resources and transform it into full CZ-NEF Args: first_pass_normalized_event (dict): A partially-processed CZ-NEF event. This version will have some of the general-purpose fields normali...
he specifics will be missing. Returns: dict - the fully normalized CZ-NEF event """ event_name = first_pass_normalized_event['event_name'] logger.debug(f'Running plugin for {event_name}') normalized_event = { **first_pass_normalized_event, 'service_type': 'ec2', 're...
deontp/misc
zenoic_api/cve-search-master/web/advanced_api.py
Python
gpl-3.0
7,190
0.017524
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Minimal web interface to cve-search to display the last entries # and view a specific CVE. # # Software is free software released under the "Modified BSD license" # # Copyright (c) 2017 Pieter-Jan Moreels - pieterjan.moreels@gmail.com # imports import json import os...
'f': self.api_admin_add_blacklist}, {'r': '/api/admin/whitelist/remove', 'm': ['PUT'], 'f': self.api_admin_remove_whitelist}, {'r': '/api/admin/blacklist/remove', 'm': ['PUT'], 'f': self.api_admin_remove_blacklist}, {'r': '/api/admin/get_token', 'm': ['GET'], 'f': s...
admin/new_token', 'm': ['GET'], 'f': self.api_admin_generate_token}, {'r': '/api/admin/get_session', 'm': ['GET'], 'f': self.api_admin_get_session}, {'r': '/api/admin/start_session', 'm': ['GET'], 'f': self.api_admin_start_session}, {'r': '/api/admin/updatedb'...
andrewsosa/hackfsu_com
api/api/models/wifi_cred.py
Python
apache-2.0
879
0.002275
from django.db import models from django.contrib.auth.models import User from django.contrib import admin from api.models import Hackathon from hackfsu_com.admin import hackfsu_admin
class WifiCred(models.Model): hackathon = models.ForeignKey(to=Hackathon, on_delete=models.CASCADE) username = models.CharField(max_length=100) password = models.CharField(max_length=100) assigned_user = models.OneToOneField(User, on_del
ete=models.SET_NULL, default=None, null=True, blank=True) def __str__(self): return '[WifiCred {}]'.format(self.username) @admin.register(WifiCred, site=hackfsu_admin) class WifiCredAdmin(admin.ModelAdmin): list_filter = ('hackathon',) list_display = ('username', 'assigned_user',) list_editab...
google-research/federated
fedopt_guide/cifar10_resnet/federated_cifar10.py
Python
apache-2.0
5,796
0.004313
# Copyright 2021, Google LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
sed for the task. It then uses `iterative_process_builder` to create an iterative process that it applies to the task, using `federated_research.utils.training_loop`. We assume that the iterative process has the following functional type signatures: * `initialize`: `( -> S@SERVER)` where `S` represents ...
the server state, `{B*}` represents the client datasets, and `T` represents a python `Mapping` object. The iterative process must also have a callable attribute `get_model_weights` that takes as input the state of the iterative process, and returns a `tff.learning.ModelWeights` object. Args: itera...
apache/libcloud
libcloud/backup/base.py
Python
apache-2.0
15,294
0.001177
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use ...
. :type target: :
class:`.BackupTarget` :param driver: BackupDriver instance. :type driver: :class:`.BackupDriver` :param extra: (optional) Extra attributes (driver specific). :type extra: ``dict`` """ self.id = str(id) if id else None self.status = status self.progress =...
chaosct/GestureAgents
GestureAgentsPygame/Mouse.py
Python
mit
1,272
0
#!/usr/bin/env python # -*- coding: utf-8 -*- from GestureAgentsTUIO.Tuio import TuioAgentGenerator import GestureAgentsPygame.Screen as Screen from pygame.locals import * class MouseAsTuioAgentGenerator(object): def __init__(self): self.pressed = False self.myagent = None self.sid = -1...
ent(self.myagent, e) self
.myagent.newAgent(self.myagent) self.myagent.newCursor(self.myagent) elif e.type == MOUSEBUTTONUP: self.pressed = False self._updateAgent(self.myagent, e) self.myagent.removeCursor(self.myagent) self.myagent.finish() self.myagent = None ...
thethomaseffect/travers-media-tools
django_filepicker/forms.py
Python
mit
4,508
0.003327
from django import forms from django.core.files import File from django.conf import settings from .widgets import FPFileWidget import urllib2 try: from cStringIO import StringIO except ImportError: from StringIO import StringIO class FPFieldMixin(): widget = FPFileWidget default_mimetypes = "*/*" ...
idget_attrs(self, widget):
attrs = { 'data-fp-apikey': self.apikey, 'data-fp-mimetypes': self.mimetypes, } if self.services: attrs['data-fp-option-services'] = self.services if self.additional_params: attrs = dict(attrs.items() + self.additional_params.it...
ryu22e/algorithm1000
ishi/ishi1.py
Python
mit
922
0.001337
#!/usr/bin/env python # -*- codi
ng: utf-8 -*- import sys """ 「石取りゲーム1」(「C言語による最新アルゴリズム事典」6ページより) """ def get_num(message): sys.stdout.write(message) n = '' while (not n.isdigit()):
n = raw_input() return int(n) n = get_num(u"石の数?") m = get_num(u"1回に取れる最大の石の数?") if (n < 1 or m < 1): sys.exit(1) my_turn = True while(n != 0): if (my_turn): x = (n - 1) % (m + 1) if (x == 0): x = 1 print(u"私は%d個の石を取ります." % x) else: r = False while (n...
mmcauliffe/linguistic-helper-functions
linghelper/phonetics/vowels/mahalanobis.py
Python
gpl-3.0
11,375
0.008176
import numpy as np ### 1: IH ### 2: EH ### 3: AE ### 4: AO ### 6: AH ### 7: UH ### ### 11: iyC beat ### 12: iyF be ### 21: eyC bait ### 22: eyF bay ### 41: ayV buy ### 47: ayO bite ### 61: oy boy ### 42: aw bough ### 62: owC boat ### 63: owF bow ### 72: uwC boot ### 73: uwF too ### 82: iw suit ### 43: ah father ### 53...
.542, 4.40423, 4.894037], '22': [592.5507, 1959.899, 4.087865, 4.802181], '24': [569.8613, 1991.994, 4.516866, 4.941955], '33': [620.1378, 2059.224, 4.347911, 5.027536], '39': [766.087, 1829.261, 4.693657, 5.013284], '41': [808.0645, 144...
5.007045], '43': [780.8631, 1326.295, 4.705, 4.908504], '44': [718.2819, 1273.59, 4.702502, 4.840136], '47': [777.8737, 1478.317, 4.718795, 4.919554], '53': [740.2186, 1167.617, 4.744859, 4.794929], '54': [557.1122, 975.9273, 4.660808, ...
dpazel/music_rep
transformation/functions/tonalfunctions/tonality_permutation.py
Python
mit
830
0.003614
""" File: tonal_permutation.py Purpose: Class defining a function on one tonality based on a permatuation specification. """ from transformation.functions.tonalfunctions.tonal_permutation import TonalPermutation class TonalityPermutation(TonalPermutation): ""
" Class implementation of a permutation on a set of tones. More restrictive than Permutation, in that tones of a given tonality are the elements of the permutation. """ def __init__(self, tonality, cycles=list()): """ Constructor :param tonality: :param cycles: "...
nalPermutation.__init__(self, cycles, domain_tones) @property def tonality(self): return self._tonality
indictranstech/erpnext
erpnext/non_profit/doctype/member/member.py
Python
agpl-3.0
738
0.01897
# -*- coding: utf-8 -*- # Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt from __future__ import unicode_literals from frappe.model.document import Document from frappe.contacts.address_and_contact import load_address_and_contact STANDARD_USERS = ("...
Load address and contacts in `__onload`""" load_address_and_contact(self) def validate(self): if self.name not in STANDARD_USERS: self.validate_email_type(self.email) self.validate_email_type(self.name) def validate_email_type(self, email): from frappe.utils import validate_email_add validate_email_...
True)
jonrf93/genos
dbservices/tests/functional_tests/steps/user_service_steps.py
Python
mit
1,685
0.003561
from behave import given, when, then from genosdb.models import User from genosdb.exceptions import UserNotFound # 'mongodb://localhost:27017/') @given('a valid user with values {userna
me}, {password}, {email}, {first_name}, {last_name}') def step_impl(context, username, passwo
rd, email, first_name, last_name): context.base_user = User(username=username, email=email, password=password, first_name=first_name, last_name=last_name) @when('I add the user to the collection') def step_impl(context): context.user_service.save(context.base_user) @then('I check {us...
zyga/arrowhead
arrowhead/inspector.py
Python
bsd-3-clause
6,120
0.000163
import sys from arrowhead.core import Step from arrowhead.core import ErrorArrow from arrowhead.core import NormalArrow from arrowhead.core import ValueArrow def print_flow_state(flow, active_step_name=None, file=sys.stdout): """ Display the state of a given flow. :param flow: A Flow, instance o...
];'.format( step.Meta.name, "box", step.Meta.label.replace('"', '\\"
') ), file=file) for arrow in step.Meta.arrows: if isinstance(arrow, NormalArrow): print('\t{} -> {};'.format( step.Meta.name, arrow.target ), file=file) elif isinstance(arrow, ValueArrow): print('\t{} -> {} ...
m-wichmann/pyCheck
src/ifJUnit.py
Python
lgpl-3.0
1,199
0.000834
#!/us
r/bin/env python3 # -*- coding: utf-8 -*- """This file contains everything needed to interface with JUnit""" ##### # pyCheck # # Copyright 2012, erebos42 (https://github.com/erebos42/miscScripts) # # This is free software; you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public Lice...
the Free Software Foundation; either version 2.1 of # the License, or (at your option) any later version. # # This software 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 # Lesser Gen...
vodik/pacman
test/pacman/tests/clean002.py
Python
gpl-2.0
615
0
self.descript
ion = "CleanMethod = KeepCurrent" sp = pmpkg("dummy", "2.0-1") self.addpkg2db("sync", sp) sp = pmpkg("bar", "2.0-1") self.addpkg2db("sync", sp) sp = pmpkg("baz", "2.0-1") self.addpkg2db("sync", sp) lp = pmpkg("dummy", "1.0-1") self.addpkg2db("local", lp) lp = pmpkg("bar", "2.0-1") self.addpkg2db("local", lp) self...
le("!CACHE_EXISTS=dummy|1.0-1") self.addrule("CACHE_EXISTS=bar|2.0-1") self.addrule("CACHE_EXISTS=baz|2.0-1")
luotao1/Paddle
python/paddle/fluid/tests/unittests/test_maxout_op.py
Python
apache-2.0
5,104
0.001763
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
): # test paddle.nn.Maxout, paddle.nn.functional.maxout def setUp(self): self.x_np
= np.random.uniform(-1, 1, [2, 6, 5, 4]).astype(np.float64) self.groups = 2 self.axis = 1 self.place=paddle.CUDAPlace(0) if core.is_compiled_with_cuda() \ else paddle.CPUPlace() def test_static_api(self): with paddle.static.program_guard(paddle.static.Program()): ...
miroag/mfs
setup.py
Python
mit
2,863
0.001048
#!/usr/bin/env python # -*- encoding: utf-8 -*- from __future__ import absolute_import from __future__ import print_function import io import re from glob import glob from os.path import basename from os.path import dirname from os.path import join from os.path import splitext from setuptools import find_packages fro...
rd1', 'keyword2', 'keyword3', ], i
nstall_requires=[ 'beautifulsoup4', 'requests', 'aiohttp', 'tqdm', 'docopt' ], setup_requires=[ 'pytest-runner', ], tests_require=[ 'pytest', ], extras_require={ # eg: # 'rst': ['docutils>=0.11'], # ':python_version=="2.6"': ['argparse'], }...
nuagenetworks/vspk-python
vspk/v6/nuvmresync.py
Python
bsd-3-clause
11,928
0.00897
# -*- coding: utf-8 -*- # # Copyright (c) 2015, Alcatel-Lucent Inc, 2017 Nokia # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyrigh...
>>> vmresync = NUVMResync(data=my_dict) """ super(NUVMResync, self).__init__() # Read/Write Attributes
self._last_request_timestamp = None self._last_time_resync_initiated = None self._last_updated_by = None self._last_updated_date = None self._embedded_metadata = None self._entity_scope = None self._creation_date = None self._status = None sel...
dermute/ansible
lib/ansible/executor/task_queue_manager.py
Python
gpl-3.0
11,908
0.002939
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) an...
= tempfile.TemporaryFile() def _initialize_processes(self, num): self._workers = [] for i in range(num): main_q = multiprocessing.Queue() rslt_q = multiprocessing.Queue() self._workers.append([None, main_q, rslt_q]) self._result_prc = ResultProcess(sel...
s): ''' Clears and initializes the shared notified handlers dict with entries for each handler in the play, which is an empty array that will contain inventory hostnames for those hosts triggering the handler. ''' # Zero the dictionary first by removing any entries there...
chrxr/wagtail
wagtail/wagtailforms/models.py
Python
bsd-3-clause
9,515
0.001261
from __future__ import absolute_import, unicode_literals import json import os from django.contrib.contenttypes.models import ContentType from django.core.serializers.json import DjangoJSONEncoder from django.db import models from django.shortcuts import render from django.utils.encoding import python_2_unicode_compa...
add=True) def get_data(self): """ Returns dict with form data. You can override this method to add additional data. """
form_data = json.loads(self.form_data) form_data.update({ 'submit_time': self.submit_time, }) return form_data def __str__(self): return self.form_data class Meta: abstract = True verbose_name = _('form submission') class FormSubmission(Abstra...
rwatson/chromium-capsicum
chrome/tools/extract_actions.py
Python
bsd-3-clause
4,264
0.010319
#!/usr/bin/python # Copyright (c) 2009 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. """Extract UserMetrics "actions" strings from the Chrome source. This program generates the list of known actions we expect to see in ...
'..', 'webkit', 'glue', 'editor_client_impl.cc') for line in open(editor_file
): match = action_re.search(line) if match: # Plain call to RecordAction actions.add(match.group(1)) def GrepForActions(path, actions): """Grep a source file for calls to UserMetrics functions. Arguments: path: path to the file actions: set of actions to add to """ action_re = re.compi...
skyportsystems/kafka-python
setup.py
Python
apache-2.0
990
0
import os.path import sys from setuptools import setup, Command class Tox(Command): user_options = [] def initialize_options(self): pass
def finalize_options(self): pass def run(self): import tox sys.exit(tox.cmdline([])) setup( name="kafka-python", version="0.9.0", install_requires=["distribute"], tests_require=["tox"], cmdclass={"test": Tox}, packages=["kafka"], author="David Arthur", ...
ght 2012, David Arthur under Apache License, v2.0", description="Pure Python client for Apache Kafka", long_description=""" This module provides low-level protocol support for Apache Kafka as well as high-level consumer and producer classes. Request batching is supported by the protocol as well as broker-aware ...
OriHoch/Open-Knesset
auxiliary/migrations/0007_auto__add_feedback.py
Python
bsd-3-clause
5,930
0.007757
# -*- coding: 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): # Adding model 'Feedback' db.create_table(u'auxiliary_feedback', ( (u'id', self.gf('django.db.mo...
('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'ordering': ('djang
o.db.models.fields.IntegerField', [], {'default': '20', 'db_index': 'True'}), 'photo': ('django.db.models.fields.files.ImageField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'suggested_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'...
gazeti/aleph
aleph/migrate/versions/9c92c85163a9_events.py
Python
mit
1,959
0.011741
"""events Revision ID: 9c92c85163a9 Revises: 666668eae682 Create Date: 2016-05-09 19:04:44.498817 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = '9c92c85163a9' down_revision = '666668eae682' def upgrade(): op.cre...
sa.Column('data', postgresql.JSONB(), nullable=True), sa.Column('created_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True), sa.PrimaryKeyConstraint('id') ) op.drop_table('processing_log') def downgrade(): op.create_table('processing_log', sa.
Column('created_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True), sa.Column('updated_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True), sa.Column('id', sa.BIGINT(), nullable=False), sa.Column('operation', sa.VARCHAR(), autoincrement=False, nullable=True), sa.Column('compon...
KevinMidboe/statusHandler
plex/tmdb.py
Python
mit
1,451
0.026189
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Author: KevinMidboe # @Date: 2017-02-08 14:00:04 # @Last Modified by: KevinMidboe # @Last Modified time: 2017-02-16 17:08:08 import requests from pprint import pprint try: from plexSearch import plexSearch except ImportError: from plex.plexSearch import plexSearc...
:str(page), } header = {'Accept': 'application
/json'} try: r = requests.get("https://api.themoviedb.org/3/search/multi", params=payload, headers=header) except requests.exceptions.ConnectionError: return {"errors": "Could not connecting to: tmdb.com"} except requests.exceptions.Timeout: return {"errors": "Request timed out."} except requests.exceptions....
Jspsun/LEETCodePractice
Python/BinaryTreeLevelOrderTraversal2.py
Python
mit
687
0.002911
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def levelOrderBottom(self, root): list =
[] self.helper(list, root, 0) return list[::-1] def helper(self, list, root, level): if root == None: return if level >= len(list): list.append([]) list[level].append(root.val) self.helper(list, root.left, level + 1
) self.helper(list, root.right, level + 1) from TestObjects import * b = BinaryTree() s = Solution() print s.levelOrderBottom(b.root)
jokey2k/sentry
tests/sentry/api/endpoints/test_project_releases.py
Python
bsd-3-clause
1,979
0
from __future__ import absolute_import from datetime import datetime from django.core.urlresolvers import reverse from sentry.models import Release from sentry.testutils import APITestCase class ProjectReleaseListTest(APITestCase): def test_simple(self): self.login_as(user=self.user) team = sel...
assert
response.data['version'] assert Release.objects.filter( project=project, version=response.data['version'], ).exists()
HenrikPoulsen/Json2Class
test/testConvert.py
Python
mit
475
0.006316
import unittest from convert import convert class TestConv
ert(unittest.TestCase): def testEmptyJsonParse(self): generated = convert.parse(convert._load_json_files("./jsonSamples/minimal.json")[0]) def testGlossaryJsonParse(self): generated = convert.parse(convert._load_json_files("./jsonSamples/Glossary.json")[0]) generated = convert.generate...
(f["content"])
huiyiqun/check_mk
doc/treasures/Event_Console/snmptd_mkevent.py
Python
gpl-2.0
2,674
0.00187
#!/usr/bin/python # -*- encoding: utf-8; py-indent-offset: 4 -*- # +------------------------------------------------------------------+ # | ____ _ _ __ __ _ __ | # | / ___| |__ ___ ___| | __ | \/ | |/ / | # | | | | '_ \ / _ \/ __| |/ /...
ifth Fl
oor, # Boston, MA 02110-1301 USA. # This script is called by snmptrapd and sends # all traps to the mkeventd # # Bastian Kuhn, bk@mathias-kettner.de # If you use this script please keep in mind that this script is called # for every trap the server receives. # To use this Script, you have to configure your snmptrad.c...
085astatine/togetter
togetter/xml_tools.py
Python
mit
972
0
# -*- coding: utf-8 -*- import pathlib from typing import Union import lxml.etree def save_as_xml( element_tree: Union[lxml.etree._Element, lxml.etree._ElementTree],
filepath: Union[str, pathlib.Path], pretty_print: bool = True) -> None: """save ElementTree in the file as XML Args: element_tree (lxml.etree._ElementTree): the ElementTree to be save. filepath (str, pathlib.Path): The path of the File to be output as XML. pretty_print (bool) optio...
rue. """ if not isinstance(filepath, pathlib.Path): filepath = pathlib.Path(filepath) with filepath.open(mode='w', encoding='utf-8', newline='') as file: file.write(lxml.etree.tostring( element_tree, encoding='utf-8', pretty_print=p...
leighpauls/k2cro4
third_party/python_26/Lib/test/test_dict.py
Python
bsd-3-clause
17,651
0.005156
import unittest from test import test_support import UserDict, random, string import gc, weakref class DictTest(unittest.TestCase): def test_constructor(self): # calling built-in types without argument must return empty self.assertEqual(dict(), {}) self.assert_(dict() is not {}) def ...
class SimpleUserDict: def __init__(self): self.d = {1:1, 2:2, 3:3} def keys(self): return self.d.keys() def __getitem__(self, i): return self.d[i] d.clear() d.update(SimpleUserDict()) self.assertEqual(d, {1...
raise Exc self.assertRaises(Exc, d.update, FailingUserDict()) class FailingUserDict: def keys(self): class BogonIter: def __init__(self): self.i = 1 def __iter__(self): return self ...
akvo/akvo-rsr
akvo/rest/serializers/user.py
Python
agpl-3.0
6,303
0.002697
# -*- coding: utf-8 -*- # Akvo RSR is covered by the GNU Affero General Public License. # See more details in the license.txt file located at the root folder of the Akvo RSR module. # For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >. from django.contrib.auth import get_u...
programs = serializers.SerializerMethodField() class Meta: model = get_user_model() fields = ( 'id', 'first_name', 'last_name',
'email', 'username', 'is_active', 'is_staff', 'is_admin', 'is_support', 'is_superuser', 'can_manage_users', 'organisation', 'organisations', 'approved_employments', 'api_key', ...
slobberchops/rop
opc/drivers/echo.py
Python
gpl-3.0
455
0
from opc.drivers.baseclass import RopDriver class Driv
er(RopDriver):
""" Just pass back the raw data to the caller for rendering by the app """ def __init__(self, width, height, address): pass def putPixels(self, channel, pixels): return pixels def sysEx(self, systemId, commandId, msg): pass def setGlobalColorCorrection(self, gamma,...
sophie63/FlyLFM
stanford_lfanalyze_v0.4/lfrectify.py
Python
bsd-2-clause
3,622
0.004417
#!/usr/bin/env python2.7 # __BEGIN_LICENSE__ # # Copyright (C) 2010-2012 Stanford University. # All rights reserved. # # __END_LICENSE__ # rectify.py # # Usage: rectify.py <lightfield_image.{tif,png,etc}> [--pixels-per-lenslet <ppl>] # # This script simply applies a rectification from a # campixel_to_camlens.warp fil...
not options.calibration_file: fileName, fileExtension = os.path.splitext(filename) calibration_file = fileName + '.lfc' else: calibration_file = opt
ions.calibration_file # Default output filename has a -RECTIFIED suffix if not options.output_filename: fileName, fileExtension = os.path.splitext(filename) output_filename = fileName + '-RECTIFIED' + fileExtension else: output_filename = options.output_filen...
bayespy/bayespy
bayespy/inference/vmp/nodes/tests/test_dot.py
Python
mit
34,668
0.006202
################################################################################ # Copyright (C) 2013-2014 Jaakko Luttinen # # This file is licensed under the MIT License. ################################################################################ """ Unit tests for `dot` module. """ import unittest import nu...
linalg.outer(y, y, ndim=2), 'ij->ij', y)
# Do nothing for 2-D array Y = GaussianARD(np.random.randn(5,2,3), np.random.rand(5,2,3), plates=(5,), shape=(2,3)) y = Y.get_moments() compare_moments(y[0], y[1], 'ij->...
josircg/raizcidadanista
raizcidadanista/cms/migrations/0004_auto__add_articlecomment.py
Python
gpl-3.0
14,504
0.008274
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'ArticleComment' db.create_table('cms_articlecomment', ( ...
'article': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Article']"}), 'author': ('django.db.models.fields.CharField', [], {'max_length': '60'}), 'comment': ('django.db.models.fields.TextField', [], {}), 'created_at': ('django.db.models.fields.DateFi...
}, 'cms.filedownload': { 'Meta': {'object_name': 'FileDownload'}, 'count': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'expires_at': ('django.db.models.fields.DateTimeField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}), 'file': ('...
fieldaware/optimoroute
optimo/util.py
Python
bsd-3-clause
2,432
0.000822
# -*- coding: utf-8 -*- import json import datetime from decimal import Decimal from requests.packages.urllib3.util import parse_url from .models import BaseModel from .errors import OptimoError DEFAULT_API_VERSION = 'v1' class CoreOptimoEncoder(json.JSONEncoder): """Custom JSON encoder that knows how to ser...
ed parameters. :raises OptimoError: On providing incomplete or invalid config data """ if
not optimo_url or not isinstance(optimo_url, basestring): raise OptimoError("'optimo_url' must be a url string") validate_url(optimo_url) if not version or not isinstance(version, basestring) or not \ version.startswith('v'): raise OptimoError("'version' must be a string denoting ...
shadowmint/nwidget
lib/cocos2d-0.5.5/cocos/layer/python_interpreter.py
Python
apache-2.0
9,867
0.003142
# ---------------------------------------------------------------------------- # cocos2d # Copyright (c) 2008-2012 Daniel Moisset, Ricardo Quesada, Rayentray Tappa, # Lucio Torre # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided t...
if not self.doing_more: more = self.interpreter.execute('\n'.join(self.current_input)) if self.doing_more and not line.strip(): self.doing_more = False self.interpreter.execute('\n'.join(self.current_input)) more = more or sel...
self._write(self.prompt_more) self.start_of_line = len(self.document.text) self.caret.position = len(self.document.text) elif symbol == pyglet.window.key.SPACE: pass else: return pyglet.event.EVENT_UNHANDLED return pyglet.event.EV...
eunchong/build
scripts/slave/recipe_modules/url/example.py
Python
bsd-3-clause
743
0.012113
# Copyright 2014 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. DEPS = [ 'recipe_engine/step', 'url', ] def RunSteps(api): api.step('step1', ['/bin/echo', api.url
.join('foo', 'bar', 'baz')]) api.step('step2', ['/bin/echo', api.url.join('foo/', '/bar/', '/baz')]) api.step('step3', ['/bin/echo', api.url.join('//foo/', '//bar//', '//baz//')]) api.step('step4', ['/bin/echo', api.url.join('//foo/bar//', '//baz//')]) api.url.fetch('fake://foo/...
tch('fake://foo/bar (w/ auth)', headers={'Authorization': 'thing'}) def GenTests(api): yield api.test('basic')
fatiherikli/dbpatterns
web/dbpatterns/documents/tests.py
Python
mit
3,562
0.016844
import os import json from django.test import TestCase from documents.models import Document from docu
ments.exporters.sql import (MysqlExporter, OracleExporter, PostgresExporte
r, SQLiteExporter) TEST_DOCUMENT_PATH = os.path.join(os.path.dirname(__file__), "fixtures/test_document.json") class ExporterTestCase(TestCase): def setUp(self): self.document = Document(json.load(open(TEST_DOCUMENT_PATH))) def test_mysql_exporter(self): ""...