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
brainwane/zulip
zerver/tests/test_thumbnail.py
Python
apache-2.0
17,260
0.00197
import base64 import urllib from io import StringIO import orjson from django.conf import settings from zerver.lib.test_classes import ZulipTestCase from zerver.lib.test_helpers import ( create_s3_buckets, get_test_image_file, override_settings, use_s3_backend, ) from zerver.lib.upload import upload_b...
s_code, 302, result)
expected_part_url = get_file_path_urlpart(uri) self.assertIn(expected_part_url, result.url) # Test thumbnail size. result = self.client_get(f"/thumbnail?url={quoted_uri}&size=thumbnail") self.assertEqual(result.status_code, 302, result) expected_part_url = get_file_path_ur...
itucsdb1611/itucsdb1611
classes/information.py
Python
gpl-3.0
270
0
class Information: def __in
it__(self, objectid, cvid, information_type_id, description): self.objectid = objectid self.cvid = cvid
self.information_type_id = information_type_id self.description = description self.deleted = 0
kuiche/chromium
net/tools/testserver/testserver.py
Python
bsd-3-clause
36,527
0.008104
#!/usr/bin/python2.4 # Copyright (c) 2006-2008 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. """This is a simple HTTP server used for testing Chrome. It supports several test URLs, as specified by the handlers in TestPa...
r it only looks at the file extension.""" (shortname, extension) = os.path.splitext(file_name) if len(extension) == 0: # no extension.
return self._default_mime_type # extension starts with a dot, so we need to remove it return self._mime_types.get(extension[1:], self._default_mime_type) def KillHandler(self): """This request handler kills the server, for use when we're done" with the a particular test.""" if (self.path.fin...
Kami/libcloud
libcloud/common/types.py
Python
apache-2.0
6,989
0
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use ...
f._data]) repr_string = '[%s]' % (repr_string) return rep
r_string def _load_all(self): while not self._exhausted: newdata, self._last_key, self._exhausted = \ self._get_more(last_key=self._last_key, value_dict=self._value_dict) self._data.extend(newdata) self._all_loaded = True
nint8835/NintbotForDiscordV2
NintbotForDiscord/Enums.py
Python
mit
1,656
0
from enum imp
ort Enum class EventType(Enum): """Enum containing the various types of events that can occur.""" CLIENT_READY = "CLIENT_READY" CLIENT_RESUMED = "CLIENT_RESUMED" MESSAGE_RECEIVED = "MESSAGE_RECEIVED" SERVER_MESSAGE_RECEIVED = "SERVER_MESSAGE_RECEIVED" PRIVATE_MESSAGE_REC
EIVED = "PRIVATE_MESSAGE_RECEIVED" COMMAND_RECEIVED = "COMMAND_RECEIVED" MESSAGE_DELETED = "MESSAGE_DELETED" MESSAGE_EDITED = "MESSAGE_EDITED" CHANNEL_DELETED = "CHANNEL_DELETED" CHANNEL_CREATED = "CHANNEL_CREATED" CHANNEL_UPDATED = "CHANNEL_UPDATED" MEMBER_JOINED = "MEMBER_JOINED" ME...
kikinteractive/MaxMind-DB-Reader-python
setup.py
Python
apache-2.0
5,415
0.000554
import os import re import sys # This import is apparently needed for Nose on Red Hat's Python import multiprocessing from distutils.command.build_ext import build_ext from distutils.errors import (CCompilerError, DistutilsExecError, DistutilsPlatformError) try: from setuptools impo...
.S).match(maxminddb_text).group(1) def status_msgs(*msgs): print('*' * 75) for msg in msgs: print(msg) print('*' * 75) def find_packages(location): packages = [] for pkg in ['maxminddb']: for _dir, subdirectories, files in ( os.walk(os.path.join(location, pkg))): ...
py' in files: tokens = _dir.split(os.sep)[len(location.split(os.sep)):] packages.append(".".join(tokens)) return packages def run_setup(with_cext): kwargs = {} if with_cext: if Feature: kwargs['features'] = {'extension': Feature( "optiona...
Kennyl/calibre-web
cps/ub.py
Python
gpl-3.0
23,868
0.005237
#!/usr/bin/env python # -*- coding: utf-8 -*- from sqlalchemy import * from sqlalchemy import exc from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import * from flask_login import AnonymousUserMixin import sys import os import logging from werkzeug.security import generate_password_hash from...
name = Column(String(64), unique=True) email = Column(String(120), unique=Tru
e, default="") role = Column(SmallInteger, default=ROLE_USER) password = Column(String) kindle_mail = Column(String(120), default="") shelf = relationship('Shelf', backref='user', lazy='dynamic', order_by='Shelf.name') downloads = relationship('Downloads', backref='user', lazy='dynamic') locale ...
OneDrive/onedrive-sdk-python
src/onedrivesdk/model/items_collection_page.py
Python
mit
1,072
0.005597
# -*- coding
: utf-8 -*- ''' # Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. # # This file was generated and any changes will be overw
ritten. ''' from __future__ import unicode_literals from ..collection_base import CollectionPageBase from ..model.item import Item class ItemsCollectionPage(CollectionPageBase): def __getitem__(self, index): """Get the Item at the index specified Args: index (int): The index...
erramuzpe/C-PAC
CPAC/median_angle/tests/test_median_angle.py
Python
bsd-3-clause
1,151
0.01477
def test_median_angle_correct(): from CPAC.median_angle import median_angle_correct import numpy as np import nibabel as nb def getY(filepath): nii = nb.load(filepath) data = nii.get_data().astype(np.float64) mask = (data != 0).sum(-1) != 0 return data[mask]...
ii.gz' target_angle = 88.0 Y_orig = normalize(getY(subject)) U_orig, S, Vh = np.linalg.svd(Y_
orig, full_matrices=False) corrected_file, angles_file = median_angle_correct(target_angle, subject) Y_corr = normalize(getY(corrected_file)) median_angle_orig = np.median(np.arccos(U_orig[:,0].T.dot(Y_orig))) median_angle_corr = np.median(np.arccos(U_orig[:,0].T.dot(Y_corr))) pr...
rafaelsierra/estoudebike-api
src/bike_auth/models.py
Python
apache-2.0
376
0.00266
import uuid from django.contrib.auth.models import User from django.db import models class Token(models.Model): key = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_at = models.DateTimeField(auto_now_ad
d=True) is_active = models.BooleanField(default=True, db_index=True) user = models.ForeignKey(User, null=True, blank=True)
seijim/cloud-robotics-fx-v2
CloudRoboticsApi/ClientCode_Pepper/HeadWaters/PepperCode2/lib/cloudrobotics/conversation/message.py
Python
mit
746
0.002809
# -*- coding: utf-8 -*- # # Cloud Robotics FX 会話理解API用メッセージ # # @author: Osamu Noguchi <noguchi@headwaters.co.jp> # @version: 0.0.1 import cloudrobotics.message as message APP_ID = 'SbrApiServices' PROCESSING_ID = 'RbAppConversationApi' # 会話メッセージ # class ConversationMessage(message.CRFXMessage): def __init__...
it__() self.header['RoutingType'] = message.ROUTING_TYPE_CALL self.header['AppProcessingId'] = PROCESSING_ID self.header['MessageId'] = type self.body = { 'visitor': visitor, 'visitor_id': visitor_id,
'talkByMe': talkByMe }
Fleurer/flask-oauthlib
example/facebook.py
Python
bsd-3-clause
1,663
0
from flask import Flask, redirect, url_for, session, request from flask_oauthlib.client import OAuth, OAuthException FACEBOOK_APP_ID = '188477911223606' FACEBOOK_APP_SECRET = '621413ddea2bcc5b2e83d42fc40495de' app = Flask(__name__) app.debug = True app.secret_key = 'development' oauth = OAuth(app) facebook = oauth...
ct(url_for('login')) @app.route('/login') def login(): callback = url_for( 'facebook_authorized', next=request.args.get('next') or request.referrer or None, _external=True ) return facebook.authorize(callback=callback) @app.route('/login/authorized') def facebook_aut
horized(): resp = facebook.authorized_response() if resp is None: return 'Access denied: reason=%s error=%s' % ( request.args['error_reason'], request.args['error_description'] ) if isinstance(resp, OAuthException): return 'Access denied: %s' % resp.message ...
rob-b/belt
belt/values.py
Python
bsd-3-clause
1,091
0
import os import logging from .axle import split_package_name logger = logging.getLogger(__name__) class Path(object): def __init__(self, path): self.path = path @property def exists(self): return os.path.exists(self.path) class ReleaseValue(object): _md5 = '' def __init__(...
self._md5 = hashed.read() except IOError: # msg = u'{} does not exist'.format(hash_name) # logger.exception(msg) pass return self._md5 @property
def fullpath(self): return os.path.join(self.package_dir, self.fullname)
vuolter/pyload
src/pyload/core/managers/event_manager.py
Python
agpl-3.0
3,084
0
# -*- coding: utf-8 -*- import time from ..utils.purge import uniquify class EventManager: def __init__(self, core): self.pyload = core self._ = core._ self.clients = [] def new_client(self, uuid): self.clients.append(Client(uuid)) def clean(self): for n, client...
uuid = False for client in self.clients: if client.uuid == uuid: client.last_active = time.time() valid_uuid = True while cli
ent.new_events(): events.append(client.pop_event().to_list()) break if not valid_uuid: self.new_client(uuid) events = [ ReloadAllEvent("queue").to_list(), ReloadAllEvent("collector").to_list(), ] retu...
crmccreary/openerp_server
openerp/addons/board/__init__.py
Python
agpl-3.0
1,082
0.001848
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the...
uld have received a copy of the GNU Affero Gen
eral Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import board import wizard # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
plotly/plotly.py
packages/python/plotly/plotly/validators/bar/hoverlabel/_namelengthsrc.py
Python
mit
432
0.002315
import _plotly_utils.basevalidators class NamelengthsrcValidator(_plotly_utils.basevalidators.SrcValidator): def __init__(
self, plotly_name="namelengthsrc", parent_name="bar.hoverlabel", **kwargs ): super(NamelengthsrcValidator, self).__init__( plotly_name=plotly_name,
parent_name=parent_name, edit_type=kwargs.pop("edit_type", "none"), **kwargs )
mrjacobagilbert/gnuradio
grc/core/generator/hier_block.py
Python
gpl-3.0
6,202
0.000967
import collections import os import codecs from .top_block import TopBlockGenerator from .. import Constants from ..io import yaml class HierBlockGenerator(TopBlockGenerator): """Extends the top block generator to also generate a block YML file""" def __init__(self, flow_graph, _): """ Ini...
d S_IWRITE, other flags are ignored os.chmod(self.file_path_yml, self._mode) def _build_block_n_from_flow_graph_io(self): """ Generate a block YML nested data from the flow graph IO Returns: a yml node tree """ # Extract info from the flow graph ...
def var_or_value(name): if name in (p.name for p in parameters): return "${" + name + " }" return name # Build the nested data data = collections.OrderedDict() data['id'] = block_id data['label'] = ( self._flow_graph.get_option('t...
andreipradan/raspberrymediaplayer
src/radio/api/utils.py
Python
mit
328
0
import subprocess de
f send_command(*args): delimiter = '&&' if len(args) == 2 and delimiter in args[1]: split_arg = args[1].split(delimiter) args = [args[1]] args.extend(split_arg) process = subprocess.Popen(args, stdout=subprocess.PIPE) return process.communicate()[0].decode("utf-8"
)
lukeshingles/artistools
artistools/makemodel/__init__.py
Python
mit
65
0.015385
# import .1dslicefrom3d import artistools.make
model.botyanski2
017
lwahlmeier/python-litesockets
tests/__init__.py
Python
unlicense
24
0.041667
#fro
m . import sslTests
aldenjenkins/foobargamingwebsite
paypal/standard/ipn/south_migrations/0006_auto__chg_field_paypalipn_custom__chg_field_paypalipn_transaction_subj.py
Python
bsd-3-clause
14,862
0.007872
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'PayPalIPN.custom' db.alter_column(u'paypal_ipn', 'cust...
64', 'decimal_places': '2', 'blank': 'True'}), 'auth_exp': ('django.db.models.fields.CharField', [], {'max_length': '28', 'blank': 'True'}), 'auth_id': ('django.db.models.fields.CharField', [], {'max_length': '19', 'blank': 'True'}), 'auth_status': ('django.db.models.fields.CharField...
, [], {'max_length': '255', 'blank': 'True'}), 'business': ('django.db.models.fields.CharField', [], {'max_length': '127', 'blank': 'True'}), 'case_creation_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'case_id': ('django.db.models.fields.C...
bluemini/kuma
vendor/packages/translate/storage/test_dtd.py
Python
mpl-2.0
20,624
0.001746
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2013 Zuza Software Foundation # # This file is part of translate. # # translate 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 t...
", 'the "thing"' ] fo
r special in specials: quoted_special = dtd.quoteforandroid(special) unquoted_special = dtd.unquotefromandroid(quoted_special) print("special: %r\nquoted: %r\nunquoted: %r\n" % (special, quoted_special, ...
jtyr/ansible
lib/ansible/modules/command.py
Python
gpl-3.0
13,711
0.003502
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>, and others # Copyright: (c) 2016, Toshio Kuratomi <tkuratomi@ansible.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, div...
using the C(args) L(task keyword,../reference_appendices/playbooks_keywords.html#task) or use C(cmd) parameter. - Either a free form command or C(cmd) parameter is required, see the examples. - For Windows targets, use the M(ansible.windows.win_command) module instead. options: free_form: descri...
g as a command to run. - There is no actual parameter named 'free form'. cmd: type: str description: - The command to run. argv: type: list description: - Passes the command as a list rather than a string. - Use C(argv) to avoid quoting values that would otherwise be interpre...
openstack/oslo.vmware
oslo_vmware/_i18n.py
Python
apache-2.0
852
0
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in
compliance with the License. You may obtain # a copy of the License at # # http://www.
apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permiss...
msullivan/advent-of-code
2019/setup.py
Python
mit
164
0.04878
from dis
tutils.core import setup, Extension setup(name = '_intcode', version = '0.1', ext_modules = [Extension('_i
ntcode', sources = ['_intcode.c'])])
apllicationCOM/youtube-dl-api-server
youtube_dl_server/youtube_dl/extractor/clipfish.py
Python
unlicense
1,624
0.000616
from __future__ import unicode_literals import re import time import xml.etree.ElementTree from .common import InfoExtractor f
rom ..utils import ( ExtractorError, parse_duration, ) class ClipfishIE(InfoExtractor): IE_NAME = 'clipfish' _VALID_URL = r'^https?://(?:www\.)?clipfish\.de/.*?/video/(?P<id>[0-9]+)/' _TEST = { 'url': 'http://www.clipfish.de/special/game-trailer/video/396
6754/fifa-14-e3-2013-trailer/', 'md5': '2521cd644e862936cf2e698206e47385', 'info_dict': { 'id': '3966754', 'ext': 'mp4', 'title': 'FIFA 14 - E3 2013 Trailer', 'duration': 82, }, 'skip': 'Blocked in the US' } def _real_extract(self,...
phelmig/django-fastbill
django_fastbill/migrations/0004_auto__add_field_customer_deleted.py
Python
mit
10,979
0.007469
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Customer.deleted' db.add_column(u'django_fastbill_custome...
_length': '50'}), 'subscription_number_events': ('django.db.models.fields.IntegerField', [], {}), 'subscription_trial': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'tags': ('django.db.models.fields.CharField', [], {'max_length': '500'}), 'title': ('dj...
lds.CharField', [], {'max_length': '500'}), 'unit_price': ('django.db.models.fields.FloatField', [], {}), 'vat_percent': ('django.db.models.fields.FloatField', [], {}) }, u'django_fastbill.customer': { 'Meta': {'object_name': 'Customer'}, 'changed_at': ('d...
santisiri/popego
envs/ALPHA-POPEGO/lib/python2.5/site-packages/gdata/test_data.py
Python
bsd-3-clause
87,056
0.001861
#!/usr/bin/python # # Copyright (C) 2006 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
ase/feeds/snippets?start-index=1&amp;max-results=25&amp;bq=digital+camera'> </link> <link rel='next' type='application/atom+xml' href='http://www.google.com/base/feeds/snippets?start-index=26&amp;max-results=25&amp;bq=digital+camera'> </link> <generator version='1.0' uri='http://base.google.com'>GoogleBase ...
alResults>2171885</openSearch:totalResults> <openSearch:startIndex>1</openSearch:startIndex> <openSearch:itemsPerPage>25</openSearch:itemsPerPage> <entry> <id>http://www.google.com/base/feeds/snippets/13246453826751927533</id> <published>2007-02-08T13:23:27.000Z</published> <updated>2007-02-08T16:40:57.000Z</updated> <...
ayoubg/gem5-graphics
Mesa-7.11.2_GPGPU-Sim/src/mapi/glapi/gen/gl_XML.py
Python
bsd-3-clause
24,796
0.038877
#!/usr/bin/env python # (C) Copyright IBM Corporation 2004, 2005 # All Rights Reserved. # # 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 # ...
preprocessor macro `PURE' that wraps GCC's `pure' function attribute. The conditional code can be easilly adapted to other compilers that support a similar feature. The name is also added to the file's undef_list. """ self.undef_list.append("PURE") print """# if defined(__GNUC__) || (defined(__SUNPRO_C...
define PURE __attribute__((pure)) # else # define PURE # endif""" return def printFastcall(self): """Conditionally define `FASTCALL' function attribute. Conditionally defines a preprocessor macro `FASTCALL' that wraps GCC's `fastcall' function attribute. The conditional code can be easilly adapt...
ProjectBabbler/ebird-api
tests/validation/test_clean_provisional.py
Python
mit
483
0
import un
ittest from ebird.api.validation import clean_provisional class CleanProvisionalTests(unittest.TestCase): """Tests for the clean_provisional validation function.""" def test_converts_bool(self): self.assertEqual("true", clean_provisional(True)) self.assertEqual("false", clean_provisional(Fal...
)
inteos/IBAdmin
system/apps.py
Python
agpl-3.0
128
0
from __future__ import unicode_literals from django.apps import Ap
pConfig class SystemConfig(AppConfig): name
= 'system'
rspavel/spack
var/spack/repos/builtin/packages/glm/package.py
Python
lgpl-2.1
666
0.001502
# Copyright 2013-2020 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) from spack import * class Glm(CMakePackage): """OpenGL Mathematics (GLM) is a header only C++ mathematics library fo...
oftware based on the OpenGL Shading Language (GLSL) specification
""" homepage = "https://github.com/g-truc/glm" url = "https://github.com/g-truc/glm/archive/0.9.7.1.tar.gz" version('0.9.7.1', sha256='285a0dc8f762b4e523c8710fbd97accaace0c61f45bc8be2bdb0deed07b0e6f3') depends_on('cmake@2.6:', type='build')
strets123/pyms
Utils/Math.py
Python
gpl-2.0
5,643
0.010987
""" Provides mathematical functions """ ############################################################################# # # # PyMS software for processing of metabolomic mass-spectrometry data # # Copyright (C) 2005-2012 Vladimir Lik...
""" if not is_number(vstart) or not is_number(vstop) or not is_number(vstep): error("parameters start, stop, step must be numbers") v = [] p = vstart while
p < vstop: v.append(p) p = p + vstep return v def MAD(v): """ @summary: median absolute deviation @param v: A list or array @type v: ListType, TupleType, or numpy.core.ndarray @return: median absolute deviation @rtype: FloatType @author: Vladimir Likic """ ...
igudym/twango
twango/template/default/src/conf/h_third_party_apps.py
Python
bsd-3-clause
115
0.026087
try: INSTALLED_APPS except Name
Error: INSTALLED_APPS=() #Generated Config - Don't modify ab
ove this line
phenoxim/nova
nova/api/openstack/compute/views/images.py
Python
apache-2.0
6,081
0.000493
# Copyright 2010-2011 OpenStack Foundation # Copyright 2013 IBM Corp. # 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/license...
used to generate the next link for a pagination query :returns: Image reply data in dictionary format """ image_list = [list_func(request, image)["image"] for image in images] images_links = self._get_collection_links(request, images, coll_name) images...
ges_links"] = images_links return images_dict def _get_links(self, request, identifier, collection_name): """Return a list of links for this image.""" return [{ "rel": "self", "href": self._get_href_link(request, identifier, collection_name), }, { ...
david672orford/pykarta
pykarta/geocoder/massgis.py
Python
gpl-2.0
3,478
0.02674
# pykarta/geocoder/massgis.py # Copyright 2013--2019, Trinity College Computing Center # Last modified: 22 October 2019 from __future__ import print_function import lxml.etree as ET from .geocoder_base import GeocoderBase, GeocoderResult, GeocoderError import pykarta.address # https://wiki.state.ma.us/confluence/page...
").text) lon = float(match.find("{http://tempuri.org/}Long").text) #print(score, lat, lon) if score == "100" and matched_address.startswith("%s %s," % (address[self.f_house_number], abbr_street.upper())): result.coordinates = (lat, lon) result.precision = "INTERPOLATED" e
lse: result.alternative_addresses.append(matched_address) if __name__ == "__main__": gc = GeocoderMassGIS() gc.debug_enabled = True print(gc.FindAddr(["457","Union Street","","West Springfield","MA",""])) #print(gc.FindAddr(["10","Improbable Street","","Westfield","MA","01085"])) #print gc.FindAddr(["32","Par...
kernsuite-debian/lofar
CEP/Calibration/ExpIon/src/__init__.py
Python
gpl-3.0
1,065
0.001878
# -*- coding: iso-8859-1 -*- # __init__.py: Top level .py file for python solution analysis tools. # # Copyright (C) 2010 # ASTRON (
Netherlands Institute for Radio Astronomy) # P.O.Box 2, 7990 AA Dwingeloo, The Netherlands # # This file is part of the LOFAR software suite. # The LOFAR software suite 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. # # The LOFAR software suite is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABI...
jag1g13/lammps
lib/gpu/Install.py
Python
gpl-2.0
5,201
0.013459
#!/usr/bin/env python # Install.py tool to build the GPU library # used to automate the steps described in the README file in this dir from __future__ import print_function import sys,os,subprocess # help message help = """ Syntax from src dir: make lib-gpu args="-m machine -h hdir -a arch -p precision -e esuffix -...
tting") # create Makefile.auto # reset EXTRAMAKE, CUDA_HOME, CUDA_ARCH, CUDA_PRECISION if requested if not os.path.exists("Makefile.%s" % isuffix): error("lib/gpu/Makefile.%s does not exist" % isuffix) lines = open("Makefile.%s" % isuffix,'r').readlines() f
p = open("Makefile.auto",'w') for line in lines: words = line.split() if len(words) != 3: fp.write(line) continue if hflag and words[0] == "CUDA_HOME" and words[1] == '=': line = line.replace(words[2],hdir) if aflag and words[0] == "CUDA_ARCH" and words[1] == '=': line = line.replace(words[2],...
Erotemic/plottool
plottool_ibeis/interact_annotations.py
Python
apache-2.0
52,275
0.001607
""" Interactive tool to draw mask on an image or image-like array. TODO: * need concept of subannotation * need to take options on a right click of an annotation * add support for arbitrary polygons back in . * rename species_list to label_list or category_list * Just use metadata instead of specie...
metadata=None, valid_species=None, manager=None): super(AnnotPoly, poly).__init__(verts, animated=True, fc=fc, ec='none',
alpha=0) poly.manager = manager # Ensure basecoords consistency poly.basecoords = vt.verts_from_bbox(vt.bbox_from_verts(poly.xy)) #poly.basecoords = poly.xy poly.num = num poly.is_orig = is_orig poly.theta = theta poly.metadata = metadata poly...
TedaLIEz/sentry
tests/sentry/api/endpoints/test_project_tagkey_values.py
Python
bsd-3-clause
862
0.00116
from
__future__ import absolute_import from django.core.urlresolvers import reverse from sentry.models import TagKey, TagValue from sentry.testutils import APITestCase class ProjectTagKeyValuesTest(APITestCase): def test_simple(self): project = self.create_project() tagkey = TagKey.objects.create(pr...
cts.create(project=project, key='foo', value='bar') self.login_as(user=self.user) url = reverse('sentry-api-0-project-tagkey-values', kwargs={ 'organization_slug': project.organization.slug, 'project_slug': project.slug, 'key': tagkey.key, }) respon...
CalthorpeAnalytics/urbanfootprint
footprint/main/models/analysis_module/agriculture_module/agriculture_updater_tool.py
Python
gpl-3.0
9,307
0.002579
# UrbanFootprint v1.5 # Copyright (C) 2017 Calthorpe Analytics # # This file is part of UrbanFootprint version 1.5 # # UrbanFootprint is distributed under the terms of the GNU General # Public License version 3, as published by the Free Software Foundation. This # code is distributed WITHOUT ANY WARRANTY, without impl...
feature.labor_force = 0 feature.truck_trips = 0 else: applied_acres = feature.acres_gross * feature.density_pct * feature.dev_pct agriculture_attribute_set = feature.built_form.resolve_built_form(feature.built_form).agriculture_attribute_set ...
eature.built_form_key = feature.built_form.key feature.crop_yield = agriculture_attribute_set.crop_yield * applied_acres feature.market_value = agriculture_attribute_set.unit_price * feature.crop_yield feature.production_cost = agriculture_attribute_set.cost * applied_acr...
dhoffman34/django
django/contrib/auth/models.py
Python
bsd-3-clause
17,902
0.001061
from __future__ import unicode_literals from django.core.exceptions import PermissionDenied from django.core.mail import send_mail from django.core import validators from django.db import models from django.db.models.manager import EmptyManager from django.utils.crypto import get_random_string, salted_hmac from django...
ord, **extra_fields): return self._create_user(username, email, password, True, True, **extra_fields) @python_2_unicode_compatible class AbstractBaseUser(models.Model): password = models.CharField(_('password'), max_length=128) last_login = models.DateTimeField(_('last...
ifying username for this User" return getattr(self, self.USERNAME_FIELD) def __str__(self): return self.get_username() def natural_key(self): return (self.get_username(),) def is_anonymous(self): """ Always returns False. This is a way of comparing User objects to ...
qsheeeeen/Self-Driving-Car
rl_toolbox/policy/shared.py
Python
mit
8,677
0
import torch import torch.nn as nn import torch.nn.functional as F from torch.distributions import Normal from ..net import VAE from ..util.common import batch_to_sequence, sequence_to_batch from ..util.init import orthogonal_init class _CNNBase(nn.Module): def __init__(self): super(_CNNBase, self).__ini...
mean = self.mean_head(memory) std = self.log_std_head.expand_as(mean).exp() self.pd = Normal(mean, std) action = self.pd.sample() if self.training else mean value = self.value_head(memory) return
action, value @property def num_steps(self): return 8 @property def recurrent(self): return True @property def name(self): return 'CNNLSTMPolicy' class MLPPolicy(nn.Module): def __init__(self, input_shape, output_shape): super(MLPPolicy, self).__init__()...
CN-UPB/OpenBarista
utils/decaf-utils-rpc/tests/unittests/InlineCallbacks.py
Python
mpl-2.0
468
0.002137
__author__ = 'thgoette' from BasicTest import BasicTest, wait import un
ittest class InlineCallbacks(BasicTest): @wait def test_inlinecallbacks(self): print "Starting inlineCallback Test " def callback(result): print "Callback: " + str(result) self.assertEqual(result, 50) d = sel
f.caller.call("plus5times10", 0) d.addBoth(callback) return d if __name__ == '__main__': unittest.main()
PapenfussLab/Srtools
bin/fastq_split.py
Python
artistic-2.0
1,113
0.006289
#!/usr/bin/env python """ fastq_split.py [-n|--num_files N_FILES] <input filename> <output directory> """ import os import sys import math from srt.fastq import * from optparse import OptionParser parser = OptionParser() parser.add_option("-n", "--num_files", dest="num_files", help="Number of output files", type...
um_files<=0: print "Number of files must be > 0" sys.exit(-1) num_places = 1+int(math.log10(options.num_files)) # Define output filename format _ = os.path.split(input_filename)[-1] base = os.path.splitext(_)[0] ext = os.path.splitext(_)[1] format = os.path.join(output_directory, "%s_%%0.%ii%s") % (base, num_p...
utput_file = [] for i in xrange(options.num_files): output_filename = format % (i+1) output_file.append(FastqFile(output_filename, "w")) # Split reads i = 0 for h,s,q in FastqFile(input_filename): output_file[i].write(h,s,q) i = (i+1) % options.num_files # Close files for _ in output_file: _.close...
AlexCatarino/pythonnet
tests/test_field.py
Python
mit
8,719
0
# -*- coding: utf-8 -*- """Test CLR field support.""" import System import pytest from Python.Test import FieldTest def test_public_instance_field(): """Test public instance fields.""" ob = FieldTest() assert ob.PublicField == 0 ob.PublicField = 1 assert ob.PublicField == 1 with pytest.rai...
FieldTest.InternalStaticField def test_private_field(): """Test private fields.""" with pytest.raises(AttributeError): _ = FieldTest().PrivateFie
ld with pytest.raises(AttributeError): _ = FieldTest().PrivateStaticField with pytest.raises(AttributeError): _ = FieldTest.PrivateStaticField def test_field_descriptor_get_set(): """Test field descriptor get / set.""" # This test ensures that setting an attribute implemented with ...
libvirt/autotest
scheduler/email_manager.py
Python
gpl-2.0
3,273
0.002139
import traceback, socket, os, time, smtplib, re, sys, getpass, logging try: import autotest.common as common except ImportError: import common from autotest_lib.client.common_lib import global_config CONFIG_SECTION = 'SCHEDULER' CONFIG_SECTION_SMTP = 'SERVER' class EmailNotificationManager(object): def _...
separator = '\n' + '-' * 40 + '\n' body = separator.join(self._emails) self.send_email(self._notify_address, subject, body) self._emails = [] def log_stacktrace(self, reason): logging.exception(reason) message = "EXCEPTION: %s\n%s" % (reason, traceback.format_exc()) ...
ify_email("monitor_db exception", message) manager = EmailNotificationManager()
leonardoRC/PyNFe
pynfe/utils/flags.py
Python
lgpl-3.0
11,560
0.004088
# -*- coding: utf-8 -*- NAMESPACE_NFE = 'http://www.portalfiscal.inf.br/nfe' NAMESPACE_SIG = 'http://www.w3.org/2000/09/xmldsig#' NAMESPACE_SOAP = 'http://www.w3.org/2003/05/soap-envelope' NAMESPACE_XSI = 'http://www.w3.org/2001/XMLSchema-instance' NAMESPACE_XSD = 'http://www.w3.org/2001/XMLSchema' NAMESPACE_METODO = ...
o'), ('71', 'PIS 71 - Operação de Aquisição com Isenção'), ('72', 'PIS 72 - Operação de Aquisição com Suspensão'), ('73', 'PIS 73 - Operação de Aquisição a Alíquota Zero'), ('74', 'PIS 74 - Operação de Aquisição; sem Incidência da Co
ntribuição'), ('75', 'PIS 75 - Operação de Aquisição por Substituição Tributária'), ('98', 'PIS 98 - Outras Operações de Entrada'), ('99', 'PIS 99 - Outras operacoes'), ) PIS_TIPOS_CALCULO = IPI_TIPOS_CALCULO COFINS_TIPOS_TRIBUTACAO = ( ('01', 'COFINS 01 - Operação Tributável - Base de cálculo = valor...
Spoken-tutorial/spoken-website
creation/templatetags/creationdata.py
Python
gpl-3.0
11,230
0.011843
# Standard Library from builtins import str import os import zipfile from urllib.parse import quote_plus from urllib.request import urlopen # Third Party Stuff from django import template from django.conf import settings from django.contrib.auth.models import User from django.db.models import Q # Spoken Tutorial Stuf...
me(key): rec = None try: rec = ContributorLog.objects.filter(tutorial_resource_id = key.id).order_by('-created')[0]
tmpdt = key.updated for tmp in rec: tmpdt = rec.created return tmpdt except: return key.updated def get_component_name(comp): comps = { 1: 'Outline', 2: 'Script', 3: 'Video', 4: 'Slides', 5: 'Codefiles', 6: 'Assignment' } key = '' try: ...
MobileWebApps/backend-python-rest-gae
lib/rest_framework/tests/test_request.py
Python
bsd-3-clause
13,239
0.001057
""" Tests for content parsing, and form-overloaded content parsing. """ from __future__ import unicode_literals from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from django.contrib.sessions.middleware import SessionMiddleware from django.core.handlers.wsgi import W...
TA in
# json request. # """ # data = {'qwerty': 'uiop'} # content = json.dumps(data) # content_type = 'application/json' # parsers = (JSONParser, ) # request = factory.post('/', content, content_type=content_type, # parsers=parsers) # ...
nth2say/simple_django_blog
blog/migrations/0001_initial.py
Python
mit
1,171
0.001708
# -*- coding: utf-8 -*-
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration
): dependencies = [ ] operations = [ migrations.CreateModel( name='Article', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('title', models.CharField(max_length=200)), ...
savioabuga/lipame
lipame/taskapp/celery.py
Python
mit
903
0.005537
import os from celery import Celery from django.apps import apps, AppConfig from django.conf import settings if not settings.configured: # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.local') # pragma: no cover app = Cele...
_name = 'Celery Config' def ready(self): # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings') installed_apps = [app_config.name for app_config in apps.get_app_configs()] app.autodiscove...
a: no cover
googlefonts/gftools
bin/gftools-nametable-from-filename.py
Python
apache-2.0
7,889
0.013056
#!/usr/bin/env python3 # Copyright 2013,2016 The Font Bakery Authors. # Copyright 2017 The Google Font Tools Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache....
name = '%s %s' % (family_name, style_name) if 'Italic' in name: name = re.sub(r'Italic', r'', name) return name def _win_subfamily_name(style_name): name = style_name if 'BoldItalic' == name: retu
rn 'Bold Italic' elif 'Italic' in name: return 'Italic' elif name == 'Bold': return 'Bold' else: return 'Regular' def set_usWeightClass(style_name): name = style_name if name != 'Italic': name = re.sub(r'Italic', r'', style_name) return WEIGHTS[name] def set_macStyle(style_name): ret...
mic4ael/indico
indico/modules/groups/__init__.py
Python
mit
889
0.001125
# This file is part of Indico. # Copyright (C) 2002 - 2020 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. from __future__ import unicode
_literals from flask import session from indico.core import signals from indico.modules.groups.core import GroupProxy from indico.util.i18n import _ from indico.web.flask.util import url_for from indico.web.menu import SideMenuItem __all__ = ('GroupProxy',) @signals.menu.items.connect_via('admin-sidemenu') def _e...
f session.user.is_admin: return SideMenuItem('groups', _("Groups"), url_for('groups.groups'), section='user_management') @signals.users.merged.connect def _merge_users(target, source, **kwargs): target.local_groups |= source.local_groups source.local_groups.clear()
ystk/debian-audit
system-config-audit/src/dialog_base.py
Python
gpl-2.0
5,208
0.000768
# Common dialog code. # # Copyright (C) 2007, 2008 Red Hat, Inc. All rights reserved. # This copyrighted material is made available to anyone wishing to use, modify, # copy, or redistribute it subject to the terms and conditions of the GNU # General Public License v.2. This program is distributed in the hope that it ...
e dialog.''' self.window.destroy()
def _validate_get_failure(self): '''Check whether the window state is a valid configuration. Return None if it is valid. Otherwise, return (message, notebook page index or None, widget). ''' raise NotImplementedError() def _validate_values(self): '''Check whethe...
thyagostall/apollo
src/problem.py
Python
mit
6,320
0.004589
from enum import Enum from collections import namedtuple import settings import os import dbaccess import urllib.request import ast import shutil def move_file(filename, src, dest): src = os.path.join(src, filename) dest = os.path.join(dest, filename) shutil.move(src, dest) def create_file(filename, path...
t_dir)
move_file(problem.output_file, src_dir, dest_dir) dbaccess.update( 'problem_attempt', data={'status_id': problem.status.value}, where={'problem_id': problem.problem_id, 'attempt_no': problem.attempt_no}) def get_data_for_new(self...
gwu-libraries/vivo2notld
vivo2notld/definitions/organization_summary.py
Python
mit
157
0.006369
definition = { "where": "?subj a foaf:Organization .", "fields": { "name": {
"where": "?subj rdfs:label ?
obj ." } } }
tombstone/models
official/vision/detection/modeling/architecture/nn_blocks.py
Python
apache-2.0
11,423
0.002626
# Copyright 2020 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...
ilon self._kernel_regularizer = kernel_regularizer self._bias_regularizer = bias_regularizer if use_sync_bn: self._norm = tf.keras.layers.experimental.SyncBatchNormalization else: self._norm = tf.keras.layers.BatchNormalization if tf.keras.backend.image_data_format() == 'channels_last':...
1 else: self._bn_axis = 1 self._activation_fn = tf_utils.get_activation(activation) def build(self, input_shape): if self._use_projection: self._shortcut = tf.keras.layers.Conv2D( filters=self._filters, kernel_size=1, strides=self._strides, use_bias=Fal...
51reboot/actual_09_homework
07/zhaoyuanhai/cmdb/loganalysis.py
Python
mit
1,002
0.003018
#encoding:utf-8 def get_topn(logfile, topn=10): fhandler = open(logfile, 'r') rt_dict = {} # 统计 while True: line = fhandler.readline() if line == '': break nodes
= line.split() ip, url, code = nodes[0], nodes[6], nodes[8] key = (ip, url, code) if key not in rt_dict: rt_dict[key] = 1 else: rt_dict[key] = rt_dict[key] + 1 fhandler.
close() #print rt_dict # 排序 rt_list = rt_dict.items() # [(key, value), (key, value)] for j in range(0, topn): for i in range(0, len(rt_list) - 1): if rt_list[i][1] > rt_list[i + 1][1]: temp = rt_list[i] rt_list[i] = rt_list[i + 1] ...
Rub4ek/scalors-assignment-backend
reminder/tasks.py
Python
mit
447
0
from django.core.mail import send_mail from greatesttodo.celery import app from reminder.models import Reminder @app.task def send_email_reminder(reminder_id): try: reminder = Reminder.objects.get(id=reminder_id) send_mail(
subject=reminder.text, message=reminder.text, from_email=None, recipient_list=[reminder.email] ) except Reminder.DoesNotExist: pass
gwr/samba
source4/scripting/python/samba/__init__.py
Python
gpl-3.0
11,696
0.002137
#!/usr/bin/env python # Unix SMB/CIFS implementation. # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-2008 # # Based on the original in EJS: # Copyright (C) Andrew Tridgell <tridge@samba.org> 2005 # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General P...
modules_dir: Optional modules directory :param session_info: Optional session information :param credentials: Optional credentials, defaults to anonymous.
:param flags: Optional LDB flags :param options: Additional options (optional) This is different from a regular Ldb file in that the Samba-specific modules-dir is used by default and that credentials and session_info can be passed through (required by some modules). """ ...
yahman72/robotframework
utest/running/test_handlers.py
Python
apache-2.0
12,868
0.001399
import unittest import sys import inspect from robot.running.handlers import _PythonHandler, _JavaHandler, DynamicHandler from robot import utils from robot.utils.asserts import * from robot.running.testlibraries import TestLibrary from robot.running.dynamicmethods import ( GetKeywordArguments, GetKeywordDocumenta...
ring.', doc=True) def test_none_argspec(self): self._assert_spec(None, maxargs=sys.maxint, vararg='varargs', kwarg=False) def test_none_argspec_when_kwargs_supported(self): self._assert_spec(None, maxargs
=sys.maxint, vararg='varargs', kwarg='kwargs') def test_empty_argspec(self): self._assert_spec([]) def test_mandatory_args(self): for argspec in [['arg'], ['arg1', 'arg2', 'arg3']]: self._assert_spec(argspec, len(argspec), len(argspec), argspec) def test_only_default_args(self...
SmartSearch/Edge-Node
LinkedDataManager/feed_generator/ldm_feeder.py
Python
mpl-2.0
8,016
0.013348
## ##SMART FP7 - Search engine for MultimediA enviRonment generated contenT ##Webpage: http://smartfp7.eu ## ## 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/. ##...
m(db,item): db.save(item) if __name__ == '__main__': #inicialization logging.basicConfig(level=logging.DEBUG,format='%(asctime)s-> %(message)s') parser = argparse.ArgumentParser() parser.add_argument("-c", "--conf_file",type=str, help="configuration file path") ...
ser.add_argument("-s", "--section",type=str, help="section of the configuration to apply") args = parser.parse_args() conf_file = args.conf_file if args.conf_file else "ldm_feeder_conf.ini" section = args.section if args.conf_file else "default" while True: #until loop ...
dajohnso/cfme_tests
cfme/tests/infrastructure/test_esx_direct_host.py
Python
gpl-2.0
3,559
0.001686
# -*- coding: utf-8 -*- """ Tests of managing ESX hypervisors directly. If another direct ones will be supported, it should not be difficult to extend the parametrizer. """ import pytest from cfme.infrastructure.provider.virtualcenter import VMwareProvider from cfme.common.provider import DefaultEndpoint from utils i...
ls"], hostname=host["name"
]) # Mock provider data provider_data = {} provider_data.update(args['provider'].data) provider_data["name"] = host["name"] provider_data["hostname"] = host["name"] provider_data["ipaddress"] = ip_address provider_data.pop("host_provisioning", None) provid...
google-research/l2p
augment/color_util.py
Python
apache-2.0
17,401
0.006724
# coding=utf-8 # Copyright 2020 The Learning-to-Prompt Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
image = tf.image.random_brightness(image, max_delta=max_delta) els
e: raise ValueError('Unknown impl {} for random brightness.'.format(impl)) return image def to_grayscale(image, keep_channels=True): image = tf.image.rgb_to_grayscale(image) if keep_channels: image = tf.tile(image, [1, 1, 3]) return image def color_jitter(image, strength, random_order=True, impl='si...
juntatalor/qexx
cart/urls.py
Python
mit
768
0.004049
from django.conf.urls
import patterns, url from cart import views urlpatterns = patterns('', url(r'^$', views.view_cart, name='view'), url(r'^add/$', views.add_to_cart, name='add'), url(r'^remove/$', views.remove_from_cart, name='remove'),
url(r'^update/$', views.update_cart, name='update'), url(r'^checkout/$', views.checkout, name='checkout'), url(r'^update_checkout/$', views.update_checkout, name='update_checkout'), # Для ajax обновления виджета корзины ...
kk6/tssm
app.py
Python
mit
5,552
0.001441
# -*- coding: utf-8 -*- import json import os import urllib.parse from functools import wraps import bottle from bottle import ( route, run, jinja2_template as template, redirect, request, response, static_file, BaseTemplate, ) import tweepy BASE_DIR = os.path.dirname(os.path.abspath(_...
TwitterManager(**self.tweepy_settings) def __call__(self, environ, start_response): environ['twitter'] = self.tweepy_manager return self.app(environ, start_response) ####################################################################################################################### # # Decorat...
############################################################################################### def login_required(f): @wraps(f) def _login_required(*args, **kwargs): twitter = request.environ.get('twitter') if twitter.api is None: return redirect('/') return f(*args, **kwarg...
be-cloud-be/horizon-addons
server-tools/date_range/wizard/date_range_generator.py
Python
agpl-3.0
2,576
0
# -*- coding: utf-8 -*- # © 2016 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from openerp import api, fields, models from dateutil.rrule import (rrule, YEARLY, MONTHLY, WEEKLY, ...
'date_start': date_start, 'date_end': date_end, 'type_id': self.type_id.id, 'company_id': self.company_id.id}) return date_ranges @api.multi def action_apply(self): date_ranges = self._compute_date_ranges() if date_ranges: for...
return self.env['ir.actions.act_window'].for_xml_id( module='date_range', xml_id='date_range_action')
DTOcean/dtocean-core
dtocean_core/interfaces/plots_installation.py
Python
gpl-3.0
18,785
0.000799
# -*- coding: utf-8 -*- # Copyright (C) 2016 Adam Collin, Mathew Topper # Copyright (C) 2017-2018 Mathew Topper # # 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...
se_installation_times", "install_mooring_times": "project.mooring_phase_installation_t
imes", "plan": "project.installation_plan" } return id_map def connect(self): self.fig_handle = installation_gantt_chart( self.data.plan, self.data.install_support_structure_dates, self.dat...
TheRealVestige/VestigeX-Server
Data/scripts/player/objects/objectclick2.py
Python
gpl-3.0
196
0.02551
from s
erver.util import ScriptManager def objectClick2_2213(player, obId, obX, obY): player.getPA().openUpBank() def objectClick2_11758(player, obId, obX, obY):
player.getPA().openUpBank()
opentrials/opentrials-airflow
dags/data_contributions.py
Python
mpl-2.0
718
0
import datetime from airflow.models import DAG from airflow.operators.latest_only_operator import LatestOnlyOperator import utils.helpers as helpers args
= { 'owner': 'airflow', 'depends_on_past':
False, 'start_date': datetime.datetime(2017, 3, 1), 'retries': 1, 'retry_delay': datetime.timedelta(minutes=10), } dag = DAG( dag_id='data_contributions', default_args=args, max_active_runs=1, schedule_interval='@daily' ) latest_only_task = LatestOnlyOperator( task_id='latest_only', ...
LubyRuffy/spiderfoot
modules/sfp_template.py
Python
gpl-2.0
2,631
0.00152
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------- # Name: sfp_XXX # Purpose: Description of the plug-in. # # Author: Name and e-mail address # # Created: Date # Copyright: (c) Name # Licence: GPL # ----------------------------...
# or you risk them persisting between threads. for opt in userOpts.keys(): self.opts[opt] = userOpts[opt] # What events is this module interested in for input # * = be notified about all events. def watchedEvents(self): return ["*"] # What events this mod...
producedEvents(self): return None # Handle events sent to this module def handleEvent(self, event): eventName = event.eventType srcModuleName = event.module eventData = event.data # If you are processing TARGET_WEB_CONTENT from sfp_spider, this is how you ...
overfly83/bjrobot
src/BJRobot/keywords/logging.py
Python
mit
1,462
0.004788
import os import sys from robot.api import logger from keywordgroup import KeywordGroup from robot.libraries.BuiltIn import BuiltIn try: from robot.libraries.BuiltIn import RobotNotRunningError except ImportError: RobotNotRunningError = AttributeError class Logging(KeywordGroup): # Private def _deb...
ge) def _log_list(self, items, what='item'): msg = ['Altogether %d %s%s.' % (len(items), what, ['s',''][len(items)==1])] for index, item in enumerate(items): msg.append('%d: %s' % (index+1, item)) self._info('\n'.join(msg))
return items def _warn(self, message): logger.warn(message)
Kozea/WeasyPrint
weasyprint/layout/replaced.py
Python
bsd-3-clause
11,239
0
"""Layout for images and other replaced elements. See http://dev.w3.org/csswg/css-images-3/#sizing """ from .min_max import handle_min_max_height, handle_min_max_width from .percent import percentage def default_image_sizing(intrinsic_width, intrinsic_height, intrinsic_ratio, specified_wid...
_height = cover_constraint_image_sizing( box.width, box.height, intrinsic_ratio) else: assert object_fit == 'none', object_fit draw_width, draw_height = intrinsic_width, intrinsic_height if object_fit == 'scale-down': draw_width = min(draw_width, intr...
width ref_y = box.height - draw_height position_x = percentage(position_x, ref_x) position_y = percentage(position_y, ref_y) if origin_x == 'right': position_x = ref_x - position_x if origin_y == 'bottom': position_y = ref_y - position_y position_x += box.content_box_x() po...
rmwdeveloper/webhack
webhack/__init__.py
Python
mit
38
0.026316
from __futu
re__ import absolute_im
port
Cawb07/t1-python
terminalone/models/vertical.py
Python
bsd-3-clause
596
0
# -*- coding: utf-8 -*- """Provides vertical object.""
" from __future__ import absolute_import from ..entity import Entity class Vertical(Entity): """docstring for Vertical.""" collection = 'verticals' resource = 'vertical' _relations = { 'advertiser', } _pull = { 'id': int, 'name': None, 'created_on': Entity._st...
self).__init__(session, properties, **kwargs)
johan--/Geotrek
geotrek/tourism/management/commands/sync_rando.py
Python
bsd-2-clause
1,966
0.002543
from django.conf import settings from django.utils import translation from geotrek.tourism import models as tourism_models from geotrek.tourism.views import TouristicContentViewSet, TouristicEventViewSet from geotrek.trekking.management.commands.sync_rando import Command as BaseCommand # Register mapentity models fro...
c_pictograms('**', tourism_models.InformationDeskType) self.sync_pictograms('**', tourism_models.TouristicContentCategory) self.sync_pictograms('**', tourism_models.TouristicContentType) self.sync_pictograms('**', tour
ism_models.TouristicEventType) for lang in settings.MODELTRANSLATION_LANGUAGES: translation.activate(lang) self.sync_tourism(lang)
delftrobotics/keras-retinanet
tests/models/test_densenet.py
Python
apache-2.0
1,587
0.00063
""" Copyright 2018 vidosits (https://github.com/vidosits/) 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 agree...
ANY KIND, either express or implied. See the License for the specific language governing permissions and
limitations under the License. """ import warnings import pytest import numpy as np from tensorflow import keras from keras_retinanet import losses from keras_retinanet.models.densenet import DenseNetBackbone parameters = ['densenet121'] @pytest.mark.parametrize("backbone", parameters) def test_backbone(backbone):...
scheib/chromium
third_party/protobuf/benchmarks/util/result_parser.py
Python
bsd-3-clause
8,710
0.00907
# This import depends on the automake rule protoc_middleman, please make sure # protoc_middleman has been built before run this file. import json import re import os.path # BEGIN OPENSOURCE import sys sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir)) # END OPENSOURCE import tmp.bench...
enchmark results: # # goos: linux # goarch: amd64 # Benchmark/.././datasets
/google_message2/dataset.google_message2.pb/Unmarshal-12 3000 705784 ns/op # Benchmark/.././datasets/google_message2/dataset.google_message2.pb/Marshal-12 2000 634648 ns/op # Benchmark/.././datasets/google_message2/dataset.google_message2.pb/Size-12 5000 2...
reviewboard/reviewboard
reviewboard/accounts/backends/ad.py
Python
mit
18,842
0
"""Active Directory authentication backend.""" import itertools import logging import dns from django.conf import settings from django.contrib.auth.models import User from django.utils.encoding import force_text from django.utils.translation import ugettext_lazy as _ try: import ldap from ldap.dn import dn2s...
This is ``auth_ad_find_dc_from_dns`` in the site configuration. .. setting:: AD_GROUP_NAME ``AD_GROUP_NAME``: The optional name of the group to res
trict available users to. This must be a string. This is ``auth_ad_group_name`` in the site configuration. .. setting:: AD_OU_NAME ``AD_OU_NAME``: The optional name of the Organizational Unit to restrict available users to. This must be a string. This is ``auth_ad_ou_na...
kshedstrom/pyroms
bathy_smoother/external/lp_solve_5.5/extra/Python/pyhelp.py
Python
bsd-3-clause
381
0.023622
import os im
port sys setupfile = file("setup.py",'r') input = sys.argv[1] lines = setupfile.readlines() output = file("setup.py", 'w') for line in lines: if line.startswith(" library_dirs"): newline = " library_dirs=['"+str(input)+"'],\n" output.
write(newline) else: output.write(line) setupfile.close() output.close()
xguse/outspline
src/outspline/conf/plugins/wxtrayicon.py
Python
gpl-3.0
1,043
0
# Outspline - A highly modular and extensible outliner. # Copyright (C) 2011-2014 Dario Giovannetti <dev@dariogiovannetti.net> # # This file is part of Outspline. # # Outspline 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 Softw...
ven the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULA
R PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Outspline. If not, see <http://www.gnu.org/licenses/>. from collections import OrderedDict as OD data = ( OD(( ("enabled", "on"), )), OD(( ...
TomBaxter/osf.io
api_tests/nodes/views/test_node_preprints.py
Python
apache-2.0
6,285
0.003819
import pytest from addons.osfstorage.models import OsfStorageFile from api.base.settings.defaults import API_BASE from api_tests import utils as test_utils from api_tests.preprints.filters.test_filters import PreprintsListFilteringMixin from api_tests.preprints.views.test_preprint_list_mixin import PreprintIsPublished...
ider_filter_equals_returns_one(self, app, user, provider_two, preprint_two, provider_url): expected = [preprint_two._id] res = app.get('{}{}'.format(provider_url, provider_two._id), auth=user.auth) actual = [preprint['id'] for preprint in res.json['data']] assert expected == actual clas...
ser_admin_contrib(self): return AuthUserFactory() @pytest.fixture() def provider_one(self): return PreprintProviderFactory() @pytest.fixture() def provider_two(self): return PreprintProviderFactory() @pytest.fixture() def project_published(self, user_admin_contrib): ...
WGDEVS/RouterSim
RouterSim.py
Python
gpl-2.0
10,354
0.016226
''' Router Sim v1.0 Program description: This program simulates a network consisting of routers. It will be displayed in a command line interface and feature controls to build and maintain the network by modifying routers, save/load the network to external files, display information about the routers in the network ...
def showRouters(): print("Showing all routers in the network:") for i in Main: print("Router " + str(i[0]) + " has " + str(len(i[1])) + " link(s) to other routers") ''' Description: Prints all the routers that are directly linked to a router Parameters: Router1: The specified router's number ''' de...
ain,Router1) if (not ln[1]): print ("Router does not exist!") return print("Showing neighbour(s) for router "+str(Router1)+":") for i in Main[ln[0]][1]: print("Other router is " + str(i[0]) + " with a delay of " + str(i[1]) + ".") ''' Description: Takes two routers, creates them if...
p2pu/learning-circles
studygroups/migrations/0084_auto_20180215_0747.py
Python
mit
366
0
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2018-02-15 07:47 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('studygroups', '0083_auto_20180209_1210'), ] operations = [ migrations.RenameModel(
old_name='Facilitator', new_name='Profile', ), ]
GeorgiaTechDHLab/TOME
topics/migrations/0002_auto_20170308_2245.py
Python
bsd-3-clause
537
0
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-08 22:45 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('topics', '0001_initial'), ] operations = [
migrations.AlterModelOptions( name='articletopicrank', options={'ordering': ('rank',)}, ), migrations.AlterModelOptions( name='wordtopicrank', options={'orderin
g': ('rank',)}, ), ]
ArcasProject/Arcas
tests/test_springer.py
Python
mit
3,670
0.007084
import arcas import pandas def test_setup(): api = arcas.Springer() assert api.standard == 'http://api.springer.com/metadata/pam?q=' def test_keys(): api = arcas.Springer() assert api.keys() == ['url', 'key', 'unique_key', 'title', 'author', 'abstract', 'doi', 'date', 'journa...
= ['subject:game theory'] url = api.create_url_search(parameters) assert url == 'http://api.springer.com/metadata/pam?q=subject:game theory&api_key=Your key here' def test_parameters_and_url_journal(): api = arcas.Springer() para
meters = api.parameters_fix(journal='Springer') assert parameters == ['pub:Springer'] url = api.create_url_search(parameters) assert url == 'http://api.springer.com/metadata/pam?q=pub:Springer&api_key=Your key here' def test_parameters_and_url_record(): api = arcas.Springer() parameters = api.para...
jreback/pandas
pandas/tests/series/methods/test_shift.py
Python
bsd-3-clause
13,266
0.00098
import numpy as np import pytest from pandas.errors import NullFrequencyError import pandas as pd from pandas import ( DatetimeIndex, Index, NaT, Series, TimedeltaIndex, date_range, offsets, ) import pandas._testing as tm from pandas.tseries.offsets import BDay class TestShift: @pyt...
hift(1) unshifted = shifted.shift(-1) tm.assert_index_equal(shifted.index, ps.index) tm.assert_index_equal(unshifted.index,
ps.index) tm.assert_numpy_array_equal(unshifted.dropna().values, ps.values[:-1]) shifted2 = ps.shift(1, "B") shifted3 = ps.shift(1, BDay()) tm.assert_series_equal(shifted2, shifted3) tm.assert_series_equal(ps, shifted2.shift(-1, "B")) msg = "Given freq D does not match ...
diffeo/rejester
rejester/_redis.py
Python
mit
2,666
0.0015
"""Common base class for Redis-based distributed worker systems. This software is released under an MIT/X11 open source license. Copyright 2012-2014 Diffeo, Inc. """ from __future__ import absolute_import import logging import socket import redis from rejester.exceptions import ProgrammerError logger = logging.g...
ocation namespace name (should be unique per run) """ super(RedisBase, self).__init__() self.config = config if 'registry_addresses' not in config: raise ProgrammerError('registry_addresses not
set') redis_address, redis_port = config['registry_addresses'][0].split(':') redis_port = int(redis_port) self._local_ip = self._ipaddress(redis_address, redis_port) if 'app_name' not in config: raise ProgrammerError('app_name must be specified to configure Registry') ...
zaibacu/zTemplate
lib/zTemplate.py
Python
mit
2,885
0.038475
import platform from copy import * from ctypes import * class Param(Structure): #Forward declaration pass class Value(Structure): pass class StringValue(Structure): pass class BoolValue(Structure): pass class NumberValue(Structure): pass class ListValue(Structure): pass PARAM_P = POINTER(Param) VALUE_P = P...
->%s" % (key, name)).encode("UTF-8") v = self.handle_type(member) p.value = VALUE_P(v) cursor.next = PARAM_P(p) cur
sor = p else: p = Param() p.key = key.encode("UTF-8") v = self.handle_type(value) p.value = VALUE_P(v) cursor.next = PARAM_P(p) cursor = p return root
MrTrustworthy/traveler
tests/test_poller.py
Python
mit
340
0.002941
import un
ittest import traveler class MainTest(unittest.TestCase): def test_base(self): self.assertTrue(True) def setUp(self): self.poller = traveler.Poller() def test_poller(self)
: j = self.poller.load() self.assertTrue(isinstance(j, str)) if __name__ == '__main__': unittest.main()
kaday/rose
lib/python/rose/macros/trigger.py
Python
gpl-3.0
24,332
0
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # (C) British Crown Copyright 2012-6 Met Office. # # This file is part of Rose, a framework for meteorological suites. # # Rose is free software: you can redistribute it and/or modify # it under the terms of the GNU ...
E_CHECKS = 10000 def _setup_triggers(self, meta_config): self.trigger_family_lookup = {} self._id_is_duplicate = {} # Speedup dictionary. self
.enabled_dict = {} self.evaluator = rose.macros.rule.RuleEvaluator() self.rec_rule = rose.macros.rule.REC_EXPR_IS_THIS_RULE for setting_id, sect_node in meta_config.value.items(): if sect_node.is_ignored(): continue opt_node = sect_node.get([rose.META_PROP...
waxe/waxe-image
waxe_image/scripts/get_ng_build.py
Python
mit
1,483
0
import io import os import requests import shutil import sys import zipfile from waxe_image import __version__ API_RELEASES_URL = 'https://api.github.com/repos/waxe/waxe-image/releases' NG_BUILD_FOLDER = 'website' def main(argv=sys.argv): if len(argv) > 2: print('Too many arguments') sys.exit(1...
nd for the current version %s' % __version__) ng_asset = None for asset in releas
e['assets']: if 'waxe-image-ng.zip' in asset['browser_download_url']: ng_asset = asset break assert(ng_asset) url = ng_asset['browser_download_url'] r = requests.get(url, stream=True) if r.status_code != 200: raise ValueError('Bad status code %s' % r.status_code...
relekang/python-semantic-release
tests/mocks/mock_gitlab.py
Python
mit
4,092
0.000489
import gitlab from .. import mock, wrapped_config_get gitlab.Gitlab("") # instantiation necessary to discover gitlab ProjectManager class _GitlabProject: def __init__(self, status): self.commits = {"my_ref": self._Commit(status)} self.tags = self._Tags() self.releases = self._Releases()...
{"name": "bad_job", "status": "failed", "allow_failure": False
}, ] elif status == "allow_failure": self.jobs = [ { "name": "notsobad_job", "status": "failed", "allow_failure": True, }, ...
chaosim/dao
dao/base.py
Python
gpl-3.0
113
0.035398
# -*- coding: utf-8 -*- def classeq(x, y): return x.__class__=
=y.__class__ class
Element(object): pass
avtomato/HackerRank
Python/_03_Strings/_09_Designer_Door_Mat/solution.py
Python
mit
333
0.006006
N, M = map(int,input().split()) # More than 6 lines of code will result in 0 score. Bla
nk lines are not counted. for i in range(1, N, 2): print(('.|.' * i).center(M, '-')) # Enter Code Here print('WELCOME'.center(M, '-')) # Enter Code Here for i in range(N-2, -1, -2):
print(('.|.' * i).center(M, '-')) # Enter Code Here
redsolution/redsolution-cms
redsolutioncms/templatetags/redsolutioncms_tags.py
Python
gpl-3.0
1,289
0.006206
from django import template from django.template import TOKEN_VAR, TOKEN_BLOCK, TOKEN_COMMENT, TOKEN_TEXT, \ BLOCK_TAG_START, VARIABLE_TAG_START, VARIABLE_TAG_END, BLOCK_TAG_END register = template.Library() class RawNode(template.Node): def __init__(self, data): self.data = data def render(self,...
eturn self.data @register.tag def raw(parser, token): """ Render as just text everything between ``{% raw %}`` and ``{% endraw %}``. """ E
NDRAW = 'endraw' data = u'' while parser.tokens: token = parser.next_token() if token.token_type == TOKEN_BLOCK and token.contents == ENDRAW: return RawNode(data) if token.token_type == TOKEN_VAR: data += '%s %s %s' % (VARIABLE_TAG_START, token.contents, VARIABLE_...
itucsdb1509/itucsdb1509
clubs.py
Python
gpl-3.0
8,354
0.003953
import datetime import os import json import re import psycopg2 as dbapi2 from flask import Flask from flask import redirect from flask import request from flask import render_template from flask.helpers import url_for from store import Store from fixture import * from sponsors import * from curlers import * from cl...
cursor): cursor.execute(""" INSERT INTO CLUBS (NAME, PL
ACES, YEAR, CHAIR, NUMBER_OF_MEMBERS, REWARDNUMBER) VALUES ( 'Orlando Curling Club', 1, 2014, 'Bryan Pittard', '7865', '0'); INSERT INTO CLUBS (NAME, PLACES, YEAR, CHAIR, NUMBER_OF_MEMBERS, REWARDNUMBER) VALUES ( 'Wausau Curling Club', 1...
google/trax
trax/shapes_test.py
Python
apache-2.0
2,632
0.00304
# coding=utf-8 # Copyright 2022 The Trax Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
rt shapes from trax.shapes import ShapeDtype
class ShapesTest(absltest.TestCase): def test_constructor_and_read_properties(self): sd = ShapeDtype((2, 3), np.int32) self.assertEqual(sd.shape, (2, 3)) self.assertEqual(sd.dtype, np.int32) def test_default_dtype_is_float32(self): sd = ShapeDtype((2, 3)) self.assertEqual(sd.shape, (2, 3)) ...
okuta/chainer
chainer/testing/parameterized.py
Python
mit
4,970
0.000201
import functools import itertools import types import unittest import six from chainer.testing import _bundle from chainer import utils def _param_to_str(obj): if isinstance(obj, type): return obj.__name__ return repr(obj) def _shorten(s, maxlen): # Shortens the string down to maxlen, by repla...
_generator(base, params): # Defines the logic to generate parameterized test case classes. for i, param in enumerate(params): cls_name = _make_class_name(base.__name__, i, par
am) def __str__(self): name = base.__str__(self) return '%s parameter: %s' % (name, param) mb = {'__str__': __str__} for k, v in six.iteritems(param): if isinstance(v, types.FunctionType): def create_new_v(): f = v ...