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
alfasin/st2
st2client/st2client/models/core.py
Python
apache-2.0
11,745
0.001192
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use th...
e(item) for item in respon
se.json()] else: return response.json() @add_auth_token_to_kwargs_from_env def get_by_ref_or_id(self, ref_or_id, **kwargs): return self.get_by_id(id=ref_or_id, **kwargs) @add_auth_token_to_kwargs_from_env def query(self, **kwargs): if not kwargs: raise E...
smartczm/python-learn
Old-day01-10/s13-day8/有序字典/s1.py
Python
gpl-2.0
689
0.001541
#!/usr/bin/env python3.5 # -*- coding: utf-8 -*- # Author: ChenLiang # 通过列表存储dick的key来达到创建有序字典 class MyDict(dict): def __init__(self): self.li = [] super(MyDict, self).__init__() def __setitem__(self, key, value): self.li.append(key) super(MyDi
ct, self).__setitem__(key, value) def __str__(self): temp_list = [] for key in self.li: value = self.get(key) # 获取get方法 temp_list.append("'%s':%s" % (key, value)) temp_str = "{" + ",".join(temp_list) + "}" return temp_str obj = MyDict() obj['k1'] = 123 obj...
6 obj['k3'] = 789 print(obj)
CospanDesign/verilog-visualizer
verilogviz/view/graph/graphics_view.py
Python
gpl-2.0
2,510
0.005578
# Distributed under the MIT licesnse. # Copyright (c) 2013 Dave McCoy (dave.mccoy@cospandesign.com) # 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 lim...
uthor__ = "Dave McCoy dave.mccoy@cospandesign.com" import sys import os from PyQt4.QtCore import * from PyQt4.QtGui import * p = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, ...
v class GraphicsView(gv): def __init__(self, parent): super(GraphicsView, self).__init__(parent) self.initialize = True def fit_in_view(self): self._scale_fit() def update(self): self._scale_fit() self.initialize = False super (GraphicsView, self).update()...
saltstack/salt
tests/unit/returners/test_sentry_return.py
Python
apache-2.0
787
0.001271
import salt.returners.sentry_return as sentry from tests.support.unit import TestCase class SentryReturnerTestCase(TestCa
se): """ Test Sentry Returner """ ret = { "id": "12345", "fun": "mytest.func", "fun_args": ["arg1", "arg2", {"foo": "bar"}], "jid": "54321", "return": "Long Return containing a Traceback", } def test_get_message(self): self.assertEqual( ...
ge({"fun": "test.func", "fun_args": []}), "salt func: test.func", ) self.assertEqual( sentry._get_message({"fun": "test.func"}), "salt func: test.func" )
VisTrails/VisTrails
vistrails/core/vistrail/connection.py
Python
bsd-3-clause
10,497
0.005716
############################################################################### ## ## Copyright (C) 2014-2016, New York University. ## Copyright (C) 2011-2014, NYU-Poly. ## Copyright (C) 2006-2011, University of Utah. ## All rights reserved. ## Contact: contact@vistrails.org ## ## This file is part of VisTrails. ## ## ...
stinationId) def _get_source(self): """_get_source() -> Port Returns source port. Do not use
this function, use source property: c.source """ try: return self.db_get_port_by_type('source') except KeyError: pass return None def _set_source(self, source): """_set_source(source: Port) -> None Sets this connection source port...
xflr6/bitsets
bitsets/transform.py
Python
mit
2,607
0
"""Convert between larger integers and chunks of smaller integers and booleans. Note: chunks have little-endian bit-order like gmpy2.(un)pack, but reverse of numpy.(un)packbits """ from itertools import compress, zip_longest __all__ = ['chunkreverse', 'pack', 'unpack', 'packbools', 'unpackbools'] NBITS = {'B'...
zip_longest(*[iter(bools)] *
r, fillvalue=False): yield sum(compress(atoms, chunk)) def unpackbools(integers, dtype='L'): """Yield booleans unpacking integers of dtype bit-length. >>> list(unpackbools([42], 'B')) [False, True, False, True, False, True, False, False] """ atoms = ATOMS[dtype] for chunk in integer...
mcaleavya/bcc
tests/python/test_probe_count.py
Python
apache-2.0
2,656
0.000377
#!/usr/bin/env python # Copyright (c) Suchakra Sharma <suchakrapani.sharma@polymtl.ca> # Licensed under the Apache License, Version 2.0 (the "License") from bcc import BPF, _get_num_open_probes, TRACEFS import os import sys from unittest import main, TestCase class TestKprobeCnt(TestCase): def setUp(self): ...
return 0; } """) self.b.attach_kprobe(event_re="^vfs_.*", fn_name="wololo") def test_attach1(self): actual_cnt = 0 with open("%s/available_filter_functions" % TRACEFS, "rb") as f: for line in f: if line.startswith(b"vfs_"): ...
um_open_kprobes() self.assertEqual(actual_cnt, open_cnt) def tearDown(self): self.b.cleanup() class TestProbeGlobalCnt(TestCase): def setUp(self): self.b1 = BPF(text="""int count(void *ctx) { return 0; }""") self.b2 = BPF(text="""int count(void *ctx) { return 0; }""") def...
Transkribus/TranskribusDU
TranskribusDU/tasks/TablePrototypes/DU_ABPTableSkewed_txtBIOStmb_sepSIO_line.py
Python
bsd-3-clause
8,251
0.021937
# -*- coding: utf-8 -*- """ *** Labelling is B I O St Sm Sb Singletons are split into: - St : a singleton on "top" of its cell, vertically - Sm : a singleton in "middle" of its cell, vertically - Sb : a singleton in "bottom" of its cell, vertically Copyright Naver Labs Eu...
roid.y:
sXmlLabel = "St" else: sXmlLabel = "Sb" try: sLabel = self.dXmlLabel2Label[sXmlLabel] except KeyError: # #not a label of interest, can we ignore it? # try: # self.checkIsIgnored(sXmlLabel) # ...
drepetto/chiplotle
chiplotle/geometry/core/__init__.py
Python
gpl-3.0
98
0
from gr
oup import Group from label import Label from path import Path from
polygon import Polygon
s0lst1c3/eaphammer
local/hostapd-eaphammer/tests/hwsim/fst_module_aux.py
Python
gpl-3.0
33,202
0.001867
# FST tests related classes # Copyright (c) 2015, Qualcomm Atheros, Inc. # # This software may be distributed under the terms of the BSD license. # See README for more details. import logging import os import signal import time import re import hostapd import wpaspy import utils from wpasupplicant import WpaSupplican...
vent_type=(\S+)", ev) if f is None: return None event['type'] = f.group(1) f
= re.search("session_id=(\d+)", ev) if f is not None: event['id'] = f.group(1) f = re.search("old_state=(\S+)", ev) if f is not None: event['old_state'] = f.group(1) f = re.search("new_state=(\S+)", ev) if f is not None: event['new_state'] = f.group(1) f = re.search("rea...
jestapinski/oppia
core/domain/collection_domain.py
Python
apache-2.0
30,872
0.000065
# coding: utf-8 # # Copyright 2015 The Oppia Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requi...
ty_name'] not in self.COLLECTION_PROPERTIES): raise Exception('Invalid change_dict: %s' % change_dict) self.property_name = change_dict['property_name'] self.new_value = change_dict['new_value'] self.old_value = change_dict.get('old_value') ...
self.to_version = change_dict['to_version'] else: raise Exception('Invalid change_dict: %s' % change_dict) class CollectionCommitLogEntry(object): """Value object representing a commit to an collection.""" def __init__( self, created_on, last_updated, user_id, username, col...
FilippoC/pke
src/pke/gui.py
Python
mit
1,481
0.025051
# -*- coding: utf-8 -*- import cv, cv2 import numpy as np def display_histogram(frame): hist_height = 300 hist_width = 256 cv2.namedWindow('colorhist', cv2.CV_WINDOW_AUTOSIZE) b,g,r = cv2.split(frame) color = [(255,0,0),(0,255,0),(0,0,255)] # image à afficher h = np.zeros((300,256,3)) ...
st_item,0,255,cv2.NORM_MINMAX) hist=np.int32(np.around(hist_item)) pts = np.column_stack((bins,hist)) cv2.polylines(h,[pts],False,
col) h=np.flipud(h) cv2.imshow('colorhist',h) cv2.waitKey(0) def display_frame(f1): cv2.imshow("test", f1.getCVFrame()) cv2.waitKey() def display_2_frames(f1, f2): f1 = f1.getCVFrame() f2 = f2.getCVFrame() # http://stackoverflow.com/questions/7589012/combining-two-images-with-openc...
futurice/fabric-deployment-helper
soppa/remote/runner.py
Python
bsd-3-clause
593
0.008432
#!/usr/bin/env python import os, sys, argparse from fabric.api import execute from soppa.file import import_string def use_fabric_env(path): path = path or env.sync_filename local_env =
json.loads(open(path, 'r').read().strip() or '{}') env.update(**local_env) def main(args): use_fabric_env(args.filename) execute(import_string(args.cmd)) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Run stuff.') parser.add_argument('--cmd', type=str) parser.add_argu...
ename', type=str) args = parser.parse_args() main(args)
wallarelvo/CRoPS
code/configuration.py
Python
apache-2.0
8,245
0.001698
#!/usr/bin/env python import math import random import pygame import pygame.color as color import boid import mapparser as mp from prm import PRMGenerator class Configuration: """ Static class that holds important global variables """ ## Dimensions of the screen dim = xSize, ySize = 1000, 600 ...
for zone in nogo_zones: distance_between = math.sqrt( (zone[0] - node[0]) ** 2 + (zone[1] - node[1]) ** 2
) if distance_between < 150: return False # check against other about-to-be obstacles (i.e. other nodes) # make sure they are no where near each other! for other_node_set in self.nodes[:-1]: for other_node in other_node_set: n_1 = li...
tiberiuichim/minitools
get_git_social_log.py
Python
gpl-3.0
1,890
0.000529
#!./bin/python """ Shows interesting activity from followed users of Github """ from __future__ import print_function from github import Github from datetime import datetime, timedelta from argparse import ArgumentParser from config import GITHUB_USERNAME, GITHUB_PASS def repo_title(repo): return "{} ({}/{})".fo...
]) def main(): parser = ArgumentParser(description="Show Github social log") parser.add_argument('-u', '--username', help='Github Username', type=str, default=GITHUB_USERNAME) parser.add_argument('-d', ...
default=2, ) args = parser.parse_args() username = args.username days = args.days gh = Github(GITHUB_USERNAME, GITHUB_PASS) usr = gh.get_user(username) d = datetime.now().date() - timedelta(days=days) events = usr.get_received_events() watched = { 'CreateEvent'...
andresailer/DIRAC
tests/Integration/Resources/Storage/Test_Resources_GFAL2StorageBase.py
Python
gpl-3.0
14,281
0.008333
""" This integration tests will perform basic operations on a storage element, depending on which protocols are available. It creates a local hierarchy, and then tries to upload, download, remove, get metadata etc Potential problems: * it might seem a good idea to simply add tests for the old srm in it. It is not :-) ...
DESTINATION_PATH, 'Workflow/FolderA/FolderAA'), os.path.join(
DESTINATION_PATH, 'Workflow/FolderA/FolderABA'), os.path.join(DESTINATION_PATH, 'Workflow/FolderA/FolderAAB') ] putFile = {os.path.join(DESTINATION_PATH, 'Workflow/FolderA/File1'): os.path.join(self.LOCAL_PATH, ...
wavesoft/creditpiggy
creditpiggy-server/creditpiggy/frontend/views/embed.py
Python
gpl-2.0
3,531
0.021524
################################################################ # CreditPiggy - Volunteering Computing Credit Bank Project # Copyright (C) 2015 Ioannis Charalampidis # # 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 Fr...
e """ # Check if we are members of a particular website, in this case # show the contribution to the active campaign website = website_from_request(request, whitelistPath=True) if not website: return { 'website': None } # Prepare response data = { } data['website'] = website # Check if we have a camp...
# Get first campaign d_campaign = d_campaign[0] # Get achieved instances in the order they were achieved data['campaign'] = { 'details': d_campaign, 'past': CampaignAchievementInstance.objects.order_by('date'), 'next': campaign_next_achievement( d_campaign ), } # Render return data
ninemoreminutes/django-datatables
datatables/views.py
Python
bsd-3-clause
197
0
# Dja
ngo
from django.views.generic.list import ListView __all__ = ['DataTableView'] class DataTableView(ListView): """Class-based list view using a datatable.""" # FIXME: Implement me!
ParsonsAMT/Myne
datamining/apps/profiles/migrations/0008_auto__add_field_courseimage_year__add_field_courseimage_type__chg_fiel.py
Python
agpl-3.0
21,539
0.008264
# encoding: 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 field 'CourseImage.year' db.add_column('profiles_courseimage', 'year', self.gf('dj...
Field', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'unique_together': "(('app_label', 'model'),)", 'object_name
': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}...
pbrod/numpy
numpy/core/arrayprint.py
Python
bsd-3-clause
61,625
0.000471
"""Array printing function $Id: arrayprint.py,v 1.9 2005/09/13 13:58:44 teoliphant Exp $ """ __all__ = ["array2string", "array_str", "array_repr", "set_string_function", "set_printoptions", "get_printoptions", "printoptions", "format_float_positional", "format_float_scientific"] __docformat__ = ...
) in the sign position of positive values. If '-', omit the sign character of positive values. (default '-') formatter : dict of callables, optional If not None, the keys should indicate the type(s) that the respective formatting fun
ction applies to. Callables should return a string. Types that are not specified (by their corresponding keys) are handled by the default formatters. Individual types for which a formatter can be set are: - 'bool' - 'int' - 'timedelta' : a `numpy.timedelta64` -...
qedsoftware/commcare-hq
corehq/couchapps/tests/test_all_docs.py
Python
bsd-3-clause
3,246
0.003389
from corehq.dbaccessors.couchapps.all_docs import \ get_all_doc_ids_for_domain_grouped_by_db, get_doc_count_by_type, \ delete_all_docs_by_doc_type, get_doc_count_by_domain_type from dimagi.utils.couch.database import get_db from django.test import TestCase class AllDocsTest(TestCase): maxDiff = None ...
'users').uri: ['users_db_doc_all-docs-domain1'], get_db('meta').uri: [], get_db('fixtures').uri: [], get_db('domains').uri: [], get_db('apps').uri: []} ) def
test_get_doc_count_by_type(self): self.assertEqual(get_doc_count_by_type(get_db(None), 'Application'), 2) self.assertEqual(get_doc_count_by_type(get_db('users'), 'CommCareUser'), 2) self.assertEqual(get_doc_count_by_type(get_db(None), 'CommCareUser'), 0) self.assertEqual(get_doc_count_by...
vuolter/pyload
src/pyload/__init__.py
Python
agpl-3.0
1,504
0.000666
# -*- coding: utf-8 -*- # ____________ # ___/ | \_____________ _ _ ___ # / ___/ | _ __ _ _| | ___ __ _ __| | \ # / \___/ ______/ | '_ \ || | |__/ _ \/ _` / _` | \ # \ ◯ | | .__/\_, |____\___/\__,_\__,_| / # \_______\ /_______|_| |__/...
gging import locale import os import pkg_resources import semver import sys import traceback # Info APPID
= "pyload" PKGNAME = "pyload-ng" PKGDIR = pkg_resources.resource_filename(__name__, "") USERHOMEDIR = os.path.expanduser("~") os.chdir(USERHOMEDIR) __version__ = pkg_resources.get_distribution(PKGNAME).parsed_version.base_version __version_info__ = semver.parse_version_info(__version__) # Locale locale.setlocale(...
uclouvain/OSIS-Louvain
base/migrations/0249_auto_20180327_1458.py
Python
agpl-3.0
7,422
0.004042
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2018-03-27 12:58 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('base', '0248_auto_20180328_1347'), # ('attribution', '0032_auto_20180327_1458'), ] ...
deleted is not null OR id in ( SELECT base_learningclassyear.id FROM base_learningclassyear JOIN base_learningcomponentyear on (base_learningcomponentyear.id = base_learningclassyear.learning_component_year_id) JOIN base_le...
on (base_learningcontainer.id = base_learningcontaineryear.learning_container_id) WHERE base_learningclassyear.deleted is null AND ( base_learningcomponentyear.deleted is not null OR base_learningcontaineryear.deleted is not null OR ...
mgrela/whitestar
ansible/roles/whitestar/files/bin/whitestar-watchdog.py
Python
mit
7,240
0.020856
#!/usr/bin/env python2 import os, sys, time, subprocess, threading from struct import pack import kismetclient, netifaces, requests led_device='/dev/serial/by-id/pci-FTDI_USB__-__Serial-if00-port0' ppp_iface = 'ppp0' ovpn_iface = 'tun.bukavpn' uplink_usb_id = '1199:68a3' storage_usb_id = '152d:2336' external_url = 'h...
' kismet_port = 2501 sources = { '39ed09aa-2dcd-4eab-b460-781de88f79d6': { 'interface': 'alfa', 'state': '', 'lastseen': 0, }, 'e8d964d0-9409-408f-a1d7-01e841bae7ed': { 'interface': 'sr71', 'state': '', 'lastseen': 0, }, 'fb187219-afd4-4be8-871a-220d16fb5cb0'
: { 'interface': 'chibi', 'state': '', 'lastseen': 0 } } def purge_sources(): for uuid in sources: if (time.time() - sources[uuid]['lastseen']) > 10: # Source is gone if not receiving updates for 10 seconds sources[uuid]['state'] = '' def update_source_state(client,uuid,error): if uuid in sources:...
plotly/python-api
packages/python/plotly/plotly/validators/histogram2dcontour/hoverlabel/_alignsrc.py
Python
mit
501
0
import _plotly_utils.basevalidators class AlignsrcValidator(_plotly_utils.basevalidators.SrcValidator): def __init__( self
, plotly_name="alignsrc", parent_name="histogram2dcontour.hoverlabel", **kwargs ): super(AlignsrcValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "none"), role=kwargs.pop("ro...
**kwargs )
warddr/wiktionary-frverb
verb-ger.py
Python
gpl-3.0
6,287
0.008133
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys ### auteur: Ward De Ridder ### bedoeling: regelmatige werkwoorden op -cer vervoegen in het Frans werkwoord = input("Werkwoord: ") #werkwoord = developper stam = werkwoord[:-3] FILE = open(werkwoord+".txt","w",encoding='utf-8') begin = "{{-start-}}\n" eind =...
pers=1|num=p|temp=imp}}"+fraverbform+"pers=1|num=p|temp=sp|nohead=1}}") FILE.write(eind) #-ons FILE.write(begin + "'''" + stam + "geons" + "'''") FILE.write(basis) FILE.write(fraverbform+"pers=1|num=p|temp=ip}}"+fraverbform+"pers=1|num=p|temp=impp|nohead=1}}") FILE.write(eind) #-âmes FILE.write(begin + "'''" + stam +...
FILE.write(eind) #-ât FILE.write(begin + "'''" + stam + "geât" + "'''") FILE.write(basis) FILE.write(fraverbform+"pers=3|num=s|temp=simp}}") FILE.write(eind) #-âtes FILE.write(begin + "'''" + stam + "geâtes" + "'''") FILE.write(basis) FILE.write(fraverbform+"pers=2|num=p|temp=ps}}") FILE.write(eind) #-èrent FILE.wr...
cjbrasher/LipidFinder
LipidFinder/PeakFilter/Summary.py
Python
mit
2,682
0.000373
# Copyright (c) 2019 J. Alvarez-Jarreta and C.J. Brasher # # This file is part of the LipidFinder software tool and governed by the # 'MIT License'. Please see the LICENSE file that should have been # included as part of this software. """Set of methods focused on creating a summary of the dataset: > create_summary...
l sample means are before the iso
tope annotation firstIndex = -parameters['numSamples'] * 2 lastIndex = firstIndex + parameters['numSamples'] summaryData = pandas.concat( [data.iloc[:, 0], data[parameters['mzCol']], data[rtCol], data.iloc[:, firstIndex : lastIndex]], axis=1) summaryData.insert(3, 'P...
samstern/MSc-Project
pybrain/rl/environments/timeseries/test programs/ar1TestScript.py
Python
bsd-3-clause
976
0.018443
from pybrain.rl.environments.timeseries.maximizereturntask import DifferentialSharpeRatioTask from pybr
ain.rl.environments.tim
eseries.timeseries import AR1Environment, SnPEnvironment from pybrain.rl.learners.valuebased.linearfa import Q_LinFA from pybrain.rl.agents.linearfa import LinearFA_Agent from pybrain.rl.experiments import ContinuousExperiment from matplotlib import pyplot """ This script aims to create a trading model that trades on...
machristie/airavata
airavata-api/airavata-client-sdks/airavata-python-sdk/src/main/resources/samples/testAiravataClient.py
Python
apache-2.0
1,089
0.003673
#!/usr/bin/env python # # 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 # "L...
# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing p...
ies') as client: client.printProperties() client.printVersion() print client.getAllComputeResourceNames() if __name__ == "__main__": main()
olduvaihand/ProjectEuler
src/python/problem415.py
Python
mit
990
0.002033
# -*- coding: utf-8 -*- # ProjectEuler/src/python/problem415.py # # Titanic sets # ============ # Published on Sunday, 17th February 2013, 10:00 am # # A set of lattice points S is called a titanic set if there exists a line # passing through exactly two points in S. An example of a titanic set is S = # {(0, 0), (0, 1...
ies 0 x, y N. It can be verified # that T(1)
= 11, T(2) = 494, T(4) = 33554178, T(111) mod 108 = 13500401 and # T(105) mod 108 = 63259062. Find T(1011) mod 108. import projecteuler as pe def main(): pass if __name__ == "__main__": main()
IEMLdev/propositions-restful-server
ieml/usl/parser/__init__.py
Python
gpl-3.0
30
0.033333
from .pa
rser import IEMLPa
rser
50wu/gpdb
gpMgmt/bin/gppylib/test/unit/test_unit_gpcheckcat.py
Python
apache-2.0
16,180
0.005562
import imp import logging import os import sys from mock import * from .gp_unittest import * from gppylib.gpcatalog import GPCatalogTable class GpCheckCatTestCase(GpTestCase): def setUp(self): # because gpcheckcat does not have a .py extension, we have to use imp to import it # if we had a gpchec...
# GOOD_MOCK_EXAMPLE for testing functionality in "__main__": put all code inside a method "main()", # which can then be mocked as necessary. with patch.object(sys, 'argv', testargs): self.subject.main() se
lf.assertEqual(self.subject.GV.opt['-B'], len(primaries)) #mock_log.assert_any_call(50, "Truncated batch size to number of primaries: 50") # I am confused that .assert_any_call() did not seem to work as expected --Larry last_call = m
iksteen/jaspyx
jaspyx/visitor/types.py
Python
mit
351
0
import json from jaspyx.visitor i
mport BaseVisitor class Types(BaseVisitor): def visit_Num(self, node):
self.output(json.dumps(node.n)) def visit_Str(self, node): self.output(json.dumps(node.s)) def visit_List(self, node): self.group(node.elts, prefix='[', infix=', ', suffix=']') visit_Tuple = visit_List
nicangeli/Algorithms
arrays/quick_sort/tests.py
Python
mit
1,602
0.003745
import unittest from QuickSort import QuickSort class QuickSortTester(unittest.TestCase): def setUp(self): self.qs = QuickSort() def test_partition(self): arr = [10, 5, 2, 90, 61, 32, 3] #pivot point is 10 #after partition array should be #[5, 2, 3, 10, 90, 61, 32] ...
t, [1, 2, 4, 10, 23, 90, 1001]) def test_quick_sort_on_single_element_array(self): arr = [9] result = self.qs.quick_sort(arr) self.assertEqual(result, [9]) def test_quick_sort_on_two_element_array(self): arr = [2, 1] result = self.qs.quick_sort(arr) self.assertE...
oren88/vasputil
vasputil/tests/test_dos.py
Python
mit
592
0.001689
# -*- coding: utf-8 -*- # vim: set fileencoding=utf-8 # Copyright (c) 2008, 2010 Janne Blomqvist
# This source code file is subject to the terms of the MIT (Expat) # License. See the file LICENSE for details. """This module contains unit tests for the vasputil.dos module.""" import unittest import vasputil.dos as d class LdosTestCase(unittest.TestCase): """Testcase for vasputil.dos.LDOS class.""" def suit...
der().loadTestsFromTestCase(LdosTestCase) return unittest.TestSuite([ldos_suite]) if __name__ == "__main__": unittest.main()
cjaymes/pyscap
src/scap/model/xnl_2_0/GeneralSuffixElement.py
Python
gpl-3.0
962
0.00104
# Copyright 2016 Casey Jaymes # T
his file is part of PySCAP. # # PySCAP 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. # # PySCAP is distributed in the hope that it wi...
he 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 PySCAP. If not, see <http://www.gnu.org/licenses/>. from scap.Model import Model import logging logg...
yes7rose/maya_utils
python/maya_utils/api_utils.py
Python
mit
2,347
0.005113
# encoding:utf-8 import logging import maya.api.OpenMaya as om # fast convenience tests on API objects def isValidMObjectHandle(obj): if isinstance(obj, om.MObjectHandle): return obj.isValid() and obj.isAlive() else: return False def isValidMObject(obj): if isinstance(obj, om.MObject): ...
bj) or isValidMNode(obj) # returns a MObject for an existing node def toMObject(nodeName): """ Get the API MObject given the name of an existing node """ sel = om.MSelectionList() obj = om.MObject() result = None
try: sel.add(nodeName) sel.getDependNode(0, obj) if isValidMObject(obj): result = obj except: pass return result def toMDagPath(nodeName): """ Get an API MDagPAth to the node, given the name of an existing dag node """ obj = toMObject(nodeName) if obj...
Micronaet/micronaet-bom
lavoration_cl_sl_mrp/__openerp__.py
Python
agpl-3.0
1,541
0.001298
############################################################################### # # Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.it>). # # 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 ...
duction_accounting_external', 'lavoration_cl_sl', ], 'i
nit_xml': [], 'demo': [], 'data': [ 'mrp_view.xml', ], 'active': False, 'installable': True, 'auto_install': False, }
forcecore/yupgi_alert0
assets/shp/slave/run.py
Python
gpl-3.0
385
0.002597
#!/usr/bin/python3 #!/usr/bin/python3 from PIL import Image, ImageDraw import glob impor
t os from recolor import replace_color dest = "." for fname in glob.glob("in/*.png"): im = Image.open(fname) replace_color(im, range(112,
123+1), range(80, 95+1)) _, ofname = os.path.split(fname) ofname = os.path.join(dest, ofname) print(fname, ofname) im.save(ofname)
mcallaghan/tmv
BasicBrowser/twitter/migrations/0021_auto_20200214_1232.py
Python
gpl-3.0
784
0.002551
# Generated by Django 2.2 on 2020-02-14 12:32 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('scoping', '0315_auto_20200114_1420'), ('twitter', '0020_auto_20200115_1237'), ] operations = [
migrations.AddField( model_name='twitt
ersearch', name='project_list', field=models.ManyToManyField(related_name='plist_TwitterSearches', to='scoping.Project'), ), migrations.AlterField( model_name='twittersearch', name='project', field=models.ForeignKey(null=True, on_delete=django....
t3dev/odoo
addons/base_automation/tests/test_models.py
Python
gpl-3.0
1,762
0.00227
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from dateutil import relativedelta from odoo import fields, models, api class LeadTest(models.Model): _name = "base.automation.lead.test" _description = "Automated Rule Test" name = fields.Char(string='Sub...
string="Status", readonly=True, default='draft') active = fields.Boolean(default=True) partner_id = fields.Many2one('res.partner', string='Partner') date_action_last = fields.Datetime(string='Last Action', readonly=True) customer = fields.Boolean(related='partner_id.customer', readonly=True, sto...
_deadline', store=True) is_assigned_to_admin = fields.Boolean(string='Assigned to admin user') @api.depends('priority') def _compute_deadline(self): for record in self: if not record.priority: record.deadline = False else: record.deadline = fi...
mick-d/nipype
nipype/pipeline/plugins/tests/test_tools.py
Python
bsd-3-clause
1,756
0.006264
# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Tests for the engine module """ import numpy as np import scipy.sparse as ssp import re import mock from nipype.pipeline.plugins.tools import report_crash def test_report_crash...
code to test that a mapnode crash continues successfully Need to put this into a nose-test with a timeout import nipype.interfaces.utility as niu import nipype.pipeline.engine as pe wf = pe.Workflow(name='test') def func(arg1): if arg1 == 2:
raise Exception('arg cannot be ' + str(arg1)) return arg1 funkynode = pe.MapNode(niu.Function(function=func, input_names=['arg1'], output_names=['out']), iterfield=['arg1'], name = 'functor') funkynode.inputs.arg1 = [1,2] wf.add_nodes([funkynode]) wf.base_dir = '/t...
kenshay/ImageScript
ProgramData/SystemFiles/Python/Lib/site-packages/elan/Backup Pools/Repeat_One_Test/1____Serial_Device_Settings_Change_Check.py
Python
gpl-3.0
1,335
0.019476
from ImageScripter import * from elan import * raise ValueError('fff') Viewer.Start() Viewer.CloseAndClean() Configurator.Start() Configurator.inputoutput.Click() addNewComDev(ComType = "Standard Connection",HardwareType = "Serial Port",Comport = '0') addNewDevice(Configurator.genericserialdevices,"Generic Serial De...
') HlConfig.PushButton.Click('Yes') Configurator.atatat2.WaitVanish() Configurator.system.Click() Conf
igurator.Reset()
iamaris/pystock
scansingle.py
Python
apache-2.0
2,023
0.024221
import urllib import pandas as pd import pandas.io.data as web #from datetime import datetime import matplotlib.pyplot as plt import pickle as pk from pandas.tseries.offsets import BDay # pd.datetime is an alias for datetime.datetime #today = pd.datetime.today() import time #time.sleep(5) # delays for 5 seconds today ...
r(stock, "google", yesterday,today) if len(price.index)==2: if price.at[price.index[0],'High'] > price.at[price.index[1],'High']: if price.at[price.index[0],'Low'] < price.at[price.index[1],'Low']: prin
t stock, price.at[price.index[1],'High'], price.at[price.index[1],'Low'],(price.at[price.index[1],'High']-price.at[price.index[1],'Low']) except: pass #pk.dump(znga, open( "znga.p", "wb" )) #znga2 = pk.load( open( "znga.p", "rb" ) ) #print znga2 """ z = znga['Adj Close'].sum() g = gluu['Adj Close'].sum() zz = z...
Bouke/mvvm
mvvm/viewbinding/display.py
Python
mit
6,057
0.001816
import time import wx class ShowBinding(object): def __init__(self, field, trait, show_if_value=True): self.field, self.trait, self.show_if_value = field, trait, show_if_value trait[0].on_trait_change(self.update_view, trait[1], dispatch='ui') self.update_view() def update_view(self):...
ge(self.update_view, trait[1], dispatch='ui') self.update_view() def update_view(self): self.field.SetLabel(unicode(getattr(*self.trait))) class StatusBarBinding(object): def __init__(self, field, trait, field_number): self.field, self.trait, self.field_number = (field, trait, fie
ld_number) trait[0].on_trait_change(self.update_view, trait[1], dispatch='ui') self.update_view() def update_view(self): self.field.SetStatusText(getattr(*self.trait), self.field_number) class TitleBinding(object): def __init__(self, field, trait): self.field, self...
mhbu50/erpnext
erpnext/payroll/doctype/employee_tax_exemption_category/employee_tax_exemption_category.py
Python
gpl-3.0
218
0.004587
# C
opyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors # For license information, pleas
e see license.txt from frappe.model.document import Document class EmployeeTaxExemptionCategory(Document): pass
khrapovs/diffusions
diffusions/param_vasicek.py
Python
mit
2,899
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Vasicek parameter class ~~~~~~~~~~~~~~~~~~~~~~~ """ from __future__ import print_function, division import numpy as np from .param_generic import GenericParam __all__ = ['VasicekParam'] class VasicekParam(GenericParam): """Parameter storage for Vasicek model....
"""
return 'Vasicek' @staticmethod def get_names(subset='all', measure='PQ'): """Return parameter names. Returns ------- (3, ) list of str Parameter names """ return ['mean', 'kappa', 'eta'] def get_theta(self, subset='all', measure='PQ'): ...
fausecteam/ctf-gameserver
src/ctf_gameserver/web/templatetags/__init__.py
Python
isc
311
0.006472
""" "Custom template tags and filters must live inside a Django app. If they relate to an existing app it makes sense to bundl
e them there; otherwise, you should create a new app to hold them." – https://docs.djangoproject.com/en/1.8/howto/custom-template-tags/ This
is such an app to hold template tags. """
mrunge/openstack_horizon
openstack_horizon/dashboards/admin/volumes/volume_types/extras/views.py
Python
apache-2.0
3,595
0
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
(self): return ("/admin/volumes/volume_types/%s/extras/" % (self.kwargs['type_id'])) class EditView(ExtraSpecMixin, forms.ModalFormView): form_class = project_forms.EditExtraSpec template_name = 'admin/volumes/volume_types/extras/edit.html' success_url =
'horizon:admin:volumes:volume_types:extras:index' def get_success_url(self): return reverse(self.success_url, args=(self.kwargs['type_id'],)) def get_initial(self): type_id = self.kwargs['type_id'] key = self.kwargs['key'] try: extra_specs = ...
zhangw/leancloud_apperance_app
views/weibos.py
Python
mit
1,920
0.017857
# coding: utf-8 from leancloud import Object from leancloud import Query from leancloud import LeanCloudError from flask import Blueprint from flask import request from flask import redirect from flask import url_for from flask import render_template import sys sys.path.insert(0,'../') from utils import JsonDict import...
weibos = Query(Weibo).descending('createdAt').find() except LeanCloudError, e: #服务端还没有Weibo这个Class if e.code == 101: weibos = [] else: raise e return render_template('weibo
s.html', weibos=weibos) """ try: todos = Query(Todo).descending('createdAt').find() except LeanCloudError, e: if e.code == 101: # 服务端对应的 Class 还没创建 todos = [] else: raise e return render_template('todos.html', todos=todos) """ @weibos_handler.route('...
tobspr/RenderPipeline-Samples
03-Lights/main.py
Python
mit
5,332
0.002063
""" Lights sample This sample shows how to setup multiple lights and load them from a .bam file. """ # Disable the "xxx has no yyy member" error, pylint seems to be unable to detect # the properties of a nodepath # pylint: disable=no-member from __future__ import print_function import os import sys import math fr...
the motion blur blend_type = "noBlend" np = model.find("**/MBRotate") np.hprInterval(1.5, Vec3(360,
360, 0), Vec3(0, 0, 0), blendType=blend_type).loop() np = model.find("**/MBUpDown") np_pos = np.get_pos() - Vec3(0, 0, 2) Sequence( np.posInterval(0.15, np_pos + Vec3(0, 0, 6), np_pos, blendType=blend_type), np.posInterval(0.15, np_pos, np_pos + Vec3(0, 0, 6), blendType...
mct/kohorte
p2p/child.py
Python
gpl-2.0
2,883
0.001734
#!/usr/bin/env python # vim:set ts=4 sw=4 ai et: # Kohorte, a peer-to-peer protocol for sharing git repositories # Copyright (c) 2015, Michael Toren <kohorte@toren.net> # Released under the terms of the GNU GPL, version 2 import fcntl import traceback import os import signal from subprocess import Popen, PIPE, STDOU...
id(self) def __init__(self, peer, tag, cmd): self.tag = tag self.peer = peer self.cmd = cmd self.popen = Popen(cmd, stdout=PIPE, stderr=STDOUT, preexec_fn=os.setsid) self.pid = self.popen.pid self.fd = self.popen.stdout self.eof = False self.closed =...
Set non-blocking flags = fcntl.fcntl(self.fd, fcntl.F_GETFL) flags |= os.O_NONBLOCK fcntl.fcntl(self.fd, fcntl.F_SETFL, flags) print timestamp(), self, "Running", repr(' '.join(cmd)) EventLoop.register(self) def fileno(self): return self.fd.fileno() def close(...
thierrymarianne/valuenetwork
valuenetwork/valueaccounting/migrations/0018_auto__add_field_commitment_stage__add_field_commitment_state__add_fiel.py
Python
agpl-3.0
53,765
0.006882
# -*- 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 field 'Commitment.stage' db.add_column('valueaccounting_commitment', 'stage', ...
, [], {'max_length': '32', '
null': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'plural_name': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '128'}) }, 'valueaccounting.agentresourcerole': { 'Meta': {'object_name': 'AgentResource...
mworion/mountwizzard
mountwizzard/mount/ascommount.py
Python
apache-2.0
12,566
0.004536
############################################################ # -*- coding: utf-8 -*- # # Python-based Tool for interaction with the 10micron mounts # GUI with PyQT5 for python # Python v3.5 # # Michael Würtenberger # (c) 2016, 2017, 2018 # # Licence APL2.0 # ############################################################...
driver_real and self.connected: try: # all with error handling if command in self.app.mount.BLIND_COMMANDS: # these are th...
# than do blind command else: # reply = self.ascom.CommandString(command) # with return value ...
skk/eche
eche/tests/test_step3_env.py
Python
mit
1,749
0.000572
import pytest from eche.env import get_default_env from eche.tests import eval_ast_and_verify_env, eval_ast_and_read_str from eche.eche_types import Node from eche.eche_types import List from eche.eval import eval_ast from eche.reader import read_str import eche.step3_env as step @pytest.mark.parametrize("test_input...
nput", [ '(7 8)' ]) def test_read(test_input): assert step.READ(test_input) == List(7, 8) @pytest.mark.parametrize("test_input", [ '(1 2 3)', '(+ 1 2)' ]) def test_eval(test_input): assert step.EVAL(test_input, None) == test_input @pytest.mark.parametrize("test_input", [ '(- 2 3)', '(% 1...
'[5 6 7]' ]) def test_rep(test_input): assert step.REP(test_input) @pytest.mark.parametrize("test_input,expected_value", [ ('(let* (c 2) c)', 2), ('(let* (a 1 b 2) (+ a b))', 3), ('(let* (a 1 b 2 c 3) (+ (* a b) (^ 2 c)))', 10), ]) def test_let_star(test_input, expected_value): assert eval_ast_an...
ishahid/django-blogg
source/website/wsgi.py
Python
mit
524
0.001908
""" WSGI config for lms 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 from os.path import abspath, dirname from sys import path SITE_ROOT = dirname(dirname(abspath(__file__))) path.append(SITE_ROOT) os.environ.setdefault("DJANGO_SETT...
()
joaduo/xpathwebdriver
xpathwebdriver/default_settings.py
Python
mit
5,213
0.004796
# -*- coding: utf-8 -*- ''' xpathwebdriver Copyright (c) 2014 Juju. Inc Code Licensed under MIT License. See LICENSE file. ''' from xpathwebdriver.solve_settings import ConfigVar, BaseSettings import logging class DefaultSettings(BaseSettings): base_url = ConfigVar( doc='specifies the root URL string to ...
DEPRECATED: Specify firefox's profile path Eg: '/home/<user>/.mozilla/firefox/4iyhtofy.xpathwebdriver'", default=None, parser=str) webdriver_browser_profile = ConfigVar( doc="Specify browser's profile path Eg: '/home/<user>/.mozilla
/firefox/4iyhtofy.xpathwebdriver'", default=None, parser=str) webdriver_window_size = ConfigVar( doc='Dimensions in pixels of the Browser\'s window', default=(800, 600), parser=eval) #Remote driver related settings webdriver_remote_credentials_path = ConfigVar( ...
mozilla/verbatim
vendor/lib/python/webassets/merge.py
Python
gpl-2.0
12,313
0.000893
"""Contains the core functionality that manages merging of assets. """ from __future__ import with_statement import contextlib import urllib2 import logging try: import cStringIO as StringIO except: import StringIO from utils import cmp_debug_levels __all__ = ('FileHunk', 'MemoryHunk', 'merge...
raise NotImplementedError() def __hash__(self): return hash(self.data()) def __eq__(self, other): if isinstance(other, BaseHunk): # Allow class to be used as a unique dict key. return hash(self) == hash(other) return False def data(self): ...
ite(self.data()) class FileHunk(BaseHunk): """Exposes a single file through as a hunk. """ def __init__(self, filename): self.filename = filename def __repr__(self): return '<%s %s>' % (self.__class__.__name__, self.filename) def mtime(self): pass de...
Peter-Collins/NormalForm
src/config-run/RunHill.py
Python
gpl-2.0
1,029
0.015549
""" AUTHOR: Peter Collins, 2005.
This software is Copyright (C) 2004-2008 Bristol University and is released under the GNU General Public License version 2. MODULE: RunHill PURPOSE: A sample setup and configuration for the normalization algorithms. NOTES: See RunConfig.py for configuration options """ import sys import RunConfig degree = 6 if ...
2h config = { "tolerance" : 5.0e-14 , "degree" : degree , "system" : "Hill" , "do_stream" : False , "compute_diagonalisation" : True , "run_normal_form_python" : False , "run_normal_form_cpp" : True } RunConfig.NfConfig(config).run_examp() # Now do a python run if degree is...
ganong123/HARK
cstwMPC/cstwMPC.py
Python
apache-2.0
45,177
0.001549
''' <<<<<<< HEAD This package contains the estimations for cstwMPC. ======= Nearly all of the estimations for the paper "The Distribution of Wealth and the Marginal Propensity to Consume", by Chris Carroll, Jiri Slacalek, Kiichi Tokuoka, and Matthew White. The micro model is a very slightly altered version of ConsIndS...
def assignBetaDistribution(type_list,DiscFac_list): ''' Assigns the discount factors in DiscFac_list to the types in type_list. If there is heterogeneity beyond the discount factor, then the same DiscFac is assigned to consecutive types. Parameters ---------- type_list : [cstwMPCage
nt] The list of types that should be assigned discount factors. DiscFac_list : [float] or np.array List of discount factors to assign to the types. Returns ------- none ''' DiscFac_N = len(DiscFac_list) type_N = len(type_list)/DiscFac_N j = 0 b = 0 while ...
toogad/PooPyLab_Project
PooPyLab/ASMModel/asm_2d.py
Python
gpl-3.0
24,192
0.003555
# This file is part of PooPyLab. # # PooPyLab is a simulation software for biological wastewater treatment processes using International Water Association # Activated Sludge Models. # # Copyright (C) Kai Zhang # # PooPyLab is free software: you can redistribute it and/or modify it under the terms of the GNU Gener...
onification of Org-N in biomass (k_a, L/mgBiomassCOD-day) self._params['k_a'] = self._kinetics_20C['k_a']\ * pow(1.072, self._delta_t) # Yield of Hetero. Growth on COD (Y_H, mgBiomassCOD/mgCODremoved) sel
f._params['Y_H'] = self._kinetics_20C['Y_H'] # Yield of Auto. Growth on TKN (Y_A, mgBiomassCOD/mgTKNoxidized) self._params['Y_A'] = self._kinetics_20C['Y_A'] # Fract. of Debris in Lysed Biomass(f_D, gDebrisCOD/gBiomassCOD) self._par
Goldmund-Wyldebeast-Wunderliebe/raven-python
tests/contrib/zerorpc/tests.py
Python
bsd-3-clause
2,939
0.001021
import os import pytest import random import shutil import tempfile from raven.utils.testutils import TestCase from raven.base import Client from raven.contrib.zerorpc import SentryMiddleware zerorpc = pytest.importorskip("zerorpc") gevent = pytest.importorskip("gevent") class TempStoreClient(Client): def __ini...
lf.assertEqual(frames
[0]['function'], 'choice') self.assertEqual(frames[0]['module'], 'random') return self.fail('An IndexError exception should have been sent to Sentry') def tearDown(self): self._client.close() self._server.close() shutil.rmtree(self._socket_dir, ignor...
oderby/VVD
diffgraph.py
Python
mit
602
0.009967
import CommonGraphDiffer as cgd import argparse def parseArgs(): parser = argparse.ArgumentParser() parser.add_argument("cg1", help="This is the first .CGX (CommonGraph) file") parser.add_argument("cg2", help="This is the second .CGX (CommonGraph) file") parser.add_argument("ds", help="This is the outp...
1) CGB = cgd.CgxToObject(args.cg2) ds = CGA.diff(CGB) print ds cgd.DSToXML(ds, args.ds) if __name__ == "__main__": main()
annaelde/forum-app
site/users/serializers.py
Python
mit
859
0.002328
from rest_framework.serializers import (DateTimeField, ModelSerializer, PrimaryKeyRelatedField, SerializerMethodField) from threads.models import Post from threads.serializers import PostSerializer from .models import User class BaseUserSerializer(ModelSerializer): posts =...
= ('username', 'avatar', 'date_joined', 'posts', 'bio') class PrivateUserSerializer(BaseUserSerializ
er): class Meta(BaseUserSerializer.Meta): fields = ('username', 'avatar', 'email', 'date_joined', 'last_login', 'posts', 'bio')
sinotradition/sinoera
sinoera/tiangan/wu4.py
Python
apache-2.0
217
0.03271
#!/usr/bin/python #coding=utf-8 ''' @author: sheng @contact: sinotradition@gm
ail.com @copyright: License according to the project license. ''' NAME='wu4' SPELL='wù' CN='戊' SEQ='5' if __name__=='__main__':
pass
foodsnag/foodsnag-web
app/api/events.py
Python
mit
576
0.020833
from flask import jsonify, request from .. import db from ..
models import Event from . import api # Get event @api.route('/event/<int:id>') def get_event(id): event = Event.query.get_or_404(id) # TODO: Implement when the model updates attendees_count = 1 json_post = event.to_json() # TODO: Change when new model is available json_post['num_attendees'] = attendees_c...
/<int:id>/attending') def get_attendees(id, lim): # TODO: Implement when new model available pass
ElliotTheRobot/LILACS-mycroft-core
mycroft/skills/LILACS_chatbot/__init__.py
Python
gpl-3.0
5,092
0.002357
# Copyright 2016 Mycroft AI, Inc. # # This file is part of Mycroft Core. # # Mycroft Core 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 versio...
ot_on") def stop(self): self.handle_deactivate_intent("global stop") def converse(self, transcript, lang="en-us"): # parse 1st utterance for entitys if self.active and "bump chat" not in transcript[0] and "bump curiosity" not in transcript[0]: nodes, parents, synonims = sel...
self.log.info("nodes: " + str(nodes)) self.log.info("parents: " + str(parents)) self.log.info("synonims: " + str(synonims)) # get concept net , talk possible_responses = [] for node in nodes: try: dict = self.servic...
plotly/python-api
packages/python/plotly/plotly/validators/layout/scene/annotation/_startarrowsize.py
Python
mit
557
0
import _plotly_utils.basevalidators class StartarrowsizeValidator(_plotly_utils.basevalidators.NumberValidator): def __init__( self, plotly_name="startarrowsize", parent_name="layout.scene.annotation", **kwargs ): supe
r(StartarrowsizeValidator, self).__init__( plotly_name=plotly_name, parent_name=p
arent_name, edit_type=kwargs.pop("edit_type", "calc"), min=kwargs.pop("min", 0.3), role=kwargs.pop("role", "style"), **kwargs )
sergiusens/snapcraft
tests/integration/general/test_prime_filter.py
Python
gpl-3.0
1,931
0.001036
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright (C) 2016-2018 Canonical Ltd # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in ...
"], "prime-filter") # Verify that only
the `prime1` file made it into prime (i.e. `prime2` # was filtered out). self.assertThat(os.path.join(self.prime_dir, "prime1"), FileExists()) self.assertThat(os.path.join(self.prime_dir, "prime2"), Not(FileExists())) def test_snap_filter_is_deprecated(self): output = self.run_snapc...
ekasitk/sahara
sahara/tests/tempest/scenario/data_processing/client_tests/test_data_sources.py
Python
apache-2.0
3,802
0
# Copyright (c) 2014 Mirantis 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 ...
urce response body because response body has no 'credentials' # field. self.swift_data_source = self.swift_data_source_with_creds.copy() del self.swift_data_source
['credentials'] source_id, source_name = self._check_data_source_create( self.swift_data_source_with_creds) self._check_data_source_list(source_id, source_name) self._check_data_source_get(source_id, source_name, self.swift_data_source) sel...
pizzathief/scipy
scipy/misc/common.py
Python
bsd-3-clause
9,678
0.006716
""" Functions which are common and require SciPy Base and Level 1 SciPy (special, linalg) """ from numpy import arange, newaxis, hstack, prod, array, frombuffer, load __all__ = ['central_diff_weights', 'derivative', 'ascent', 'face', 'electrocardiogram'] def central_diff_weights(Np, ndiv=1): """ ...
'uint8') return face def electrocardiogram(): """ Load an electrocardiogram as an example for a 1-D signal. The returned signal is a 5 minute long electrocardiogram (ECG), a medical recording of the heart's electrical activity, sampled at 360 Hz. Returns ------- ecg : ndarray ...
_ (lead MLII) provided by the MIT-BIH Arrhythmia Database [1]_ on PhysioNet [2]_. The excerpt includes noise induced artifacts, typical heartbeats as well as pathological changes. .. _record 208: https://physionet.org/physiobank/database/html/mitdbdir/records.htm#208 .. versionadded:: 1.1.0 R...
jcsp/manila
manila/tests/share/test_migration.py
Python
apache-2.0
19,945
0.00005
# Copyright 2015 Hitachi Data Systems 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 # # Unless...
context, db, driver.CONF.migration_create_delete_share_timeout, driver.CONF.migration_wait_access_rules_timeout, self.share) def test_deny_rules_and_wait(self): saved_rules = [db_utils.create_access(share_id=self.share['id'], state=constants.STATUS_ACTIVE)] ...
ance') self.mock_object(db, 'share_access_get_all_for_share', mock.Mock(side_effect=[saved_rules, []])) self.mock_object(time, 'sleep') self.helper.deny_rules_and_wait( self.context, self.share, saved_rules) db.share_access_get_all_for_share.assert_...
dariansk/python_training
generator/contact.py
Python
apache-2.0
1,606
0.006227
from model.contact import Contact import random import string import os.path import js
onpickle import getopt import sys try: opts, args = getopt.getopt(sys.argv[1:], "n:f", ["number of contacts", "file"]) except getopt.GetoptError as err: getopt.usage() sys.exit(2) n = 5 f = "data/contacts.json" for o, a in opts:
if o == "-n": n = int(a) elif o == "-f": f = a def random_string(prefix, maxlen): symbols = string.ascii_letters + string.digits + string.punctuation + " "*10 return prefix + "".join([random.choice(symbols) for i in range(random.randrange(maxlen))]) def random_string_phone(prefix, m...
waxkinetic/fabcloudkit
fabcloudkit/build_tools/python_build.py
Python
bsd-3-clause
7,221
0.003324
""" fabcloudkit :copyright: (c) 2013 by Rick Bohrer. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import # pypi from fabric.context_managers import cd, prefix, settings from fabric.operations import run, sudo from fabric.state import env # package from fabcloudkit impo...
alse], and an "ignore_fail" value of [True|False]. :param interpreter: specifies the Python interpreter to use in the build's virtualenv. if not specified, the operating system default interpreter is used. note that the interpreter must alr
eady exist on the system. :param tarball: True to create a tarball of the build; this is required if any other instance will use "copy_from". :param unittest: TBD :return: the new build name """ start_msg('Executing build for ins...
uchchwhash/fortran-linter
docs/source/conf.py
Python
mit
9,283
0.006033
# -*- coding: utf-8 -*- # # fortran-linter documentation build configuration file, created by # sphinx-quickstart on Fri Jun 9 02:28:25 2017. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file...
relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = ...
17, Imam Alam' author = u'Imam Alam' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = u'0.6' # The full version, including alpha/beta/rc tags. release = u'0....
titom73/inetsix-config-builder
setup.py
Python
gpl-2.0
1,313
0
import shutil from setuptools import setup # Load list of requirements from req file with open('requirements.txt') as f: REQUIRED_PACKAGES = f.read().splitlines() # Load description from README file with open("README.md", "r") as fh: LONG_DESCRIPTION = fh.read() # Rename Scripts to sync with original name sh...
ong_description_content_type='text/markdown', zip_safe=False, classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Programmi
ng Language :: Python :: 2.7", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", 'Environment :: Console', 'Intended Audience :: Information Technology', 'Intended Audience :: Telecommunications Industry', 'Natural Language :: English', ]...
RTS2/rts2
scripts/u_point/u_point/httpd_connection.py
Python
lgpl-3.0
3,250
0.009846
# (C) 2016, Markus Wildi, wildi.markus@bluewin.ch # # 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, or (at your option) # any later version. # # This program is distr...
er_name=pwd.getpwuid(os.getuid())[0] db_name='stars' conn = psycopg2.connect('dbname={} user={} password={}'.format(db_name, db_user_name, '')) crsr = conn.cursor() crsr.execute('DELETE FROM users WHERE usr_login=\'{}\' ;'.format(user_name)) result=crsr.rowcount conn.commit() crsr.close() ...
l: {}'.format(crsr.statusmessage)) if result == 1: lg.info('user: {} deleted from database'.format(user_name)) elif result == 0: pass else: lg.warn('delete user: {} manually, result: {}'.format(user_name, result))
RENCI/xDCIShare
hs_geo_raster_resource/tests/test_raster_metadata_user_zone.py
Python
bsd-3-clause
8,568
0.002801
from django.test import TransactionTestCase from django.contrib.auth.models import Group from django.conf import settings from hs_core import hydroshare from hs_core.hydroshare import utils from hs_core.models import CoreMetaData from hs_core.testing import TestCaseCommonUtilities class TestRasterMetaData(TestCaseCo...
super(TestRasterMetaData, self).tearDown() if not super(TestRasterMetaData, self).is_federated_irods_available(): return super(TestRasterMetaData, self).delete_irods_user_in_user_zone() def test_metadata_in_user_zone(self): # only do federation testing when REMOTE_USE_IRODS i
s True and irods docker containers # are set up properly if not super(TestRasterMetaData, self).is_federated_irods_available(): return # test metadata extraction with resource creation with tif file coming from user zone space fed_test_file_full_path = '/{zone}/home/{username...
redhat-cip/dci-control-server
tests/api/v1/test_issues.py
Python
apache-2.0
15,798
0.000886
# -*- coding: utf-8 -*- # # Co
pyright (C) 2016 Red Hat, 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, sof...
nse for the specific language governing permissions and limitations # under the License. from __future__ import unicode_literals import mock import requests GITHUB_TRACKER = "dci.trackers.github.requests" BUGZILLA_TRACKER = "dci.trackers.bugzilla.requests" def test_attach_issue_to_job(user, job_user_id, topic_user...
SciTools/iris
lib/iris/tests/unit/coord_systems/test_VerticalPerspective.py
Python
lgpl-3.0
3,251
0
# Copyright Iris contributors # # This file is part of Iris and is released under the LGPL license. # See COPYING and COPYING.LESSER in the root of the repository for full # licensing details. """Unit tests for the :class:`iris.coord_systems.VerticalPerspective` class.""" # Import iris.tests first so that some things ...
eck for propert
y defaults when no kwargs options were set. # NOTE: except ellipsoid, which is done elsewhere. self.assertEqualAndKind(crs.false_easting, 0.0) self.assertEqualAndKind(crs.false_northing, 0.0) def test_no_optional_args(self): # Check expected defaults with no optional args. c...
piotroxp/scibibscan
scib/lib/python3.5/site-packages/astropy/visualization/__init__.py
Python
mit
180
0
# Licensed under a 3-clause BSD
style license - see LICENSE.rst from .stretch import * from .interval import * from .transform import * from .ui import * from .mpl_style
import *
4dn-dcic/fourfront
src/encoded/tests/test_upgrade_data_release_update.py
Python
mit
3,172
0.000631
import pytest pytestmark = [pytest.mark.setone, pytest.mark.working] @pytest.fixture def data_release_update_1(award, lab): return{ "schema_version": '1', "award": award['@id'], "lab": lab['@id'], "summary": "Upgrader test.", "update_tag": "UPGRADERTEST", "submitted...
upgrade('data_release_update', data_release_update_1, current_version='1', target_version='2') assert value['schema_version'] == '2' update_items = value['update_items'] assert len(update_items) == 1 assert 'primary_id' in update_items[0] assert 'secondary_ids' in update_items[0] assert 'seconda...
y_ids']) == 1 def test_data_release_updates_secondary_ids_to_objects( app, data_release_update_2): """ Needed because secondary IDs got the 'additional_info' field and are now an array of objects """ migrator = app.registry['upgrader'] value = migrator.upgrade('data_release_update', da...
vicnet/weboob
modules/suravenir/pages.py
Python
lgpl-3.0
4,491
0.00468
# -*- coding: utf-8 -*- # Copyright(C) 2018 Arthur Huillet # # This file is part of a weboob module. # # This weboob module 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 Licens...
obj_code = CleanText(TableCell("ISIN"), default=NotAvailable) obj_code_type = Investment.CODE_TYPE_ISIN obj_quantity = CleanDecimal(TableCell("qty
"), replace_dots=True, default=NotAvailable) obj_unitprice = CleanDecimal(TableCell("unitprice"), replace_dots=True, default=NotAvailable) obj_unitvalue = CleanDecimal(TableCell("unitvalue"), replace_dots=True, default=NotAvailable) obj_valuation = CleanDecimal(TableCell("valuation")...
SoundGoof/NIPAP
nipap/nipap/authlib.py
Python
mit
24,138
0.002941
""" Authentication library ====================== A base authentication & authorization module. Includes the base class BaseAuth. Authentication and authorization in NIPAP ----------------------------------------- NIPAP offers basic authentication with two different backends, a simple two...
All authentication modules should extend this class. """ username = None password = None authenticated_as = None full_name = None authoritative_source = None auth_backend = None trusted = None readonly = None _logger = None _auth_options = None _c
fg = None def __init__(self, username, password, authoritative_source, auth_backend, auth_options=None): """ Constructor. Note that the instance variables not are set by the constructor but by the :func:`authenticate` method. Therefore, run the :func:`authenticate`-met...
mlongo4290/mattermost-wunderground-slash-command
wunderground-slash-command.py
Python
gpl-3.0
4,117
0.00486
from http.server import BaseHTTPRequestHandler, HTTPServer import requests import urllib.parse import json # Define server address and port, use localhost if you are running this on your Mattermost server. HOSTNAME = '' PORT = 7800 # guarantee unicode string _u = lambda t: t.decode('UTF-8', 'replace') if isinstance(t...
token = "" channel_id = "" team_id = "" command = "" team_domain = "" user_name = "" channel_name = "" # Get POST data and initialize MattermostRequest object for key in data: if key == 'response_url': response_url = da...
ext': text = data[key] elif key == 'token': token = data[key] elif key == 'channel_id': channel_id = data[key] elif key == 'team_id': team_id = data[key] elif key == 'command': command = data[...
OlegGirko/osc
osc/OscConfigParser.py
Python
gpl-2.0
13,677
0.003436
# Copyright 2008,2009 Marcus Huewe <suse-tux@gmx.de> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License version 2 # as published by the Free Software Foundation; # # This program is distributed in the hope that it will be useful, # but WITHOUT...
me, type): self.name = name self.type = type class SectionLine(Line): """ This class represents a [section]. It stores all lines which belongs to this certain section in the _lines list. The _lines list either contains CommentLine() or OptionLine() instances. """ def __init__(se...
{}): Line.__init__(self, sectname, 'section') self._lines = [] self._dict = dict def _find(self, name): for line in self._lines: if line.name == name: return line return None def _add_option(self, optname, value = None, line = None, sep = '='...
RlSEN/bannedcho
c.ppy.sh/loginEvent.py
Python
gpl-3.0
7,180
0.02507
import userHelper import serverPackets import exceptions import glob import consoleHelper import bcolors import locationHelper import countryHelper import time import generalFunctions import channelJoinEvent def handle(flaskRequest): # Data to return responseTokenString = "ayy" responseData = bytes() # The IP for ...
.logInIP(userID) # Get location and country from ip.zxq.co or database if generalFunctions.stringToBool(glob.conf.config["server"]["localizeusers"]): # Get location and country from IP location = locationHelper.getLocation(requestIP) country = countryHelper.getCountryID(locationHelper.getCountry(requestI...
# Set location to 0,0 and get country from db print("[!] Location skipped") location = [0,0] country = countryHelper.getCountryID(userHelper.getCountry(userID)) # Set location and country responseToken.setLocation(location) responseToken.setCountry(country) # Send to everyone our userpanel and userSt...
lukas-hetzenecker/home-assistant
homeassistant/components/viaggiatreno/sensor.py
Python
apache-2.0
5,443
0.000367
"""Support for the Italian train system using ViaggiaTreno API.""" import asyncio import logging import time import aiohttp import async_timeout import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import ATTR_ATTRIBUTION, HTTP_OK, TIME_MINUTES im...
igine", "subTitle", ] DEFAULT_NAME = "Train {}" CONF_NAME = "train_name" CONF_STATION_ID = "station_id" CONF_STATION_NAME = "station_name" CONF_TRAIN_ID = "train_id" ARRIVED_STRING = "Arrived" CANCELLED_STRING = "Cancelled" NOT_DEPARTED_STRING = "Not departed yet" NO_INFORMATION_STRING = "No information for this...
al(CONF_NAME): cv.string, } ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the ViaggiaTreno platform.""" train_id = config.get(CONF_TRAIN_ID) station_id = config.get(CONF_STATION_ID) if not (name := config.get(CONF_NAME)): name = DEFAULT_...
avoinsystems/product_lot_sequence
__init__.py
Python
agpl-3.0
994
0.002012
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2015 Avoin Systems (http://avoin.systems). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # publ...
gram 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 the GNU Affero General Public ...
am. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## # noinspection PyUnresolvedReferences import product, stock
blckshrk/Weboob
modules/batoto/__init__.py
Python
agpl-3.0
796
0
# -*- coding: utf-8 -*- # Copyright(C) 2011 Noé Rubinstein # # This file is part of weboob. # # weboob 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 opt...
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 the GNU Affero General Public License # along with weboob. If not, see <ht...
/licenses/>. from .backend import BatotoBackend __all__ = ['BatotoBackend']
googleapis/python-dialogflow-cx
samples/generated_samples/dialogflow_v3_generated_pages_list_pages_async.py
Python
apache-2.0
1,481
0.000675
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this fi
le except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIN...
ense for the specific language governing permissions and # limitations under the License. # # Generated code. DO NOT EDIT! # # Snippet for ListPages # NOTE: This snippet has been automatically generated for illustrative purposes only. # It may require modifications to work in your environment. # To install the latest ...
slickqa/slickqaweb
slickqaweb/model/featureReference.py
Python
apache-2.0
120
0
f
rom mongoengine import * class Feature
Reference(EmbeddedDocument): id = ObjectIdField() name = StringField()
nuclearsandwich/autokey
src/lib/qtui/dialogs.py
Python
gpl-3.0
20,532
0.005796
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2011 Chris Dekter # # 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 late...
self.setModal(True) #self.connect(self, SIGNAL("okClicked()"), self.on_okClicked) def load(self, item): self.targetItem = item self.widget.abbrListWidget.clear() if model.TriggerMode.ABBREVIATION in item.modes: for abbr in item.abbreviations: s...
AbbrListItem(abbr)) self.widget.removeButton.setEnabled(True) self.widget.abbrListWidget.setCurrentRow(0) else: self.widget.removeButton.setEnabled(False) self.widget.removeTypedCheckbox.setChecked(item.backspace) self.__resetWordCharCombo() ...
gnina/scripts
bootstrap.py
Python
bsd-3-clause
3,080
0.047403
#!/usr/bin/env python3 import predict import sklearn.metrics import argparse, sys import os import numpy as np import glob import re import matplotlib.pyplot as plt def calc_auc(predictions): y_true =[] y_score=[] for line in predictions: values= line.split(" ") y_true.append(float(values[1])) y_score.append...
l template. Must use TESTFILE with unshuffled,
unbalanced input") parser.add_argument('-w','--weights',type=str,required=True,help="Model weights (.caffemodel)") parser.add_argument('-i','--input',type=str,required=True,help="Input .types file to predict") parser.add_argument('-g','--gpu',type=int,help='Specify GPU to run on',default=-1) parser.add_argument('-o...
BackupTheBerlios/cuon-svn
cuon_client/cuon/Proposal/SingleProposalMisc.py
Python
gpl-3.0
1,877
0.018667
# -*- coding: utf-8 -*- ##Copyright (C) [2003] [Jürgen Hamel, D-32584 Löhne] ##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 versio...
lues): print 'readNonWidgetEntries(self) by S
ingleorderGets' dicValues['orderid'] = [self.ordernumber, 'int'] return dicValues
buckiracer/data-science-from-scratch
RefMaterials/Text-Manipulation/find_email.py
Python
unlicense
258
0.034884
import sys from collection
s import Counter def get_domain(email_address): return email_address.lower().split("@
")[-1] with open('email_addresses.txt','r') as f: domain_counts = Counter(get_domain(line.strip()) for line in f if "@" in line)
JetChars/vim
vim/bundle/python-mode/pymode/libs/logilab/common/ureports/nodes.py
Python
apache-2.0
5,838
0.002227
# copyright 2003-2011 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-common. # # logilab-common is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as publ...
e link's label as a string (use
the url by default) """ def __init__(self, url, label=None, **kwargs): super(Link, self).__init__(**kwargs) assert url self.url = url self.label = label or url class Image(BaseComponent): """an embedded or a single image attributes : * BaseComponent attributes ...
skarphed/skarphed
admin/src/skarphedadmin/gui/__init__.py
Python
agpl-3.0
1,295
0.015456
#!/usr/bin/python #-*- coding: utf-8 -*- ########################################################### # © 2011 Daniel 'grindhold' Brendle and Team # # This file is part of Skarphed. # # Skarphed is free software: you can redistribute it and/or # modify it under the terms of the GNU Affero General Public License # as ...
t() import ExceptHook import MainWindow as MainWindow_ from skarphedadmin import Application MainWindow = MainWindow_.MainWi
ndow def run(): gtk.main() class Gui(object): def __init__(self,app): self.app = Application() def doLoginTry(self,username,password): self.app.doLoginTry(username,password)
kenshay/ImageScript
ProgramData/SystemFiles/Python/Lib/site-packages/networkx/utils/contextmanagers.py
Python
gpl-3.0
632
0
from __future__ import absolute_import from contextlib import contextm
anager __all__ = [ 'reversed', ] @contextmanager def reversed(G): """A context manager for temporarily reversing a directed graph in place. This is a no-op for undirected graphs. Parameters ---------- G : graph A NetworkX graph. """ directed = G.is_directed() if directed...
G._adj = G._succ try: yield finally: if directed: # Reverse the reverse. G._pred, G._succ = G._succ, G._pred G._adj = G._succ
laurmurclar/mitmproxy
mitmproxy/proxy/protocol/websocket.py
Python
mit
7,179
0.002368
import os import socket import struct from OpenSSL import SSL from mitmproxy import exceptions from mitmproxy import flow from mitmproxy.proxy.protocol import base from mitmproxy.net import tcp from mitmproxy.net import websockets from mitmproxy.websocket import WebSocketFlow, WebSocketMessage class WebSocketLayer(b...
The response from the server is then parsed and negotiated settings are extracted. Finally the handshake is completed by forwarding the server-response to the client. After that, only WebSocket frames are exchanged. PING/PONG frames pass through and must be a
nswered by the other endpoint. CLOSE frames are forwarded before this WebSocketLayer terminates. This layer is transparent to any negotiated extensions. This layer is transparent to any negotiated subprotocols. Only raw frames are forwarded to the other endpoint. WebSocket mes...