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
UCSBarchlab/PyRTL
tests/test_helperfuncs.py
Python
bsd-3-clause
47,619
0.001638
import random import unittest import six import os import sys import pyrtl import pyrtl.corecircuits import pyrtl.helperfuncs from pyrtl.rtllib import testingutils as utils # --------------------------------------------------------------- class TestWireVectorList(unittest.TestCase): def setUp(self): pas...
Raises(ValueError): pyrtl.helperfuncs.wirevector_list(['one', 'two', 'three'], [2, 4]) with self.assertRaises(pyrtl.PyrtlError): pyrtl.helperfuncs.wirevector_list('one/2, two/4, three/8', 16) with self.
assertRaises(pyrtl.PyrtlError): pyrtl.helperfuncs.wirevector_list(['one/2', 'two/4', 'three/8'], [8, 4, 2]) class TestNonCoreHelpers(unittest.TestCase): def setUp(self): pass def test_log2(self): self.assertEqual(pyrtl.log2(1), 0) self.assertEqual(pyrtl.log2(2), 1) ...
oriordan/yubistack
yubistack/exceptions.py
Python
bsd-2-clause
1,873
0.003737
""" yubistack.exceptions ~~~~~~~~~~~~~~~~~~~~ List all custom exceptions here """ STATUS_CODES = { # YKAuth 'BAD_PASSWORD': 'Invalid password', 'DISABLED_TOKEN': 'Token is disabled', 'UNKNOWN_USER': 'Unknown user', 'INVALID_TOKEN': 'Token is not associated with user', # YKVal 'BACKEND_ERR...
rror(Exception): """ Yubistack Exception """ NAME = 'Yubistack error' def __init__(self, *args): super(YubistackError, self).__init__(*args) self.error_code = self.args[0] def __str__(self): message = STATUS_CODES[self.error_code] if len(self.args) == 2:
message += ': %s' % self.args[1] return message class YKAuthError(YubistackError): """ Error returned by the Client class """ NAME = 'Authentication error' class YKValError(YubistackError): """ Error returned by the Validator class """ NAME = 'Validation error' class YKSyncError(YubistackEr...
CAB-LAB/cablab-core
esdl/dat.py
Python
gpl-3.0
3,600
0.003611
""" .. _xarray.Dataset: http://xarray.pydata.org/en/stable/data-structures.html#dataset .. _xarray.DataArray: http://
xarray.pydata.org/en/stable/data-structures.html#dataarray .. _Numpy: http://www.numpy.org/ The following functions provide the hi
gh-level API of the ESDC Python DAT. It provides additional analytical utility functions which work for `xarray.Dataset`_ objects which are used to represent the ESDC data. """ import xarray as xr def corrcf(ds, var1=None, var2=None, dim='time'): ''' Function calculating the correlation coefficient of two v...
fy0/my-leetcode
990.Satisfiability Of Equality Equations/main.py
Python
apache-2.0
674
0.001484
class Solution:
def translateNum(self, num: int) -> int: if num < 10: return 1 table = {} for i in range(26): table[str(i)] = chr(ord('a') + i) num_str = str(num) arr = [] def solve(eated, s, last): if not s: arr.append(eated) ...
if last == '1' or (last == '2' and i in ('0', '1', '2', '3', '4', '5')): # if ord(eated[-1]) < ord('k'): solve(table[last + i], s[1:], last + i) solve(eated + table[i], s[1:], i) solve('', num_str, None) return len(arr)
free-free/pyblog
pyblog/cache/redis_cache.py
Python
mit
13,227
0.001285
#-*- coding:utf-8 -*- import logging logging.basicConfig(level=logging.ERROR) from cache_abstract import CacheAbstractDriver import asyncio try: import redis except ImportError: logging.error("Can't import 'redis' module") exit(-1) try: import aioredis except ImportError: logging.error("Can't import...
oroutine d
ef delete_key(self, key, key_prefix): if not self.__connection: yield from self.get_connection() key = key_prefix + key return (yield from self.__connection.hdel(self.__key_type_hash, key)) @asyncio.coroutine def delete(self, key, key_prefix): if not self.__connectio...
felipenaselva/repo.felipe
plugin.video.salts/salts_lib/worker_pool.py
Python
gpl-2.0
4,999
0.006001
""" SALTS XBMC Addon Copyright (C) 2016 tknorris 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. T...
if new_workers > max_new: new_workers = max_new for _ in xrange(new_workers): try: worker = threading.Thread(target=self.consumer) worker.daemon = True ...
% (worker.name, len(self.workers), self.max_workers), log_utils.LOGDEBUG, COMPONENT) except RuntimeError as e: try: log_utils.log('Pool Manager: %s missed Pool: %s - (%s/%s)' % (worker.name, e, len(self.workers), self.max_workers), log_utils.LOGWARNING) ...
fahadadeel/Aspose.Cells-for-Java
Plugins/Aspose-Cells-Java-for-Python/setup.py
Python
mit
705
0.014184
__author__ = 'fahadadeel' from setuptools import setup, find_packages setup( name = 'aspose-cells-java-for-python', packages
= find_packages(), version = '1.0', description = 'Aspose.cells Java for Python is a project that demonstrates / provides the Aspose.Cells for Java API usage examples in Python.', author='Fahad Adeel', author_email='cells@aspose.com', url='https://github.com/asposecells/Aspose_Cells_Java/tree/maste...
:: OSI Approved :: MIT License', 'Operating System :: OS Independent' ] )
lucashmorais/x-Bench
mozmill-env/python/Lib/site-packages/jsbridge/__init__.py
Python
mit
1,601
0
# This 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 http://mozilla.org/MPL/2.0/. import asyncore from datetime import datetime, timedelta import socket import os import sys from time import sleep from...
t.AF_INET, socket.SOCK_STREAM) free_socket.bind(('127.0.0.1', 0)) port = free_socket.getsockname()[1] free_socket.close() return port def wait_and_create_network(host, port, timeout=wait_to_create_timeout): deadline = datetime.utcnow() + timedelta(seconds=timeout) connected = False w
hile datetime.utcnow() < deadline: try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) s.close() connected = True break except socket.error: pass sleep(.25) if not connected: raise ...
kooksee/TIOT
test/project/src/app/proto/controller/RFIDController.py
Python
gpl-2.0
4,692
0.002081
#encoding=utf-8 from app.proto.common.data_parse import hex_to_dec, dec_to_hex from app.proto.common.hachi.c
ore import XBee from app.proto.frames.RFIDFrames import rfid_frame class RFIDController: def __init__(self, escaped=True): # self.xbee = XBee() pass def parse_pkgs(self, bytestream): ''' 未处理leftovers数据 todo ''' container = rfid_frame.parse(bytestre...
rgs, **kwargs): pass # rfid = RFIDController() # rfid.parse_pkgs("FF FF F1 07 0E 01 00 13 8E 88 00 04 00 47 ").pkgs # frame = bytearray.fromhex("FF FF F1 07 0E 01 00 13 8E 88 00 04 00 47 ") # frame = bytearray.fromhex("ff ff f1 07 44 0a 80 13 8e 00003f80139400003f 00138d00003f 00138f00003f00139a00003f0...
lexibrent/certificate-transparency
python/ct/client/async_log_client.py
Python
apache-2.0
18,435
0.000868
"""RFC 6962 client API.""" from ct.client import log_client from ct.client.db import database import gflags import logging import random from twisted.internet import defer from twisted.internet import error from twisted.internet import protocol from twisted.internet import reactor as ireactor from twisted.internet im...
"10kB.") gflags.DEFINE_bool("persist_entries", True, "Cache entries on disk.") class HTTPConnectionError(log_client.HTTPError): """Connection failed.""" pass class HTTPResponseSizeExceededError(log_client.HTTPError): """HTTP response exceeded maximum permitted size.""" pass ...
asynchronous twisted log client. # ############################################################################### class ResponseBodyHandler(protocol.Protocol): """Response handler for HTTP requests.""" def __init__(self, finished): """Initialize the one-off response handler. ...
brainwane/carmen
carmen.py
Python
gpl-3.0
6,748
0.0123
#!/usr/bin/python # Copyright 2013 Sumana Harihareswara # 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 progra...
but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ ...
import mock def anykey(): x = raw_input("Press Return to continue. ") + "a" class City(object): """Each City has a name, a set of destinations one step away, and a clue.""" def __init__(self, n, c): self.dests = [] self.name = n self.clue = c class Villain(object): def __init...
SEMAFORInformatik/femagtools
examples/model-creation/createall.py
Python
bsd-2-clause
886
0.001129
import femagtools import importlib import os import logging logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s') models = ['statorBG-magnetSector', 'stator1-magnetIron3', 'stator1-magnetIron4', 's
tator1-magnetIron5', 'stator1-magnetIronV', 'stator2-magnetSector', 'stator4-magnetSector', 'statorR
otor3-magnetIron' ] logger = logging.getLogger("fslcreator") workdir = os.path.join(os.path.expanduser('~'), 'femag') try: os.mkdir(workdir) except FileExistsError: pass logger.info("Femagtools Version %s Working Dir %s", femagtools.__version__, workdir) for m in models: mod = importlib.import_...
VitalPet/c2c-rd-addons
c2c_reporting_tools_chricar/core/__init__.py
Python
agpl-3.0
1,404
0.000713
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (c) Camptocamp SA # Author: Arnaud WÃŒst # # # This file is part of the c2c_report_tools module. # # # WARNING: This program as such is intended to be used by professional # programmers who take the w...
ee Software # Service Company # # This program is Free Software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option)
any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General P...
tuttleofx/sconsProject
autoconf/fontconfig.py
Python
mit
105
0
fr
om _external import * fontconfig = LibWithHeaderChecker('fontconfig', 'fontconfig/fontconf
ig.h', 'c')
shitolepriya/Saloon_erp
erpnext/hr/doctype/attendance_status/test_attendance_status.py
Python
agpl-3.0
299
0.006689
#
-*- coding: utf-8 -*- # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # See license.txt from __future__ import unicode_literals import frappe import unittest # test_records = frappe.get_test_records('Attendance Status') class TestAttendanceStatus(unittest.TestCase):
pass
stdweird/aquilon
lib/python2.6/aquilon/worker/commands/update_interface_machine.py
Python
apache-2.0
7,493
0.000801
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2012,2013 Contributor # # 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...
equired_parameters = ["interfac
e", "machine"] def render(self, session, logger, interface, machine, mac, model, vendor, boot, pg, autopg, comments, master, clear_master, default_route, rename_to, **arguments): """This command expects to locate an interface based only on name and machine - all other ...
astrieanna/haiku-dropbox-client
db_ls.py
Python
mit
476
0.004202
import sys from cli_client import AP
P_KEY, APP_SECRET, DropboxTerm def main(path): if APP_KEY == '' or APP_SECRET == '': exit("You need to set your APP_KEY and APP_SECRET!") term = DropboxTerm(APP_KEY, APP_SECRET) if path != "": term.do_cd(path) term.do_ls() if __name__ == '__main__': if len(sys.argv) == 1: ...
print "usage: python db_ls.py <path>" else: main(sys.argv[1])
indico/indico
indico/web/flask/wrappers.py
Python
mit
9,269
0.001834
# This file is part of Indico. # Copyright (C) 2002 - 2022 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. import os import re from contextlib import contextmanager from uuid import uuid4 from flask import Bluepr...
r once they are available
customization_dir = os.path.join(config.CUSTOMIZATION_DIR, 'templates') if config.CUSTOMIZATION_DIR else [] return CustomizationLoader(default_loader, customization_dir, config.CUSTOMIZATION_DEBUG) def add_url_rule(self, rule, endpoint=None, view_func=None, **options): from indico.web.rh import ...
tum-vision/articulation
articulation_tutorials/python_service_client/model_selection_client.py
Python
bsd-2-clause
1,925
0.038961
#!/usr/bin/env python import roslib; roslib.load_manifest('articulation_tutorials') import rospy import numpy from articulation_msgs.msg import * from articulation_msgs.srv import * from geometry_msgs.msg import Pose, Point, Quaternion from sensor_msgs.msg import ChannelFloat32 PRISMATIC = 0 ROTATIONAL = 1 MODELS={...
.items(): request = TrackModelSrvRequest() print "generating track of type '%s'" % model_name request.model.track = sample_track( model_type ) try: response = model_select(request) print "selected model: '%s' (n = %d, log LH = %f)" % ( response.model.name, len(response.mode...
'loglikelihood'][0] ) model_pub.publish(response.model) except rospy.ServiceException: print "model selection failed" pass if rospy.is_shutdown(): exit(0) print rospy.sleep(0.5) if __name__ == '__main__': main()
wavesoft/creditpiggy
creditpiggy-server/creditpiggy/api/migrations/0002_projectcredentials_websitecredentials.py
Python
gpl-2.0
1,466
0.003411
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import creditpiggy.core.models class Migration(migrations.Migration): dependencies = [ ('core', '0014_auto_20150616_1247'), ('api', '0001_initial'), ] operations = [ migratio...
fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('token', models.CharField(default=creditpiggy.core.models.new_uuid, help_text=b'Anonymous authentication token for the credentials', unique=True, max_length=32, db_index=Tru...
models.CharField(default=creditpiggy.core.models.gen_token_key, help_text=b'Shared secret between project and administrator', max_length=48)), ('project', models.ForeignKey(to='core.PiggyProject')), ], ), migrations.CreateModel( name='WebsiteCredentials', ...
iawells/gluon
gluon/common/particleGenerator/DataBaseModelGenerator.py
Python
apache-2.0
6,227
0.000803
#!/usr/bin/python from __future__ import print_function import sys import re import yaml import sqlalchemy as sa from sqlalchemy.ext.declarative import declarative_base class DataBaseModelProcessor(object): def __init__(self): self.db_models = {} def add_model(self, model): self.data = model...
attrs['__name__'] = table_name self.db_models[table_name] = ty
pe(table_name, (base,), attrs) except: print('During processing of table ', table_name, file=sys.stderr) raise @classmethod def get_primary_key(cls, table_data): primary = [] for k, v in table_data['attributes'].iteritems(): ...
samuelmaudo/yepes
yepes/forms/inline_model.py
Python
bsd-3-clause
2,021
0.000495
# -*- coding:utf-8 -*- from __future__ import unicode_literals from django.forms.models import ( inlineformset_factory, ModelForm, ModelFormMetaclass, ) from django.utils import six class InlineModelFormMetaclass(ModelFormMetaclass): def __new__(cls, name, bases, attrs): options = attrs.get('Me...
kwargs = {'extra': 0} if not isinstan
ce(field_name, six.string_types): kwargs.update(field_name[1]) field_name = field_name[0] field = getattr(model, field_name).related FormSet = inlineformset_factory(model, field.model, **kwargs) form_set = FormSet(data=data, files=files, instance=self...
gautamMalu/rootfs_xen_arndale
usr/lib/python2.7/plat-arm-linux-gnueabihf/IN.py
Python
gpl-2.0
15,532
0.009207
# Generated by h2py from /usr/include/netinet/in.h _NETINET_IN_H = 1 # Included from features.h _FEATURES_H = 1 _ISOC95_SOURCE = 1 _ISOC99_SOURCE = 1 _ISOC11_SOURCE = 1 _POSIX_SOURCE = 1 _POSIX_C_SOURCE = 200809L _XOPEN_SOURCE = 700 _XOPEN_SOURCE_EXTENDED = 1 _LARGEFILE64_SOURCE = 1 _DEFAULT_SOURCE = 1 _BSD_SOURCE = 1...
eturn \ __BIT_TYPES_DEFINED__ = 1 # Included from endian.h _ENDIAN_H = 1 __LITTLE_ENDIAN = 1234 __BIG_ENDIAN = 4321 __PDP_ENDIAN = 3412 # Included from bits/endian.h __BYTE_ORDER = __BIG_ENDIAN __BYTE_ORDER = __LITTLE_EN
DIAN __FLOAT_WORD_ORDER = __BYTE_ORDER LITTLE_ENDIAN = __LITTLE_ENDIAN BIG_ENDIAN = __BIG_ENDIAN PDP_ENDIAN = __PDP_ENDIAN BYTE_ORDER = __BYTE_ORDER # Included from bits/byteswap.h _BITS_BYTESWAP_H = 1 def __bswap_constant_16(x): return \ def __bswap_constant_32(x): return \ def __bswap_32(x): return \ def __bswap_...
sergiopasra/megaradrp
megaradrp/processing/tests/test_fibermatch.py
Python
gpl-3.0
2,099
0.000953
import pytest from megaradrp.processing.fibermatch import generate_box_model from megaradrp.processing.fibermatch import count_peaks PEAKS = [ 3.806000000000000000e+03, 3.812000000000000000e+03, 3.818000000000000000e+03, 3.824000000000000000e+03, 3.830000000000000000e+03, 3.8360000000000000...
(10, 0), (12, 1), (13, 0), (14, 0), (15, 0) ] model = generate_box_model(5, start=10, skip_fibids=[11], missing_relids=[2]) assert len(model) == len(expected) for m, e in zip(model, expected): ass...
[] idx = 0 for p in PEAKS: t = (idx + 1, p, 0, idx) expected.append(t) idx += 1 result = count_peaks(PEAKS, tol=1.2, distance=6.0) assert result == expected
a67878813/script
handwrite.py
Python
apache-2.0
765
0.023112
from PIL import Image, ImageFont from handright import Template, handwrite text = "啊啊啊啊巴巴爸爸啛啛喳喳顶顶顶顶柔柔弱弱共和国刚刚\n\r 顶顶顶顶灌灌灌灌哈哈哈哈斤斤计较坎坎坷坷啦啦啦啦噢噢噢噢噗噗噗噗噗" template = Template( background=Image.new(mode="1", size=(3300, 1000), color=1), font=ImageFont.truetype("C:\\font\\MiNiJianJiaShu-1.ttf", size=150), ...
2, line_spacing_sigma = 1, font
_size_sigma = 2, word_spacing_sigma = 0.8, perturb_x_sigma = 3, perturb_y_sigma = 3, perturb_theta_sigma = 0.1 ) images = handwrite(text, template) for im in images: assert isinstance(im, Image.Image) im.save("C:\\font\\3.png") #im.show()
alexmilowski/duckpond
duckpond/apps/service/app.py
Python
apache-2.0
1,161
0.023256
from flask import Flask, request, g, session, redirect, abort, Response from datetime import datetime from functools import wraps import base64 app = Flask(__name__) app.config.from_envvar('WEB_CONF') def authenticate(f): @wraps(f) def wrapper(*args, **kwargs): v = request.headers.get('authorization') ...
d('Bearer ')==0: roles = app.config['AUTH_SERVICE'].validateToken(v[7:]) if roles is not None: authenticated = True request.roles = roles if authenticated: return f(*args, **kwargs) else: return
Response(status=401, headers={'WWW-Authenticate': 'Basic realm="service"'}) return wrapper @app.before_request @authenticate def before_request(): pass
bitmazk/django-feedback-form
feedback_form/models.py
Python
mit
2,071
0
"""Models for the ``feedback_form`` app.""" from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models from django.conf import settings from django.utils.encoding import python_2_unicode_compatible from django.utils.translatio...
Date'), ) # Generic FK to the object this feedback is about content_type = models.ForeignKey( ContentType, related_
name='feedback_content_objects', null=True, blank=True, ) object_id = models.PositiveIntegerField(null=True, blank=True) content_object = GenericForeignKey('content_type', 'object_id') class Meta: ordering = ['-creation_date'] def __str__(self): if self.user: re...
Russell-IO/ansible
lib/ansible/modules/network/netscaler/netscaler_gslb_service.py
Python
gpl-3.0
24,020
0.002748
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2017 Citrix Systems # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, div
ision, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: netscaler_gslb_service short_description: Manage gslb service entities in Netscaler. description: ...
Manage gslb service entities in Netscaler. version_added: "2.4" author: George Nikolopoulos (@giorgos-nikolopoulos) options: servicename: description: - >- Name for the GSLB service. Must begin with an ASCII alphanumeric or underscore C(_) character, and must...
iandees/all-the-places
locations/spiders/aunt_annes.py
Python
mit
10,953
0.006665
import scrapy import xml.etree.ElementTree as ET from locations.items import GeojsonPointItem URL = 'http://hosted.where2getit.com/auntieannes/2014/ajax?&xml_request=%3Crequest%3E%3Cappkey%3E6B95F8A2-0C8A-11DF-A056-A52C2C77206B%3C%2Fappkey%3E%3Cformdata+id%3D%22locatorsearch%22%3E%3Cdataview%3Estore_default%3C%2Fdat...
h", "Abha", "Jizan", "Al Yamamah", "Tabuk", "Sambah", "Ras Tanura", "At Tuwal", "Sabya", "Buraidah", "Najran", "Sakaka", "Madinat Yanbu` as Sina`iyah", "Hayil", "Khulays", "Khamis Mushait", "Ra's
al Khafji", "Al Bahah", "Rahman", "Jazirah", "Jazirah" ) Indonesia_Cities = ( "Jakarta", "Surabaya", "Medan", "Bandung", "Bekasi", "Palembang", "Tangerang", "Makassar", "Semarang", "South Tangerang", ) Malaysia_Cities = ( "Kaula Lumpur", "Kota Bharu", "Klang", "Johor Bahru", "Subang J...
mscuthbert/abjad
abjad/tools/selectortools/CountsSelectorCallback.py
Python
gpl-3.0
3,980
0.001508
# -*- encoding: utf-8 -*- from abjad.tools import sequencetools from abjad.tools import datastructuretools from abjad.tools import selectiontools from abjad.tools.abctools import AbjadValueObject class CountsSelectorCallback(AbjadValueObject): r'''A counts selector callback. :: >>> callback = select...
def fuse_overhang(self): r'''Gets counts selector callback fuse overhang flag. Returns ordinal constant. '''
return self._fuse_overhang @property def nonempty(self): r'''Gets counts selector callback nonempty flag. Returns boolean. ''' return self._nonempty @property def overhang(self): r'''Gets counts selector callback overhang flag. Returns boolean. ...
quodlibet/mutagen
tests/test_dsdiff.py
Python
gpl-2.0
2,668
0
import os from mutagen.dsdiff import DSDIFF, IffError from tests import TestCase, DATA_DIR, get_temp_copy class TDSDIFF(TestCase): silence_1 = os.path.join(DATA_DIR, '28
22400-1ch-0s-silence.dff') silence_2 = os.path.join(DATA_DIR, '5644800-2ch-s01-silence.dff') silence_dst = os.path.join(DATA_DIR, '5644800-2ch-s01-silence-dst.dff') def setUp(self): self.dff_1 =
DSDIFF(self.silence_1) self.dff_2 = DSDIFF(self.silence_2) self.dff_dst = DSDIFF(self.silence_dst) self.dff_id3 = DSDIFF(get_temp_copy(self.silence_dst)) self.dff_no_id3 = DSDIFF(get_temp_copy(self.silence_2)) def test_channels(self): self.failUnlessEqual(self.dff_1.info.c...
babraham123/mysite
blogs/views.py
Python
mit
842
0.004751
from django.shortcuts imp
ort render, render_to_response from django.core.paginator import Paginator, InvalidPage, EmptyPage from django.core.urlresolvers import rev
erse from blogs.models import Post from django.http import Http404 def postlist(request): posts = Post.objects.all().order_by("-created") paginator = Paginator(posts, 2) try: page = int(request.GET.get("page", '1')) except ValueError: page = 1 try: posts = paginator.page(...
nabin-info/hackerrank.com
python-division.py
Python
mit
132
0.015152
#!/usr/bin/python im
port sys a = int(raw_input().strip()) b = int(raw_input().strip()) print (a / b) print (
float(a) / float(b))
NiLuJe/calibre-kobo-driver
tests/test_common.py
Python
gpl-3.0
4,914
0.001231
# vim: fileencoding=UTF-8:expandtab:autoindent:ts=4:sw=4:sts=4 from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals # To import from calibre, some things need to be added to `sys` first. Do not import # anything from calibr...
trouvé mon livre préféré"] ], }, { "encodings": {"UTF-8", "CP1256"}, "test_strings": [unicode_type(s) for s in ["مرحبا بالعالم"]], }, { "encodings": {"UTF-8", "CP1251"}, "test_strings": [unicode_type(s) for s in ["Привет мир"]], }, { "encodings": {...
odings = set() for o in TEST_STRINGS: encodings |= o["encodings"] for enc in encodings: yield enc class TestCommon(unittest.TestCase): orig_lang = "" # type: str def setUp(self): # type: () -> None self.orig_lang = os.environ.get("LANG", None) def tearDown(self): # ty...
shrimo/node_image_tools
node_graph.py
Python
gpl-3.0
3,999
0.021505
# Visualize node graph # Copyright 2013 Victor Lavrentev import matplotlib.pyplot as plt import json, sys import networkx as nx from node_lib import graph print '\nNode image tools (Visualize node graph) v01a\n' try: file_node=sys.argv[1] except: print '->Error. No script' sys.exit (0) w...
e(node.name) if (node.type=='composite'): Node_graph.add_node(node.name) Node_graph.add_edge(node.link_a,node.name
) Node_graph.add_edge(node.link_b,node.name) if (node.job=='mask'): Node_graph.add_edge(node.mask,node.name) if (node.type=='blur'): Node_graph.add_node(node.name) Node_graph.add_edge(node.link,node.name) if (node.type=='sharpen'): Node_graph.add_n...
newbee-7/News_Crawl
crawl.py
Python
mit
1,994
0.008024
# coding:utf-8 import url_manager, html_downloader, html_parser, html_outputer import traceback import iMessage class Crawl(object): def __init__(self): self.urls = url_manager.UrlManager() self.downloader = html_downloader.HtmlDownloader() self.parser = html_parser.HtmlParser() sel...
ormat_exc():\n%s' % traceback.format_exc() datass = self.outputer.output_html() News = '' for datas in datas
s: for data in datas: News += datas[data]+'\n' #print News if News != '': iMessage.send_Message(News, 'CQUT_News') if __name__=="__main__": root_urls = ["http://cs.cqut.edu.cn/Notice/NoticeStudentMore.aspx", "http://cs.cqut.edu.cn/Notice/NoticeMore.aspx?NtcCa...
nacl-webkit/chrome_deps
tools/telemetry/telemetry/tab_test_case.py
Python
bsd-3-clause
1,243
0.011263
# 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 unittest from telemetry import browser_finder from telemetry import options_for_unittests class TabTestCase(unittest.TestCase): def __init__(se...
inder.FindBrowser(options) if not browser_to_create: raise Exception('No b
rowser found, cannot continue test.') try: self._browser = browser_to_create.Create() self._tab = self._browser.tabs[0] except: self.tearDown() raise def tearDown(self): if self._tab: self._tab.Disconnect() if self._browser: self._browser.Close() def CustomizeBr...
jgmize/kuma
kuma/wiki/models.py
Python
mpl-2.0
73,565
0.00015
import hashlib import json import sys import traceback from datetime import datetime, timedelta from functools import wraps from uuid import uuid4 import newrelic.agent import waffle from constance import config from django.apps import apps from django.conf import settings from django.core.exceptions import Validation...
'/
'.join(slug_bits) try: parent = Document.objects.get(locale=locale, slug=parent_slug) except Document.DoesNotExist: raise Exception( ugettext('Parent %s does not exist.' % ( '%s/%s' % (locale, parent_slug)))) return parent class Document...
lemonad/behorighet
behorighet/main/views.py
Python
bsd-3-clause
532
0
# -*- coding: utf-8 -*- from django.shortcuts import render from units.models import Unit def startpage(request): """Start page. Shows list of units availab
le for statistics
/filtering. """ units = Unit.objects.all() # t = loader.get_template('startpage.html') # c = RequestContext(request, { # 'units': units, # }) # return HttpResponse(t.render(c)). return render(request, 'startpage.html', ...
bcraenen/KFClassifier
other/methods/ExtraTreesSample.py
Python
gpl-3.0
3,466
0.018465
#!/usr/bin/env python import arff import numpy as np import sys from sklearn import preprocessing #from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import ExtraTreesClassifier from sklearn.feature_selection import RFE from sklearn.pipeline import Pipeline from sklearn.grid_search import GridSea...
idSearch.fit(inputs,output) estimator = gridSearch.best_estimator_ print "Results: " print "Selected features: {0}".format(estimator.named_steps['RFE'].n_features_to_select) print "Max depth: {0}".format(estimator.named_steps['classifier'].max_depth) print "Number of trees: {0}".format(estimator.named_steps['classifier...
r count in range(0,n_accuracy): cv = StratifiedKFold(output,n_folds=n_folds,shuffle=True) predicted = cross_validation.cross_val_predict(estimator,inputs,output,cv=cv,verbose=verboseLevel,n_jobs=n_jobs,) score = metrics.accuracy_score(output,predicted,normalize=True) accuracy.append(score) print "Accura...
plotly/python-api
packages/python/plotly/plotly/validators/sankey/link/_label.py
Python
mit
442
0.002262
import _plot
ly_utils.basevalidators class LabelValidator(_plotly_utils.basevalidators.DataArrayValidator): def __init__(self, plotly_name="label", parent_name="sankey.link", **kwargs): super(LabelValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type...
kwargs.pop("role", "data"), **kwargs )
srcole/tools
plt.py
Python
mit
10,251
0.025266
# -*- coding: utf-8 -*- """ Miscellaneous functions for plotting 1. bar : create a bar chart with error bars 2. viztime : plot a pretty time series 3. scatt_2cond : scatter plot that compares the x and y values for each point 4. unpair_2cond : plot to compare the distribution of two sets of values 5. scatt_corr : plot...
is None: ytick
s = ylim plt.figure(figsize=figsize) plt.plot(x,y,'k.', ms = ms) if showline: from tools.misc import linfit linplt = linfit(x,y) plt.plot(linplt[0],linplt[1], 'k--') if showrp: if corrtype == 'Pearson': r, p = sp.stats.pearsonr(x,y) elif corrtype ==...
ygol/odoo
addons/account_payment/controllers/portal.py
Python
agpl-3.0
1,661
0.005418
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and lic
ensing details. from odoo.addons.account.controllers.portal import PortalAccount from odoo.http import request class PortalAccount(P
ortalAccount): def _invoice_get_page_view_values(self, invoice, access_token, **kwargs): values = super(PortalAccount, self)._invoice_get_page_view_values(invoice, access_token, **kwargs) payment_inputs = request.env['payment.acquirer']._get_available_payment_input(partner=invoice.partner_id, compa...
scollis/price_watch
scripts/get_html.py
Python
bsd-2-clause
379
0.002639
#!/bin/env python import urllib2 from datet
ime import datetime site = 'http://www.fuel-prices-europe.info/' fh = urllib2.urlopen(site) lines = fh.readlines() fh.close() now = datetime.now() my_str_date = now.strftime('%Y%m%d') outdir = '/Users/scollis/tmp/' prefix = 'fuel' p
ostfix = '.html' ofh = open(outdir+prefix+my_str_date+postfix, 'w') ofh.writelines(lines) ofh.close()
EmuKit/emukit
tests/emukit/multi_fidelity/test_convert_list_to_array.py
Python
apache-2.0
2,211
0.000905
import numpy as np import pytest from emukit.multi_fidelity.convert_lists_to_array import ( convert_x_list_to_array, convert_xy_lists_to_arrays, convert_y_list_to_array, ) def test_convert_x_list_to_array(): x_list = [np.array([[1, 0], [2, 1]]), np.array([[3, 2], [4, 5]])] x_array = convert_x_lis...
x_list = [np.array([[1, 0], [2, 1], [3, 4]]), np.array([[3, 2], [4, 5]])] y_list = [np.array([0
.0, 1.0]), np.array([2.0, 5.0])] with pytest.raises(ValueError): convert_xy_lists_to_arrays(x_list, y_list)
sesamesushi/desatisrevu
controllers/utils.py
Python
apache-2.0
24,558
0.000407
# Copyright 2012 Google Inc. All Rights Reserved. # #
Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the L
icense. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # S...
tier-one-monitoring/monstr
Monstr/Modules/CMSJobStatus/CMSJobStatus.py
Python
apache-2.0
9,424
0.002759
#!/bin/python from datetime import timedelta from pprint import pprint as pp import json import Monstr.Core.Utils as Utils import Monstr.Core.DB as DB import Monstr.Core.BaseModule as BaseModule import pytz from Monstr.Core.DB import Column, Integer, String, DateTime, UniqueConstraint, func class CMSJobStatus(Bas...
ite_name']} return result def _get_fail_ratio_status(self, fail_ratio): return {fail_ratio < 0.01: 10, 0.01 <= fail_ratio < 0.05: 20, 0.05 <= fail_ratio < 0.12: 30, 0.12 <= fail_ratio < 0.3: 40, 0.3 <= fail_ratio: 50}[True] def _g...
15000 >= load > 7000: 30, 7000 >= load > 1000: 40, 1000 >= load: 50}[True] def _get_rank_status(self, rank): return {rank < 4: 10, 4 <= rank < 5: 20, 5 <= rank < 6: 30, 6 <= rank < 7: 40, 7 <= rank...
lsaffre/lino-cosi
lino_cosi/setup_info.py
Python
agpl-3.0
3,193
0.000627
# -*-
coding: UTF-8 -*- # Copyright 2014-2021 Rumma & Ko Ltd # License: GNU Affero General Public License v3 (see file COPYING for details) SETUP_INFO = dict( name='lino-cosi', version='21.3.0', install_requires=['lino-xl', 'django-iban', 'lxml'], # tests_require=['beautifulsoup4'], # satisfied by lino dep...
imple", long_description=""" **Lino Così** is a `Lino application <http://www.lino-framework.org/>`__ for accounting (`more <https://cosi.lino-framework.org/about.html>`__). - The central project homepage is http://cosi.lino-framework.org - You can try it yourself in `our demo sites <https://www.lino-framework...
Hedde/fabric_interface
src/fabric_interface/hosts/context_processors.py
Python
mit
548
0.001825
__author__ = 'heddevanderheide' # Django spec
ific from fabric_interface.projects.models import Project from fabric_interface.hosts.models import Host def hosts(request): """ Adds host QuerySet context variable to the context. """ view_name = request.resolver_match.view_name kwargs = request.resolver_match.kwargs slug = kwargs.get('slug'...
return {'host_list': Host.objects.all()}
mhbu50/frappe
frappe/printing/doctype/print_style/print_style.py
Python
mit
664
0.024096
# -*- coding: utf-8 -*- # Copyright (c) 2017, Frappe Tec
hnologies and contributors # For license information, please see license.txt import frappe from frappe.model.document import Document class PrintStyle(Document): def validate(self): if (self.standard==1 and not frappe.local.conf.get("developer_mode") and not (frappe.flags.in_import or frappe.flags.in_test)):...
def on_update(self): self.export_doc() def export_doc(self): # export from frappe.modules.utils import export_module_json export_module_json(self, self.standard == 1, 'Printing')
ymap/aioredis
aioredis/errors.py
Python
mit
2,627
0
__all__ = [ 'RedisError', 'ProtocolError', 'ReplyError', 'MaxClientsError', 'AuthError', 'PipelineError', 'MultiExecError', 'WatchVariableError', 'ChannelClosedError', 'ConnectionClosedError', 'ConnectionForcedCloseError', 'PoolClosedError', 'MasterNotFoundError', ...
exceptions.""" class ProtocolError(RedisError): """Raised when pr
otocol error occurs.""" class ReplyError(RedisError): """Raised for redis error replies (-ERR).""" MATCH_REPLY = None def __new__(cls, msg, *args): for klass in cls.__subclasses__(): if msg and klass.MATCH_REPLY and msg.startswith(klass.MATCH_REPLY): return klass(msg,...
danielreed/python-hpOneView
hpOneView/resources/networking/ethernet_networks.py
Python
mit
9,856
0.002334
# -*- coding: utf-8 -*- ### # (C) Copyright (2012-2016) Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limi...
out: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation in OneView, just stops waiting for its completion. Returns: list
: List of created Ethernet Networks. """ data = {"type": "bulk-ethernet-network"} data.update(resource) uri = self.URI + '/bulk' self._client.create(data, uri=uri, timeout=timeout) return self.get_range(resource['namePrefix'], resource['vlanIdRange']) def get_range...
thread/django-yadt
django_yadt/management/commands/yadt_gc.py
Python
bsd-3-clause
1,117
0.000895
import os from django.core.files.storage import default_storage from django.core.management.base import BaseCommand, CommandError from ...utils import get_variant class Command(BaseCommand): USAGE = "<app_label> <model> <field> <variant>" def handle(self, *args, **options): try: app_labe...
raise CommandError(self.USAGE) variant = get_variant(app_label, model_name, field_name, variant_name) in_database = set( getattr(getattr(x, field_name), variant_name).filename for x in variant.image.field.model._default_manager.all() ) base = os.path.join( ...
image.field.upload_to, variant.name, x, ) for x in os.listdir(default_storage.path(base)) ) for x in on_disk.difference(in_database): print("I: Can be deleted: %s" % x)
ccubed/AngelBot
Currency.py
Python
mit
5,135
0.002532
import aiohttp class Currency: def __init__(self, client): self.apiurl = "https://api.fixer.io" self.currencies = {'USD': 'US Dollar', 'JPY': 'Japanese Yen', 'BGN': 'Bulgarian Lev', 'CZK': 'Czech Koruna', ...
encies[currency_from], self.currencies[currency_to])) async def latest(self, message): """ #currency [base] """ if len(message.content.split()) == 2: base = message.content.split()[1] else: b
ase = "GBP" async with aiohttp.ClientSession() as session: async with session.get(self.apiurl+"/latest", params={'base': base}, headers={'User-Agent': 'AngelBot 2 (Python 3.5.1 AioHTTP)'}) as response: if response.status == 200: jsd = await response.json() ...
yk5/incubator-airflow
airflow/contrib/kubernetes/kubernetes_request_factory/kubernetes_request_factory.py
Python
apache-2.0
6,584
0.000456
# 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 u...
ermissions and limitations # under the License. from abc import ABCMeta, abstractmethod import six class Kubernet
esRequestFactory: """ Create requests to be sent to kube API. Extend this class to talk to kubernetes and generate your specific resources. This is equivalent of generating yaml files that can be used by `kubectl` """ __metaclass__ = ABCMeta @abstractmethod def create(self, pod): ...
huggingface/transformers
src/transformers/utils/dummy_sentencepiece_and_speech_objects.py
Python
apache-2.0
347
0
# This file is autogenerated by the command `make fix-
copies`, do not edit. # flake8: noqa from ..file_utils import DummyObject, requires_backends class Speech2TextProcessor(metaclass=DummyObject): _backends = ["sentencepiece", "speech"] def __init__(self, *args, **kwargs):
requires_backends(self, ["sentencepiece", "speech"])
EmanueleCannizzaro/scons
bin/scons_dev_master.py
Python
mit
5,698
0.003335
#!/bin/sh # # A script for turning a generic Ubuntu system into a master for # SCons development. import getopt import sys from Command import CommandRunner, Usage INITIAL_PACKAGES = [ 'subversion', ] INSTALL_PACKAGES = [ 'wget', ] PYTHON_PACKAGES = [ 'g++', 'gcc', 'make', 'zlib1g-dev', ] ...
cmd.run('%(sudo)s apt-get %(yesflag)s install %(testing_packages)s') elif arg == 'buildbot': cmd.run('%(sudo)s apt-get %(yesflag)s install %(buildbot_packages)s') elif arg == 'python-versions': if install_packages:
cmd.run('%(sudo)s apt-get %(yesflag)s install %(install_packages)s') install_packages = None cmd.run('%(sudo)s apt-get %(yesflag)s install %(python_packages)s') try: import install_python except ImportError: msg = 'Could not import ins...
hansenhahn/playton-2
Programas/tl_overlay.py
Python
cc0-1.0
1,277
0.052467
#!/usr/bin/
env python # -*- coding: windows-1252 -*- ''' Created on 17/04/2018 @author: diego.hahn ''' import time import re import glob import os.path import struct import array import sys import mmap if __name__ == '__main__': import argparse os.chdir( sys.path[0] ) parser = argparse.Argument
Parser() parser.add_argument( '-s0', dest = "src0", type = str, nargs = "?", required = True ) parser.add_argument( '-s1', dest = "src1", type = str, nargs = "?", required = True ) parser.add_argument( '-n', dest = "num", type = int , required = True ) args = parser.parse_args() print "Upd...
ingadhoc/website
l10n_ar_website_sale_ux/__manifest__.py
Python
agpl-3.0
1,366
0
############################################################################## # # Copyright (C) 2015 ADHOC SA (http://www.adhoc.com.ar) # All Rights Reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # pub...
n the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have rece
ived a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'l10n_ar Website Sale UX', 'category': 'base.module_category_knowledge_management', 'vers...
tkcroat/Augerquant
Development/Auger_integquant_functions_11Nov16backup.py
Python
mit
64,350
0.024149
# -*- coding: utf-8 -*- """ Created on Wed May 11 08:08:52 2016 @author: tkc """ import re from collections import defaultdict import pandas as pd import numpy as np import scipy import scipy.stats from scipy import optimize from math import factorial # used by Savgol matrix from scipy.optimize import cu...
ent set for i, elem in enumerate(elemlist): # find row in AESquantparams for this element thiselemdata=AESquantparams[(AESquantparams['element']==elem)] thiselemdata=thiselemdata.squeeze() # series with this elements params thresholds.update({elem:thiselemdata.siglevel}) ...
ws(df): ''' Make param log entry for for each areanum - used by calccomposition to correctly process spe files with multiple spatial areas passed df is usually list of spe files this solves problem that AugerParamLog only has one entry (despite possibly having multiple distinct areas with different spect...
rayosborn/pycal
scripts/SendReminder.py
Python
lgpl-3.0
2,414
0.004143
#!/usr/bin/env python # PyCal - Python web calend
ar # # Copyright (C) 2004 Ray Osborn # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as publi
shed by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Les...
unnikrishnankgs/va
venv/lib/python3.5/site-packages/IPython/core/shellapp.py
Python
bsd-2-clause
15,915
0.005278
# encoding: utf-8 """ A mixin for :class:`~IPython.core.application.Application` classes that launch InteractiveShell instances, load extensions, etc. """ # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. import glob import os import sys from traitlets.config.applic...
Bool(True, help="""Should variables loaded at startup (by startup files, exec_lines, etc.) be hidden from tools like %who?""" ).tag(config=True) exec_files = List(Unicode(), help="""List of files to run at IPython startup.""" ).tag(config=True) exec_PYTHONSTARTUP = Bool(True, ...
file referenced by the PYTHONSTARTUP environment variable at IPython startup.""" ).tag(config=True) file_to_run = Unicode('', help="""A file to be run""").tag(config=True) exec_lines = List(Unicode(), help="""lines of code to run at IPython startup.""" ).tag(config=True) co...
eventable/vobject
docs/build/lib/vobject/change_tz.py
Python
apache-2.0
3,148
0.003812
"""Translate an ics file's events to a different timezone.""" from optparse import OptionParser from vobject import icalendar, base try: import PyICU except: PyICU = None from datetime import datetime def change_tz(cal, new_timezone, default, utc_only=False, utc_tz=icalendar.utc): """ Change the tim...
None: print("Failure. change_tz requires PyICU, exiting") elif options.list: for tz_string in PyICU.TimeZone.createEnumeration(): print(tz_string) elif ar
gs: utc_only = options.utc if utc_only: which = "only UTC" else: which = "all" print("Converting {0!s} events".format(which)) ics_file = args[0] if len(args) > 1: timezone = PyICU.ICUtzinfo.getInstance(args[1]) else: ...
peraktong/AnniesLasso
sandbox-scripts/rf_start.py
Python
mit
1,538
0.004551
import os import numpy as np from astropy.table import Table import AnniesLasso as tc a = tc.load_model("gridsearch-2.0-3.0.model", threads=8) # Load the d
ata. PATH, CATALOG, FILE_FORMAT = ("", "apogee-rg.fits", "apogee-rg-custom-normalization-{}.memmap") labelled_set = Table.read(os.path.join(PATH, CATALOG)) dispersion = np.memmap(os.path.join(PATH, FILE_FORMAT).format("dispersion"), mode="r", dtype=float) normalized_flux = np.memmap( os.path.join(PATH, FIL...
((len(labelled_set), -1)) normalized_ivar = np.memmap( os.path.join(PATH, FILE_FORMAT).format("ivar"), mode="c", dtype=float).reshape(normalized_flux.shape) # Split up the data into ten random subsets. np.random.seed(123) # For reproducibility. q = np.random.randint(0, 10, len(labelled_set)) % 10 validate_set...
itdxer/neupy
examples/competitive/sofm_compare_weight_init.py
Python
mit
1,754
0
from itertools import product import matplotlib.pyplot as plt from neupy import algorithms, utils, init from utils import plot_2d_grid, make_circle, make_elipse, make_square plt.style.use('ggplot') utils.reproducible() if __name__ == '__main__': GRID_WIDTH = 4 GRID_HEIGHT = 4 datasets = [ mak...
ialized: sofm.init_weights(data) plt.subplot(n_rows, n_columns, index) plt.title(conf[
'title']) plt.scatter(*data.T, color=blue, alpha=0.05) plt.scatter(*sofm.weight, color=red) weights = sofm.weight.reshape((2, GRID_HEIGHT, GRID_WIDTH)) plot_2d_grid(weights, color=red) index += 1 plt.show()
caot/intellij-community
python/testData/refactoring/extractmethod/Statement.after.py
Python
apache-2.0
98
0.010204
def f():
a = 1
b = 1 foo(a, b) def foo(a_new, b_new): print(a_new + b_new * 123)
atdsaa/django-pgcrypto-fields
pgcrypto/admin.py
Python
bsd-2-clause
209
0
class PGPAdmin(object): def get_queryset(self, request): """Skip any auto decryp
tion when ORM calls are from the admin.""" return self.model.objects
.get_queryset(**{'skip_decrypt': True})
amiraliakbari/sharif-mabani-python
by-session/ta-921/j1/turtle7.py
Python
mit
73
0
x = 2 print "salam!" for
i in range(10): print x, x = x * 2
acidjunk/django-scrumboard
scrumtools/wsgi.py
Python
gpl-3.0
395
0.002532
""" WSGI config for ScrumBoard project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on thi
s file, see https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "scrumtools.settings") from django.core.wsgi import get_wsgi_application application
= get_wsgi_application()
simontakite/sysadmin
pythonscripts/thinkpython/pie.py
Python
gpl-2.0
1,636
0.001222
"""This module contains code from Think Python by Allen B. Downey http://thinkpython.com Copyright 2012 Allen B. Downey License: GNU GPLv3 http://www.gnu.org/licenses/gpl
.html """ import math try: # see if Swampy is installed as a package from swampy.TurtleWorld import * except ImportError: # otherwise see if the modules are on the PYTHONPATH from TurtleWorld import * def draw_pie(t, n, r): """Draws a pie, then moves into position to the right. t: Turtle ...
ength of the radial spokes """ polypie(t, n, r) pu(t) fd(t, r*2 + 10) pd(t) def polypie(t, n, r): """Draws a pie divided into radial segments. t: Turtle n: number of segments r: length of the radial spokes """ angle = 360.0 / n for i in range(n): isosceles(...
pablogonzalezalba/a-language-of-ice-and-fire
lexer_rules.py
Python
mit
1,138
0.011424
# -*- cod
ing: utf-8 -*- tokens = [ 'LPAREN', 'RPAREN', 'LBRACE', 'RBRACE', 'EQUAL', 'DOUBLE_EQUAL', 'NUMBER', 'COMMA', 'VAR_DEFINITION', 'IF', 'ELSE', 'END'
, 'ID', 'PRINT' ] t_LPAREN = r"\(" t_RPAREN = r"\)" t_LBRACE = r"\{" t_RBRACE = r"\}" t_EQUAL = r"\=" t_DOUBLE_EQUAL = r"\=\=" def t_NUMBER(token): r"[0-9]+" token.value = int(token.value) return token t_COMMA = r"," def t_VAR_DEFINITION(token): r",\sFirst\sof\s(his|her)\sName" return tok...
aurelienmaury/galaxie
sandbox_mo/zero-ears/proc.py
Python
gpl-3.0
645
0.007752
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'amaury' import subprocess import time import s
ys class Timeout(Exception): pass def run(command, timeout=10): proc = subprocess.Popen(command, bufsize=0, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) poll_seconds = .250 deadline = time.time()+timeout while time.time() < deadline and proc.poll() == None: time.sleep(poll_s...
dout, stderr = proc.communicate() return stdout, stderr, proc.returncode
StackPointCloud/profitbricks-sdk-python
tests/test_errors.py
Python
apache-2.0
2,455
0.000815
# Copyright 2015-2017 ProfitBricks GmbH # # 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 i...
ND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest
from profitbricks.client import ProfitBricksService, Datacenter, Volume from profitbricks.errors import PBError, PBNotAuthorizedError, PBNotFoundError, PBValidationError from helpers import configuration from helpers.resources import resource class TestErrors(unittest.TestCase): @classmethod def setUpClass...
MarcoMengoli/marcomengoli.github.io
filesForPosts/parserBasket.py
Python
mit
3,836
0.011992
import re import urllib.request import io from bs4 import BeautifulSoup base_url = "http://www.basketball-reference.com" file_name = "players" separator = "#" def getPlayers(character)
: url = "{0}/players/{1}".format(base_url, character) u = urllib.re
quest.urlopen(url, data = None) f = io.TextIOWrapper(u,encoding='utf-8') dataString = f.read() #with open("http://www.basketball-reference.com/players/a") as playersFile: #dataBinary = playersFile.read() #dataString = str(dataBinary) namesRegex = r'(?i)<tr[^>]*>\s*<td[^>]*>\s*<a\s+href...
gds-attic/transactions-explorer
test/filters/test_filters.py
Python
mit
7,300
0.000548
from hamcrest import assert_that, is_ from lib.filters import number_as_magnitude, number_as_financial_magnitude, join_url_parts, string_as_static_url, digest, number_as_grouped_number, number_as_percentage_change def test_number_as_magnitude(): assert_that(number_as_magnitude(1.23), is_("1.23")) assert_that...
k")) assert_that(number_as_magnitude(123600), is_("124k")) assert_that(number_as_magnitude(1230000), is_("1.23m")) assert_that(number_as_magnitude(1234000), is_("1.23m")) assert_that(number_as_magnitude(1236000), is_("1.24m")) assert_that(number_as_m
agnitude(12300000), is_("12.3m")) assert_that(number_as_magnitude(12340000), is_("12.3m")) assert_that(number_as_magnitude(12360000), is_("12.4m")) assert_that(number_as_magnitude(123000000), is_("123m")) assert_that(number_as_magnitude(123400000), is_("123m")) assert_that(number_as_magnitude(12360...
6mandati6/6mandati6
tt.py
Python
apache-2.0
135
0.014815
"hey iam there yyyyyyyyyyyyyyyyyyyyyyyyyyyy
yyyyyuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuyyy"
hornn/interviews
tools/bin/ext/figleaf/__init__.py
Python
apache-2.0
8,016
0.003244
""" figleaf is another tool to trace Python code coverage. figleaf uses the sys.settrace hook to record which statements are executed by the CPython interpreter; this record can then be saved into a file, or otherwise communicated back to a reporting script. figleaf differs from the gold standard of Python coverage t...
I: :: * ``start(ignore_lib=True)`` -- start recording code coverage. * ``stop()`` -- stop recording code coverage. * ``get_trace_obj()`` -- return the (singleton) trace object. * ``get_info()`` -- get the coverage dictionary Classes & functions worth knowing about (lower level A...
coverage dictionary * ``write_coverage(filename)`` -- write the coverage out. * ``annotate_coverage(...)`` -- annotate a Python file with its coverage info. Known problems: -- module docstrings are *covered* but not found. AUTHOR: C. Titus Brown, titus@idyll.org, with contributions from Iain Lowe. 'figleaf' is ...
joshuahoman/vivisect
vdb/qt/registers.py
Python
apache-2.0
753
0.002656
from PyQt4 import QtCore, QtGui import vtrace.qt import vdb.qt.base from vqt.main import * class VdbRegistersWindow(vdb.qt.base.VdbWidgetWindow): def __init__(self, db, dbt, parent=None): vdb.qt.base.VdbWidgetWindow.__init__(self, db, dbt, parent=parent) s
elf.regsWidget = vtrace.qt.RegistersView(trace=dbt, parent=parent) vbox = QtGui.QVBoxLayout() vbox.addWidget(self.regsWidget) self.setLayout(vbox) self.setWindowTitle('Registers') vqtconnect(self.vqLoad, 'vdb:setregs') vqtconnect(self.vqLoad, 'vdb:setthread') def ...
''' the widgets in RegistersView already register for notifications. ''' self.regsWidget.reglist.vqLoad()
gramps-project/addons-source
PythonGramplet/PythonGramplet.gpr.py
Python
gpl-2.0
423
0.023641
register(GRAMPLET, id="Python Gram
plet", name=_("Python Shell"), description = _("Interactive Python interpreter"), status = STABLE, fname="PythonGramplet.py", height=250, gramplet = '
PythonGramplet', gramplet_title=_("Python Shell"), version = '1.0.33', gramps_target_version = "5.1", help_url="PythonGramplet", )
arunkgupta/gramps
gramps/gui/editors/editdate.py
Python
gpl-2.0
13,619
0.004846
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2002-2006 Donald N. Allingham # Copyright (C) 2009 Douglas S. Blank # # 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; e...
sh } WIKI_HELP_PAGE = '%s_-_Entering_and_Editing_Data:_Detaile
d_-_part_1' % URL_MANUAL_PAGE WIKI_HELP_SEC = _('manual|Editing_Dates') #------------------------------------------------------------------------- # # EditDate # #------------------------------------------------------------------------- class EditDate(ManagedWindow): """ Dialog allowing to build the date preci...
fin/froide
froide/account/migrations/0019_auto_20190309_1223.py
Python
mit
755
0
# Generated by Django 2.1.
7 on 2019-03-09 11:23 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ("account", "0018_auto_20190309_1153"), ] operations = [ migrations.AddField( model_name="taggeduser", name="co
unt", field=models.PositiveIntegerField(default=1), ), migrations.AddField( model_name="taggeduser", name="tag_new", field=models.ForeignKey( null=True, on_delete=django.db.models.deletion.CASCADE, related_na...
Utkarshdevd/summer14python
getText.py
Python
mit
665
0.034586
import re def getText(data): res = [] resString = "" pattern = re.compile(r"\(?M{0,4}(CM|CD|D?C{0,3})(
XC|XL|L?X{0,3})(IX|IV|V?I{0,3})\)(.*?)\. *\n", re.I) iteratable = pattern.finditer(data) newPattern = re.compile(r"\(?M{0,4}CM|CD|D?C{0,3}XC|XL|L?X{0,3}IX|IV|V?I{0,3}\)", re.I) checkPattern = re.compile(r"\(?M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?
X{0,3})(IX|IV|V?I{0,3})\) *", re.I) resString = "" for _ in iteratable: resString = str(_.group()) if(newPattern.match(resString) == None): for a in checkPattern.finditer(resString): resString = resString.replace(a.group(), "") res.append(resString) else: print "notCool" continue return res
0x326/academic-code-portfolio
2016-2021 Miami University/CSE 467 Computer and Network Security/2019-03-06 Homework 2.py
Python
mit
3,384
0.006206
#!/usr/bin/env python3 from typing import NamedTuple from ciphers import HexString rijndael_s_box = ( 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
, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x3
4, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39,...
choderalab/openpathsampling
openpathsampling/tests/test_volume.py
Python
lgpl-2.1
17,171
0.001223
""" @author David W.H. Swenson """ from __future__ import absolute_import from builtins import object from nose.tools import (assert_equal, assert_not_equal, assert_is, raises, assert_true, assert_false) from nose.plugins.skip import Skip, SkipTest from .test_helpers import (CallIdentity, raise...
ssert_is((full & volA), volA) assert_is((volA & full), volA) assert_is((full | volA), full) assert_is((volA | full), full) assert_equal((volA - full), volume.EmptyVolume()) assert_equal((full - volA), ~ volA) assert_equal((full ^ volA), ~ volA) assert_equal((volA ...
assert_equal(volA(0.49), True) assert_equal(volA(0.50), False) assert_equal(volA(0.51), False) def test_lower_boundary(self): assert_equal(volA(-0.49), True) assert_equal(volA(-0.50), True) assert_equal(volA(-0.51), False) def test_negation(self): assert_...
darkframemaster/pyrepo
app/local/__pycache__/ui.py
Python
mit
5,962
0.070665
#!/usr/bin/env python3 #-*- coding:utf-8 -*- ''' this is a simple UI for offline working ''' __author__='xuehao' import re import tkinter import tkinter.simpledialog import tkinter.messagebox import gittime import gitcount ''' list with a scrollbar and a lable of lines in the list ''' class myListBox(object): def ...
gebox.showerror('git count','start time bigger than end time!') return self.comInfo
=gitcount.Info() self.user=gitcount.Coder() self.comInfo.get_commit_dic(self.st_time,self.ed_time) self.user.collect_stats(self.comInfo.commit_dic) self.user.sort_coder() listroot=tkinter.Tk() listbox=myListBox(listroot,self.user.user_sort) ''' ''' def initDia(self): #init 按钮绑定的事件 d=initDia(self....
Ban3/Limnoria
plugins/Filter/plugin.py
Python
bsd-3-clause
25,613
0.004295
# -*- encoding: utf-8 -*- ### # Copyright (c) 2002-2005, Jeremiah Fincher # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright not...
bytes_ = text.encode() else: bytes_ = text else: if isinstance(text, unicode): text = text.encode() bytes_ = map(ord, text) for i in bytes_: LL = [] assert i<=256 counte
r = 8 while i: counter -= 1 if i & 1: LL.append('1') else: LL.append('0') i >>= 1 while counter: LL.append('0') counter -= 1 LL.reverse() ...
morepath/morepath
morepath/pdbsupport.py
Python
bsd-3-clause
465
0
from pdb import Pdb # pragma: nocoverage morepath_pdb = Pdb( skip=["reg.*", "inspect", "repoze.lru"] ) # pragma: nocoverage def set_trace(*args, **kw): # pragma: nocoverage """Set pdb trace as in ``import pdb; pdb.set_trace``, ignores ``reg``. Use ``from morepath import pdbsupport; pdbsupport.set_tr...
gs, **kw)
ProteinDF/ProteinDF_bridge
tests/test_ssbond.py
Python
gpl-3.0
649
0
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest import doctest from proteindf_bridge.ssbond import SSBond
class SSBondTest(unittest.TestCase): def setUp(self): pass def tearDown(self): pass # def test_check(self): # tmp_pdb = Pdb('./data/1hls.pdb') # models = tmp_pdb.get_atomgroup() # model = models.get_group('model_1') # ssbond = SSBond() # ssbond.ch...
__name__ == '__main__': unittest.main()
MDAnalysis/mdanalysis
package/MDAnalysis/lib/picklable_file_io.py
Python
gpl-2.0
15,899
0
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*- # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 # # MDAnalysis --- https://www.mdanalysis.org # Copyright (c) 2006-2017 The MDAnalysis Development Team and contributors # (see the file AUTHORS for the full list of names) # # Released under t...
lable
(XYZ_bz2) >>> file.readline() >>> file_pickled = pickle.loads(pickle.dumps(file)) >>> print(file.tell(), file_pickled.tell()) 5 5 See Also --------- FileIOPicklable BufferIOPicklable TextIOPicklable GzipPicklable .. versionadded:: 2.0.0 """ def ...
karlbright/beets
test/test_vfs.py
Python
mit
1,621
0.003085
# This file is part of beets. # Copyright 2011, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, ...
(unittest.TestCase): def setUp(self): self.lib = library.Library(':memory:', path_formats=[ ('default', 'albums/$album/$title'), ('singleton:true', 'tracks/$artist/$title'), ]) self.lib.add(_common.item()) self.lib.add_album([_common.item()]) self.lib....
ee = vfs.libtree(self.lib) def test_singleton_item(self): self.assertEqual(self.tree.dirs['tracks'].dirs['the artist']. files['the title'], 1) def test_album_item(self): self.assertEqual(self.tree.dirs['albums'].dirs['the album']. files['th...
iniverno/RnR-LLC
simics-3.0-install/simics-3.0.31/amd64-linux/lib/telos_mote_components.py
Python
gpl-2.0
9,668
0.006309
# MODULE: telos-mote-components # CLASS: telos-mote from sim_core import * from components import * # Telos Mote class telos_mote_component(component_object): classname = 'telos-mote' basename = 'system' description = "A Telos Mote, based on the msp430 processor" # connectors: connectors = { ...
.o.timer_b.irq_dev = self.o.cpu self.o.timer_b.irq_vector_ccr0 = 13 self.o.timer_b.irq_vector_tmiv = 12 # basic clock self.o.basic_clock.queue = self.o.cpu # buttons self.o.reset_button.irq_dev = self.o.cpu self.o.reset_button.irq_level = 15 # Memory map ...
s_mem.map = [ # Memory is all considered as RAM, including what is # really FLASH. This works for the currently tested code. [0x00000200, self.o.ram, 0, 0x200, 0x10000 - 0x200], # sfr registers [0x00000000, self.o.sfr, 0, 0, 6], # HOLE -- all holes...
rossonet/RAM
OctoPrint/src/octoprint/filemanager/storage.py
Python
lgpl-3.0
35,942
0.029886
# coding=utf-8 from __future__ import absolute_import __author__ = "Gina Häußge <osd@foosel.net>" __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import logging import os im...
f the new folder :param bool ignore_existing: if set to True, no error will be raised if the folder to be added already exists :return: the sanitized name of the new folder to be used for future references to the folder """ raise NotImplementedError() def remove_folder(self, path, recursive=True): """ Rem...
the path of the folder to remove :param bool recursive: if set to True, contained folders and files will also be removed, otherwise and error will be raised if the folder is not empty (apart from ``.metadata.yaml``) when it's to be removed """ raise NotImplementedError() def add_fil...
OSGeoLabBp/tutorials
hungarian/python/code/ellipse.py
Python
cc0-1.0
775
0.002581
#!/usr/bin/env python # -*- coding: UTF-8 -*- import math from circle import Circle class Ellipse(Circle): """ class for 2D ellipses """ def __init__(self, x=0, y=0, p=2, r=1, b=1): super(Ellipse, sel
f).__init__(x, y, p, r) self.b =
b def __str__(self): return ("{0:." + str(self.p) + "f}, {1:." + str(self.p) + "f}, {2:." + str(self.p) + "f}, {3:." + str(self.p) + "f}").format(self.x, self.y, self.r, self.b) def area(self): """ area of ellipse """ return self.r * self.b * math.pi ...
wendysuly/TeamTalk
win-client/3rdParty/src/json/devtools/batchbuild.py
Python
apache-2.0
11,585
0.018127
import collections import itertools import json import os import os.path import re import shutil import string import subprocess import sys import cgi class BuildDesc: def __init__(self, prepend_envs=None, variables=None, build_type=None, generator=None): self.prepend_envs = prepend_envs or [] # [ { "var":...
ilding:
', cmd = ['cmake', '--build', self.work_dir] if self.desc.build_type: cmd += ['--config', self.desc.build_type] succeeded = self._execute_build_subprocess( cmd, self.desc.env(), self.build_log_path ) print 'done' if succeeded else 'FAILED' return succeeded def _e...
thesuperzapper/tensorflow
tensorflow/contrib/keras/python/keras/initializers_test.py
Python
apache-2.0
5,930
0.007589
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
l(self): tensor_shape = (5, 6, 4, 2) with self.test_session(): fan_in, fan_out = init_ops._compute_fans(tensor_shape) scale = np.sqrt(2. / (fan_in + fan_out)) self._runner(keras.initializers.glorot_normal(seed=123), tensor_shape, target_mean=0., target_std=None, target_max=2...
def test_he_normal(self): tensor_shape = (5, 6, 4, 2) with self.test_session(): fan_in, _ = init_ops._compute_fans(tensor_shape) scale = np.sqrt(2. / fan_in) self._runner(keras.initializers.he_normal(seed=123), tensor_shape, target_mean=0., target_std=None, target_max=2 * s...
larsks/cloud-init
tests/cloud_tests/testcases/modules/set_password_expire.py
Python
gpl-3.0
727
0
# This file is part of cloud-init. See LICENSE file for license information. """cloud-init Integration Test Verify Script.""" from tests.cloud_tests.testcases import base class TestPasswordExpire(base.CloudTestCase): """Test password module.""" def test_shadow(self): """Test user frozen in shadow.""...
arry:!:', out) self.assertIn('dick:!:', out) self.assertIn('tom:!:', out) self.assertIn('harry:!:', out) def test_ssh
d_config(self): """Test sshd config allows passwords.""" out = self.get_data_file('sshd_config') self.assertIn('PasswordAuthentication yes', out) # vi: ts=4 expandtab
paulocmi/Prod_pc
prod_announcer/settings.py
Python
mit
5,111
0.001957
# Django settings for prod_announcer project. import os LOCAL = lambda x: os.path.join(os.path.sep.join( os.path.abspath( os.path.dirname(__file__)).split(os.path.sep)), x) DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( ('Guilherme da Costa de Albuquerque', 'guilherme.albuq...
ue # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/var/www/example.com/media/" MEDIA_ROOT = LOCAL('media') MEDIA_URL = '/media/' STATIC_RO
OT = LOCAL('static_root') STATIC_URL = '/static/' STATICFILES_DIRS = ( LOCAL('static'), ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFi...
kaushik94/sympy
sympy/utilities/_compilation/tests/test_compilation.py
Python
bsd-3-clause
1,775
0.001127
from __future__ import absolute_import import shutil from sympy.external import import_module from sympy.utilities.pytest import skip from sympy.utilities._compilation.compilation import compile_link_import_strings numpy = import_module('numpy') cython = import_module('cython') _sources1 = [ ('sigmoid.c', r""" ...
ings(): if not numpy: skip("numpy not installed.") if not cython: skip("cython not installed.") from sympy.utilities._compilation import has_c if not has_c(): skip("No C compiler found.") compile_kw = dict
(std='c99', include_dirs=[numpy.get_include()]) info = None try: mod, info = compile_link_import_strings(_sources1, compile_kwargs=compile_kw) data = numpy.random.random(1024*1024*8) # 64 MB of RAM needed.. res_mod = mod.sigmoid(data) res_npy = npy(data) assert numpy.all...
nigelsmall/py2neo
py2neo/packages/httpstream/watch.py
Python
apache-2.0
3,162
0
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright 2011-2014, Nigel Small # # 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 # # Unle...
36m{}\x1b[0m".format(s) def white(s): return "\x1b[36m{}\x1b[0m".format(s) def bright_black(s): return "\x1b[30;1m{}\x1b[0m".format(s) def bright_red(s): return "\x1b[31;1m{}\x1b[0m".format(s) def bright_green(s): return "\x1b[32;1m{}\x1b[0m".format(s) def bright_yellow(s): return "\x1b[33...
def bright_cyan(s): return "\x1b[36;1m{}\x1b[0m".format(s) def bright_white(s): return "\x1b[37;1m{}\x1b[0m".format(s) class ColourFormatter(logging.Formatter): def format(self, record): s = super(ColourFormatter, self).format(record) if record.levelno == logging.CRITICAL: ...
l-vincent-l/APITaxi
APITaxi/tasks/send_request_operator.py
Python
agpl-3.0
2,485
0.004829
#coding: utf-8 from flask import current_app from flask_restplus import marshal from APITaxi_models.hail import Hail, HailLog from ..descriptors.hail import hail_model from ..extensions import celery, redis_store_saved import requests, json @celery.task() def send_request_operator(hail_id, endpoint, operator_header_n...
current_app.extensions['sqlalchemy'].d
b.session.commit() return True