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
PhoenixIgnis/Phoenix-Repo
Pygame/PyPet/Setup.py
Python
gpl-2.0
247
0.08502
from cx_Freeze import setup, Executable setup(name = "PyPet" , version = "0.0.1" ,
description = "PyPet by PhoenixIgnis, Indev: 0.0.1 " , executables = [Executable("main.py")]) ##cmd... ## python Setup.
py build
ProteinDF/QCLObot
qclobot/qcframe.py
Python
gpl-3.0
48,942
0.001224
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2002-2014 The ProteinDF project # see also AUTHORS and README. # # This file is part of ProteinDF. # # ProteinDF 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 Softwa...
def _get_db_path(self): db_path = o
s.path.abspath(os.path.join(self.work_dir, self._db_filename)) logger.debug("db_filename: {}".format(self._db_filename)) return db_path db_path = property(_get_db_path) def get_pdfarchive(self): """ pdfArchiveオブジェクトを返す """ logger.debug("get_pdfarchive db_path={}...
dsjin/ThinPotApplication
core.py
Python
apache-2.0
3,973
0.004027
# -*- coding: utf-8 -*- """ Core Application - manage multiplexer connected with Analog Discovery 2 | receive voltage from sensors to estimate distance API : wavefroms API Author: Thatchakon Jom-ud """ from ctypes import * from dwfconstants import * import sys import time class Core(): hdwf = c_i...
AnalogIOChannelNodeSet(self.hdwf, c_int(0), c_int(0), c_double(True)) # set voltage to 5 V self.dwf.FDwfAnalogIOChannelNodeSet(self.hdwf, c_int(0), c_int(1), c_double(5)) # enable negative supply self.dwf.FDwfAnalogIOChannelNodeSet(self.hdwf, c_int(1), c_int(0), c_double(True)) #...
ge to -5 V self.dwf.FDwfAnalogIOChannelNodeSet(self.hdwf, c_int(1), c_int(1), c_double(-5)) self.dwf.FDwfAnalogIOEnableSet(self.hdwf, c_int(enable)) def setup_digital_output(self): self.dwf.FDwfDigitalOutInternalClockInfo(self.hdwf, byref(self.hzSys)) self.dwf.FDwfDigitalOutEnableS...
vmendez/DIRAC
DataManagementSystem/scripts/dirac-dms-user-lfns.py
Python
gpl-3.0
5,259
0.038791
#!/usr/bin/env python ######################################################################## # $HeadURL$ ######################################################################## """ Get the list of all the user files. """ __RCSID__ = "$Id$" from DIRAC.Core.Base import Script days = 0 months = 0 years = 0 wildcard = ...
import gLogger from DIRAC.ConfigurationSystem.Client.Helpers.Registry import getVOForGroup from DIRAC.Core.Security.ProxyInfo import getProxyInfo from DIRAC.Resources.Catalog.FileCatalog import FileCatalog from DIRAC.Core.Utilities.List import ...
medelta import sys, os, time, fnmatch fc = FileCatalog() def isOlderThan( cTimeStruct, days ): timeDelta = timedelta( days = days ) maxCTime = datetime.utcnow() - timeDelta if cTimeStruct < maxCTime: return True return False withMetadata = False if days or months or years: withMetadata = True totalDays ...
nwjs/chromium.src
infra/config/scripts/milestones.py
Python
bsd-3-clause
4,423
0.012209
#!/usr/bin/env vpython3 # Copyright 2020 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. """Script for updating the active milestones for the chromium project. To activate a new chromium branch, run the following from the ...
e with id {milestone!r}: ' f'{milestones[milestone]}') milestones[milestone] = { 'name': f'm{milestone}', 'project': f'chromium-m{milestone}', 'ref': f'refs/branch-heads/{branch}', } milestones = { k: milestones[k] for k in so
rted(milestones, key=numeric_sort_key) } return json.dumps(milestones, indent=4) + '\n' def activate_cmd(args): with open(args.milestones_json) as f: milestones = json.load(f) milestones = add_milestone(milestones, args.milestone, args.branch) with open(args.milestones_json, 'w') as f: f.write(mil...
scitran/core
tests/integration_tests/python/test_download.py
Python
mit
26,062
0.0033
import cStringIO import os import tarfile import zipfile def test_download(data_builder, file_form, as_admin, api_db): project = data_builder.create_project(label='project1') session = data_builder.create_session(label='session1') session2 = data_builder.create_session(label='session1') session3 = dat...
plus'], project: ['plus', 'minus'] file_name = 'test.csv' as_admin.post('/acquisitions/' + acquisit
ion + '/files', files=file_form( file_name, meta={'name': file_name, 'type': 'csv'})) as_admin.post('/acquisitions/' + acquisition2 + '/files', files=file_form( file_name, meta={'name': file_name, 'type': 'csv'})) as_admin.post('/acquisitions/' + acquisition3 + '/files', files=file_form( ...
petrjasek/superdesk-core
apps/archive_broadcast/__init__.py
Python
agpl-3.0
930
0.002151
# -*- coding: utf-8;
-*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license import logging from flask_babel...
mport superdesk from .broadcast import ArchiveBroadcastResource, ArchiveBroadcastService, ARCHIVE_BROADCAST_NAME logger = logging.getLogger(__name__) def init_app(app) -> None: endpoint_name = ARCHIVE_BROADCAST_NAME service = ArchiveBroadcastService(endpoint_name, backend=superdesk.get_backend()) Archiv...
jmorton/yatsm
yatsm/cache.py
Python
mit
8,031
0.000249
""" Functions related to writing to and retrieving from cache files """ import os import numpy as np from log_yatsm import logger _image_ID_str = 'image_IDs' def get_line_cache_name(dataset_config, n_images, row, nbands): """ Returns cache filename for specified config and line number Args: dataset_...
an the filenames to read and the line to read Raises: ValueError: Raise error if old cache file does not record `image_IDs` """ images = np.asarray(images) image_IDs = np.asarray(image_IDs) # Cannot proceed if old cache file doesn't store filen
ames old_cache = np.load(old_cache_filename) if _image_ID_str not in old_cache.files: raise ValueError('Cannot update cache.' 'Old cache file does not store image IDs.') old_IDs = old_cache[_image_ID_str] old_Y = old_cache['Y'] nband, _, ncol = old_Y.shape # Cre...
aioworkers/aioworkers
aioworkers/worker/supervisor.py
Python
apache-2.0
3,772
0
import asyncio import logging import random from .base import Worker logger = logging.getLogger(__name__) class Supervisor(Worker): """ config: children: Union[int, list[str], list[dict]] - count or list child: Mapping - config for child worker """ def __init__(self, *args, **kwargs...
if add:
conf = conf.new_child(add) return cls(conf, context=self.context, loop=self.loop) async def get(self): return await self.input.get() async def put(self, *args, **kwargs): return await self.output.put(*args, **kwargs) async def work(self): children = list(self._children....
martindimondo/PyC8
chip8/operations.py
Python
bsd-3-clause
6,673
0.008842
from __future__ import print_function import re import logging logging.basicConfig(level=logging.INFO) class Executor(object): def __init__(self, op_map): processed = {} for pattern, f in op_map.iteritems(): s = self._build_pattern_groups(pattern.lower()) processed[re.com...
t.index_reg = nnn context.pc += 2 def pop_stack(context): logging.info('Returning from a subroutine') context.pc = context.stack.pop() def call_rca1082(context, address): #TODO print("operation not implemented yet:", address) context.pc += 1 def clear(context): logging.info('Clearing screen'...
logging.info('Calling subroutine at 0x%2x address' % address) context.pc += 2 context.stack.append(context.pc) context.pc = address def skip_equal(context, x, nnn, ifeq=True): logging.info('Skip if V[X] === NNN is %s' % ifeq) if (context.v[x] == nnn) == ifeq: context.pc += 2 context.p...
rlucioni/cs171-hw4-lucioni-renzo
ProblemGeoUSA/aggregator.py
Python
mit
950
0.002105
import json from datetime import datetime # In order for this script to work, the original allData2003_2004.json # file must be downloaded and placed in the data directory! f = open('../data/allData2003_2004.json', 'r') g = open('../data/aggregated-radiation-data.json', 'wb') raw = json.load(f) # Since month-by-mon...
tion isn't required for the final # visualization, I've chosen to aggregate by hour only. aggregated = {} for station, measurements in raw.iteritems(): # Note my use of a 24-element array to hold hourly sums. aggregated[station] = {'sum': 0, 'hourly': [0]*24} for measurement in measurements: value ...
date = datetime.strptime(measurement['date'], "%b %d, %Y %I:%M:%S %p") ix = int(date.strftime('%H')) aggregated[station]['hourly'][ix] += value g.write(json.dumps(aggregated, indent=2)) f.close() g.close()
utarsuno/urbtek
project_euler_problems/problems/problem_019.py
Python
apache-2.0
1,284
0.014019
# coding=utf-8 """ This module, problem_019.py, solves the nineteenth project euler problem. """ from project_eul
er_problems.problem import Pr
oblem from datetime import date ''' You are given the following information, but you may prefer to do some research for yourself. 1 Jan 1900 was a Monday. Thirty days has September, April, June and November. All the rest have thirty-one, Saving February alone, Which has twenty-eight, rain or shine. And on leap years...
pajlada/pajbot
pajbot/managers/websocket.py
Python
mit
4,650
0.002796
from typing import List, Any import json import logging import threading from pathlib import Path log = logging.getLogger("pajbot") class WebSocketServer: clients: List[Any] = [] def __init__(self, manager, port, secure=False, key_path=None, crt_path=None, unix_socket_path=None): self.manager = mana...
return self.server = WebSocketServer(self, port, ssl, key_path, crt_path, unix_socket_path) except: log.exception("Uncaught exception in WebSocketManager") def emit(self, event, data={}): if self.server: payload = json.dumps({"event": event, "data...
: client.sendMessage(payload, False) @staticmethod def on_log_message(message, isError=False, printed=False): if isError: log.error(message["message"]) else: pass # log.debug('on_log_message({})'.format(message['message']))
pferreir/indico
indico/modules/search/controllers.py
Python
mit
2,694
0.002598
# This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from flask import jsonify, session from marshmallow import INCLUDE, fields from marshmallow_enum import En...
yCategoryBase): def _process(self): return WPCategorySearch.render_template('category_search.html', self.category) class RHEventSearchDisplay(RHDisplayEventBase): def _process(self): return WPEventSearch.render_template('event_search.html', self.event) class RHAPISearch(RH): """API for s...
esides pagination, filters or placeholders may be passed as query parameters. Since `type` may be a list, the results from the search provider are not mixed with the InternalSearch. """ @use_kwargs({ 'page': fields.Int(missing=None), 'q': fields.String(required=True), 'type': fi...
ryansb/gitsniffer
gitsniffer/cli.py
Python
mit
2,420
0.003719
from collections import namedtuple import click import os import pygit2 import requests import sys GitObj = namedtuple("GitObj", "fname prefix hash") def hash_gen(index): for entry in index: fullhex = entry.hex fname = entry.path prefix, h = fullhex[0:2], fullhex[2:] yield GitObj...
log)) def grab_refs(url): make_dirs('refs', 'refs/heads'
, 'refs/remotes', 'refs/remotes/origin') ref_jazz = ['refs/heads/master', 'refs/remotes/origin/HEAD'] for ref in ref_jazz: download_file("./{0}".format(ref), "{0}/{1}".format(url, ref)) def grab_meta(url): meta_files = ['COMMIT_EDITMSG', 'config', 'description', 'FETCH_HEAD', 'HEA...
olitheolix/qtmacs
doc/source/code_snippets/tut_1_1.py
Python
gpl-3.0
696
0
""" Tutorial 1: a "Hello world" macro. """
# Import the module with the global variables and the macro base class. import qtmacs.qte_global as qte_global from qtmacs.base_macro import QtmacsMacro # Get a reference to the main instance
of Qtmacs. qteMain = qte_global.qteMain class HelloWorld(QtmacsMacro): """ Prints 'Hello world.' to the console. |Signature| * *applet*: '*' * *widget*: '*' """ def __init__(self): super().__init__() self.qteSetAppletSignature('*') self.qteSetWidgetSignature('*') ...
fake-name/ReadableWebProxy
WebMirror/management/rss_parser_funcs/feed_parse_extractHutnovelBlogspotCom.py
Python
bsd-3-clause
745
0.028188
def extractHutnovelBlogspotCom(item): ''' Parser for 'hutnovel.blogspot.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('True Star', 'True Star',
'translated'), ('please start your show', 'please start your show', 'translated'), ('PRC', 'PRC',
'translated'), ('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, tl_type in tagmap: if tagname in item['tags']: return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
gaoxiaofeng/troubleShooting
src/troubleshooting/framework/output/welcome.py
Python
apache-2.0
2,569
0.006596
# -*- coding: utf-8 -*- from troubleshooting.framework.output.output import OutPut from troubleshooting.framework.libraries.library import singleton from troubleshooting.framework.modules.configuration import ConfigManagerInstance @singleton class welcome(object): def __init__(self): super(self.__class__...
\ |
\ | \ / | ____________------\ | | | | || / | | | || | | | | || | | | | || | Trou...
Ingenico-ePayments/connect-sdk-python3
tests/unit/test_meta_data_provider.py
Python
mit
5,371
0.005958
# -*- coding: UTF-8 -*- import base64 import unittest from ingenico.co
nnect.sdk.defaultimpl.default_marshaller import DefaultMarshaller from ingenico.connect.sdk.domain.metadata.shopping_cart_extension import ShoppingCartExtension from ingenico.connect.sdk.meta_data_provider import MetaDataProvider from ingenico.connect.sdk.request_header import RequestHeader class MetaDataProviderTest...
ta_data_headers_full(self): """Tests that the MetaDataProvider can construct meta_data_headers when supplied with a full shopping cart""" shopping_cart_extension = ShoppingCartExtension("Ingenico.creator", "Extension", "1.0", "ExtensionId") meta_data_provider = MetaDataProvider("Ingenico", shopp...
Alex4913/PyOpenGL-Boilerplate
src/display.py
Python
mit
3,803
0.016303
from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * import camera import time class Display(object): # Inheritrance convinience functions def init(self): pass def close(self): pass def mouse(self, mouseButton, buttonState, x, y): pass def mouseMotion(self, x, y, dx, dy): pass def pa...
self.timerFired(value) glutTimerFunc(self.timerDelay, self.timerFired, value +
1) # Wrapper to handle as much GL as possible def drawWrapper(self): self.preGL() # Let the camera draw the view self.camera.draw(self.draw, self.pos, self.ypr) self.postGL() # Wrapper to pass change in position as well as position # Only called when mouse motion and button pressed def...
yunojuno/elasticsearch-django
elasticsearch_django/management/commands/__init__.py
Python
mit
2,479
0.00121
"""Base command for search-related management commands.""" from __future__ import annotations import argparse import builtins import logging from typing import Any, Optional, Union from django.core.management.base import BaseCommand from elasticsearch.exceptions import TransportError CommandReturnType = Optional[Uni...
} except Except
ion as ex: # noqa: B902 logger.warning("Error running command: %s", ex) data = { "index": index, "status": "N/A", "reason": str(ex), } finally: logger.info(data)
tapomayukh/projects_in_python
classification/Classification_with_kNN/Single_Contact_Classification/Time_Window/test10_cross_validate_objects_400ms.py
Python
mit
4,258
0.015031
# Principal Component Analysis Code : from n
umpy import mean,cov,double,cumsum,dot,linalg,array,rank,size,flipud from pylab import * import numpy as np import matplotlib.pyplot as pp #from enthought.mayavi import mlab import scipy.ndimage as ni import roslib; roslib.load_manifest('sandbox_tapo_darpa_m3') import rospy #import hrl_lib.mayavi2_u
til as mu import hrl_lib.viz as hv import hrl_lib.util as ut import hrl_lib.matplotlib_util as mpu import pickle from mvpa.clfs.knn import kNN from mvpa.datasets import Dataset from mvpa.clfs.transerror import TransferError from mvpa.misc.data_generators import normalFeatureDataset from mvpa.algorithms.cvtranserror im...
wackerl91/luna
tests/testgame.py
Python
gpl-3.0
1,774
0.001127
import unittest from resources.lib.model.game import Game class TestGame(unittest.TestCase): def testGameMergeSelfNone(self): game1 = Game('Name') game2 = Game('Name') game2.genre = ['Action', 'Adventure'] game2.posters = ['/path/to/poster'] game2.fanarts = ['path/to/art/...
game1.fanarts = ['path/to/art/1-1', 'path/to/art/1-2', 'path/to/art/1-3'] game2 = Game('Name') game2.genre = ['Action', 'Adventure'] game2.posters = ['/path/t
o/poster'] game2.fanarts = ['path/to/art/1', 'path/to/art/2', 'path/to/art/1-3'] game1.merge(game2) self.assertEqual(game1.genre, ['Action', 'Adventure', 'Shooter']) self.assertEqual('/path/to/poster/original' in game1.posters, True) self.assertEqual('/path/to/poster' in game1....
sassoftware/conary
conary/local/sqldb.py
Python
apache-2.0
94,996
0.003537
# # Copyright (c) SAS Institute Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in w...
version, isnSet, use) tuples, along with a isPresent flag """ def __init__(self, db): self.db = db schema.createInstances(db) def iterNames(self): cu = self.db.cursor() cu.execute("SELECT DISTINCT troveName FROM Instances " "WHERE isPresent=1") ...
.execute("SELECT instanceId FROM Instances " "WHERE troveName=? AND isPresent=1", name) return cu.fetchone() != None def iterByName(self, name): cu = self.db.cursor() cu.execute("SELECT instanceId, versionId, troveName, flavorId FROM " ...
olivierdm/rviz
src/test/config_sample.py
Python
gpl-2.0
2,859
0.022036
#!/usr/bin/env python import roslib; roslib.load_manifest('rviz') import sys #setattr(sys, 'SELECT_QT_BINDING', 'pyside') # Shiboken setattr(sys, 'SELECT_QT_BINDING', 'pyqt') # SIP import python_qt_binding.QtBindingHelper # @UnusedImport from QtGui import * from QtCore import * import rviz c = rviz.Config() c.mapSet...
for i in range( 0, tools.listLength() ): print " class:", tools.listChildAt( i ).mapGetChild( "Class" ).getValue() w = rviz.YamlConfigWriter() f
irst_string = w.writeString( c ) print "Entire default.rviz written to a string:" print first_string r2 = rviz.YamlConfigReader() c2 = rviz.Config() r2.readString( c2, first_string ) second_string = w.writeString( c2 ) if first_string == second_string: print "reading and re-writing...
konata39/chatbot-backend
trips/migrations/0008_article.py
Python
gpl-3.0
655
0.003053
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2016-09-06 07:35 from __future__ import unicode_literals from django.db import migrations, models class Mig
ration(migrations.Migration): dependencies = [ ('trips', '0007_post'), ] operations = [ migrations.CreateModel( nam
e='Article', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('content', models.TextField(verbose_name='Content')), ('title', models.CharField(max_length=50, verbose_name='Title')), ], ...
quantmind/pulsar
pulsar/utils/profiler.py
Python
bsd-3-clause
521
0
import cProfile import pstats class Profiler: def __init__(self, sortby=None): self.profiler = None self.sor
tby = sortby or ('cumtime',) def __enter__(self): self.profiler = cProfile.Profile(
) self.profiler.enable() return self def __exit__(self, exc_type, exc_val, exc_tb): self.profiler.disable() self.write_stats() def write_stats(self): p = pstats.Stats(self.profiler) p.strip_dirs().sort_stats(*self.sortby).print_stats()
lsbardel/django-extracontent
extracontent/tests/__init__.py
Python
bsd-3-clause
249
0.008032
from extracontent.tests.testing import * def run(): import sys from django.conf import settings from django.test.simple import run_tests failures = run_tests(['extracon
tent'], verbosity=1
) if failures: sys.exit(failures)
CKboss/VirtualJudgePY
Handlers/ProblemHandler.py
Python
gpl-2.0
4,706
0.003187
import tornado.web import tornado.gen from tornado.concurrent import run_on_executor
from concurrent.futures import ThreadPoolExecutor from tools.dbcore import ConnPool from tools.encode import UTF8StrToBase64Str, Base64StrToUTF8Str from UIModule.MsgModule import renderMSG from Crawler.BnuVJCrawler.BnuVJCrawler import BnuVJCrawler class ProblemHandler(tornado.web.RequestHandler): executor = Thr...
t_argument('cid', -1) print('oj: ' + oj + ' pid: ' + pid) D = yield self.getProblem(oj, pid) if D is None : yield self.CrawlerOnLine(oj,pid) D = yield self.getProblem(oj, pid) if D is None : self.write(renderMSG('Can\'t find this problem',waittime=1...
analytehealth/django-analytics
djanalytics/tests/test_exit_page.py
Python
bsd-2-clause
2,477
0.002019
import datetime from django.core.urlresolvers import reverse from django.utils import timezone from djanalytics import models from djanalytics.tests.base_chart_test import BaseChartTest class TestExitPage(BaseChartTest): def test_exit_page(self): for i in range(3): first_page = models.Reques...
ip_address='192.168.1.%s' % i ) mode
ls.RequestEvent.objects.create( client=self.dja_client, path='/last_page', ip_address=first_page.ip_address, tracking_key=first_page.tracking_key, tracking_user_id=first_page.tracking_user_id ) first_page = models.Reques...
wiheto/fetchopenfmri
fetchopenfmri/__init__.py
Python
mit
28
0
import fe
tchopenfmri.fetch
jeffery9/mixprint_addons
ineco_purchase_sequence/__openerp__.py
Python
agpl-3.0
1,458
0.002058
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2012 - INECO PARTNERSH
IP LIMITED (<http://www.ineco.co.th>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any la
ter version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of th...
inspectorbean/spat
po/forms.py
Python
gpl-3.0
1,543
0.007129
from django import forms from .models import PO, Line_PO, Cost_Center from vendor.models import Supplier, Publisher from quote.models import Quote from django.contrib.auth.models import User cla
ss POForm(forms.Form): supplier = forms.ModelChoiceField(queryset=Supplier.objects.all()) blanket = forms.BooleanField(required=False) auth = forms.ModelChoiceField(queryset=User.objects.all()) status = forms.CharField(strip=True) #make this a dropdown? comments = forms.CharFiel
d(strip=True, required=False) #add tax handling tax = forms.BooleanField(required=False) tax_amt = forms.DecimalField(max_digits=5, decimal_places=5, required=False) quote = forms.ModelChoiceField(queryset=Quote.objects.all(), required=False) budgeted = forms.BooleanField() class LineForm(forms.For...
50wu/gpdb
gpMgmt/bin/gppylib/test/unit/test_unit_gppkg.py
Python
apache-2.0
3,975
0.00327
from mock import * from .gp_unittes
t import * from gppylib.programs.gppkg import GpPkgProgram import sys class GpPkgProgramTestCase(GpTestCase): def setUp(self): self.mock_cmd
= Mock() self.mock_gppkg = Mock() self.mock_uninstall_package = Mock() self.apply_patches([ patch('gppylib.operations.package.logger', return_value=Mock(spec=['log', 'info', 'debug', 'error'])), patch('gppylib.programs.gppkg.Command', return_value=self.mock_cmd), ...
smilefreak/selectionTools
selection_pipeline/multipipeline.py
Python
mit
15,215
0.000986
# Multipopulation script calls the selection # pipeline for each population that we need # to do then zips up and runs a script to p# each of the cross population # statistics once # it has all finished. # institution: University of Otago # author: James Boocock # # # requires that the selection pipeline # installed. ...
Read the config file and save the results in a dictionary """ config = ConfigParser.ConfigParser() config.read(options.config_file)
config_parsed = {} logger.debug(config.sections()) for section in config.sections(): logger.debug(section) opts = config.options(section) config_parsed[section] = {} for op in opts: logger.debug(op) try: config_parsed[section][op] = con...
credp/lisa
external/devlib/devlib/utils/android.py
Python
apache-2.0
35,289
0.001955
# Copyright 2013-2018 ARM Limited # # 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...
if line.startswith('launchable-activity:'): match = self.name_regex.search(line) self.activity = match.group('name') elif line.startswith('native-code'): apk_abis = [entry.strip() for entry in li
ne.split(':')[1].split("'") if entry.strip()] mapped_abis = [] for apk_abi in apk_abis: found = False for abi, architectures in ABI_MAP.items(): if apk_abi in architectures: mapped_abis.append(abi...
4Subsea/evapy
evapy/_optimize.py
Python
mit
1,491
0
''' Custom optimization routines for distributions where ML estimators perform poorly or do not exist. ''' import numpy as np def _residual_error(self, theta, x, y_fun, **kwargs): ''' Return special purspose lsq objective error function to minimize. Method is overwritten to hook into scipy.stats optimiza...
) and np.isinf
(self.b).all(): Nbad = 0 else: cond0 = (x <= self.a) | (self.b <= x) Nbad = sum(cond0) if Nbad > 0: x = x[~cond0] N = len(x) # Refactor ecdf out into own code at some point. f_ecdf = np.array([(i + 1 - 0.3)/(N + 0.4) for i in range(N)]) error = np.abs(y_fun...
rananda/cfme_tests
cfme/tests/configure/test_tag.py
Python
gpl-2.0
7,263
0.00179
# -*- coding: utf-8 -*- import fauxfactory import pytest from cfme.configure.configuration import Category, Tag from cfme.rest.gen_data import a_provider as _a_provider from cfme.rest.gen_data import categories as _categories from cfme.rest.gen_data import dialog as _dialog from cfme.rest.gen_data import services as _...
s(request, rest_api_modscope, categories_mod) @pytest.fixture(scope="module") def service_catalogs(self, request, rest_api_modscope): return _service_catalogs(request, rest_api_modscope) @pytest.fixture(scope="module") def tenants(self, request, rest_api_modscope): return _tenants(requ...
fixture(scope="module") def dialog(self): return _dialog() @pytest.fixture(scope="module") def services(self, request, rest_api_modscope, a_provider, dialog, service_catalogs): try: return _services(request, rest_api_modscope, a_provider, dialog, service_catalogs) except...
lmazuel/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2017_11_01/models/application_gateway_sku.py
Python
mit
1,567
0
# 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 cause incorrect behavior and ...
s ApplicationGatewaySku(Model): """SKU of an application gateway. :param name: Name of an application gateway SKU. Possible values include: 'Standard_Small', 'Standard_Medium', 'Standard_Large', 'WAF_Medium', 'WAF_Large' :type name: str or ~azure.mgmt.network.v2017_11_01.models.ApplicationGa...
Hybrid-Cloud/conveyor
conveyor/conveyorheat/engine/resources/huawei/elb/listener.py
Python
apache-2.0
9,416
0
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # ...
self.TCP_TIMEOUT,
'protocol': self.PROTOCOL, 'tcp': self.TCP}) raise exception.StackValidationFailed(message=msg) def _resolve_attribute(self, name): if not self.resource_id: return ls = self.client().listener.get(self.resource_id) if name == self.MEMBE...
tobiasgehring/qudi
logic/tasks/refocus.py
Python
gpl-3.0
2,217
0.001353
# -*- coding: utf-8 -*- """ Confocal-refocus task. Qudi is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Qudi is distributed in the hope tha...
es a confocal focus optimisation. """ def __init__(self, **kwargs): super().__init__(**kwargs) print('Task {0} added!'.format(self.name)) def startTask(self): """ Get position from scanning device and do the refocus """ pos = self.ref['optimizer']._scanning_device.get_scann...
# self.ref['optimizer'].start_refocus(caller_tag='task') def runTaskStep(self): """ Wait for refocus to finish. """ time.sleep(0.1) return self.ref['optimizer'].isstate('locked') def pauseTask(self): """ pausing a refocus is forbidden """ pass def resumeTask(s...
whiplash01/pyCycle
src/pycycle/test/test_duct.py
Python
apache-2.0
1,762
0.016459
import unittest from openmdao.main.api import set_as_top from openmdao.util.testutil import assert_rel_error from pycycle import duct, flowstation class DuctTestCase(unittest.TestCase): def test_start(self): comp = set_as_top(duct.Duct()) comp.dPqP = 0 comp.Q_dot = -237.8 comp...
assert_rel_error(self,comp.Fl_O.area, 221.4, .
005) #vary something comp.dPqP = .1 comp.run() assert_rel_error(self,comp.Fl_O.W, 1.080, .005) assert_rel_error(self,comp.Fl_O.Pt, .306, .005) assert_rel_error(self,comp.Fl_O.Tt, 540.00, .005) assert_rel_error(self,comp.Fl_O.rhos, .0013783, .005) assert_...
karttrak/project-euler
14.py
Python
mit
380
0.036842
def collatz(start): cur = start numbers =
[start] while cur != 1: if cur < start: return counts[cur] + len(numbers)-1 if cur%2 == 0: numbers.append(int(cur/2)) else: numbers.append(3*cur + 1) cur = numbers[len(numbers)-1] return len(numbers) counts = [0]
for j in range(1, 1000000): count = collatz(j) counts.append(count) print(max(counts))
NigelCleland/Tessen
Tessen/generate.py
Python
bsd-3-clause
15,217
0.001774
""" """ import pandas as pd import numpy as np from OfferPandas import Frame, load_offerframe import sys import os import datetime import time def create_fan(energy, reserve, fName=None, return_fan=True, break_tp=False, force_plsr_only=True, verbose=False, *args, **kargs): """ A wrapper which ...
nd visualised usin
g the visualise functionality. Parameters: ----------- energy: An energy offer frame, fans will be created for every permutation in this frame. reserve: The corresponding reserve offer frame. Returns ------- DataFrame: A DataFrame containing the fan object """ stat...
lino-framework/lino
lino/management/commands/install.py
Python
bsd-2-clause
1,888
0.001589
# -*- coding: UTF-8 -*- # Copyright 2019-2021 Rumma & Ko Ltd # License: GNU Affero General Public License v3 (see file COPYING for details) import subprocess from rstgen.utils import confirm from django.core.management.base import BaseCommand from django.conf import settings def runcmd(cmd, **kw): # same code as in...
parser.add_argument('--noi
nput', action='store_false', dest='interactive', default=True, help='Do not prompt for input of any kind.') parser.add_argument('-l', '--list', action='store_true', dest='list', default=False, help="J...
owlabs/incubator-airflow
airflow/contrib/hooks/gcs_hook.py
Python
apache-2.0
23,732
0.001601
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the #...
' 'must be different, not both the same: bucket=%s, object=%s' % (source_bucket, source_object)) if not source_bucket or not source_object: raise ValueError('source_bucket and source_object cannot be empty.') client = self.get_conn() source_bucket = ...
estination_bucket = client.bucket(destination_bucket) token, bytes_rewritten, total_bytes = destination_bucket.blob( blob_name=destination_object).rewrite( source=source_object ) self.log.info('Total Bytes: %s | Bytes Written: %s', total_bytes, byt...
yunlzheng/chat
chat/handler/tumblr.py
Python
mit
664
0.00753
#coding: utf-8 __author__ = 'zheng' import re import tornado.gen from tornado.httpclient import AsyncHTTPClient from BeautifulSoup import Beau
tifulSoup from chat.handler import BaseHandler class TumblrHandler(BaseHandler): @tornado.gen.coroutine def get(self): http_client = AsyncHTTPClient() http_response = yield http_client.fetch("https://www.tumblr.com/") content = http_response.body soup = BeautifulSou...
img')[0] pattern=re.compile(r"""<img\s.*?\s?src\s*=\s*['|"]?([^\s'"]+).*?>""",re.I) m = pattern.findall(str(img)) self.write(m[0])
benjaminy/ZombieComm
server.py
Python
mit
845
0.004734
import pyaudio import collections import threading ''' ZombieComm radio server ''' sound_frames = collections.deque() def record(): global sound_frames CHUNK = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 2 RATE = 10000 p = pyaudio.PyAudio() stream = p.open(format=FORMAT, ...
hile True: data = stream.read(CHUNK) sound_frames.append(data) if __name__ == '__main__': ''' main method simply prints recorded data right now ''' t = threading.Thread(target=record) t.start() while True: try:
if len(sound_frames) > 0: print (sound_frames.popleft()) except: pass
felipecruz/coopy
tests/unit/test_network_select.py
Python
bsd-3-clause
8,077
0.004086
import six import sys import pytest import socket from coopy.network.network import COPYNET_HEADER from coopy.network.default_select import CopyNet, CopyNetSlave, _HEADER_SIZE _str_to_bytes = lambda x: x.encode('utf-8') if type(x) != bytes else x if six.PY3 or 'PyPy' in sys.version: socket_select_error = ValueEr...
o_bytes('copynet')) actors = [actor1, actor2] #guarantee that the client is already connected import time time.sleep(0.2) copynet_client1 = list(copynet.clientmap.values())[0] copynet.send_direct(copynet_client1.client,
_str_to_bytes("message")) time.sleep(0.2) if six.PY3: import pickle else: import cPickle as pickle import struct, zlib, pickle size = struct.calcsize(COPYNET_HEADER) #one of the 2 reads will raise an error and the other will work error_count = 0 for actor in actors: ...
heprom/pymicro
pymicro/core/samples.py
Python
mit
218,980
0.001233
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """DataPlatform module for the management of multimodal mechanical datasets. The `samples` module provides a base class `SampleData` implementing a generic data model and data paltform API, allowing to define by inheritance specific data platform classes for specific mech...
= verbose self.aut
odelete = autodelete self.autorepack = autorepack if os.path.exists(self.h5_path) and overwrite_hdf5: self._verbose_print('-- File "{}" exists and will be ' 'overwritten'.format(self.h5_path)) os.remove(self.h5_path) os.remove(self.xdm...
thepian/thepian-lib
fs/__init__.py
Python
gpl-3.0
784
0.017857
from file_util import * from walk import walk from listdir
import listdir,filterdirs from distutils.dir_util import copy_tree from manip import link,symlink,first_exists def makedirs(*elements): import os from os.path import exists, join dirs = join(*elements) if not exists(dirs): os.makedirs(dirs) mkpath = makedirs makepath = makedirs def ma...
Take a list of directory names(string or tuple) and create a tree in base_dir """ import os from os.path import exists, join for dir in dirs: if type(dir) == tuple: dir = join(dir) dir = join(base_dir,dir) if not exists(dir): os.makedirs(dir) """ cl...
tensorflow/datasets
tensorflow_datasets/scripts/documentation/doc_utils_test.py
Python
apache-2.0
5,983
0.00117
# coding=utf-8 # Copyright 2022 The TensorFlow Datasets 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 appl...
description='Config description.', ), ] class DocumentNightlyDatasetsTest(tfds.tes
ting.TestCase): def test_full_names_to_dict(self): full_names_dict = doc_utils._full_names_to_dict([ 'ds1/c1/1.0.0', 'ds1/c1/2.0.0', 'ds1/c2/2.0.0', 'ds2/1.0.0', 'ds2/2.0.0', ]) self.assertEqual( full_names_dict, { 'ds1': { 'c1':...
wummel/patool
patoolib/programs/shar.py
Python
gpl-3.0
1,074
0.001862
# -*- coding: utf-8 -*- # Copyright (C) 2012-2015 Bastian Kleineidam # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. #...
l 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/l...
Create a SHAR archive.""" cmdlist = [util.shell_quote(cmd)] cmdlist.extend([util.shell_quote(x) for x in filenames]) cmdlist.extend(['>', util.shell_quote(archive)]) return (cmdlist, {'shell': True})
Snailed/group-generator
gruppeapp/apps.py
Python
mit
158
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.apps import AppConfig class Gr
uppeappCon
fig(AppConfig): name = 'gruppeapp'
gsnbng/erpnext
erpnext/hr/doctype/payroll_period/payroll_period.py
Python
agpl-3.0
4,141
0.022941
# -*- coding: utf-8 -*- # Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe import _ from frappe.utils import date_diff, getdate, formatdate, cint, month_diff, flt from frappe.model.docu...
e)s and end_date > %(end_date)s)) """ if not self.name: # hack! if name is null, it could cause problems with != self.name = "New "+self.doctype overlap_doc = frappe.db.sql(query.format(self.doctype),{ "start_date": self.start_date, "end_date": self.end_date, "name": self.name, "company": ...
te(self.start_date), formatdate(self.end_date)) \ + """ <b><a href="#Form/{0}/{1}">{1}</a></b>""".format(self.doctype, overlap_doc[0].name) \ + _(") for {0}").format(self.company) frappe.throw(msg) def get_payroll_period_days(start_date, end_date, employee, company=None): if not company: company = frappe...
SShehriyar/Tuition-Manager
app/gui/teacher.py
Python
gpl-3.0
9,541
0
"""Manipulation of teacher objects.""" import gi from gi.repository import Gtk from app.constants import class_list, modify_teacher_list from app.teacher import Teacher gi.require_version('Gtk', '3.0') class AddTeacherMenu(Gtk.Window): """Window that provides entry boxes to add a new teacher.""" def __init...
text() if not new_value: no_value_dialog = Gtk.MessageDialog(self, 0, Gtk.MessageType.INFO, Gtk.ButtonsType.OK, "Please enter the new value")
no_value_dialog.run() no_value_dialog.destroy() return Teacher.modify_teacher(registration, the_option, new_value) complete_dialog = Gtk.MessageDialog(self, 0, Gtk.MessageType.INFO, Gtk.ButtonsType.OK, ...
meraki-analytics/cassiopeia-datastores
cassiopeia-diskstore/cassiopeia_diskstore/status.py
Python
mit
1,801
0.004997
from typing import Type, TypeVar, MutableMapping, Any, Iterable from datapipelines import DataSource, DataSink, PipelineContext, Query, validate_query from cassiopeia.data import Platform, Region from cassiopeia.dto.status import ShardStatusDto from cassiopeia.datastores.uniquekeys import convert_region_to_platform f...
has("platform").as_(Platform) @get.register(ShardStatusDto) @validate_query(_validate_g
et_status_query, convert_region_to_platform) def get_status(self, query: MutableMapping[str, Any], context: PipelineContext = None) -> ShardStatusDto: key = "{clsname}.{platform}".format(clsname=ShardStatusDto.__name__, platform=query["platform"].value) return ShardStatusDto(self._get(key)) @pu...
ashumallik/Compression-Engine
huffman.py
Python
gpl-3.0
2,799
0.026882
import huffman import bitstring from bitstring import BitArray myfile = open("foo.txt","r") allofthefile = myfile.read() myfile.close() mycharset = u"\u000A" mycharset = mycharset + " abcdefghijklmnopqrstuvwxyz"+\ "ABCDEFGHIJKLMNOPQRSTUVWXYZ"+\ "0123456789!#$%&'()\"*+,-./:;<=>?@[\]^_`{|}~"+\ ...
e charecters print(mycharset[i] , " has " , '{0:04d}'.format(countset[i]) , " times appeared. "+\ "Probability = " , '{:.10f}'.format(probabilityset[i]) + " Huffman: " + mycodebook[str(mycharset[i])]) # just a print out operation onesandzeros = "" for i in range (0, len(allofthefile)): onesa...
0 while (i < len(onesandzeros)): b = BitArray(bin=onesandzeros[i:i+8]) # divide array with 8 many bits and make them into a byte b.tofile(binary_file) i = i+8 binary_file.close() binary_file = open('compressed_foo.bin', "rb") allofthebinaryfile = binary_file.read() binary_file.close() newonesandzeros ...
AuScope/VHIRL-Portal
src/main/resources/org/auscope/portal/server/scriptbuilder/templates/run_busselton.py
Python
gpl-3.0
10,162
0.00738
"""Script for running a tsunami inundation scenario for Busselton, WA Australia. Source data such as elevation and boundary data is assumed to be available in directories specified by project.py The output sww file is stored in directory named after the scenario, i.e slide or fixed_wave. The scenario is define...
'ocean_wsw': [3], 'ocean_w': [4], 'ocean_wnw': [5], 'top': [6], 'land_nne': [7], ...
'land_se': [9]}, maximum_triangle_area=default_res, mesh_filename=meshname, use_cache=v_cache, verbose=v_verbose) # Print some stats ...
sdoerig/TestRest
testrest/testrest/TestRestManager.py
Python
gpl-3.0
2,047
0.001954
''' Created on May 11, 2014 ''' __author__ = 'sdoerig@bluewin.ch' from testrest.TestRestCase import TestRestCase from testrest.handler import YamlHandler from testrest.logger.LogHandler import LogHandler class TestRestManager(object): ''' classdocs ''' lh = None logger = None _configHandler...
.YamlHandler() self._configHandler.load(configFile) TestRestManager.lh = LogHandler(self._configHandler.get('logger')) TestRestCase.lh = TestRestManager.lh YamlHandler.YamlHandler.setLogHandler(TestRestManager.lh) TestRestManager.logger = TestRestManager.lh.getLogger("Hammer") ...
dler.LogHandler', self._configHandler.get('logger')) # logger.info('Hellos') # logger.error('Error') testCases = self._configHandler.get('test') testCasesKeys = list(testCases.keys()) testCasesKeys.sort() globalTestCase = {} if 'global' in testCasesKeys: ...
datalogics/scons
test/BadBuilder.py
Python
mit
2,846
0.002811
#!/usr/bin/env python # # __COPYRIGHT__ # # 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, ...
TH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" """ Test the ability to catch Builder creation with poorly specified Actions. """ import os.path import TestSCons test = TestSCons.TestSCons() SConstruct_path = test.workpath('SConstruct')...
find(str(target[0])) == -1: outf.write(line) inpf.close() outf.close() b1 = Builder(action=buildop, src_suffix='.a', suffix='.b') %s env=Environment(tools=[], BUILDERS={'b1':b1, 'b2':b2}) foo_b = env.b1(source='foo.a') env.b2(source=foo_b) """ test.write('foo.a', """\ foo.c foo.b built """) python...
openfisca/LawToCode
lawtocode/texthelpers.py
Python
agpl-3.0
2,921
0.01062
# -*- coding: utf-8 -*- # Law-to-Code -- Extract formulas & parameters from laws # By: Emmanuel Raviart <emmanuel@raviart.com> # # Copyright (C) 2013 OpenFisca Team # https://github.com/openfisca/LawToCode # # This file is part of Law-to-Code. # # Law-to-Code is free software; you can redistribute it and/or modify # ...
'blockquote', 'code', 'em', 'i', 'img', 'li', 'ol', 'p', 'strong', 'ul', ] def clean_html(text): if not text: return u'' return bleach.clean(text, attributes = bleach_allowed_attributes, styles = bleach_allowed_styles, tags = bleach_allowed_tags) ret...
tags = [], strip = True) def truncate(text, length = 30, indicator = u'…', whole_word = False): """Truncate ``text`` to a maximum number of characters. Code taken from webhelpers. ``length`` The maximum length of ``text`` before replacement ``indicator`` If ``text`` exceeds the ``len...
uclouvain/OSIS-Louvain
infrastructure/learning_unit/domain/service/tutor_distributed_to_class.py
Python
agpl-3.0
2,385
0.002517
############################################################################## # # OSIS stands for Open Student Information System. It's an application # designed to manage the core business of higher education institutions, # such as universities, faculties, institutes and professional schools. # The core ...
U General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITN...
s. # # A copy of this license - GNU General Public License - is available # at the root of the source code of this program. If not, # see http://www.gnu.org/licenses/. # ############################################################################## from typing import Optional from ddd.logic.effective_class_r...
fgregg/streetaddress-us
addressconf.py
Python
mit
10,198
0.100804
import re class Directions(object): DIRECTIONAL = { "north":"N", "northeast":"NE", "east":"E", "southeast":"SE", "south":"S", "southwest":"SW", "west":"W", "northwest":"NW"} DIRECTIONAL_CODES = dict((v,k) for k,v in DIRECTIONAL.iteritems()) class Streets(object): STREET_TYPES = { "allee":"aly", ...
harb":"hbr", "harbor":"hbr", "harbors":"hbrs", "harbr":"hbr", "haven":"hvn", "havn":"hvn", "height":"hts", "heights":"hts", "hgts":"hts", "highway":"hwy", "highwy":"hwy", "hill":"hl", "hills":"hls", "hiway":"hwy", "hiwy":"hwy", "hllw":"holw", "hollow":"holw", "hollows":"holw", "holws...
, "island":"is", "islands":"iss", "isles":"isle", "islnd":"is", "islnds":"iss", "jction":"jct", "jctn":"jct", "jctns":"jcts", "junction":"jct", "junctions":"jcts", "junctn":"jct", "juncton":"jct", "key":"ky", "keys":"kys", "knol":"knl", "knoll":"knl", "knolls":"knls", "la":"ln", "l...
Kingdread/qutebrowser
qutebrowser/commands/userscripts.py
Python
gpl-3.0
12,321
0.000081
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2014-2015 Florian Bruhin (The Compiler) <mail@qutebrowser.org> # # 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...
browser.utils import message, log, objreg, standarddir from qutebrowser.commands import runners, cmdexc from qutebrowser.config import config from qutebrowser.misc import guiprocess class _QtFIFOReader(QObject): """A FIFO reader based on a QSocketNotifier.""" got_line = pyqtSignal(str) def __init__(sel...
filepath # We open as R/W so we never get EOF and have to reopen the pipe. # See http://www.outflux.net/blog/archives/2008/03/09/using-select-on-a-fifo/ # We also use os.open and os.fdopen rather than built-in open so we # can add O_NONBLOCK. fd = os.open(filepath, os.O_RDWR | ...
RedHenLab/Audio
CNN/detect_outlier.py
Python
gpl-2.0
3,781
0.013224
import numpy as np import sys sys.path.append("../Pipeline/Audio/Pipeline/") from AudioPipe.features import mfcc # Feature Extraction Module, part of the shared preprocessing import AudioPipe.speaker.recognition as SR # Speaker Recognition Module import scipy.io.wavfile as wav import commands, os import json import ar...
rite("file "+clip["name"]+"\n") count+=1 # Merge all the data into one audio audio_merge = os.path.join(spk_dir,"merged_gross.wav") commands.getstatusoutput("ffmpeg -f concat -i "+temp_fl.repla
ce(" ", "\ ")+" -c copy -y "+audio_merge) os.remove(temp_fl) return audio_merge def from_jsonfile(filename): with open(filename) as fh: return json.load(fh) def get_sec(time_str): h, m, s = time_str.split(':') return int(h) * 3600 + int(m) * 60 + float(s) def to_json(result, **kwargs): ...
kusti8/hue-plus
hue_plus/hue_gui.py
Python
gpl-3.0
45,771
0.000721
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'hue-gui.ui' # # Created by: PyQt5 UI code generator 5.8.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindo...
Widget() self.presetTab.setObjectName("presetTab") self.presetModeWidget = QtWidgets.QTabWidget(self.presetTab) self.presetModeWidget.setGeometry(QtCore.QRect(6, 10, 1101, 411)) self.p
resetModeWidget.setLayoutDirection(QtCore.Qt.LeftToRight) self.presetModeWidget.setObjectName("presetModeWidget") self.fixedTab = QtWidgets.QWidget() self.fixedTab.setObjectName("fixedTab") self.groupBox = QtWidgets.QGroupBox(self.fixedTab) self.groupBox.setGeometry(QtCore.QRect(...
jmesteve/saas3
openerp/addons/website_sale/models/sale_order.py
Python
agpl-3.0
1,823
0.002743
# -*- coding: utf-8 -*- from openerp import SUPERUSER_ID from openerp.osv import osv, fields from openerp.addons.web.http import request class SaleOrder(osv.Model): _inherit = "sale.order" _columns = { 'website_session_id': fields.char('Session UUID4'), 'website_order_line': fields.one2many( ...
ned several times -> fix me ? if context is None: context = {} user_obj = self.pool.get('res.users') if ids and not product_id: order_line = self.browse(cr, SUPERUSER_ID, ids[0], context=context) assert order_line.order_id.website_session_id == request.httpre...
return self.product_id_change( cr, SUPERUSER_ID, ids, pricelist=context.pop('pricelist'), product=product_id, partner_id=user_obj.browse(cr, SUPERUSER_ID, uid).partner_id.id, context=context )['value']
martyanov/notv
manage.py
Python
mit
622
0
""" manage ====== Collection of helpers to mana
ge database migrations, shell access, etc. :copyright: Copyright (c) 2015 Andrey Martyanov. All rights reserved. :licens
e: MIT, see LICENSE for more details. """ from flask.ext.migrate import MigrateCommand from flask.ext.script import Manager from notv import models from notv.app import create_app from notv.extensions import db app = create_app() manager = Manager(app) @manager.shell def _make_context(): return dict(app=app, ...
cds-amal/addressparser
nyctext/neighborhoods/manhattan.py
Python
mit
1,393
0
from regexps import make_neighorbood_regex _hoods = '''Alphabet City Astor Row Battery Park City Bowery Carnegie Hill Chelsea Chinatown Civic Center Columbus Circle Cooperative Village Diamond District East Harlem East Village Ellis Island Essex Crossing Financial District Five Points Flatiron District Garment Distric...
Manhattan Morningside Heights Murray Hill NoHo Nolita NoMad Penn South Peter Cooper Village Pomander Walk Radio Row Randalls Island Riverside
South Roosevelt Island Rose Hill Silicon Alley SoHo South Street Seaport South Village Stuyvesant Square Stuyvesant Town Sugar Hill Sutton Place Sylvan Tenderloin Theater District Times Square Tribeca Tudor City Turtle Bay Two Bridges Union Square Upper East Side Upper Manhattan Upper West Side Wards Island Washington...
iABC2XYZ/abc
DM_Twiss/TwissTrain9.py
Python
gpl-3.0
1,927
0.048615
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Sep 20 13:37:16 2017 Author: Peiyong Jiang : jiangpeiyong@impcas.ac.cn Function: 旋转使得变换。 """ import matplotlib.pypl
ot as plt import tensorflow as tf import numpy as np plt.close('all') emitX=12 alphaX=-10. betaX=13. gammaX=(1.+alphaX**2)/betaX sigmaX=np.array([[betaX,-alphaX],[-alphaX,gammaX]]
)*emitX; numPart=np.int32(1e5); X=np.random.multivariate_normal([0.,0.],sigmaX,numPart).T plt.figure(1) plt.plot(X[0,:],X[1,:],'.') ## w=tf.Variable(tf.random_normal([1,1])) w1=tf.cos(w) w2=tf.sin(w) P_Row_1=tf.concat([w1,-w2],0) P_Row_2=tf.concat([w2,w1],0) P=tf.concat([P_Row_1,P_Row_2],1) xI=tf.placehol...
JohnVinyard/zounds
zounds/persistence/identitydimension.py
Python
mit
466
0
from .basedimension import BaseDimensionEncoder, BaseDimensionDecoder from zounds.core import Identi
tyDimension class IdentityDimensionEncoder(BaseDimensionEncoder): def __init__(self): super(IdentityDimensionEncoder, self).__init__(IdentityDimension) def dict(self, o): return dict() class IdentityDimensionDecoder(BaseDimensionDecoder): def __init__(self): super(IdentityDimens...
er, self).__init__(IdentityDimension)
fireeye/flare-wmi
python-cim/samples/ui/uicommon.py
Python
apache-2.0
121
0
def emptyLayout(layout): for i in rever
sed(range(layout.count())): layout.itemAt(i).widget().setPare
nt(None)
LucaCanali/Linux_tracing_scripts
BPF-bcc_Userspace_Oracle/ora_wait_histogram_12c_18c.py
Python
apache-2.0
4,853
0.007418
#!/usr/bin/python # # ora_wait_histogram.py - Oracle wait event latency histograms using BPF/bcc and uprobes # # This script traces Oracle sessions by hooking on the functions "kskthewt" and # "kews_update_wait_time" and reads from function arguments (CPU registers). BPF computes # the latency histogram for the wait ...
R) return 0; rsi = ctx->si; if (rsi > 0) wait_time.update(&pid, &rsi); return 0; }; """ # code substitutions if args.pid: bpf_text = bpf_text.replace('FILTER', 'pid != %s' % args.pid) else: bpf_text = bpf_text.replace('FILTER', '0') b = BPF(text=bpf_text) # work
around for Oracle 12c and higher # need to attach the address of the probe + 2 address_list = BPF.get_user_functions_and_addresses(oracle_executable, "^kskthewt$") paddr = address_list[0][1] + 2 b.attach_uprobe(name=oracle_executable, addr=paddr, fn_name="trace_kskthewt") # This is the original code, works on Oracle ...
JaneliaSciComp/osgpyplusplus
examples/rough_translated1/osgsharedarray.py
Python
bsd-3-clause
11,182
0.009032
#!/bin/env python # Automatically translated python version of # OpenSceneGraph example program "osgsharedarray" # !!! This program will need manual tuning before it will work. !!! import sys from osgpypp import osg from osgpypp import osgViewer # Translated from file 'osgsharedarray.cpp' # OpenSceneGraph exampl...
1.), osg.Vec3(-1.,-1.,-1.),
osg.Vec3( 1.,-1.,-1.), osg.Vec3( 1.,-1., 1.), osg.Vec3(-1.,-1., 1.), osg.Vec3 myNormals[] = osg.Vec3( 0., 0., 1.), osg.Vec3( 0., 0., 1.), osg.Vec3( 0., ...
stevepiercy/cookiecutter
tests/repository/test_determine_repository_should_use_local_repo.py
Python
bsd-3-clause
1,964
0
# -*- coding: utf-8 -*- import os from cookiecutter import repository, exceptions import pytest def test_finds_local_repo(tmpdir): """A valid local repository should be returned.""" project_dir = repository.determine_repo_dir( 'tests/fake-repo', abbreviations={}, clone_to_dir=str(tmpd...
no_input=True )
assert 'tests/fake-repo' == project_dir def test_local_repo_with_no_context_raises(tmpdir): """A local repository without a cookiecutter.json should raise a `RepositoryNotFound` exception. """ template_path = os.path.join('tests', 'fake-repo-bad') with pytest.raises(exceptions.RepositoryNotFoun...
GeoLabs/QgsWPSClient
Ui_qgswpsdescribeprocessgui.py
Python
gpl-2.0
1,346
0.004458
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file '/home/barpadue/.qgis/python/plugins/wps/qgswpsdescribeprocessgui.ui' # # Created: Thu Mar 15 14:27:35 2012 # by: PyQt4 UI code generator 4.8.5 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui tr...
ocessGUI")) QgsWpsDescribeProcessGUI.setWindowModality(QtCore.Qt.NonModal) QgsWpsDescribeProcessGUI.resize(800, 600) QgsWpsDescribeProcessGUI.setWindowTitle(QtGui.QApplication.translate("QgsWpsDescribeProcessGUI", "Describe Process", None, QtGui.QAppli
cation.UnicodeUTF8)) self.retranslateUi(QgsWpsDescribeProcessGUI) QtCore.QMetaObject.connectSlotsByName(QgsWpsDescribeProcessGUI) def retranslateUi(self, QgsWpsDescribeProcessGUI): pass if __name__ == "__main__": import sys app = QtGui.QApplication(sys.argv) QgsWpsDescribePro...
ProfessorX/Config
.PyCharm30/system/python_stubs/-1247971765/apt_pkg/Description.py
Python
gpl-2.0
1,338
0.005979
# encoding: utf-8 # module apt_pkg # from /usr/lib/python
3/dist-packages/apt_pkg.cpython-34m-x
86_64-linux-gnu.so # by generator 1.135 """ Classes and functions wrapping the apt-pkg library. The apt_pkg module provides several classes and functions for accessing the functionality provided by the apt-pkg library. Typical uses might include reading APT index files and configuration files and installing or removin...
cloew/NytramBox2D
nytram_box2d/engine/filter.py
Python
mit
503
0.007952
from ctypes import Structure, c_int16, c_uint16 class Filter(Structure): """ Represents a Fixture filter """ _fields_ = [("categoryBits", c_uint16), ("maskBits", c_uint16), ("groupIndex", c_int16)]
def __init__(self, categoryBits=0x1, maskBits=0xFFFF, groupIndex=0): """ Initialize the filter with the proper defaults """ Structure.__init__(self, c
ategoryBits=categoryBits, maskBits=maskBits, groupIndex=groupIndex)
lucastx/tjrj-processos
tjrj/scraping.py
Python
gpl-2.0
1,302
0.002304
#!/usr/bin/env python #
-*- encoding: utf-8 -*- from bs4 import BeautifulSoup def parse_html(html): def strip_elem(e): return str(e).strip() def non_empty_children(elem): if hasattr(elem, "children"): return list(filter(strip_elem, elem.children)) else: return None def parse_mov...
movimento): def parse_tr(tr): tds = non_empty_children(tr) if tds and len(tds) == 2: conteudos = map(lambda f: f.text.strip(), tds) return tuple(conteudos) else: return () def items_do_movimento(movimento): ...
kaze/paasmaker
paasmaker/pacemaker/scm/base.py
Python
mpl-2.0
4,827
0.024446
# # Paasmaker - Platform as a Service # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # import uuid import os import re import paasmaker import tornado import torna...
st pulls new changes each time. """ # These are defaults - you should set your own. MODES = { paasmaker.util.plugin.MODE.SCM_EXPORT: BaseSCMParametersSchema(), paasmaker.util.plugin.MODE.SCM_FORM: None } OPTIONS_SCHEMA = BaseSCMConfigurationSchema() def _get_this
_scm_path(self, postfix): scratch_path = self.configuration.get_flat('scratch_directory') path = os.path.join(scratch_path, 'scm', self.__class__.__name__, postfix) if not os.path.exists(path): os.makedirs(path, 0750) return path def _get_temporary_scm_dir(self): """ Get a temporary directory to unpac...
PrintNode/PrintNode-Python
setup.py
Python
mit
278
0.003597
from setuptools import setup
setup( name='PrintNodeApi', version='0.2.0', description="Python Client for PrintNode's API", author='printnode', author_email='support@printnode.com', packages=['printnodeapi'], instal
l_requires=['requests','future'])
NejcZupec/ggrc-core
test/selenium/src/lib/file_ops.py
Python
apache-2.0
886
0.011287
# Copyright (C) 2016 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> import os import logging logger = logging.getLogger(__name__) def create_directory(path): """ Creates a directory if it doesn't already exist. """ # Check if path is a file_path or a dir_path. Di...
logger.info("Creating directory: %s", path) os.makedirs(path) def get_unique_postfix(file_path
, extension): postfix = 0 new_path = file_path + str(postfix) + extension while os.path.isfile(new_path): postfix += 1 new_path = file_path + str(postfix) + extension return new_path def delete_directory_contents(path): for file_name in os.listdir(path): os.remove(path + os.sep + file_name)
craigulmer/gut-buster
squareplot.py
Python
mit
1,320
0.02197
# Simple plotter for Gut books. # All this does is draw a sqare for every stat in the input # and color it based on the score. # # Another fine example of how Viz lies to you. You will # need to fudge the range by adjusting the clipping. import numpy as np import matplotlib.pyplot as plt import sys as sys if len(s...
want 3x1 ratio, so 3n*n= 30824 (max entries), horiz=3n=300 NUM_COLS=300 fig = plt.figure(figsize=(12,9)) ax = fig.add_subplot(111) ax.set_axis_bgcolor('0.50') ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) for i in range(len(vals)): #print i, ids[i]
row = int(ids[i]) / NUM_COLS col = int(ids[i]) % NUM_COLS cval = score[i] #score[i]*score[i] # Square the values to drop the lower end cmap = plt.get_cmap('hot') val = cmap(cval) ax.add_patch(plt.Rectangle((col,row),1,1,color=val)); #, cmap=plt.cm.autumn)) ax.set_aspect('equal') ...
castelao/CoTeDe
cotede/qctests/gradient.py
Python
bsd-3-clause
2,756
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ """ import logging import numpy as np from numpy import ma from cotede.qctests import QCCheckVar try: import pandas as pd PANDAS_AVAILABLE = True except ImportError: PANDAS_AVAILABLE = Fa...
It should contain a threshold item." ) threshold = self.cfg assert ( (np.size(threshold) == 1) and (threshold is not None) and (np.isfinite(threshold)) ) flag = np.zeros(np.shape(self.data[self.varname]), dtype="i1") feature =...
np.atleast_1d(self.data[self.varname]) flag[ma.getmaskarray(x) | ~np.isfinite(x)] = 9 self.flags["gradient"] = flag
yunity/yunity-core
karrot/webhooks/migrations/0006_auto_20201108_1335.py
Python
agpl-3.0
527
0
# G
enerated by Django 3.1.2 on 2020-11-08 13:35 from django.db import migrations, models class Migration(migrations.M
igration): dependencies = [ ('webhooks', '0005_auto_20190918_1219'), ] operations = [ migrations.AlterField( model_name='emailevent', name='payload', field=models.JSONField(), ), migrations.AlterField( model_name='incomingemai...
AlphaSmartDog/DeepLearningNotes
Note-6 A3CNet/Note-6.3 强化学习选股-SH50指数增强/emulator/env_market.py
Python
mit
2,528
0.000791
import numpy as np import pandas as pd from emulator.env_factor import get_factors turnovers = pd.read_excel('emulator/SH50.xls', sheetname='total_turnover') opens = pd.read_excel('emulator/SH50.xls', sheetname='open') closes = pd.read_excel('emulator/SH50.xls', sheetname='close') highs = pd.read_excel('emulator/SH50....
'600050.XSHG', '600000.XSHG', '600
485.XSHG', '601288.XSHG', '601377.XSHG', '600029.XSHG', '601198.XSHG', '601211.XSHG', '600893.XSHG', '600547.XSHG', '601668.XSHG', '601166.XSHG', '600100.XSHG', '601006.XSHG', '601818.XSHG', '600036.XSHG', '600837.XSHG', '600958.XSHG', '601318.XSHG...
jmvasquez/redashtest
redash/handlers/queries.py
Python
bsd-2-clause
4,842
0.003717
from flask import request from flask_restful import abort from flask_login import login_required import sqlparse from funcy import distinct, take from itertools import chain from redash.handlers.base import routes, org_scoped_rule from redash.handlers.query_results import run_query from redash import models from reda...
_def: query_def['data_source'] = query_def.pop('data_source_id') query_def['last_modified_by'] = self.current_user query.update_instance(**query_def) return query.to_dict(with_visualizations=True) @require_permission('view_query') def get(self, query_id): q = get_...
_org) require_access(q.groups, self.current_user, view_only) if q: return q.to_dict(with_visualizations=True) else: abort(404, message="Query not found.") # TODO: move to resource of its own? (POST /queries/{id}/archive) def delete(self, query_id): query...
blond-admin/BLonD
unittests/llrf/test_beam_feedback.py
Python
gpl-3.0
8,713
0.00264
# -*- coding: utf-8 -*- """ Created on Fri Apr 13 18:27:10 2018 @author: schwarz """ import unittest import numpy as np import cmath from blond.input_parameters.ring import Ring from blond.input_parameters.rf_parameters import RFStation from blond.beam.beam import Beam, Proton from blond.beam.distributions import bi...
5634e-03, -1.37832214e-03, -1.35829791e-03, -1.32588558e-03, -1.28146000e-03, -1.22518721e-03, -1.15769141e-03, -1.07943574e-03, -9.91143310e-04, -8.93671637e-04, -7.87961546e-04, -6.74866999e-04, -5.55444011e-04, -4.30919368e-04, -3.02270469e-04, -1.7082
4836e-04, -3.77396109e-05, 9.56816273e-05, 2.28299979e-04, 3.58842001e-04, 4.86074690e-04, 6.08875045e-04, 7.26090501e-04, 8.36677390e-04, 9.39639556e-04, 1.03407702e-03, 1.11906014e-03, 1.19386315e-03, 1.25779004e-03, 1.31037519e-03, 1.35108872e-03, 1.37...
bbfamily/abu
abupy/UmpBu/ABuUmpEdgeFull.py
Python
gpl-3.0
8,818
0.003609
# -*- encoding:utf-8 -*- """示例ump边裁特征多混模块""" from __future__ import division from __future__ import print_function from __future__ import absolute_import from ..TradeBu.ABuMLFeature import AbuFeatureDeg, AbuFeaturePrice, AbuFeatureWave, AbuFeatureAtr from ..MLBu.ABuMLPd import AbuMLPd from .ABuUmpBase import ump_edge...
keys(ump_cls=AbuUmpEdgeFull) cols.extend(AbuFeaturePrice().get_feature_ump_keys(ump_cls=AbuUmpEdgeFull)) cols.extend(AbuFeatureWave().get_feature_ump_keys(ump_cls=AbuUmpEdgeFull)) cols.extend(AbuFeatureAtr().get_feature_ump_keys(ump_cls=AbuUmpEdgeFull)) return cols def get_fiter_cla...
@classmethod def class_unique_id(cls): """ 具体ump类关键字唯一名称,类方法:return 'full_edge' 主要针对外部user设置
26huitailang/bsawf
snakeeyes/blueprints/billing/models/subscription.py
Python
gpl-2.0
7,274
0
import datetime import pytz from config import settings from lib.util_sqlalchemy import ResourceMixin from snakeeyes.extensions import db from snakeeyes.blueprints.billing.models.credit_card import CreditCard from snakeeyes.blueprints.billing.models.coupon import Coupon from snakeeyes.blueprints.billing.gateways.stri...
eturn: str or None """ for key in keys: split_key = key.split('submit_') if isinstance(split_key, list) and len(split_key) == 2:
if Subscription.get_plan_by_id(split_key[1]): return split_key[1] return None def create(self, user=None, name=None, plan=None, coupon=None, token=None): """ Create a recurring subscription. :param user: User to apply the subscription to :type us...
heyitswither/Alpha-Bot
cogs/test-welcome.py
Python
mit
2,775
0.006486
import discord from discord.ext import commands from PIL import Image, ImageDraw, ImageFont import pathvalidate import requests import os class Welcome: def __init__(self, bot): self.bot = bot async def on_member_join(self, member): template = Image.open('extras/template.png') draw = ImageDraw.Draw(...
ent(chunk_size=1024): if chunk: f.write(chunk) guild_icon = Image.open('extras/{}.png'.format(server_name)) guild_icon = guild_icon.res
ize((64, 64), Image.ANTIALIAS) template.paste(guild_icon, (660, 300)) font = ImageFont.truetype("extras/segoeui.ttf", fontsize) while font.getsize(user)[0] < img_fraction * template.size[0]: fontsize += 1 font = ImageFont.truetype("extras/segoeui.ttf", fontsize) fontsize -= 1 font = Imag...
msultan/msmbuilder
msmbuilder/tests/__init__.py
Python
lgpl-2.1
339
0
import
warnings # Show warnings for our package warnings.filterwarn
ings('always', module='msmbuilder.*') # Show warnings for packages where we want to be conscious of warnings warnings.filterwarnings('always', module='mdtraj.*') warnings.filterwarnings('default', module='scipy.*') warnings.filterwarnings('default', module='sklearn.*')
djo938/dumpFormat
dumpformat/test/test.py
Python
gpl-3.0
1,155
0.021645
#!/usr/bin/python # -*- coding: utf-8 -*- #Copyright (C) 2013 Jonathan Delvaux <dumpformat@djoproject.net> #This program is free software: you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation, either version 3 of the License, or #an...
tUp(self): self.d = dumpManager() def test_init(self): self
.d.save("./test.xml") def test_ def test_load(self): pass #TODO #save then load and compare if __name__ == '__main__': unittest.main()
benoit-pierre/mcomix
mcomix/main.py
Python
gpl-2.0
48,018
0.002832
"""main.py - Main window.""" import os import shutil import threading import gtk import gobject from mcomix import constants from mcomix import cursor_handler from mcomix import i18n from mcomix import icons from mcomix import enhance_backend from mcomix import event from mcomix import file_handler from mcomix import...
= False prefs['horizontal flip'] = False # List of "toggles" than can be shown/hidden by the user. self._toggle_list = ( # Preference Action Widget(s) ('show menubar' , 'menubar' , (self.menubar,) ), ('show scrollbar' ,
'scrollbar' , self._scroll ), ('show statusbar' , 'statusbar' , (self.statusbar,) ), ('show thumbnails', 'thumbnails', (self.thumbnailsidebar,)), ('show toolbar' , 'toolbar' , (self.toolbar,) ), ) # Each "toggle" widget "eats" part of the...
volkodav1985/volkodavpython
fixture/contact.py
Python
apache-2.0
5,484
0.002553
from model.contact import Contact import re class ContactHelper: def __init__(self, app): self.app = app def create(self, contact): wd = self.app.wd self.open_contact_page() self.fill_contact_form(contact) # submit contact creation wd.find_element_by_xpath("//...
d_value("lastname", contact.lastname) self.change_field_value("company", contact.company) self.change_field_value("home", contact.homephone) self.change_field_value("mobile", contact.mobilephone) self.change_field_value("work", contact.workphone) self.change_field_value("email", ...
ef change_field_value(self, field_name, text): wd = self.app.wd if text is not None: wd.find_element_by_name(field_name).click() wd.find_element_by_name(field_name).clear() wd.find_element_by_name(field_name).send_keys(text) def select_first_contact(self): ...
iniverno/RnR-LLC
simics-3.0-install/simics-3.0.31/amd64-linux/lib/python/mod_ppc405gp_turbo_commands.py
Python
gpl-2.0
245
0.008163
import ppc_commands ppc_model = 'ppc405gp' funcs =
{} ppc_commands.setup_local_functions(ppc_model, funcs) class_funcs = { ppc_model: funcs } ppc_commands.enable_generic_ppc_commands(ppc_model) ppc_commands.enable_4xx_tlb_commands(ppc
_model)
ucsb-ilabs/shapematching
src/main/python/edu/ucsb/ilab/shapematching/pt2graph.py
Python
gpl-2.0
5,365
0.006524
#!/home/longbin/install/apps/Python-2.5_gcc/bin/python import sys import math import getopt import string import fileinput clrs = ['ff0000', '00ff00', '0000ff'] def printheader(n): print '<?xml version="1.0" encoding="UTF-8" standalone="no"?>' print ' <graphml xmlns="http://graphml.graphdrawing.org/xmln...
print ' </data>' print ' <data key="d3"/>' print ' </edge>' if __na
me__ == '__main__': # load the image gived on the command line X = [] X1 = [] Y = [] Y1 = [] U = [] V = [] for line in fileinput.input(sys.argv[1]): dr = line.split(' ') X.append(string.atof(dr[0]) ) Y.append(string.atof(dr[1])) for line in fileinput.input(sys...
linxdcn/iS3
IS3Py/SHL12_TT.py
Python
lgpl-3.0
23,740
0.0115
# -*- coding:gb2312 -*- import is3 from System.Collections.ObjectModel import ObservableCollection from System.Windows.Media import Colors def add3dview(): is3.addView3d('Map3D', 'Test.unity3d') def addBaseMap(): is3.mainframe.LoadProject('SHL12_TT.xml') is3.prj = is3.mainframe.prj is3.MainframeWrapp...
(info1, info2)) uniquevalue_renderer = is3.UniqueValueRendererDef(defaultsymbol, fields, infos) layerDef
= is3.LayerDef() layerDef.Name = 'GEO_BHL' layerDef.GeometryType = is3.GeometryType.Point #layerDef.Color = Colors.Blue #layerDef.MarkerSize = 12 #layerDef.MarkerStyle = is3.SimpleMarkerStyle.Circle layerDef.RendererDef = uniquevalue_renderer layerDef.EnableLabel = True layerDef.LabelTe...
Colorado-Realestate-Data/CO-Database
project/urls.py
Python
mit
2,141
0.002335
"""coprop URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/dev/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-base...
ation.urls')), url(r'^admin/', admin.site.urls), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^token/auth/', obtain_jwt_token), url(r'^token/refresh/', refresh_jwt_token), url(r'^token/verify/', verify_jwt_token), url(r'^$', IndexView.as_view(), name='ind...
DEBUG: urlpatterns += [ url(r'^media/(.*)$', serve, {'document_root': settings.MEDIA_ROOT}), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)