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
FabianKnapp/nexmon
buildtools/gcc-arm-none-eabi-5_4-2016q2-linux-x86/arm-none-eabi/lib/armv7e-m/softfp/fpv5-sp-d16/libstdc++.a-gdb.py
Python
gpl-3.0
2,501
0.006397
# -*- python -*- # Copyright (C) 2009-2015 Free Software Foundation, 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 3 of the License, or # (at your option) any later versio...
th:
sys.path.insert(0, dir_) # Call a function as a plain import would not execute body of the included file # on repeated reloads of this object file. from libstdcxx.v6 import register_libstdcxx_printers register_libstdcxx_printers(gdb.current_objfile())
High-Hill/bachelor_dap_gw
program/log_formatting.py
Python
mit
2,502
0.008947
# -*- coding: utf-8 -*- import sys import string from datetime import datetime,timedelta import calendar import csv import re # ファイルオープン(fpは引数でログファイル,wfpは書き出すcsvファイルを指定) fp = open(sys.argv[1],'r') # logがローテートするタイミングが1日の間にある場合,/var/log/kern.logと/var/log/kern.log.1の両方を読み込む必要があるかもしれない wfp = open('/path/to/program/csv_dat...
w[6] = l[19][4:] i += 1 # フ
ァイルに1行出力 writer.writerow(w) # ファイルクローズ fp.close() wfp.close()
tisspage/resume-website
website/views.py
Python
gpl-3.0
2,019
0.021351
#!/usr/bin/env python # encoding: utf-8 """ views.py Created by Christophe VAN FRACKEM on 2014/05/25. Copyright (c) 2014 Tiss'Page. All rights reserved. """ __author__ = 'Christophe VAN FRACKEM <[email protected]>' __version__= '0.0.1' __copyright__ = '© 2014 Tiss\'Page' from django.shortcuts import render_to_res...
**kwargs): context = super(ContactFormView, self).get_context_data(**kwargs) context.update(form=ContactForm() ) return context def form_valid(self, form): subject = u'Contact via le site tisspage.fr' from_email = '[email protected]' to = '[email protected]' text_content = 'Un inte...
et.' html_content = 'Un internaute vient de vous contacter via le formulaire de contact de votre site Internet.<br><br>' html_content += u'<strong>Son email :</strong><a href="mailto:{email}"> {email}</a><br>'.format(email=form.cleaned_data.get('email')) html_content += u'<strong>Son message :</strong> <br>{mess...
bdh1011/wau
venv/lib/python2.7/site-packages/ipykernel/datapub.py
Python
mit
1,761
0.003975
"""Publishing native (typically pickled) objects. """ # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from traitlets.config import Configurable from ipykernel.inprocess.socket import SocketABC from traitlets import Instance, Dict, CBytes from ipykernel.jsonutil imp...
---------- data : dict The data to be published. Think of it as a namespace. """ session = self.session buffers = serialize_object(data, buffer_threshold=session.buffer_threshold, item_threshold=session.item_threshold, ) content...
ident=self.topic, ) def publish_data(data): """publish a data_message on the IOPub channel Parameters ---------- data : dict The data to be published. Think of it as a namespace. """ from ipykernel.zmqshell import ZMQInteractiveShell ZMQInteractiveShell.instance().da...
tbdale/crystalfontz-lcd-ui
python/Action.py
Python
mit
289
0.020761
class Action: label = "" selectable = 0 def __init__ (self
,label="",s=0): self.label = label self.selectable = s def getLabel (self): return self.label def do (self): tm
p = 1 def canSelect (self): return self.selectable
eleme/archer
archer/_server.py
Python
mit
3,460
0
# -*- coding: utf-8 -*- import os import subprocess import sys import threading import time import signal from thriftpy.protocol import TBinaryProtocolFactory from thriftpy.server import TThrea
dedServer from thriftpy.thrift import TProcessor from
thriftpy.transport import TServerSocket, TBufferedTransportFactory from .logger import log _EXIT_RELOADER = 3 def restart_with_reloader(host, port): """Spawn a new Python interpreter with the same arguments as this one, but running the reloader thread. """ log('info', 'Running on {}:{} in DEBUG mo...
hzlf/openbroadcast
website/apps/actstream/migrations/0001_initial.py
Python
gpl-3.0
7,890
0.008365
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Follow' db.create_table('actstream_follow', ( ('id', self.gf('django.db.models...
'public': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'target_content_type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'target'", 'null': 'True', 'to': "orm['contenttypes.ContentType']"}), 'target_object_id': ('django.db.models.f...
ds.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'verb': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, 'actstream.follow': { 'Meta': {'unique_together': "(('user', 'content_type', 'object_id'),)", 'object_name': 'Follow'}, 'cont...
senior-zero/metanet
setup.py
Python
gpl-3.0
482
0.002075
__author__ = 'Evtushenko Georgy' from setuptools import setup, find_packages setup( name=
"metanet", version="0.1", description="Free portable library for meta neural network research", license="GPL3", packages=['metanet', 'metanet.datasets', 'metanet.networks', 'metanet.networks.nodes', 'metanet.networks.artificial_networks', 'metanet.ne
tworks.nodes', 'metanet.networks.groups', 'metanet.networks.connections'], install_requires=['numpy', 'networkx'], )
newvem/pytz
pytz/zoneinfo/Africa/Asmera.py
Python
mit
483
0.043478
'''tzinfo timezone information for Africa/Asmera.
''' from pytz.tzinfo import DstTzInfo from pytz.tzinfo import memorized_datetime as d from pytz.tzinfo import memorized_ttin
fo as i class Asmera(DstTzInfo): '''Africa/Asmera timezone definition. See datetime.tzinfo for details''' zone = 'Africa/Asmera' _utc_transition_times = [ d(1,1,1,0,0,0), d(1936,5,4,21,24,40), ] _transition_info = [ i(9300,0,'ADMT'), i(10800,0,'EAT'), ] Asmera = Asmera()
algorythmic/bash-completion
test/t/test_tail.py
Python
gpl-2.0
151
0
impo
rt pytest class TestTail: @pytest.mark.complete("tail --", require_longopt=True) def test_1(self
, completion): assert completion
naokits/adminkun_viewer_old
Server/gaeo/html5lib/treewalkers/_base.py
Python
mit
5,461
0.003662
import gettext _ = gette
xt.gettext from html5lib.constants import voidElements, spaceCharacters spaceCharacters = u"".join(spaceChar
acters) class TreeWalker(object): def __init__(self, tree): self.tree = tree def __iter__(self): raise NotImplementedError def error(self, msg): return {"type": "SerializeError", "data": msg} def normalizeAttrs(self, attrs): if not attrs: attrs = [] ...
dojojon/pygame
week5/spawn5.py
Python
mit
4,613
0.000434
#! /usr/bin/env python # import os import pygame import random from highscore import is_high_score_and_save # it is better to have an extra variable, than an extremely long line. player_img_path = 'player.png' pill_img_path = 'pill.png' boost_img_path = 'boost.png' background = pygame.image.load("space.jpg") # creat...
, 255, 0)) screen.blit(high_score_surface, (250, 350)) game_over_surface = myfont.render("Game Over", True, (255, 0, 0)) screen.blit(game_over_surface, (250, 160)) else: player.update() player.draw(screen) # draw the player to the screen
pillsGroup.update() pillsGroup.draw(screen) pygame.display.update() # update the screen clock.tick(40) # Limit the game to running at 40 frames per second
FredLoh/BotoSan
twilio-mnc-mcc-getter.py
Python
mit
1,280
0.003906
import logging import os f
rom twilio.rest import Client class TwilioClient(object): def __init__(self): self.logger = logging.getLogger("botosan.logger") self.account_sid = os.environ["TWILIO_SID"] self.account_token = os.environ["TWILIO_TOKEN"] self.client = Client(self.account_sid, self.account_token) ...
Country Code and Mobile Network code for a given Twilio Number :param phone_number: The phone number, containing the +CC Number, ex: +12345678901 for the US. :return: a tuple containing the mcc and mnc """ number = self.client.lookups.phone_numbers(phone_number).fetch(type="carrier") ...
KeserOner/puissance4
bestaplayer.py
Python
mit
9,518
0.001681
__author__ = 'besta' class BestaPlayer: def __init__(self, fichier, player): self.fichier = fichier self.grille = self.getFirstGrid() self.best_hit = 0 self.players = player def getFirstGrid(self): """ Implements function to get the first grid. :retur...
Lines(self): """ Implements function to transform columns in lines to make tests eaiser. :return: a reverse matrice """ column = [] for x in xrange(7): col = '' for y in xrange(6): col += self.grille[y][x] column.append(...
player, inARow): """ Implements function to check the current columns setup to evaluate best combinaison. :param player: check for your numbers (your player number) or those of your opponent. :param inARow: how many tokens in a row (3 or 2). :return: true or false """ ...
AdamMiltonBarker/TechBubble-Iot-JumpWay-Python-MQTT
src/techbubbleiotjumpwaymqtt/device.py
Python
epl-1.0
6,911
0.03328
# ***************************************************************************** # Copyright (c) 2016 TechBubble Technologies and other Contributors. # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distr...
ame property is required") elif self._configs['username'] == None: raise ConfigurationException("username property is required") elif self._configs['password'] == None: raise Configur
ationException("password property is required") def connectToDevice(self): self.mqttClient = mqtt.Client(client_id=self._configs['deviceName'], clean_session=False) deviceStatusTopic = '%s/Devices/%s/%s/Status' % (self._configs['locationID'], self._configs['zoneID'], self._configs['deviceId']) self.mqttClien...
tsili/datpy
datpy/time_operations.py
Python
agpl-3.0
4,806
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2015. Tšili Lauri Johannes # # 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 ...
digit. Returns ---------- season : str The formated data is returned in a string even when the data represents an integer. Notes ---------- Currently the only supported formating is from a name into a zero-padded string digit. The input is not case sensitive. Exa...
er()[:3] if season == 'SPR': season = "03" elif season == 'SUM': season = "06" elif season == 'AUT': season = "09" elif season == 'WIN': season = "12" else: return None return season
beloglazov/openstack-neat
utils/idle-time-fraction.py
Python
apache-2.0
2,317
0.003453
#!/usr/bin/python2 # Copyright 2012 Anton Beloglazov # # 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 ...
rint "Start time: " + str(start_time) #print "Finish time: " + str(finish_time) def total_seconds(delta): return (delta.microseconds + (delta.seconds + delta.days * 24 * 3600) * 1000000) / 1000000 total_time = 0 total_idle_time = 0 for hostname, host_id in db.select_host_ids().items(): prev_times...
, state in db.select_host_states(host_id, start_time, finish_time): if prev_timestamp: states[prev_state].append(total_seconds(timestamp - prev_timestamp)) prev_timestamp = timestamp prev_state = state states[prev_state].append(total_seconds(finish_time - prev_timestamp)) #pr...
godfryd/pylint
test/input/func_interfaces.py
Python
gpl-2.0
2,062
0.00485
# pylint:disable=R0201 """docstring""" __revision__ = '' class Interface(object): """base class for interfaces""" class IMachin(Interface): """docstring""" def truc(self): """docstring""" def troc(self, argument): """docstring""" class Correct1(object): """docstring""" __impl...
adArgument(object): """docstring""" __implements__ = (IMachin,) def __init__(self): pass def truc(self): """docstring""" pass def troc(self): """docstring""" pass class InterfaceCantBeFound(object): """docstring""" __implements__ = undefined d...
"""public method 2/2""" class InterfaceCanNowBeFound(object): """docstring""" __implements__ = BadArgument.__implements__ + Correct2.__implements__ def __init__(self): """only to make pylint happier""" def please(self): """public method 1/2""" def besilent(self): "...
zerothi/sisl
sisl/viz/input_fields/basic/bool.py
Python
mpl-2.0
1,059
0.000944
# Thi
s Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at https://mozilla.org/MPL/2.0/. from ..._input_field import InputField class BoolInput(InputField): """Simple input that controls a boolean variable. ...
= ("f", "false") _true_strings = ("t", "true") dtype = bool _type = 'bool' _default = {} def parse(self, val): if val is None: pass elif isinstance(val, str): val = val.lower() if val in self._true_strings: val = True ...
m-entrup/EFTEMj
EFTEMj-pyScripts/src/main/resources/scripts/Plugins/EFTEMj/ESI/Calculate_Jump-ratio.py
Python
bsd-2-clause
3,118
0.000962
""" file: Calculate_Jump-ratio.py author: Michael Entrup b. Epping ([email protected]) version: 20170306 info: A script that calculates the Jump-Ratio of two images. The second image is devided by the first one. A drift correction is performed. The first image is shiftet t...
mg_ratio.getProcessor().getMax() stat = img_ratio.getStatistics(Stats.MEAN + Stats.STD_DEV) mean = stat.mean stdv = stat.stdDev if minimum < mean - stdv:
if mean - stdv >= 0: img_ratio.getProcessor().setMinAndMax(mean - stdv, maximum) else: img_ratio.getProcessor().setMinAndMax(0, maximum) img_ratio.updateAndDraw() if __name__ == '__main__': run_script()
chef-buddy/chef-buddy-django
chef_buddy/migrations/0002_ingredientflavorcompound_score.py
Python
mit
444
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class
Migration(migrations.Migration): dependencies = [ ('chef_buddy', '0001_initial'), ] operations = [ migrations.AddField( model_name='ingredientflavorcompound',
name='score', field=models.FloatField(default=1.0), preserve_default=False, ), ]
chadmv/plow
lib/python/plow/gui/form/fwidgets.py
Python
apache-2.0
4,081
0.00294
from pl
ow.gui.manifest import QtCore, QtGui from plow.gui.util import formatDateTime, formatDuration __all__ = [ "Text", "Number", "Decimal", "DateTime", "PillWidget", "Checkbox" ] class FormWidget(QtGui.QWidget): """ T
he base class for all form widgets. """ __LOCKED_PIX = None def __init__(self, value, parent=None): QtGui.QWidget.__init__(self, parent) layout = QtGui.QGridLayout(self) layout.setSpacing(0) layout.setContentsMargins(0, 0, 0, 0) self._widget = None self.__st...
praekelt/sideloader2
sideloader.worker/sideloader/worker/task_db.py
Python
mit
9,546
0.005133
import time from twisted.internet import defer, reactor, protocol from twisted.python import log from twisted.enterprise import adbapi class SideloaderDB(object): def __init__(self): self.p = adbapi.ConnectionPool('psycopg2', database='sideloader', host='localhost', use...
0]) @defer.inlineCallbacks def getBuildNumber(self, repo): q = yield self.p.runQuery('SELECT build_num FROM sideloader_buildnumbers WHERE package=%s', (repo,)) if q: defer.returnValue(q[0][0]) else: defer.returnValue(0) def setBuildNumber(self, repo, num): ...
)) def setBuildState(self, id, state): return self.p.runOperation('UPDATE sideloader_build SET state=%s WHERE id=%s', (state, id)) def setBuildFile(self, id, f): return self.p.runOperation('UPDATE sideloader_build SET build_file=%s WHERE id=%s', (f, id)) # Release queries def createR...
pas256/troposphere
troposphere/route53.py
Python
bsd-2-clause
4,197
0
# Copyright (c) 2012-2013, Mark Peek <[email protected]> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject, AWSProperty, Tags from .validators import integer, positive_integer, network_port, boolean class AliasTarget(AWSProperty): props = { 'HostedZoneId': (basestring, Tru...
tring, False), 'SubdivisionCode': (basestring, False), } class BaseRecordSet(object): props = { 'AliasTarget': (AliasTarget, False), 'Comment': (basestring, False), 'Failover': (basestring, False), 'GeoLocation': (GeoLocation, False), 'HealthCheckId': (basestrin...
'HostedZoneId': (basestring, False), 'HostedZoneName': (basestring, False), 'MultiValueAnswer': (boolean, False), 'Name': (basestring, True), 'Region': (basestring, False), 'ResourceRecords': (list, False), 'SetIdentifier': (basestring, False), 'TTL': (integer,...
kotoroshinoto/Cluster_SimpleJob_Generator
pybin/Test/PipelineSampleDataTest.py
Python
unlicense
1,017
0.019666
''' Created on Mar 18, 2013 @author: Gooch ''' import unittest from Pipeline.PipelineSampleData import SampleData class SampleDataTest(unittest.TestCase): def setUp(self): #might not need this, runs before each test pass def tearDown(self): #migh
t not need this, runs after each test pass def testSingleManyColumns(self): pass def testSingleFewColumns(self): pass def testPairedManyColumns(self): pass def testPairedFewColumns(self): pass def testEmptyFile(self): pass def testIgnoresBlankLines...
ss def testDuplicateEntrySingle(self): pass def testDuplicateEntryPaired(self): pass def testDuplicateEntryMixed1(self): pass def testDuplicateEntryMixed2(self): pass def testValidSingle(self): pass def testValidPaired(self): pass if __name__ == "_...
z-plot/z-plot
setup.py
Python
bsd-3-clause
472
0.055085
# python from distutils.core import setup setup( name = 'zplot', packages = ['zplot'], version = '1.41', description = 'A simple graph-creation library', author = 'Remzi H. Arpaci-Dusseau',
author_email = '[email protected]', url = 'https://github.com/z-plot/z-plot', download_url = 'https://github.com/z-plot/z-plot/tarball/1.4', keywords = ['plotting', 'graphing
', 'postscript', 'svg'], classifiers = [], )
grahesh/Stock-Market-Event-Analysis
qstkstudy/stockListGen.py
Python
bsd-3-clause
1,592
0.013819
# (c) 2011, 2012 Georgia Tech Research Corporation # This source code is released under the New BSD license. Please see # http://wiki.quantsoftware.org/index.php?title=QSTK_License # for license details. # # Created on October <day>, 2011 # # @author: Vishal Shekhar # @contact: [email protected] # @summary: ...
etime as dt dataobj = da.DataAccess('Norgate') delistSymbols = set(dataobj.get_symbols_in_sublist('/US/Delisted Securities')) allSymbols = set(dataobj.get_all_symbols()) #by default Alive symbols only aliveSymbols = list(allSymbols - delistSymbols) # set difference is smart startday = dt.datetime(2008,1,1) endday = d...
timeofday=dt.timedelta(hours=16) timestamps = du.getNYSEdays(startday,endday,timeofday) #Actual Close Prices of aliveSymbols and allSymbols aliveSymbsclose = dataobj.get_data(timestamps, aliveSymbols, 'actual_close') allSymbsclose = dataobj.get_data(timestamps, allSymbols, 'actual_close') file = open('aliveSymbols2',...
dunkhong/grr
grr/server/grr_response_server/gui/api_call_router_without_checks.py
Python
apache-2.0
13,048
0.011343
#!/usr/bin/env python """Implementation of a router class that does no ACL checks.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from typing import Optional from grr_response_server import access_control from grr_response_server.gui import api_call_...
def ListHuntResults(self, args, token=None): return api_hunt.ApiListHuntResultsHandler() def GetExportedHuntResults(self, args, token=None): return api_hunt.ApiGetExportedHuntResultsHandler() def GetHuntResultsExportCommand(self, args, token=None): return api_hunt.ApiGetHuntResultsExportCommandHand...
dler() def ListHuntOutputPluginLogs(self, args, token=None): return api_hunt.ApiListHuntOutputPluginLogsHandler() def L
rajendrakrp/GeoMicroFormat
build/lxml/setupinfo.py
Python
bsd-3-clause
11,648
0.00601
import sys, os, os.path from distutils.core import Extension from distutils.errors import DistutilsOptionError from versioninfo import get_base_dir, split_version try: from Cython.Distutils import build_ext as build_pyx import Cython.Compiler.Version CYTHON_INSTALLED = True except ImportError: CYTHON_I...
h('-I'): result.append(possible_cflag) if sys.platform in ('darwin',): for opt in result: if 'flat_namespace' in opt: break else: result.append('-flat_namespace') return result def define_macros(): macros = [] if OPTION_WITHOUT_A...
d(('WITHOUT_THREADING', None)) if OPTION_WITH_REFNANNY: macros.append(('CYTHON_REFNANNY', None)) return macros _ERROR_PRINTED = False def run_command(cmd, *args): if not cmd: return '' if args: cmd = ' '.join((cmd,) + args) try: import subprocess except ImportEr...
zhaifangzhi/1
www/cgi-bin/show_info.py
Python
gpl-3.0
3,348
0.034528
#! /usr/bin/env python # -*- coding: utf-8 -*- import json import cgi import urllib2 #取得本机外网IP myip = urllib2.urlopen('http://members.3322.org/dyndns/getip').read() myip=myip.strip() #加载SSR JSON文件 f = file("/usr/local/shadowsocksr/mudb.json");
json = json.load(f); # 接受表达提交的数据 form = cgi.FieldStorage() # 解析处理提交的数据 getport = f
orm['port'].value getpasswd = form['passwd'].value #判断端口是否找到 portexist=0 passwdcorrect=0 #循环查找端口 for x in json: #当输入的端口与json端口一样时视为找到 if(str(x[u"port"]) == str(getport)): portexist=1 if(str(x[u"passwd"]) == str(getpasswd)): passwdcorrect=1 jsonmethod=str(x[u"method"]) jsonobfs=str(x[u"obfs"]) jsonprot...
OsirisSPS/osiris-sps
client/data/extensions/5B1D133CA24D2B5B93B675279CB60C9CB7E47502/scripts/globalvars.py
Python
gpl-3.0
57
0.035088
exte
nsion = None #httpDirectory = None omlCitation = None
gofed/gofed-ng
scenarios/golangDepsUpdate.py
Python
gpl-3.0
3,711
0.004042
#!/bin/python # -*- coding: utf-8 -*- # #################################################################### # gofed-ng - Golang system # Copyright (C) 2016 Fridolin Pokorny, [email protected] # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public Lice...
help="specify commit depth limit") since_date = SwitchAttr("--since-date", str, default=None, help="specify since date") skip_errors = Flag("--skip-errors", help="errors will be reported, but the computation will not be interrupted")...
(self): with self.get_system() as system: golang_pkgs = system.async_call.goland_package_listing() stored_projects = system.async_call.deps_project_listing() for pkg in golang_pkgs.result: if not pkg['name'].startswith('golang-github-'): ...
memsharded/conan
conans/client/build/msbuild.py
Python
mit
12,275
0.004236
import copy import os import re import subprocess from conans.client import tools from conans.client.build.visual_environment import (VisualStudioBuildEnvironment, vs_build_type_flags, vs_std_cpp) from conans.client.tools.oss import cpu_count from conans.client.tools...
self.get_command(project_file, property_file_name, targets=targets, upgrade_project=upgrade_project, buil
d_type=build_type, arch=arch, parallel=parallel, toolset=toolset, platforms=platforms, use_env=use_env, properties=properties, output_binary_log=output_binary_log, ...
utgw/programming-contest
codefestival/2016/qualA/a.py
Python
mit
40
0.025
s = input().rs
trip() print(s[:
4],s[4:])
martinribelotta/micropython
ciaa-nxp/frozen/testing/TestGPIO.py
Python
mit
3,678
0.028276
from unittest import TestCase import pyb class TestGPIO (TestCase): flagInCallback=False def test_1(self): flagOk=False try: p = pyb.Pin(0) #GPIO0 p.init(pyb.Pin.IN,pyb.Pin.PULL_NONE) flagOk=True except: pass self.assertEqual(fl...
Equal(flagOk,True,"Enable GPIO8 IN") def test_3(self): flagOk=False try: p = pyb.Pin(9) #GPIO9 - invalid p.init(pyb.Pin.IN,pyb.Pin.PULL_NONE) flagOk=True except: pass self.assertEqual(flagOk,False,"Enable invalid GPIO9 IN") def t...
pass self.assertEqual(flagOk,False,"Enable invalid mode GPIO0 IN") def test_5(self): flagOk=False try: p = pyb.Pin(0) #GPIO0 p.init(pyb.Pin.IN,99) #invalid pullup mode flagOk=True except: pass self.assertEqual(flagOk,F...
stanfordnmbl/osim-rl
examples/legacy/example.py
Python
mit
4,483
0.003346
# Derived from keras-rl import opensim as osim import numpy as np import sys from keras.models import Sequential, Model from keras.layers import Dense, Activation, Flatten, Input, concatenate from keras.optimizers import Adam import numpy as np from rl.agents import DDPGAgent from rl.memory import SequentialMemory f...
observation = Flatten()(observation_input) x = concatenate([
action_input, flattened_observation]) x = Dense(64)(x) x = Activation('relu')(x) x = Dense(64)(x) x = Activation('relu')(x) x = Dense(64)(x) x = Activation('relu')(x) x = Dense(1)(x) x = Activation('linear')(x) critic = Model(inputs=[action_input, observation_input], outputs=x) print(critic.summary()) # Set up the age...
lrq3000/author-detector
authordetector/configparser.py
Python
gpl-3.0
7,707
0.004801
#!/usr/bin/env python # encoding: utf-8 # # AuthorDetector # Copyright (C) 2013 Larroque Stephen # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your ...
'--' in key and i+1 < len(extras) and not '--' in extras[i+1]: # if the argument begins with --, and there is an argument after this one, and the next argument is in fact a value (does not begin with --), we store it with the va
lue self.config[key.lstrip('-')] = extras[i+1] i += 1 # skip the next argument (which we used as a value) # Else this argument has no value, we just set it to True else: self.config[key.lstrip('-')] = True i += 1...
google/hotel-ads-etl-tool
hotel_ads_beam_utils/hotel_ads_beam_utils/do_fn.py
Python
apache-2.0
1,021
0.003918
# Copyright 2018 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, soft...
# See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import from __future__ import division from __future__ import print_function import apache_beam as beam from apache_beam import pvalue class SplitInputsDoFn(beam.DoFn): """ParDo ...
t = line.split(',') if element[1] is not None: yield pvalue.TaggedOutput(element[1], element) else: yield element
ppham27/snapstream-reader
legacy/run_on_dates.py
Python
mit
1,762
0.008513
#!/usr/bin/env python import sys import os.path import datetime import subprocess import time """ Run snapstream reader script for several files and out a table of match counts. Example: $ python run_on_dates.py eg01china.c 2014-01-01 2014-07-01 """ def validate(date_string): try: datetime.datetime.strpti...
t("\t".join(["dt","total_matches_cnt","matching_programs_cnt","total_programs_cnt","selected_programs_cnt"])) os.system("gcc " + file_name) for f in data_files: date_string = f[5:15] full_output.write(f + "\n" + "===================
=\n\n") proc = subprocess.Popen(["./a.out",f], stdout=subprocess.PIPE) proc_out = proc.communicate()[0].decode('utf-8') full_output.write(proc_out) proc_out = proc_out.split('\n') print("\t".join([date_string]) + '\t' + proc_out[-2]) full_output.close() print(str(time.tim...
commonsearch/cosr-back
tests/cosrlibtests/document/html/test_hyperlinks.py
Python
apache-2.0
4,389
0.000456
from cosrlib.document.html import HTMLDocument import pytest def _links(html, url=None): return HTMLDocument(html, url=url).parse().get_hyperlinks() def test_get_hyperlinks(): links = _links("""<html><head><title>Test title</title></head><body>x</body></html>""") assert len(links) == 0 links = _lin...
html><head><title>Test title</title></head><body> <a href="http://[email protected]">Y</a> </body></html>""", url="http://sub.test.com/page2/x.html") assert len(links) == 0 # Looks like a forgotten mailto:, don't index links = _links("""<html><head><title>Test title</title></head><body> <...
b.test.com/page2/x.html") assert len(links) == 0 # Invalid URL should be filtered links = _links("""<html><head><title>Test title</title></head><body> <a href="http://www.[wsj-ticker ticker=">Y</a> </body></html>""", url="http://sub.test.com/page2/x.html") assert len(links) == 0 links ...
TamiaLab/PySkCode
skcode/tags/textalign.py
Python
agpl-3.0
1,809
0.001106
""" SkCode text align tag definitions code. """ from ..et
ree import TreeNode class TextAlignBaseTreeNode(TreeNode): """ Base class for all text alignment tag class. """ # HTML template for rendering html_render_template = '<p class="text
-{text_alignment}">{inner_html}</p>\n' # Default text alignment text_alignment = '' def render_html(self, inner_html, **kwargs): """ Callback function for rendering HTML. :param inner_html: The inner HTML of this tree node. :param kwargs: Extra keyword arguments for renderi...
AMOboxTV/AMOBox.LegoBuild
script.module.pydevd/lib/_pydev_jy_imports_tipper.py
Python
gpl-2.0
16,814
0.012727
import StringIO import traceback from java.lang import StringBuffer #@UnresolvedImport from java.lang import String #@UnresolvedImport import java.lang #@UnresolvedImport import sys from _pydev_tipper_common import DoFind try: False True except NameError: # version < 2.3 -- didn't have the True/False builtins...
RGS: varargs = func_code.co_varnames[nargs] nargs = nargs + 1 varkw = None if func_code.co_flags & func_code.CO_VARKEYWORDS: varkw = func_code.co_varnames[nargs] return args, varargs, varkw
args = getargs(func.func_code) return 1, [Info(func.func_name, args=args[0], varargs=args[1], kwargs=args[2], doc=func.func_doc)] if isinstance(func, core.PyMethod): #this is something from java itself, and jython just wrapped it... ...
lkrotowski/passwdk
src/passwdk/main.py
Python
gpl-3.0
2,401
0.03082
import sys, complete from argparse import ArgumentParser from config import config from file import load, save from hooks import post_add def add(conf): parser = ArgumentParser(usage="%(prog)s add arguments") parser.add_argument("-n", required=True, dest="name", help="password name") parser.add_argument("-...
s.argv[2]) complete.complete_names_and_tags(conf, sys.argv[2]) args = parser.parse_args(sys.argv[2:]) def search(it): name = it["
name"] in args.search tags = reduce(lambda b, s: b and "tags" in it and it["tags"].count(s) > 0, args.search, True) return name or tags for i, r in enumerate(filter(search, load(conf))): if i > 0: print if args.password: sys.stdout.write(r["pass"]) else: print "name:\t{0}".format(r["name"]) print "...
tanghaibao/goatools
tests/test_semantic_faster.py
Python
bsd-2-clause
3,361
0.005653
#!/usr/bin/env python """Test faster version of sematic similarity""" from __future__ import print_function # Computing basic semantic similarities between GO terms # Adapted from book chapter written by _Alex Warwick Vesztrocy and Christophe Dessimoz_ # How to compute semantic similarity between GO terms. # First...
|= goobj.get_all
_parents() else: gonotindag.add(go_id) # Add 1 for each GO annotated to this gene product for parent in allterms: gocnts[parent] += 1 if gonotindag: print("{N} Assc. GO IDs not found in the GODag\n".format(N=len(gonotindag))) return gocnts if __na...
ckclark/leetcode
py/counting-bits.py
Python
apache-2.0
336
0.002976
class Solution(object): def count_bits(self, n): c = (n - ((n >> 1) & 0o33333333333) - ((n >> 2) & 0o11111111111))
return ((c + (c >> 3)) & 0o30707070707) % 63 def countBits(self, num)
: """ :type num: int :rtype: List[int] """ return map(self.count_bits, xrange(num + 1))
hryamzik/ansible
lib/ansible/modules/cloud/cloudstack/cs_host.py
Python
gpl-3.0
18,456
0.000813
#!/usr/bin/python # -*- coding: utf-8 -*- # # (c) 2016, René Moser <[email protected]> # # 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 Lice...
e host
was last pinged. returned: success type: string sample: "1970-01-17T17:27:32+0100" management_server_id: description: Management server ID of the host. returned: success type: int sample: 345050593418 memory_allocated: description: Amount of the host's memory currently allocated. returned: success t...
SaschaMester/delicium
tools/telemetry/telemetry/internal/browser/user_agent_unittest.py
Python
bsd-3-clause
1,431
0.009783
# Copyright 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. from telemetry import decorators from telemetry.internal.browser import user_agent from telemetry.unittest_util import tab_test_case class MobileUserAgentT...
2 def testUserAgent(self): ua = self._tab.EvaluateJavaScript('window.navigator.userAgent') self.assertEquals(ua, user_agent.UA_TYPE_MAPPING['tablet']) class DesktopUserAgentTest(tab_test_case.TabTestCase): @classmethod def CustomizeBrowserO
ptions(cls, options): options.browser_user_agent_type = 'desktop' @decorators.Disabled('chromeos') # crbug.com/483212 def testUserAgent(self): ua = self._tab.EvaluateJavaScript('window.navigator.userAgent') self.assertEquals(ua, user_agent.UA_TYPE_MAPPING['desktop'])
ctlab/pypipe
pypipe-gui/windows/addfiledialog.py
Python
mit
2,392
0
from PyQt4.QtGui import * import pypipe.formats import pypipe.basefile from pypipe.core import pipeline from widgets.combobox import ComboBox class AddFileDialog(QDialog): def __init__(self, parent=None): super(AddFileDialog, self).__init__(parent) self.formats_combo = ComboBox() self.fi...
currentIndexChanged.connect(self.turn_ok_button) self.ok_button.clicked.connect(self.accept) self.open_button.clicked.connect(self.open_file) def turn_ok_button(self): try: f = self.get_file() self.ok_button.setEnabled(True) except pypipe.bas
efile.FileNotExistsError: self.ok_button.setEnabled(False) return if pypipe.core.pipeline.can_add_file(f): self.ok_button.setEnabled(True) else: self.ok_button.setEnabled(False) def open_file(self): file_name = QFileDialog.getOpenFileName(self...
pepeportela/edx-platform
common/djangoapps/terrain/browser.py
Python
agpl-3.0
10,330
0.001742
""" Browser set up for acceptance tests. """ # pylint: disable=no-member # pylint: disable=unused-argument from base64 import encodestring from json import dumps from logging import getLogger import requests from django.conf import settings from django.core.management import call_command from lettuce import after, b...
iver.save_screenshot(image_name) except WebDriverException: LOGGER.error("Could not capture a screenshot '{}'".format(image_name)) @after.each_scenario def screenshot_on_error(scenario): """ Save a screenshot to help with debugging. """ if scenario.failed: try: output_d...
t_dir, scenario.name.replace(' ', '_')) world.browser.driver.save_screenshot(image_name) except WebDriverException: LOGGER.error('Could not capture a screenshot')
the-zebulan/CodeWars
tests/kyu_6_tests/test_help_the_bookseller.py
Python
mit
518
0
import unittest from katas.kyu_6.h
elp_the_bookseller import sto
ck_list class StockListTestCase(unittest.TestCase): def setUp(self): self.a = ['ABAR 200', 'CDXE 500', 'BKWR 250', 'BTSQ 890', 'DRTY 600'] self.b = ['A', 'B'] def test_equals(self): self.assertEqual(stock_list(self.a, self.b), '(A : 200) - (B : 1140)') def test_equals_2(self): ...
wtpayne/hiai
a3_src/h20_capability/sensor/imaging/classify/__init__.py
Python
apache-2.0
863
0
# -*- coding: utf-8 -*- """ Package with support for target classification on image forming sensors. --- type: python_module validation_level: v00_minimum protection: k00_public copyright: "Copyright 2016 High Integrity Artificial Intelligence Systems" license: "Licensed under the Apache Licens...
ed 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." ... """ __all__ = ()
fitnr/census2dbf
census2dbf/cli.py
Python
gpl-3.0
1,842
0.002714
#!/usr/bin/env python # encoding: utf-8 from __future__ import print_function import sys import os.path import argparse from . import censuscsv from . import dbfwriter def main(): '''Command line util for converting census CSV to DBF''' parser = argparse.ArgumentParser(description='Convert a US Census csv to d...
') parser.add_argument
('--dd', default=False, action='store_true', help='output a data dictionary made from the header') args = parser.parse_args() output_file = args.output if output_file is None: base, _ = os.path.splitext(args.input) output_file = base + '.dbf' if output_file == '-': output_fil...
jtruscott/ld27
pytality/term_pygame.py
Python
bsd-3-clause
11,584
0.009237
import os import pygame import sys import threading, time from pygame.locals import * import logging log = logging.getLogger('pytality.term.pygame') log.debug("pygame version: %r", pygame.version.ver) """ A mapping of special keycodes into representative strings. Based off the keymap in WConio, but with 'alt...
fg, bg, ch)] = cell_sprite return cell_sprite def blit_at(x, y, fg, bg, ch): #blit one character to the screen. #because function calls are pricey, this is also inlined (ew) in draw_buffer, so the contents are kept short. #coordinates on the screen screen_x = x * W screen_y = y * H #cache...
fg, index) cell we draw into a surface so it's easier to redraw. #it's a little bit of a memory waste, and takes longer on the first draw, but we're dealing with ascii here #so there's probably a lot of reuse. try: cell_sprite = sprites[(fg, bg, ch)] except KeyError: #make a new one ...
bandang0/theia
theia/optics/special.py
Python
gpl-3.0
4,456
0.02895
'''Defines the Special class for theia.''' # Provides: # class Special # __init__ # lines import numpy as np from ..helpers import geometry, settings from ..helpers.units import deg, cm, pi from .optic import Optic class Special(Optic): ''' Special class. This class represents general opt...
+ np.sin(Wedge) * (np.cos(Alpha) * a\ + np.sin(Alpha) * b) super(Special, self).__init__(ARCenter = ARCenter, ARNorm = ARNorm, N = N, HRK = HRK, ARK = ARK, ARr = ARr, ARt = ARt, HRr = HRr, HRt = HRt, KeepI = KeepI, HRCenter = HRCenter, HRNo...
HRNorm, Thickness = Thickness, Diameter = Diameter, Wedge = Wedge, Alpha = Alpha, TonHR = TonHR, RonHR = RonHR, TonAR = TonAR, RonAR = RonAR, Ref = Ref) #Warnings for console output if settings.warning: self.geoCheck("mirror") def lines(self): ''...
Driftwood2D/Driftwood
src/entitymanager.py
Python
mit
11,732
0.002642
#################################### # Driftwood 2D Game Dev. Suite # # entitymanager.py # # Copyright 2014-2017 # # Michael D. Reiley & Paul Merrill # #################################### # ********** # Permission is hereby granted, free of charge, to any person obtaining a copy # of ...
limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and t
his 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, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT S...
filias/django
tests/invalid_models_tests/test_ordinary_fields.py
Python
bsd-3-clause
19,411
0.000515
# -*- encoding: utf-8 -*- from __future__ import unicode_literals import unittest from django.core.checks import Error, Warning as DjangoWarning from django.db import connection, models from django.test import SimpleTestCase, TestCase from django.test.utils import isolate_apps, override_settings from django.utils.tim...
rror( "'max_length' must be a positive integer.", obj=field, id='fields.E121', ), ] self.assertEqual(errors, expected) def test_non_iterable_choices(self): class Model(models.Model): field = models.CharField(max_length=...
terable (e.g., a list or tuple).", obj=field, id='fields.E004', ), ] self.assertEqual(errors, expected) def test_choices_containing_non_pairs(self): class Model(models.Model): field = models.CharField(max_length=10, choices=[(1, 2, 3),...
HydraChain/hydrachain
hydrachain/consensus/utils.py
Python
mit
750
0.004
from sha3 import sha3_256 from ethereum.utils import big_endian_to_int def sha3(seed): return sha3_256(bytes(seed)
).digest() # colors FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' def DEBUG(*args, **kargs): print(FAIL + repr(args) + repr(kargs) + ENDC) colors = ['\033[9%dm' % i for i in range(0, 7)] colors += ['\033[4%dm' % i for i in range(1, 8)] num_colors = len(colors) def cstr(num, txt): ...
%s' % (colors[num % len(colors)], txt, ENDC) def cprint(num, txt): print cstr(num, txt) def phx(x): return x.encode('hex')[:8] if __name__ == '__main__': for i in range(len(colors)): cprint(i, 'test')
jordigh/mercurial-crew
mercurial/subrepo.py
Python
gpl-2.0
56,360
0.000923
# subrepo.py - sub-repository handling for Mercurial # # Copyright 2009-2010 Matt Mackall <[email protected]> # # This software may be used and distributed according to the terms of the # GNU General Public License version 2 or any later version. import errno, os, re, shutil, posixpath, sys import xml.dom.minidom import...
return util.sha1(_exp
andedabspath(remotepath)).hexdigest()[0:12] def _calcfilehash(filename): data = '' if os.path.exists(filename): fd = open(filename, 'rb') data = fd.read() fd.close() return util.sha1(data).hexdigest() class SubrepoAbort(error.Abort): """Exception class used to avoid handling a ...
EnableSecurity/wafw00f
wafw00f/plugins/edgecast.py
Python
bsd-3-clause
371
0.002695
#!/usr/bin/env python ''' Copyright (C) 2020, WAFW00F Developers. See the LICENSE file for copying permission. ''
' NAME = 'Edgecast (Verizon Digital Media)' def is_waf(self): schemes = [ self.matchHeader(('Server', r'^ECD(.+)?')), self.matchHeader(('Server', r'^ECS(.*)?')) ] if any(i fo
r i in schemes): return True return False
m860/data-analysis-with-python
practises/macd.py
Python
mit
635
0
import json from getJsonData import getJSONData import os from datetime import date, datetime import numpy as np import stock import matplotlib.pyplot as plt dataPath = 'data/SZ#002637.txt' fileName, fileExtension = os.path.splitext(os.path.basename(dataPath)) jsonPath = os.path.join('data', '{0}.json'.format(fileNa...
r i in jsonData][-num:], dtype=np.float64) ema12 = stock.ema(close, 12) ema26 = stock.ema(close, 26) macd = stock.macd(close) plt.bar(range(
num), macd) plt.plot(range(num), ema12, 'r-') plt.plot(range(num), ema26, 'g-') plt.show()
transceptor-technology/siridb-server
itest/test_compression.py
Python
mit
3,689
0
import asyncio import functools import random import time from testing import Client from testing import default_test_setup from testing import gen_data from testing import gen_points from testing import gen_series from testing import InsertError from testing import PoolError from testing import QueryError from testing...
=TIME_PRECISION, optimize_interval=500, compression=True) async def run(self): await self.client0.connect() self.series_float = gen_points( tp=float, n=10000, time_precision=TIME_PRECISION, ts_gap='5m') random.shuffle(self.series_float) self.series_int = ...
ME_PRECISION, ts_gap='5m') random.shuffle(self.series_int) self.assertEqual( await self.client0.insert({ 'series float': self.series_float, 'series int': self.series_int }), {'success_msg': 'Successfully inserted 20000 point(s).'}) self.s...
cliftonmcintosh/openstates
openstates/wy/committees.py
Python
gpl-3.0
1,983
0.003026
import re import lxml.html from pupa.scrape import Scraper, Organization class WYCommitteeScraper(Scraper): members = {} urls = { "list": "http://legisweb.state.wy.us/LegbyYear/CommitteeList.aspx?Year=%s", "detail": "http://legisweb.state.wy.us/LegbyYear/%s", } def scrape(self, sessi...
ge.xpath("
.//table[contains(@id, 'CommitteeMembers')]"): rows = table.xpath(".//tr") chamber = rows[0].xpath('.//td')[0].text_content().strip() chamber = 'upper' if chamber == 'Senator' else 'lower' comm = Organization(name=c.strip(), chamber=chamber, classification...
muccg/rdrf
rdrf/registry/patients/migrations/0027_auto_20180116_1012.py
Python
agpl-3.0
836
0
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2018-01-16 10:12 from __future_
_ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('patients', '0026_clinicianother_user'), ] operations = [ migrations.AddField( model_...
me='use_other', field=models.BooleanField( default=False), ), migrations.AlterField( model_name='clinicianother', name='user', field=models.ForeignKey( blank=True, null=True, on_delete=models....
Deafjams/tumblr-block
setup.py
Python
mit
804
0
"""Package setup for tumblr-block""" import setuptools if __name__ == '__main__': setuptools.setup( name='tumblr_block
', version='2.0.0', description=( 'Auto blocking for tumblr' ), url='https://github.com/Deafjams/tumblr-block', author='Emma Foster', license='License :: OSI Approved :: MIT License', install_requires=[ 'plan==0.5' ], packag...
include_package_data=True, classifiers=( "Development Status :: 4 - Beta", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Programming Language :: Python :: 2.7" ) )
eduNEXT/edx-platform
openedx/core/djangoapps/models/tests/test_course_details.py
Python
agpl-3.0
11,188
0.00429
""" Tests for CourseDetails """ import datetime import pytest import ddt from pytz import UTC from unittest.mock import patch # lint-amnesty, pylint: disable=wrong-import-order from django.conf import settings from xmodule.modulestore import ModuleStoreEnum from xmodule.data import CertificatesDisplayBehaviors from...
assert details.syllabus is None, ('syllabus somehow initialized' + str(details.syllabus)) assert details.intro_video is None, ('intro_video somehow initialized' + str(details.intro_vi
deo)) assert details.effort is None, ('effort somehow initialized' + str(details.effort)) assert details.language is None, ('language somehow initialized' + str(details.language)) assert not details.self_paced def test_update_and_fetch(self): jsondetails = CourseDetails.fetch(self.c...
skywind3000/collection
script/playmp3.py
Python
mit
7,109
0.036995
#! /usr/bin/env python2 # -*- coding: utf-8 -*- #====================================================================== # # playsnd.py - play sound with ctypes + mci # # Created by skywind on 2013/12/01 # Last change: 2014/01/26 23:40:20 # #======================================================================...
e, name) if media_type:
cmd = u'open "%s" type %s alias %s'%(filename, media_type, name) hr = self.mciSendString(cmd) if isinstance(hr, str) or isinstance(hr, unicode): return name return None def close (self, name): hr = self.mciSendString(u'close %s'%name) if isinstance(hr, unicode) or isinstance(hr, str): return ...
hephaestus9/Radio
radio/config/preferences.py
Python
mit
14,591
0.004386
# -*- coding: utf-8 -*- import os import sys from radio.database import db def prefsRootPath(): if sys.platform == "darwin": return os.path.expanduser("~/Library/Application Support/radio") elif sys.
platform.startswith("win"): return os.path.join(os.environ['APPDATA'], "radio") else: return os.path.expanduser("~/.radio") class Prefs(): def _
_init__(self): # Check for ~/.ironworks if not os.path.isdir(prefsRootPath()): os.mkdir(prefsRootPath()) self.db = db.Db(os.path.join(prefsRootPath(), "prefs.db")) #self.configDb = db.Db(os.path.join(prefsRootPath(), "config.db")) #query = self.configDb.query("SE...
jayfk/django-comments-xtd
django_comments_xtd/tests/forms.py
Python
bsd-2-clause
1,785
0.006162
from django.test import TestCase import django_comments as comments from django_comments_xtd.models import TmpXtdComment from django_comments_xtd.forms import XtdCommentForm from django_comments_xtd.tests.models import Article class GetFormTestCase(TestCase): def test_get_form(self): # check function d...
.initial) form = comments.get_form()(self.article, data) self.assert_(self.form.security_errors() == {}) self.assert_(self.form.errors == {}) comme
nt = form.get_comment_object() # it does have the new field 'followup' self.assert_("followup" in comment) # and as long as settings.COMMENTS_XTD_CONFIRM_EMAIL is True # is_public is set to False until receive the user confirmation self.assert_(comment.is_public == False)
kartikluke/yotube
credentials.py
Python
mit
324
0.003086
api_token = 'd469c24f-c428-a155-eae
6-f8216cff4ace' ytkanan_token = '6bc600bd-d0aa-369e-be0c-65c6af034183' ythonest_token = 'f41ef6ea-b8ba-d952-4993-e24b9f
eeda46' ytabhinav_token = '712c5c97-15c5-fc76-68c7-2acba12287d0' yo_rss_token = '17aa580a-2863-db0f-34f1-23657b08dfe6' dev_key = 'AIzaSyBU9eMQ1xW0NNEGprJIR5wgaQdrTFn_Fdc'
Heufneutje/txircd
txircd/modules/rfc/cmd_user.py
Python
bsd-3-clause
1,685
0.02908
from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd.module_interface import Command, ICommand, IModuleData, ModuleData from txircd.utils import isValidIdent, trimStringToByteLength from zope.interface import implementer from typing import Any, Dict, List, Optional, Tuple @implementer...
userCommands(self) -> List[Tuple[str, int, Command]]: return [ ("USER", 1, self) ] def parseParams(self, user: "IRCUser", params: List[str], prefix: str, tags: Dict[str, Optional[str]]) -> Optional[Dict[Any, Any]]: if len(params
) < 4: user.sendSingleError("UserCmd", irc.ERR_NEEDMOREPARAMS, "USER", "Not enough parameters") return None if not params[3]: # Make sure the gecos isn't an empty string user.sendSingleError("UserCmd", irc.ERR_NEEDMOREPARAMS, "USER", "Not enough parameters") return None # Trim down to guarantee ident an...
mstreatfield/anim-studio-tools
grind/python/util/glWidget.py
Python
gpl-3.0
11,356
0.006692
import sys import math from pimath import * from PyQt4 import QtCore, QtGui, QtOpenGL from camera import Camera import grind #----------------------------------------------------------------------------- from rodin import logging log = logging.get_logger('grind.mangle.gl_widget') try: from OpenGL.GL import * ...
lection_marker_bbox.set_colour(0xFF0000) # R G B self.lastPos = QtCore.QPoint() self.backgroundColour = QtGui.QColor.fromCmykF(0.28, 0.28, 0.28, 0.0) self.foregroundColour = QtGui.QColor.fromCmykF(0.7, 0.7, 0.7, 0.0) self.dist = 1.0 self.up = 1.0 self.drawGrid = Tru
e self.drawDefaultObject = True self.followBBox = False self.moveGrid = False self.camera = Camera() self.frameView() def setFollowBBox(self,follow): self.followBBox = follow self.updateGL() def setCenterBBox(self,centered): self.moveGrid = not c...
KlubJagiellonski/pola-backend
pola/migrations/0006_auto_20180527_0840.py
Python
bsd-3-clause
505
0.00198
# Generated by Django 2.0.3 on 2018-05-27 06:40 import django.cont
rib.postgres.indexes from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('pola', '0005_auto_20171225_1632'), ] operations = [ migrations.AddIndex(
model_name='query', index=django.contrib.postgres.indexes.BrinIndex( fields=['timestamp'], name='pola_query_timesta_ea44b7_brin', pages_per_range=64 ), ), ]
plotly/plotly.py
packages/python/plotly/plotly/validators/scattermapbox/_showlegend.py
Python
mit
413
0.002421
import _plotly_utils.basevalidators class ShowlegendValidator(_plotly_utils.basevalidators.BooleanValidator): def __init__(self, plotly_name="showlegend", parent_name="scattermapbox", **kwargs): super(ShowlegendValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_...
)
Cantal0p3/nyu-devops-homework-1
features/environment.py
Python
apache-2.0
173
0.00578
from behave import * import icecream def before_all(context):
context.app = icecream.app.test_client()
context.icecream = icecream icecream.inititalize_redis()
brainstorm-ai/DIGITS
digits/dataset/images/classification/views.py
Python
bsd-3-clause
15,470
0.0181
# Copyright (c) 2014-2016, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import os # Find the best implementation available try: from cStringIO import StringIO except ImportError: from StringIO import StringIO import caffe_pb2 import flask import lmdb import PIL.Image from...
db_name = utils.constants.VAL_D
B, backend = backend, image_dims = job.image_dims, image_folder= image_folder, resize_mode = job.resize_mode, encoding = encoding, compression = compression, labels_file = ...
maykinmedia/django-filer
filer/admin/clipboardadmin.py
Python
bsd-3-clause
4,562
0.002192
#-*- coding: utf-8 -*- from django.forms.models import modelform_factory from django.contrib import admin from django.http import HttpResponse from django.utils import simplejson from django.views.decorators.csrf import csrf_exempt from filer import settings as filer_settings from filer.models import Clipboard, Clipboa...
lipboardAdmin, self).get_urls() from filer import views url_patterns = patterns('', url(r'^operations/paste_clipboard_to_folder/$', self.admin_site.admin_view(views.paste_clipboard_to_folder), name='filer-paste_clipboard_to_folder'), url(r'^operati...
rd_clipboard/$', self.admin_site.admin_view(views.discard_clipboard), name='filer-discard_clipboard'), url(r'^operations/delete_clipboard/$', self.admin_site.admin_view(views.delete_clipboard), name='filer-delete_clipboard'), # uplo...
duointeractive/media-nommer
media_nommer/ec2nommerd/interval_tasks.py
Python
bsd-3-clause
3,910
0.00665
""" This module contains tasks that are executed at intervals, and is imported at the time the server is started. The intervals at which the tasks run are configurable via :py:mod:`media_nommer.conf.settings`. All functions prefixed with ``task_`` are task functions that are registered with the Twisted_ reactor. All f...
IDs, along with some state data. The interval at which heartbeats occur is determined by the :py:data:`NOMMERD_HEARTBEAT_INTERVAL <media_nommer.conf.settings.NOMMERD_HEARTBEAT_INTERVAL` setting. """ if settings.NOMMERD_TERMINATE_WHEN_IDLE: # thre
ad_count_mod factors out this thread when counting active threads. is_terminated = NodeStateManager.contemplate_termination(thread_count_mod= -1) else: is_terminated = False if not is_terminated: NodeStateManager.send_instance_state_update() def task_heartbeat(): """ Checks in ...
bubbles231/Prototype
Helpers.py
Python
gpl-3.0
20,270
0.000247
#!/usr/bin/env python3 # coding=utf-8 from Geometry.Vector2 import Vector2 import math import pygame def intersecting_rows(rect1, rect2): """ @param rect2: pygame.Rect @param rect1: pygame.Rect @return: tuple """ tile_left = math.floor(rect1.left / rect2.width) tile_right = math.ceil(rect...
" @param entity: Prototype.Entity @type tiles_to_check: list @return: Prototype.Tile """ distance_from_self = 1000000 closest = None for tmp_tile in tiles_to_check: if (abs(tmp_tile.rect.centerx - entity.rect.centerx) < distance_from_self): closest = tmp_...
sest is not None: # noinspection PyArgumentList closest_img = pygame.Surface((closest.rect.width, closest.rect.height)) closest_img.fill((0, 100, 255)) if entity.debug: entity.debug_draw(closest_img, closest.rect.x, closest.rect.y) return closest def closest_tile_y(tile...
anhstudios/swganh
data/scripts/templates/object/creature/npc/droid/crafted/shared_it_o_interrogator_advanced.py
Python
mit
492
0.044715
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PL
EASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Creature() result.template = "object/creature/npc/droid/crafted/shared_it_o_interrogator_advanced.iff" result.attribute_template_id = 3 result.stfName("droid_name","it_o_interrogat
or_crafted_advanced") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
Hanaasagi/sorator
orator/commands/migrations/migrate_command.py
Python
mit
2,409
0
# -*- coding: utf-8 -*- from orator.migrations import Migrator, DatabaseMigrationRepository from .base_command import BaseCommand class MigrateCommand(BaseCommand): """ Run the database migrations. migrate {--d|database= : The database connection to use.} {--p|path= : The path of migrati...
tion('seed-path'): options.append(('--path', self.option('seed-path'))) self.call('db:seed', options) def _prepare_database(self, migrator, database): migrator.set_connection(database) if not migrator.repository_exists(): options = [] if databa...
atabase)) if self.get_definition().has_option('config'): options.append(('--config', self.option('config'))) self.call('migrate:install', options)
amadeusproject/amadeuslms
h5p/base_plugin/editor/library/editorstorage.py
Python
gpl-2.0
3,487
0.00694
""" Copyright 2016, 2017 UFPE - Universidade Federal de Pernambuco Este arquivo é parte do programa Amadeus Sistema de Gestão de Aprendizagem, ou simplesmente Amadeus LMS O Amadeus LMS é um software livre; você pode redistribui-lo e/ou modifica-lo dentro dos termos da Licença Pública Geral GNU como publicada pela ...
__isnull=False).extra(select={'name': 'machine_name', 'majorVersion': 'major_version', 'minorVersion': 'minor_version', 'tutorialUrl': 'tutorial_url'}).values( 'name', 'title', 'majorVersion', 'minorVersion', 'tutorialUrl', 'restricted').order_by('title') for library in librariesResult: ...
# Load language file(JSON) from database. # This is used to translate the editor fields(title, description, etc...) ## def getLanguage(self, machineName, majorVersion, minorVersion, language): # Load translation field from DB cursor = connection.cursor() cursor.execute(""" SELEC...
rhyolight/nupic.son
app/soc/models/user.py
Python
apache-2.0
5,797
0.009488
# Copyright 2008 the Melange authors. # # 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 wr...
""" @property def url_id(self): """URL ID pro
perty. It provides a unique string identifier of the user that is to be used as a part of various URLs. The returned string is URL safe and can be validated by linkable.LINK_ID_REGEX regular expression. Returns: a string containing URL ID property """ return self.key().name() #: A Goo...
svenvandescheur/recordstore
recordstore/core/migrations/0012_auto_20151209_2019.py
Python
mit
1,594
0.003137
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2015-12-09 20:19 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency...
], ), migrations.AddField( model_name='artist', name='collection', field=models.ForeignKey(default=0, on_delete=django.db.models.deletion.CASCADE, to='core.Collection'), preserve_default=False, ), migrations.AddField( mo...
n_delete=django.db.models.deletion.CASCADE, to='core.Collection'), preserve_default=False, ), migrations.AddField( model_name='track', name='collection', field=models.ForeignKey(default=0, on_delete=django.db.models.deletion.CASCADE, to='core.Collection'),...
neldom/qessera
developers/apps.py
Python
mit
136
0
from __f
uture__ import unicode_literals from django.apps import AppConfig class DevelopersConfig(AppConfig): name = 'developers'
rolando-contrib/scrapy
scrapy/spidermiddlewares/httperror.py
Python
bsd-3-clause
1,921
0.001562
""" HttpError Spider Middleware See documentation in docs/topics/spider-middleware.rst """ import logging from scrapy.exceptions import IgnoreRequest logger = logging.getLogger(__name__) class HttpError(IgnoreRequest): """A non-200 response was filtered""" def __init__(self, response, *args, **kwargs): ...
fo( "Ignoring response %(response)r: HTTP status code is n
ot handled or not allowed", {'response': response}, extra={'spider': spider}, ) return []
zepheira/amara
lib/xpath/locationpaths/predicates.py
Python
apache-2.0
7,392
0.001894
######################################################################## # amara/xpath/locationpaths/predicates.py """ A parsed token that represents a predicate list. """ from __future__ import absolute_import from itertools import count, izip from amara.xpath import datatypes from amara.xpath.expressions.basics impo...
_str__(self): return self.__unicode__().encode('utf-8') def __repr__(self): ptr = id(self) if ptr < 0: ptr += 0x100000000L return '<%s at 0x%x: %s>'
% (self.__class__.__name__, ptr, self) def __unicode__(self): return u''.join(map(unicode, self)) #FIXME: should this derive from boolean_expression? class predicate: def __init__(self, expression): self._expr = expression self._provide_context_size = False #See http://trac.xml3k.org...
winxos/python
smartrpi/ipreport.py
Python
mit
789
0.032953
#raspberry pi states remote query service #winxos 2016-6-10 import socket import time version="1.0" port=9000 s=socket.socket(soc
ket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) s.setsockopt(socket.SOL_SOCKET,socket.SO_BROADCAST,1) s.bind(('',port)) if __name__=='__main__': print("query service sta
rting...") while True: data,addr=s.recvfrom(1024) print("%s:%s"%(addr,data)) datas=data.split() if len(datas)==0:continue if datas[0]=="RPI": if len(datas)==1: s.sendto("IPR",addr) else: if datas[1]=="NAME": ...
SVilgelm/CloudFerry
cloudferry/lib/os/compute/instances.py
Python
apache-2.0
4,200
0
# Copyright 2015 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, so...
ord): return cls(flavor_id=db_record['flavorid'], tenant_id=db_record['project_id']) @classmethod def from_novaclient_object(cls, nc_flavor_access): return cls(flavor_id=nc_flavor_access.flavor_id, tenant_id=nc_flavor_access.tenant_id) def get_flavor_acce...
id, itp.project_id " "FROM instance_types it " "RIGHT JOIN instance_type_projects itp " "ON it.id = itp.instance_type_id " "WHERE it.flavorid = :flavor_id AND it.deleted = 0;") return db.execute(sql, flavor_id=flavor_id) def nova_live_migrate_vm(nova_client, config, vm_...
dongguangming/python-phonenumbers
python/phonenumbers/data/region_KI.py
Python
apache-2.0
1,560
0.008974
"""Auto-generated file, do not edit by hand. KI metadata""" from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_KI = PhoneMetadata(id='KI', country_code=686, international_prefix='00', general_desc=PhoneNumberDesc(national_number_pattern='[2458]\\d{4}|3\\d{4,7}|7\\d{7}', possibl...
n=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), voicemail=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), no_international_dial
ling=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), national_prefix_for_parsing='0')
UTNkar/moore
src/home/migrations/0015_auto_20180605_1111.py
Python
agpl-3.0
775
0.00129
# Generated by Django 2.0.5 on 2018-06-05 09:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('home', '0014_auto_20170725_1302'), ] operations = [ migrations.AlterField( model_name='formfield', name='field_type'...
dels.CharField(choices=[(
'singleline', 'Single line text'), ('multiline', 'Multi-line text'), ('email', 'Email'), ('number', 'Number'), ('url', 'URL'), ('checkbox', 'Checkbox'), ('checkboxes', 'Checkboxes'), ('dropdown', 'Drop down'), ('multiselect', 'Multiple select'), ('radio', 'Radio buttons'), ('date', 'Date'), ('datetime', 'Date/time'), (...
ulif/wordlist-gen
tests/test_libwordlist.py
Python
gpl-3.0
27,107
0
# -*- coding: utf-8 -*- # diceware_list -- generate wordlists for diceware # Copyright (C) 2016-2019. Uli Fouquet # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the ...
JjKk" assert normalize("ĹĺĻļĽľĿŀŃńŅņŇňŌō") == "LlLlLlL·l·NnNnNnOo" assert normalize("ŎŏŐőŔŕŖŗŘřŚśŜŝŞşŠš") == "OoOoRrRrRrSsSsSsSs" assert normalize("ŢţŤťŨũŪūŬŭŮůŰűŲų") == "TtTtUu
UuUuUuUuUu" assert normalize("ŴŵŶŷŸŹźŻżŽžſ") == "WwYyYZzZzZzs" # "þĦħĦħıĸŁłŊŋʼnŒœŦŧƀƁƂƃƄƅƆƇƈƉƊƋƌƍ"" assert normalize("mäßig") == "maessig" def test_normalize_gives_text(): # we get unicode/text strings back assert isinstance(normalize("far"), type("text")) assert isinstance(normalize("fär"), ty...
ecreall/lagendacommun
lac/views/services_processes/import_service/see_service.py
Python
agpl-3.0
1,732
0.001732
# Copyright (c) 2014 by Ecreall under licence AGPL terms # available on http://www.gnu.org/licenses/agpl.html # licence: AGPL # author: Amen Souissi from pyramid.view import view_config from pyramid.httpexceptions import HTTPFound from dace.util import getSite from dace.processinstance.core import DEFAULTMAPPING_A...
View(BasicView): title = '' name = 'seeimportservice' behaviors = [SeeImportService] template = 'lac:views/services_processes/import_service/templates/see_import_service.pt' viewid = 'seeimportservice' def update(self): self.execute(None) result = {} try: nav...
, self.request) except ObjectRemovedException: return HTTPFound(self.request.resource_url(getSite(), '')) values = {'object': self.context, 'navbar_body': navbars['navbar_body']} body = self.content(args=values, template=self.template)['body'] item = self.a...
zcbenz/cefode-chromium
native_client_sdk/src/build_tools/tests/sdktools_test.py
Python
bsd-3-clause
8,659
0.005197
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import re import subprocess import sys import tarfile import tempfile import test_server import unittest import zipfile ...
process = subprocess.Popen(cmd, stdout=subprocess.PIPE) _, _ = process.communicate() self.assertEqual(process.retur
ncode, 0) def _BuildUpdaterArchive(self, rel_path, revision): """Build a new sdk_tools bundle. Args: rel_path: The relative path to build the updater. revision: The revision number to give to this bundle. Returns: A manifest_util.Archive() that points to this new bundle on the local ...
GoblinLedger/wowapi
wowapi/__init__.py
Python
mit
9,460
0.00222
import requests """The available regions""" REGIONS = { 'US': 'https://us.api.battle.net/wow', 'EU': 'https://eu.api.battle.net/wow', 'KR': 'https://kr.api.battle.net/wow', 'TW': 'https://tw.api.battle.net/wow' } """The available fields for use to get more detailed information for a specific character...
get_resource(resourceUrl) def spell(self, spellId): """Returns some information for the given spellId""" resourceUrl = "/spell/{0}".format(spellId) return self.get_resource(resourceUrl) def battlegroups(self): """Returns a list of battlegroups for the region""" resource...
ceUrl) def character_races(self): """Returns a list of each race and their associated faction, name, uniqueId, and skin""" resourceUrl = "/data/character/races" return self.get_resource(resourceUrl) def character_classes(self): """Returns a list of character classes""" ...
noironetworks/neutron
neutron/_i18n.py
Python
apache-2.0
1,049
0
# 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 agreed to in...
s # u
nder the License. import oslo_i18n DOMAIN = "neutron" _translators = oslo_i18n.TranslatorFactory(domain=DOMAIN) # The primary translation function using the well-known name "_" _ = _translators.primary # The contextual translation function using the name "_C" _C = _translators.contextual_form # The plural transla...
kaplun/Invenio-OpenAIRE
modules/websubmit/lib/bibdocfile_regression_tests.py
Python
gpl-2.0
12,722
0.011083
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2009, 2010, 2011 CERN. ## ## Invenio 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 yo...
pg', vers
ion='1').get_version(), 1) #set description my_new_bibdoc.set_description('new description', '.jpg', version=1) #get description self.assertEqual(my_new_bibdoc.get_description('.jpg', version=1), 'new description') #set comment my_new_bibdoc.set_description('new comment',...
Lapeth/timeline
Timeline/util/Permissions.py
Python
apache-2.0
211
0.009479
from django.core.exceptions import Permissio
nDenied def require_permission(user,
*args): for arg in args: if not user.has_perm(arg): raise PermissionDenied("Action %s not allowed" % arg)
gregkorte/Python-Koans
python3/koans/about_class_attributes.py
Python
mit
4,882
0.001639
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Based on AboutClassMethods in the Ruby Koans # from runner.koan import * class AboutClassAttributes(Koan): class Dog: pass def test_objects_are_objects(self): fido = self.Dog() self.assertEqual(True, isinstance(fido, object)) def...
wl, arg: cls=" + cls.__name__ def test_since_classes_are_objects_you_can_define_singleton_methods_on_them_too(self): self.assertRegex(self.Dog2.growl(), 'classmethod growl, arg: cls=Dog2') def test_classmethods_are_not_independent_of_instance_methods(self): fido = self.Dog2() self.asse...
.growl(), 'classmethod growl, arg: cls=Dog2') self.assertRegex(self.Dog2.growl(), 'classmethod growl, arg: cls=Dog2') def test_staticmethods_are_unbound_functions_housed_in_a_class(self): self.assertRegex(self.Dog2.bark(), 'staticmethod bark, arg: None') def test_staticmethods_also_overshadow_...
jayceyxc/hue
apps/jobbrowser/src/jobbrowser/apis/workflow_api.py
Python
apache-2.0
6,200
0.009194
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
TERING from oozie.views.dashboard import get_oozie_job_log, list_oozie_workflow, manage_oozie_jobs, bulk_manage_oozie_jobs, has_dashboard_jobs_access, massaged_oozie_jobs_for_json except Exception, e: LOG.exception('Some applications are not enabled for Job Browser v2: %s' % e) clas
s WorkflowApi(Api): def apps(self, filters): kwargs = {'cnt': OOZIE_JOBS_COUNT.get(), 'filters': []} text_filters = _extract_query_params(filters) if not has_dashboard_jobs_access(self.user): kwargs['filters'].append(('user', self.user.username)) elif 'user' in text_filters: kwargs['fil...
OrangeShark/senior-project
cn/grammar.py
Python
gpl-3.0
8,351
0.022393
from cn import ast,tokenSpec tokens = tokenSpec.tokens precedence = ( ('left', 'OR', 'AND'), ('left', 'EQ', 'NE', 'LE', 'LT', 'GT', 'GE'), ('left', 'PLUS', 'MINUS'), ('left', 'TIMES', 'DIVIDE'), ('left', 'MOD'), ('right', 'PIPE') ) def p_program(t): 'program : imports declaration_list...
| iteration_stmt | return_stmt | var_dec_stmt | array_dec_stmt''' t[0] = t[1] def p_var_dec_stmt(t): '''var_dec_stmt : type ID SEMI | type ID ASSIGN expression SEMI''' if len(t) == 4: t[0] = ast.VariableDeclaration(t[1], t[2]) else: t[0]...
= ast.VariableDeclaration(t[1], t[2], t[4]) def p_array_dec_stmt(t): '''array_dec_stmt : type ID LBRACKET INTLIT RBRACKET SEMI | type ID LBRACKET INTLIT RBRACKET array SEMI''' if len(t) == 7: t[0] = ast.ArrayDeclaration(t[1], t[2], t[4]) else: t[0] = ast.ArrayDeclaration(t[1], t[2], t...