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
hblancolo/ptavi-p4
server.py
Python
gpl-2.0
2,750
0.000728
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ Clase (y programa principal) para un servidor de eco en UDP simple """ import sys import socketserver import time import json class SIPRegisterHandler(socketserver.DatagramRequestHandler): """ Echo server class """ dic = {} # almacena nombre usuario e ...
""" fich_json = open('registered.json', 'w') codigo_json = json.dumps(self.dic) fich_json.write(codigo_json) fich_json.close() def json2registered(self): """ Si existe un fichero registered.json con un registro almacenado, lo utiliza en el servidor R...
): """ Manejador de peticiones de cliente. Sólo hace algo cuando recibe peticiones tipo REGISTER """ line_str = self.rfile.read().decode('utf-8') list_linecontent = line_str.split() self.json2registered() if list_linecontent[0] == 'REGISTER': u...
jiadaizhao/LeetCode
0801-0900/0805-Split Array With Same Average/0805-Split Array With Same Average.py
Python
mit
507
0.00789
class Solution: def splitArraySameAverage(self, A: List[int]) -> bool: total = sum(A) n = len(A) if all(total*i%n for i in range(n//2 + 1)): return False sums = [set() for _ in range(1 + n // 2)] sums[0].add(0) for num in A:
for i in range(n//2, 0, -1): for s in sums[i - 1]: sums[i].add(s + num)
return any(total*i%n == 0 and total*i//n in sums[i] for i in range(1, 1 + n//2))
viswimmer1/PythonGenerator
data/python_files/34574373/cmss.py
Python
gpl-2.0
2,623
0.014487
import win32pipe import win32console import win32process import time import win32con import codecs import ctypes user32 = ctypes.windll.user32 CONQUE_WINDOWS_VK = { '3' : win32con.VK_CANCEL, '8' : win32con.VK_BACK, '9' : win32con.VK_TAB, '12' : win32con.VK_CLEAR, '13' : win32con.V...
None, 0, flags, None, '.', si) time.sleep(1) #size = con_stdout.GetConsoleScreenBufferInfo()['Window'] # with codecs.open("log.txt", "w", "utf8") as f: # for i in xrange(0, size.Bottom): # f.write(con_stdout.ReadConsoleOutputCharacter(size.Right+1, coord(0, i))) # f.write("\n") import socket s = soc...
s.bind((HOST, PORT)) s.listen(1) (sc, scname) = s.accept() while True: msg = sc.recv(1) if ord(msg) == 0: break keys = [make_input_key(msg)] if keys: con_stdin.WriteConsoleInput(keys) win32process.TerminateProcess(handle1, 0)
openbmc/openbmc-test-automation
bin/validate_plug_ins.py
Python
apache-2.0
3,734
0.004017
#!/usr/bin/env python3 import sys try: import __builtin__ except ImportError: import builtins as __builtin__ import os # python puts the program's directory path in sys.path[0]. In other words, the user ordinarily has no way # to override python's choice of a module from its own dir. We want to have that a...
n our environment. # However, we don't want to break any established python modules that depend on this behavior. So, we'll # save the value from sys.path[0], delete it, import our modules and then restore sys.path to its original # value. save_path_0 = sys.path[0] del sys.path[0] from gen_print import *
from gen_arg import * from gen_plug_in import * # Restore sys.path[0]. sys.path.insert(0, save_path_0) # Create parser object to process command line parameters and args. # Create parser object. parser = argparse.ArgumentParser( usage='%(prog)s [OPTIONS] [PLUG_IN_DIR_PATHS]', description="%(prog)s will vali...
antoinecarme/pyaf
tests/artificial/transf_RelativeDifference/trend_LinearTrend/cycle_7/ar_/test_artificial_128_RelativeDifference_LinearTrend_7__20.py
Python
bsd-3-clause
275
0.083636
import pyaf.Bench.TS_datasets as tsds import tes
ts.artificial.process_artificial_dataset as art art.process_dataset(N = 128 , FREQ = 'D', seed = 0, trendtype = "LinearTrend", cycle_length = 7, transform = "RelativeDifference", sigma = 0.0, exog_count =
20, ar_order = 0);
abhijithmannath/ml-ceeri
geo/views.py
Python
gpl-3.0
594
0.035354
from django.shortcuts import render from .
models import GeoLocation from django.http import HttpResponse def log_location(request): """ :params :lat - latitude :lon - longitude :user_agent - useful for IOT applications that needs to log the client that send the location """ if request.method == 'GET': user_agent = request.GET.get('user_...
at'] lon = request.GET['lon'] GeoLocation.objects.create(user_agent=user_agent,lat=lat,lon=lon) except: return HttpResponse(0, status=500) return HttpResponse(1, status=200)
PHB-CS123/graphene
graphene/storage/base/relationship_store.py
Python
apache-2.0
7,198
0
import struct from graphene.storage.base.general_store import * from graphene.storage.base.relationship import * class RelationshipStore(GeneralStore): """ Handles storage of relationships to a file. It stores relationships using the format: (inUse_direction, firstNode, secondNode, relType, firstPrev...
relationship.relType, relationship.firstPrevRelId, relationship.firstNextRelId, relationship.secondPrevRelId, ...
RelId, relationship.propId) return packed_data def empty_struct_data(self): """ Creates a packed struct of 0s :return: Packed class struct of 0s """ empty_struct = struct.Struct(self.STRUCT_FORMAT_STR) packed_d...
s0undt3ch/Deluge
deluge/plugins/Execute/deluge/plugins/execute/core.py
Python
gpl-3.0
5,677
0.002114
# # core.py # # Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com> # # Deluge is free software. # # You may redistribute it and/or modify it under the terms of the # GNU General Public License, as published by the Free Software # Foundation; either version 3 of the License, or (at your option) # any later version....
""" def __init__(self, command_id): sel
f._args = [command_id] class Core(CorePluginBase): def enable(self): self.config = ConfigManager("execute.conf", DEFAULT_CONFIG) event_manager = component.get("EventManager") self.registered_events = {} # Go through the commands list and register event handlers for command ...
team-xue/xue
xue/tutor/admin.py
Python
bsd-3-clause
1,563
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals, division from xue.tutor.models import * from django.contrib import admin
class TutorProjectAdmin(admin.ModelAdmin): list_display = ( 'get_teacher_na
me', 'teacher', 'name', 'year', ) list_filter = ( 'year', ) class StudentProjectAdmin(admin.ModelAdmin): list_display = ( 'get_student_realname', 'student', 'status', 'get_project_year', ...
OpenAcademy-OpenStack/nova-scheduler
nova/api/openstack/compute/plugins/v3/extended_volumes.py
Python
apache-2.0
9,702
0.000103
# Copyright 2013 OpenStack Foundation # # 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...
e_id = body['detach']['volume_id'] LOG.audit(_("Detach volume %(volume_id)s from " "instance
%(server_id)s"), {"volume_id": volume_id, "server_id": id, "context": context}) try: instance = self.compute_api.get(context, server_id) except exception.InstanceNotFound as e: raise exc.HTTPNotFound(explanation=e.format_mes...
danya02/raspi-gpio-glyphs
bin/all-leds-blink-single.py
Python
mit
345
0.049275
#!/usr/bin/python pos="/home/pi/gpio-glyphs/bin/" import RPi.GPIO as gpio import json import time flag=False gpio.setwarnings
(False) delay=1 gpio.setmode(gpio.BOARD) conv=json.load(open(pos+"conv.json")) for i in conv: gpio.setup(conv
[i],gpio.OUT) for j in range(0,2): flag=not flag for i in conv:gpio.output(conv[i],flag) time.sleep(delay)
AdamISZ/joinmarket_core
joinmarket_core/slowaes.py
Python
gpl-3.0
28,009
0.000428
#!/usr/bin/python # # aes.py: implements AES - Advanced Encryption Standard # from the SlowAES project, http://code.google.com/p/slowaes/ # # Copyright (c) 2008 Josh Davis ( http://www.josh-davis.org ), # Alex Martelli ( http://www.aleax.it ) # # Ported from C code written by Laurent Haan ( http://www.prog...
for x in map(ord, s[-numpads:-1])): raise ValueError("Invalid PKCS7 padding") return s[:-numpads] class AES(object): # valid key sizes
keySize = dict(SIZE_128=16, SIZE_192=24, SIZE_256=32) # Rijndael S-box sbox = [0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, ...
pyphrb/myweb
app/plugin/nmap/libnmap/objects/os.py
Python
apache-2.0
13,080
0.000076
# -*- coding: utf-8 -*- import warnings from libnmap.objects.cpe import CPE class OSFPPortUsed(object): """ Port used class: this enables the user of NmapOSFingerprint class to have a common and clear interface to access portused data which were collected and used during os fingerprint sc...
if 'osgen' in _osclass: self._osgen = _osclass['osgen'] if 'type' in _osclass: self._type = _osclass['type'] self._cpelist = [] for _cpe in osclass_dict['cpe']: self._cpelist.append(CPE(_cpe)) @property def cpelist(self): """ Ret...
:return: list of CPE objects :rtype: Array """ return self._cpelist @property def vendor(self): """ Accessor for vendor information (Microsoft, Linux,...) :return: string """ return self._vendor @property def osfa...
c3nav/c3nav
src/c3nav/editor/migrations/0015_changeset_last_state_update.py
Python
apache-2.0
1,114
0.002693
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-07-05 13:48 from __future__ import unicode_literals from django.core.exceptions import ObjectDoesNotExist from django.db import migrations, models import django.db.models.deletion def forwards_func(apps, schema_editor): ChangeSet = apps.get_model('edit...
: dependencies = [ ('editor', '0014_last_update_foreign_key'), ] operations = [ migrations.AddField( model_name='changeset', name='last_state_update', field=mo
dels.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='editor.ChangeSetUpdate', verbose_name='last state update'), ), migrations.RunPython(forwards_func, reverse_func), ]
mmmikael/vlfeat
python/vlfeat/demo/vl_demo_sift_edge.py
Python
gpl-2.0
733
0.051842
import Image import numpy import pylab import vlfeat from vlfeat.plotop.vl_plotframe import vl_plotframe if __name__ == '__main__': """ VL_DEMO_SIFT_EDGE Demo: SIFT: edge treshold """ I = numpy.zeros([100, 500]) for i in 10 * (1+numpy.arange(9)): d = numpy.round(i / 3.0) I[50-d-1:50+d-1, i * 5-1] = 1 I = n...
, 'f', order='F') I = 2 * numpy.pi * 8 ** 2 * vlfeat.vl_imsmooth(I, 8) I = 255 * I I = numpy.array(I, 'f', order='F') print 'sift_edge_0' ter = [3.5, 5, 7.5, 10] for te in ter: f, d = vlfeat.vl_sift(I, peak_thresh=0.0, edge_thresh=te) pylab.figure() pylab.gray()
pylab.imshow(I) vl_plotframe(f, color='k', linewidth=3) vl_plotframe(f, color='y', linewidth=2) pylab.show()
satish-avninetworks/murano
murano/tests/functional/engine/test_deployment.py
Python
apache-2.0
5,629
0
# Copyright (c) 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 w...
_service(environment, post_body, session, to_dict=True) post_body = { "name": self.rand_name("lighttest"), "updater": updater, "?": {
"type": "io.murano.apps.test.Lighttpd", "id": str(uuid.uuid4()) } } self.add_service(environment, post_body, session) self.deploy_environment(environment, session) self.status_check(environment, [[updater['instance'][...
astrofrog/reducer
reducer/image_browser.py
Python
bsd-3-clause
12,267
0.000326
from __future__ import (division, print_function, absolute_import, unicode_literals) from collections import OrderedDict import os from io import BytesIO import numpy as np from astropy.io import fits import msumastro from .notebook_dir import get_data_path from .ipython_version_helper impo...
) - x.min()) img = Image.fromarray((x*256).astype('uint8')) img_buffer = BytesIO() img.save(img_buffer, format='png') return img_buffer.getvalue() class FitsViewer(object): """ Display the image and header from a single FITS file. """ def __init__(self): self._top = widgets.T...
u.data self._png_image = None # ndarray_to_png(self._data) self._header = '' self._image = widgets.Image() self._header_display = widgets.Textarea(disabled=True) self._top.children = [self._image, self._header_display] @property def top(self): return self._top ...
ratnania/pyccel
tests/codegen/scripts/tuples.py
Python
mit
288
0.013889
ai = (1
,4,5) ai[0] = 2 bi = ai[0] ci = 2 * ai[0] di = 2 * ai[0] + 3 * ai[1] ei = 2 * ai[0] + bi * ai[1] fi = ai gi = (0,)*2 gi[:] = ai[1:] ad = (1.,4.,5.) ad[0] = 2. bd = ad[0] cd = 2. * ad[0] dd = 2. * ad[0] + 3. * ad[1] ed = 2. * ad[0] + bd * ad[1] fd = ad gd = (0.,)*2 gd[:] = ad[1:]
dddTESTxx/Gym-Final
src/data/tests.py
Python
mit
268
0.003731
import unittest from click.tes
ting import CliRunner from make_dataset import main class TestMain(unittest.TestCase): def test_main_runs(self): runner = CliRunner() result = runner.invoke(main, ['.', '.']) assert result.exit_code == 0
shazamengineering/gearman-geodis
setup.py
Python
apache-2.0
570
0.019298
from distutils.core import setup PKGLIST = ['gearman_geodis'] setup(name='gearman-geodis', version='1.0.0', description='Geolocation Gearman worker powered by Geodis',
author_email='engineering@shazamteam.com', license='Apache License, Version 2.0', packages=PKGLIST, scripts=['gearman_geodis/geodis_worker.py', 'gearman_geodis/gearman_geodisd.py', 'gearman_geodis/std
in_geodis_worker.py'], data_files=[('/etc/sysconfig/',['support/gearman_geodis.sysconfig']), ('/etc/init.d/',['support/gearman_geodis'])] )
WorldBank-Transport/DRIVER
app/data/migrations/0011_copy_ashlar_tables.py
Python
gpl-3.0
2,467
0.00527
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2018-09-10 18:20 from __future__ import unicode_literals from django.db import migrations from django.db import connection def table_exists(tablename): cursor = connection.cursor() cursor.execute( """SELECT EXISTS (SELECT * FROM pg_tables WHERE...
rout_record (LIKE ashlar_record INCLUDING ALL);') cursor.execute('INSERT INTO grout_record SELECT * FROM ashlar_record;') def reverse(apps, schema_editor): cursor = connection.cursor() # The only time we would reverse is if we know that we previously used Ashlar, which we can only # know for sure ...
shlar_table, grout_table in tables: cursor.execute('ALTER TABLE {g} RENAME TO {a};'.format(a=ashlar_table, g=grout_table)) cursor.execute('DROP TABLE grout_record;') class Migration(migrations.Migration): dependencies = [ ('data', '0010_auto_20160527_2236'), ] operations = [ ...
badock/nova
nova/virt/libvirt/volume.py
Python
apache-2.0
47,624
0.000294
# Copyright 2011 OpenStack Foundation # (c) Copyright 2013 Hewlett-Packard Development Company, L.P. # 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 # # ...
ount_point_base', default=paths.state_path_def('mnt'), help='Directory where the NFS volume is mounted on the' ' compute node'), cfg.StrOpt('nfs_m
ount_options', help='Mount options passedf to the NFS client. See section ' 'of the nfs man page for details'), cfg.IntOpt('num_aoe_discover_tries', default=3, help='Number of times to rediscover AoE target to find volume'), cfg.StrOpt('glusterfs_...
macopedia/hr
__unported__/hr_language/hr_language.py
Python
agpl-3.0
2,057
0
# -*- encoding: utf-8 -*- ############################################################################### # # OpenERP, Open Source Management Solution # Copyright (C) 2013 Savoir-faire Linux (<http://www.savoirfairelinux.com>). # # This program is free software: you can redistribute it and/or modify # it un...
Employee', required=True, ), 'read': fields.boolean( 'Read', ), 'write': fields.boolean( 'Write', ),
'speak': fields.boolean( 'Speak', ), } _defaults = { 'read': True, 'write': True, 'speak': True, } class hr_employee(orm.Model): _inherit = 'hr.employee' _columns = { 'language_ids': fields.one2many( 'hr.language', ...
lawzou/shoop
shoop_setup_utils/__init__.py
Python
agpl-3.0
780
0
# This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from .commands import COMMANDS from .excludes import set_exclude_patters, get_exclude_patterns from ...
'build_resources', 'find_packages', 'get_exclude_patterns', 'get_long_description', 'get_test_requirements_from_tox_ini', 'get_version', 'set_exclude_patters', 'write_v
ersion_to_file', ]
USGSDenverPychron/pychron
pychron/dashboard/tasks/client/preferences.py
Python
apache-2.0
1,997
0.001002
# =============================================================================== # Copyright 2014 Jake Ross # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses...
ent")) return v class DashboardClientPreferences(BasePreferencesHelper): preferences_path = "pychron.dashboard.client" host = Str port = Int class DashboardClientPreferencesPane(PreferencesPane): model_factory = DashboardClientPreferences category = "Dashboard" def traits_view(self)...
) return v # ============= EOF =============================================
dogebuild/dogebuild-hello
dogebuild_hello/loader.py
Python
mit
74
0.013514
from dogebuild_hello.h
ello import Hello def get()
: return Hello()
oxc/Flexget
flexget/plugins/cli/try_regexp.py
Python
mit
2,592
0.001929
from __future__ import unicode_literals, division, absolute_import from builtins import * # pylint: disable=unused-import, redefined-builtin from past.builtins import basestring import logging from flexget import options, plugin from flexget.event import event from flexget.terminal import console log = logging.getL...
count, len(task.entries))) console('Bye!') @event('plugin.register') def register_plugin(): plugin.register(PluginTryRegexp, '--try-regexp', builtin=True, api_ver=2) @event('options.register') def register_parser_arguments(): opt
ions.get_parser('execute').add_argument('--try-regexp', action='store_true', dest='try_regexp', default=False, help='try regular expressions interactively')
OmnesRes/pan_cancer
paper/tables/S1/table_creation.py
Python
mit
5,368
0.062221
##A script for creating tables for each cancer, with the data sorted def compare(first,second): if float(first[-2])>float(second[-2]): return 1 elif float(first[-2])<float(second[-2]): return -1 else: return 0 ## Load necessary modules import os BASE_DIR = os.path.dirname(os.path....
r i in f] i
ds,coeffs,normalized,pvalues,adjusted=zip(*data) LUSC=zip(ids,[id_to_gene[i] for i in ids],coeffs,normalized,pvalues,adjusted) f=open(os.path.join(BASE_DIR,'cox_regression','OV','coeffs_normalized_pvalues_adjusted.txt')) data=[i.strip().split() for i in f] ids,coeffs,normalized,pvalues,adjusted=zip(*data) OV=zip(ids,[...
nkripper/pynet
week2/snmp_helper.py
Python
apache-2.0
6,852
0.002043
# Requires the pysnmp4 library # Example usage (SNMPv1/SNMPv2c): # >>> from snmp_helper import snmp_get_oid,snmp_extract # >>> # >>> COMMUNITY_STRING = '<COMMUNITY>' # >>> SNMP_PORT = 161 # >>> a_device = ('1.1.1.1', COMMUNITY_STRING, SNMP_PORT) # Use the MIB-2 sysDescr as a test # >>> snmp_data = snmp_get_oid(a_device...
p.keys(): encrypt_protocol = encrypt_proto_map[encrypt_proto] else: raise ValueError("Invalid encryption protocol specified: %s" % encrypt_proto) # Create a PYSNMP cmdgen object cmd_gen = cmdgen.CommandGenerator() (error_detected, error_status, error_index, snmp_data) = cmd_gen.getCmd...
encrypt_key, authProtocol=auth_protocol, privProtocol=encrypt_protocol, ), cmdgen.UdpTransportTarget(snmp_device), oid, lookupNames=True, lookupValues=True ) if not error_detected: return snmp_data else: if displa...
LLNL/spack
var/spack/repos/builtin/packages/openfoam-org/package.py
Python
lgpl-2.1
16,158
0.001176
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) # # Original Author: Mark Olesen <mark.olesen@esi-group.com> # # Legal Notice # ------------ # OPENFOAM is a trademark own...
sha256='73103e6b1bdbf3b1e0d517cbbd11562e98c6e9464df5f43e5125e9a5b457d1c5', when='@7') patch('50-etc.patch', when='@5.0:5.9') patch('41-etc.patch', when='@4
.1') patch('41-site.patch', when='@4.1:') patch('240-etc.patch', when='@:2.4.0') patch('isnan.patch', when='@:2.4.0') # Add support for SYSTEMMPI patch('https://github.com/OpenFOAM/OpenFOAM-2.3.x/commit/ae9a670c99472787f3a5446ac2b522bf3519b796.patch', sha256='6c4c535baca3ce64035d512265c4ce...
leapcode/soledad
src/leap/soledad/client/_db/blobs/sync.py
Python
gpl-3.0
7,065
0
# -*- coding: utf-8 -*- # sync.py # Copyright (C) 2017 LEAP # # 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 version. # # This p...
er.inlineCallbacks def with_retry(func, *args, **kwargs): """ Run func repeatedly until success, as long as the exception raised is a "retriable error". If an exception of another kind is raised by func, the retrying stops and that exception is propagated up the stack. """ retry_wai
t = 1 retriable_errors = (error.ConnectError, error.ConnectionClosed, RetriableTransferError,) while True: try: yield func(*args, **kwargs) break except retriable_errors: yield sleep(retry_wait) retry_wait = min(retry_wait +...
agrawalabhishek/NAOS
python/plotEllipsoidSurfaceAccelerationLatLong.py
Python
mit
4,657
0.016964
''' Copyright (c) 2016 Abhishek Agrawal (abhishek.agrawal@protonmail.com) Distributed under the MIT License. See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT ''' # Set up modules and packages # I/O import csv from pprint import pprint # Numerical import numpy as np import pandas as pd fr...
.interpolate import griddata import math # System import sys import time from tqdm import tqdm # Get plotting packages import matplotlib import matplotlib.colors import matplotlib.axes import matplotlib.lines as mlines import matplotlib.patches as mpatches import matplotlib.pyplot as plt import matplotlib.mlab as mla...
from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d import axes3d from mpl_toolkits.basemap import Basemap from matplotlib.ticker import LinearLocator, FormatStrFormatter from mpl_toolkits.axes_grid1.inset_locator import inset_axes import matplotlib.tri as tri print "" print "----------------------------...
zygh0st/terminator
terminatorlib/util.py
Python
gpl-2.0
10,216
0.003328
#!/usr/bin/python # Terminator.util - misc utility functions # Copyright (C) 2006-2010 cmsj@tenshu.net # # 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, version 2 only. # # This progr...
idth, height) = pixmap.get_size() pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, width, height) pixbuf.get_from_drawable(pixmap, pixmap.get_colormap(), 0, 0, 0, 0, width, height) longest = max
(width, height) if maxsize is not None: factor = float(maxsize) / float(longest) if not maxsize or (width * factor) > width or (height * factor) > height: factor = 1 scaledpixbuf = pixbuf.scale_simple(int(width * factor), int(height * factor), gtk.gdk.INTERP_BILINEAR) return(scaledpi...
klmitch/python-jenkins
tests/test_plugins.py
Python
bsd-3-clause
13,759
0.000145
# Software License Agreement (BSD License) # # Copyright (c) 2015 Hewlett-Packard Development Company, L.P. # 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 ...
self.plugin_info_json['plugins'][0]) self._check_requests(jenkins_mock.call_args_list) @patch.object(jenkins.Jenkins, 'jenkins_open') def test_get_plugin_info_updated(self, jenkins_mock): jenkins_mock.side_effect
= [ json.dumps(self.plugin_info_json), json.dumps(self.updated_plugin_info_json) ] j = jenkins.Jenkins(self.make_url(''), 'test', 'test') plugins_info = j.get_plugins() self.assertEqual(plugins_info["mailer"]["version"], self.plugin_info_...
rehassachdeva/pydsa
pydsa/queue.py
Python
bsd-3-clause
786
0
class queue(object): """ A queue is a container of objects (a linear collection) that are inserted and removed according to the first-in first-out (FIFO) principle. >>> from
pydsa import queue >>> q = queue() >>> q.enqueue(5) >>> q.enqueue(8) >>> q.e
nqueue(19) >>> q.dequeue() 5 """ def __init__(self): self.List = [] def isEmpty(self): return self.List == [] def enqueue(self, item): """ Insert element in queue. """ self.List.append(item) def dequeue(self): """ Remove ele...
airportmarc/the416life
src/apps/library/apps.py
Python
mit
89
0
from django.apps import AppConfi
g class LibraryConfig(AppConfig): n
ame = 'library'
WarrenWeckesser/scikits-image
doc/examples/plot_regional_maxima.py
Python
bsd-3-clause
3,435
0.000291
""" ========================= Filtering regional maxima ========================= Here, we use morphological reconstruction to create a background image, which we can subtract from the original image to isolate bright features (regional maxima). First we try reconstruction by dilation starting at the edges of the ima...
inus a
fixed value, ``h``. """ h = 0.4 seed = image - h dilated = reconstruction(seed, mask, method='dilation') hdome = image - dilated """ To get a feel for the reconstruction process, we plot the intensity of the mask, seed, and dilated images along a slice of the image (indicated by red line). """ fig, (ax1, ax2, ax3) ...
EDITD/pyinfra-kubernetes
pyinfra_kubernetes/__init__.py
Python
mit
1,938
0
from pyinfra.api import deploy from .configure import configure_kubeconfig, configure_kubernetes_component from .install import install_kubernetes @deploy('Deploy Kubernetes master') def deploy_kubernetes_master( state, host, etcd_nodes, kube_apiserver_kwargs=None, kube_scheduler_kwargs=None, kub...
service_kwargs=kube_scheduler_kwargs, ) # Setup the kube-controller-manager service/config configure_kubernetes_component( state, host, 'kube-controller-manager', service_kwargs
=kube_controller_manager_kwargs, ) @deploy('Deploy Kubernetes node') def deploy_kubernetes_node( state, host, master_address, kubelet_kwargs=None, kube_proxy_kwargs=None, ): # Install node components install_kubernetes( state, host, components=( 'kubelet', 'kube...
ttsui/guppy
src/guppy.py
Python
gpl-2.0
21,484
0.03612
#!/usr/bin/env python ## guppy.py - Main program ## Copyright (C) 2005 Tony Tsui <tsui.tony@gmail.com> ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ...
lf, dir=None): if len(self) > 0: self.clear() if dir: if dir[0] != '\\': dir = self.current_dir + '\\' + dir else: dir = self.current_dir norm_path = os.path.normpath(dir.replace('\\', '/')) if norm_path != '.': self.current_dir = norm_path.replace('/', '\\') else: self.current_dir =...
COL] == 'd': file.insert(FileSystemModel.ICON_COL, gtk.STOCK_DIRECTORY) else: file.insert(FileSystemModel.ICON_COL, gtk.STOCK_FILE) file[FileSystemModel.SIZE_COL] = humanReadableSize(int(file[FileSystemModel.SIZE_COL])) self.append(file) def freeSpace(self): total, free = self.puppy.getDi...
Qwaz/solved-hacking-problem
SCTF/2017 Quals/dfa/solver.py
Python
gpl-2.0
308
0
from pwn import * import base64 p = remote('dfa.eatpwnno
sleep.com', 9999) p.recvline() p.recvline() p.recvline() p.recvline() p.recvline() p.sendline('
auto.c') with open('auto.patch.c', 'r') as f: content = f.read() p.recvuntil('base64 : ') p.sendline(base64.b64encode(content)) print p.recvall()
aprudent/caduceus
caduceus/transform/templateHtmlComment.py
Python
bsd-3-clause
378
0.029101
from caduceus.transform.templateEntity import CaduceusTemplateEntity class CaduceusTemplateHtmlComment(CaduceusTemplateEntity): def __init__(self, text): CaduceusTemplateEntity.__init__(self) self._text = text def render(self, dictGlob, dictLoc
, results): return
"<!-- %s -->%s" % (self._text, CaduceusTemplateEntity.render(self, dictGlob, dictLoc, results))
QuantEcon/QuantEcon.py
docs/qe_apidoc.py
Python
bsd-3-clause
10,122
0.001877
""" Our version of sphinx-apidoc @author : Spencer Lyon @date : 2014-07-16 This file should be called from the command line. It accepts one additional command line parameter. If we pass the parameter `single` when running the file, this file will create a single directory named modules where each module in quantecon ...
Write file for each markov file for mod in markov: new_path = os.path.join("source", "markov", mod + ".rst") with open(new_path, "w") as f: equals = "=" * len(mod) f.write(markov_module_template.format(mod_name=mod, equals=equals)) # Write file for each optimize file ...
new_path, "w") as f: equals = "=" * len(mod) f.write(optimize_module_template.format(mod_name=mod, equals=equals)) # Write file for each random file for mod in random: new_path = os.path.join("source", "random", mod + ".rst") with open(new_path, "w") as f: eq...
bakaat/xhtml2pdf
xhtml2pdf/parser.py
Python
apache-2.0
25,104
0.002948
# -*- coding: utf-8 -*- # Copyright 2010 Dirk Holtwick, holtwick.it # # 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 ...
idth border-right-color border-right-style border-right-width text-align vertical-align width height zoom page-break-after page-break-before list
-style-type list-style-image white-space text-indent -pdf-page-break -pdf-frame-break -pdf-next-page -pdf-keep-with-next -pdf-outline -pdf-outline-level -pdf-outline-open -pdf-line-spacing -pdf-keep-in-frame-mode -pdf-word-wrap '''.strip().split() def getCSSAttr...
bitmazk/django-oscar-asiapay
oscar_integration_example/checkout/app.py
Python
mit
331
0
"""Custom ``checkout`` app.""" from oscar.apps.checkout.app import CheckoutApplication from oscar_custom.checkout import views class OverriddenCheckoutApplication(CheckoutApplication): # Specify new view for payment details payment_details_view = views.PaymentDetailsView appl
ication = OverriddenCheckoutApplication()
Subarno/MachineLearningPracticePrograms
transfer.py
Python
gpl-3.0
565
0
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import numpy as np from kera
s.preprocessing import image from keras.applications.resnet50 import * model = ResNet50(weights=None) model.load_weights('resnet50_weights_tf_dim_ordering_tf_kernels.h5py') img = image.load_img('data/deer.jpg', target_size=(224, 224)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) ...
ions(preds, top=5)[0])
food52/thumbor
thumbor/transformer.py
Python
mit
12,511
0.002398
#!/usr/bin/python # -*- coding: utf-8 -*- # thumbor imaging service # https://github.com/globocom/thumbor/wiki # Licensed under the MIT license: # http://www.opensource.org/licenses/mit-license # Copyright (c) 2011 globo.com timehome@corp.globo.com import math import sys from thumbor.point import FocalPoint from th...
'right'] -= box[0] self.context.request.crop['bottom'] -= box[1] @property def smart_storage_key(self): return self
.context.request.image_url def smart_detect(self): is_gifsicle = (self.context.request.engine.extension == '.gif' and self.context.config.USE_GIFSICLE_ENGINE) if (not (self.context.modules.detectors and self.context.request.smart)) or is_gifsicle: self.do_image_operations() ...
kscottz/SkinnerBox
modules/__init__.py
Python
mit
120
0.008333
from Har
dwareInterface import * from CameraInterface import * #from ProtocolRunner import * from DataInterface import
*
stephentyrone/swift
utils/gyb_sourcekit_support/UIDs.py
Python
apache-2.0
23,110
0
class KEY(object): def __init__(self, internal_name, external_name): self.internalName = internal_name self.externalName = external_name class REQUEST(object): def __init__(self, internal_name, external_name): self.internalName = internal_name self.externalName = external_name ...
ion_key'), KEY('IsZeroArgSelector', 'key.is_zero_arg_selector'), KEY('SwiftVersion', 'key.swift_version'), KEY('Value', 'key.value'), KEY('EnableDiagnostics', 'key.enablediagnostics'
), KEY('GroupName', 'key.groupname'), KEY('ActionName', 'key.actionname'), KEY('SynthesizedExtension', 'key.synthesizedextensions'), KEY('UsingSwiftArgs', 'key.usingswiftargs'), KEY('Names', 'key.names'), KEY('UIDs', 'key.uids'), KEY('SyntacticOnly', 'key.syntactic_only'), KEY('ParentLoc...
wannaphongcom/flappy
flappy/events/focusevent.py
Python
mit
1,029
0.009718
from event import Event class FocusEvent(Event): FOCUS_IN = "focusIn" FOCUS_OUT = "focusOut" KEY_FOCUS_CHANGE = "keyFocusChange" MOUSE_FOCUS_CHANGE = "mouseFocusChange" def __init__(self, etype, bubbles=True, cancelable=False, relatedObject=None, shiftKey=None, keyCode=0, ...
f.cancelable), str(self.relatedObject), str(self.shiftKey), str(self.
keyCode))
scikit-learn/scikit-learn
sklearn/metrics/_ranking.py
Python
bsd-3-clause
67,892
0.000324
"""Metrics to assess performance on classification task given scores. Functions named as ``*_score`` return a scalar value to maximize: the higher the better. Function named as ``*_error`` or ``*_loss`` return a scalar value to minimize: the lower the better. """ # Authors: Alexandre Gramfort <alexandre.gramfort@inr...
_sample_weight from ..utils import column_or_1d, check_array from ..utils.multiclass import type_of_target
from ..utils.extmath import stable_cumsum from ..utils.sparsefuncs import count_nonzero from ..exceptions import UndefinedMetricWarning from ..preprocessing import label_binarize from ..utils._encode import _encode, _unique from ._base import ( _average_binary_score, _average_multiclass_ovo_score, _check_...
dlakata/VocabFinder
vocabfinder/__init__.py
Python
gpl-2.0
535
0.003738
from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.security import Security, SQLAlchemyUserDatastore from flask.ext.mail import Mail from flask.ext.babel import Babel from flask.ext.migrate import Migrate app = Flask(
__name__) app.config.from_object('config') mail = Mail(app) babel = Babel(app) db = SQLAlchemy(app) migrate = Migrate(app, db) from vocabfinder.models import User, Role datastore = SQLAlchemyUserDatastore(db, User, Role) security = Security(app, datastore) import voca
bfinder.views
waseem18/oh-mainline
vendor/packages/scrapy/scrapy/tests/test_pipeline_media.py
Python
agpl-3.0
10,726
0.002238
from twisted.trial import unittest from twisted.python.failure import Failure from twisted.internet import reactor from twisted.internet.defer import Deferred, inlineCallbacks from twisted.python import log as txlog from scrapy.http import Request, Response from scrapy.spider import BaseSpider from scrapy.utils.reques...
ia_requests'), 1) self.assertEqual(m.count('item_completed'), 1) self.assertEqual(m[-1], 'item_completed') # last hook called # twice, one per request self.
assertEqual(m.count('media_to_download'), 2) # one to handle success and other for failure self.assertEqual(m.count('media_downloaded'), 1) self.assertEqual(m.count('media_failed'), 1) @inlineCallbacks def test_get_media_requests(self): # returns single Request (without callback...
honmaple/maple-bbs
forums/admin/forums.py
Python
gpl-3.0
1,143
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # ************************************************************************** # Copyright © 2016 jianglin # File Name: forums.py # Author: jianglin # Email: xiyang0807@gmail.com # Created: 2016-12-17 13:12:23 (CST) # Last Update:星期五 2017-11-10 11:04:16 (CST) # By: #...
e='管理节点', endpoint='admin_tag',
category='管理社区'))
jrjhealey/bioinfo-tools
Shannon.py
Python
gpl-3.0
6,290
0.006518
# This script will calculate Shannon entropy from a MSA. # Dependencies: # Biopython, Matplotlib, Math """ Shannon's entropy equation (latex format): H=-\sum_{i=1}^{M} P_i\,log_2\,P_i Entropy is a measure of the uncertainty of a probability distribution (p1, ..... , pM) https://stepic.org/lesson/Scoring-...
o be passed in to AlignIO.') parser.add_argument('-v', '--verbose', action='count', default=0, help='Verbose behaviour, printing parameters of the script.')
parser.add_argument('-m', '--runningmean', action='store', type=int, default=0, help='Return the running mean (a.k.a moving average) of the MSAs Shannon Entropy. Makes for ...
toenuff/treadmill
lib/python/treadmill/postmortem.py
Python
apache-2.0
4,780
0.000209
"""Collect Treadmill node information after a crash. """ from __future__ import absolute_import import os import glob import logging import shutil import tempfile from treadmill import fs from treadmill import subproc _LOGGER = logging.getLogger(__name__) _IFCONFIG = 'ifconfig' _SYSCTL = 'sysctl' _DMESG = 'dmesg' ...
up/*/treadmill/core' for cgrp_core in glob.glob(pattern): core_dest = '%s%s' % (destroot, cgrp_core) try: shutil.copytree(cgrp_core, core_dest) except (shutil.Error, OSError): _LOGGER.exception('fail to copy %s => %s', src, dest) def collect_localdisk(approot, dest...
proot dest = '%s%s' % (destroot, src) try: shutil.copytree(src, dest) except (shutil.Error, OSError): _LOGGER.exception('fail to copy %s => %s', src, dest) # FIXME vgdisplay requires root def collect_network(approot, destroot): """Get host network information.""" src = '%s/ne...
nvl1109/testmagic
magicserver/settings.py
Python
gpl-2.0
2,220
0
""" Django settings for magicserver project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ......
o.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.cont
rib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'magicserver.urls' WSGI_APPLICATION = 'magicserver.wsgi.application' # Database # https://docs.djangoproject.com/en/1.7/ref...
dsolimando/Hot
hot-cli/src/main/resources/examples/example.show.py
Python
gpl-3.0
564
0.046099
s = "Hello My friend" def printHello(request):
return s def printJson(request): return {"items":{"name":"damien", "age":8}} def onconnect(connection): def ondata(): c
onnection.write(data) def onclose(): print 'close' connection.data(ondata) connection.close(onclose) show.rest.get("/pyitems").headers(["Accept: text/plain"]).then(printHello) show.rest.get("/pyitems").headers(["Accept: application/json"]).then(printJson) show.rest.put("/pyitem").then(printHello) show.web...
berkmancenter/mediacloud
apps/common/src/python/mediawords/solr/query.py
Python
agpl-3.0
4,650
0.002581
""" Functions for parsing Solr queries. """ import datetime import re from typing import Dict, Any, Optional, List from dateutil.relativedelta import relativedelta from mediawords.db import DatabaseHandler from mediawords.util.log import create_logger from mediawords.util.perl import decode_object_from_bytes_if_need...
if topics_id: if not media_ids: media_ids = db.query(""" SELECT media_id FROM topics_media_map WHERE topics_id = %(topics_id)s """, {'topics_id': topics_id}).flat() if not media_tags_ids: media_tags_ids = db.que
ry(""" SELECT tags_id FROM topics_media_tags_map WHERE topics_id = %(topics_id)s """, {'topics_id': topics_id}).flat() if media_ids: media_ids_list = ' '.join([str(_) for _ in media_ids]) media_clauses.append(f"media_id:( {media_ids_list} ...
dremdem/sfc_sdk
sfc_main.py
Python
mit
4,144
0.003861
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Testing module from creating product using http://www.sendfromchina.com/default/index/webservice """ from flask import Flask, render_template, request from flask_wtf.csrf import CSRFProtect from werkzeug.datastructures import MultiDict from forms import SFCCreateO...
]) def create_order(): res = None if request.method == 'POST': order_info = {k: v for k, v in request.form.items() if k in [i for i in SFCCreateOrder.__dict__.keys() if i[0] != '_']} order_detail = {k: v f
or k, v in request.form.items() if k in [i for i in SFCOrderDetail.__dict__.keys() if i[0] != '_']} res = sfcapi.create_order(p_order_info=order_info, p_order_detail=order_detail) form_order = SFCCreateOrder(MultiDict(order_info)) form_order_detail = SFCOrderDetail(MultiD...
lizardsystem/flooding
flooding/manage.py
Python
gpl-3.0
228
0.008772
import
os i
f not 'DJANGO_SETTINGS_MODULE' in os.environ: os.environ['DJANGO_SETTINGS_MODULE'] = 'flooding.windows' from django.core import management if __name__ == '__main__': management.execute_from_command_line()
maxhutch/pypif
pypif/obj/common/value.py
Python
apache-2.0
4,437
0.002705
import numbers from six import string_types from pypif.obj.common.pio import Pio from pypif.obj.common.scalar import Scalar from pypif.obj.common.file_reference import FileReference class Value(Pio): """ Information about a scalar, vector, or matrix, or a list of one of those. """ def __init__(self, ...
r def scalars(self, scalars): self._validate_list_type('scalars', scalars, dict, string_types, numbers.Number, Scalar) self._scalars = self._get_object(Scalar, scalars) self._scalars = [Scalar.normalize(x) for x
in (self._scalars if isinstance(self._scalars, list) else [self._scalars])] @scalars.deleter def scalars(self): self._scalars = None @property def vectors(self): return self._vectors @vectors.setter def vectors(self, vectors): self._validate_nested_list_type('vectors',...
willpatterson/LogoBatch
logobatch/resources.py
Python
mit
3,909
0.002558
""" For classes managing computing and storage resources """ import os import sys import socket import getpass import paramiko import subprocess from collections import namedtuple class Launcher(object): """ Base class for the lancher objects used to dispatch shell commands to local and remote resources ...
machine""" def launch_command(self, command): """ """ process = subprocess.Popen(command,
shell=False, stdout=subprocess.PIPE) return self.JobOut(process.communicate()) class Resource(object): """ Base class for Resource objects used to launch jobs on different types of remote and local computing resources Base class acts...
eucalyptus/se34euca
3.3.1/se34euca/se34euca/lib/EucaUITestLib_Security_Group.py
Python
bsd-2-clause
7,211
0.002774
from se34euca.lib.EucaUITestLib_Base import * import time class EucaUITestLib_Security_Group(EucaUITestLib_Base): def test_ui_gotopage_security_groups(self): print print "Started Test: GotoPage Security Groups" self.click_element_by_id("euca-logo") print print "Test: Receiv...
roup" print return 0 def test_ui_create_empty_security_group(self): print print "Started Test: Create Security Group" self.cl
ick_element_by_link_text("Dashboard") self.verify_element_by_link_text("Launch new instance") print print "Test: Go to the Page Security Group" self.click_element_by_css_selector("#dashboard-netsec-sgroup > span") self.click_element_by_id("table-sgroups-new") print ...
mattrobenolt/warehouse
warehouse/__about__.tmpl.py
Python
apache-2.0
1,202
0
# Copyright 2013 Donald Stufft # # 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...
unicode_literals # This file is automatically generated, do not edit it __all__ = [ "__title__", "__sum
mary__", "__uri__", "__version__", "__author__", "__email__", "__license__", "__copyright__", ] __title__ = "warehouse" __summary__ = "Next Generation Python Package Repository" __uri__ = "https://github.com/pypa/warehouse" __version__ = "{version}" __build__ = "{build}" __author__ = "Donald Stufft" __email__ = ...
astorfi/TensorFlow-World
docs/conf.py
Python
mit
5,320
0.000752
# -*- coding: utf-8 -*- # # TensorFlow-World documentation build configuration file, created by # sphinx-quickstart on Wed Jun 28 22:26:19 2017. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated fi...
"default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Title html_title = 'TensorFlow World' # -- Options for HTMLHelp output ------------------------------------------ # Output file base name for HTML help builder. htmlhelp_basename = 'TensorFlow-Worlddoc' # If true, links to th...
html_show_sourcelink = False # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. html_show_sphinx = False # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpap...
Bauble/bauble.api
test/spec/test_genus.py
Python
bsd-3-clause
4,372
0.003202
import pytest import bauble.db as db from bauble.model.family import Family from bauble.model.genus import Genus, GenusSynonym, GenusNote import test.api as api @pytest.fixture def setup(organization, session): setup.organization = session.merge(organization) setup.user = setup.organization.owners[0] setu...
n syn_json assert syn_json['genus_id'] == genus.id assert syn_json['synonym_id'] == genus.id session.delete(genus) session.commit() session.close() def test_server(setup): """ Test the server properly handle /genus resources """ user = setup.user family = api.create_resource(...
.create_resource('/genus', {'genus': api.get_random_name(), 'family': family}, user) # create another genus and use the first as a synonym data = {'genus': api.get_random_name(), 'family': family, 'notes': [{'user': 'me', 'category': 'test', 'date':...
lxsmnv/spark
python/pyspark/streaming/tests.py
Python
apache-2.0
62,587
0.001646
# # 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 us...
b", 1), ("b", 1)], [("", 1), ("", 1), ("", 1), ("", 1)], [(1, 1), (1, 1),
(2, 1), (2, 1), (3, 1)]] def func(dstream): return dstream.reduceByKey(operator.add) expected = [[("a", 2), ("b", 2)], [("", 4)], [(1, 2), (2, 2), (3, 1)]] self._test_func(input, func, expected, sort=True) def test_mapValues(self): """Basic operation test for DStream.m...
michaelkirk/QGIS
python/plugins/db_manager/db_plugins/postgis/info_model.py
Python
gpl-2.0
11,526
0.005379
# -*- coding: utf-8 -*- """ /*************************************************************************** Name : DB Manager Description : Database manager plugin for QGIS Date : May 23, 2011 copyright : (C) 2011 by Giuseppe Sucameli email : brush.tyler@...
schema? schema_priv = self.table.database().connector.getSchemaPrivileges( self.table.schemaName()) if self.table.schema() else None if schema_priv is None: pass elif not schema_priv[1]: # no usage privileges on the schema tbl.append((QApplication.translate(...
"<warning> This user doesn't have usage privileges for this schema!") )) else: table_priv = self.table.database().connector.getTablePrivileges((self.table.schemaName(), self.table.name)) privileges = [] if table_priv[0]: privileges.append("se...
csauer42/rover
controller/rover.py
Python
mit
4,030
0.005211
import pygame from pygame.locals import * from threading import Lock from videoreceiver import VideoReceiver from controlio import ControlIO import sys class Rover(object): """Primary control interface for Rover""" FPS = 15 MLIMITLOW = 32 LLIMITLOW = 96 WIDTH = 1280 HEIGHT = 960 BLACK = (0,...
ist[0] * -255) c1 = int(pos_list[1] * -255) c2 = int(pos_list[2] * 512) c3 = int(pos_list[3]
* -512) if c0 < self.MLIMITLOW and c0 > -1 * self.MLIMITLOW: c0 = 0 if c1 < self.MLIMITLOW and c1 > -1 * self.MLIMITLOW: c1 = 0 if c2 < self.LLIMITLOW and c2 > -1 * self.LLIMITLOW: c2 = 0 if c3 < self.LLIMITLOW and c3 > -1 * self.LLIMITLOW: ...
aboganas/frappe
frappe/utils/redis_wrapper.py
Python
mit
4,952
0.030695
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import redis, frappe, re import cPickle as pickle from frappe.utils import cstr class RedisWrapper(redis.Redis): """Redis client that will automatically prefix conf.db_name""" ...
y(key) try: self.delete(key) except redis.exceptions.ConnectionError: pass if key in frappe.local.cache: del frappe.local.cache[key] def lpush(self, key, value): super(redis.Redis, self).lpush(self.make_key(key),
value) def rpush(self, key, value): super(redis.Redis, self).rpush(self.make_key(key), value) def lpop(self, key): return super(redis.Redis, self).lpop(self.make_key(key)) def llen(self, key): return super(redis.Redis, self).llen(self.make_key(key)) def hset(self, name, key, value): if not name in frapp...
enkidulan/slidelint
src/slidelint/tests/utils.py
Python
apache-2.0
485
0
from contextlib import contextmanager from testfixtures import R
eplacer import os @contextmanager def subprocess_context_helper(temp_dir, cmd): config_file = os.path.join(temp_dir.path, 'tmp_file') import subprocess origing_popen = subprocess.Popen with Replacer() as r: def not_existing_program(*args, **kwargs): return origing_popen(cmd, *args[...
am) yield config_file
MarxMustermann/OfMiceAndMechs
src/itemFolder/logistics/__init__.py
Python
gpl-3.0
510
0.001961
""" import os for module in os.listdir(os.path.d
irname(__file__)): if module == "__init__.py" or module[-3:] != ".py": continue __import__("src.itemFolder.logistics." + module[:-3], locals(), globals()) del module """ import src.itemFolder.logistics.container import src.itemFolder.logistics.mover import sr
c.itemFolder.logistics.pathingNode import src.itemFolder.logistics.sorter import src.itemFolder.logistics.typedStockpileManager import src.itemFolder.logistics.uniformStockpileManager
JoyIfBam5/aws-sdk-cpp
scripts/prepare_regenerate_high_level_sdks.py
Python
apache-2.0
3,418
0.009655
#!/usr/bin/env python # # Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://aws.amazon.com/apache2.0 # # or...
le = "aws-cpp-sdk-" + highLevelSdkName + "/nuget/" + "aws-cpp-sdk-" + highLevelSdkName + ".autopkg"; with open(autopkgFile, "rt") as ftarget: content = ftarget.read() """ The following regex code is going to change content like: version : 1.0.153; depend
encies { packages: { AWSSDKCPP-Core/1.0.140, AWSSDKCPP-S3-Encryption/1.0.20060301.142 AWSSDKCPP-sqs/2.3.20070319.141 } } to: version : @RUNTIME_MAJOR_VERSION@.@RUNTIME_MINOR_VERSION@; dependencies { packages:...
bwhite/hadoop_vision
performance/bgsub_fast.py
Python
gpl-3.0
1,821
0.00659
import numpy as np import ctypes # Required Types _uint8_ptr = ctypes.POINTER(ctypes.c_uint8) _uint32_ptr = ctypes.POINTER(ctypes.c_uint32) _float_ptr = ctypes.POINTER(ctypes.c_float) _int = ctypes.c_int32 # Load library _bg = np.ctypeslib.load_library('libbgsub_fast', '.') #void bgsub_accum(unsigned int *image, int...
, float *bgsub) _bg.bgsub_classify.restype = ctypes.c_int _bg.bgsub_classify.argtypes = [ctypes.c_char_p, _int, _float_ptr, _float_ptr] def classify(image, m, v, fg): _bg.bgsub_classify(image, len(image), m.ctypes.data_as(_float_ptr), fg.ctypes.da...
e=np.float32) ss = np.zeros(len(image), dtype=np.float32) accum(image, s, ss) print(s) print(ss)
aino/aino-utkik
setup.py
Python
bsd-3-clause
1,034
0.001934
from setuptools import setup, find_packages from setuptools.command.test import test class TestCommand(test): def run(self): from tests.runtests import runtests runtests() setup( name='aino-utkik', version='0.9.1', description='Small, clean code with a lazy view dispatcher and class ...
ges=find_packages(exclude=['tests', 'tests.*']), zip_safe=False, cmdclass={"test": TestCommand}, classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Ap
proved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3 :: Only', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Framework :: Django', ], )
belteshassar/cartopy
lib/cartopy/tests/test_coding_standards.py
Python
gpl-3.0
9,853
0.000203
# (C) British Crown Copyright 2012 - 2016, Met Office # # This file is part of cartopy. # # cartopy is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 3 of the License, or # (at your option)...
if years is None: print('The file {} has no valid header license and ' 'has not been excluded from the license header ' 'test.'.format(fname)) failed = True elif last_change.year > y...
file header at {} is out of date. The last' ' commit was in {}, but the copyright states it' ' was {}.'.format(fname, last_change.year, years[1])) failed = True if failed: ...
ITPS/oerp_gap_analysis_ITPS
utils/odf2gap/settings.py
Python
gpl-3.0
149
0
username = 'admin'
pwd = '123321...' dbname = 'Prueba
' host = '127.0.0.1' port = '8069' filepath = '/home/aphu/Downloads/' filename = 'cantvnet.ods'
nsteinme/phy
phy/cluster/manual/view_models.py
Python
bsd-3-clause
37,793
0.000397
# -*- coding: utf-8 -*- """View model for clustered data.""" #------------------------------------------------------------------------------ # Imports #------------------------------------------------------------------------------ import os.path as op import numpy as np from six import string_types from ...io.kwik...
------------------------------------------------------------------------ # Stats panel #------------------------------------------------------------------------------ class StatsViewModel(HTMLClusterViewModel): """Display cluster statistics.""" def get_html(self, cluster_ids=None, up=None):
"""Return the HTML table with the cluster
Distrotech/reportlab
tools/pythonpoint/styles/htu.py
Python
bsd-3-clause
5,206
0.006531
from reportlab.lib import styles from reportlab.lib import colors from reportlab.lib.units import cm from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_RIGHT, TA_JUSTIFY from reportlab.platypus import Preformatted, Paragraph, Frame, \ Image, Table, TableStyle, Spacer from reportlab.pdfbase import pdfmetrics fr...
colors.black), ('BACKGROUND', (0,1), (-1,1), colors.Color(0,0.7,0.7)) ]) stylesheet['table1'] = ts return style
sheet
smclt30p/PCS
core/plugins/PluginLoader.py
Python
bsd-2-clause
1,237
0.001617
import importlib import os from PyQt5.QtCore import QSettings class Continue(BaseException): pass class PluginLoader: loadedPlugins = [] loaded = False settings = QSettings("plugins.ini", QSettings.IniFormat) @staticmethod def getLoadedPlugins(): """ This returns instance...
ns." + plugin + ".PluginImpl") if hasattr(mod, "PluginImpl"): instance = getattr(mod, "PluginImpl")() instance.nativeName = plugin instance.settings = PluginLoader.settings PluginLoader.loadedPlugins.append(instance) ...
ginLoader.loadedPlugins = [] PluginLoader.loaded = False PluginLoader.getLoadedPlugins()
pacbard/clsipy
wsgi/clsi.py
Python
mit
4,642
0.007755
import base64 from os.path import abspath, dirname, join import sys, os import uuid import shutil import untangle import subprocess, threading # missing module fix sys.path.append(os.path.join(os.environ['OPENSHIFT_REPO_DIR'], 'wsgi')) virtenv = os.environ['APPDIR']+'/virtenv' os.environ['PYTHON_EGG_CACHE']...
hc env-set CLSI_TOKEN=your_token --app your_app # clsi_token is the fallback token in calse no token is defined if token == os.getenv('CLSI_TOKEN', 'clsi_token'): return True else: print("User "+ token +" not found in database") re
turn sys.exit()
thomasstreet/ballast
ballast/core.py
Python
apache-2.0
4,607
0.000651
import logging import threading import time from ballast.discovery import ServerList from ballast.rule import Rule, RoundRobinRule from ballast.ping import ( Ping, SocketPing, PingStrategy, SerialPingStrategy ) class LoadBalancer(object): DEFAULT_PING_INTERVAL = 30 MAX_PING_TIME = 3 def ...
ping_interval = self.DEFAULT_PING_INTERVAL self._server_list = server_list self._servers = set()
self._stats = LoadBalancerStats() self._rule.load_balancer = self self._logger = logging.getLogger(self.__module__) # start our background worker # to periodically ping our servers self._ping_timer_running = False self._ping_timer = None if ping_on_start:...
afronski/grammar-generator
grammar-generator/Elements/G/Populators/AllParametersListWithOneNamePopulator.py
Python
mit
1,335
0.025468
from Elements.G.Populators.Base.IElementPopulator import IElementPopulator class AllParametersListWithOneNamePopulator(IElementPopulator): def __init__(self, sectionName, templates,
settingsObject): super(AllParametersListWithOneNamePopulator, self).__init__(sectionName, templates, settingsObject) self
.separator = "\n|\n" self.mainName = self.templateName.split('-')[1] def getType(self): return "CreateAllParametersListWithOneName" def openClause(self, name): return self.parameters["ModulePrefix"] + "_" + name.lower() + ":\n" def closeClause(self): return "\n;\n" def populate(self): constructedParam...
Spiderlover/Toontown
toontown/dna/DNAFlatBuilding.py
Python
mit
5,943
0.000505
from panda3d.core import NodePath, DecalEffect import DNANode import DNAWall import random class DNAFlatBuilding(DNANode.DNANode): COMPONENT_CODE = 9 currentWallHeight = 0 def __init__(self, name): DNANode.DNANode.__init__(self, name) self.width = 0 self.hasDoor = False def s...
.find('wall_*') doorNode = dnaStorage.findNode('suit_door') doorNode = doorNode.copyTo(wallNodePath, 0) doorNode.se
tScale(NodePath(), (1, 1, 1)) doorNode.setPosHpr(0.5, 0, 0, 0, 0, 0) wallNodePath.setEffect(DecalEffect.make()) node.flattenMedium() node.stash() def traverse(self, nodePath, dnaStorage): DNAFlatBuilding.currentWallHeight = 0 node = nodePath.attachNewNode(sel...
dayatz/taiga-back
tests/integration/test_occ.py
Python
agpl-3.0
15,300
0.00183
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz> # Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com> # Copyright (C) 2014-2017 David Barrag
án <bameda@dbarragan.com> # Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net> # 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 ...
LethusTI/supportcenter
vendor/django/tests/regressiontests/localflavor/id/tests.py
Python
gpl-3.0
7,211
0.000277
import warnings from django.contrib.localflavor.id.forms import (IDPhoneNumberField, IDPostCodeField, IDNationalIdentityNumberField, IDLicensePlateField, IDProvinceSelect, IDLicensePlatePrefixSelect) from django.test import SimpleTestCase class IDLocalFlavorTests(SimpleTestCase): def setUp(self): ...
Warning,
module='django.contrib.localflavor.id.id_choices' ) def tearDown(self): self.restore_warnings_state() def test_IDProvinceSelect(self): f = IDProvinceSelect() out = u'''<select name="provinces"> <option value="ACE">Aceh</option> <option value="BLI">Bali</option> <option va...
nasfarley88/rpg-game-terminal
main_terminal.py
Python
mit
6,631
0.004524
import curses import gspread from google_credentials import username, password from textwrap import fill from multiprocessing import Pipe, Process, Event class MainTerminal: """Class to manage the loading and refreshing of the main terminal.""" def _parse_menu( self, tmp_menu_list, ...
lf.ss_title_input_pipe = Pipe() self.wks_title_output_pipe, self.wks_title_in
put_pipe = Pipe() self.curr_menu_dict_output_pipe, self.curr_menu_dict_input_pipe = Pipe() self.curr_menu_str_output_pipe, self.curr_menu_str_input_pipe = Pipe() self.menu_ss_event = Event() self.menu_ss_kill_event = Event() self.menu_ss_kill_event.clear() # N...
CorwinTanner/vmupdate
tests/test_pkgmgr.py
Python
mit
1,900
0.004211
from vmupdate.config import config from vmupdate.errors import UpdateError from vmupdate.pkgmgr import get_pkgmgrs, run_pkgmgr from vmupdate.vm import VM from tests.case import TestCase from tests.constants import * from tests.context import get_data_path, mock from tests.mocks import get_mock_virtualizer, get_mock_ss...
s_calls([mock.call('sudo -S testpkgmgr update'), mock.call('sudo -S testpkgmgr upgrade')]) def
test_run_pkgmgr_update_error(self): mock_stdout = self.mock_ssh.return_value.exec_command.return_value[1] mock_stdout.channel.recv_exit_status.return_value = -1 vm = VM(self.mock_virt, 'Test Machine 4') self.assertRaises(UpdateError, run_pkgmgr, vm, TEST_PKGMGR, config.pkgmgrs[TEST_OS...
HeavenMin/PlantImageRecognition
deepLearning/flowerNet.py
Python
apache-2.0
19,281
0.021023
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ AUTHOR : MIN PURPOSE : the deep learning CNN model, similar as inception VERSION : 0.1 DATE : 4.2017 """ __author__ = 'Min' import math import time import tensorflow as tf from datetime import datetime NUM_CLASSES = 50 slim = tf.contrib.slim # 产生截断的正太分布 # pro...
branch0 = slim.conv2d(net, 64, [1, 1], scope = 'conv')
with tf.variable_scope('branch1'): branch1 = slim.conv2d(net, 48, [1, 1], scope = 'conv') branch1 = slim.conv2d(branch1, 64, [5, 5], scope = 'conv1') with tf.variable_scope('branch2'): branch2 = slim.conv2d(net, 64, [1, 1], scope = 'conv') ...
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_07_01/aio/operations/_network_management_client_operations.py
Python
mit
7,052
0.005105
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.Error, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('VirtualWanSecurityProviders', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized supported_security_providers.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/provide...
ipa-led/airbus_coop
airbus_docgen/src/airbus_docgen/docgen/pkg/node/__init__.py
Python
apache-2.0
2,723
0.006978
#!/usr/bin/env python # # Copyright 2015 Airbus # Copyright 2017 Fraunhofer Institute for Manufacturing Engineering and Automation (IPA) # # 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 # # ...
pt Exception as ex: html.HTMLException(ex,self) try: node_io = NodeInputOutput() if node_io.read(node_name, node_xml) is True: item_index += 1 title = HtmlElement(html.Sections.h4) title.text = "%i.%i.%i. Input/Outp...
elf) try: node_params = NodeParameters() if node_params.read(node_name, node_xml) is True: item_index += 1 title = HtmlElement(html.Sections.h4) title.text = "%i.%i.%i. Parameter(s)"%(isection, iarticle, item_index) ...
ViralLeadership/numpy
benchmarks/benchmarks/bench_indexing.py
Python
bsd-3-clause
1,883
0
from __future__ import absolute_import, division, print_function from .common import Benchmark, squares_, indexes_, indexes_rand_ import sys import six from numpy import memmap, float32, array import numpy as np class Indexing(Benchmark): params = [["indexes_", "indexes_rand_"], ['I', ':,I', 'np.i...
sel, op): self.func() class IndexingSeparate(Benchmark): def setup(self): self.fp = memmap('tmp.dat', dtype=float32, mode='w+', shape=(50, 60)) self.indexes = array([3, 4, 6, 10, 20]) def time_mmap_slicing(self): for i in range(1000): self.fp[5:10] def time_m...
red0D(Benchmark): def setup(self): self.dt = np.dtype([('a', 'f4', 256)]) self.A = np.zeros((), self.dt) self.B = self.A.copy() self.a = np.zeros(1, self.dt)[0] self.b = self.a.copy() def time_array_slice(self): self.B['a'][:] = self.A['a'] def time_array_...
devs1991/test_edx_docmode
venv/lib/python2.7/site-packages/django/utils/http.py
Python
agpl-3.0
10,279
0.000973
from __future__ import unicode_literals import base64 import calendar import datetime import re import sys import unicodedata from binascii import Error as BinasciiError from email.utils import formatdate from django.utils import six from django.utils.datastructures import MultiValueDict from django.utils.encoding im...
id # returning a long (#15067). The long type was removed in Python 3. if six.PY2 and value > sys.maxint: raise ValueError("Base36 input too
large") return value def int_to_base36(i): """ Converts an integer to a base36 string """ char_set = '0123456789abcdefghijklmnopqrstuvwxyz' if i < 0: raise ValueError("Negative base36 conversion input.") if six.PY2: if not isinstance(i, six.integer_types): raise...
RoboCupULaval/TrackBots
tracker/proto/messages_robocup_ssl_wrapper_pb2.py
Python
mit
2,860
0.008392
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: messages_robocup_ssl_wrapper.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import...
ame['geometry'].message_type = messages_robocup_ssl_geometry_pb2._SSL_GEOMETRYDATA DESCRIPTOR.message_t
ypes_by_name['SSL_WrapperPacket'] = _SSL_WRAPPERPACKET SSL_WrapperPacket = _reflection.GeneratedProtocolMessageType('SSL_WrapperPacket', (_message.Message,), dict( DESCRIPTOR = _SSL_WRAPPERPACKET, __module__ = 'messages_robocup_ssl_wrapper_pb2' # @@protoc_insertion_point(class_scope:SSL_WrapperPacket) )) _sym_...
google-research/federated
targeted_attack/attacked_fedavg.py
Python
apache-2.0
24,990
0.005082
# Copyright 2019, 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...
model_weights.trainable,
initial_weights.trainable) aggregated_outputs = model.report_local_unfinalized_metrics() return weights_delta_benign, aggregated_outputs, num_examples_sum @tf.function def compute_malicious_update(): """compute malicious update sent back to the se...
rbramwell/pulp
client_lib/pulp/client/commands/options.py
Python
gpl-2.0
2,491
0.004014
""" Contains CLI framework option and flag instances for options that are used across multiple command areas. Examples include specifying a repository ID or specifying notes on a resource. The option instances in this module should **NEVER** be modified; changes will be reflected across the CLI. If changes need to be ...
changed by specifying this option multiple times; notes are deleted by ' 'specifying "" as the value') DESC_ALL = _('match all records. If other filters are specified, they will be ' 'applied. This option is only useful when you need to explicitly ' 'request that no filters be applied.') ...
AME, required=False) OPTION_DESCRIPTION = PulpCliOption('--description', DESC_DESCRIPTION, required=False) OPTION_NOTES = PulpCliOption('--note', DESC_NOTE, required=False, allow_multiple=True, parse_func=parsers.parse_notes) # IDs OPTION_REPO_ID = PulpCliOption('--repo-id', DESC_ID_ALLOWI...
Zokol/ArduinoCNC
cnc.py
Python
mit
2,290
0.049345
import serial import sys from time import sleep def move(dir): print dir ser.write(dir) # write a string ser.sendBreak(0.25) ser.flush() sleep(1) def ResetCoords(): dir = 'r' print dir ser.write(dir) # write a string ser.sendBreak(0.25) ser.flush() sleep(1) def DrawRect(d...
run == 1: print "" print "" print "___________________________" print "Use Keypad or following keys to control motors" print "Direction:" print "q w e" print "a s d" print "z x c" print "Drill control:" print " Up: f" print "Down: v" print "" print "Press m to exit
to menu" print "___________________________" select = raw_input(": ") if select == "m": run = 0 else: move(select) def DrawText(): print "This option is not ready yet" return 0 def ClosePort(): ser.close() # close port def OpenPort(port): print "" print "Initi...
kylef/jsonschema-test
jsonschema_test/__init__.py
Python
bsd-2-clause
3,350
0.002687
import sys import os import json from jsonschema import validate def load_json(path): with open(path) as fp: return json.load(fp) def load_json_suite(path): schema = test_schema() suite = load_json(path) try: validate(suite, schema) except Exception as e: print('{} is no...
r test in case['tests']: if test.get('skip', False): skipped += 1
print_yellow(' -> {} (skipped)'.format(test['description'])) continue success = True try: validate(test['data'], schema) except Exception as e: if test['valid']: success = Fal...
pythonsingapore/pythonsingapore
website/webapps/django/myproject/myproject/urls.py
Python
mit
1,625
0
"""Main urls.py for the ``pythonsingapore.com`` project.""" from django.conf import settings from django.conf.urls.defaults import patterns, include, url from django.conf.urls.static import static from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from cms.sitemaps imp...
h>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}), url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ) urlpatterns += patterns( '', url(r'^sitemap.xml$', 'django.contrib.sitemaps.views.sitemap', ...
onf.urls.i18n')), url(settings.ADMIN_URL, include(admin.site.urls)), url(r'^admin-.+/', include('admin_honeypot.urls')), url(r'^rosetta/', include('rosetta.urls')), url(r'^accounts/', include('registration_email.backends.default.urls')), url(r'^u/', include('user_data.urls')), url(r'^', include(...
rpbeltran/cleverbot-api
Cleverbot API/Cleverbot/Cleverbot.py
Python
mit
6,027
0.011117
# # Cleverbot Webscraping API for Python # # Made By: Ryan Beltran # # On: March 30th 2016 # # Version history: # 1.0 3/30/16 # # Todo list: # * Disguise traffic as human # * Make ask() more resilient to changes in site structure # * Add reset operation by clearing CBSTATE cookie # * Save sessions by s...
edent from previous court cases including 'Ebay V. Bidders Edge', the use of a web scraper in ways that interfere with the host's intersts may (possibly) be considered illegal trespass. # Cleverbot does not openly grant site access to robots, or humans attempting to access the site indirectly, and infact statedly denie...
as a result of your use of any of the following code, consider it a personal problem. # Per my undrstanding, the only authorized ways of using Cleverbot are: # * To have a human interface their web application directly at www.cleverbot.com # * To pay a heck of a lot of money to use their cleverscript API #...