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
garciparedes/python-examples
web/django/graphene/graphene-quickstart/lesson-02-enums.py
Python
mpl-2.0
332
0
#!/
usr/bin/env python3 """ URL: http://docs.graphene-python.org/en/latest/types/enums/ """ import graphene class Episode(graphene.Enum): NEWHOPE = 4 EMPIRE = 5 JEDI = 6 @property def description(self): if self == Episode.NEWHOPE: return 'New Hope Episode' ret
urn 'Other episode'
KaiSzuttor/espresso
samples/p3m.py
Python
gpl-3.0
5,654
0.000531
# # Copyright (C) 2013-2019 The ESPResSo project # # This file is part of ESPResSo. # # ESPResSo 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...
WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <
http://www.gnu.org/licenses/>. # """ Simulate a Lennard-Jones liquid with charges. The P3M method is used to calculate electrostatic interactions. """ import numpy as np import espressomd required_features = ["P3M", "WCA"] espressomd.assert_features(required_features) from espressomd import electrostatics import argp...
HailStorm32/Q.bo_stacks
qbo_stereo_anaglyph/hrl_lib/src/hrl_lib/msg/_Pose3DOF.py
Python
lgpl-2.1
5,992
0.019526
"""autogenerated by genpy from hrl_lib/Pose3DOF.msg. Do not edit.""" import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct import std_msgs.msg class Pose3DOF(genpy.Message): _md5sum = "646ead44a0e6fecf4e14ca116f12b08b" _type = "hrl_lib/Pose3DOF" _has_header = True #flag ...
nd += length if python3: self.header.frame_id = str[start:end].decode('utf-8') else: self.header.frame_id = str[start:end] _x = s
elf start = end end += 32 (_x.x, _x.y, _x.theta, _x.dt,) = _struct_4d.unpack(str[start:end]) return self except struct.error as e: raise genpy.DeserializationError(e) #most likely buffer underfill _struct_I = genpy.struct_I _struct_3I = struct.Struct("<3I") _struct_4d = struct.Struct(...
RedHatInsights/insights-core
insights/parsers/tests/test_parsers_module.py
Python
apache-2.0
24,552
0.002403
import pytest from collections import OrderedDict from insights.parsers import (calc_offset, keyword_search, optlist_to_dict, parse_delimited_table, parse_fixed_table, split_kv_pairs, unsplit_lines, ParseException, SkipException) SPLIT_TEST_1 = """ # Comment line keyword1 = value1 #...
assert len(lines) == 4 assert lines[0] == '' assert lines[1] == 'web.default_taskmaster_tasks = RHN::Task::SessionCleanup, RHN::Task::ErrataQueue, RHN::Task::ErrataEngine, RHN::Task::DailySummary, RHN::Task::SummaryPopulation, RHN::Task::RHNProc, RHN::Task::Pack
ageCleanup' assert lines[2] == '' assert lines[3] == 'db_host =' def test_calc_offset(): assert calc_offset(OFFSET_CONTENT_1.splitlines(), target=[]) == 0 assert calc_offset(OFFSET_CONTENT_1.splitlines(), target=[None]) == 0 assert calc_offset(OFFSET_CONTENT_1.splitlines(), target=['data ']) == 0 ...
prophile/compd
src/screen_db.py
Python
mit
2,580
0.005039
"""Screen database.""" import redis_client import control import re from twisted.internet import defer class ScreenDB(object): """A screen database.""" def __init__(self): """Default constructor.""" pass def set_mode(self, screen, mode): redis_client.connection.set('screen:{0}:mod...
t') @
defer.inlineCallbacks def perform_screen_list(responder, options): screen_list = yield screens.list() for screen, settings in screen_list.iteritems(): if settings['host'] is None: online_string = 'offline' else: online_string = 'online from {0} port {1}'.format(*settings[...
saechtner/turn-events
Turnauswertung-py3/common/views.py
Python
mit
2,597
0.004621
from django.core.urlresolvers import reverse, reverse_lazy from django.shortcuts import
render, redirect from django.views import generic from common.models import Discipline, Performance # renders index / home page def index(request): return redirect(reverse('tournaments.main')
) # renders todo page def process(request): return render(request, 'gymnastics/process.html', None) def performances_index(request): context = { 'performances': Performance.objects.all() \ .select_related('athlete').select_related('discipline') } return render(request, 'gymnastics/performances/i...
stev-0/bustimes.org.uk
busstops/management/commands/import_ie_naptan_xml.py
Python
mpl-2.0
4,087
0.003181
"""Import an Irish NaPTAN XML file, obtainable from https://data.dublinked.ie/dataset/national-public-transport-nodes/resource/6d997756-4dba-40d8-8526-7385735dc345 """ import warnings import zipfile import xml.etree.cElementTree as ET from django.contrib.gis.geos import Point from django.core.management.base import Ba...
stop.save() def handle_file(self, archive, filename):
with archive.open(filename) as open_file: iterator = ET.iterparse(open_file) for _, element in iterator: tag = element.tag[27:] if tag == 'StopPoint': self.handle_stop(element) element.clear() def handle(self, *ar...
pferreir/indico
indico/modules/events/abstracts/models/fields.py
Python
mit
1,096
0.002737
# 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 indico.core.db import db from indico.modules.events.contributions.models.fields import ContributionFi...
ldValueBase): """Store a field values related to abstracts.""" __tablename__ = 'abstract_field_values' __table_args__ = {'schema': 'event_abstracts'} contribution_field_backref_name = 'abstract_values' abstract_id = db.Column( db.Integer, db.ForeignKey('event_abstracts.abstracts.id...
eld_values) def __repr__(self): text = text_to_repr(self.data) if isinstance(self.data, str) else self.data return format_repr(self, 'abstract_id', 'contribution_field_id', _text=text)
infobip/infobip-api-python-client
infobip_api_client/model/sms_destination.py
Python
apache-2.0
6,770
0.000295
""" Infobip Client API Libraries OpenAPI Specification OpenAPI specification containing public endpoints supported in client API libraries. # noqa: E501 The version of the OpenAPI document: 1.0.172 Contact: support@infobip.com Generated by: https://openapi-generator.tech """ import re # noqa: ...
If passed, type conversion is attempted If omitted no type conversion is done. _visited_composed_classes (tuple): This stores a tuple of classes that we have traveled through so that if we
see that class again we will not use its discriminator again. When traveling through a discriminator, the composed schema that is is traveled through is added to this set. ...
singingwolfboy/flask-dance
tests/consumer/storage/test_sqla.py
Python
mit
24,167
0.001407
import pytest sa = pytest.importorskip("sqlalchemy") import os import responses import flask from flask_sqlalchemy import SQLAlchemy from sqlalchemy import event from flask_caching import Cache from flask_login import LoginManager, UserMixin, current_user, login_user, logout_user from flask_dance.consumer import OAut...
( "/login/test-service/authorized?code=secret-code&state=random-string", base_
url="https://a.b.c", ) # check that we redirected the client assert resp.status_code == 302 assert resp.headers["Location"] == "https://a.b.c/oauth_done" assert len(queries) == 2 # check the database authorizations = OAuth.query.all() assert len(authoriz...
abid-mujtaba/fetchheaders
fetchheaders.py
Python
apache-2.0
20,367
0.022193
#!/usr/bin/python2 # # Copyright 2012 Abid Hasan Mujtaba # # 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 la...
vers[ account ][ key ] = config[ 'accounts'
][ 'DEFAULT' ][ key ] # Now we read in the global settings: globalSettings = {} # Create empty dictionary to populate for key in config[ 'global' ].keys() : globalSettings[ key ] = config[ 'global' ][ key ] return servers, globalSettings def argParse() : ''' This function rea...
piotrmaslanka/bellum
space/views/planetview.py
Python
agpl-3.0
4,242
0.009194
# coding=UTF-8 from django.shortcuts import redirect from bellum.common.alliance import isAllied from bellum.common.session.login import must_be_logged from bellum.common.session import getAccount, getRace from bellum.common.session.mother import getCurrentMother from djangomako.shortcuts import render_to_response, ren...
.duePosition()): # Differe
nt position than current can_relocate = mum.canRelocate() if can_relocate: relocation_time = getRelocationTime(mum, getRace(request), mum.orbiting, planet) # can scan? can_scan = False if getRace(request) == 1: if mum.isRelocating() == False: if mum.orbiting ...
sam-m888/gprime
gprime/plug/_docgenplugin.py
Python
gpl-2.0
4,499
0.000222
# # gPrime - A web-based genealogy program # # Copyright (C) 2008 Brian G. Matherly # Copyright (C) 2012 Paul Franklin # # 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 versio...
""" Plugin.__init__(self, name, description, basedoc.__module__) self.__basedoc = basedoc self.__paper = paper self.__style = style self.__extension = extension self.__docoptclass = docoptclass self.__basedocname = basedocname def get_basedoc(self): ...
turn self.__basedoc def get_paper_used(self): """ Get the paper flag for this plugin. :return: bool - True = use paper; False = do not use paper """ return self.__paper def get_style_support(self): """ Get the style flag for this plugin. :retur...
shuxin/androguard
androguard/gui/fileloading.py
Python
apache-2.0
1,625
0
import traceback from PyQt5 import QtCore import androguard.session as session from androguard.core import androconf import logging log = logging.getLogger("androguard.gui") class FileLoadingThread(QtCore.QThread): file_loaded = QtCore.pyqtSignal(bool) def __init__(self, parent=None): QtCore.QThre...
open(file_path, 'rb').read()) self.file_loaded.emit(ret) elif file_type == "SESSION": self.parent.session = session.Load(file_path) self.file_loaded.emit(True) else:
self.file_loaded.emit(False) except Exception as e: log.debug(e) log.debug(traceback.format_exc()) self.file_loaded.emit(False) self.incoming_file = [] else: self.file_loaded.emit(False)
MegaMark16/django-puzzle-captcha
puzzle_captcha/admin.py
Python
bsd-3-clause
505
0.011881
from django.contrib import admin from puzzle_captcha.models import Puzzle,
PuzzlePiece class PuzzlePieceInline(admin.StackedInline): model = PuzzlePiece readonly_fields = ('key', 'image', 'order') can_delete = False extra = 0 clas
s PuzzleAdmin(admin.ModelAdmin): list_display = ('key', 'rows', 'cols') readonly_fields = ('key', 'rows', 'cols') class Meta: model = Puzzle inlines = [ PuzzlePieceInline, ] admin.site.register(Puzzle, PuzzleAdmin)
belangeo/pyo
pyo/examples/04-soundfiles/02-read-from-disk-2.py
Python
lgpl-3.0
1,308
0.002294
""" 02-read-from-disk-2.py - Catching the `end-of-file` signal from the SfPlayer object. This example demonstrates how to use the `end-of-file` signal of the SfPlayer object to trigger another playback (possibly with another sound, another speed, etc.). When a SfPlayer reaches the end of the file, it sends a trigger ...
s = Server().boot() # Sound bank folder = "../snds/" sounds = ["alum1.wav", "alum2.wav", "alum3.wav", "alum4.wav"] # Creates the left and right players sfL = SfPlayer(folder + sounds[0], speed=1, mul=0
.5).out() sfR = SfPlayer(folder + sounds[0], speed=1, mul=0.5).out(1) # Function to choose a new sound and a new speed for the left player def newL(): sfL.path = folder + sounds[random.randint(0, 3)] sfL.speed = random.uniform(0.75, 1.5) sfL.out() # The "end-of-file" signal triggers the function "newL" t...
thisisshi/cloud-custodian
tools/c7n_openstack/tests/test_server.py
Python
apache-2.0
2,461
0
# Copyright The Cloud Custodian Authors. # SPDX-License-Identifier: Apache-2.0 from common_openstack import OpenStackTest class ServerTest(OpenStackTest): def test_server_query(self): factory = self.replay_flight_data() p = self.load_policy({ 'name': 'all-servers', 'resour...
p = self.load_policy(policy, session_factory=factory) resources = p.run() self.assertEqual(len(resources), 1) self.assertEqual(resources[0].name, "c7n-test-1") def test_server_filter_tags(self): factory = self.replay_flight_data() p
olicy = { 'name': 'get-server-c7n-test-1', 'resource': 'openstack.server', 'filters': [ { "type": "tags", "tags": [ { "key": "a", "value": "a", ...
finaldie/final_httpd_mock
.ycm_extra_conf.py
Python
mit
6,141
0.021821
# This file is NOT licensed under the GPLv3, which is the license for the rest # of YouCompleteMe.
# # Here's the license text for this file: # # This is free and unencumbered software released into the public domain. # # Anyone is free to copy, modify, publish, use, compile, sell, or # distribute this software, either in source code form or as a compiled
# binary, for any purpose, commercial or non-commercial, and by any # means. # # In jurisdictions that recognize copyright laws, the author or authors # of this software dedicate any and all copyright interest in the # software to the public domain. We make this dedication for the benefit # of the public at large and ...
Knln/COMP2041
examples/4/filetest2.py
Python
mit
135
0
#!/usr/bin/python2.7 -u import os.path if os.path.isd
ir('/dev/null'):
print '/dev/null' if os.path.isdir('/dev'): print '/dev'
dls-controls/pymalcolm
tests/test_profiler.py
Python
apache-2.0
2,778
0.00108
import ast import logging import time import unittest from malcolm.profiler import Profiler # https://github.com/bdarnell/plop/blob/master/plop/test/collector_test.py class ProfilerTest(unittest.TestCase): def filter_stacks(self, results): # Kind of hacky, but this is the simplest way to keep the tests ...
me.time() profiler.stop("profiler_test.plop") elapsed = end - start self.assertTrue(0.8 < elapsed < 0.9, elapsed) with open("/tmp/profiler_test.plop") as f: resul
ts = f.read() counts = self.filter_stacks(results) expected = { ("a", "test_collector"): 10, ("c", "a", "test_collector"): 10, ("b", "test_collector"): 20, ("c", "b", "test_collector"): 10, ("c", "test_collector"): 30, } self.c...
fuxiang90/speed-prediction
script/loc_train.py
Python
bsd-3-clause
1,847
0.02653
# coding=utf-8 #! /usr/bin/python import matplotlib.pyplot as plt import numpy as np import mlpy import sys import math from config import loc_store_path, times_day class LocTrain(object): """ """ def __init__(self, file_name , flag): if flag == "ridge": self.l...
kday: self.x_weekday[weekday] = [] self.y_weekday[weekday] = [] self.x_
weekday[weekday].append(each_x) self.y_weekday[weekday].append(float(l[4])) def main(): tmp = LocTrain('../data/train/3860_data',"ridge") tmp.train() print tmp.predict(1,[1,10,10,20,10]) pass if __name__ == '__main__': main()
Katello/katello-cli
src/katello/client/api/package.py
Python
gpl-2.0
1,296
0.000772
# -*- coding: utf-8 -*- # # Copyright 2013 Red Hat, Inc. # # This software is licensed to you under the GNU General Public License, # version 2 (GPLv2). There is NO WARRANTY for this software, express or # implied, including the implied warranties of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. You should hav...
= self.server.GET(path)[1] return pack def packages_by_repo(self, repoId): path = "/api/repositories/%s/packages" % repoId pack_list = self.server.GET(path)[1] return pack_list def search(self, query, repoId): path = "/api/repositories/%s/packages/search" % repoId ...
ack_list
onshape-public/onshape-clients
python/onshape_client/oas/models/btp_expression_operator244.py
Python
mit
12,168
0.000164
# coding: utf-8 """ Onshape REST API The Onshape REST API consumed by all clients. # noqa: E501 The version of the OpenAPI document: 1.113 Contact: api-support@onshape.zendesk.com Generated by: https://openapi-generator.tech """ from __future__ import absolute_import import re # noqa: F401 im...
USER_TYPE": "USER_TYPE", "FEATURE_DEFINITION": "FEATURE_DEF
INITION", "FILE_HEADER": "FILE_HEADER", "UNDOCUMENTABLE": "UNDOCUMENTABLE", "UNKNOWN": "UNKNOWN", }, } validations = {} additional_properties_type = None @staticmethod def openapi_types(): """ This must be a class method so a model may h...
psd-tools/psd-tools
src/psd_tools/__init__.py
Python
mit
158
0
from __future__ import a
bsolute_import, unicode_literals from .api.psd_image import PSDImage from .composer import compose __all__ = ['PSDImage', 'compose']
abramhindle/UnnaturalCodeFork
python/testdata/launchpad/lib/lp/code/model/branchrevision.py
Python
agpl-3.0
984
0
# Copyright 2009-2010 Canonical Ltd. This software is licensed under the # GNU Affero General Public License version 3 (see the file LICENSE). __metaclass__ = type __all__ = [ 'BranchRevision', ] from storm.locals import ( Int, Reference, Storm, ) from zope.interface import implements from l...
on.i
d') sequence = Int(name='sequence', allow_none=True) def __init__(self, branch, revision, sequence=None): self.branch = branch self.revision = revision self.sequence = sequence
luckasfb/OT_903D-kernel-2.6.35.7
kernel/scripts/rt-tester/rt-tester.py
Python
gpl-2.0
5,104
0.021552
#!/usr/bin/python import os import sys import getopt import shutil import string # Globals quiet = 0 test = 0 comments = 0 sysfsprefix = "/sys/devices/system/rttest/rttest" statusfile = "/status" commandfile = "/command" # Command opcodes cmd_opcodes = { "schedother" : "1", "schedfifo" : "2", "loc...
: "11", "resetevent" : "98", "reset" : "99", } test_opcodes = { "prioeq" : ["P" , "eq" , None], "priolt" : ["P" , "lt" , None], "priogt" : ["P" , "gt" , None], "nprioeq" : ["N" , "eq" , None], "npriolt" : ["N" , "lt" , None], "nprio...
q" , 1], "blocked" : ["M" , "eq" , 2], "blockedwake" : ["M" , "eq" , 3], "locked" : ["M" , "eq" , 4], "opcodeeq" : ["O" , "eq" , None], "opcodelt" : ["O" , "lt" , None], "opcodegt" : ["O" , "gt" , None], "eventeq" : ["E" , "eq" , None], "eventlt" ...
coll-gate/collgate
server/printer/urls.py
Python
mit
317
0.003175
# -*- coding: utf-8; -*- # # @file urls.py # @brief collgate # @author Frédéric SCHERMA (INRA UMR1095) # @date 2018-09-20 # @copyright Copyright (c) 2
018 INRA/CIRAD # @license MIT (see LICENSE f
ile) # @details coll-gate printer module url entry point. from django.conf.urls import include, url urlpatterns = [ ]
tcwang817/django-choices-enum
django_choices_enum/__init__.py
Python
mit
62
0
from bas
e import ChoicesEnum from _version i
mport __version__
towerjoo/mindsbook
django/contrib/auth/tests/auth_backends.py
Python
bsd-3-clause
9,952
0.003014
import warnings from django.conf import settings from django.contrib.auth.models import User, Group, Permission, AnonymousUser from django.contrib.contenttypes.models import ContentType from django.test import TestCase class BackendTest(TestCase): backend = 'django.contrib.auth.backends.ModelBackend' def s...
return # We only support row level perms if not isinstance(obj, TestObj): return ['none'] if 'test_group' in [group.name for group in user.groups.all()]: return ['group
_perm'] else: return ['none'] class RowlevelBackendTest(TestCase): """ Tests for auth backend that supports object level permissions """ backend = 'django.contrib.auth.tests.auth_backends.SimpleRowlevelBackend' def setUp(self): self.curr_auth = settings.AUTHENTICATION_...
jawilson/home-assistant
homeassistant/components/ialarm/alarm_control_panel.py
Python
apache-2.0
1,923
0.00052
"""Interfaces with iAlarm control panels.""" from homeassistant.components.alarm_control_panel import AlarmControlPanelEntity from homeassistant.components.alarm_control_panel.const import ( SUPPORT_ALARM_ARM_AWAY, SUPPORT_ALARM_ARM_HOME, ) from homeassistant.helpers.entity import DeviceInfo from homeassistant....
urn the state of the device.""" return self.coordinator.state @property def supported_features(self) -> int: """Return the list of supported features.""" return SUPPOR
T_ALARM_ARM_HOME | SUPPORT_ALARM_ARM_AWAY def alarm_disarm(self, code=None): """Send disarm command.""" self.coordinator.ialarm.disarm() def alarm_arm_home(self, code=None): """Send arm home command.""" self.coordinator.ialarm.arm_stay() def alarm_arm_away(self, code=None)...
dgoldin/snakebite
snakebite/channel.py
Python
apache-2.0
26,513
0.002565
# -*- coding: utf-8 -*- # Copyright (c) 2009 Las Cumbres Observatory (www.lcogt.net) # Copyright (c) 2010 Jan Dittberner # # 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,...
n: raise Exception("RpcBufferedReader only managed to read %s out of %s bytes" % (len(bytes_read), n)) def rewind(self, places): '''Rewinds the current buffer to a position. Needed for reading varints, because we might read bytes that belong to the stream after the varint. ''' ...
f.pos, places)) self.pos -= places log.debug("Reset buffer to pos %d" % self.pos) def reset(self): self.buffer = "" self.pos = -1 # position of last byte read @property def buffer_length(self): '''Returns the length of the current buffer.''' return len(self...
google-research/text-to-text-transfer-transformer
t5/models/mesh_transformer.py
Python
apache-2.0
12,873
0.00536
# Copyright 2022 The T5 Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
(or None). Used as shuffle seed for tf.data. vocabulary: unused argument, maintains
compatibility with other dataaset_fns num_inference_examples: maximum number of examples per task to do inference on. If None or less than 0, use all examples. use_cached: bool, whether to load the cached version of this dataset. evals but should not be used for iterative decoding. priming_sequ...
palankai/pyrs
pyrs/conf.py
Python
mit
200
0
""" This module contains the global configurations o
f the framework """ #: This name suppose to be used for general meta decoration for functions, #: methods o
r even classes meta_field = '_pyrsmeta'
andre487/news487
collector/rss/reader.py
Python
mit
2,757
0.001451
import feedparser import logging from rss import sources from util import date, dict_tool, tags log = logging.getLogger('app') def parse_feed_by_name(name): feed_params = sources.get_source(name) if not feed_params: raise ValueError('There is no feed w
ith name %s' % name) source_name = feed_params['name'] feed = feedparser.parse(feed_params['url']) data = [] for entry in feed['entries']: data.append( create_doc( source_name, feed, e
ntry, feed_params.get('tags', ()), feed_params.get('author_name'), feed_params.get('author_link'), feed_params.get('dressing_params'), ) ) log.info('%s: got %d documents', source_name, len(data)) return data def create_doc(s...
PeWu/python-geneteka
merge.py
Python
apache-2.0
4,704
0.013818
#!/usr/bin/python3
""" Merges raw data from geneteka into larger json files. """ from collections import defaultdict import html import json import os import re INPUT_DIR = 'data_raw' OUTPUT_DIR = 'data' def extractNotes(value): match = re.search(r'i.png" title="([^"]*)"', value) if match: return (value.split('<', 1)[0].st...
f = record[9] lastName, lastNameNotes = extractNotes(record[3]) motherLastName, motherLastNameNotes = extractNotes(record[6]) output = { 'year': record[0].strip(), 'record_number': record[1].strip(), 'first_name': record[2].strip(), 'last_name': lastName, 'father_first_name': record[4].strip...
Carreau/gistpynb
nbconvert/lexers.py
Python
apache-2.0
904
0.006637
#----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from pygments.lexers import PythonLexer, BashLexer from pygments.lexer import bygroups, using from pygments.token import Keyword, Operator, Name, Text ...
s #----------------------------------------------------------------------------- class IPythonLexer(PythonLexer): name = 'IPython' aliases = ['ip', 'ipython'] filenames = ['*.ipy'] tokens = PythonLexer.tokens.copy() tokens['root'] = [ (r'(\%+)(\w+)\s+(\.*)(\n)', bygroups(Operator, Keyword, ...
or, Keyword)), (r'^(!)(.+)(\n)', bygroups(Operator, using(BashLexer), Text)), ] + tokens['root']
lightengine/lightstream
lightstream/oldlib/dac.py
Python
bsd-2-clause
5,679
0.035217
# j4cDAC test code # # Copyright 2011 Jacob Potter # # 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, version 3. # # This program is distributed in the hope that it will be useful, # but WITHOUT ...
lf.conn.sendall("p") return self.readresp("p") def stop(self): self.c
onn.sendall("s") return self.readresp("s") def estop(self): self.conn.sendall("\xFF") return self.readresp("\xFF") def clear_estop(self): self.conn.sendall("c") return self.readresp("c") def ping(self): self.conn.sendall("?") return self.readresp("?") def play_stream(self, stream): # First, prep...
eeshangarg/zulip
zerver/views/realm_icon.py
Python
apache-2.0
2,456
0.00285
from django.conf import settings from django.http import HttpRequest, HttpResponse from django.shortcuts import redirect from django.utils.translation import gettext as _ from zerver.decorator import require_realm_admin from zerver.lib.actions import do_change_icon_source from zerver.lib.exceptions import JsonableErro...
user_profile.realm) json_result = dict( icon_url=gravatar_url, ) return json_success(json_result) def get_icon_backend(request: HttpRequest, user_profile: UserProfile) -> HttpResponse: url = realm_icon_url(user_profile.realm) # We can rely on the URL already having query parameters. Becau...
lates depend on being able to use the ampersand to # add query parameters to our url, get_icon_url does '?version=version_number' # hacks to prevent us from having to jump through decode/encode hoops. url = append_url_query_string(url, request.META["QUERY_STRING"]) return redirect(url)
AusDTO/dto-digitalmarketplace-buyer-frontend
tests/app/views/test_login.py
Python
mit
14,240
0.001545
# coding: utf-8 from app.api_client.error import HTTPError from app.helpers.login_helpers import generate_buyer_creation_token from dmapiclient.audit import AuditTypes from dmutils.email import generate_token, EmailError from dmutils.forms import FakeCsrf from ...helpers import BaseApplicationTest from lxml import htm...
_with('valid@email.com', '1234567890') def test_should_not_strip_whitespace_surrounding_login_password_field(self): self.client.post(self.expand_path('/login'), data={ 'email_address': 'valid@email.com', 'password': ' 1234567890 ', 'csrf_token': FakeCsrf.valid_token, ...
email.com', ' 1234567890 ') @mock.patch('app.main.views.login.data_api_client') def test_ok_next_url_redirects_buyer_on_login(self, data_api_client): with self.app.app_context(): data_api_client.authenticate_user.return_value = self.user(123, "email@email.com", None, None, 'Name') ...
JamesLinEngineer/RKMC
addons/script.module.axel.downloader/lib/standalone_server.py
Python
gpl-2.0
1,470
0.010204
''' Axe
lProxy XBMC Addon Copyright (C) 2013 Eldorado This
program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful...
patilsangram/erpnext
erpnext/stock/doctype/stock_reconciliation/stock_reconciliation.py
Python
gpl-3.0
11,573
0.02575
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe, erpnext import frappe.defaults from frappe import msgprint, _ from frappe.utils import cstr, flt, cint from erpnext.stock.stock_ledger im...
if row.qty and row.valuation_rate in ["", None]: row.valuation_rate = get_stock_balance(row.item_code, row.warehouse, self.posting_date, self.posting_time, with
_valuation_rate=True)[1] if not row.valuation_rate: # try if there is a buying price list in default currency buying_rate = frappe.db.get_value("Item Price", {"item_code": row.item_code, "buying": 1, "currency": default_currency}, "price_list_rate") if buying_rate: row.valuation_rate = bu...
ryfeus/lambda-packs
Keras_tensorflow_nightly/source2.7/tensorflow/tools/api/generator/api/keras/preprocessing/__init__.py
Python
mit
371
0.002695
"""Imports for Python API. This file is M
ACHI
NE GENERATED! Do not edit. Generated by: tensorflow/tools/api/generator/create_python_api.py script. """ from tensorflow.tools.api.generator.api.keras.preprocessing import image from tensorflow.tools.api.generator.api.keras.preprocessing import sequence from tensorflow.tools.api.generator.api.keras.preprocessing import...
ivanlyon/exercises
kattis/k_sequences.py
Python
mit
969
0.003096
''' Swap counting Status: Accepted ''' ############################################################################### def inversions(constants, variables): """Number of swaps"""
if variables: pow2 = pow(2, variables - 1, 1_000_000_007) return pow2 * (constants * 2 + variables) return constants ############################################################################### def main(): """Read input and print output""" zeroes, qmarks, swaps = 0, 0, 0 for gly...
0': zeroes += 1 else: if glyph == '1': swaps += inversions(zeroes, qmarks) if glyph == '?': swaps += inversions(zeroes, qmarks) + swaps qmarks += 1 swaps %= 1_000_000_007 print(swaps) ########################...
hackaugusto/raiden
raiden/network/rpc/client.py
Python
mit
34,000
0.002441
import copy import json import os import warnings from enum import Enum from typing import Any, Callable, Dict, List, Optional, Tuple import gevent import structlog from eth_utils import ( decode_hex, encode_hex, is_checksum_address, remove_0x_prefix, to_canonical_address, to_checksum_address, ...
symbols_to_contract[unresolved] for unresolved in unresolved_symbols ] return dependencies def dependencies_order_of_build(target_contract, dependencies_map): """ Return an ordered list of contracts that is sufficient to successfully deploy the target contract. Note: This funct...
if target_contract not in dependencies_map: raise ValueError("no dependencies defined for {}".format(target_contract)) order = [target_contract] todo = list(dependencies_map[target_contract]) while todo: target_contract = todo.pop(0) target_pos = len(order) for depend...
npdoty/pywikibot
setup.py
Python
mit
8,699
0.000345
# -*- coding: utf-8 -*- """Installer script for Pywikibot 3.0 framework.""" # # (C) Pywikibot team, 2009-2017 # # Distributed under the terms of the MIT license. # from __future__ import absolute_import, print_function, unicode_literals import itertools import os import sys try: # Work around a traceback on Pytho...
's menu # to set the console font and copy and paste, achieved using pywinauto # which depends on pywin32. # These tests may be disabled because pywin32 depends on VC++, is time # comsuming to build, and the console window cant be accessed du
ring appveyor # builds. # Microsoft makes available a compiler for Python 2.7 # http://www.microsoft.com/en-au/download/details.aspx?id=44266 # If you set up your own compiler for Python 3, on 3.3 two demo files # packaged with pywin32 may fail. Remove com/win32com/demos/ie*.py if os.name == 'nt' and os.environ.get('PY...
MarketShareData/Internal
code/test1/inheritanceTest.py
Python
mit
600
0.006667
__author__ = 'http://www.python-course.eu/python3_inheritance
.php' class Person: def __init__(self, first, last): self.firstname = first self.lastname = last def Name(self): return self.firstname + " " + self.lastname class Employee(Person): def __init__(self, first, last, staffnum): Person.__init__(self,first, last) self...
ployee("Homer", "Simpson", "1007") print(x.Name()) print(y.GetEmployee())
rht/zulip
zerver/webhooks/clubhouse/view.py
Python
apache-2.0
27,498
0.002655
from functools import partial from typing import Any, Callable, Dict, Generator, List, Optional from django.http import HttpRequest, HttpResponse from zerver.decorator import webhook_view from zerver.lib.exceptions import UnsupportedWebhookEventType from zerver.lib.request import REQ, has_request_variables from zerve...
nt = "{}_{}".format(event, "state") elif changes.get("workflow_state_id") is not None: event = "{}_{}".format(event, "state") elif changes.get("name") is not None: event = "{}_{}".format(event, "name") elif changes.get("archived") is not None: event = "{}_{}"....
}_{}".format(event, "complete") elif changes.get("epic_id") is not None: event = "{}_{}".format(event, "epic") elif changes.get("estimate") is not None: event = "{}_{}".format(event, "estimate") elif changes.get("file_ids") is not None: event = "{}_{}".format(...
cactusbin/nyt
matplotlib/examples/axes_grid/demo_colorbar_with_inset_locator.py
Python
unlicense
1,052
0.013308
import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1.inset_locator import inset_axes fig, (ax1, ax2) = plt.subplots(1, 2, figsize=[6, 3]) axins1 = inset_axes(ax1, width="50%", # width = 10% of parent_bbox width height="5%", # height : 50% loc=1) im...
bbox_transform=ax2.transAxes, borderpad=0, ) # Controlling the placement of the
inset axes is basically same as that # of the legend. you may want to play with the borderpad value and # the bbox_to_anchor coordinate. im=ax2.imshow([[1,2],[2, 3]]) plt.colorbar(im, cax=axins, ticks=[1,2,3]) plt.draw() plt.show()
buffer/thug
thug/ActiveX/modules/ScriptingFileSystemObject.py
Python
gpl-2.0
5,185
0.010222
import os import string import random import logging from thug.ActiveX.modules import WScriptShell from thug.ActiveX.modules import TextStream from thug.ActiveX.modules import File from thug.ActiveX.modules import Folder from thug.OS.Windows import win32_files from thug.OS.Windows import win32_folders log = logging....
hugLogging.add_behavior_warn(f'[Scripting.FileSystemObject ActiveX] GetSpecialFolder("{arg}")') arg = int(arg) f
older = '' if arg == 0: folder = WScriptShell.ExpandEnvironmentStrings(self, "%windir%") elif arg == 1: folder = WScriptShell.ExpandEnvironmentStrings(self, "%SystemRoot%\\system32") elif arg == 2: folder = WScriptShell.ExpandEnvironmentStrings(self, "%TEMP%") log.ThugLogging.ad...
meowlab/shadowsocks-comment
shadowsocks/lru_cache.py
Python
apache-2.0
4,886
0.003684
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2015 clowwindy # # 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 b...
y, keys stored in the cache # m: visits not timed out, proportional to QPS * timeout # get & set is O(1), not O(n). thus we can support very large n # TODO: if timeout or QPS is too large, then this cache is not very efficient, # as sweep() causes long pause class LRUCache(collections.
MutableMapping): # ABCs for read-only and mutable mappings. """This class is not thread safe""" def __init__(self, timeout=60, close_callback=None, *args, **kwargs): self.timeout = timeout # the cache expire time self.close_callback = close_callback ...
jphnoel/udata
udata/core/dataset/signals.py
Python
agpl-3.0
226
0
# -*- coding: utf-8 -*- from __futur
e__ import unicode_literals from blinker import Namespace namespace = Namespace() #: Trigerred when a dataset is published on_dataset_published = namespace.signal('on-dataset-published'
)
ktan2020/legacy-automation
win/Lib/site-packages/wx-3.0-msw/wx/lib/analogclock/lib_setup/fontselect.py
Python
mit
1,713
0.005838
# AnalogClock's font selector for setup dialog # E. A. Tacao <e.a.tacao |at| estadao.com.br> # http://j.domaindlx.com/elements28/wxpython/ # 15 Fev 2006, 22:00 GMT-03:00 # Distributed under the wxWidgets license. import wx from wx.lib.newevent import NewEvent from wx.lib.buttons import GenButton #----...
self): return self.value def SetValue(self, value): if value is None: value = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT) self.value = value def OnClick(self, event): data = wx.FontData() data.EnableEffects(False) font = self.va...
data = dlg.GetFontData() self.value = data.GetChosenFont() self.Refresh() dlg.Destroy() if changed: nevt = FontSelectEvent(id=self.GetId(), obj=self, val=self.value) wx.PostEvent(self.parent, nevt) # ## ### eof
weargoggles/jwt-oauth-test
project/hooks/views.py
Python
gpl-3.0
995
0.00201
import binascii from cryptography.hazmat.primitives import hmac from cryptography.hazmat.primitives.hashes import SHA1 from cryptography.hazmat.primitives.constant_time import bytes_eq import cryptography.hazmat.backends from django.conf import settings from django.core.mail import send_mail from django.http import Htt...
= cryptography.hazmat.backends.default_backend() def verify_signature(request, request_body): hmac_hmac = hmac.HMAC(settings.GITHUB_WEBHOOK_SECRET, SHA1(), crypto_backend) hmac_hmac.update(request_body) signature = b'sha1=' + binascii.hexlify(hmac_hmac.finalize()) return bytes_eq(signature, request.M...
quest): verify_signature(request, request.body) send_mail('Hook from github', request.body, settings.SERVER_EMAIL, map(lambda t: t[-1], settings.ADMINS)) return HttpResponse(status=200)
arskom/spyne
spyne/util/tdict.py
Python
lgpl-2.1
2,861
0.00035
# # spyne - Copyright (C) Spyne contributors. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This libra...
: vt = type(v) retval = tdict(kt, vt) for s in S:
retval[s] = v return retval def repr(self): return "tdict(kt=%s, vt=%s, data=%s)" % \ (self._kt, self._vt, super(tdict, self).__repr__())
kdlucas/pyrering
lib/baserunner_test.py
Python
apache-2.0
10,873
0.003219
#!/usr/bin/python # # Copyright 2008 Google 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 required by app...
t redirect to stderr.""" self.one_config['TEST_SCRIPT'] = 'echo testEchoToSTDERRCommand >&2' self.scanner.SetConfig([self.one_config]) result = self.runner.Run(['testEchoSTDERRCommand'], False) self.assertEqual(result, 0) self.assertEqual(self.runner.passed, 1) #TODO(mwu): need to check the log...
nScript(self): """A real script to run.""" self.one_config['TEST_SCRIPT'] = os.path.join(global_settings['root_dir'], 'test/test1_echo.sh') self.scanner.SetConfig([self.one_config]) result = self.runner.Run(['testRunScript'], False) self.assertEqual...
ptrendx/mxnet
python/mxnet/optimizer/optimizer.py
Python
apache-2.0
66,906
0.002735
# 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 # "License"...
index to identify the weight. weight : NDArray The weight. Returns ------- state : any obj The state associated with the weight. """ def create_state_multi_precision(self, index, weight): """Creates auxiliary state for a given weight, includi...
opy if original weight is FP16. Th
xmikos/qhangups
qhangups/ui_qhangupsbrowser.py
Python
gpl-3.0
1,146
0.004363
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'qhangups/qhangupsbrowser.ui' # # Created by: PyQt5 UI code generator 5.7 # # WARNING! All changes made in this file
will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_QHangupsBrowser(object): def setupUi(self, QHangupsBrowser): QHangupsBrowser.setObjectName("QHangupsBrowser") QHangupsBrowser.resize(600, 450) self.verticalLayout = QtWidgets.QVBoxLayout(QHangupsBrowser) self.vertica...
("verticalLayout") self.browserWebView = QtWebKitWidgets.QWebView(QHangupsBrowser) self.browserWebView.setUrl(QtCore.QUrl("about:blank")) self.browserWebView.setObjectName("browserWebView") self.verticalLayout.addWidget(self.browserWebView) self.retranslateUi(QHangupsBrowser) ...
M4rtinK/pyside-android
tests/QtGui/qlayout_ref_test.py
Python
lgpl-2.1
4,597
0.003481
'''Test cases for QLayout handling of child widgets references''' import unittest from sys import getrefcount from PySide.QtGui import QHBoxLayout, QVBoxLayout, QGridLayout, QWidget from PySide.QtGui import QStackedLayout, QFormLayout from PySide.QtGui import QApplication, QPushButton, QLabel from helper import Use...
kLayoutReference(QFormLayout(w)) def testStackedReference(self): #QStackedLayout.addWidget reference count w = QWidget() self.checkLayoutReference(QStackedLayout(w)) class MultipleAdd(UsesQApplication): '''Test case to check if refcount is incremented only once when multiple
calls to addWidget are made with the same widget''' qapplication = True def setUp(self): #Acquire resources super(MultipleAdd, self).setUp() self.widget = QPushButton('click me') self.win = QWidget() self.layout = QHBoxLayout(self.win) def tearDown(self): ...
FreshXOpenSource/wallaby-base
wallaby/pf/peer/searchDocument.py
Python
bsd-2-clause
1,556
0.005141
# Copyright (c) by it's authors. # Some rights reserved. See LICENSE, AUTH
ORS. from peer import * from viewer import Viewer from editor import Editor class SearchDocument(Peer): #Receiving pillows: Search = Pillow.In Sending = [ Viewer.In.Document ] Routings = [ (Editor.Out.FieldChanged, Viewer.In.Refresh) ] def __init__(self, searchRoom, re...
Room = searchRoom self._resultRoom = resultRoom self._identifier = identifier self._appendWildcard = appendWildcard if document: self._document = document else: from wallaby.common.queryDocument import QueryDocument self._document = QueryDocu...
tonsom1592-cmis/tonsom1592-cmis-cs2
recursion.py
Python
cc0-1.0
624
0.0625
def countup(n): if n >= 10: print "Blastoff!" else: print n countup(n+1) def main(): countup(1) main() def countdown_from_to(start,stop): if start == stop: print "Blastoff!" elif start <= stop: print "Invalid pair" else: print start countdown_from_to(start - 1,stop) def main(): countdown_...
elif number == float: print number else: sum_ += float(number) print "Running total: {}".format(sum_) adder(sum_) def main(): sum_ = 0 adder(sum_) mai
n()
nsubiron/configure-pyz
setup.py
Python
gpl-3.0
1,666
0.006002
#!/usr/bin/env python """zip source directory tree""" import argparse import fnmatch import logging import os import re import subprocess import zipfile def get_version(): command = ['git', 'describe', '--tags', '--dirty', '--always'] ret
urn subprocess.check_output(command).decode('utf-8') def source_walk(root): root = os.path.abspath(root) regex = re.compile(fnmatch.translate('*.py[co]')) for path, _, files in os.walk(root): files[:] = [f
for f in files if regex.match(f) is None] for filename in files: fullpath = os.path.join(path, filename) yield fullpath, os.path.relpath(fullpath, root) def setup(): argparser = argparse.ArgumentParser(description=__doc__) argparser.add_argument( '-d', '--debug', action='...
jcnix/abg
enemies.py
Python
gpl-3.0
2,843
0.008442
# -*- coding: utf-8 -*- # File: enemy.py # Author: Casey Jones # # Created on July 20, 2009, 4:48 PM # # This file is part of Alpha Beta Gamma (abg). # # ABG 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, ...
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 ABG. If not, see <http://www.gnu.org/licenses/>. #class to handle all enemies...
Surface([Enemy.enemy.get_width(), Enemy.enemy.get_height()]) blackSurface.fill([0,0,0]) screen = None def set_screen(self, screen): self.screen = screen def create(self): #range that the current player ship can shoot where_spawn = random.randint(1, properties.width - En...
gppezzi/easybuild-framework
easybuild/tools/module_naming_scheme/mns.py
Python
gpl-2.0
7,666
0.004696
## # Copyright 2011-2019 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), # Flemish Research Foundation (F...
Determine list of subdirector
ies relative to the user-specific modules directory for which to extend $MODULEPATH with when this module is loaded (if any). :param ec: dict-like object with easyconfig parameter values; for now only the 'name', 'version', 'versionsuffix' and 'toolchain' parameters are guaranteed to...
grpc/grpc-ios
native_src/third_party/googletest/googletest/test/googletest-json-outfiles-test.py
Python
apache-2.0
5,705
0.003155
#!/usr/bin/env python # Copyright 2018, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list o...
ne', u'SetUpProp': u'1', u'TestSomeProperty': u'1', u'TearDownProp': u'1', }], }], } EX
PECTED_2 = { u'tests': 1, u'failures': 0, u'disabled': 0, u'errors': 0, u'time': u'*', u'timestamp': u'*', u'name': u'AllTests', u'testsuites': [{ u'name': u'PropertyTwo', u'tests': 1, ...
xuru/pyvisdk
pyvisdk/enums/profile_numeric_comparator.py
Python
mit
307
0
######################################## # Automatically generated, do not edit. ##########################
############## from pyvisdk.thirdparty import Enum ProfileNumericComparator = Enum( 'equal',
'greaterThan', 'greaterThanEqual', 'lessThan', 'lessThanEqual', 'notEqual', )
poeticcapybara/pythalesians
pythalesians-examples/marketliquidity_examples.py
Python
apache-2.0
758
0.006596
__author__ = 'saeedamen' # # Copyright 2015 Thalesians Ltd. - http//www.thalesians.com / @thalesians # # 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 ...
r express or implied. # # See the License for the specific language governing permissions and limitations under the License. # """ marke
tliquidity_examples Shows how to calculate market liquidity using bid/ask data and tick counts. """ # TODO
pdelsante/thug
thug/ActiveX/modules/NamoInstaller.py
Python
gpl-2.0
1,217
0.008217
# NamoInstaller ActiveX Control 1.x - 3.x # CVE-NOMATCH import logging log = logging.getLogger("Thug") def Install(s
elf, arg): if len(arg) > 1024: log.ThugLogging.log_exploit_event(self._window.url,
"NamoInstaller ActiveX", "Overflow in Install method") log.DFT.check_shellcode(arg) if str([arg]).find('http') > -1: log.ThugLogging.add_behavior_warn('[NamoInstaller ActiveX] Insecure download from URL %s' % (arg, )) log.ThugLogging.log_e...
chemalot/chemalot
bin/gOpt.py
Python
apache-2.0
7,487
0.024709
#!/usr/bin/env python #Alberto from __future__ import print_function, division import os import glob import argparse from subprocess import Popen, PIPE from argparse import RawTextHelpFormatter import sys import re from textwrap import dedent from subprocess import call def warn(*objs): print(*objs, file=sys.stder...
mmand, self.middle, self.coords, self.end]) def isOpt(self): return GJob.OPTPat.search(self.command) def isFreq(self): return GJob.FREQPat.search(self.command) def execute(self, outName): com = dedent(""" date>>%s;gaussian.csh >>%s<<'gJOBComs' %s'gJOBComs'""") % (outName,o...
"-fc", com]) if status > 0: raise IOError("Gaussian returned error code=%d" % status) p = Popen("tail -n 10 "+outName, shell=True, bufsize=2048, stdin=PIPE, stdout=PIPE, close_fds=True) stdin,stdout= p.stdin, p.stdout #stdin,stdout = os.popen2("tail -n 10 "+outName) ...
EternityForest/KaithemAutomation
kaithem/src/thirdparty/uncertainties/umath_core.py
Python
gpl-3.0
14,767
0.001761
# !!!!!!!!!!! Add a header to the documentation, that starts with something # like "uncertainties.UFloat-compatible version of...", for all functions. """ Implementation of umath.py, with internals. """ # This module exists so as to define __all__, which in turn defines # which functions are visible to the user in um...
sys import itertools #
Local modules import uncertainties.core as uncert_core from uncertainties.core import (to_affine_scalar, AffineScalarFunc, LinearCombination) ############################################################################### # We wrap the functions from the math module so that they keep ...
embotech/forcesnlp-examples
robot/acado/export_MPC/forces/interface/forces_build.py
Python
mit
2,126
0.031044
#forces : A fast customized optimization solver. # #Copyright (C) 2013-2016 EMBOTECH GMBH [info@embotech.com]. All rights reserved. # # #This software is intended for simulation and testing purposes only. #Use of this software for any commercial purpose is prohibited. # #This program is distributed in the hope that it...
_preargs=['-O3','-fPIC','-fopenmp','-mavx']) if sys.platform.startswith('linux'): c.set_libraries(['rt','gomp']) else: objects = c.compil
e([sourcefile], output_dir=objdir) # create libraries libdir = os.path.join(os.getcwd(),"forces","lib") exportsymbols = ["%s_solve" % "forces"] c.create_static_lib(objects, "forces", output_dir=libdir) c.link_shared_lib(objects, "forces", output_dir=libdir, export_symbols=exportsymbols)
clicumu/epo_utils
epo_utils/api.py
Python
mit
20,708
0.000145
# -*- coding: utf-8 -*- """ Module for making calls to EPO-OPS REST-API. This module contain classes and functions to get data from [EPO-OPS API](http://www.epo.org/searching-for-patents/technical/espacenet/ops.html) """ import logging import re import time from base64 import b64encode from collections import namedtup...
elf.id_type == 'docdb': id_ =
'.'.join(parts) elif self.id_type == 'epodoc': if self.date is not None: id_ = ''.join(parts[:-1]) id_ += '.' + self.date else: id_ = ''.join(parts) elif self.id_type == 'classification': return number else: ...
dakrauth/snarf
snagit/core.py
Python
mit
7,965
0.000126
import os import re import sys import json import shlex import logging import inspect import functools import importlib from pprint import pformat from collections import namedtuple from traceback import format_tb from requests.exceptions import RequestException import strutil from cachely.loader import Loader from ....
line = chars.rstrip() if not line or line.lstrip().startswith('#'): continue logger.debug('Lexed {} byte(s) line {}'.format(len(line), chars)) yield Instruction.parse(line, l
ineno) def load_libraries(extensions=None): if isinstance(extensions, str): extensions = [extensions] libs = BASE_LIBS + (extensions or []) for lib in libs: importlib.import_module(lib) class Interpreter: def __init__( self, contents=None, loader=None, ...
shahin/sqltxt
tests/unit/table_test.py
Python
mit
5,179
0.013516
import unittest import os from sqltxt.table import Table from sqltxt.column import Column, ColumnName, AmbiguousColumnNameError from sqltxt.expression import Expression class TableTest(unittest.TestCase): def setUp(self): self.data_
path = os.path.join(os.path.dirname(__file__), '../data') table_header = ["col_a", "col_b"] table_contents = """1,1 2,3 3,2""" self.table_a = Table.from_cmd( name = 'table_
a', cmd = 'echo -e "{0}"'.format(table_contents), columns = table_header ) table_header = ["col_a", "col_b"] table_contents = """1,w 2,x 2,y 5,z""" self.table_b = Table.from_cmd( name = 'table_b', cmd = 'echo -e "{0}"'.format(table...
mramire8/active
strategy/randomsampling.py
Python
apache-2.0
21,847
0.006454
__author__ = 'mramire8' from collections import defaultdict import copy import numpy as np from sklearn.linear_model import LogisticRegression from baselearner import BaseLearner from sklearn.feature_extraction.text import CountVectorizer from datautil.textutils import StemTokenizer show_utilitly = False class Ra...
rmat(neu), print "\t{0:.3f}".format(costk), return utility def getk(self, doc_text): ''' Return a set of subinstance of k words in classifier f
ormat :param doc_text: :return: set of subinstances of doc_tex
rolepoint/appengine-mapreduce
python/test/mapreduce/control_test.py
Python
apache-2.0
10,366
0.00328
#!/usr/bin/env python # # Copyright 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
ed by handlers_test. Just a smoke test is enough. """ TestEntity().put() shard_count = 4 mapreduce_id = control.start_map( "test_map", __name__ + ".test_handler", "mapreduce.input_reader
s.DatastoreInputReader", { "entity_kind": __name__ + "." + TestEntity.__name__, }, shard_count, mapreduce_parameters={"foo": "bar"}, base_path="/mapreduce_base_path", queue_name=self.QUEUE_NAME) self.validate_map_started(mapreduce_id) def testStartMap_...
FrancescoCeruti/linux-show-player
lisp/modules/midi/midi_output.py
Python
gpl-3.0
1,339
0
# -*- coding: utf-8 -*- # # This file is part of Linux Show Player # # Copyright 2012-2016 Francesco Ceruti <ceppofrancy@gmail.com> # # Linux Show Player 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 ...
eral Public License # along with Linux Show Player. If not, see <http://www.gnu.org/licenses/>. import mido from lisp.modules.midi.midi_common import MIDICommon from lisp.modules.midi.midi_utils import mido_backend, mido_port_name class MIDIOutput(MIDICommon): def __init__(self,
port_name='AppDefault'): super().__init__(port_name=port_name) def send_from_str(self, str_message): self.send(mido.parse_string(str_message)) def send(self, message): self._port.send(message) def open(self): port_name = mido_port_name(self._port_name, 'O') self._p...
Lucas-Wong/ToolsProject
CodeReview/Change_Xml.py
Python
gpl-3.0
1,695
0.00767
# ! /usr/bin/env python # _*_ coding:utf-8 _*_ """ @author = lucas.wang @create_time = 2018-01-12 """ from xml.etree import ElementTree as ET import fnmatch class change_xml(object): """ xml main function """ names = ['iConn.CreateXmlTools.vshost.exe', 'AutoUpdater.dll', 'NewTonsoft.Json.dll', ...
name self.tree = ET.parse(file_path + file_name) self.path_name = path_name def read_xml(self): """ Read xml file :return: """ root = self.tree.getroot() # print(root) for item in root.getchildren(): # root.iter("file"): ...
if fnmatch.filter(self.names, item.get('path')): root.remove(item) self.write_xml() def write_xml(self): self.tree.write(self.file_path + self.file_name) print("Update xml file success. file: " + self.file_path + self.file_name) if __name__ == '__main__': "...
fiduswriter/fiduswriter
fiduswriter/document/models.py
Python
agpl-3.0
11,689
0
from builtins import str from builtins import object from django.db import models from django.db.utils import OperationalError, ProgrammingError from django.core import checks from django.conf import settings from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models impor...
return False return True @classmethod def check(cls, **kwargs): errors = super().check(**kwargs) errors.extend(cls._check_doc_versions(**kwargs)) return errors @cla
ssmethod def _check_doc_versions(cls, **kwargs): try: if len( cls.objects.filter(doc_version__lt=str(FW_DOCUMENT_VERSION)) ): return [ checks.Warning( "Documents need to be upgraded. Please navigate to " ...
CGATOxford/CGATPipelines
obsolete/pipeline_genesets.py
Python
mit
12,292
0.000163
"""=========================== Geneset analysis =========================== :Author: Andreas Heger :Release: $Id$ :Date: |today| :Tags: Python Overview ======== This pipeline performs gene set analysis of one or more genesets. Input data are two collections of files, genelists and pathways. Genelists are tabular d...
ix matrix = SetTools.unionIntersectionMatrix(genesets) with IOTools.openFile(outfile + ".matrix.gz", "w") as outf: IOTools.writeMatrix(outf, matrix, headers, headers) matrix = SetTools.unionIntersectionMatrix(backgrounds) with IOTools.openFile(outfile + ".bg.matrix.gz", "w") as outf: IOT...
ix, headers, headers) @transform(buildGeneListMatrix, suffix(".tsv.gz"), ".load") def loadGeneListMatrix(infile, outfile): '''load fgene list matrix into table.''' track = P.snip(infile, ".tsv.gz") P.load(infile, outfile, tablename="%s_foreground" % track) P.load(infile + ".bg.ts...
cyclops1982/pdns
regression-tests.recursor-dnssec/test_RootNXTrust.py
Python
gpl-2.0
3,474
0.002303
import dns import requests import socket from recursortests import RecursorTest class RootNXTrustRecursorTest(RecursorTest): def getOutgoingQueriesCount(self): headers = {'x-api-key': self._apiKey} url = 'http://127.0.0.1:' + str(self._wsPort) + '/api/v1/servers/localhost/statistics' r = r...
_confdir = 'RootNXTrustEnabled' _wsPort = 8042 _wsTimeout = 2 _wsPassword = 'secretpassword' _apiKey = 'secretapikey' _config_template = """ root-nx-trust=yes webserver=yes webserver-port=%d webserver-address=127.0.0.1 webserver-password=%s api-key=%s """ % (_wsPort, _wsPassword, _apiKey) ...
trust enabled, we don't query the root for www2.nx-example. after receiving a NXD from "." for nx-example. as an answer for www.nx-example. """ # first query nx.example. before = self.getOutgoingQueriesCount() query = dns.message.make_query('www.nx-example.', 'A') res = ...
Alexoner/health-care-demo
careHealth/earth/action/hooks.py
Python
gpl-2.0
1,374
0
# -*- coding: utf-8 -*- import json def json_pre_process_hook(action, request, *args, **kwargs): json_data = request.body if not json_data: action.ret('002').msg('json_params_required') return False try: param_dict = json.loads(json_data) except ValueError: action.ret...
ue for key, value in params_dict.items(): setattr(action, key, value) return True def form_pre_process_hook(action, request, *args, **kwargs): param_dict = request.POST if not param_dict: action.ret('004').msg('form_params_req
uired') return False for key, value in param_dict.items(): setattr(action, key, value) return True def jsonp_post_render_hook(action): if action.jsonp_callback: action.resp_data_json( action.jsonp_callback + '(' + action.resp_data_json + ')', ) ...
epam/DLab
infrastructure-provisioning/src/general/scripts/aws/jupyter_configure.py
Python
apache-2.0
15,517
0.004705
#!/usr/bin/python # ***************************************************************************** # # Copyright (c) 2016, EPAM SYSTEMS INC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # #...
DEBUG, filename=local_log_filepath) notebook_config = dict() try: notebook_config['exploratory_name'] = os.environ['exploratory_name'] except: notebook_config['exploratory_name'] = '' notebook_config['service_base_name'] = os.environ['conf_service_base_name'] ...
ebook_config['key_name'] = os.environ['conf_key_name'] notebook_config['user_keyname'] = os.environ['edge_user_name'] notebook_config['instance_name'] = '{}-{}-nb-{}-{}'.format(notebook_config['service_base_name'], os.environ['edge_user_name'], ...
imndszy/voluntary
app/admin/__init__.py
Python
mit
178
0.005618
# -*- coding:utf8 -*- # Aut
hor: shizhenyu96@gamil.com # github: https://github.com/imndszy from flask import Blueprint admin = Blueprint('admin', __
name__) from . import views
lightsweeper/lightsweeper-api
setup.py
Python
mit
528
0.020833
#!/usr/bin/env python
import sys from setuptools import setup if sys.hexversion < 0x030200a1: print ("LightSweeper requires python 3.2 or higher.") print("Exiting...") sys.exit(1) setup(name='LightSweeper', version='0.6b', description='The LightSweeper API', author='The LightSweeper Team', author_email='codewi...
)
tantalor/emend
app/emend/twitter.py
Python
mit
1,161
0.014643
from megaera import local, json from oauth import signed_url from google.appengine.api import urlfetch __TWITTER_API__ = "http://api.twitter.com/1" def tweet(status, **credentials): if no
t credentials: # shortcut for no-credentials case credentials = local.config_get('twitter') if not credentials: return update_url = "%s/statuses/update.json" % __TWITTER_API__ fetch_url = signed_url(url=update_url, method='POST', status=status, **credentials) response = urlfetch.fetch(fetch_url,...
if not credentials: # shortcut for no-credentials case credentials = local.config_get('twitter') if not credentials: return destroy_url = "%s/statuses/destroy.json" % __TWITTER_API__ fetch_url = signed_url(url=destroy_url, method='POST', id=status_id, **credentials) response = urlfetch.fetch(fe...
nmunro/azathoth
news/migrations/0001_initial.py
Python
agpl-3.0
603
0.001658
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-08-06 11:13 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='NewsIt...
h=256)), ('content', models.TextFi
eld()), ], ), ]
LegionXI/pydarkstar
pydarkstar/tests/auction/test_worker.py
Python
mit
350
0.014286
import unittest import logging logging.getLogger().setLevel(logging.DEBUG) from
...auction.worker import Worker from ...database import Database from ...rc import sql class TestCase(unittest.TestCase): def setUp(self
): self.db = Database.pymysql(**sql) self.ob = Worker(self.db, fail=True) def test_init(self): pass
Juanvulcano/zulip
zerver/tests/test_messages.py
Python
apache-2.0
72,787
0.001924
# -*- coding: utf-8 -*- from __future__ import absolute_import from django.db.models import Q from django.conf import settings from django.http import HttpResponse from django.test import TestCase, override_settings from django.utils import timezone from zerver.lib import bugdown from zerver.decorator import JsonableEr...
elf.assert_json_error(result, 'Invalid stream id') class TestCrossRealmPMs(ZulipTestCase): def make_realm(self, domain): # type: (Text) -> Realm realm = Realm.objects.create(string_id=domain, domain=domain, invite_required=False) RealmAlias.objects.create(realm=realm, domain=domain) ...
f setUp(self): # type: () -> None dep = Deployment() dep.base_api_url = "https://zulip.com/api/" dep.base_site_url = "https://zulip.com/" # We need to save the object before we can access # the many-to-many relationship 'realms' dep.save() dep.realms = [ge...
colloquium/spacewalk
backend/satellite_tools/rhn_ssl_dbstore.py
Python
gpl-2.0
4,252
0.005174
# # Copyright (c) 2009--2010 Red Hat, Inc. # # This software is licensed to you under the GNU General Public License, # version 2 (GPLv2). There is NO WARRANTY for this software, express or # implied, including the implied warranties of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. You should have received a c...
import CFG, initCFG from spacewalk.server import rhnSQL import satCerts DEFAULT_TRUSTED_CERT = 'RHN-ORG-TRUSTED-SSL-CERT' def fetchTraceback(method=None, req=None, extra=None): """ a cheat for snagging just the string value of a Tr
aceback NOTE: this tool may be needed for RHN Satellite 3.2 as well, which doesn't have a fetchTraceback. So... this if for compatibility. """ from cStringIO import StringIO exc = StringIO() rhnTB.Traceback(method=method, req=req, mail=0, ostream=exc, ...
dasbruns/netzob
src/netzob/Common/Models/Types/Raw.py
Python
gpl-3.0
7,876
0.001398
# -*- coding: utf-8 -*- # +---------------------------------------------------------------------------+ # | 01001110 01100101 01110100 01111010 01101111 01100010 | # | | # | Netzob : Inferring communication prot...
HexaString return "{0}={1} ({2})".format(self.typeName, repr(TypeConverter.convert(self.value, BitArray, Raw)), self.size) else: return "{0}={1} ({2})".format(self.typeName, self.value, self.size) def __repr__(sel
f): if self.value is not None: from netzob.Common.Models.Types.TypeConverter import TypeConverter from netzob.Common.Models.Types.BitArray import BitArray return str(TypeConverter.convert(self.value, BitArray, self.__class__)) else: return str(self.value) ...
BigRoy/vrayformayaUtils
tests/attributes_tests.py
Python
gpl-2.0
5,376
0.006696
import unittest import maya.cmds as mc import vrayformayaUtils as vfm class TestMeshAttributes(unittest.TestCase): """ This is a generic TestCase for most v-ray mesh attributes. Note that it doesn't test every single case of changes, but it should capture overall changes of the code. """ d...
s("{0}.vrayViewDep".format(shape))) vfm.attributes.vray_subquality(shapes, smartConvert=False, state=False) for shape in shapes: self.assertFalse(mc.objExists("{0}.vrayEdgeLength".format(shape)))
self.assertFalse(mc.objExists("{0}.vrayMaxSubdivs".format(shape))) self.assertFalse(mc.objExists("{0}.vrayOverrideGlobalSubQual".format(shape))) self.assertFalse(mc.objExists("{0}.vrayViewDep".format(shape))) def test_vray_user_attributes(self): transform = self.mesh shapes...
OpusVL/odoo-confutil
confutil/account_setup.py
Python
agpl-3.0
4,594
0.00566
# -*- coding: utf-8 -*- ############################################################################## # # Post-installation configuration helpers # Copyright (C) 2015 OpusVL (<http://opusvl.com/>) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General P...
te_id, code_digits=None, context=None): chart_wizard = registry['wizard.multi.charts.accounts'] defaults = chart_wizard.default_get(cr, uid, ['bank_accounts_id', 'currency_id'], context=context) bank_accounts_spec = defaults.pop('bank_accounts_id') bank_accounts_id = [(0, False, i) for i in bank_accoun...
bank_accounts_id': bank_accounts_id, }) onchange = chart_wizard.onchange_chart_template_id(cr, uid, [], data['chart_template_id'], context=context) data.update(onchange['value']) if code_digits: data.update({'code_digits': code_digits}) conf_id = chart_wizard.create(cr, uid, data, context=...
Bl4ckb0ne/ring-api
ring_api/extra/servers/cherrypy/api/root.py
Python
gpl-3.0
347
0.008646
import c
herrypy, json from bottle import request, get from ring_api.server.api import ring, user class Root(object): def __init__(self, dring): self.dring = dring self.user = user.User(dring) @cherrypy.expose def index(self): return 'todo' @cherrypy.expose def routes(self): ...
n 'todo'
charlietsai/catmap
catmap/cli.py
Python
gpl-3.0
2,874
0.000348
import os import shutil usage = {} usage['import'] = """catmap import <mkm-file> Open a *.mkm project file and work with it interactively. """ def get_options(args=None, get_parser=False): import optparse import os from glob import glob import catmap parser = optparse.OptionParser( ...
ed \ import InteractiveShellEmbed InteractiveShellEmbed(banner1=banner)() except ImportError: from IPython.Shell import IPShellEmbed
IPShellEmbed(banner=banner)() else: from IPython.Shell import IPShellEmbed IPShellEmbed(banner=banner)()
weykent/ansible-runit-sv
tests/test_runit_sv.py
Python
isc
14,619
0
# Copyright (c) weykent <weykent@weasyl.com> # See COPYING for details. import pytest import runit_sv as _runit_sv_module SETTABLE_MASK = _runit_sv_module.SETTABLE_MASK idempotent = pytest.mark.idempotent def pytest_generate_tests(metafunc): if 'idempotency_state' not in metafunc.fixturenames: return ...
e_checker(params) module = FakeAnsibleModule(params, check) with pytest.raises(FakeAnsibleModuleBailout) as excinfo: _runit_sv_module.main(module) assert excinfo.value.success != should_fail if check_change is not None: check_change(exc
info.value.params['changed']) else: raise ValueError('unknown param', request.param) if idempotency_state == 'checked': _do = do def do(**params): _do(_must_change=True, **params) _do(_must_not_change=True, **params) return do @pytest.fixture def basedir...
foreni-packages/hachoir-regex
hachoir_regex/parser.py
Python
gpl-2.0
6,130
0.006199
""" Parse string to create Regex object. TODO: - Support \: \001, \x00, \0, \ \[, \(, \{, etc. - Support Python extensions: (?:...), (?P<name>...), etc. - Support \<, \>, \s, \S, \w, \W, \Z <=> $, \d, \D, \A <=> ^, \b, \B, [[:space:]], etc. """ from hachoir_regex import (RegexString, RegexEmpty, RegexRepeat, R...
if char == 'b': new_regex = RegexWord() else: if not(char in REGE
X_COMMAND_CHARACTERS or char in " '"): raise SyntaxError("Operator '\\%s' is not supported" % char) new_regex = RegexString(char) index += 1 else: raise NotImplementedError("Operator '%s' is not supported" % char) if las...
lukesanantonio/blendergltf
gpu_luts.py
Python
apache-2.0
3,110
0.018328
from gpu import * LAMP_TYPES = [ GPU_DYNAMIC_LAMP_DYNVEC, GPU_DYNAMIC_LAMP_DYNCO, GPU_DYNAMIC_LAMP_DYNIMAT, GPU_DYNAMIC_LAMP_DYNPERSMAT, GPU_DYNAMIC_LAMP_DYNENERGY, GPU_DYNAMIC_LAMP_DYNENERGY, GPU_DYNAMIC_LAMP_DYNCOL, GPU_DYNAMIC_LAMP_DISTANCE, GPU_DYNAMIC_LAMP_ATT1, GPU_DYNAMIC...
GPU_DYNAMIC_OBJECT_VIEWMAT : 'view_mat', GPU_DYNAMIC_OBJECT_MAT : 'model_mat', GPU_DYNAMIC_OBJECT_VIEWIMAT : 'inv_view_mat', GPU_DYNAMIC_OBJECT_IMAT : 'inv_model_mat', GPU_DYNAMIC_OBJECT_COLOR : 'color', GPU_DYNAMIC_OBJECT_AUTOBUMPSCALE : 'auto_bump_scale', GPU_DYNAMIC_MIST_ENABLE : 'u
se_mist', GPU_DYNAMIC_MIST_START : 'start', GPU_DYNAMIC_MIST_DISTANCE : 'depth', GPU_DYNAMIC_MIST_INTENSITY : 'intensity', GPU_DYNAMIC_MIST_TYPE : 'falloff', GPU_DYNAMIC_MIST_COLOR : 'color', GPU_DYNAMIC_HORIZON_COLOR : 'horizon_color', GPU_DYNAMIC_AMBIENT_COLOR : 'ambient_color', GPU_...
msartintarm/site
server.py
Python
mit
1,592
0.029523
import os.path from tornado import ioloop, httpserver, web, websocket, templ
ate from config import GameConfig OS = os.path.dirname(__file__) def server_path(uri): return os.path.join(OS, uri) def static_path(uri): return { "path": server_path("static/" + uri) } level_1 = G
ameConfig() class TarmHandler(web.RequestHandler): def get(self): self.render(server_path("html/game.html"), config = level_1) def write_error(self, code, **kwargs): self.render(server_path("html/error.html")) class TarmSocket(websocket.WebSocketHandler): def open(self, *args): self.stream.set_nodelay(Tru...
Azure/azure-sdk-for-python
sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/__init__.py
Python
mit
1,234
0.002431
# 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 ...
----- from ._policy_tracked_resources_operations import PolicyTrackedResourcesOperations from ._remediations_operations import RemediationsOperations from ._policy_events_operations import PolicyEventsOperations from ._policy_states_operations import PolicyStatesOperations from ._operations import Operations from ._po...
mport PolicyMetadataOperations from ._policy_restrictions_operations import PolicyRestrictionsOperations from ._attestations_operations import AttestationsOperations __all__ = [ 'PolicyTrackedResourcesOperations', 'RemediationsOperations', 'PolicyEventsOperations', 'PolicyStatesOperations', 'Operat...
toastdriven/eliteracing
cmdrs/tests/test_models.py
Python
bsd-3-clause
666
0
import hashlib import mock import uuid from django.test import TestCase from ..models im
port Commander class CommanderTestCase(TestCase): def test_generate_token(self): with mock.patch.object(uuid, 'uuid4', return_value='a_test'): cmdr = Commander( name='Branch' ) self.assertEqual( cmdr.generate_token(), hash...
ommander.objects.create( name='Branch' ) self.assertTrue(len(cmdr.api_token) > 0)