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
szopu/django-rest-registration
rest_registration/__init__.py
Python
mit
91
0
__versi
on__ = "0.5.2" default_app_config = 'rest_registration.apps.RestR
egistrationConfig'
KarolBedkowski/kupfer-adds
kupfer/plugin/session_xfce.py
Python
gpl-3.0
793
0.011364
# -*- coding: utf-8 -* __kupfer_name__ = _("XFCE Session Management") __kupfer_sources__ = ("XfceItemsSource", ) __description__ = _("Special items and actions for XFCE environment") __version__ = "2012-09-17" __author__ = "Karol Będkowski <karol.bedkowski@gmail.com>" from kupfer.plugin import session_support as supp...
["xdg-screensaver", "lock"], ) class XfceItemsSource (support.CommonSource): def __init__(self): support.CommonSource.__init__(self, _("XFCE Session Management")) def get_items(self): return ( support.LogoutBrowse(LOGOUT_CMD), support.LockScreen(LOCKS
CREEN_CMD), support.ShutdownBrowse(SHUTDOWN_CMD), )
RuiNascimento/krepo
script.module.lambdascrapers/lib/lambdascrapers/sources_placenta/en_placenta-1.7.8/viooz.py
Python
gpl-2.0
4,650
0.013548
# -*- coding: UTF-8 -*- ####################################################################### # ---------------------------------------------------------------------------- # "THE BEER-WARE LICENSE" (Revision 42): # @Daddy_Blamo wrote this file. As long as you retain this notice you # can do whatever you want wi...
-------------------------------------------------------------- ####################################################################### # Addon Name: Placenta # Addon id: plugin.video.placenta # Addon Provider: Mr.Blamo import re,urllib,urlparse,json,base64,time from resources.lib.modules import cleantitle from resou...
self.language = ['en'] self.domains = ['vioozfree.net'] self.base_link = 'http://vioozfree.net' self.search_link = '/watch/%s-%s-online-viooz.html' def movie(self, imdb, title, localtitle, aliases, year): try: clean_title = cleantitle.geturl(title) ...
Orav/kbengine
kbe/src/lib/python/Lib/email/utils.py
Python
lgpl-3.0
14,708
0.00102
# Copyright (C) 2001-2010 Python Software Foundation # Author: Barry Warsaw # Contact: email-sig@python.org """Miscellaneous utilities.""" __all__ = [ 'collapse_rfc2231_value', 'decode_params', 'decode_rfc2231', 'encode_rfc2231', 'formataddr', 'formatdate', 'format_datetime', ...
air is false, then the second element is returned unmodified. Optional charset if given is the character set that is used to encode realname in case realname is not ASCII safe. Can be an instance of str or a Charset-like object which has a header_encode method. Default is 'utf-8'. """ ...
dress MUST (per RFC) be ascii, so raise an UnicodeError if it isn't. address.encode('ascii') if name: try: name.encode('ascii') except UnicodeEncodeError: if isinstance(charset, str): charset = Charset(charset) encoded_name = charset.he...
DISMGryphons/GryphonCTF2017-Challenges
challenges/crypto/BinaryBacon/generate/create.py
Python
gpl-3.0
740
0.078378
#!/usr/bin/env python3 import random import sys f=open("BACON","r") o=open("BINARY","w") z=f.readlines() k=[] oo="" st=sys.argv[1] ss=''.join(['%08d'%int(bin(ord(i))[2:]) for i in st]) print("ENCRYPTING...") print("Word => ",st,end="\n\n") print("Encrypted => ",end="") for i in z: k.append(i.strip()) for i in ss: ...
(0,len(k[n])-1) j=k[n][b] print(j,end="") oo=oo+j print(n+1,":",b+1,file=o) if i=="0": j="" while not j.islower(): n
=random.randint(0,13) b=random.randint(0,len(k[n])-1) j=k[n][b] print(j,end="") oo=oo+j print(n+1,":",b+1,file=o) print(end="\n\n") print("Binary => ",ss,end="\n\n") f.close() o.close()
akarol/cfme_tests
cfme/containers/image.py
Python
gpl-2.0
11,425
0.003501
# -*- coding: utf-8 -*- import attr from cached_property import cached_property from navmazing import NavigateToSibling, NavigateToAttribute from wrapanapi.containers.image import Image as ApiImage from cfme.common import (WidgetasticTaggable, PolicyProfileAssignable, TagPageView) from cfme.c...
ger from cfme.configure import tasks from cfme.modeling.base import BaseCollection, BaseEntity from cfme.utils.wait import
wait_for, TimedOutError from widgetastic_manageiq import SummaryTable, BaseEntitiesView from widgetastic.widget import View from cfme.utils.providers import get_crud_by_name class ImageAllView(ContainerObjectAllBaseView): SUMMARY_TEXT = "Container Images" # ProviderEntity has its own fields, image view shoul...
OpenSoccerManager/opensoccermanager
structures/filters.py
Python
gpl-3.0
2,796
0
#!/usr/bin/env python3 # This file is part of OpenSoccerManager. # # OpenSoccerManager 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 ver...
urrently applied. ''' return self.options != self.de
faults class Club: defaults = (("league", 0),) defaults = collections.OrderedDict(defaults) def __init__(self): self.options = {} self.reset_filter() def reset_filter(self): ''' Restore default filtering attributes. ''' self.options = collections.Orde...
mushorg/conpot
conpot/core/attack_session.py
Python
gpl-2.0
2,606
0.000384
# Copyright (C) 2014 Johnny Vestergaard <jkv@unixcluster.dk> # # 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 ...
le elapse_ms in self.data: elapse_ms += 1 self.data[elapse_ms] = event_data # TODO:
We should only log the session when it is finished self.log_queue.put(self._dump_data(event_data)) def dump(self): return self._dump_data(self.data) def set_ended(self): self._ended = True
iEngage/python-sdk
test/test_interaction_response.py
Python
apache-2.0
971
0.00309
# coding: utf-8 """ Stakeholder engagement API This API enables Intelligent Engagement for your Business. iEngage is a platform that combines process, augmented intelligence and rewards to help you intelligently engage customers. OpenAPI spec version: 1.0 Generated by: https://github.com/swagger...
setUp(self): pass def tearDown(self): pass def testInteracti
onResponse(self): """ Test InteractionResponse """ model = iengage_client.models.interaction_response.InteractionResponse() if __name__ == '__main__': unittest.main()
zephyrplugins/zephyr
zephyr.plugin.jython/jython2.5.2rc3/Lib/compiler/syntax.py
Python
epl-1.0
1,444
0.00554
"""Check for errs in the AST. The Python parser does not catch all syntax errors. Others, like assignments with invalid targets, are caught in the code generation phase. The compiler package catches some errors in the transformer module. But it seems clearer to write checkers that use the AST to detect errors. """ ...
None, then print messages for each error rather than raising a SyntaxError for the first. """ self.multi = multi self.errors = 0 def error(self, node, msg): self.
errors = self.errors + 1 if self.multi is not None: print "%s:%s: %s" % (node.filename, node.lineno, msg) else: raise SyntaxError, "%s (%s:%s)" % (msg, node.filename, node.lineno) def visitAssign(self, node): # the transformer module handles many of these pas...
Small-Star/PDV3
app/graph_weightlifting.py
Python
gpl-3.0
15,504
0.021478
import pandas as pd import datetime import math from bokeh.models import HoverTool, FactorRange, Plot, LinearAxis, Grid, Range1d, Slider, PanTool, WheelZoomTool, ResetTool, SaveTool, CustomJS from bokeh.models.glyphs import Line from bokeh.models.markers import X from bokeh.plotting import figure from bokeh.charts imp...
tv.append(d_tv[c - 1]) else: d_tv.append(d_w['deadlift_total_vol'][c]) if math.isnan(d_w['bench_total_vol'][c]): b_tv.append(b_tv[c - 1]) else: b_tv.append(d_w['bench_total_vol'][c]) if math.isnan(d_w['ohp_total_vol'][c]): o_tv.append(o_tv[c - 1]) else: o_tv.append(d_w['ohp_total_vol'][c]) #P...
e='s_m') cds_max.add(d_m, name='d_m') cds_max.add(b_m, name='b_m') cds_max.add(o_m, name='o_m') cds_w.add(d['date'], name='date') cds_w.add(s_mvps, name='s_mvps') cds_w.add(d_mvps, name='d_mvps') cds_w.add(b_mvps, name='b_mvps') cds_w.add(o_mvps, name='o_mvps') cds_w.add(s_tv, name='s_tv') cds_w.add(d_tv, n...
byteweaver/django-eca-catalogue
eca_catalogue/product/abstract_models.py
Python
bsd-3-clause
579
0.003454
from django.db import models from django.utils.translation import ugettext_lazy as _ class AbstractProduct(models.Model): item_number = models.CharField(_("Item number"), max_length=255, unique=True) name = models.CharField(_("Name"), max_length=128) description = models.TextField(_("Description"), blank=...
e, null=True) class Meta: abstract = True verbose_name = _("P
roduct") verbose_name_plural = _("Products") ordering = ['item_number'] def __unicode__(self): return "%s (%s)" % (self.name, self.item_number)
slundberg/shap
shap/_explanation.py
Python
mit
32,276
0.004462
import pandas as pd import numpy as np import scipy as sp import sys import warnings import copy import operator import sklearn from slicer import Slicer, Alias, Obj # from ._order import Order from .utils._general import OpChain # slicer confuses pylint... # pylint: disable=no-member op_chain_root = OpChain("shap....
self._s.output_indexes @property def feature_names(self): """ Pass-through from the underlying slicer object. """ return self._s.feature_names @feature_names.setter def feature_names(self, new_feature_names): self._s.feature_names = new
_feature_names @property def lower_bounds(self): """ Pass-through from the underlying slicer object. """ return self._s.lower_bounds @property def upper_bounds(self): """ Pass-through from the underlying slicer object. """ return self._s.upper_bounds ...
nigelb/SerialGrabber
examples/ThingSpeak/ThingSpeakTransformer.py
Python
gpl-2.0
2,101
0.000952
#!/usr/bin/env python # SerialGrabber reads data from a serial port and processes it with the # configured processor. # Copyright (C) 2012 NigelB # # 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 Foundatio...
rm api_key = "GT14ED5QGNLE2E8N" field_map = { "1": "field8", "2": "field7", "3": "field6", "4": "field5", "5": "field4", "6": "field3", "7": "field2", "8": "field1", } # A Transform is used by a TransformProcessor to transform the data received # from the reader into a form that can ...
igured processor. class ThingSpeakTransformer(Transform): def transform(self, process_entry): # Retrieve the transaction's data from the process_entry payload = process_entry[constants.data][constants.payload] transformed_data = {"api_key": api_key} # Process the retrieved data i...
frictionlessdata/datapackage-pipelines
datapackage_pipelines/generators/schedules.py
Python
mit
171
0
SCHEDUL
E_NONE = None SCHEDULE_HOURLY = '0 * * * *' SCHEDULE_DAILY = '0 0 * * *' SCHEDULE_WEEKLY = '0 0 * * 0' SCHEDULE_MONTHLY = '0 0 1 * *' SCHEDULE_YEARLY = '0 0 1 1
*'
webtrike/compliance-checker
compliance_checker/cf/appendix_f.py
Python
apache-2.0
2,157
0.000464
#!/usr/bin/env python ''' Appendix F. Grid Mappings --- Each recognized grid mapping is described in one of the sections below. Each section contains: the valid name that is used with the grid_mapping_name attribute; a list of the specific attributes that may be used to assign values to the mapping's parameters; the st...
ences to the mapping's definition or other information that may help in using the mapping. Since the attributes used to set a mapping's parameters may be shared among several mappings, their definitions are contained in a table in the final section. The attributes which describe the ellipsoid and prime meridian may be ...
ve used the FGDC "Content Standard for Digital Geospatial Metadata" [FGDC] as a guide in choosing the values for grid_mapping_name and the attribute names for the parameters describing map projections. ''' grid_mapping_names = [ 'albers_conical_equal_area', 'azimuthal_equidistant', 'lambert_az...
akeym/cyder
cyder/cydns/nameserver/forms.py
Python
bsd-3-clause
4,749
0
from django import forms from django.core.exceptions import ValidationError from cyder.models import Ctnr from cyder.cydns.address_record.models import AddressRecord from cyder.cydns.view.models import View from cyder.cydns.forms import DNSForm from cyder.cydns.nameserver.models import Nameserver from cyder.cydhcp.int...
ue = AddressRecord.objects.filter( label=self.instance.glue.label, domain=self.instance.glue.domain) intr_glue = StaticInterface.objects.filter( label=self.instance.glue.label, domain=self.instance.glue.domain) glue_choices = [] for glue in addr_g...
lue in intr_glue: glue_choices.append(("intr_{0}".format(glue.pk), str(glue))) if isinstance(self.instance.glue, AddressRecord): initial = "addr_{0}".format(self.instance.glue.pk) elif isinstance(self.instance.glue, StaticInterface): initial = "intr_{0}".format(self....
kubeflow/pipelines
samples/core/sidecar/sidecar_test.py
Python
apache-2.0
853
0
# Copyright 2021 The Kubeflow 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...
ions and # limitations under the License. import kfp.deprecated as kfp from kfp.samples.test.utils import TestCase, relative_path, run_pipeline_func run_pipeline_func([ TestCase( pipeline_file=relative_path(__file__, 's
idecar.py'), mode=kfp.dsl.PipelineExecutionMode.V1_LEGACY, ), ])
sho-87/python-machine-learning
Logistic Regression/xor_logistic.py
Python
mit
2,256
0.005319
# XOR gate. No hidden layer, basic
logistic regression # Demonstration - can't learn nonlinearity. Hidden layer is required import numpy as np import theano import theano.tensor as T import matplotlib.pyplot as plt # Set inputs and correct output values inputs = [[0,0], [1,1], [0,1], [1,0]] outputs = [0, 0, 1, 1] # Set training parameters alpha = 0.1...
theano.shared(value=1.0, name='b') # Set random seed rng = np.random.RandomState(2345) # Initialize random weights w_values = np.asarray( rng.uniform(low=-1, high=1, size=(2, 1)), dtype=theano.config.floatX) # Force type to 32bit float for GPU w = theano.shared(value=w_values, name='w', borrow=True) # Thean...
ruchee/vimrc
vimfiles/bundle/vim-python/submodules/pylint/pylint/extensions/docparams.py
Python
mit
23,695
0.000886
# Copyright (c) 2014-2015 Bruno Daniel <bruno.daniel@blue-yonder.com> # Copyright (c) 2015-2020 Claudiu Popa <pcmanticore@gmail.com> # Copyright (c) 2016-2019 Ashley Whetter <ashley@awhetter.co.uk> # Copyright (c) 2016 Glenn Matthews <glenn@e-dad.net> # Copyright (c) 2016 Glenn Matthews <glmatthe@cisco.com> # Copyright...
re import astroid from pylint.checkers import BaseChecker from pylint.checkers import utils as checker_utils from pylint.extensions import _check_docs_utils as utils from pylint.interfaces import IAstroidChecker from pylint.utils import get_global_option class DocstringParameterChecker(BaseChecker): """Checker...
that all function, method and constructor parameters are mentioned in the params and types part of the docstring. Constructor parameters can be documented in either the class docstring or ``__init__`` docstring, but not both. * Check that there are no naming inconsistencies between the signature ...
camillescott/boink
benchmarks/benchmark-dbg-insert.py
Python
mit
1,086
0
import argparse from goetia import libgoetia from goetia.dbg import dBG from goetia.hashing import StrandAware, FwdLemireShifter, CanLemireShifter from goetia.parsing import iter_fastx_inputs, get_fastx_args from goetia.storage import * from goetia.timer import measure_time parser = argpars
e.ArgumentParser() group = get_fastx_args(parser) group.add_argument('-i', dest='inputs', nargs='+', required=True) args = parser.parse_args() for storage_t in [SparseppSe
tStorage, PHMapStorage, BitStorage, BTreeStorage]: for hasher_t in [FwdLemireShifter, CanLemireShifter]: hasher = hasher_t(31) if storage_t is BitStorage: storage = storage_t.build(int(1e9), 4) else: storage = storage_t.build() graph = dBG[storage_t, hasher_t]...
boakley/robotframework-workbench
rwb/widgets/textfinder.py
Python
apache-2.0
8,510
0.003878
'''TextFinder - a widget for searching through a text widget ''' import Tkinter as tk import ttk class TextFinder(ttk.Frame): def __init__(self, parent, text_widget): self.text = text_widget ttk.Frame.__init__(self, parent) validatecommand = (self.register(self._on_validate), "%P") ...
e: range1 = (start, "1.0") if self.text.compar
e(start, "<", "end"): range2 = ("end", start) else: range2 = () # tkinter's text widget doesn't support the -all option for searching, # so we'll have to directly interface with the tcl subsystem command = [self.text._w, "search", "-nocase", "-all"] ...
josephkirk/PipelineTools
main/qtui.py
Python
bsd-2-clause
2,163
0.004161
import maya.cmds as cm import maya.mel as mm import pymel.core as pm try: from PySide2 import QtWidgets, QtCore, QtGui except ImportError: from PySide import QtCore, QtGui QtWidgets = QtGui # Get Maya Main Window mayaMainWindow = pm.ui.Window('MayaWindow').asQtObject() # Wrapper SIGNAL = QtCore.Signal # UI...
self.mainCtner.setLayout(self.mainLayout) self.setCentralWidget(self.mainCtner) def rigUtilLayout(self): self.rigUtilUI = [] self.button class PipelineTool(QtWidgets.QMainWindow): def __init__(self, parent=None): super(PipelineTool, self).__init__() try: pm.deleteU...
'Parent is not of type QMainWindow' self.setParent(parent) else: self.setParent(mayaMainWindow) self.setWindowFlags(QtCore.Qt.Window) self.setWindowTitle('Pipeline Tools') self.setObjectName('PipelineToolWindow') self.setMinimumSize(250,100) ...
bancek/egradebook
src/lib/compressor/filters/csstidy.py
Python
gpl-3.0
870
0.003448
from subprocess import Popen, PIPE import tempfile import warnings from compressor.conf import settings from compressor.filters import FilterBase warnings.simplefilter('ignore', RuntimeWarning) class CSSTidyFilter(FilterBase): def output(self, **kwargs): tmp_file = tempfile.NamedTemporaryFile(mode='w+b'...
PIPE).communicate() filte
red_css = output_file.read() output_file.close() tmp_file.close() if self.verbose: print command_output return filtered_css
rh-s/heat
heat/api/openstack/v1/resources.py
Python
apache-2.0
5,715
0.000175
# # 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 # ...
as e: raise exc.HTTPBadRequest(six.text_type(e))
else: return default @util.identified_stack def index(self, req, identity): """ Lists information for all resources """ nested_depth = self._extract_to_param(req, rpc_api.PARAM_NESTED_DEPTH, ...
leppa/home-assistant
homeassistant/components/heos/__init__.py
Python
apache-2.0
12,267
0.001141
"""Denon HEOS Media Player.""" import asyncio from datetime import timedelta import logging from typing import Dict from pyheos import Heos, HeosError, const as heos_const import voluptuous as vol from homeassistant.components.media_player.const import DOMAIN as MEDIA_PLAYER_DOMAIN from homeassistant.config_entries i...
_event(self, event): """Handle connection event.""" if event == heos_const.EVENT_CONNECTED: try: # Retrieve latest players and refresh status data = await self.controller.load_players() self.update_ids(data[heos_const.DATA_MAPPED_IDS]) ...
eosError as ex: _LOGGER.error("Unable to refresh players: %s", ex) # Update players self._hass.helpers.dispatcher.async_dispatcher_send(SIGNAL_HEOS_UPDATED) def update_ids(self, mapped_ids: Dict[int, int]): """Update the IDs in the device and entity registry.""" # ma...
alimon/reproducible-builds
mainapp/models.py
Python
mit
1,040
0.005769
from django.db import models class Build(models.Model): build_id = models.CharField(max_length=64, primary_key=True) build_date = models.DateTimeField() target_machine = models.CharField(max_length=64) class BuildDetails(models.Model): build = models.ForeignKey(Build, on_delete=models.CASCADE) rep...
T_TYPE_CHOICES = ( (ArtifactType.TARGET, 'Target artifact'), (ArtifactType.NATIVE, 'Native artifact') ) build = models.ForeignKey(Build, on_delete=models.CASCADE) artifact_type = models.CharField(max_length=16, choices=ART
IFACT_TYPE_CHOICES) rb_status = models.CharField(max_length=1) class SstateTask(models.Model): sstate = models.ForeignKey(Sstate, on_delete=models.CASCADE) file_name = models.CharField(max_length=128) diff = models.BinaryField()
markvl/acrylamid
acrylamid/filters/typography.py
Python
bsd-2-clause
12,390
0.004197
# -*- encoding: utf-8 -*- # # License: New BSD Style # # [typography.py][1] is a set of filters enhancing written text output. As the # name says, it adds specific typography things documented in the definitions # itself and [smartypants][2]. # # The typography.py filter comes with two options: ``mode`` and ``default``...
"caps">D.O.T.</span> like so.' All caps with with apostrophes in them shouldn't break. Only handles dump apostrophes though. >>> caps("J
IMMY'S") u'<span class="caps">JIMMY\\'S</span>' >>> caps("<i>D.O.T.</i>HE34T<b>RFID</b>") u'<i><span class="caps">D.O.T.</span></i><span class="caps">HE34T</span><b><span class="caps">RFID</span></b>' """ tokens = smartypants._tokenize(text) result = [] in_skipped_tag = False cap_find...
devendermishrajio/nova_test_latest
nova/tests/unit/compute/test_tracker.py
Python
apache-2.0
56,271
0.000373
# 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 # d...
': 256, 'vcpus': 2, 'root_gb': 5, 'ephemeral_gb': 0, 'swap': 0, 'rxtx_factor': 0, 'vcpu_weight': 1, 'extra_specs': {}, }, } _INSTANCE_TYPE_OBJ_FIXTURES = { 1: objects.Flavor(id=1, flavorid='fakeid-1', name='fake1.small', memory_mb=1...
id=2, flavorid='fakeid-2', name='fake1.medium', memory_mb=256, vcpus=2, root_gb=5, ephemeral_gb=0, swap=0, rxtx_factor=0, vcpu_weight=1, extra_specs={}), } _2MB = 2 * units.Mi / units.Ki _INSTANCE_NUMA_TOPOLOGIES = { '2mb': objects.InstanceNUMATop...
crossbario/autobahn-python
autobahn/wamp/test/test_wamp_scram.py
Python
mit
3,040
0.001316
############################################################################### # # The MIT License (MIT) # # Copyright (c) Crossbar.io Technologies GmbH # # 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 ...
TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN #
THE SOFTWARE. # ############################################################################### import os import txaio from binascii import a2b_hex if os.environ.get('USE_TWISTED', False): txaio.use_twisted() from twisted.trial import unittest elif os.environ.get('USE_ASYNCIO', False): txaio.use_asyncio()...
keelanfh/electionary
analysis/city-mentions.py
Python
mit
1,375
0.001455
import json import os from commonfunctions import commonfunctions as cf dir = cf.working_directory transcripts = [] for x in os.listdir(dir): with open(os.path.join(dir, x)) as f: transcripts.append(json.load(f)) with open('worldcitiesout.json', 'r') as f: city_dicts = json.load(f) city_dicts = [x...
if index > 0: if index < 90: from_index = 0 else: from_index = index - 100 if len(text['text']) < index + 90: to_index = len(text['text']) else: to_index = index + ...
'debate': {'description': description, 'date': date, 'context': text['text'][from_index:to_index]}}) print result results.append(result) with open('city-mentions.json', 'w') as f: json.dump(results, f)
aslab/rct
mrt/src/tum_simulator_ws/build/tum_simulator-master/cvg_sim_msgs/catkin_generated/pkg.installspace.context.pc.py
Python
gpl-3.0
485
0.002062
# generated from catkin/cmake/template/pkg.context.pc.in CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_INCLUDE_DIR
S = "/home/jorge/tum_simulator_ws/install/include".s
plit(';') if "/home/jorge/tum_simulator_ws/install/include" != "" else [] PROJECT_CATKIN_DEPENDS = "message_runtime".replace(';', ' ') PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else [] PROJECT_NAME = "cvg_sim_msgs" PROJECT_SPACE_DIR = "/home/jorge/tum_simulator_ws/install" PROJECT_VERSION = "0.0.0"
pade/sprinkler
src/database.py
Python
gpl-3.0
1,254
0.000797
# -*- coding: UTF-8 -*- from jsonvalidate import Validate import json import os class Database(): """ program database interface""" def __init__(self, dbfile): """ @param dbfile: full path of database file """ self.dbfile = dbfile self.iscached = False self.va...
data): self.iscached = False with open(self.dbfile, 'w') as fd: self.data = self.validator.validate_json(data) fd.write(json.dumps(data)) self.iscached = True def update_channels(self, ch): prog = self.read() ch = self.validator.validate_channel(...
prog["channels"][i] = ch break i +=1 self.write(prog) def file_exists(self): return os.path.isfile(self.dbfile)
GenericError/Project-Shell
ls.py
Python
gpl-3.0
961
0.004162
""" Module that runs the ls command """ import os import shutil import textwrap MAN_DOC = """ls - list files and directories Usage: ls [directory] Executing the command with no directory argument will list the files and folders in the current working directory. Executing the command with a directory argument will li...
os.listdir(os.path.abspath(dir_to_scan)) terminal_width = int(shutil.get_terminal_size()[0]) constructed_string = "" for thing in file_dir_list: constructed_string += thing constructed_string += ' \t\t\t' done_first_thing = True lines = textwrap.fill(text=c
onstructed_string, width=terminal_width) print(lines) return return_code
viger/docker
proxy/proxy/code/default/python27/1.0/lib/noarch/OpenSSL/crypto.py
Python
mit
90,546
0.000022
import datetime from base64 import b16encode from functools import partial from operator import __eq__, __ne__, __lt__, __le__, __gt__, __ge__ from warnings import warn as _warn from six import ( integer_types as _integer_types, text_type as _text_type, PY3 as _PY3) from OpenSSL._util import ( ffi as...
se to put into the BIO so that they can be read out. """ if buffer is None: bio = _lib.BIO_new(_lib.BIO_s_mem()) free = _lib.BIO_free else: data = _ffi.new("char[]", buffer)
bio = _lib.BIO_new_mem_buf(data, len(buffer)) # Keep the memory alive as long as the bio is alive! def free(bio, ref=data): return _lib.BIO_free(bio) if bio == _ffi.NULL: # TODO: This is untested. _raise_current_error() bio = _ffi.gc(bio, free) return bio d...
cobbler/cobbler
tests/items/profile_test.py
Python
gpl-2.0
8,089
0
import pytest from cobbler import enums from cobbler.items.distro import Distro from cobbler.items.profile import Profile from tests.conftest import does_not_raise def test_object_creation(cobbler_api): # Arrange # Act profile = Profile(cobbler_api) # Arrange assert isinstance(profile, Profile)...
value, str): assert profile.virt_disk_driver.value == value else: assert profile.virt_disk_driver == value @pytest.mark.parametrize("value,expected_exception", [ ("", pytest.raises(ValueError)), (0, does_not_raise()), (0.0, pytest.rai
ses(TypeError)) ]) def test_virt_ram(cobbler_api, value, expected_exception): # Arrange profile = Profile(cobbler_api) # Act with expected_exception: profile.virt_ram = value # Assert assert profile.virt_ram == int(value) @pytest.mark.parametrize("value,expected_exception", [...
konradxyz/cloudify-manager
plugins/plugin-installer/plugin_installer/tests/mock-with-dependencies-plugin/setup.py
Python
apache-2.0
1,216
0
# ************************************************************************** # * Copyright (c) 2013 GigaSpaces Technologies Ltd. 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 t...
setuptools import setup setup( name='mock-with-dependencies-plugin', version='3.2', author='elip',
author_email='elip@gigaspaces.com', packages=['mock_with_dependencies_for_test'], license='LICENSE', description='Mock plugin for test', install_requires=[ # Just some dependency. # we assert for this name in the tests code. 'simplejson' ] )
mffiedler/svt
reliability/tasks/utils/LoadApp.py
Python
apache-2.0
1,646
0.003645
from .SlackIntegration import slackIntegration import logging from aiohttp import ClientSession import asyncio from time import perf_counter class LoadApp(): def __init__(self): self.logger = logging.getLogger('reliability') self.app_visit_succeeded = 0
self.app_visit_failed = 0 self.tasks = [] async def get(self, url): # To simulate differnt users accessing same app, do not reuse session async with ClientSession() as session: async with sessi
on.get(url) as response: code = response.status result = await response.text() self.logger.info(f"{str(code)} : load: {url}") #print (f"{str(code)} : load: {url}") if code == 200: self.app_visit_succeeded += 1 ...
gtaylor/python-colormath
colormath/density.py
Python
bsd-3-clause
2,458
0
# -*- coding: utf-8 -*- """ Formulas for density calculation. """ from math import log10 from colormath.density_standards import ( ANSI_STATUS_T_BLUE, ANSI_STATUS_T_GREEN, ANSI_STATUS_T_RED, VISUAL_DENSITY_THRESH, ISO_VISUAL, ) def ansi_density(color, density_standard): """ Calculates den...
_density(color, ISO_VISUAL) elif blue_density > green_density and blue_density > red_density: return blue_density elif green_density
> blue_density and green_density > red_density: return green_density else: return red_density
bigmlcom/bigmler
check_files/reify_anomaly_score.py
Python
apache-2.0
909
0.019802
from bigml.api import BigML api = BigML() source1_file = "iris.csv" args = \ {'fields': {'000000': {'name': 'sepal length', 'optype': 'numeric'}, '000001': {'name': 'sepal width', 'optype': 'numeric'}, '000002': {'name': 'petal length', 'op
type': 'numeric'}, '000003': {'name': 'petal width', 'optype': 'numeric'}, '000004': {'name': 'species', 'optype': 'categorical', 'term_analysis': {'enabled': True}}}, } source2 = api.create_source(source1_file, args) api.ok(source2) args = \ {'objective_field': {'id': '000004'}, } dataset1 = api.create_dataset(source2...
y1 = api.create_anomaly(dataset1, args) api.ok(anomaly1) args = \ {'input_data': {'petal length': 0.5, 'petal width': 0.5, 'sepal length': 1, 'sepal width': 1, 'species': 'Iris-setosa'}, } anomalyscore1 = api.create_anomalyscore(anomaly1, args) api.ok(anomalyscore1)
jrichte43/ProjectEuler
Problem-0004/solutions.py
Python
gpl-3.0
774
0.006468
__problem_title__ = "Largest palindrome product" __problem_url___ = "https://projecteuler.net/problem=4" __problem_description__ = "A palindromic number reads the same both ways. The largest palindrome " \ "made from the product of two 2-digit numbers is 9009 = 91 × 99. F
ind " \ "the largest palindrome made from the product of two 3-digit numbers." import timeit class Solution(): @staticmethod def solution1(): pass @staticmethod def time_solutions(): setup = 'from __main__ import Solution' print('Solution 1:', timei...
solution1()) s.time_solutions()
eiiches/pigrate
pigrate/internal.py
Python
mit
2,208
0.00317
# coding: utf-8 import os from
datetime import datetime from pigrate import PigrateError class Pigration(object): def __init__(self, id, name, script): self.id = id self.name = name self.script = script def __repr__(self): return '{0}-{1}.pigrate.py'.format(self.id, self.name) class PigrationStatus(object...
id) def load_config_module(basedir): import imp from uuid import uuid4 config_path = os.path.join(basedir, 'config.py') if not os.path.isfile(config_path): raise PigrateError("directory '{0}' does not exists or is not a valid pigrate directory".format(basedir)) return imp.load_source(uuid4...
kreopt/aioweb
aioweb/conf/__init__.py
Python
mit
4,182
0.001674
""" Settings and configuration for Django. Values will be read from the module specified by the DJANGO_SETTINGS_MODULE environment variable, and then from django.conf.global_settings; see the global settings file for a list of all possible variables. """ import importlib import os import time from aiohttp.log import...
deleted.add(name) if hasattr(self, name): super(UserSettingsHolder, self).__delattr__(name) def __dir__(self): return sorted( s for s in list(self.__dict__) + dir(self.default_settings) if s not in self._deleted ) def is_overridden(s
elf, setting): deleted = (setting in self._deleted) set_locally = (setting in self.__dict__) set_on_default = getattr(self.default_settings, 'is_overridden', lambda s: False)(setting) return (deleted or set_locally or set_on_default) def __repr__(self): return '<%(cls)s>' % ...
owlabs/incubator-airflow
airflow/task/task_runner/base_task_runner.py
Python
apache-2.0
6,779
0.000738
# -*- 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 #...
task instance. :type local_task_job: airflow.jobs.LocalTaskJob """ def __init__(self, local_task_job): # Pass task instance context into log handlers to setup the logger. super(BaseTaskRunner, self).__init__(local_task_job.task_instance) self._task_instance = local_task_job.task_ins...
er else: try: self.run_as_user = conf.get('core', 'default_impersonation') except conf.AirflowConfigException: self.run_as_user = None # Add sudo commands to change user if we need to. Needed to handle SubDagOperator # case using a Sequent...
Valka7a/python-playground
sqlite3/tutorials/having-clause.py
Python
mit
3,568
0.001121
""" The HAVING clause enables you to specify conditions that filter which group results appear in the final results. The WHERE clause places conditions on the selected columns, whereas the HAVING clause places condiitons on groups created by the GROUP BY clause. """ # Syntax: """ The following is the position of the ...
44 Norway 5000.0 10 James 45 Texas 5000.0 ________________________________________________________________________________ Following is the example, which would display record for which name count is less than 2: ________________
________________________________________________________________ sqlite> SELECT * FROM COMPANY GROUP BY name HAVING count(name) < 2; ________________________________________________________________________________ This would produce the following result: ________________________________________________________________...
unitips/unitipsQuestions
src/urls.py
Python
mit
989
0.001011
"""src URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based ...
s 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from dj...
(r'^$', TemplateView.as_view(template_name='home.html'), name='homepage'), url(r'^quiz/', include(quiz_urls, namespace='quiz')), url(r'^admin/', admin.site.urls) ]
jjas0nn/solvem
tensorflow/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/dataframe/transform.py
Python
mit
10,524
0.005226
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
ance(x, Series): return [x] elif isinstance(x, collections.Iterable): for i, y in enumerate(x): if not isinstance(y, Series): raise TypeError( "Expected a tuple or list of Series; entry %s has type %s." % (i, type(y).__name__)) return list(x) raise TypeError("Expect...
eries; got %s" % type(x).__name__) def _make_tuple_of_string(x): """Converts `x` into a list of `str` if possible. Args: x: a `str`, a list of `str`, a tuple of `str`, or `None`. Returns: `x` if it is a tuple of str, `tuple(x)` if it is a list of str, `(x)` if `x` is a `str`, `()...
melqkiades/yelp
source/python/topicmodeling/external/lda_testing.py
Python
lgpl-2.1
2,284
0.001751
__author__ = 'f
pena' import numpy as np import lda import lda.datasets def run(): # document-term matrix X = lda.datasets.load_reuters() print("type(X): {}".format(type(X))) print("shape: {}\n".format(X.shape)) # the vocab vocab = lda.datasets.load_reuters_vocab() print("type(vocab): {}".format(type(v...
t(len(vocab))) # titles for each story titles = lda.datasets.load_reuters_titles() print("type(titles): {}".format(type(titles))) print("len(titles): {}\n".format(len(titles))) doc_id = 0 word_id = 3117 print("doc id: {} word id: {}".format(doc_id, word_id)) print("-- count: {}".forma...
saullocastro/mapy
mapy/model/elements/__init__.py
Python
bsd-2-clause
3,526
0.013613
import numpy as np import alg3dpy class Elements(object): __slots__ = [ 'id', 'model', 'xvec', 'yvec', 'zvec', 'mask', 'tmp', \ 'grids', 'cg', 'pobj', 'entryclass', 'card', 'panel' ] def __init__(self): self.grids = [] self.mask = False self.panel = None def reb...
): for j in range(9): data[ 18*i + j ] = tmp[j] row = scipy.array(\ [i for i in range(dim) for j in range( 3 )], dtype='int8') col = scipy.array(\ [j + int(i/3)*3 for i in range(dim) for j in range( 3 )], dtype='int8') #self.R2el c...
data, (row, col)), shape = (dim,dim), dtype='float32') self.R2global = self.R2el.transpose() def build_k(self): import scipy.sparse as ss self.kelem = ss.coo_matrix( self.kelem ) R = self.R2el.tocsc() Rinv = self.R2global.tocsc() kel...
bgroff/kala-app
django_kala/projects/views/projects/tests/test_new_project.py
Python
mit
2,542
0.00118
import pytest from django.contrib.auth import get_user_model from django.urls import reverse from rest_frame
work.status import HTTP_200_OK, HTTP_302_FOUND, HTTP_403_FORBIDDEN from organizations.views.tests import setup, user_permissions_test_create, login from projects.tes
ts.factories import ProjectFactory User = get_user_model() @pytest.mark.django_db def test_user_permissions_for_new_project(): user, organization, client = setup() user_permissions_test_create( view='projects:new_project', client=client, user=user, organization=organization, ...
davidh-ssec/polar2grid
polar2grid/compare.py
Python
gpl-3.0
22,388
0.002546
#!/usr/bin/env python3 # encoding: utf-8 # Copyright (C) 2014-2021 Space Science and Engineering Center (SSEC), # University of Wisconsin-Madison. # # 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 Softw...
the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this pr...
software package. Polar2grid takes # satellite observation data, remaps it, and writes it to a file format for # input into another program. # Documentation: http://www.ssec.wisc.edu/software/polar2grid/ """Script for comparing writer output.""" from __future__ import annotations import logging import os import sys ...
uwcirg/true_nth_usa_portal
portal/migrations/versions/9c6788e6db2f_.py
Python
bsd-3-clause
1,271
0
"""promote __system__ user to admin Revision ID: 9c6788e6db2f Revises: c242e22f5a47 Create Date: 2019-08-01 17:28:56.859235 """ import random from werkzeug.security import generate_password_hash from portal.database import db from portal.models.user import User from portal.models.role import Role, ROLE # revision i...
admin_only = Role.query.filter(Role.name == ROLE.ADMIN.value).all() sys_user.update_roles(role_list=admin_only, acting_user=sys_user) # CYA - give the system account a decent, random password password = (''.join([random.choice(list( '123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCV...
i = pw_hash.find('$') sys_user.password = pw_hash[i:] db.session.commit() def downgrade(): # ### commands auto generated by Alembic - please adjust! ### pass # ### end Alembic commands ###
pattu777/LearningDjango
apps/apps/settings.py
Python
mit
3,307
0.00121
""" Django settings for apps project. Generated by 'django-admin startproject' using Django 1.9.7. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os from...
BUG = DEBUG ALLOWED_HOSTS = [ 'learningdjango.in', 'localhost', '127.0.0.1' ] #
Application definition INSTALLED_APPS = [ 'home.apps.HomeConfig', 'polls.apps.PollsConfig', 'blog.apps.BlogConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MI...
kermitfr/kermit-webui
src/webui/plugins/urls.py
Python
gpl-3.0
517
0.009671
''' Created on Nov 7, 2012 @author: mmornati ''' from django.conf.urls.defaults import patterns, include import logging from webui.plugins import utils logger = logging.getLogger(__name__) urlpatterns = patterns('', ) installed_plugins = utils.installed_plugins_list() for plugin in installed_plugins: try: ...
include("webui.plugins.%s.urls" %
plugin)), ) except: logger.debug ("Plugin %s does not provides urls" % plugin)
setminami/TokageUtil
util/y2butil.py
Python
apache-2.0
15,689
0.00524
#!/usr/bin/env python # -*- coding: utf-8 -*- import http.client import httplib2 import os, random, sys, time from threading import Lock from . import fileutil from apiclient.discovery import build from apiclient.errors import HttpError from apiclient.http import MediaFileUpload from oauth2client.client import flow_f...
Storage from oauth2client.tools import argparser, run_flow # Explicitly tell the underlying HTTP transport library not to retry, since # we are handling retry logic ourselves. httplib2.RETRIES = 1 # Maximum number of times to retry before giving up. MAX_RETRIES = 10 # Always retry when these exceptions are raised....
uest, http.client.CannotSendHeader, http.client.ResponseNotReady, http.client.BadStatusLine) # Always retry when an apiclient.errors.HttpError with one of these status # codes is raised. RETRIABLE_STATUS_CODES = [500, 502, 503, 504] # The CLIENT_SECRETS_FILE variable specifies the name of a file that contains # t...
devincachu/devincachu-2014
devincachu/urls.py
Python
bsd-2-clause
2,555
0.001174
# Copyright 2014 Dev in Cachu authors. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. from django.conf import settings from django.conf.urls import include, patterns, url from django.views.decorators import csrf from django.views.generic impor...
Certificado.as_view(), name="busca_certifi
cado"), url(r"^certificado/(?P<slug>[0-9a-f]+)/$", iviews.Certificado.as_view(), name="certificado"), url(r"^sobre/$", base.TemplateView.as_view( template_name="sobre.html", ), ...
vileopratama/vitech
src/openerp/tools/float_utils.py
Python
mit
9,416
0.00531
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import math def _float_check_precision(precision_digits=None, precision_rounding=None): assert (precision_digits is not None or precision_rounding is not None) and \ not (precision_digits and precision_round...
desired precision (for example, 0.01 for a 2-digit precision). :param rounding_method: the rounding method used: 'HALF-UP' or 'UP', the first one rounding up to the closest number with the rule that number>=0.5 is rounded up to 1, and the latest one always rounding up. ...
precision_rounding=precision_rounding) if rounding_factor == 0 or value == 0: return 0.0 # NORMALIZE - ROUND - DENORMALIZE # In order to easily support rounding to arbitrary 'steps' (e.g. coin values), # we normalize the value before rounding it as an integer, and de-normalize # af...
leo-naeka/django-rest-framework-json-api
example/tests/integration/test_meta.py
Python
bsd-2-clause
766
0
from datetime import datetime from django.core.urlresolvers import reverse
import pytest from example.tests.utils import dump_json, redump_json pytestmark = pytest.mark.django_db def test_top_level_meta(blog, client): expected = { "data": { "type": "blogs", "id": "1", "attributes": { "name": blog.name }, ...
} response = client.get(reverse("blog-detail", kwargs={'pk': blog.pk})) content_dump = redump_json(response.content) expected_dump = dump_json(expected) assert content_dump == expected_dump
EliasLi/JunctionHackathon
public/3odel_old/3d/tools/build.py
Python
mit
2,656
0.048946
import os import sys import shutil import re currentPath = os.path.dirname (os.path.abspath (__file__)) os.chdir (currentPath) def PrintInfo (message): print ('Info: ' + message) def PrintError (error): print ('Error: ' + error) def ReplaceInFile (filePath, source, dest): file = open (filePath, 'rb') content = ...
ntent.replace (source, dest) file = open (filePath, 'wb') file.write (content); file.close () def BuildWebSite (rootFolder, resultFolder): targetFolder = os.path.join (resultFolder, 'website') shutil.copytree (os.path.join (rootFolder, 'website'), targetFolder) shutil.copytree (os.path.join (rootFolder, 'jsm
odeler'), os.path.join (targetFolder, 'jsmodeler')) indexFilePath = os.path.join (targetFolder, 'index.html') ReplaceInFile (indexFilePath, '../jsmodeler/', 'jsmodeler/') def BuildEmbeddable (rootFolder, resultFolder): targetFolder = os.path.join (resultFolder, 'embeddable') shutil.copytree (os.path.join (rootFol...
zdvresearch/fast15-paper-extras
ecfs_user_sessions/src/analyze_user_sessions.py
Python
mit
7,526
0.007175
#!/usr/bin/env python3 """ Categorize and analyze user sessions. Read in ecfs_obfuscated_filtered.gz file, output some fancy results. """ from collections import defaultdict from collections import Counter import sys import time import os import resource import json import fnmatch from pipes import Pipes impo...
= os.path.dirname(result) target_file_name = os.path.basename(result) users_session_files = [os.path.join(dirpath, f) for dirpath, dirnames, files in os.walk(source_dir) for f in fnmatch.filter(files, '*.user_session.csv')]
#remove the old log file, as outpipe is append only. if os.path.exists(os.path.join(results_dir, target_file_name)): os.remove(os.path.join(results_dir, target_file_name)) out_pipe = Pipes(results_dir) csv_header = ";".join(["user_id", "from_ts", "till_t...
lgaborini/decathlon_review_scraper
decathlon_scrapy/items.py
Python
mit
729
0
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html from scrapy_djangoitem import DjangoItem # To get your settings from (settings.py): from scrapy.utils.project import get_project_settings settings = get_project_setti...
goItem # Notice that DjangoItems are scrapy.Items class ProductItem(DjangoItem):
if settings.get("USE_DJANGO"): django_model = ProductDjangoItem class ProductReviewItem(DjangoItem): if settings.get("USE_DJANGO"): django_model = ProductReviewDjangoItem
beangoben/toulouse_secretgui
cipsi/orbitalWidget.py
Python
gpl-3.0
1,291
0.001549
class orbitalWidget(QGroupBox): def __init__(self): super(QGroupBox, self).__init__() self.initUI() def initUI(self): table= orbitalTable(0, 3) table.horizontalHeader().setResizeMode(QHeaderView.Stretch) btn_active = QPushButton('Active', self) btn_active.se...
bital_space["btn_inactive"]) vbox = QVBoxLayout() vbox.addWidget(table) vbox.addWidget(btn_active) vbox.addWidget(btn_frozen) vbox.addWidget(btn_inactive) w=QWidget() w.setLayout(vbox) self.setTitle("O
rbital class") vbox = QVBoxLayout() vbox.addWidget(w) self.setLayout(vbox)
willkg/harold
harold/base/admin.py
Python
mpl-2.0
497
0
from django.contrib import admin from django.core.exceptions import PermissionDenied from harold.base.models import Feedback class FeedbackAdmin(admin.ModelAdmin): list_display = ('created_on', 'sentiment', 'text', 'email', 'notes', 'assigned_to', 'closed')
search_fields = ('text',) def has_add_permission(self, request, obj=None):
# Prevent anyone from adding feedback in the admin. return False admin.site.register(Feedback, FeedbackAdmin)
google-research/google-research
motion_blur/train/dataset.py
Python
apache-2.0
3,453
0.008688
# coding=utf-8 # Copyright 2022 The Google Research 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 applicab...
compat.v1 as tf def read_jpg(filename): """Reads an 8-bit JPG file from disk and
normalizes to [0, 1].""" image_file = tf.read_file(filename) image = tf.image.decode_jpeg(image_file, channels=3) white_level = 255.0 return tf.cast(image, tf.float32) / white_level def read_images(dir_name): """Reads motion blur training inputs and label images.""" images = [ read_jpg(dir_name + '...
minlex/django-socialregistration
socialregistration/contrib/instagram/south_migrations/0001_initial.py
Python
mit
6,041
0.008111
# 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 model 'InstagramProfile' db.create_table('instagram_instagramprofile', ( ('id', self....
main': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) } } complete_apps = ['instagram']
amplifylitco/asiaq
tests/unit/test_disco_elastigroup.py
Python
bsd-2-clause
22,367
0.001207
""" Tests of disco_elastigroup """ import random from unittest import TestCase from parameterized import parameterized from mock import MagicMock, ANY, patch from disco_aws_automation import DiscoElastigroup ENVIRONMENT_NAME = "moon" class DiscoElastigroupTests(TestCase): """Test DiscoElastigroup class""" ...
( ENVIRONMENT_NAME ) self.elastigroup.spotinst_client = MagicMock() def test_delete_groups_bad_hostclass(self): """Verifies elastigroup not deleted for bad hostclass""" self.elastigroup._delete_group = MagicMock() self.elastigroup._spotinst_call = MagicMock() ...
"""Verifies elastigroup not deleted for bad group name""" self.elastigroup._delete_group = MagicMock() self.elastigroup._spotinst_call = MagicMock() self.elastigroup.delete_groups(group_name='moon_mhcfoo_12345678') self.assertFalse(self.elastigroup._delete_group.called) d...
wigginslab/lean-workbench
lean_workbench/google_analytics/google_analytics_models.py
Python
mit
6,662
0.010808
from database import db import time import datetime ga_profiles_association = db.Table('user_profiles_association', db.Column('user_id', db.Integer, db.ForeignKey('google_analytics_oauth_credentials.id')), db.Column('profile_id', db.Integer, db.ForeignKey('google_analytics_profiles.id')) ) class GoogleAnalyti...
me, default=datetime.datetime.now()) status = db.Column(db.String) experiment_id = db.Column(db.String) objective_metric = db.Column(db.S
tring) start_time = db.Column(db.DateTime) end_time = db.Column(db.DateTime) minimum_experiment_length_in_days = db.Column(db.Integer) winner_id = db.Column(db.String) winner_found = db.Column(db.Boolean) variations = db.relationship('GoogleAnalyticsExperimentVariation', backref='GoogleAna...
ellxc/piperbot
plugins/help.py
Python
gpl-2.0
2,390
0.004603
from wrappers import * from inspect import getdoc @plugin class Help: @command("list") def list(self, message): """list the loaded plugins""" return message.reply(list(self.bot.plugins.keys()), "loaded plugins: " + ", ".join(self.bot.plugins.keys())) @command("commands") d...
found") doc = func.__doc__ if not doc: return message.reply("No help found for specified command") else: firstline = "%s: %s" % (com, doc.
split("\n")[0]) return message.reply(doc, firstline) else: return message.reply("Help can be found at https://github.com/ellxc/piperbot/blob/master/README.md or by joining #piperbot on freenode")
EvaErzin/DragonHack
DragonHack/management/commands/dolocanjeGostisc.py
Python
mit
8,452
0.004614
import csv #import datetime import numpy as np import HackApp.models as database from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): def handle(self, *args, **options): percentageAfterNine = 0.05 percentage3to50 = 0.7 longBound = [13.375556, 16.61...
ongN latN = int(np.ceil((latBound[1] - latBound[0]) / squareSize)) # poravnano zgoraj # notri [davcna, poslovalni
ca, moc, barva] grid = np.zeros((longN, latN, 4)) tip = database.Tip.objects.get(id=45635) for i in kandidati: lokacija = database.Lokacija(poslovniProstor=hex(int(i[1]))[2:].upper(), davcnaStevilka = str(int(i[0]))) lokacija.long = i[6] lokacija.lat = i[7] ...
kronenpj/python-for-android
pythonforandroid/recipes/six/__init__.py
Python
mit
265
0
from pythonforandroid.recipe import PythonRecipe class SixRecipe(PythonRecipe): version = '1.10.0' url = 'https://pypi.python.org/packages/source/s/six/six-{version}.ta
r.gz' depends = [('python
2', 'python3', 'python3crystax')] recipe = SixRecipe()
bcimontreal/bci_workshop
python/extra_stuff/livebargraph.py
Python
mit
940
0.001064
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Aug 25 21:11:45 2017 @author: hubert """ import numpy as np import matplotlib.pyplot as plt class LiveBarGraph(object): """ """ def __init__(self, band_names=['delta', 'theta', 'alpha', 'beta'], ch_names=['TP9', 'AF7', 'A...
""" """ self.band_names = band_names self.ch_names = ch_names self.n_bars = self.band_names * self.ch_names self.x = self.fig, self.ax = plt.subplots() self.ax.set_ylim((0, 1)) y = np.zeros((self.n_bars,)) x = range(self.n_bars) s...
[rect.set_height(y) for rect, y in zip(self.rects, new_y)] if __name__ == '__main__': bar = LiveBarGraph() plt.show() while True: bar.update(np.random.random(10)) plt.pause(0.1)
mbr0wn/gnuradio
gr-qtgui/grc/qtgui_time_sink_x.block.yml.py
Python
gpl-3.0
11,608
0.001551
#!/usr/bin/env python import math import re EVERYTHING_BEFORE_PARAMS = """id: qtgui_time_sink_x label: QT GUI Time Sink parameters: - id: type label: Type dtype:
enum default: complex options: [complex, float, msg_complex, msg_float
] option_labels: [Complex, Float, Complex Message, Float Message] option_attributes: fcn: [time_sink_c, time_sink_f, time_sink_c, time_sink_f] t: [complex, float, message, message] hide: part - id: name label: Name dtype: string default: '""' hide: ${ ('none' if len(name) >...
maxisi/gwsumm
gwsumm/plot/builtin.py
Python
gpl-3.0
33,208
0.000813
# -*- coding: utf-8 -*- # Copyright (C) Duncan Macleod (2013) # # This file is part of GWSumm. # # GWSumm 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) ...
setattr(ax, key, val) if (len(channels) > 1 or plotargs[0].get('label', None) in [re.sub(r'(_|\\_)', r'\_', channels[0]), None]): plot.add_legend(ax=ax, **legendargs) # add extra axes and finalise if not plot.colorbars: plot.add_colorbar(ax=ax, visib...
SeriesDataPlot): """DataPlot a Spectrogram """ type = 'spectrogram' data = 'spectrogram' defaults = {'ratio': None, 'format'
catapult-project/catapult
tracing/tracing/value/diagnostics/breakdown_unittest.py
Python
bsd-3-clause
1,818
0.00165
# Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import json import math import unittest from tracing.value import histogram_serializer from tracing.value.diagnostics import breakdown from tracing.value.di...
s = histogram_serializer.HistogramSerializer() b = breakdown.Breakdown.FromEntries
({'a': 10, 'b': 20}) self.assertEqual(b.Serialize(s), [0, 3, 10, 20]) self.assertEqual(s.GetOrAllocateId(''), 0) self.assertEqual(s.GetOrAllocateId('a'), 1) self.assertEqual(s.GetOrAllocateId('b'), 2) self.assertEqual(s.GetOrAllocateId([1, 2]), 3)
NeovaHealth/patientflow
nh_etake_list/review.py
Python
agpl-3.0
8,568
0.004085
# Part of Patient Flow. # See LICENSE file for full copyright and licensing details. from openerp.osv import orm, fields, osv from openerp import SUPERUSER_ID import logging _logger = logging.getLogger(__name__) class nh_etake_list_review(orm.Model): _name = "nh.etake_list.review" _inherits = {'nh.activity':...
ext=context) if 'plan' in vals: activity_pool.submit(cr, uid, review.activity_id.id, {'plan': vals['plan']}, context=context) activity_pool.submit(cr, uid, review.id, {'doctor_plan': va
ls['plan']}, context=context) if 'doctor_task_ids' in vals: for dt in vals['doctor_task_ids']: if dt[2]: activity_pool.write(cr, uid, dt[1], dt[2], context=context) return True def transfer(self, cr, uid, ids, context=None): pt...
jiadaizhao/LeetCode
0001-0100/0001-Two Sum/0001-Two Sum.py
Python
mit
372
0
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: table = {} result = [0, 0]
for i, num in enumerate(nums): if target - num in table: result[0] = table[target - num] result[1] = i break
else: table[num] = i return result
OuterDeepSpace/OuterDeepSpace
techviewer/DependencyPanel.py
Python
gpl-2.0
1,962
0.046381
import wx from Gauge import Gauge class DependencyPanel(wx.Panel): def __init__(self, parent, text, gaugeColor, textColor, env = 0, mineral = 0, energy = 0, nothing = 0): wx.Panel.__init__(self, parent, -1) gaugeBorders = (5, 5, 1, 7) self.env = Gauge(self, gaugeColor, textColor, gaugeBorders, env) self.m...
= Gauge(self, gaugeColor, textColor, gaugeBorders, mineral) self.energy = Gauge(self, gaugeColor, textColor, gaugeBorders, energy) self.nothing = Gauge(self, gaugeColor, textColor, gaugeBorders, nothing) vertBox = wx.BoxSizer(wx.
VERTICAL) panelCaption = wx.StaticText(self, -1, text) font = panelCaption.GetFont() font.SetWeight(wx.FONTWEIGHT_BOLD) panelCaption.SetFont(font) vertBox.Add(panelCaption, 0, wx.BOTTOM, 5) gbs = wx.GridBagSizer(4, 4) gbs.SetFlexibleDirection(wx.HORIZONTAL) gbs.SetCols(2) gbs.SetRows(4) gbs.AddGrow...
dmort27/epitran
epitran/test/test_french.py
Python
mit
2,463
0
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals import logging import unittest import epitran logger = logging.getLogger('epitran') def map_slice(xs, start, end): return [x[start:end] for x in xs] def assemble_ipa(xs): return ''.join([x[3] for x in xs...
._derivation('fusils', 'fyzi') def test_oe
f(self): self._derivation('œuf', 'œf') self._derivation('œufs', 'œf') def test_decret(self): self._derivation('décret', 'dekʀɛ') self._derivation('décrets', 'dekʀɛ') def test_loi(self): self._derivation('loi', 'lwa') self._derivation('lois', 'lwa') def test...
inovtec-solutions/OpenERP
openerp/addons/account/report/account_journal.py
Python
agpl-3.0
9,777
0.0045
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
elf.get_start_period, 'get_end_period': self.get_end_period, 'get_account': self._get_account, 'get_filter': self._get_filter, 'get_start_date': self._get_start_date, 'get_end_date': self._get_end_date, 'get_fiscalyear': self._get_fiscalyear, ...
'get_sortby': self._get_sortby, 'get_target_move': self._get_target_move, 'check_last_move_id': self.check_last_move_id, 'set_last_move_id': self.set_last_move_id, 'tax_codes': self.tax_codes, 'sum_vat': self._sum_vat, }) def set_context(self...
bitesofcode/projexui
projexui/designer/build/xscintillaeditplugin.py
Python
lgpl-3.0
2,537
0.010642
#!/usr/bin/python ''' Auto-generated ui widget plugin ''' from projexui.qt.QtDesigner import QPyDesignerCustomWidgetPlugin from projexui.qt.QtGui import QIcon import projex.resources from projexui.widgets.xscintillaedit import XScintillaEdit as Base setattr(Base, '__designer_mode__', True) DEFAULT_XML = ...
stomwidget> <class>XScintillaEdit</class> <header>projexui.widgets.xscintillaedit</header> <addpagemethod>%(addpagemethod)s</addpagemethod> <propertyspecifications> %(propertyspecs)s </propertyspecifications> </customwidget> </customwidgets> </ui>''' class XScinti...
) self.initialized = False def initialize(self, core): if self.initialized: return self.initialized = True def isInitialized(self): return self.initialized def createWidget(self, parent): return Base(parent) ...
dash1291/major
webserver/app.py
Python
gpl-3.0
4,561
0.007893
import json import os.path import sys sys.path.append(os.path.join(os.path.dirname(__file__), '../scripts')) from flask import Flask, render_template, request from py2neo import neo4j from ollie import pipeline app = Flask(__name__) """@app.route('/render', method=['POST']) def render(): pairs = json.loads(re...
rue: try: concept = q.next() except: break rels += concept.match() if not concept: return json.loads(pairs) nodes = {} edges = [] for rel in rels: n1 = rel.start_node['name'] n2 = rel.end_node['name'] if n1 not in nodes...
des: nodes[str(n2)] = {"radius":10.0, "weight":1.00, "centrality":0.00, "fill":"rgba(0,127,255,0.70)", "stroke":"rgba(0,0,0,0.80)"} nodes[str(rel.type)] = {"radius":10.0, "weight":1.00, "centrality":0.00, "fill":"rgba(0,127,255,0.70)", "stroke":"rgba(0,0,0,0.80)"} #edges.append([str(n1), s...
pignacio/vld
vld/serialization.py
Python
bsd-3-clause
1,246
0
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals, division import json import logging import os from .objects import Ingredient logger = logging.getLogger(__name__) # pylint: disable=invalid-name def load_ingredients(directory): if not os.path.isdir(direct...
= os.path.join(path, filename) logging.debug(" - Parsi
ng ingredients from '%s'", fullpath) with open(fullpath) as fin: try: parsed = json.load(fin) except Exception: logger.exception("Could not parse JSON from '%s'", fullpath) contin...
deepmind/dm_robotics
py/moma/sensors/robotiq_gripper_sensor_test.py
Python
apache-2.0
1,597
0.001252
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
uted under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions
and # limitations under the License. """Tests for robotiq_gripper_sensor.""" from absl.testing import absltest from dm_robotics.moma.models.end_effectors.robot_hands import robotiq_2f85 from dm_robotics.moma.sensors import robotiq_gripper_observations from dm_robotics.moma.sensors import robotiq_gripper_sensor # Ab...
sgraham/nope
third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/port/browser_test_driver.py
Python
bsd-3-clause
4,523
0.001105
# Copyright (C) 2014 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the ...
AGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS...
: """Object for running print preview test(s) using browser_tests.""" def __init__(self, port, worker_number, pixel_tests, no_timeout=False): """Invokes the constructor of driver.Driver.""" super(BrowserTestDriver, self).__init__(port, worker_number, pixel_tests, no_timeout) def start(self,...
tylertian/Openstack
openstack F/python-novaclient/novaclient/crypto.py
Python
apache-2.0
1,286
0
# Copyright 2013 Nebula, 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 ...
ANTIES OR CONDITIONS OF ANY KIND, either
express or implied. See the # License for the specific language governing permissions and limitations # under the License. import base64 import subprocess class DecryptionFailure(Exception): pass def decrypt_password(private_key, password): """Base64 decodes password and unecrypts it with private key...
turbokongen/home-assistant
script/hassfest/services.py
Python
apache-2.0
2,796
0.001431
"""Validate dependencies.""" import pathlib import re from typing import Dict import voluptuous as vol from voluptuous.humanize import humanize_error from homeassistant.const import CONF_SELECTOR from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import config_validation as cv, selecto...
integration.add_error( "services", "Registers services but unable to load services.yaml" ) return try: SERVICES_SCHEMA(data) except vol.Invalid as err: integration.add_error( "services", f"
Invalid services.yaml: {humanize_error(data, err)}" ) def validate(integrations: Dict[str, Integration], config): """Handle dependencies for integrations.""" # check services.yaml is cool for integration in integrations.values(): if not integration.manifest: continue v...
benoitclem/gEDALibraries
footprints/nxp/bsr14.py
Python
gpl-2.0
210
0.019048
#!/usr/bin
/python import footgen f = footgen.Footgen("BSR14","geda") f.add_pad("3", - 0.95, -1, 0.6, 0.7) f.add_pad("2", 0.95, -1, 0
.6, 0.7) f.add_pad("1", 0, 1, 0.6, 0.7) f.silkbox(3.3,1) f.finish()
LACNIC/simon
simon-web/scripts.py
Python
gpl-2.0
6,922
0.040451
#!/usr/bin/python from __future__ import print_function from __future__ import absolute_import import os from .simon_app.functions import whoIs from .simon_app.models import TestPoint, Results, Country from geopy import geocoders from __future__ import division #float division import math os.environ['DJANGO_SETTINGS_M...
t urlopen from lxml import etree def db_cleaning(): """ Script that cleans the Results table with the following criteria - remove negative results - remove high-end and low-end results (above or below 2 sigma) """ test_points = TestPoint.objects.all() del
eted_registers = 0 for test_point in test_points: test_point_results = Results.objects.filter(ip_destination = test_point.ip_address).values('ave_rtt', 'number_probes', 'dev_rtt') count = sum(test_point_results.values_list('number_probes',flat=True)) test_point_avg = 0 #Grand Mean test_point_dev = 0 #overall S...
levilucio/SyVOLT
t_core/rollbacker.py
Python
mit
3,343
0.006581
#import pickle, os from util.infinity import INFINITY from iterator import Iterator from t_core.messages import TransformationException class Rollbacker(Iterator): ''' Provides back-tracking capacity. ''' def __init__(self, condition, max_iterations=INFINITY): ''' ...
self.is_success = False try: self.establish(packet) self.is_success = True except Exception, e: self.is_success = False self.exception = TransformationException(e) self.exception.packet = packet self.exception.transformat...
eturn packet def next_in(self, packet): self.exception = None self.is_success = False if self.iterations < self.max_iterations: # If came from the same scope as the rollbacker, then just pass it over if packet.current in packet.match_sets: ...
Katello/grinder
src/grinder/KickstartFetch.py
Python
gpl-2.0
3,746
0.00347
# # Copyright (c) 2011 Red Hat, Inc. # # This software is licensed to you under the GNU General Public # License as published by the Free Software Foundation; either version # 2 of the License (GPLv2) or (at yo
ur option) any later version. # There is NO WARRANTY for this software, express or implied, # including the implied warranties of MERCHANTABILITY, # NON-INFRINGEMENT, or FITNESS FOR A PARTICULAR PURPOSE. You should # have received a copy of GPLv2 along with this software; if not, see # http://www.gnu.org/licenses/old-l...
rom grinder.RHNComm import RHNComm LOG = logging.getLogger("grinder.KickstartFetch") class KickstartFetch(BaseFetch): def __init__(self, systemId, baseURL): BaseFetch.__init__(self) self.baseURL = baseURL self.systemId = systemId self.rhnComm = RHNComm(baseURL, self.systemId) ...
erikvw/django-crypto-fields
django_crypto_fields/exceptions.py
Python
gpl-3.0
445
0
class DjangoCryptoFieldsLoading
Error(Exception): pass class DjangoCryptoFieldsKeysAlreadyLoaded(Exception): pass class EncryptionError(Exception): pass class CipherError(Exception): pass class AlgorithmError(Exception): pass class ModeError(Exception): pass class EncryptionKeyError(Exception): pass class Enc...
tError(Exception): pass
kyvinh/home-assistant
tests/components/sensor/test_rfxtrx.py
Python
apache-2.0
13,915
0
"""The tests for the Rfxtrx sensor platform.""" import unittest import pytest from homeassistant.bootstrap import setup_component from homeassistant.components import rfxtrx as rfxtrx_core from homeassistant.const import TEMP_CELSIUS from tests.common import get_test_home_assistant @pytest.mark.skipif("os.environ....
705020095220269': { 'name': 'Test', 'data_type': 'Temperature'}}}})) self.assertEqual(1, len(rfxtrx_core.RFX_DEVICES)) entity = rfxtrx_core.RFX_DEVICES['sensor_0502']['Temperature'] self.assertEqual('Test', entity.name) self....
y.state) def test_one_sensor_no_datatype(self): """Test with 1 sensor.""" self.assertTrue(setup_component(self.hass, 'sensor', { 'sensor': {'platform': 'rfxtrx', 'devices': {'0a52080705020095220269': { 'nam...
piotr1212/gofed
inspecttarball.py
Python
gpl-2.0
4,610
0.035358
# #################################################################### # gofed - set of tools to automize packaging of golang devel codes # Copyright (C) 2014 Jan Chaloupka, jchaloup@redhat.com # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public Licen...
, "-s", "--spec", dest="spec", action="store_true", default = False, help = "If set with -p options, print list of provided paths in spec file format." ) parser.add_option( "", "-d", "--dirs", dest="dirs", action = "store_true", default = False, help = "Display all direct directories" ...
False, help = "Display all directories containing *.go test files" ) parser.add_option( "", "", "--scan-all-dirs", dest="scanalldirs", action = "store_true", default = False, help = "Scan all dirs, including Godeps directory" ) parser.add_option( "", "", "--skip-dir...
usakhelo/FreeCAD
src/Mod/Fem/importInpMesh.py
Python
lgpl-2.1
9,765
0.001126
# *************************************************************************** # * * # * Copyright (c) 2016 - Frantisek Loeffelmann <LoffF@email.cz> * # * * # * Th...
s = 20 elif elm_type == "C3D6": elm_category = elements.penta6 number_of_nodes = 6 elif elm_type == "C3D15": elm_category = elements.penta15 number_of_nodes = 15 elif elm_type in ["B31", "B31R", "T3D2"]: ...
elif elm_type in ["B32", "B32R", "T3D3"]: elm_category = elements.seg3 number_of_nodes = 3 error_seg3 = True # to print "not supported" elif elm_category != []: line_list = string.split(line, ',') if elm_2nd_line is False: ...
mtulio/kb
dev/satellite6_api/create_obj_env.py
Python
apache-2.0
3,870
0.001809
#!/usr/bin/python # Red Hat Satellite - API Guide - 4.2.1. Creating Objects Using Python # Link: https://access.redhat.com/documentation/en-US/Red_Hat_Satellite/6.1/html-single/API_Guide/index.html#idm4983248 # # The following script connects to the Red Hat Satellite 6 API and creates a new organization, then creates ...
SAT_API + "organizations/" + str(org_id) + "/environments/", json.dumps( { "name": environment, "organization_id": org_id, "prior": p
rior_env_id} ))["id"] print "Creating environment: \t" + environment prior_env_id = new_env_id if __name__ == "__main__": main()
paradiseOffice/Bash_and_Cplus-plus
CPP/full_examples/pyqt/chap07/findandreplacedlg.py
Python
gpl-2.0
4,146
0.003618
#!/usr/bin/env python3 # Copyright (c) 2008-9 Qtrac Ltd. All rights reserved. # This program or module 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 # version 3 of the Lic...
= regex.search(self.__text, self.__index) if match i
s not None: self.__index = match.end() self.emit(SIGNAL("found"), match.start()) else: self.emit(SIGNAL("notfound")) @pyqtSignature("") def on_replaceButton_clicked(self): regex = self.makeRegex() self.__text = regex.sub(str(self.repl...
anrl/W12x
server/vxserver.py
Python
mit
3,668
0.022901
# The MIT License (MIT) # Copyright (c) 2011 Derek Ingrouville, Julien Lord, Muthucumaru Maheswaran # Permission is hereby grant
ed, free of
charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit pers...
sourcelair/castor
castor/webhooks/migrations/0011_remove_delivery_docker_event.py
Python
mit
402
0
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-12-20 17:51 from __future
__ i
mport unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('webhooks', '0010_auto_20170129_1356'), ] operations = [ migrations.RemoveField( model_name='delivery', name='docker_event', ), ]
Arthur2e5/arguman.org
web/nouns/migrations/0016_channel.py
Python
mit
803
0.002491
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations c
lass Migration(migrations.Migration
): dependencies = [ ('nouns', '0015_auto_20151104_2059'), ] operations = [ migrations.CreateModel( name='Channel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('title', m...
DevicePilot/synth
synth/watch_zeromq.py
Python
mit
1,364
0.005132
#!/usr/bin/env python # # Copyright (c) 2017 DevicePilot Ltd. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software an
d associ
ated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the follo...