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
kilon/sverchok
nodes/generator/basic_spline.py
Python
gpl-3.0
6,037
0.001656
# ##### 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...
FloatVectorProperty(name='knot_2', description="k2", update=updateNode) def sv_init(self, context): self.i
nputs.new('StringsSocket', "num_verts").prop_name = 'num_verts' self.inputs.new('VerticesSocket', "knot_1").prop_name = 'knot_1' self.inputs.new('VerticesSocket', "ctrl_1").prop_name = 'ctrl_1' self.inputs.new('VerticesSocket', "ctrl_2").prop_name = 'ctrl_2' self.inputs.new('VerticesSoc...
ammarkhann/FinalSeniorCode
lib/python2.7/site-packages/google/gax/utils/oneof.py
Python
mit
2,265
0
# Copyright 2017, Google 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 source code must retain the above copyright # notice, this list of con
ditions 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 materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # co...
ed to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # ...
the-blue-alliance/the-blue-alliance
src/backend/api/main.py
Python
mit
10,215
0.001468
from json import JSONDecodeError from flask import Blueprint, Flask, make_response, Response from flask_cors import CORS from google.appengine.api import wrap_wsgi_app from werkzeug.routing import BaseConverter from backend.api.handlers.district import ( district_events, district_list_year, district_ranki...
c=media_tags) # Team api_v3.add_url_rule("/team/<string:team_key>", view_func=team) api_v3.add_url_rule( "/team/<string:team_key>/<simple_model_type:model_type>", view_func=team ) # Team History api_v3.add_url_rule( "/team/<string:team_key>/years_participated", view_func=team_years_participated ) api_v3.add_u...
team/<string:team_key>/social_media", view_func=team_social_media) # Team Events api_v3.add_url_rule("/team/<string:team_key>/events", view_func=team_events) api_v3.add_url_rule( "/team/<string:team_key>/events/<model_type:model_type>", view_func=team_events ) api_v3.add_url_rule("/team/<string:team_key>/events/<i...
nodejs/node-gyp
gyp/pylib/gyp/msvs_emulation.py
Python
mit
54,358
0.002024
# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ This module helps emulate Visual Studio 2008 behavior on top of other build systems, primarily ninja. """ import collections import os import re import subpro...
dxsdk_dir = _FindDirectXInstallation() env["$(DXSDK_DIR)"] = dxsdk_dir if dxsdk_dir else "" # Try to find an installation location for the Windows DDK by checking # the WDK_DIR environment variable, may be None. env["$(WDK_DIR)"] = os.environ.get("WDK_DIR", "") return env def ExtractShared
MSVSSystemIncludes(configs, generator_flags): """Finds msvs_system_include_dirs that are common to all targets, removes them from all targets, and returns an OrderedSet containing them.""" all_system_includes = OrderedSet(configs[0].get("msvs_system_include_dirs", [])) for config in configs[1:]: ...
simas/django-paginated
paginated/settings.py
Python
mit
943
0.00106
from django.conf import settings PAGINATED_PER_PAGE = getattr(settings, 'PAGINATED_PER_PAGE', 10) PAGINATED_NEXT_TEXT = getattr( settings, 'PAGINATED_NEXT_TEXT', '&raquo;' ) PAGINATED_PREV_TEXT = getattr( settings, 'PAGINATED_PREV_TEXT', '&laquo;' ) PAGINATED_LEADING_PAGE_RANGE_DISPLAYED = getattr( settin...
_LEADING_PAGE_RANGE = getattr( settings, 'PAGINATED_LEADING_PAGE_RANGE', 8 ) PAGINATED_TRAILING_PAGE_RANGE = getattr( settings, 'PAGINATED_TRAILING_PAGE_RANGE', 8 ) PAGINATED_NUM_PAGES_OUTSIDE_RANGE = getattr( settings, 'PAGINATED_NUM_PAGES_OUTSIDE_RANGE', 2 ) PAGINATED_ADJACENT_PAGES = g
etattr( settings, 'PAGINATED_ADJACENT_PAGES', 4 ) PAGINATED_TEMPLATE = getattr( settings, 'PAGINATED_TEMPLATE', 'paginated/pagination.html' )
libracore/erpnext
erpnext/stock/utils.py
Python
gpl-3.0
11,261
0.025575
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe, erpnext from frappe import _ import json from frappe.utils import flt, cstr, nowdate, nowtime from six import string_types class Invali...
get_value('Item', item_code, 'valuation_method') if not val_method: val_method =
frappe.db.get_value("Stock Settings", None, "valuation_method") or "FIFO" return val_method def get_fifo_rate(previous_stock_queue, qty): """get FIFO (average) Rate from Queue""" if qty >= 0: total = sum(f[0] for f in previous_stock_queue) return sum(flt(f[0]) * flt(f[1]) for f in previous_stock_queue) / flt(t...
bigfatnoob/DISCAW
testRig.py
Python
mit
7,916
0.029939
from __future__ import division,print_function import sys, random, math import numpy as np from sklearn.tree import DecisionTreeClassifier from sklearn.linear_model import LinearRegression from lib import * from where2 import * import Technix.sk as sk import Technix.CoCoMo as CoCoMo from Models import * MODEL = JPL.J...
if doLinRg: scores[
'linRg'] = N() for score in scores.values(): score.go=True for test, train in loo(dataset._rows): say(".") desired_effort = effort(dataset, test) tree = launchWhere2(dataset, rows=None, verbose=False) n = scores["clstr"] n.go and clusterk1(n, dataset, tree, test, desired_effort) n = scor...
spulec/moto
moto/instance_metadata/__init__.py
Python
apache-2.0
114
0
from .models import instance_meta
data_backend instance_met
adata_backends = {"global": instance_metadata_backend}
ToonTownInfiniteRepo/ToontownInfinite
otp/distributed/DistributedDistrict.py
Python
mit
1,171
0.001708
from direct.directnotify.DirectNotifyGlobal import directNotify from direct.distributed.DistributedObject import DistributedObject class DistributedDistrict(DistributedObject): notify = directNotify.newCategory('DistributedDistrict') neverDisable = 1 def __init__(self, cr): DistributedObject.__ini...
nt = 0 self.newAvatarCount = 0 def announceGenerate(self): DistributedObject.announceGenerate(self)
self.cr.activeDistrictMap[self.doId] = self messenger.send('shardInfoUpdated') def delete(self): if base.cr.distributedDistrict is self: base.cr.distributedDistrict = None if self.cr.activeDistrictMap.has_key(self.doId): del self.cr.activeDistrictMap[self.doI...
richlewis42/qsardb
qsardb/models/models.py
Python
mit
3,946
0.002534
from sqlalchemy import Column, Integer, String, Sequence, ForeignKey, Enum, Float from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from . import Base from .utils import ModelMixin class Source(Base, ModelMixin): __tablename__ = 'source' __repr_props__ = ['id', ...
unique=True, nullable=False, index=True) source_id = Column(Integer, ForeignKey('source.id'), nullable=False) source = relationship('Source') # define species species_id = Column(Integer, ForeignKey('species.id'), nullable=False) species = relationship('Species', backref='targets') # define t...
ctional', 'Property', 'Unassigned', name='assay_type') ACTIVITIES = Enum('Kd', 'AC50', 'Potency', 'XC50', 'IC50', 'Ki', 'EC50', name='activity_type') RELATIONS = Enum('=', '>', '<', '<=', '>=', name='relation') class Activity(Base, ModelMixin): __tablename__ = 'activity' __re...
eshijia/magnum
magnum/templates/docker-swarm/fragments/make-cert.py
Python
apache-2.0
4,072
0
#!/usr/bin/python # Copyright 2015 Rackspace, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
:-1] def load_config(): config = dict() with open(HEAT_PARAMS_PATH, 'r') as fp: for line in fp.readlines(): key, value = line.split('=', 1) config[key] = _parse_config_value(value) return config def create_dirs(): os.makedirs(CERT_CONF_DIR) def _get_public_ip(): ...
_names = [ 'IP:%s' % _get_public_ip(), 'IP:%s' % config['SWARM_NODE_IP'], 'IP:127.0.0.1' ] return ','.join(subject_alt_names) def write_ca_cert(config): bay_cert_url = '%s/certificates/%s' % (config['MAGNUM_URL'], config['BAY_UUID']) h...
ibara1454/pyss
pyss/util/match.py
Python
mit
3,068
0
#! /usr/bin/env python # -*- coding: utf-8 -*- def replace_attr_if_match(mapper, dic): """ Parameters ---------- mapper : sorted list [(key, [(pattern, value)])] dic : sorted list [(key, value)] Returns ------- dic : dict dict mapped by mapper. Examples -------- >>> d...
tches, return the same value of x if there has no match. Parameters ---------- xs : [(pattern, value)] y : object Returns ------- result : object """ # Find the first match in ys matches = next(filter(lambda tup: tup[0] == y, xs), None) if matches is None: return
y else: return matches[1] def __match_map(mapper, xs, res): """ Parameters ---------- mapper : sorted list [(key, [(pattern, value)])] xs : sorted list [(key, value)] res : list of (key, value) tuples Returns ------- res : list of (key, value) tuples """ if no...
fedora-infra/fmn
fmn/tests/test_confirmations.py
Python
lgpl-2.1
2,584
0
import fmn.lib.models import fmn.tests class TestConfirmations(fmn.tests.Base): def create_user_and_context_data(self): fmn.lib.models.User.get_or_create( self.sess, openid="ralph.id.fedoraproject.org", openid_url="http://ralph.id.fedoraproject.org/", ) fmn.lib.mode...
(self.sess, user, context) confirmation = fmn.lib.models.Confirmation.create( self.sess, user, context, detail_value='awesome', ) self.assertEqual(preference.detail_values, []) confirmation.set_status(self.sess, 'accepted') self.ass...
some')
wlach/treeherder
treeherder/embed/views.py
Python
mpl-2.0
1,205
0
from django.http import Http404 from django.views.generic.base import TemplateView from treeherder.model.derived import JobsModel class ResultsetStatusView(TemplateView): template_name = "embed/resultset_status.html" def get_context_data(self, **kwargs): assert "r
epository" in kwargs and "revision" in kwargs context = super(ResultsetStatusView, self).get_context_data(**kwargs) with JobsModel(kwargs['repository']) as jm
: resultset_list = jm.get_resultset_all_revision_lookup( [kwargs['revision']]) if not resultset_list: raise Http404("No resultset found for revision {0}".format( kwargs['revision'])) result_set_id = resultset_list[kwargs['revision']...
Tankske/InfoVisNBA
scraper/remove.py
Python
bsd-3-clause
1,393
0.009332
import json import csv teamfolder = "teamdata/out/" with open('combined.json', 'r') as jsonfile: data = json.load(jsonfile) for yeardata in data: year = yeardata['year'] print "" print "NEW YEAR " + str(year) for team in yeardata['teams']: teamname = team['team']
print "Doing team " + teamname team['info'] = { "PTS/G": team['info']['PTS/G'], "FG%": team['info']['FG%']} team['opponent'] = { "PTS/G": team['opponent']['PTS/G']} team['misc'] = {"Attendance": team['misc']['Attendance'], "Age": team['misc']['Age'],
"ORtg": team['misc']['ORtg'], "DRtg": team['misc']['DRtg']} newplayers = [] totalper = 0 for player in team['players']: if player['advanced']['G'] > 5: del player['pergame'] del player['perminute'] player['perposs'] = { "ORtg": player['...
MiLk/youtube-dl
youtube_dl/extractor/channel9.py
Python
unlicense
11,499
0.004435
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ExtractorError class Channel9IE(InfoExtractor): ''' Common extractor for channel9.msdn.com. The type of provided URL (video or playlist) is determined according to meta Search.PageType from web pa...
ne' if x.group('note') == 'Audio only' else None, } for x in list(re.finditer(FORMAT_REGEX,
html)) if x.group('quality') in self._known_formats] self._sort_formats(formats) return formats def _extract_title(self, html): title = self._html_search_meta('title', html, 'title') if title is None: title = self._og_search_title(html) TITLE_SUF...
FNNDSC/ChRIS_ultron_backEnd
chris_backend/filebrowser/views.py
Python
mit
5,178
0.001931
from django.http import Http404 from rest_framework import generics, permissions from rest_framework.reverse import reverse from rest_framework.response import Response from rest_framework.views import APIView from core.utils import filter_files_by_n_slashes from .serializers import (FileBrowserPathListSerializer, Fi...
FileBrowserPathFileSerializer) from .services import get_path_folders, get_path_file_queryset, get_path_file_model_class class FileBrowserPathList(
generics.ListAPIView): """ A view for the initial page of the collection of file browser paths. The returned collection only has a single element. """ http_method_names = ['get'] serializer_class = FileBrowserPathListSerializer permission_classes = (permissions.IsAuthenticated,) def lis...
bjodah/mpmath
mpmath/__init__.py
Python
bsd-3-clause
8,555
0.001753
__version__ = '0.19' from .usertools import monitor, timing from .ctx_fp import FPContext from .ctx_mp import MPContext from .ctx_iv import MPIntervalContext fp = FPContext() mp = MPContext() iv = MPIntervalContext() fp._mp = mp mp._mp = mp iv._mp = mp mp._fp = fp fp._fp = fp mp._iv = iv fp._iv = iv iv._iv = iv # ...
= mp.fmod ldexp = mp.ldexp frexp = mp.frexp sign = mp.sign arg = mp.arg phase = mp.phase polar = mp.polar rect = mp.rect degrees = mp.degrees radians
= mp.radians atan2 = mp.atan2 fib = mp.fib fibonacci = mp.fibonacci lambertw = mp.lambertw zeta = mp.zeta altzeta = mp.altzeta gamma = mp.gamma rgamma = mp.rgamma factorial = mp.factorial fac = mp.fac fac2 = mp.fac2 beta = mp.beta betainc = mp.betainc psi = mp.psi #psi0 = mp.psi0 #psi1 = mp.psi1 #psi2 = mp.psi2 #psi3 ...
euhackathon/commission-today-api
backend/backend/migrations/0007_auto_20141203_0934.py
Python
mit
480
0.002083
# -*- coding: utf-8 -*- from __future__ imp
ort unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('backend', '0006_auto_20141203_0021'), ] operations = [ migrations.Alter
Field( model_name='meeting', name='organization', field=models.ForeignKey(blank=True, to='backend.Organization', null=True), preserve_default=True, ), ]
soerendip42/rdkit
rdkit/Chem/Recap.py
Python
bsd-3-clause
21,394
0.027017
# $Id$ # # Copyright (c) 2007, Novartis Institutes for BioMedical Research 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 source code must retain the abov...
ns: continue #print ' .',nSmi #print ' !!!!',rxnIdx,nSmi,reactionDefs[rxnIdx] ps = reaction.RunReactants((node.mol,)) #print ' ',len(ps) if ps: for prodSeq in ps: seqOk=True # we want to disqualify small fragments, so sort the product sequenc...
tSeq = [(prod.GetNumAtoms(onlyExplicit=True),idx) for idx,prod in enumerate(prodSeq)] tSeq.sort() ts=[(x,prodSeq[y]) for x,y in tSeq] prodSeq=ts for nats,prod in prodSeq: try: Chem.SanitizeMol(prod) except: continue ...
tomerfiliba/plumbum
tests/test_putty.py
Python
mit
1,938
0
"""Test that PuttyMachine initializes its SshMachine correctly""" import pytest from plumbum import PuttyMachine, SshMachine @pytest.fixture(params=["default", "322"]) def ssh_port(request): return request.param class TestPuttyMachine: def test_putty_command(self, mocker, ssh_port): local = m
ocker.patch("plumbum.machines.ssh_machine.local") init = mocker.spy(SshMachine, "__init__")
mocker.patch("plumbum.machines.ssh_machine.BaseRemoteMachine") host = mocker.MagicMock() user = local.env.user port = keyfile = None ssh_command = local["plink"] scp_command = local["pscp"] ssh_opts = ["-ssh"] if ssh_port == "default": putty_port = ...
loads/molotov
molotov/tests/test_api.py
Python
apache-2.0
2,203
0
from molotov.api import pick_scenario, scenario, get_scenarios, setup from molotov.tests.support import TestLoop, async_test class TestUtil(TestLoop): def test_pick_scenario(self): @scenario(weight=10) async def _one(self): pass @scenario(weight=90) async def _two(self...
# same for fixtures await _setup(self) def test_default_weight(self): @scenario() async def _default_weight(self): pass self.assertEqual(len(get_scenarios()), 1) self.assertEqual(get_scenarios()[0]["weight"], 1) def test_no_scenario(self): @scenario...
async def _one(self): pass @scenario(weight=0) async def _two(self): pass self.assertEqual(get_scenarios(), []) def test_scenario_not_coroutine(self): try: @scenario(weight=1) def _one(self): pass exc...
bytestudios/balitmorenode-lightboard
master control - python/control.sendpercolumn.py
Python
mit
7,835
0.047735
from PIL import Image from PIL import ImageDraw from PIL import ImageFont from numpy import array import numpy as np import struct import serial, time import twitter #ser = serial.Serial('/dev/ttyACM0', 1000000) ser = serial.Serial('/dev/cu.usbmodem1421', 1000000) time.sleep(2) def convertImageToPins(img, xoffset): ...
llo Node.", font=font, fill=(255,181,40)) #img = Image.open("fish.jpg") #time.sleep(5) def getTwitterStatus(which): this_current_status = '--not connected--' i = 0 for s in statuses: this_current_status = s.text #remove links if this_current_status.find('http://') > 0: this_current_status = this_current_sta...
_status break current_status = getTwitterStatus(1) panAndDisplayLongText(current_status, 1) current_status = getTwitterStatus(2) panAndDisplayLongText(current_status, 10) current_status = getTwitterStatus(3) panAndDisplayLongText(current_status, 5) ser.close()
SANDEISON/The-Huxley
Python/Viagem de Amigos.py
Python
gpl-3.0
615
0.013008
quantidade = int (input()) cidade = input() qt_quartos = int (input()) if cidade.lower() == "pipa": if qt_quartos == 2: valor_total = (quantidade * 75)+ 600 valor_unitario = valor_total / quantidade else: valor_total = (quantidade * 75)+ 900 valor_unitario = valor_total / quanti...
valor_unitario = valor_total / quantidade else: valor_total = (quantidade * 60)+ 1120 valor_unitario = valor_total / quantidade prin
t("%.2f" %valor_total) print("%.2f" %valor_unitario)
gusyussh/learntosolveit
languages/python/software_engineering_sqlite3.py
Python
bsd-3-clause
6,193
0.004198
from collections import namedtuple import sqlite3 # make a basic Link class Link = namedtuple('Link', ['id', 'submitter_id', 'submitted_time', 'votes', 'title', 'url']) # list of Links to work with links = [ Link(0, 60398, 1334014208.0, 109, "C overtakes Java as the No. 1 progr...
sod-1-0
"), Link(3, 30305, 1333968061.0, 270, "TIL about the Lisp Curse", "http://www.winestockwebdesign.com/Essays/Lisp_Curse.html"), Link(4, 59008, 1334016506.0, 19, "The Downfall of Imperative Programming. Functional Programming and the Multicore Revolution", "http://fpcomplete.co...
JeffHeard/terrapyn_docker
pysqlite-2.6.3/lib/test/py25/py25tests.py
Python
apache-2.0
2,745
0.002186
#-*- coding: ISO-8859-1 -*- # pysqlite2/test/regression.py: pysqlite regression tests # # Copyright (C) 2007 Gerhard Häring <[email protected]> # # This file is part of pysqlite. # # This software is provided 'as-is', without any express or implied # warranty. In no event will the authors be held liable for any damages #...
f.con.close() def CheckContextManager(self): """Can the connection be used as a context manager at all?""" with self.con: pass def CheckContextManagerCommit(self): """Is a commit called in the context manager?""" with self.con: self.con.execute("insert i...
lback() count = self.con.execute("select count(*) from test").fetchone()[0] self.assertEqual(count, 1) def CheckContextManagerRollback(self): """Is a rollback called in the context manager?""" global did_rollback self.assertEqual(did_rollback, False) try: ...
sketchturnerr/WaifuSim-backend
models/user_model.py
Python
cc0-1.0
861
0
import hashlib import random import string from datetime import datetime from models.base_model import BaseModel from peewee import CharField, DateTimeField, IntegerField USER_ROLE_USER = 1 USER_ROLE_MODERATOR = 2 TOKEN_CHARS = string.ascii_uppercase+string.digits+string.ascii_lowercase class UserModel(BaseModel): ...
ncode('utf-8')).hexdigest() def update_token(self): token = ''.join(random.choice(TOKEN_CHARS) for _ in range(16)) self.token_hash = self.generate_token_hash(token) retur
n token
edx/edx-ora
controller/migrations/0013_auto__add_message.py
Python
agpl-3.0
5,456
0.008431
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Message' db.create_table('controller_message', ( ('id', self.gf('django.db.model...
': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'xqueue_queue_name': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '1024'}), 'xqueue_submission_id': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '102
4'}), 'xqueue_submission_key': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '1024'}) } } complete_apps = ['controller']
opencivicdata/python-opencivicdata-django
opencivicdata/legislative/migrations/0011_auto_20191124_1658.py
Python
bsd-3-clause
606
0
# Generated by Django 2.2.3 on 2019-11-24 16:58 from django.db import migrations, models import django.db.models.deletion class Mig
ration(migrations.Migration): dependencies = [("legislative", "0010_auto_20191031_1507")] operations = [ migrations.AlterField(
model_name="searchablebill", name="version_link", field=models.OneToOneField( null=True, on_delete=django.db.models.deletion.CASCADE, related_name="searchable", to="legislative.BillVersionLink", ), ) ...
gnsiva/Amphitrite
gui/CalibrationGui/CalibrationGui.py
Python
gpl-2.0
16,785
0.007209
#!/usr/bin/env python # -*- coding: utf-8 -*- # generated by wxGlade 0.6.4 on Sun Dec 9 09:55:02 2012 """Program for calculating calibration curves for travelling wave ion mobility mass spectrometry""" __author__ = "Ganesh N. Sivalingam <[email protected]" import wx, os # begin wxGlade: extracode # end wxGl...
alibrant(self, event): # wxGlade: CalibrationGui.<event_handler> """Open a calibration amphitrite file (FileDialog). """ dlg = wx.FileDialog(self, message="Choose an Amphitrite file"
, wildcard="Amphitrite IM file (*.a)|*.a", style=wx.OPEN) if dlg.ShowModal() == wx.ID_OK: self.settings.setCalPath(str(dlg.GetPath())) self.textCtrlPath.SetValue(self.settings.getCalPath()) dlg.Destroy() ...
dmachard/extensive-testing
src/ea/serverinterfaces/TestServerInterface.py
Python
lgpl-2.1
13,189
0.001592
#!/usr/bin/env python # -*- coding: utf-8 -*- # ------------------------------------------------------------------- # Copyright (c) 2010-2019 Denis Machard # This file is part of the extensive automation project # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Le...
@type listeningAddress: """ NetLayerLib.ServerAgent.__init__(self, listeningAddress=listeningAddress, agentName=agentName, keepAliveInterval=Settings.getInt( 'Network', 'ke...
'Network', 'inactivity-timeout'), responseTimeout=Settings.getInt( 'Network', 'response-timeout'), selectTimeout=Settings.get( 'Network'...
cartwheelweb/packaginator
apps/grid/views.py
Python
mit
12,655
0.00806
"""views for the :mod:`apps.grid` app""" from django.conf import settings from django.contrib.auth.decorators import login_required, permission_required from django.contrib.auth.models import User from django.core.cache import cache from django.core.urlresolvers import reverse from django.db.models import Count from...
ants') ] return render_to_response( template_name, { 'grid': grid, 'features': features, 'grid_packages': grid_packages, 'attributes': default_attributes, 'elements': element_map, }, context_instance = RequestContext(request) ...
ure(request, slug, feature_id, bogus_slug, template_name="grid/grid_detail_feature.html"): """a slightly more focused view than :func:`grid.views.grid_detail` shows comparison for only one feature, and does not show the basic grid parameters Template context is the same as in :func:`grid.views.grid_det...
mlibrary/image-conversion-and-validation
falcom/tree/test/test_tree.py
Python
bsd-3-clause
5,278
0.00701
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. from hamcrest import * import unittest from ...test.hamcrest import evaluates_to from ..read_only_tree import Tree from ..mutable_tree import...
_that(list(self.tree.walk_values()), is_(equal_to([2, 4, 6, 5, 3]))) def test_can_get_two_items_by_index (self): assert_that(self.tree[0].value, is_(equal_to(2)))
assert_that(self.tree[1].value, is_(equal_to(3))) assert_that(calling(lambda t: t[2]).with_args(self.tree), raises(IndexError)) def test_tree_is_equal_to_mutable_tree (self): assert_that(self.tree, is_(equal_to(self.mutable_tree))) def test_tree_is_not_equal_to_empty_tre...
readevalprint/cartridge
cartridge/shop/defaults.py
Python
bsd-2-clause
8,233
0.002065
from socket import gethostname from django.utils.translation import ugettext as _ from mezzanine.conf import register_setting #################################################################### # This first set of settings already exists in Mezzanine but can # # be overridden or appended to here with Cartridge...
pty " "string is used, will fall back to the system's locale.", editable=False, default="", ) register_setting( name="SHOP_DEFAULT_SHIPPING_VALUE", label=_("Default Shipping Cost"), description=_("Default cost of shipping when no custom shipping is " "implemented."), editable=Tr...
CART", label=_("Discount in Cart"), description=_("Discount codes can be entered on the cart page."), editable=True, default=True, ) register_setting( name="SHOP_DISCOUNT_FIELD_IN_CHECKOUT", label=_("Discount in Checkout"), description=_("Discount codes can be entered on the first checkout ...
LennonChin/Django-Practices
MxShop/extra_apps/DjangoUeditor/settings.py
Python
apache-2.0
9,532
0.000575
# coding:utf-8 from django.conf import settings as gSettings # 全局设置 # 工具栏样式,可以添加任意多的模式 TOOLBARS_SETTINGS = {"besttome": [['source', 'undo', 'redo', 'bold', 'italic', ...
dateUserSettings(): # UserSettings = getattr(gSettings, "UEDITOR_SETTINGS", {}).copy() # if UserSettings.get("config", None): # UEditorSettings.update(UserSettings["config"]) # if UserSettings.get("upload", None): # UEditorUploadSettings.update(UserSettings["upload"]) def UpdateUserSettings(...
Settings, "UEDITOR_SETTINGS", {}).copy() if "config" in UserSettings:
DPaaS-Raksha/horizon
openstack_dashboard/dashboards/project/dashboard.py
Python
apache-2.0
1,678
0.002384
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 Nebula, 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 # # ...
izon.PanelGroup): slug = "compute" name = _("Manage Compute") panels = ('overview', 'instances', 'volumes',
'images_and_snapshots', 'access_and_security',) class NetworkPanels(horizon.PanelGroup): slug = "network" name = _("Manage Network") panels = ('networks', 'routers', 'loadbalancers', 'network_topology',) class ObjectStorePanels(horizon.Pa...
ZhangDubhe/Tropical-Cyclone-Information-System
TyphoonApi/suncreative/migrations/0008_auto_20210306_0049.py
Python
mit
891
0.00226
# Generated by Django 2.2.13 on 2021-03-06 00:49 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('suncreative', '0007_postrecord_state'), ] operations = [ migrations.CreateModel( name='MediaFo...
name='folder', field=models.ForeignKey(default=None, null=True,
on_delete=django.db.models.deletion.CASCADE, related_name='文件夹', to='suncreative.MediaFolder'), ), ]
erudit/eruditorg
tests/unit/erudit/test_import_journals_from_fedora.py
Python
gpl-3.0
2,888
0.003116
import datetime as dt import pytest from django.core.management import call_command from erudit.fedora import repository from erudit.test.factories import IssueFactory, CollectionFactory, JournalTypeFactory from erudit.models import Journal pytestmark = pytest.mark.django_db @pytest.mark.parametrize( "kwargs"...
_fedor
a", *[], **kwargs) # After the import command is run, only issue 1 & 3 should now be published. published_issues = issue_1.journal.issues.filter(is_published=True).values_list( "localidentifier", flat=True ) assert list(published_issues) == [ issue_1.localidentifier, issue_3.loc...
samanehsan/osf.io
website/addons/github/routes.py
Python
apache-2.0
3,429
0
# -*- coding: utf-8 -*- from framework.routing import Rule, json_renderer from website.addons.github import views settings_routes = { 'rules': [ # Configuration Rule( [ '/project/<pid>/github/settings/', '/project/<pid>/node/<nid>/github/settings/', ...
uth: User Rule( '/settings/github/oauth/', 'get', views.auth.github_oauth_start, json_renderer, endpoint_suffix='__user', ), Rule( '/settings/github/oauth/',
'delete', views.auth.github_oauth_delete_user, json_renderer, ), # OAuth: Node Rule( [ '/project/<pid>/github/oauth/', '/project/<pid>/node/<nid>/github/oauth/', ], 'get', views.auth.github...
akshaybabloo/Car-ND
Term_1/advanced_lane_finding_10/color_space_10_8.py
Python
mit
2,835
0.001058
""" HLS and Color Threshold ----------------------- You've now seen that various color thresholds can be applied to find the lane lines in images. Here we'll explore this a bit further and look at a couple examples to see why a color space like HLS can be more robust. """ import numpy as np import cv2 import matplot...
d_subplot(size_x, size_y, 6) plt.imshow(blue, cmap='gray') plt.title("Blue") f.add_subplot(size_x, size_y, 7) plt.imshow(binary_2, cmap='gray') plt.title("Threshold of Red color") f.add_subplot(size_x, size_y, 8)
plt.imshow(hue, cmap='gray') plt.title("Hue") f.add_subplot(size_x, size_y, 9) plt.imshow(lightness, cmap='gray') plt.title("Lightness") f.add_subplot(size_x, size_y, 10) plt.imshow(saturation, cmap='gray') plt.title("Saturation") f.add_subplot(size_x, size_y, 11) plt.imshow(b...
fbradyirl/home-assistant
homeassistant/components/linode/switch.py
Python
apache-2.0
2,885
0
"""Support for interacting with Linode nodes.""" import logging import voluptuous as vol from homeassistant.components.switch import PLATFORM_SCHEMA, SwitchDevice import homeassistant.helpers.config_validation as cv from . import ( ATTR_CREATED, ATTR_IPV4_ADDRESS, ATTR_IPV6_ADDRESS, ATTR_MEMORY, ...
"""Return the name of the switch.""" return self._name @property def
is_on(self): """Return true if switch is on.""" return self._state @property def device_state_attributes(self): """Return the state attributes of the Linode Node.""" return self._attrs def turn_on(self, **kwargs): """Boot-up the Node.""" if self.data.status ...
autosportlabs/podium-api
podium_api/login.py
Python
mit
2,804
0.000713
#!/usr/bin/env python # -*- coding: utf-8 -*- from podium_api.types.token import get_token_from_json from podium_api.asyncreq import make_request_custom_success, get_json_header import podium_api def make_login_post(username, password, success_callback=None, failure_callback=None, progress...
'.format(podium_api.PODIUM_APP.podium_url) body = {'grant_type': 'password', 'username': username, 'password': password} header = get_json_header() return make_request_custom_success(endpoint, login_success_handler, method='POST', ...
llback=success_callback, failure_callback=failure_callback, progress_callback=progress_callback, redirect_callback=redirect_callback, body=body, header=header) ...
sh01/liasis
src/liasis/test/__init__.py
Python
gpl-2.0
709
0.00141
#!/usr/bin/env python #Copyright 2009 Sebastian Hagen # This file is part of liasis. # # liasis 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 late
r version. # # liasis 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 #...
g/licenses/>.
LSaldyt/qnp
scripts/quant_exp.py
Python
mit
901
0.00222
try: from IBMQuantumExperience import IBMQuantumExperience from pprint import pprint def quant_exp(args): with open('etc/IBMtoken', 'r') as infile: token = infile.read().replace('\n', '') config = { "url": 'https://quantumexperience.ng.bluemix.net/api' } ...
nt('IBM Results for{}'.form
at(name)) pprint(code['executions'][-1]['result']) #pprint(code.keys()) #pprint(api.get_execution(name)) ''' except ModuleNotFoundError: print('IBM suite not installed') #1/0 def quant_exp(args): 1/0
finnurtorfa/aflafrettir
flask_aflafrettir/__init__.py
Python
gpl-3.0
3,945
0.012941
""" flask.aflafrettir ~~~~~~~~~~~~~~ Adds support for fetching data from the Department of Fisheries in Iceland and calculating the total catch for certain period of time. """ import logging from .soap import DOFService from .landings import Landings, sort_landings from .excel import save_excel class Aflafre...
make_list(self, name, date_from, date_to): """ Takes in two dates, fetches the la
ndings for the period and creates an excel sheet with lists of the landings. :param self: An instance attribute of the :class Aflafrettir: :param name: A name for the excel file :param date_from: A start date of the period :param date_to: An end date of the period. """ i...
pahaz/fabtools
fabtools/service.py
Python
bsd-2-clause
2,235
0.000447
""" System services =============== This module provides low-level tools for managing system services, using the ``service`` command. It supports both `upstart`_ services and traditional SysV-style ``/etc/init.d/`` scripts. .. _upstart: http://upstart.ubuntu.com/ """ from __future__ import with_statement from fabri...
# Force reload service fabtools.service.force_reload('foo') .. warning:: The service needs to support the ``force-reload`` operation. """ sudo('service %(service)s force-reload' % loc
als())
Secure-Trading/PythonAPI
securetrading/test/test_requestobject.py
Python
mit
5,171
0
#!/usr/bin/env python import unittest import securetrading from securetrading.test import abstract_test_stobjects import six class Test_Request(abstract_test_stobjects.Abstract_Test_StObjects): def setUp(self): super(Test_Request, self).setUp() self.class_ = securetrading.Request def test___...
= {"datacenterurl": "url"} requests4 = get_requests( [get_request({"a": "b"}), get_request(datacenter_url_dict)]) datacenter_path_dict = {"datacenterpath": "path"} requests5 = get_requests( [get_request({"a": "b"}), get_request(datacenter_path_d...
equests4, securetrading.ApiError, "10", "10 The key 'datacenterurl' must be specifed \ in the outer 'securetrading.Requests' object", ["The key 'datacenterurl' must be specifed in the \ outer 'securetrading.Requests' object"]), (requests5, securetrading.ApiError, ...
f304646673/scheduler_frame
src/tools/repair_tables.py
Python
apache-2.0
5,015
0.010658
#coding=utf-8 #-*- coding: utf-8 -*- import os import re import sys import time import MySQLdb import urllib2 sys.path.append("../frame/") from loggingex import LOG_INFO from loggingex import LOG_ERROR from loggingex import LOG_WARNING from mysql_conf_parser import mysql_conf_parser from scheduler_frame_conf_inst im...
D COLUMN `volume_ma5` float(16,2) NOT NULL DEFAULT 0 COMMENT '成交量5日均值' AFTER `close_ma180`, # ADD COLUMN `volume_ma10` float(16,2) NOT NULL DEFAULT 0 COMMENT '成交量10日均值' AFTER `volume_ma5`, # ADD COLUMN `volume_ma20` float(16,2) NOT NULL DEFAULT 0 COMMENT '成交量20日均值' AFTER `volume_ma10`, # ADD COL...
均值' AFTER `volume_ma20`, # ADD COLUMN `volume_ma60` float(16,2) NOT NULL DEFAULT 0 COMMENT '成交量60日均值' AFTER `volume_ma30`, # ADD COLUMN `volume_ma90` float(16,2) NOT NULL DEFAULT 0 COMMENT '成交量90日均值' AFTER `volume_ma60`, # ADD COLUMN `volume_ma180` float(16,2) NOT NULL DEFAULT 0 COMMENT '成交量180日...
openregister/country-update-demo
country_update_demo/factory.py
Python
mit
1,157
0.002593
# -*- coding: utf-8 -*- '''The app module, containing the app factory function.''' from flask import Flask, render_template # from country_update_demo.extensions import ( # #add as needed # ) def asset_path_context_processor(): return {'asset_path': '/static/'} def create_app(config_filename): ''' An ap...
tp://flask.pocoo.org/docs/patterns/appf
actories/ ''' app = Flask(__name__) app.config.from_object(config_filename) register_errorhandlers(app) register_blueprints(app) app.context_processor(asset_path_context_processor) return app def register_errorhandlers(app): def render_error(error): # If a HTTPException, pull th...
WorldLeadCurrency/WLC
contrib/pyminer/pyminer.py
Python
mit
6,435
0.03481
#!/usr/bin/python # # Copyright (c) 2011 The Bitcoin developers # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # import time import json import pprint import hashlib import struct import re import base64 import httplib import...
ttings: setti
ngs['hashmeter'] = 0 if 'scantime' not in settings: settings['scantime'] = 30L if 'rpcuser' not in settings or 'rpcpass' not in settings: print "Missing username and/or password in cfg file" sys.exit(1) settings['port'] = int(settings['port']) settings['threads'] = int(settings['threads']) settings['hashmet...
heuermh/gemini
gemini/annotation_provenance/HPRD/hprd_graph.py
Python
mit
1,338
0.003737
#!/usr/bin/env python import cPickle from pygraph.classes.graph import graph from pygraph.classes.exceptions import AdditionError """ This script converts a binary protein-protein interaction file from HPRD (http://http://www.hprd.org/) into a cPickled graph generated by the python-graph library. The resulting file ...
open("BINARY_PROTEIN_PROTEIN_INTERACTIONS.txt", 'r'): fields=line.strip().split("\t") first = str(fields[0]) second = str(fields[3]) if first != "-": try: gr.add_nodes([first]) except AdditionError: pass; if second != "-": try: gr.add_nodes...
pass; else: try: gr.add_edge((first, second)) except AdditionError: pass; cPickle.dump(gr, output) output.close()
spivachuk/sovrin-node
indy_node/test/upgrade/test_node_upgrade_in_progress.py
Python
apache-2.0
978
0.002045
from indy_common.constants import IN_PROGRESS from indy_node.test.upgrade.helper import check_node_sent_acknowledges_upgrade w
hitelist = ['unable to send message'] def test_node_sent_upgrade_in_progress(looper, nodeSet, nodeIds, validUpgrade): ''' Test that each node se
nds NODE_UPGRADE In Progress event (because it sees scheduledUpgrade in the Upgrader) ''' version = validUpgrade['version'] for node in nodeSet: node_id = node.poolManager.get_nym_by_name(node.name) node.upgrader.scheduledAction = (version, validUpgrade['...
ceos-seo/data_cube_ui
apps/water_detection/models.py
Python
apache-2.0
10,162
0.003149
# Copyright 2016 United States Government as represented by the Administrator # of the National Aeronautics and Space Administration. All Rights Reserved. # # Portion of this code is Copyright Geoscience Australia, Licensed under the # Apache License, Version 2.0 (the "License"); you may not use this file # except in c...
get_chunk_size(self): """Implements get_chunk_size as required by the base class See the base query class docstring for more information. """ return {'time': 25, 'geographic': 0.05} def get_iterative(self): """implements get_ite
rative as required by the base class See the base query class docstring for more information. """ return True def get_reverse_time(self): """implements get_reverse_time as required by the base class See the base query class docstring for more information. """ ...
macterra/galton
montecarlo.py
Python
apache-2.0
2,516
0.019078
from numpy import * from numpy.random import lognormal from random import * import time Sigma1 = 0.27043285 RiskMap = { 'none' : 0.001, 'low' : Sigma1, 'medium' : 2*Sigma1, 'high' : 3*Sigma1, 'very high' : 4*Sigma1 } BaseFactors = { 50 : 1, 60 : 1.07091495269662, 70 : 1.15236358602526, 80 : 1.2555855388372...
lf.p50 = estimate elif type == 'p60': self.p50 = self.CalcMedian(estimate, 60, risk) elif type
== 'p70': self.p50 = self.CalcMedian(estimate, 70, risk) elif type == 'p80': self.p50 = self.CalcMedian(estimate, 80, risk) elif type == 'p90': self.p50 = self.CalcMedian(estimate, 90, risk) else: raise 'unknown estimate type' ...
FUSED-Wind/fusedwind
src/fusedwind/runiec_proto/splitsamples.py
Python
apache-2.0
708
0.007062
import sys base = sys.argv[1] lines=file(base).readlines() incr = int(sys.argv[2]) hdr = lines[0].strip() cnt = 1 fno = 0 print "splitting %s into files wi
th no more than %d samples" % (base, incr) while (cnt < len(lines)): fname = "%s.%d" % (base, fno) fout = file(fname, "w") fout.write("%s\n" % hdr) thiscnt = 0 while (cnt < len(lines) and thiscnt < incr): ln = lines[cnt].strip() fout.write("%s\n" % ln)
cnt += 1 thiscnt += 1 fout.close() fno += 1 for i in range(0,fno): print "python openruniec.py -p -c -i int_samples16161616.txt.%d" % i print "cp dlcproto.out dlcproto.out.%d" %i print "## now reassemble"
chaostrigger/rl-library
projects/agents/randomAgentPython/src/RandomAgent.py
Python
apache-2.0
2,498
0.03763
# # Brian Tanner took this agent from the rl-competition code at http://rl-competition.googlecode.com/ # # Copyright (C) 2007, Mark Lee # # 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...
1 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import random import sys from rlglue.agent.Agent import Agent from rlglue.types import Action from rlglue.types import Observation class RandomAgent(Agent): #"2:e:2_[f,f]_[-1.2,0
.6]_[-0.07,0.07]:1_[i]_[0,2]"; def agent_init(self,taskSpec): self.action = Action() self.action_types = [] random.seed(0) (version,episodic,states,actions,reward) = taskSpec.split(':') (stateDim,stateTypes,stateRanges) = states.split('_',2) (actionDim,actionTypes,actionRanges) = actions.split('_',2) act...
deanhiller/databus
webapp/play1.3.x/python/Lib/site-packages/pyreadline/clipboard/win32_clipboard.py
Python
mpl-2.0
3,724
0.007787
# -*- coding: utf-8 -*- #***************************************************************************** # Copyright (C) 2003-2006 Jack Trainor. # Copyright (C) 2006 Jorgen Stenarson. <[email protected]> # # Distributed under the terms of the BSD License. The full license is in # the file...
his contribution. # ################################################################################### from ctypes import * from pyreadline.keysyms.winconstants import CF_TEXT, GHND from pyreadline.unicode_helper import ensure_unicode,ensure_str OpenClipboard = windll.user32.OpenClipboard EmptyClipboar
d = windll.user32.EmptyClipboard GetClipboardData = windll.user32.GetClipboardData GetClipboardFormatName = windll.user32.GetClipboardFormatNameA SetClipboardData = windll.user32.SetClipboardData EnumClipboardFormats = windll.user32.EnumClipboardFormats CloseClipboard = windll.user32.CloseClipboard OpenClipboard....
robertchase/rhc
tests/test_timer.py
Python
mit
2,103
0
import time import rhc.timer as timer class Action(object): def __init__(self): self.t1 = False self.t2 = False def a1(self): self.t1 = True def a2(self): self.t2 = True def test_no_start(): t = timer.Timer() a = Action() t.add(a.a1, 15) t.add(a.a2, 10...
Action() t.add(a.a1, 15).start() t.add(a.a2, 10) assert len(t) == 1 time.sleep(.02) t.service() assert a.t1 is True assert a.t2 is False def test_start_all(): t = timer.Timer() a = Action() t.add(a.a1, 15).start() t.add(a.a2, 10).start() assert
len(t) == 2 time.sleep(.02) t.service() assert a.t1 is True assert a.t2 is True def test_start_restart(): t = timer.Timer() a = Action() t.add(a.a1, 10).start() t2 = t.add(a.a2, 20).start() time.sleep(.015) t.service() assert a.t1 is True assert a.t2 is False t2.re_...
hawkowl/axiom
axiom/batch.py
Python
mit
40,033
0.002573
# -*- test-case-name: axiom.test.test_batch -*- """ Utilities for performing repetitive tasks over potentially large sets of data over an extended period of time. """ import weakref, datetime, os, sys from zope.interface import implements from twisted.python import reflect, failure, log, procutils, util, runtime fr...
pe): if first: first = False else: return True self.forwardMark = workUnit.storeID self._doOneWork(workUnit, _ForwardProcessingFailure) for workUnit in self._bac
kwardWork(self.processor.workUnitType): if first: first = False else: return True self.backwardMark = workUnit.storeID self._doOneWork(workUnit, _BackwardProcessingFailure) if first: raise _NoWorkUnits() if VERB...
chrhartm/SORN
utils/lstsq_reg.py
Python
mit
564
0.010638
import numpy as np """ Performs tikhonov regularized least squares I.e. solution of y = Ax for x Parameters: A: NxM ndarray
y: NxK ndarray mue: double regularization parameter Returns: x: MxK array """ def lstsq_reg(A,Y,mue): Ac = A.copy() Yc = Y.copy() result = np.dot(np.dot(np.linalg.inv( (Ac.T).dot(Ac) +mue*np.eye(np.shape(Ac)[1])), ...
), Yc) return result # Simple test example if __name__ == '__main__': pass
rjhelms/photo
src/photo/admin.py
Python
mit
3,376
0.001481
""" Admin classes for photo application """ from django.contrib import admin from django.contrib.admin.filters import RelatedOnlyFieldListFilter from photo.models import FilmFormat, Manufacturer, Film, Developer, FilmRoll, \ PhotoPaper, PhotoPaperFinish, Frame, Print, Enlarger class FilmAdmin(admin.ModelAdmin):...
:model:`photo.FilmRoll` """ list_display = ('name', 'film', 'format', 'shot_date', 'developed_date') list_filter = ('film', 'format', 'shot_date', 'developed_date',) prepopulated_fields = {'developed_speed': ('shot_speed',)} def get_changeform_initial_data(self, request): initial = super()....
) initial['photographer'] = request.user return initial class PhotoPaperAdmin(admin.ModelAdmin): """ Admin class for :model:`photo.PhotoPaper` """ list_display = ('name', 'manufacturer_short_name', 'multigrade', 'grade') list_filter = ('manufacturer', 'multigrade',) def paper_sh...
pzfreo/ox-clo
code/wc/spark/wc.py
Python
cc0-1.0
532
0.011278
# ~/spar
k/bin/spark-submit --master local[*] wc.py "file:///home/oxclo/datafiles/books/*" from pyspark import SparkContext, SparkConf import sys conf = SparkConf().setAppName("wordCount") sc = SparkContext(conf=conf) books = sc.textFile(sys.argv[1]) split = books.flatMap(lambda line: line.split()) stripped = split.map(lambd...
v) sc.stop()
alex/changes
tests/changes/api/test_user_details.py
Python
apache-2.0
1,350
0
from changes.models import User from changes.testutils import APITestCase class UserDetailsTest(APITestCase): def test_simple(self): user = self.create_user(email='[email protected]') path = '/api/0/users/{0}/'.form
at(user.id) resp = self.client.get(path) assert resp.status_code == 200 data = self.unserialize(resp) assert data['id'] == user.id.hex
class UpdateUserTest(APITestCase): def test_simple(self): user = self.create_user( email='[email protected]', is_admin=False, ) path = '/api/0/users/{0}/'.format(user.id) # ensure endpoint requires authentication resp = self.client.post(path, data={...
euphy/dymo-kanban-labels
dymo_kanban_labels/tests/test_jira_api.py
Python
mit
358
0
import unittest from jira import Issue from dymo_kanban_labels.lib
import jira_api class TestJiraAPI(unittest.TestCase): def test_get_issue(self): issue = jira_api.get_issue("DKL-2") print issue self.assertEqual(Issue, type(issue)) self.assertEqual(issue.key, "DKL-2") if __name__ ==
'__main__': unittest.main()
twitter/pants
src/python/pants/backend/native/targets/external_native_library.py
Python
apache-2.0
4,836
0.009926
# coding=utf-8 # Copyright 2018 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import absolute_import, division, print_function, unicode_literals import re from future.utils import text_type from pants.base.hash_utils import stable_j...
t(self): return stable_json_sha1(tuple(hash(req) for re
q in self)) class ConanRequirement(datatype([ ('pkg_spec', text_type), ('include_relpath', text_type), ('lib_relpath', text_type), ('lib_names', tuple), ])): """A specification for a conan package to be resolved against a remote repository. Example `pkg_spec`: 'lzo/2.10@twitter/stable' The inc...
garrettcap/Bulletproof-Backup
wx/tools/Editra/src/extern/pygments/token.py
Python
gpl-2.0
5,662
0.002473
# -*- coding: utf-8 -*- """ pygments.token ~~~~~~~~~~~~~~ Basic token types and the standard tokens. :copyright: Copyright 2006-2010 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ class _TokenType(tuple): parent = None def split(self): buf = [] ...
>> string_to_token('String.Double') Token.Literal.String.Double >>> string_to_token('Token.Literal.Number') Token.Literal.Number
>>> string_to_token('') Token Tokens that are already tokens are returned unchanged: >>> string_to_token(String) Token.Literal.String """ if isinstance(s, _TokenType): return s if not s: return Token node = Token for item in s.split('.'): n...
ella/mypage
mypage/pages/forms.py
Python
bsd-3-clause
6,005
0.006162
import itertools import logging from django import forms from django.conf import settings from django.utils.translation import ugettext_lazy as _ from mypage.pages.models import Page, Widget from mypage.rsswidgets.models import RSSWidget from mypage.rsswidgets.forms import RSSCreationConfigForm log = logging.getLogg...
alueError, err: log.error("Widget %s not added: %s" % (str(widget), str(err))) for commercial_id, normal_id in getattr(settings, 'COMMERCIAL_EQUIVALENTS', []): if widget.pk == normal_id: self.page.remove_widget(Widget.objects.get(pk=commercial...
class RemoveCustomWidgetForm(forms.Form): widget = forms.ModelChoiceField(queryset=None, empty_label=None) def __init__(self, page, data=None, files=None, *args, **kwargs): if data is not None and data.get('command', None) != ('remove-custom-widget'): data = files = None ...
cchristelis/feti
django_project/feti/migrations/0005_auto_20150428_1519.py
Python
bsd-2-clause
604
0.001656
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations impor
t django.core.validators class Migration(migrations.Migration): dependencies = [ ('feti', '0004_auto_20150428_1412'), ] operations = [ migrations.AlterField( model_name='address', name='phone', field=models.CharField(blank=True, max_length=40, null=Tru...
umber should have the following format: '+27888888888'.")]), ), ]
NeCTAR-RC/horizon
openstack_dashboard/dashboards/identity/identity_providers/protocols/views.py
Python
apache-2.0
1,718
0
# Copyright (C) 2015 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/LICENSE-2.0 # # Unle
ss required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS I
S" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from django.urls import reverse from django.utils.translation import ugettext_lazy as _ from horizon import forms from openstack_...
EliteTK/qutebrowser
qutebrowser/browser/webkit/network/webkitqutescheme.py
Python
gpl-3.0
4,617
0
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2014-2016 Florian Bruhin (The Compiler) <[email protected]> # # This file is part of qutebrowser. # # qutebrowser 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 S...
errorstr = "No handler found for {}!".format( request.url().toDispla
yString()) return networkreply.ErrorNetworkReply( request, errorstr, QNetworkReply.ContentNotFoundError, self.parent()) except qutescheme.QuteSchemeOSError as e: return networkreply.ErrorNetworkReply( request, str(e), QNetworkReply.ContentN...
seraphlnWu/django-mongoengine
example/tumblelog/tumblelog/views.py
Python
bsd-3-clause
2,227
0.000898
from django.http import HttpResponse from django_mongoengine.forms.fields import DictField from django_mongoengine.views import (CreateView, UpdateView, DeleteView, ListView, EmbeddedDetailView, View) from tumblelog.models import Post, BlogPo...
= {'post': BlogPost, 'video': Video, 'image': Image, 'quote': Quote, 'music': Music} success_message = "Post Added!" form_exclude = ('created_at', 'comments') @property def document(self): post_type = s
elf.kwargs.get('post_type', 'post') return self.doc_map.get(post_type) def get_form(self, form_class): form = super(AddPostView, self).get_form(form_class) music_parameters = form.fields.get('music_parameters', None) if music_parameters is not None: schema = { ...
talbrecht/pism_pik
examples/std-greenland/slr_show.py
Python
gpl-3.0
3,919
0.002807
#!/usr/bin/env python # Copyright (C) 2011-2012, 2014, 2016, 2017 The PISM Authors # script to generate figure: results from SeaRISE experiments # usage: if UAFX_G_D3_C?_??.nc are result NetCDF files then do # $ slr_show.py -m UAFX # try different netCDF modules try: from netCDF4 import Dataset as CDF except: ...
, # dark blue '#084594', # dark blue '#084594', # dark blue '#4DAF4A'] # green # print plot with white background fig = plt.f
igure() ax = fig.add_subplot(111) for j in range(n - 1): ax.plot(t, -(ivolshift[:, j] / 1.0e9) * scale, dashes[j], color=colors[j], linewidth=2) ax.set_xlabel('years from 2004') ax.set_ylabel('sea level rise relative to control (m)') ax.legend(labels, loc='upper left') ax.grid(True) plt.savefig(model + '_slr.pdf')
caterinaurban/Lyra
src/lyra/unittests/numerical/interval/forward/indexing3/keyval.py
Python
mpl-2.0
351
0.005764
D: Dict[str, Dict[int, int]] = {'a': {1: 0}, 'b': {1: 1}, 'c': {1: 2}, 'd': {1: 3}} k: S
et[str] = D.keys() z: Set[Dict[int, int]] = D.values() # FINAL: D -> "a"@[0, 1], "b"@[1, 1], "c"@[1, 2], _@[1, 3]; k -> [-inf, inf]; keys(D) -> 0@[-inf, inf], _@⊥; len(D) ->
[4, 4]; len(k) -> [1, 1]; len(z) -> [1, 1]; values(D) -> 1@[0, 3], _@⊥; z -> [0, 3]
cordis/pycloudia
pycloudia/channels/__init__.py
Python
mit
90
0
from .consts imp
ort * from .factory import SocketFactoryRegistry from
. import txzmq_impl
vmthunder/nova
nova/tests/api/openstack/compute/contrib/test_consoles.py
Python
apache-2.0
22,895
0.000262
# Copyright 2012 OpenStack Foundation # 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 requ...
sole_no_instance(self): self.stubs.Set(compute_api.API, 'get', fake_get_not_found) body = {'os-getVNCConsole': {'type': 'novnc'}} req = webob.Request.blank(self.url) req.method = "POST" req.body = jsonutils.dumps(body) req.headers["content-type"] = "application/json" ...
nsole_get(self): self.stubs.Set(compute_api.API, 'get_vnc_console', fake_get_vnc_console_not_found) body = {'os-getVNCConsole': {'type': 'novnc'}} req = webob.Request.blank(self.url) req.method = "POST" req.body = jsonutils.dumps(body) req.headers["...
kejbaly2/members
members/_version.py
Python
gpl-3.0
236
0
#
!/usr/bin/env python # Author: "Chris Ward" <[email protected]> # PY3 COMPAT from __future__ import unicode_literals, absolute_import version_info = ('0', '0', '5') __version__ = '.'.join(version_info[0:3]) # + '-' + version_info[3]
Cinntax/home-assistant
homeassistant/components/geo_rss_events/sensor.py
Python
apache-2.0
5,348
0.001122
""" Generic GeoRSS events service. Retrieves current events (typically incidents or alerts) in GeoRSS format, and shows information on events filtered by distance to the HA instance's location and grouped by category. For more details about this platform, please refer to the documentation at https://home-assistant.io...
operty def name(self): ""
"Return the name of the sensor.""" return "{} {}".format( self._service_name, "Any" if self._category is None else self._category ) @property def state(self): """Return the state of the sensor.""" return self._state @property def unit_of_measurement(self): ...
Markus-Goetz/CDS-Invenio-Authorlist
modules/bibauthorid/lib/bibauthorid_personid_tables_utils.py
Python
gpl-2.0
129,744
0.00454
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2011 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) a...
Sets the Data Cacher content to True if the table is not empty ''' try: res = run_sql("SELECT count(pers
onid) FROM aidPERSONID " "where tag='paper'") if res and res[0] and res[0][0] > 0: return True else: return False except Exception: # database problems, return empty cache re...
notmem/ops-p4dp
targets/l2_switch/tests/of-tests/openflow.py
Python
apache-2.0
7,105
0.006474
""" Openflow tests on an l2 table """ import sys import os import logging from oftest import config import oftest.base_tests as base_tests import ofp from oftest.testutils import * from oftest.parse import parse_mac import openflow_base_tests sys.path.append(os.path.join(sys.path[0], '..', '..', '..', '..', ...
append(os.path.join(sys.path[0], '..', '..', '..', '..', 'targets', 'l2_switch', 'build', 'thrift')) print sys.path from p4_pd_rpc.ttypes import * from res_pd_rpc.ttypes import * import sys import os import time sys.path.append(os.path.join(sys.path[0], '..', '..', '..', '..', ...
thands flow_add = ofp.message.flow_add flow_delete = ofp.message.flow_delete group_add = ofp.message.group_add group_mod = ofp.message.group_mod buf = ofp.OFP_NO_BUFFER # dmac table fields eth_dst_addr = "ethernet_dstAddr" def get_oxm(field_obj): """ Returns an oxm and an arg-dict for updating ...
Readon/mvpsample
src/gtkcustom.py
Python
lgpl-3.0
414
0.009662
""" Created on 2013-12-16 @author: readon @copyright: reserved @note: CustomWidget example for mvp """ from gi.repository import Gtk fr
om gi.repository import GObject class CustomEntry(Gtk.Entry): """ custom widget inherit from gtkentry. """ def __init__(self): Gtk.Entry.__init__(self) print "this is a custom widget loading"
GObject.type_register(CustomEntry)
arsenovic/clifford
clifford/tools/g3c/cuda.py
Python
bsd-3-clause
20,805
0.002547
from .cuda_products import gmt_func as gp_device from .cuda_products import imt_func as ip_device import numpy as np import numba.cuda import numba import math import random from . import * def sequential_rotor_estimation_chunks(reference_model_array, query_model_array, n_samples, n_objects_per_sample, mutation_pro...
# Check if they are the same other than a sign flip sum_abs = 0.0 for b_ind in range(32): sum_abs += abs(C1[b_ind] + C2[b_ind]) if sum_abs < 0.0001: set_as_unit_rotor_device(r_root) else: rotor_between_objects_dev...
mp, r_root) # Update the set rotor and the running rotor gp_device(r_root, r_set, r_temp) normalise_mv_copy_device(r_temp, r_set) gp_device(r_root, r_running, r_temp) normalise_mv_copy_device(r_temp, r_running) # Check if we have converged ...
tzshlyt/python-webapp-blog
www/wsgiapp.py
Python
gpl-3.0
1,257
0.006509
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging logging.basicConfig(level=logging.INFO) import os import time from datetime import datetime from transwarp import db from transwarp.web import WSGIApplication, Jinja2TemplateEngine from config import configs # init db: db.create_engine(**configs.db) de...
s小时前' % (delta // 3600) if delta < 604
800: return u'%s天前' % (delta // 86400) dt = datetime.fromtimestamp(t) return u'%s年%s月%s日' % (dt.year, dt.month, dt.day) # init wsgi app: wsgi = WSGIApplication(os.path.dirname(os.path.abspath(__file__))) template_engine = Jinja2TemplateEngine( os.path.join(os.path.dirname(os.path.abspath(__file__)...
toumorokoshi/transmute-core
transmute_core/tests/frameworks/test_aiohttp/test_full.py
Python
mit
3,409
0
i
mport pytest import json @pytest.mark.asyncio async def test_content_type_in_response(cli): """the content type should be specified in the
response.""" resp = await cli.get("/optional") assert 200 == resp.status assert resp.headers["Content-Type"] == "application/json" @pytest.mark.asyncio async def test_headers(cli): """the content type should be specified in the response.""" resp = await cli.get("/headers/") assert "boo" == res...
broadinstitute/cfn-pyplates
cfn_pyplates/core.py
Python
mit
18,588
0.000807
# Copyright (c) 2013 MetaMetrics, Inc. # # 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, publish, d...
nical JSON representation of a JSONableDict' return self.to_json(indent=2, separators=(',', ': ')) def add(self, child): """Add a child
node Args: child: An instance of JSONableDict Raises: AddRemoveError: :exc:`cfn_pyplates.exceptions.AddRemoveError` """ if isinstance(child, JSONableDict): self.update( {child.name: child} ) else: rai...
charlesporter/incubator-metron
metron-platform/metron-data-management/src/main/scripts/Whois_CSV_to_JSON.py
Python
apache-2.0
8,130
0.003444
#!/usr/bin/python """ Copyright 2014 Cisco Systems, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License
at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, so
ftware 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 permissions and limitations under the License. """ import sys import os import csv import json import multiprocessing imp...
zhaoshengshi/practicepython-exercise
exercise/8.py
Python
apache-2.0
1,238
0.005654
import random CHOICES = {1: 'Rock', 2: 'Paper', 3: 'Scissors'} RESULTS = [[0, -1, 1], [1, 0, -1], [-1, 1, 0]] def ask(): while True: s = input('Let\'s play the game:\n\t1. Rock\n\t2. Paper\n\t3. Scissors?\nWhat you choose?: ') if s.isdigit(): c = int(s) if not (1 <= c <= 3)...
ef compete(c, s): r = RESULTS[c-1][s-1] if r == 0: print('HaHa, no one wins!') elif r == -1: print('You\'re %s, I\'m %s, I win!' % (CHOICES[c], CHOICES[s])) else: print('You\'re %s, I\'m %s, You win!' % (CHOICES[c], CHOICES[s])) def another(): while True: ans = input...
ans == 'y': return True elif ans == 'n': return False else: print('Invalid input, try again!') continue if __name__ == '__main__': while True: c = ask() a = ai() compete(c, a) if not another(): break
lk-geimfari/elizabeth
mimesis/data/__init__.py
Python
mit
403
0
from .int.ad
dress import * from .int.code import * from .int.common import * from .int.datetime import * from .int.development import * from .int.file import * from .int.finance import * from .int.hardware import * from .int.internet import * from .int.path import * from .int.payment import * from .int.person import * from .int.sc...
t import *
wormer/funrun
src/funrun/match/urls.py
Python
mit
383
0.013055
from django.conf.urls
import url from . import views app_name = 'match' urlpatterns = [ url(r'^$', views.index, name='root'), url(r'^match/$', views.start_match, name='start_match'), url(r'^match/(?P<match_id>\d+)/$', views.match, name='match'), url(r'^match/(?P<match_id>\d+)/round/$', views.round, name='round'), url(r'^stats/$', v...
s, name='month_stats'), ]
ktbyers/pynet-ons-nov16
day2/func_ex3.py
Python
apache-2.0
841
0
#!/usr/bin/env python def my_func(x, y, z=20): return x + y + z my_list = [22, 17, 19] my_dict = { 'x':
13, 'y': 22, 'z': 1, } print return_val = my_func(10, 20, 30) print "Calling with three positional args: {}".format(return_val) return_val = my_func(x=10, y=20) print "Calling with two named args: {}".format(return_val) return_val = my_func(10, z=13, y=20) print "Calling with one positional and two named arg...
y'], z=['z']) print "Calling with three lists: {}".format(return_val) return_val = my_func(*my_list) print "Calling with *args: {}".format(return_val) return_val = my_func(**my_dict) print "Calling with **kwargs: {}".format(return_val) print
JointBox/jbaccess-server
jbaccess/jba_core/service/UserService.py
Python
gpl-3.0
481
0.002079
from typing
import Optional from django.contrib.auth.models import User from jba_core import exceptions def get_user_by_credentials(username: str, password: str) -> Optional[User]: try: user = User.objects.get(username=username) if not user.check_password(password):
raise exceptions.IncorrectCredentials return user except User.DoesNotExist: raise exceptions.UserNotFound except: raise exceptions.SomethingWrong
ciaron/djangofine
djangofine/wsgi.py
Python
gpl-3.0
395
0.002532
""" WSGI config for djangofine project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs
.djangoproject.com/en/1.6/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangofine.settings") from djan
go.core.wsgi import get_wsgi_application application = get_wsgi_application()
40423217/2016fallcadp_hw
pelicanconf.py
Python
agpl-3.0
1,944
0.005895
#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals AUTHOR = 'KMOL' SITENAME = '2016Fall 課程網誌 (虎尾科大MDE)' # 不要用文章所在目錄作為類別 USE_FOLDER_AS_CATEGORY = False #PATH = 'content' #OUTPUT_PATH = 'output' TIMEZONE = 'Asia/Taipei' DEFAULT_LANG = 'en' # Feed generation is usually not desire...
'articles': 0.5, 'indexes': 0.5, 'pages': 0.5 }, 'changefreqs': { 'articles': 'monthly', 'indexes': 'daily', 'pages': 'monthly' } } # search is for Tipu
e search DIRECT_TEMPLATES = (('index', 'tags', 'categories', 'authors', 'archives', 'search')) # for pelican-bootstrap3 theme settings #TAG_CLOUD_MAX_ITEMS = 50 DISPLAY_CATEGORIES_ON_SIDEBAR = True DISPLAY_RECENT_POSTS_ON_SIDEBAR = True DISPLAY_TAGS_ON_SIDEBAR = True DISPLAY_TAGS_INLINE = True TAGS_URL = "tags.html" C...
ncliang/zillowpy
zillowpy/base_request.py
Python
mit
737
0.016282
#/usr/bin/python """ Created on Apr 19, 2011 @author: ncliang """ import urllib import urllib2 from zillowpy import zillow_response class BaseRequest(object): """classdocs""" REQ_SUCCESS = 0 SERVICE_ERROR = 1 INVALID_ZWSID = 2 SERVICE_UNAVAILABLE = 3 API_UNAVAILA
BLE = 4 API_URL_TEMPLATE = "http://www.zillow.com/webservice/%s.htm" def __init__(self, api_url, parameters): """Constructo
r""" self._api_url = api_url self._parameters = parameters def ConstApiUrl(self): return self.API_URL_TEMPLATE % self.__class__.__name__ def Execute(self): resp_str = urllib2.urlopen( self._api_url, urllib.urlencode(self._parameters)).read() return zillow_response.ZillowResponse(resp_s...
Tinkerforge/brickv
src/brickv/plugin_system/plugins/red/red_tab_importexport_systemlogs.py
Python
gpl-2.0
9,261
0.004643
# -*- coding: utf-8 -*- """ RED Plugin Copyright (C) 2015, 2017 Matthias Bolte <[email protected]> Copyright (C) 2017 Ishraq Ibne Ashraf <[email protected]> red_tab_importexport_systemlogs.py: RED import/export system logs tab implementation This program is free software; you can redistribute it and/or mo...
og.log('Error: Log file is not UTF-8 encoded', bold=True) return if '\x00' in content: content = re.sub(r'(\n?)\x00+(\n?)', '\n[REBOOT]\n', content) if truncated_ref[0]: content = '[TRUNCATED]\n' + content log
.set_content(content) length = self.log_file.length if length > self.MAX_LOG_LENGTH: position = self.log_file.set_position(length - self.MAX_LOG_LENGTH, REDFile.ORIGIN_BEGINNING) length -= position truncated_ref[0] = True self.progre...
reyrodrigues/EU-SMS
temba/campaigns/models.py
Python
agpl-3.0
22,625
0.003624
from __future__ import absolute_import, unicode_literals from datetime import timedelta from django.db import models from django.db.models import Model from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from smartmin.models import SmartModel from temba.contacts.models import Cont...
er, modified_by=user) @classmethod def get_campaigns(cls, org, archived=None): qs = cls.objects.filter(org=org, is_active=True) if archived is not None: qs = qs.filter(is_archived=archived) return qs @classmethod def get_unique_name(cl
s, org, base_name, ignore=None): """ Generates a unique campaign name based on the given base name """ name = base_name[:255].strip() count = 2 while True: campaigns = Campaign.objects.filter(name=name, org=org, is_active=True) if ignore: ...
gnudo/grecoman
src/main.py
Python
gpl-3.0
29,750
0.004134
from ui_main import Ui_reco_mainwin from ui_dialogs import DebugCommand, Postfix from ui_slider import RangeSlider from io_img import Image from io_config import ConfigFile from arguments import ParameterWrap from connector import Connector from datasets import DatasetFolder from prj2sin import Prj2sinWrap from PyQt4.Q...
lf.loadTemplate(param)) # MENU create CPR with log correction QObject.connect(self.menuCreateFltp, SIGNAL("triggered()"), lambda param='createFltp': self.loadTe
mplate(param)) # MENU create Fltp QObject.connect(self.menuCreateFltpCpr, SIGNAL("triggered()"), lambda param='createFltpCpr': self.loadTemplate(param)) # MENU create Fltp+CPR QObject.connect(self.menuCreateSinosQuick, SIGNAL("triggered()"), lambda param='createSinosQuick': sel...
keplr-io/quiver
quiver_engine/imagenet_utils.py
Python
mit
2,049
0.000488
from __future__ import absolute_import, division, print_function ''' From https://github.com/fchollet/deep-learning-models ''' import json from keras.utils.data_utils import get_file from keras import backend as K import numpy as np CLASS_INDEX = None CLASS_INDEX_PATH = 'https://s3.amazonaws.com/deep-learning-m...
x[:, :, :, 2] -= 123.68 # 'RGB'->'BGR' x = x[:, :, :, ::-1] return x def decode_imagenet_predictions(preds, top=5): global CLASS_INDEX if len(preds.shape) != 2 or preds.shape[1] != 1000: raise ValueError('`decode_predictions` expects ' 'a batch of ...
0)). ' 'Found array with shape: ' + str(preds.shape)) if CLASS_INDEX is None: fpath = get_file('imagenet_class_index.json', CLASS_INDEX_PATH, cache_subdir='models') CLASS_INDEX = json.load(open(fpath)) results = [] f...
bealdav/OpenUpgrade
addons/hr_evaluation/hr_evaluation.py
Python
agpl-3.0
19,434
0.003911
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the G...
ext('Action Plan', help="If the evaluation does not meet the expectations, you can propose an action plan"),
'rating': fields.selection([ ('0', 'Significantly below expectations'), ('1', 'Do not meet expectations'), ('2', 'Meet expectations'), ('3', 'Exceeds expectations'), ('4', 'Significantly exceeds expectations'), ], "Appreciation", help="This is t...
gmimano/commcaretest
corehq/apps/data_interfaces/interfaces.py
Python
bsd-3-clause
3,559
0.003372
from django.utils.safestring import mark_safe from corehq.apps.data_interfaces.dispatcher import EditDataInterfaceDispatcher from corehq.apps.groups.models import Group from django.core.urlresolvers import reverse from corehq.apps.reports import util from corehq.apps.reports.datatables import DataTablesHeader, DataTabl...
ort_url(self): return reverse('data_interfaces_default', args=[self.request.project]) class CaseReassignmentInterface(CaseListMixin, DataInterface): name = ugettext_noop(
"Reassign Cases") slug = "reassign_cases" report_template_path = 'data_interfaces/interfaces/case_management.html' asynchronous = False ajax_pagination = True @property @memoized def all_case_sharing_groups(self): return Group.get_case_sharing_groups(self.domain) @property ...
Iconoclasteinc/tgit
testing/drivers/musician_tab_driver.py
Python
gpl-3.0
1,892
0.000529
from cute.matchers import named, with_text from tgit.ui.pages.musician_tab import MusicianRow from ._screen_driver import ScreenDriver class MusicianTabDriver(ScreenDriver): def shows_only_musicians_in_table(sel
f, *musicians): for index, musician in enumerate(musicians): instrument, name = musician self.lineEdit(with_text(instrument)).exists() self.lineEdit(with_text(name)).exists() def remove_musician(self, row): musician_row_driv
er(self, row - 1).remove_musician() def add_musician(self, instrument, name, row): self.button(named("_add_musician_button")).click() musician_row_driver(self, row - 1).change_instrument(instrument) musician_row_driver(self, row - 1).change_musician_name(name) def change_instrum...