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
ilastik/ilastik-0.5
ilastik/modules/classification/gui/batchProcessDlg.py
Python
bsd-2-clause
6,255
0.009752
# -*- coding: utf-8 -*- """ Created on Mon Mar 22 09:33:57 2010 @author: - """ import os import warnings with warnings.catch_warnings(): warnings.simplefilter("ignore") from PyQt4 import QtCore, QtGui from ilastik.modules.classification.core.batchProcess import BatchOptions, BatchProcessCore from ilastik.gui.i...
.image = None def removeSelectedEntry(self):
itemIndex = self.filesView.currentRow() if itemIndex >= 0: dummy = self.filesView.takeItem(itemIndex) del dummy del self.filenames[itemIndex] for a in self.filenames: print a def slotDir(self): selection = QtGui.QFile...
RemiZOffAlex/specialistoff.net
Python/crm/crmapp/lib/info.py
Python
mit
868
0.003606
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- __author__ = 'RemiZOffAlex' __copyright__ = '(c) RemiZOffAlex' __license__ = 'MIT' __email__ = 'remizoffalex@mail.ru' __url__ = 'http://remizoffalex.ru' from flask import session, request from .. import app, models def get_user(): """ Получить текущ
его пользователя """ result = None if 'user_id' in session: result = models.db_session.query( models.User ).filter( models.
User.id==session['user_id'] ).first() app.logger.info(result.name) return result def get_ip(): """ Получить IP """ result = '' if request.headers.getlist("X-Forwarded-For"): result = request.headers.get("X-Forwarded-For").split(",")[0] else: result = request....
kashefy/caffe_sandbox
nideep/iow/test_lmdb_utils.py
Python
bsd-2-clause
1,119
0.002681
''' Created on Jan 06, 2016 @author: kashefy ''' from nose.tools import assert_greater, assert_equal, assert_is_instance, assert_true import nideep.iow.lmdb_utils as lu class TestLMDBConsts: def test_map_sz(self): assert_greater(lu.MAP_SZ, 0) assert_is_instance(lu.MAP_SZ, int) def test_num_...
ce(lu.NUM_IDX_DIGITS, int) class TestIdxFormat: def test_idx_format(self): assert_greater(len(lu.IDX_FMT), 0) assert_is_instance(lu.IDX_FMT, str) assert_true(lu.IDX_FMT.startswith('{')) assert_true(lu.IDX_FMT.endswith('}')) def test_idx_format_zero(self): assert_equa...
t_idx_format_nonzero(self): assert_greater(lu.NUM_IDX_DIGITS, 1) s = ''.join(['0'] * lu.NUM_IDX_DIGITS) for i in xrange(10): assert_equal(lu.IDX_FMT.format(i), s[:-1] + '%d' % i) for i in xrange(10, 100): assert_equal(lu.IDX_FMT.format(i), s[:-2] + '%d' % i)
karelklic/flashfit
font.py
Python
gpl-3.0
814
0.006143
from PyQt4 import QtCore, QtGui class Font(QtGui.QFont): def __init__(self, font = None, pointSize = 0): QtGui.QFont.__init__(self) if font: self.fromString(font.toString()) if pointSize > 0: self.setPointSize(pointSize)
def toUserString(self): res = self.family() + ", " if self.pixelSize() >= 0:
res += str(self.pixelSize()) + " px" else: res += str(self.pointSize()) + " pt" return res def toStorableString(self): return "{0},{1}".format(self.family(), self.pointSize()) def fromStorableString(self, string): elems = string.split(",") if le...
simonhampe/pylab
gameData/GameState.py
Python
gpl-3.0
2,339
0.002993
from gameData import Player, LabyrinthConstants from tools import GridTools from tools.MatrixTools import * class GameState: def __init__(self, generator, settings): self.labyrinth = generator.generate_labyrinth() self.settings = settings (x, y) = self.labyrinth.get_start() self.pl...
stener) def remove_update_listener(self, listener): while listener in self.update_listeners: self.update_listeners.remove(listener) def notify_player_moved(self): f
or l in self.update_listeners: l.player_moved(self)
sfaci/fighter2d
fighter2d/ShooterEnemy.py
Python
gpl-2.0
687
0.030568
## BigEnemy ## Clase que implementa un tipo de
enemigo mas grande y resistente ## ## Author: Santiago Faci ## Version: 2.0 from direct.showbase.DirectObject import DirectObject import random from Enemy import Enemy VELOCIDAD = -2 VELOCIDAD_MISIL = 10 Y = 55 FRECUENCIA_DISPARO = 0.2 PUNTOS = 200 VIDA = 4 clas
s ShooterEnemy(Enemy): def __init__(self, x0, z0, modelo): # Invoca al constructor de la clase base Enemy.__init__(self, x0, z0, modelo) # Inicializa algunos atributos con valores diferentes self.ship.setScale(4, 1, 3) self.ia = False self.vida = VIDA self.puntos = PUNTOS self.velocidad = VELOCIDAD...
apple/swift
utils/gyb_syntax_support/StmtNodes.py
Python
apache-2.0
14,850
0.000135
from .Child import Child from .Node import Node # noqa: I201 STMT_NODES = [ # continue-stmt -> 'continue' label? ';'? Node('ContinueStmt', kind='Stmt', children=[ Child('ContinueKeyword', kind='ContinueToken'), Child('Label', kind='IdentifierToken', is_opt...
stmt -> label? ':'? 'while' condition-list code-block ';'? Node('WhileStmt', kind='Stmt', traits=['WithCodeBlock', 'Labeled'], children=[ Child('LabelName', kind='IdentifierToken', is_optional=True), Child('LabelColon', kind='ColonToken', ...
collection_element_name='Condition'), Child('Body', kind='CodeBlock'), ]), # defer-stmt -> 'defer' code-block ';'? Node('DeferStmt', kind='Stmt', traits=['WithCodeBlock'], children=[ Child('DeferKeyword', kind='DeferToken'), Child('Body', k...
ninuxorg/netengine
docs/source/conf.py
Python
mit
8,226
0.006321
# -*- coding: utf-8 -*- # # netengine documentation build configuration file, created by # sphinx-quickstart on Fri Aug 8 15:35:40 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # #...
# The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of th...
file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "def...
shaform/ptt-beauty
ptt_beauty/utils.py
Python
bsd-3-clause
577
0
import json import os from b2.upload_source impor
t UploadSourceBytes from scrapy.utils.project import get_project_settings def get_shub_project_settings(): settings = get_project_settings() shub_settings = json.loads(os.environ.get('SHUB_SETTINGS', '{}')) settings.setdict( shub_settings.get('project_settings', {}), priority='project') ...
e, content): source = UploadSourceBytes(content) bucket.upload(source, file_name)
Azure/azure-sdk-for-python
sdk/compute/azure-mgmt-compute/azure/mgmt/compute/v2019_07_01/operations/_virtual_machine_scale_sets_operations.py
Python
mit
124,616
0.004903
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
params=query_parameters, headers=header_parameters, json=json, content=content, **kwargs ) def build_updat
e_request_initial( resource_group_name: str, vm_scale_set_name: str, subscription_id: str, *, json: JSONType = None, content: Any = None, **kwargs: Any ) -> HttpRequest: content_type = kwargs.pop('content_type', None) # type: Optional[str] api_version = "2019-07-01" accept = "a...
slamice/aboutrape
aboutrape/urls.py
Python
mit
374
0.02139
from django.conf.urls import p
atterns, include, url from aboutrape.views import about, base, category from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', base), url(r'^/$', base), url(r'^about/$', about), url(r'^admin/', include(admin.site.urls)), url(r'^category/(?P<category_id>\d+)/$', categ...
y'), )
1a1a11a/mimircache
PyMimircache/cache/abstractCache.py
Python
gpl-3.0
3,025
0.001653
# coding=utf-8 """ An abstract cache for cache replacement algorithms Author: Jason Yang <peter.waynechina@gmail.com> 2016/05 """ import abc class Cache: __metaclass__ = abc.ABCMeta all = ["access", "get", "access", "evict", "_update", "_insert"] ...
m or not :param **kwargs: :param req_item: the element in the reference, it can be in the cache, or not :return: -1 if not in cache, otherwise old rank (if there is) or 1 """ raise NotImplementedError("access is not implemented") @abc.abstractmethod def _update(self, req...
be updated cache replacement algorithm related metadata real request data (not used in current version) :param **kwargs: :param req_item: :return: True on success, False on failure """ raise NotImplementedError("_update is not implemented") @abc.abstractmeth...
Unit03/aio_web_sandbox
foo/views.py
Python
mit
295
0
from aiohttp import web import json from foo import storage async def index(request): bars = await storage.get_some_bar() bars = { "id": bars[0], "nam
e": bars[1], "crea
ted_at": bars[2].isoformat(), } return web.Response(body=json.dumps(bars).encode())
freyes/juju
scripts/leadershipclaimer/count-leadership.py
Python
agpl-3.0
2,748
0.008734
#!/usr/bin/env python3 # Copyright 2019 Canonical Ltd. # Licensed under the AGPLv3, see LICENCE file for details. import argparse import re import sys def main(args): p = argparse.ArgumentParser(description="parse claim l
og files, reporting output") p.add_argument("file", type=argparse.FileType('r'), default=sys.stdin, nargs="?", help="the name of the file to parse") p.add_argument("--tick", type=float, default=1.0, help="seconds between printing status ticks") opts = p.parse_args(args) actionsRE...
+(?P<action>claimed|extended|lost|connected).*in (?P<duration>[0-9m.]+s)") # We don't have minutes if we have 'ms', so match 'ms' first, we might have 'm' if we have 's', so put it before s. durationRE = re.compile("((?P<milliseconds>\d+)ms)?((?P<minutes>\d+)m)?((?P<seconds>\d+(\.\d+)?)s)?") totalClaims = 0...
oconnor663/peru
peru/plugin.py
Python
mit
12,866
0
import asyncio from collections import namedtuple import contextlib import os import subprocess import tempfile import yaml from .async_helpers import create_subprocess_with_handle from . import cache from . import compat from .compat import makedirs from .error import PrintableError DEFAULT_PARALLEL_FETCH_LIMIT = 1...
raise PluginPermissionsError( "Module type '{0}' does not support {1}.", definition.type, command) if not os.path.exists(exe): raise PluginPermissionsError('Plugin exe is missing: ' + exe) if not os.access(exe, os.X_OK): raise PluginPermissionsError('Plugin ex...
e_fields(module_fields): return {'PERU_MODULE_{}'.format(name.upper()): value for name, value in module_fields.items()} def _validate_plugin_definition(definition, module_fields): field_names_not_strings = [name for name in definition.fields if not isinstance(name, s...
klaus385/openpilot
panda/tests/disable_esp.py
Python
mit
76
0.013158
#!/usr/bin/env python from panda import Panda Panda()
.set_esp_
power(False)
agustinhenze/doit.debian
doc/tutorial/getargs_dict.py
Python
mit
301
0.0299
def ta
sk_compute(): def comp(): return {'x':5,'y':10, 'z': 20} return {'actions': [(comp
,)]} def show_getargs(values): print(values) def task_args_dict(): return {'actions': [show_getargs], 'getargs': {'values': ('compute', None)}, 'verbosity': 2, }
Orpheus11/nile
nile/common/reflection.py
Python
apache-2.0
7,670
0
# -*- coding: utf-8 -*- # Copyright (C) 2012-2013 Yahoo! Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICE...
YPE = type # See: https://docs.python.org/2/library/__builtin__.html#module-__builtin__ # and see https://docs.python.org/2/reference/executionmodel.html (and likely # others)... _BUILTIN_MODULES = ('builtins', '__builtin__', '__builtins__', 'exceptions') if six.PY3:
Parameter = inspect.Parameter Signature = inspect.Signature get_signature = inspect.signature else: # Provide an equivalent but use funcsigs instead... import funcsigs Parameter = funcsigs.Parameter Signature = funcsigs.Signature get_signature = funcsigs.signature def get_members(obj, e...
victorywang80/Maintenance
saltstack/src/salt/returners/__init__.py
Python
apache-2.0
52
0
# -*- codi
ng: utf-8 -*- ''' Returners Directory '''
alexhersh/libcalico
calico_containers/pycalico/ipam.py
Python
apache-2.0
36,358
0.000083
# Copyright 2015 Metaswitch Networks # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in w...
or 6. :param pool: IPPool to get blocks from, or None to use all pools :return: An iterator of block CIDRs. """ # Get the pools
and verify we got a valid one, or n
dogancankilment/Django-obs
yonetim/forms.py
Python
gpl-2.0
1,672
0.035885
from django import forms from django.forms import ModelForm from models import * from django.forms import Textarea from django.contrib.auth.hashers import make_password from django.contrib.auth.models import Group class OgretimElemaniFormu(ModelForm): parolasi=forms.CharField(label="Parolasi", help_text='Paro...
lasi','email','telefonu') def save(self,commit=True): instance = super(OgretimElemaniFormu,self).save(commit=False) if self.cleaned_data.get('parolasi'): instance.password=make_password(self.cleaned_data['parolasi']) if commit: instance.save() if instance.group.filter(name='ogretimelemanlari'):...
ers widgets = { 'tanimi':Textarea(attrs={'cols':35, 'rows':5}), } #class OgretimElemaniAltFormu(ModelForm): # class Meta: # model = OgretimElemani # fields = ('username','parolasi','email') #exclude=('unvani','telefonu') bu da ayni gorevi gorur # fields kullanarak hangi sirada gozukmesini i...
uclouvain/OSIS-Louvain
base/migrations/0208_create_role_executive.py
Python
agpl-3.0
951
0.001052
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-11-22 07:11 fro
m __future__ import unicode_literals from django.core.management.sql import emit_post_migrate_signal from django.db import migrations def add_executive_group(apps, schema_editor): # create group db_alias = schema_editor.connection.alias emit_post_migrate_signal(1, False, db_alias) Group = apps.get_mo...
or_create(name='executive') if created: # Learning unit can_access_learningunit = Permission.objects.get(codename='can_access_learningunit') executive_group.permissions.add(can_access_learningunit) class Migration(migrations.Migration): dependencies = [ ('base', '0207_auto_2017...
mweb/flask-starter
app/models/__init__.py
Python
bsd-2-clause
1,410
0
# # Copyright (C) 2014 Mathias Weber <mathew.weber@gmail.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # thi...
UTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE PO...
danakj/chromium
tools/vim/chromium.ycm_extra_conf.py
Python
bsd-3-clause
12,768
0.007832
# 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. # Autocompletion config for YouCompleteMe in Chromium. # # USAGE: # # 1. Install YCM [https://github.com/Valloric/YouCompleteMe] # (Googlers s...
o |filename|. Compile flags used to build the default source file is assumed to be a close-enough approximation for building |filename|. Args: chrome_root: (String) Absolute path to the root of Chromium checkout. filename: (String) Absolute path to the source file. Returns: (String) Absolute path...
return os.path.join(blink_root, 'Source', 'core', 'Init.cpp') else: if 'test.' in filename: return os.path.join(chrome_root, 'base', 'logging_unittest.cc') return os.path.join(chrome_root, 'base', 'logging.cc') def GetBuildableSourceFile(chrome_root, filename): """Returns a buildable source fil...
intel-analytics/analytics-zoo
pyzoo/test/zoo/chronos/data/utils/test_roll.py
Python
apache-2.0
3,826
0.000261
# # Copyright 2018 Analytics Zoo Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to...
icense for the specific language governing permissions and # limitations under the License. # import pytest import pandas as pd
import numpy as np import random from test.zoo.pipeline.utils.test_utils import ZooTestCase from zoo.chronos.data.utils.roll import roll_timeseries_dataframe class TestRollTimeSeries(ZooTestCase): def setup_method(self, method): self.easy_data = pd.DataFrame({"A": np.random.randn(10), ...
mvo5/snapcraft
snapcraft/internal/indicators.py
Python
gpl-3.0
3,981
0.000754
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright (C) 2016-2017 Canonical Ltd # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by
the Free Software Foundation. # # 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 Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import os import sys from urllib.request import urlretrieve from progressbar import AnimatedMarker, Bar, Percentage, Pro...
Qalthos/remysmoke
remysmoke/tests/models/test_auth.py
Python
agpl-3.0
1,498
0.010013
# -*- coding: utf-8 -*- """Test suite for the TG app's models""" from nose.tools import eq_ from remysmoke import model from remysmoke.tests.models import
ModelTest class TestGroup(ModelTest): """Unit test case for the ``Group`` model.""" klass = model.Group attrs = dict( group_name = u"test_group", display_name = u"Test Group" ) class TestUser(ModelTest): """Unit test case for the ``User`` model.""" klass = model.User ...
me(self): """The obj constructor must set the user name right""" eq_(self.obj.user_name, u"ignucius") def test_obj_creation_email(self): """The obj constructor must set the email right""" eq_(self.obj.email_address, u"ignucius@example.org") def test_no_permissions_by_default(se...
uclmr/inferbeddings
tests/inferbeddings/model/training/test_objectives.py
Python
mit
658
0.00304
# -*- coding: utf-8 -*- import pytest import numpy as np import t
ensorflow as tf from inferbeddings.models.training import pairwise_losses def test_additive_walk_embedding(): pos_scores = tf.Variable(np.array([.9]), name='pos_scores') neg_scores = tf.Variable(np.array([.1]), name='neg_scores') init_op = tf.global_variables_initializer() with tf.Session() as sessi...
np.testing.assert_almost_equal(100 - .9 + .1, res) tf.reset_default_graph() if __name__ == '__main__': pytest.main([__file__])
sidzan/netforce
netforce_stock/netforce_stock/migrations/stock_journal.py
Python
mit
1,123
0.016028
from netforce.model import get_model from netforce import migration from netforce.database import get_connection class Migration(migration.Migration): _name="stock.stock_journal" _version="1.115.0" def migrate(self): res=get_model("stock.journal").search([]) if res: print("Stoc...
"in", } in_id=get_model("stock.journal").create(vals) vals={ "name": "Goods Transfers", "type": "internal", } internal_id=get_model("stock.journal").create(vals) vals={ "name": "Goods Issues",
"type": "out", } out_id=get_model("stock.journal").create(vals) db=get_connection() db.execute("UPDATE stock_picking SET journal_id=%s WHERE type='in'",in_id) db.execute("UPDATE stock_picking SET journal_id=%s WHERE type='internal'",internal_id) db.execute("UPDATE stoc...
mpurzynski/MozDef
loginput/index.py
Python
mpl-2.0
6,727
0.014568
# 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 https://mozilla.org/MPL/2.0/. # Copyright (c) 2017 Mozilla Corporation import os from bottle import route, run, response, request, default_app from b...
bottlelog('request:{0}\n'.format(bulkpost)) request.body.close() try: # Handles json array bulk format [{},{},...] mess
ages = json.loads(bulkpost) for event in messages: # don't post the items telling us where to post things.. if 'index' not in event: ensurePublish=mqConn.ensure(mqproducer,mqproducer.publish,max_retries=10) ensurePublish(event,exchange=...
danallan/octal-application
server/apps/ki/views.py
Python
gpl-3.0
1,125
0.004444
import json from django.http import HttpResponse from django.contrib.auth.models import User from django.shortcuts import get_object_or_404 from apps.exercises.models import Attempts from apps.maps.models import Graphs from apps.ki.utils import performInference from apps.research.u
tils import getParticipantByUID, studyFilter def knowledge_inference(request, gid=""): if request.method == "GET": g = get_object_or_404(Graphs, pk=gid) if not request.user.is_authenticated(): return HttpResponse(status=403) u, uc = User.objects.get_or_create(pk=request.user.pk)
p = getParticipantByUID(request.user.pk, gid) if g.study_active and p is None: return HttpResponse(status=401) ex = Attempts.objects.filter(graph=g).filter(submitted=True) ex = studyFilter(g, p, u, ex) inferences = [] if ex.count() > 1: r = [e.get_correctness() fo...
percyfal/luigi
test/task_test.py
Python
apache-2.0
3,356
0.001192
# -*- coding: utf
-8 -*- # # Copyright 2012-2015 Spotify AB # # 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 ...
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import doctest from helpers import unittest from datetime import datetime, timedelta import luigi import luigi.task from luigi.task_registe...
irushchyshyn/portingdb
scripts/get-history.py
Python
mit
5,840
0.000685
#! /usr/bin/env python3 """Get historical status data as a CSV file Walks the Git history of the repo, loading each revision where data/ changed, and recording the number of packages for each status. When an existing data file is specified with --update, the file is repeated, with commits that aren't in it appended. ...
blocked", "py3-only", "dropped", "idle", "in-progress", "released", "legacy-leaf", "mispackaged"] columns = [tables.Package.status, func.count()] query = select(columns).select_from(tables.Package.__table__) query = query.group_by(tables.Package.status) package_numbers = {status: num_packages ...
atus in all_statuses: row = { 'commit': commit, 'date': date, 'status': status, 'num_packages': package_numbers.get(status, 0), } prev_batch.append(row) return prev_batch def get_history_naming_package_numbers(db, commit, date): """Get nu...
moonbury/notebooks
github/Numpy/Chapter9/emalegend.py
Python
gpl-3.0
1,648
0.009102
from matplotlib.finance import quotes_historical_yahoo from matplotlib.dates import DateFormatter from matplotlib.dates import DayLocator from matplotlib.dates import MonthLocator import sys from datetime import date import matplotlib.pyplot as plt import numpy as np today = date.today() start = (today.year - 1, today...
or i in range(9, 18, 3): weights =
np.exp(np.linspace(-1., 0., i)) weights /= weights.sum() ema = np.convolve(weights, close)[i-1:-i+1] idx = (i - 6)/3 ax.plot(dates[i-1:], ema, lw=idx, label="EMA(%s)" % (i)) data = np.column_stack((dates[i-1:], ema)) emas.append(np.rec.fromrecords(data, names=["dates", "ema"])) first = emas[0]["e...
minhphung171093/GreenERP_V9
openerp/addons/account_tax_cash_basis/__openerp__.py
Python
gpl-3.0
740
0.009459
# -*- coding: utf-8 -*- # Part of Odoo. S
ee LICENSE file for full copyrigh
t and licensing details. { 'name' : 'Account Tax Cash Basis', 'version' : '1.1', 'author' : 'OpenERP SA', 'summary': 'Allow to have cash basis on tax', 'sequence': 4, 'description': """ Add an option on tax to allow them to be cash based, meaning that during reconciliation, if there is a tax...
axltxl/m2bk
tests/test_app.py
Python
mit
1,751
0.001142
# -*- coding: utf-8 -*- """ Test for: command line arguments """ from nose.tools import eq_, a
ssert_raises from m2bk import app, config, const import os def _get_arg_cfg_file_name(arg, filename): try: app.init_parsecmdline([arg, filename]) except FileNotFoundError: pass return config.get_config_file_name() def test_args_co
nfig(): # file names f1 = 'f1.txt' f2 = 'f2.txt' f3 = 'f3.txt' # --- # Test whether -c works as --config eq_(_get_arg_cfg_file_name('-c', f1), _get_arg_cfg_file_name('--config', f1), msg="-c and --config are not capturing the expected file name") # --- # Test -c and -...
GutenkunstLab/SloppyCell
Example/Robertson/generate_ensembles_predictions.py
Python
bsd-3-clause
3,417
0.007609
from numpy import * import scipy.stats from SloppyCell.ReactionNetworks import * import example_net, example_model # # Calculate an ensemble # # Step scale = 3 gives faster convergence for this problem. print("Generating ensemble") ens_data, costs, ratio = Ensembles.ensemble_log_params(example_model.m, ...
ured = calc_trajectories(ens_one_measured[::10], tt) pred_jtj = calc_trajectories(ens_jtj[::10], tt) # # Calculate 95% bounds on predictions # pred_data_lw, pred_data_up = calc_trajectory_bounds(pred_data) pred_all_measured_lw, pred_all_measured_up = calc_trajectory_bounds(pred_all_measured)
pred_one_measured_lw, pred_one_measured_up = calc_trajectory_bounds(pred_one_measured) pred_jtj_lw, pred_jtj_up = calc_trajectory_bounds(pred_jtj) Utility.save((pred_data_lw, pred_data_up, pred_all_measured_lw, pred_all_measured_up, pred_one_measured_lw, pred_one_measured_up, ...
dstl/lighthouse
lighthouse/urls.py
Python
mit
5,370
0
# (c) Crown Owned Copyright, 2016. Dstl. """lighthouse URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: u...
ams/new/?$', TeamCreate.as_view(), name='organisation-team-create', ), url( r'^teams/?$', TeamList.as_view(), name='team-list', ), url( r'^teams/new/?$', TeamCreat
e.as_view(), name='team-create', ), url( r'^teams/(?P<pk>\d+)/join/?$', TeamJoin.as_view(), name='team-join', ), url( r'^teams/(?P<pk>\d+)/leave/?$', TeamLeave.as_view(), name='team-leave', ), url( r'^teams/(?P<pk>\d+)/?$', TeamDetail.as_view(), ...
filias/django
tests/migrations/routers.py
Python
bsd-3-clause
320
0
class TestRout
er(object): d
ef allow_migrate(self, db, app_label, model_name=None, **hints): """ The Tribble model should be the only one to appear in the 'other' db. """ if model_name == 'tribble': return db == 'other' elif db == 'other': return False
yephper/django
tests/urlpatterns_reverse/included_urls2.py
Python
bsd-3-clause
489
0
""" These URL patterns are included in two different ways in the main urls.py, with an extra argument present in one case.
Thus, there are two different ways for each name to resolve and Django must distinguish
the possibilities based on the argument list. """ from django.conf.urls import url from .views import empty_view urlpatterns = [ url(r'^part/(?P<value>\w+)/$', empty_view, name="part"), url(r'^part2/(?:(?P<value>\w+)/)?$', empty_view, name="part2"), ]
ctsit/nacculator
tests/test_cls.py
Python
bsd-2-clause
5,905
0.000677
import unittest from io import StringIO from nacc.uds3 import clsform from nacc.uds3 import packet from nacc.uds3.fvp import forms as fvp_forms from nacc.uds3.ivp import forms as ivp_forms class TestCLS(unittest.TestCase): def test_cls_blank_not_added_to_ivp(self): """Don't add blank CLS form to IVP."""...
(): return { 'eng_preferred_language': '1', 'eng_years_speak_spanish': '1', 'eng_years_speak_english': '1', 'eng_percentage_spanish': '50', 'eng_percentage_english': '50', 'eng_proficiency_spanish': '1', 'eng_proficiency_read_spanish': '1', 'eng_profic...
'eng_proficiency_write_english': '1', 'eng_proficiency_oral_english': '1', 'hispanic': '1', # This is from Form A1 'visityr': '2018', 'visitmo': '11', 'form_cls_linguistic_history_of_subject_complete': '2', } if __name__ == "__main__": unittest.main()
XianliangJ/collections
CNUpdates/updates/examples/loadwild/loadbalancer/lbtest/Alphas.py
Python
gpl-3.0
4,597
0.01588
# ========================================== # Author: Richard Wang # Contact: rwthree@princeton.edu # # Performs simple parsing of an "Alpha" file # Contents are simply (Server #, Alpha) # Ex: # 1, 3 # 2, 0 # 3, 1 # ========================================== import random import Globals def updateAlphas(newAlphas, ...
ca'], 'alphaTarget': newAlphas[i]['alphaTarget'], 'alphaAssign': 0}) for i in range(0, len(oldTargetList)): for j in range(0, len(Globals.ALPHAS)): if oldTargetList[i]['replica'] == Globals.ALPHAS[j]['replica']: Globals.ALPHAS[j]['alphaAssign'] -= 1 def getAlphas(filename): ...
ine2 = line.replace('\n', '') line3 = line2.replace(' ', '') l = line3.split(',') for i, replica in enumerate(Globals.REPLICAS): if replica['no'] == int(l[0]): if replica['mac'] != '': alphalist.append({'replica': int(l[0]), 'alphaTarget': int(l[1]), 'alphaAssign': 0})...
chrism333/xpcc
tools/system_design/builder/cpp_postman.py
Python
bsd-3-clause
4,175
0.018204
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2009, Roboterclub Aachen e.V. # 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 ...
st = "container", default = None, help = "name of the container in the XML file") optparser.add_option( "--namespace", dest = "namespac
e", default = "robot", help = "Namespace of the generated identifiers.") def generate(self): # check the commandline options if not self.options.outpath: raise builder_base.BuilderException("You need to provide an output path!") if not self.options.container or self.options.container not in self.tree...
khera-shanu/tap_to_survive
game.py
Python
gpl-3.0
5,559
0.019248
import pyglet from init_game import * import random def get_4_random_xy_combo_coordinates(): qs = ( ( (width, 1.5*width), (0, height/2) ), ( (1.5*width, 2*width), (0, height/2) ), ( (width, 1.5*width), (height/2, height-150) ), ( (1.5*width, 2*widt...
e_y_low and hero_y_low < sprite_y_up) #print (sprite_y_low > hero_y_low and sprite_y_low < hero_y_up) #print (hero_x_low > sprite_x_low and hero_x_low < sprite_x_up) #print (sprite_x_low > hero_x_low and sprite_x_low < hero_x_up) #import sys; sys.exit() @window.event de...
key.UP: if s_hero.y < height-150: s_hero.y = s_hero.y+30 elif sym == pyglet.window.key.DOWN: if s_hero.y > 30: s_hero.y = s_hero.y-30 #playing continuous sound snd = pyglet.media.load('bg.mp3') looper = pyglet.media.SourceGroup(snd.audio_format, None) looper.loop = True loop...
ppwwyyxx/tensorflow
tensorflow/python/saved_model/load.py
Python
apache-2.0
25,197
0.006032
# Copyright 2018 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...
rce_variable_ops from tensorflow.python.ops import variables from tensorflow.python.saved_model import function_deserialization from tensorflow.python.saved_model import load_v1_in_v2 from tensorflow.python.saved_model import loader_impl from tensorflow.python.saved_model import nested_structure_coder from tensorflow.p...
ython.training.tracking import graph_view from tensorflow.python.training.tracking import tracking from tensorflow.python.training.tracking import util from tensorflow.python.util import nest from tensorflow.python.util.tf_export import tf_export def _unused_handle(): """Returns a placeholder as a handle that is no...
troelsfr/BatchQ
batchq/contrib/examples/tutorial2_create_file4.py
Python
mit
532
0.009398
from tutorial2_create_file3 import CreateFileShort from batchq.core import batch from batchq.pipelines.shell.ssh import SSHTerminal import getpass class
CreateFileSSH(CreateFileShort): server = batch.Property() username = batch.Property() password = batch.Property() terminal = batch.Controller(SSHTerminal, server, username, password) user = raw_input("Username:") pasw = getpass.getpass() instance = CreateFileSSH("Documents/DEMO_SSH", "echo Hello SSH
> hello.txt", "localhost",user,pasw) instance.create_file()
Azure/azure-sdk-for-python
sdk/compute/azure-mgmt-compute/azure/mgmt/compute/v2021_04_01/operations/_virtual_machine_images_edge_zone_operations.py
Python
mit
22,628
0.004287
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
s=query_parameters, headers=header_parameters, **kwargs ) def build_list_offers_request( location: str, edge_zone: str, publisher_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: api_version = "2021-04-01" accept = "application/json" # Construct URL ...
.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/edgeZones/{edgeZone}/publishers/{publisherName}/artifacttypes/vmimage/offers') path_format_arguments = { "location": _SERIALIZER.url("location", location, 'str'), "edgeZone": _SERIALIZER.url("edge_...
jaor/python
bigml/api_handlers/datasethandler.py
Python
apache-2.0
8,741
0
# -*- coding: utf-8 -*- # # Copyright 2014-2021 BigML # # 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 ...
ls https://bigml.com/api/datasets """ try: import simplejson as json except Impor
tError: import json from bigml.api_handlers.resourcehandler import ResourceHandlerMixin from bigml.api_handlers.resourcehandler import check_resource_type, \ get_resource_type, resource_is_ready, check_resource, get_source_id, \ get_dataset_id, get_cluster_id from bigml.constants import (DATASET_PATH, SOUR...
Maronato/aosalunos
misago/models/monitoritemmodel.py
Python
gpl-2.0
784
0.001276
from django.db import models class MonitorItem(models.Model): id = models.CharField(max_length=255, primary_key=True) _val
ue = mo
dels.TextField(db_column="value", blank=True, null=True) type = models.CharField(max_length=255, default="int") updated = models.DateTimeField(blank=True, null=True) class Meta: app_label = 'misago' @property def value(self): if self.type in ("int", "integer"): return i...
ystk/debian-openipmi
swig/python/openipmigui/gui_term.py
Python
gpl-2.0
9,780
0.002147
# gui_term.py # # openipmi GUI terminal handling for SoL # # Author: MontaVista Software, Inc. # Corey Minyard <minyard@mvista.com> # source@mvista.com # # Copyright 2006 MontaVista Software Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU L...
elif (key == "Return") or (key == "KP_Enter"): s = "\x0d" elif (key == "Backspace"): s = "\x08" elif (key == "Up"): s = "\x1b[A" elif (key == "Down"):
s = "\x1b[B" elif (key == "Right"): s = "\x1b[C" elif (key == "Left"): s = "\x1b[D" elif (key == "Next"): s = "\x1b[6~" elif (key == "Prior"): s = "\x1b[5~" elif (key == "Insert"): s = "\x1b[2~" elif (key == ...
jonparrott/google-cloud-python
monitoring/google/cloud/monitoring_v3/proto/notification_service_pb2_grpc.py
Python
apache-2.0
15,062
0.004847
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc from google.cloud.monitoring_v3.proto import notification_pb2 as google_dot_cloud_dot_monitoring__v3_dot_proto_dot_notification__pb2 from google.cloud.monitoring_v3.proto import notification_service_pb2 as google_dot_cloud_dot_monitoring...
quest_serializer=google_dot_cloud_dot_monitoring__v3_dot_proto_dot_notification__service__pb2.DeleteNotificationChannelRequest.SerializeToSt
ring, response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, ) self.SendNotificationChannelVerificationCode = channel.unary_unary( '/google.monitoring.v3.NotificationChannelService/SendNotificationChannelVerificationCode', request_serializer=google_dot_cloud_dot_m...
dimitardanailov/appbuilder-sublime-package
app_builder/command_executor.py
Python
apache-2.0
4,567
0.006131
import sublime import os import subprocess import platform from .bootstrapper import get_config from .notifier import log_info, log_error, log_fail from .thread
_progress import run_progress_indicator from .command_thread import CommandThread _appbuilder_path = [] def run_command(command, on_data=None, on_
done=None, show_progress=True, in_progress_message="Loading", success_message="", failure_message = "", show_status=True, filter_empty_args=True, no_save=False, **kwargs): appbuilder_path = _get_appbuilder_path() if appbuilder_path == None: on_done(False) return None command = appbu...
lluc/django_jdf
jdf/models.py
Python
mit
1,451
0.011027
from django.db import models from django_hstore import hstore # Create your models here. class Place(models.Model): osm_type = models.CharField(max_length=1) osm_id = models.IntegerField(primary_key=True) class_field = models.TextField(db_column='class') # Field renamed because it was a Python reserved wor...
e = hstore.DictionaryField(blank=True) # This field type is a guess. admin_level = models.IntegerField(null=True, blank=True) housenumber = models.TextField(blank=True) street = models.TextField(blank=True) isin = models.TextField(blank=True) postcode = models.TextField(blank=True) country_code ...
a guess. objects = hstore.HStoreManager() class Meta : managed = False db_table= 'place' unique_together = ('osm_id', 'class_field') class Phonetique(models.Model): nom = models.TextField() #osm_id = models.IntegerField() osm = models.ForeignKey(Place) poids =...
zhulangen/python-websocket-shell
tests/exc_shell.py
Python
mit
168
0.035714
import subprocess subp=subprocess.Popen('.
/test.sh',shell=True,stdout=subprocess.PIPE) while subp.poll()==None:
print subp.stdout.readline() print subp.returncode
cedriclaunay/gaffer
python/Gaffer/CompoundPathFilter.py
Python
bsd-3-clause
3,444
0.033101
#####################################
##################################### # # Copyright (c) 2012, Image Engine Design Inc. 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 s
ource code must retain the above # copyright notice, this list of conditions and the following # disclaimer. # # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materia...
mmarkov/pygraphviz
pygraphviz/graphviz.py
Python
bsd-3-clause
7,770
0.027284
# This file was automatically generated by SWIG (http://www.swig.org). # Version 3.0.2 # # Do not make changes to this file unless you know what you are doing--modify # the SWIG interface file instead. from sys import version_info if version_info >= (2,6,0): def swig_import_helper(): from ...
viz.agprvnode(*args) agprvnode = _graphviz.agprvnode def agedge(*args): return _graphviz.agedge(*args) agedge = _graphviz.agedge def agidedge(*args): return _graphviz.agidedge(*args) agidedge = _graphviz.agidedge def agsubedge(*args): return _graphviz.agsubedge(*args) agsubedge = _graphviz.agsubed...
s): return _graphviz.agnxtin(*args) agnxtin = _graphviz.agnxtin def agfstout(*args): return _graphviz.agfstout(*args) agfstout = _graphviz.agfstout def agnxtout(*args): return _graphviz.agnxtout(*args) agnxtout = _graphviz.agnxtout def agfstedge(*args): return _graphviz.agfstedge(*args) agfsted...
boothead/karl
karl/content/models/tests/test_forum.py
Python
gpl-2.0
4,533
0.000882
# Copyright (C) 2008-2009 Open Society Institute # Thomas Moroz: tmoroz@sorosny.org # # This program is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License Version 2 as published # by the Free Software Foundation. You may not use, modify or distribu...
ent.models.forum import Forum return Forum def _makeOne(self, title='title', description='description', creator=None): return self._getTargetClass()(title, description, cr
eator) def test_class_conforms_to_IForum(self): from zope.interface.verify import verifyClass from karl.content.interfaces import IForum verifyClass(IForum, self._getTargetClass()) def test_instance_conforms_to_IForum(self): from zope.interface.verify import verifyObject ...
ap13p/elearn
apps/views/dosen/__init__.py
Python
bsd-3-clause
3,490
0.001433
from flask import render_template, g, flash, redirect, url_for, request from flask_peewee.utils import object_list from werkzeug.datastructures import FileStorage from werkzeug.utils import secure_filename from peewee import fn, JOIN from apps.forms.others import TugasForm from apps.models import KumpulTugas, Tugas, M...
) form.action = url_for('dosen:tugas:update', tugas_id=tugas_id) matkul = MataKuliah.get(MataKuliah.dosen == user) if form.validate_on
_submit(): form.populate_obj(tugas) tugas.mata_kuliah = matkul tugas.save() flash('Sukses memperbarui tugas') return redirect(url_for('dosen:tugas:list')) return render_template('dosen/tugas/update.html', form=form) @dosen_required def tugas_create(): form = TugasForm(r...
xesscorp/xess_fp_wizard
xess_fp_wizard.py
Python
mit
18,484
0.002218
# MIT license # # Copyright (C) 2015 by XESS Corp. # # 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, modi...
/ Through-Hole (N)' pad_drill_key = 'Drill Size' pad_soldermask_margin_key = 'Soldermask Margin' pad_paste_fill_key = 'Paste Fill (%)' fp_name_key = 'Footprint Name' fp_ref_key = 'Reference Prefix' land_dim_key = 'Land Pattern (Y) / Mechanical (N)' outline_key = 'Silkscreen Outline (%...
bevel_key = 'Bevel (%)' add_index_key = 'Add index (Y/N)' paddle_enable_key = 'Thermal Pad (Y/N)' paddle_width_key = 'Width' paddle_height_key = 'Height' paddle_orgx_key = 'Center (X)' paddle_orgy_key = 'Center (Y)' paddle_soldermask_margin_key = 'Soldermask Margin' paddle_past...
addition-it-solutions/project-all
addons/sale_stock/sale_stock.py
Python
agpl-3.0
26,655
0.005627
# -*- 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 GNU...
lds.function(_get_delivery_count, type='integer', string='Delivery Orders'), } _defaults = { 'warehouse_id': _get_default_warehouse, 'picking_policy': 'direct', 'order_policy': 'manual', } def onchange_warehouse_id(self, cr, uid, ids, warehouse_id, context=None): val = {}...
ehouse = self.pool.get('stock.warehouse').browse(cr, uid, warehouse_id, context=context) if warehouse.company_id: val['company_id'] = warehouse.company_id.id return {'value': val} def action_view_delivery(self, cr, uid, ids, context=None): ''' This function retur...
RL-LDV-TUM/RobotAPI
robot/epuck.py
Python
gpl-3.0
8,049
0.009195
#!/usr/bin/python # -*- coding: utf-8 -*- ''' Copyright © 2016 by Michael Keil 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 yo...
port :Type: Port """
return self._port def disconnect(self): """ Disconnect from robot :return: If disconnect was successful :rType: boolean :raise Exception: if it was a problem closing the connection """ if self._connectionStatus: ...
alephu5/Soundbyte
environment/lib/python3.3/site-packages/matplotlib/finance.py
Python
gpl-3.0
23,591
0.013183
""" A collection of modules for collecting, analyzing and plotting financial data. User contributions welcome! """ import contextlib, os, sys, warnings from urllib.request import urlopen if sys.version_info[0] < 3: from hashlib import md5 else: import hashlib md5 = lambda x: hashlib.md5(x.encode()) im...
lotlib import verbose, get_cachedir from matplotlib.dates import date2num from matplotlib.cbook import iterable, mkdirs from matplotlib.collections import LineCollection, PolyCollection from matplotlib.colors import colorConverter from matplotlib.lines import Line2D, TICKLEFT, TICKRIGHT from matplotlib.patches import R...
writable directory. if cachedir is not None: cachedir = os.path.join(cachedir, 'finance.cache') else: # Should only happen in a restricted environment (such as Google App # Engine). Deal with this gracefully by not caching finance data. cachedir = None stock_dt = np.dtype([('date', object), ...
DMS-Aus/Roam
src/roam_tests/test_featurecursor.py
Python
gpl-2.0
1,206
0.005804
import pytest from roam_tests import objects from roam.infodock import FeatureCursor, NoFeature layer = objects.newmemorylayer() layer = objects.addfeaturestolayer(layer, 2) features = layer.getFeatures() featureone = next(features) featuretwo = next(features) @pytest.fixture def cursor(): return FeatureCursor(...
atureone, featuretwo]) def test_should_start_at_index_0(cursor): assert cursor.index == 0 def test_next_shoul
d_move_index(cursor): cursor.next() assert cursor.index == 1 def test_next_should_wrap_to_start_when_on_last(cursor): last = len(cursor.features) - 1 cursor.index = last assert cursor.index == last cursor.next() assert cursor.index == 0 def test_back_should_wrap_to_end_when_on_first(cursor...
happylindz/algorithms-tutorial
lintcode/FindMin/findMinII.py
Python
mit
1,448
0.004325
''' LintCode: http://www.lintcode.com/zh-cn/problem/find-minimum-in-rotated-sorted-array-ii/ 160. 寻找旋转排序数组中的最小值 II 假设一个旋转排序的数组其起始位置是未知的(比如0 1 2 4 5 6 7 可能变成是4 5 6 7 0 1 2)。 你需要找到其中最小的元素。 数组中可能存在重复的元素。 样例: 给出[4,4,5,6,7,0,1,2] 返回 0 ''' # 跟 findMin I 类似 # 因为可能存在重复的元素,所以在判断 num[left] >= num[mid] 之后 # 需要判断 left - mi...
if n < 1: return 0 left = 0 right = n - 1 while left < right: if num[left] < num[right]: return num[left] mid = (left + right) / 2 if num[left] < num[mid]: left = mid + 1 else: ...
right = mid flag = False if flag: left = mid + 1 return num[left]
juanbond/doctorcoin
contrib/bitrpc/bitrpc.py
Python
mit
7,842
0.038128
from jsonrpc import ServiceProxy import sys import string # ===== BEGIN USER SETTINGS ===== # if you do not set these you will be prompted for a password for every command rpcuser = "" rpcpass = "" # ====== END USER SETTINGS ====== if rpcpass == "": access = ServiceProxy("http://127.0.0.1:9332") else: access = Ser...
print access.backupwallet(path) except: print "\n---An error occurred---\n" elif cmd == "getaccount": try: addr = raw_input("Enter a Doctorcoin address: "
) print access.getaccount(addr) except: print "\n---An error occurred---\n" elif cmd == "getaccountaddress": try: acct = raw_input("Enter an account name: ") print access.getaccountaddress(acct) except: print "\n---An error occurred---\n" elif cmd == "getaddressesbyaccount": try: acct = raw_input("Ent...
Kami/libcloud
docs/examples/loadbalancer/nttcis/edit_ssl_offload_profile.py
Python
apache-2.0
1,131
0
# This script demonstrates how to edit a profile import libcloud def edit_ssl_offload_profile(lbdriver): # Identify the wich profile by name to be edited profile_name = "ssl_offload" datacenter_id = "EU6" profile = lbdriver.ex_list_ssl_offload_profiles( name=profile_name, datacenter_id=datace...
h as the current ciphers, unless ciphers were to be changed. # Here a new description is being added. result = lbdriver.ex_edit_ssl_offload_profile( profile.id, profile.name, profile.sslDomainCertificate.id, ciphers=profile.ciphers, description="A test edit of an offload profile") as...
ud.get_driver(libcloud.DriverType.LOADBALANCER, libcloud.DriverType.LOADBALANCER.NTTCIS) driver = cls('mitchgeo-test', 'Snmpv2c!', region='eu') return driver if __name__ == "__main__": lb = lbdriver() edit_ssl_offload_profile(lb)
tiangolo/fastapi
tests/test_tutorial/test_request_files/test_tutorial001.py
Python
mit
6,215
0.001126
from fastapi.testclient import TestClient from docs_src.request_files.tutor
ial001 import app client = TestClient(app) openapi_schema = { "openapi": "3.0.2",
"info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/files/": { "post": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, ...
Azure/azure-sdk-for-python
sdk/keyvault/azure-keyvault-certificates/samples/contacts.py
Python
mit
2,462
0.004062
# ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ import os from azure.identity import DefaultAzureCredential from azure.keyvault.certificates import CertificateClient, CertificateContact from azure.core.exceptions impo...
2. azure-keyvault-certificates and azure-identity packages (pip instal
l these) # # 3. Set Environment variables AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET, VAULT_URL # (See https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/keyvault/azure-keyvault-keys#authenticate-the-client) # # -------------------------------------------------------------------------------------...
marcosbontempo/inatelos
poky-daisy/meta/lib/oeqa/utils/commands.py
Python
mit
3,796
0.003425
# Copyright (c) 2013 Intel Corporation # # Released under the MIT license (see COPYING.MIT) # DESCRIPTION # This module is mainly used by scripts/oe-selftest and modules under meta/oeqa/selftest # It provides a class and methods for running commands on the host in a convienent way for tests. import os import sys im...
if self.status: lout = "\n".join(self.output.splitlines()[-20:]) self.log.debug("Last 20 lines:\n%s" % lout) class Result(object): pass def runCmd(command, ignore_status=False, timeout=No
ne, **options): result = Result() cmd = Command(command, timeout=timeout, **options) cmd.run() result.command = command result.status = cmd.status result.output = cmd.output result.pid = cmd.process.pid if result.status and not ignore_status: raise AssertionError("Command '%s...
andersx/s22-charmm
structures/ref.py
Python
unlicense
2,038
0.026006
energies = dict() energies[81] = -3.17 # Ammoniadimer.xyz energies[82] = -5.02 # Waterdimer.xyz energies[8
3] = -1.50 # BenzeneMethanecomplex.xyz energies[84] = -18.61 # Formicaciddimer.xyz energies[85] = -15.96 # Formamidedimer.xyz energies[86] = -20.65 # Uracildimerhbonded.xyz energies[87] = -16.71 # 2pyridoxine2aminopyridinecomplex.xyz energies[88] = -16.37 # AdeninethymineWatsonCrickcomplex.xyz ...
placed.xyz energies[92] = -4.42 # Pyrazinedimer.xyz energies[93] = -10.12 # Uracildimerstack.xyz energies[94] = -5.22 # Indolebenzenecomplexstack.xyz energies[95] = -12.23 # Adeninethyminecomplexstack.xyz energies[96] = -1.53 # Etheneethynecomplex.xyz energies[97] = -3.28 # Benzenewatercompl...
f-santos/elasticsearch-dsl-py
test_elasticsearch_dsl/test_integration/test_data.py
Python
apache-2.0
35,274
0.001616
from __future__ import unicode_literals # FIXME: copy-pasted from elasticsearch-py/example/load.py def create_git_index(client, index): # we will use user on several places user_mapping = { 'properties': { 'name': { 'type': 'text', 'fields': { 'raw': {'type' : 'key...
th ES server', 'author': {'name': 'Honza Kr\xe1l', 'email': 'honza.kral@gmail.com'}, 'parent_shas': ['dd1
5b6ba17dd9ba16363a51f85b31f66f1fb1157'], 'committed_date': '2014-05-01T13:32:14', 'authored_date': '2014-05-01T13:32:14'}, '_index': 'git'}, {'_type': 'commits', '_parent': 'elasticsearch-dsl-py', '_id': 'dd15b6ba17dd9ba16363a51f85b31f66f1fb1157', '_source': {'files': ['elasticsearch_dsl/utils.py', 'test_elasticsea...
l8orre/nxtBridge
nxtPwt/nxtBridgeCtrl.py
Python
mit
2,586
0.018948
# -*- coding: utf-8 -*- """ Copyright (c) 2014 l8orre 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 th
e Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission...
BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWAR...
dwkim78/ASTRiDE
astride/utils/edge.py
Python
mit
13,521
0.00037
import numpy as np from scipy.optimize import leastsq class EDGE: """ Detect edges (i.e. borders) using the input contours. Parameters ---------- contours : array_like An array containing contour list. min_points : int, optional The number of minimum data points in each edge....
1] + y[1:]) * xyxy) # Perimeter. perimeter = np.sum(np.sqrt((x[1:] - x[:-1])**2 + (y[1:] - y[:-1])**2)) # Distances from the center. distances = np.sqrt((x - x_center)**2 + (y - y_center)**2) return np.abs(A), perimeter, x_center, y_center, d...
ered_edges = [] filtered_cnt = 1 for edge in self.edges: if edge['shape_factor'] <= self.shape_cut and \ edge['area'] >= self.area_cut and \ edge['radius_deviation'] >= self.radius_dev_cut: # Reset index, incremental from 1. edge[...
ros2/launch
launch_xml/test/launch_xml/test_timer.py
Python
apache-2.0
1,975
0
# Copyright 2020 Open Source Robotics Foundation, 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...
iod_is_substitution(): xml_file = \ """\ <launch> <timer period="$(var my_period 5)"> <executable cmd="ls -las"/> </timer> </launch> """ xml_file = textwrap.dedent(xml_file) root_entity, parser = Parser.load(io.StringIO(xml_file)) l...
timer, TimerAction) assert isinstance(timer.period, list) assert len(timer.period) == 1 assert isinstance(timer.period[0], LaunchConfiguration) assert len(timer.actions) == 1
sposs/DIRAC
DataManagementSystem/test/IntegrationFCT.py
Python
gpl-3.0
6,261
0.032263
# TODO: to be moved to TestDIRAC and transformed into a real test ######################################################################## # File: ReplicateAndRegisterTests.py # Author: Krzysztof.Ciba@NOSPAMgmail.com # Date: 2013/05/13 18:38:55 ######################################################################## "...
uid in files: repFile = File() repFile.LFN = lfn repFile.Size = size repFile.Checksum = checksum repFile.ChecksumType = "adler32" replicateAndRegister.addFile( repFile ) removeReplica = Operation() removeReplica.Type = "RemoveReplica" removeReplica.TargetSE = sourceSE ...
n() removeFile.Type = "RemoveFile" for fname, lfn, size, checksum, guid in files: removeFile.addFile( File( {"LFN": lfn } ) ) removeFileInit = Operation() removeFileInit.Type = "RemoveFile" for fname, lfn, size, checksum, guid in files: removeFileInit.addFile( File( {"LFN": lfn } ) ) ...
uclouvain/OSIS-Louvain
base/migrations/0344_auto_20180903_1613.py
Python
agpl-3.0
626
0.001597
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2018-0
9-03 16:13 from __future__ import unicode_literals from django.db import mig
rations, models class Migration(migrations.Migration): dependencies = [ ('base', '0343_auto_20180903_1105'), ] operations = [ migrations.AlterField( model_name='educationgroupyear', name='constraint_type', field=models.CharField(blank=True, choices=[('...
sotondriver/Lego_classification
Lego/extend.py
Python
mit
5,541
0.001805
import os import numpy as np import cv2 import Levenshtein temp_count = 1 train_box = 0 train_box_logo = 1 temp_img = None predict_list = np.zeros((1, 5), dtype='float32') count = 1 def denoise_info(img): gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # _, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY...
tches is not None: lyu = np.argmax(matches) if lei is not None: lei_class = np.argmax(lei) if matches is None:
predict_class = cnn elif max(matches) == 1: predict_class = np.argmax(matches) elif max(lei) == 1: predict_class = np.argmax(lei) else: # print(matches) temp_list2 = np.asarray(matches, dtype='float32') temp_list3 = np.asarray(lei, dtype='float32') temp_lis...
dzon4xx/system
backend/components/element.py
Python
mit
4,504
0.006661
from backend.components.base_component import BaseComponent from backend.misc.sys_types import Et class Element(BaseComponent): table_name = "elements" COL_MODULE_ID, COL_REG, = 3, 4, column_headers_and_types = BaseComponent.column_headers_and_types + [['module_id', 'integer'], ['register', 'integer']] ...
esired_value = 0 self.setter_priority = OutputElement.defualt_priority # Default priority can be overriden by everybody def set_desired_value(self, value, priority, set_flag=False): if priority <= self.setter_priority: self.desired_value = value if s
et_flag: self.setter_priority = priority else: self.setter_priority = self.defualt_priority return True else: return False def __str__(self, ): return "".join([super().__str__(), "\tdesired_value: ", str(self.desired_value)]) ...
davidzchen/tensorflow
tensorflow/compiler/tests/tridiagonal_solve_ops_test.py
Python
apache-2.0
18,238
0.00499
# Copyright 2019 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...
np.array([1, 2, 3, 4], dtype=np.float32) _sample_result = np.array([-9, 5, -4, 4], dtype=np.float32) def _tfconst(array): return constant_op.constant(array, dtype=dtypes.float32) def _tf_ones(shape): return array_ops.ones(shape, dtype=dtypes.float64) class TridiagonalSolveOpsTest(xla_test.XLATestCase): """T...
ed ops.""" def testTridiagonalSolverSolves1Rhs(self): np.random.seed(19) batch_size = 8 num_dims = 11 diagonals_np = np.random.normal(size=(batch_size, 3, num_dims)).astype(np.float32) rhs_np = np.random.normal(size=(batch_size, num_dims, 1)).astype(np....
Gamebasis/3DGamebasisServer
GameData/blender-2.71-windows64/2.71/scripts/startup/bl_ui/space_nla.py
Python
gpl-3.0
6,129
0.002121
# ##### BEGIN GPL LICENSE BLOCK ##### # # 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 distrib...
ayout.prop(st, "show_frame_indicator") layout.prop(st, "show_seconds") layout.prop(st, "show_locked_time") layout.prop(st, "show_strip_curves") layout.separator() layout.operator("anim.previewrange_set") layout.operator("anim.previewrange_clear") layout.operato...
reviewrange_set") layout.separator() layout.operator("nla.view_all") layout.operator("nla.view_selected") layout.separator() layout.operator("screen.area_dupli") layout.operator("screen.screen_full_area") class NLA_MT_select(Menu): bl_label = "Select" def dra...
the-hypermedia-project/representor-python
tests/adapters/hale_json_test.py
Python
mit
4,564
0.001753
import sys import unittest import json import logging from representor import Representor from representor.adapters.hale_json import HaleJSONAdapter hale_example = """{ "_meta": { "any": { "json": "object" } }, "attribute": "value", "_links": { "self": { ...
"maybe" ], "in": true }, "user_id": { "scope": "href",
"required": true } } } }, "name": "Tom", "send_info": "yes" } ] } }""" class TestParse(unittest.TestCase): def setUp(self): Representor.adapters.add(H...
yceruto/django
tests/generic_inline_admin/admin.py
Python
bsd-3-clause
1,061
0.000943
from django.contrib import admin from django.contrib.contenttypes import generic from .models import (Media, PhoneNumber, Episode, EpisodeExtra, Contact, Category, EpisodePermanent, EpisodeMaxNum) site = admin.AdminSite(name="admin") class MediaInline(generic.GenericTabularInline): model = Media class Ep...
n(admin.ModelAdmin): inlines = [ MediaInline, ] class MediaExtraInline(generic.GenericTabularInline): model = Media extra = 0 class MediaMaxNumInline(generic.GenericTabularInline): model = Media extra = 5 max_num = 2 class PhoneNumberInline(generic.GenericTabularInline): mo...
isode, EpisodeAdmin) site.register(EpisodeExtra, inlines=[MediaExtraInline]) site.register(EpisodeMaxNum, inlines=[MediaMaxNumInline]) site.register(Contact, inlines=[PhoneNumberInline]) site.register(Category) site.register(EpisodePermanent, inlines=[MediaPermanentInline])
theSage21/judge-interface
webserver/contest/models.py
Python
mit
1,082
0.000924
from socket import create_connection from django.db import models from django.utils import timezone class Slave(models.Model): def __str__(self): return self.ip + str(self.port) ip = models.GenericIPAddressField() port = models.IntegerField() busy = models.BooleanField(default=False) def...
self.name name = models.CharField(max_length
=100, default='Contest') start = models.DateTimeField(default=timezone.now) end = models.DateTimeField(default=timezone.now)
olebole/astrometry.net
net/enhance_models.py
Python
bsd-3-clause
7,569
0.006077
from __future__ import print_function import os import numpy as np import tempfile import fitsio from django.db import models from django.db import transaction import settings from astrometry.util.util import * import logging log = logging.getLogger('enhance_models') class EnhanceVersion(models.Model): name ...
np.sin(theta), pscale * np.cos(theta), 1000,1000) xy = np.array([wcs.xyz2pixelxy(xyz[0], xyz[1], xyz[2]) for xyz in [xyz0, xyz1, xyz2, xyz3]]) # ok,x,y -> x,y x
y = xy[:,1:] xlo,ylo = xy.min(axis=0) xhi,yhi = xy.max(axis=0) # Make the WCS just barely contain the healpix -- magic 501 # here comes from 500 above. W,H = int(np.ceil(xhi - xlo)), int(np.ceil(yhi - ylo)) hpwcs = Tan(r0, d0, 501.-xlo, 501.-ylo, pscale * np.cos(theta), -ps...
rjfellman/molecule
test/unit/verifier/test_trailing.py
Python
mit
2,152
0.000929
# Copyright (c) 2015-2016 Cisco Systems # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publ...
res = trailing_instance._trailing_whitespace(line) assert res def test_trailing_whitespace_matched_multiline(trailing_instance): line = ['line1', 'line2 ', 'line3', 'line4 '] res = trailing_instance._tra
iling_whitespace(line) assert [2, 4] == res
laetrid/learning
First_course/ex6_5.py
Python
apache-2.0
736
0.001359
#!/usr/bin/env python ''' 5. Write a program that prompts a user for an IP address, then checks if the IP address is valid, and then converts the IP address to binary (dotted
decimal format). Re-use the functions created in exercises 3 and 4 ('import' the functions into your new program). ''' # Import functiosn - ip check, ip to bin and bin padding from ex6_3 import ip_checker from ex6_4 import ip2bin, bin_padding ip_valid = False while not ip_valid: ip_addr = raw_input('Please ente...
_addr print "In binary it is: %s." % '.'.join(ip_addr_bin) print "" # The END
bilbeyt/ituro
ituro/projects/migrations/0003_auto_20160131_0706.py
Python
mit
970
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('projects', '0002_auto_20150401_2057'), ...
name='membership', name='member', ), migrations.RemoveField( model_name='membership', name='project', ), migrations.Del
eteModel( name='Membership', ), migrations.AddField( model_name='project', name='manager', field=models.ForeignKey(default=1, to=settings.AUTH_USER_MODEL), preserve_default=False, ), ]
dnet/pySSTV
pysstv/__init__.py
Python
mit
85
0
#!/usr/
bin/env
python __all__ = ['color', 'grayscale', 'sstv', 'tests', 'examples']
jcchoiling/learningPython
s13/Day08/practice/s16.py
Python
gpl-3.0
237
0.008889
class MyException(Excepti
on): def __init__(self, msg): self.message = msg def __str__(self): return self.message try: rais
e MyException("Janice自定义的异常") except MyException as e: print(e)
refeed/coala-bears
tests/general/URLHeadBearTest.py
Python
agpl-3.0
4,508
0
import unittest import requests import requests_mock from bears.general.URLHeadBear import URLHeadBear, LINK_CONTEXT, URLHeadResult from coalib.results.SourceRange import SourceRange from coalib.testing.LocalBearTestHelper import get_results from coalib.settings.Section import Section from queue import Queue from .Inv...
tp://www.facebook.com/200 http://www.google.com/404
""".splitlines() with requests_mock.Mocker() as m: m.add_matcher(custom_matcher) result = get_results(self.uut, valid_file) self.assertEqual(result[0].contents, [2, 'http://www.facebook.com/200', 200, LINK_CONTEXT...
willvousden/ptemcee
ptemcee/util.py
Python
mit
4,906
0.001019
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import division, print_function, absolute_import, unicode_literals __all__ = ['_ladder', 'get_acf', 'get_integrated_act', 'thermodynamic_integration_log_evidence'] import numpy as np def _ladder(betas): """ Convert an arbitrary iterable of float...
s. See `Sokal's notes <http://www.stat.unc.edu/faculty/cji/Sokal.pdf>`_ on MCMC and sample estimators for autocorrelation times. :param x: The time series.
If multidimensional, set the time axis using the ``axis`` keyword argument and the function will be computed for every other axis. :param axis: (optional) The time axis of ``x``. Assumed to be the first axis if not specified. :param window: (optional) The size of the window to...
pgum/haus
hauser/amiibro.py
Python
gpl-3.0
501
0.00998
class A
miibro: def __init__(self): self._amiibos={#'hex': {'name': 'Noname', 'method': methodObject, 'params': params} } def handleTag(self, hex=None): if hex in self._amiibos: print(self._amiibos[hex]['name']) if self._amiibos[hex]['params']: ...
name']
suyashphadtare/vestasi-erp-1
erpnext/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py
Python
agpl-3.0
8,288
0.022683
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import unittest import frappe import frappe.model import json from frappe.utils import cint import frappe.defaults from erpnext.stock.doctype.purcha...
unt Customs Duty - _TC", 125, 1350], ["_Test Account Excise Duty - _TC", 140, 1490], ["_Test Account Education Cess - _TC", 2.8, 1492.8],
["_Test Account S&H Education Cess - _TC", 1.4, 1494.2], ["_Test Account CST - _TC", 29.88, 1524.08], ["_Test Account VAT - _TC", 156.25, 1680.33], ["_Test Account Discount - _TC", 168.03, 1512.30], ] for i, tax in enumerate(wrapper.get("other_charges")): self.assertEqual(tax.account_head, expected_v...
alexander-bzikadze/graph_diff
graph_diff/nirvana_object_model/worflow_generator/chain_workflow_generator.py
Python
apache-2.0
3,332
0.0009
import random import numpy from graph_diff.nirvana_object_model.workflow import Workflow from .standard_workflow_generator import StandardWorkflowGenerator class ChainWorkflowGenerator(StandardWorkflowGenerator): """Generator for chained workflows""" def __init__(self): super().__init__() s...
prev_block = self.types_of_block[0] prev_number
= workflow.add_block(prev_block) for new_block in self.types_of_block[1:]: new_number = workflow.add_block(new_block) workflow.add_connection_by_execution(prev_block, prev_number, new_block, new_number) prev_block = new_block prev_number = n...
reneetrei/agile-bayou-76491
teams/migrations/0001_initial.py
Python
mit
1,068
0.002809
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf i
mport settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Team', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=Fa...
('slug', models.SlugField(max_length=255, blank=True)), ('created', models.DateTimeField(auto_now_add=True)), ('modified', models.DateTimeField(auto_now=True)), ('members', models.ManyToManyField(related_name='member', to=settings.AUTH_USER_MODEL)), ...
nicko96/Chrome-Infra
appengine/findit/waterfall/extractor_util.py
Python
bsd-3-clause
5,268
0.003986
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import re # File extensions to filter out files from log. SUPPORTED_FILE_EXTENSIONS = [ 'c', 'cc', 'cpp', 'css', 'exe', 'gn', '...
) a/b/../c.cc -> a/c.cc a/b/./c.cc -> a/b/c.cc /b/build/slave/Android_Tests/build/src/a/b/c.cc -> a/b/c.cc """ # In some log (like
gn step), file paths start with // or \\, but they are # not an absolute path from the root directory. Thus strip them. file_path = file_path.lstrip('\\/') file_path = file_path.replace('\\', '/') file_path = file_path.replace('//', '/') filtered_parts = [] for part in file_path.split('/'): if part ...
cjgrady/irksome-broccoli
slr/common/costFunctions.py
Python
gpl-2.0
1,173
0.007673
""" @summary: This module contains potential cost functions to be used for calculating cost distance @author: CJ Grady @version: 1.0 @status: release @license: gpl2 @note: All cost functions should take arguments:
- currentCost: The cost already incurred - cellValue: The value at the origin cell - connCellValue: The value at the connected cell in question - cellSize: The size of the cells @note: To start, we will only have sea level rise """ # ..............................................................
......... def seaLevelRiseCostFn(currentCost, cellValue, connCellValue, cellSize): """ @summary: This cost function finds the cost to inundate a cell based on the current cost to get to that cell and the value of the connected cell @param currentCost: The cost to reach this po...
LamaHamadeh/Microsoft-DAT210x
Module-4/assignment2.py
Python
mit
3,877
0.00877
''' author Lama Hamadeh ''' import pandas as pd import matplotlib.pyplot as plt import matplotlib import assignment2_helper as helper # Look pretty... matplotlib.style.use('ggplot') # Do * NOT * alter this line, until instructed! scaleFeatures = True #Features scaling (if it's false no scaling appears and that aff...
int out and check your dataframe's dtypes. You'll probably # want to call 'exit()' after you print it out so you can stop the # program's execution. # # You can either take a look at the dataset webpage in the attribute info # section: h
ttps://archive.ics.uci.edu/ml/datasets/Chronic_Kidney_Disease # or you can actually peek through the dataframe by printing a few rows. # What kind of data type should these three columns be? If Pandas didn't # properly detect and convert them to that data type for you, then use # an appropriate command to coerce these ...
GuessWhoSamFoo/pandas
pandas/tests/io/formats/test_format.py
Python
bsd-3-clause
110,932
0.000046
# -*- coding: utf-8 -*- """ Test output formatting for Series/DataFrame, including to_string & reprs """ from __future__ import print_function from datetime import datetime import itertools from operator import methodcaller import os import re import sys import textwrap import warnings import dateutil import numpy ...
only_dot_row = True return only_dot_row def has_truncated_rep
r(df): return has_horizontally_truncated_repr( df) or has_vertically_truncated_repr(df) def has_doubly_truncated_repr(df): return has_horizontally_truncated_repr( df) and has_vertically_truncated_repr(df) def has_expanded_repr(df): r = repr(df) for line in r.split('\n'): if l...
OpenNingia/l5r-character-manager-3
l5r/tools/__init__.py
Python
gpl-3.0
24
0
__aut
hor__ = 'cns_
dasi'