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
selective-inference/selective-inference
selectinf/constraints/intervals.py
Python
bsd-3-clause
6,279
0.005733
import numpy as np import warnings import operator from heapq import merge class intervals(object): r""" This class implements methods for intervals or union of two unbounded intervals, when all these sets have a point in their intersection """ def __init__(self, I = None): """ ...
True if x is in the intersection, False if it's not
Examples -------- >>> I = intervals() >>> I(2) False >>> I = intervals.intersection(intervals((-1, 6)), \ intervals(( 0, 7)), \ ~intervals((1, 4))) >>> x1, x2, x3, x4, x5 = 0.5...
ostree/plaso
tests/preprocessors/linux.py
Python
apache-2.0
2,940
0.003061
#!/usr/bin/python # -*- coding: utf-8 -*- """Tests for the Li
nux preprocess plug-ins.""" import unittest from dfvfs.helpers import file_system_searcher from dfvfs.path import fake_path_spec from plaso.engine import knowledge_base from plaso.preprocessors import linux from tests.preprocessors import test_lib class LinuxHostnameTest(test_lib.PreprocessPluginTest): """Test...
e preprocess plug-in object.""" _FILE_DATA = ( 'plaso.kiddaland.net\n') def setUp(self): """Sets up the needed objects used throughout the test.""" self._fake_file_system = self._BuildSingleFileFakeFileSystem( u'/etc/hostname', self._FILE_DATA) mount_point = fake_path_spec.FakePathSpec(...
tanium/pytan
lib/taniumpy/object_types/sensor_subcolumn_list.py
Python
mit
487
0.014374
# Copyright (c) 2015 Tanium Inc # # Generated from console.wsdl version 0.0.1 # # from .base import BaseType class SensorSubcolumnList(BaseType): _soap_tag = 'subcolumns' def __init__(self): BaseType.__init__( self, simple_properties={},
complex_properties={}, list_properties={'subcolumn': SensorSubcolumn}, ) self.subcolumn = [] from
sensor_subcolumn import SensorSubcolumn
yaoyi92/qbox_libxc
util/qbox_dos.py
Python
gpl-2.0
2,774
0.018385
#!/usr/bin/python # qbox_dos.py: extract electronic DOS from Qbox output # generate DOS plot in gnuplot format # use: qbox_dos.py [-last] emin emax width file.r # emin, emax: bounds of plot in [eV] # width: gaussian broadening in [eV] # the DOS is accumulated separately for each spin # With the -last option, only the l...
= 0 self.accumulate_dos() def accumulate_dos(self): self.e = self.buffer.split() if self.spin == 0: for i in range(len(self.e)): for j in range(ndos): ej = emi
n + j * de self.dos_up[j] += gauss(float(self.e[i])-ej, width ) * self.weight if self.spin == 1: for i in range(len(self.e)): for j in range(ndos): ej = emin + j * de self.dos_dn[j] += gauss(float(self.e[i])-ej, width ) * self.weight def print_dos(self): print "# "...
ares/robottelo
tests/foreman/api/test_variables.py
Python
gpl-3.0
50,980
0
# -*- encoding: utf-8 -*- """Test class for Smart/Puppet Variables :Requirement: Smart_Variables :CaseAutomation: Automated :CaseLevel: Acceptance :CaseComponent: API :TestType: Functional :CaseImportance: High :Upstream: No """ import json from random import choice, uniform import yaml from fauxfactory import ...
nts Smart Variables tests in API""" @classmethod def setUpClass(cls): """Import some parametrized puppet classes. This is required to make sure tha
t we have data to be able to perform interactions with smart class variables. """ super(SmartVariablesTestCase, cls).setUpClass() cls.puppet_modules = [ {'author': 'robottelo', 'name': 'api_test_variables'}, ] cls.org = entities.Organization().create() ...
Beauhurst/django
tests/admin_ordering/models.py
Python
bsd-3-clause
891
0
from django.contrib import admin from django.db import models class Band(models.Model): name = models.CharField(max_length=100) bio = models.TextField() rank = models.IntegerField() class Meta: ordering = ('name',) class Song(models.Model): band = models.F
oreignKey(Band, models.CASCADE) name = models.CharField(max_length=100) duration = models.IntegerField() other_interpreters = models.ManyToManyField(Band, related_name='covers') class Meta: ordering = ('name',) class SongInlineDefaultOrdering(admin.StackedInline): mode
l = Song class SongInlineNewOrdering(admin.StackedInline): model = Song ordering = ('duration', ) class DynOrderingBandAdmin(admin.ModelAdmin): def get_ordering(self, request): if request.user.is_superuser: return ['rank'] else: return ['name']
liangtianyou/ST
stclient/app.py
Python
gpl-3.0
661
0.013616
#-*- coding: utf-8 -*- import os import sys import traceback try: if sys.getdefaultencoding() != 'utf-8':
reload(sys) sys.setdefaultencoding('utf-8') except: pass currdir = os.path.join(os.getcwd(),os.path.dirname(__file__)) if currdir not in sys.path: sys.path.append(currdir) from base import app #----------------------------------------- # #----------------------------------------- def main(): ''' ...
(),sys.stderr.fileno()) ''' app.run() if __name__ == "__main__": main()
SohKai/ChronoLogger
web/flask/lib/python2.7/site-packages/sqlalchemy/orm/dependency.py
Python
mit
49,199
0.002805
# orm/dependency.py # Copyright (C) 2005-2012 the SQLAlchemy authors and contributors <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """Relationship dependencies. """ from sqlalchemy import sql, util, exc as sa_exc ...
ate) if parent_in_cycles:
parent_saves = unitofwork.SaveUpdateState( uow, state, parent_base_mapper) if child_in_cycles: child_actions = [] for ...
crmccreary/openerp_server
openerp/addons/import_google/wizard/import_google_data.py
Python
agpl-3.0
8,149
0.008835
# -*- 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...
ontext.get('contact'): data_
id = data_obj._get_id(cr, uid, 'import_google', 'view_synchronize_google_contact_import_form') if context.get('calendar'): data_id = data_obj._get_id(cr, uid, 'import_google', 'view_synchronize_google_calendar_import_form') if data_id: view_id = data_obj.browse(cr, uid, da...
jeremiahyan/odoo
addons/hr_work_entry/models/hr_employee.py
Python
gpl-3.0
596
0.001678
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, _ class HrEmployee(models.
Model): _inherit = 'hr.employee' def action_open_work_entries(self): self.ensure_one() return { 'type': 'ir.actions.act_window', 'name': _('%s work entries', self.display_name), 'view_mode': 'calendar,gantt,tree,form', 'res_model': 'hr.work.entry'...
lt_employee_id': self.id}, 'domain': [('employee_id', '=', self.id)], }
abahdanovich/distorm
disOps/x86header.py
Python
gpl-3.0
6,156
0.032164
# # x86header.py # # Copyright (C) 2009 Gil Dabah, http://ragestorm.net/disops/ # class OperandType: """ Types of possible operands in an opcode. Refer to the diStorm's documentation or diStorm's instructions.h for more explanation about every one of them. """ (NONE, IMM8, IMM16, ...
G field or the whole next byte.
OL_33 and OL_4 are used in raw opcode bytes, they include the mandatory prefix, therefore when they are defined in the instruction tables, the mandatory prefix table is added, and they become OL_23 and OL_3 correspondingly. There is no effective opcode which is more than 3 bytes. """ (OL_1, # 0 ...
jwang-share/said
black3/factory/workers/weibo/weibominiblogs.py
Python
apache-2.0
4,022
0.041024
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys from factory.supports import format from factory.supports.parser import parser from weibocommon import weibocommon from rootcfg import HIS_ORIGIN_BLOG_PREFIX from rootcfg import BLOG_NUM_PER_BLOCK from rootcfg import MAX_PAGE_NUM_PER_USER import time import simp...
, uid): params = {} params['count'] = '50' params['_t'] = '0' params['uid'] = uid params['__rnd'] = str(int(time.time() * 1000)) params['_k'] = str(int(time.time() * (10**6))) init_url = '%s&%s'%(HIS_ORIGIN_BLOG_PREFIX, format.urlencode(params)) return init_url def do_r
un(self,task): item = task uid = item[0] lastestmid = uid[1] url = self.__init_url(uid) nxt_url = url self.end_id = 0 index = 0 while True: max_id = self.__get_one_block_content(nxt_url,lastestmid) if max_id < 1: break nxt_url = self.__get_next_url(nxt_url,self.end_id,max_id) index += 1...
convexengineering/gplibrary
gpkitmodels/GP/aircraft/wing/jho1polars/jho1_polarfits.py
Python
mit
2,692
0.002972
"jho1_polarfits.py" from builtins import zip from builtins import range import numpy as np import pandas as pd import matplotlib.pyplot as plt plt.rcParams.update({'font.size':15}) def text_to_df(filename): "parse XFOIL polars and concatente data in DataFrame" lines = list(open(filename)) for i, l in enume...
="none", mew=1.5) cd = return_fit(cls, r*1000.) ax.plot(cls, cd, c=col, label="Re = %dk" % r, lw=2)
ax1.plot(cls, cls**1.5/cd) ax.legend(loc=2, fontsize=15) ax.set_xlabel("$C_L$") ax.set_ylabel("$c_{d_p}$") ax.grid() return fig, ax, fig1 if __name__ == "__main__": Re = list(range(200, 750, 50)) X, Y = fit_setup(Re) # call fit(X, Y, 4, "SMA") to get fit F, A, F1 = plot_fits([300, ...
sreichholf/python-coherence
coherence/ui/av_widgets.py
Python
mit
32,894
0.010519
# Licensed under the MIT license # http://opensource.org/licenses/mit-license.php # Copyright 2008, Frank Scholz <coherence@beebits.net> """ simple and hopefully reusable widgets to ease the creation of UPnP UI applications icons taken from the Tango Desktop Project """ import os.path import urllib import ...
elf.root=root self.uuid = None self.name = name self.standalone=standalone icon = resource_filename(__name__, os.path.joi
n('icons','emblem-new.png')) self.new_icon = gtk.gdk.pixbuf_new_from_file(icon) icon = resource_filename(__name__, os.path.join('icons','emblem-shared.png')) self.shared_icon = gtk.gdk.pixbuf_new_from_file(icon) icon = resource_filename(__name__, os.path.join('icons','emblem-unreadable.p...
openstack/tempest
tempest/api/volume/test_volumes_actions.py
Python
apache-2.0
7,582
0
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
ents'][0] self.assertEqual('/dev/%s' % CONF.compute.volume_device_name, attachment['device']) self.assertEqual(server['id'], attachment['server_id']) self.assertEqual(self.volume['id'], attachment['id']) self.assertEqual(self.volume['id'...
ume_upload(self): """Test uploading volume to create an image""" # NOTE(gfidente): the volume uploaded in Glance comes from setUpClass, # it is shared with the other tests. After it is uploaded in Glance, # there is no way to delete it from Cinder, so we delete it from Glance # u...
mjtamlyn/django-denorm
test_project/settings_sqlite.py
Python
bsd-3-clause
139
0
from settings import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', '
NAME': ':memory:'
, } }
Empire-of-Code-Puzzles/checkio-empire-pawn-brotherhood
verification/src/referee.py
Python
mit
594
0.001684
from checkio_referee import RefereeBase, ENV_NAME import settings_env from tests import TESTS cover = """def cover(func, data): return func(set(
str(x) for x in data)) """ def set_repr(data, f): return repr("{}({})".format(f, set(data["input"]))) class Referee(RefereeBase): TESTS = TESTS ENVIRONMENTS = settings_env.ENVIRONMENTS DEFAULT_FUNCTION_NAME = "safe_pawns" FUNCTION_NAMES = { ENV_NAME.JS_NODE: "safePawns" } ENV_CO...
: cover, } CALLED_REPRESENTATIONS = { ENV_NAME.PYTHON: set_repr, }
plotly/plotly.py
packages/python/plotly/plotly/validators/volume/slices/x/_locations.py
Python
mit
427
0
import _plotly_utils.basevalidators class LocationsValidator(_plotly_utils.basevalidators.DataArrayValidator): def
__init__( self, plotly_name="locations", parent_name="volume.slices.x", **kwargs ): super(LocationsValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "calc"), **kwargs )
gityopie/odoo-addons
crm_maps/models/crm_lead.py
Python
lgpl-3.0
1,670
0
from odoo import api, fields, models class CrmLead(models.Model): _inherit = 'crm.lead' customer_longitude = fields.Float( string='Customer Longitude', digits=(16, 5) ) customer_latitude = fields.Float( string='Customer Latitude', digits=(16, 5) ) @api.onchange('partner_id') ...
_longitude = self.partner_id.partner_longitude @api.model def _geo_localize(self, street='', zip='', city='', state='', country=''): geo_obj = self.env['base.geocoder'] search = geo_obj.geo_query_address( street=street,
zip=zip, city=city, state=state, country=country ) result = geo_obj.geo_find(search, force_country=country) if result is None: search = geo_obj.geo_query_address( city=city, state=state, country=country ) result = geo_obj.geo_find(search, force...
elainekmao/hiphoptextanalysis
lyricwiki-scraper/lyricwiki/spiders/mastakilla_spider.py
Python
gpl-2.0
1,143
0.006999
from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.s
gml import SgmlLinkExtractor from scrapy.selector import Selector from lyricwiki.items import LyricWikiItem class LyricWikiSpider(CrawlSpider): name = "mastakilla" #CHANGE NAME allowed_domains = ["lyrics.wikia.com"] start_urls = [ "http://lyrics.wik...
Masta_Killa", #CHANGE URL ] rules = ( #CHANGE REGEX Rule(SgmlLinkExtractor(allow=('/Masta_Killa.*',),restrict_xpaths=('//ol/li',)), callback='parse_item', follow=True), ) def parse_item(self, response): sel = Selector(response...
eevee/cocos2d-mirror
test/test_particle_meteor.py
Python
bsd-3-clause
911
0.020856
# This code is so you can run the samples without installing the package import sys import os sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) # testinfo = "f 10 0.033, s, f 20 0.033, s, f 30 0.033, s, f 30 0.033, s, q" tags = "particles, Meteor" import pyglet import cocos from cocos.director import ...
= Galaxy() p.position = (480,200) self.add( p ) def main(): director.init( resizable=True ) main_scene = cocos.scene.Scene()
main_scene.add( L() ) director.run( main_scene ) if __name__ == '__main__': main()
fioreinc/ipp-15-16
deprecated/catkin_ws/src/loadcell_calibration/scripts/loadcell.py
Python
gpl-3.0
808
0.02599
#!/usr/bin/env python import sys im
port rospy from loadcell_calibration.srv import * def loadcell_init_client(): rospy.wait_for_service('get_factor') try: get_factor = rospy.ServiceProxy('get_factor', GetFactor); # lbs = 100 # factor = 2 # for x in range(0, 10): # response = get_factor(lbs*factor) # ...
factor(x) return response.is_done except rospy.ServiceException, e: print "Service call failed: %s"%e def usage(): return "%s [x]"%sys.argv[0] if __name__ == "__main__": if len(sys.argv) == 2: x = float(sys.argv[1]) else: print usage() sys.exit(1) print "Inputted Calibration Weight: %s"%(lo...
rezoo/chainer
chainer/functions/array/flatten.py
Python
mit
932
0
import chainer def flatten(x): """Flatten a given array into one dimension. Args: x (:class:`~chainer.Variable` or :class:`numpy.ndarray` or \ :class:`cupy.ndarray`): Input variable. Returns: ~chainer.Variable: Output variable flatten to one dimension. .. note:: Whe...
x.shape (2, 2) >>> y = F.flatten(x) >>> y.shape (4,) >>> y.data array([1, 2, 3, 4]) >>> x = np.arange(8).reshape(2, 2, 2) >>> x.shape (2, 2, 2) >>> y = F.flatten(x) >
>> y.shape (8,) >>> y.data array([0, 1, 2, 3, 4, 5, 6, 7]) """ return chainer.functions.reshape(x, (x.size,))
lowitty/selenium
com/ericsson/xn/x/pm/PmCommons/PmCommon.py
Python
mit
29,289
0.003858
# -*- coding: utf-8 -*- import time from datetime import datetime, timedelta from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException from com.ericsson.xn...
# click the query button id_query_btn = (By.ID, "idBtn-search") fin
d_single_widget(driver, 10, id_query_btn).click() # wait for the notification, maximum 20 seconds id_body_date = (By.XPATH, "//div[@class='ebTabs']/div[2]/div/div/div/div/table/tbody") find_single_widget(driver, 20, id_body_date) def wait_until_pm_date_show_up(driver, ne_name, wait_time=720): select_...
mindbody/API-Examples
SDKs/Python/swagger_client/models/contact_log_comment.py
Python
bsd-2-clause
5,761
0.000174
# coding: utf-8 """ MINDBODY Public API No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: v6 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 impor...
hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) ...
[attr] = value if issubclass(ContactLogComment, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self):...
dtudares/hello-world
yardstick/yardstick/vTC/apexlake/tests/heat_manager_test.py
Python
apache-2.0
6,931
0
# Copyright (c) 2015 Intel Research and Development Ireland Ltd. # # 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...
credentials['password'] = 'password' credentials['auth_uri'] = 'auth_uri' credentials['project'] = 'project' self.heat_manager = HeatManagerMock(credentials) self.heat_manager.init_heat() def tearDown(self): pass def test_is_stack_deployed_for_success(self): ...
_manager.is_stack_deployed('stack_1')) self.assertFalse(self.heat_manager.is_stack_deployed('stack_n')) def test_check_status_for_success(self): self.assertEqual('stack_1_status', self.heat_manager.check_stack_status('stack_1')) self.assertEqual('NOT_FOUND', ...
ccrisan/motioneye
motioneye/meyectl.py
Python
gpl-3.0
8,206
0.005484
#!/usr/bin/env python # Copyright (c) 2013 Calin Crisan # This file is part of motionEye. # # motionEye 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) a...
d of built-in defaults', type=str, dest='config_file') parser.add_argume
nt('-d', help='enable debugging, overriding log level from config file', action='store_true', dest='debug') parser.add_argument('-h', help='print this help and exit', action='help', default=argparse.SUPPRESS) parser.add_argument('-l', help='log to file instead of standard error', ...
dart-lang/sdk
tools/run_with_coredumps_enabled.py
Python
bsd-3-clause
627
0
#!/usr/bin/env python3 # Copyright (c) 2021, the Dart project authors. Please s
ee the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. from contextlib import ExitStack import subprocess import sys import utils def Main(): args = sys.argv[1:] with ExitStack() as stack: for ctx i...
s.DiagnoseExitCode(exit_code, args) return exit_code if __name__ == '__main__': sys.exit(Main())
botify-labs/py-rocksdb
test/try.py
Python
bsd-3-clause
2,259
0.031873
#!/usr/bin/python # Copyright (c) Arni Mar Jonsson. # See LICENSE for details. import rocksdb, pointless, random, string, itertools, collections from twisted.internet import reactor, defer, threads def compare(a, b): return cmp(a, b) c = 'bytewise' c = ('rocksdb.BytewiseComparator', compare) kw = { 'create_if_m...
ferToThread(i.next) except StopIteration: break if c > n_max: break ops['n_scans'] += 1 if ops['n_scans'] > 0 and ops['n_scans'] % 1000 == 0: print 'INFO: n_scans: %iK' % (ops['n_scans'] // 10
00,) def main(): #generate_data() reactor.suggestThreadPoolSize(20) kv = pointless.Pointless('/home/arni/py-rocksdb/data.map', allow_print = False).GetRoot() db = rocksdb.RocksDB('./db', **kw) stop = [False] def do_stop(): stop[0] = True reactor.stop() ops = collections.defaultdict(int) for i in xran...
SciTools/iris
lib/iris/tests/unit/coord_systems/test_LambertConformal.py
Python
lgpl-3.0
3,143
0
# Copyright Iris contributors # # This file is part of Iris and is released under the LGPL license. # See COPYING and COPYING.LESSER in the root of the repository for full # licensing details. """Unit tests for the :class:`iris.coord_systems.LambertConform
al` class.""" # Import iris.tests first so that some things can be initialised before # importing anything else. import iris
.tests as tests # isort:skip from iris.coord_systems import LambertConformal class Test_init_defaults(tests.IrisTest): # NOTE: most of the testing for LambertConformal is in the legacy test # module 'iris.tests.test_coordsystem'. # This class *only* tests the defaults for optional constructor args. ...
capveg/ONL
tools/py/pcgen.py
Python
epl-1.0
4,616
0.0026
#!/usr/bin/python ############################################################ # <bsn.cl fy=2013 v=onl> # # Copyright 2013, 2014 Bi
g Switch Networks, Inc. # # Licensed under the Eclipse Public License, Version 1.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.eclipse.org/l
egal/epl-v10.html # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, # either express or implied. See the License for the specific # language governing permissions and limitations un...
himaaaatti/qtile
libqtile/layout/floating.py
Python
mit
6,615
0
# Copyright (c) 2010 matt # Copyright (c) 2010-2011 Paul Colomiets # Copyright (c) 2011 Mounier Florian # Copyright (c) 2012 Craig Barnes # Copyright (c) 2012, 2014-2015 Tycho Andersen # Copyright (c) 2013 Tao Sauvage # Copyright (c) 2013 Julien Iguchi-Cartigny # Copyright (c) 2014 ramnes # Copyright (c) 2014 Sean Vig ...
ntaining some or all of the keys:: {'wname': WM_NAME, 'wmclass': WM_CLASS, 'role': WM_WINDOW_ROLE} The keys must be specified as above. You only need one, but you need to provide the value for it. When a new window is opened it's ``match`` method is
called with each of these rules. If one matches, the window will float. The following will float gimp and skype:: float_rules=[dict(wmclass="skype"), dict(wmclass="gimp")] Specify these in the ``floating_layout`` in your config. """ Layout.__init__(self, **config...
project-owner/Peppy
ui/slider/equalizerslider.py
Python
gpl-3.0
3,755
0.005326
# Copyright 2016-2021 Peppy Player peppy.player@gmail.com # # This file is part of Peppy Player. # # Peppy 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 version 3 of the License, or # (at you...
am id: band ID :param util: utility object :p
aram name: slider name :param bgr: slider background color :param slider_color: slider center line color :param img_knob: knob image :param img_knob_on: knob image in on state :param key_incr: keyboard key associated with slider increment action :param key_decr: keyboard ...
mkalioby/ModelTracker
ModelTracker/management/commands/restoreObject.py
Python
mit
1,770
0.020339
from django.core.management.base import BaseCommand, CommandError import __future__ from ModelTracker.models import History import datetime from django.apps import apps def getModel(table_name): return next((m for m in apps.get_models() if m._meta.db_table==table_name), None) class Command(BaseCommand): help =...
argument("--state",type=str,nargs='?',default="new") def handle(self, *args, **options): if not options.get("id",None): print ("Change ID is needed") exit(1) print (options) h = History.objects.get(id=int(options["id"])) model = getModel(h.table) if mo...
an't find the Model") exit(2) d=[f.name for f in model._meta.get_fields()] if options["state"]=="old": state=h.old_state else: state=h.new_state keys2del=[] for key in state: if (key.startswith("_") and "_cache" in key) or (key not in d and not ("_id" in k...
wangjun/pyload
module/plugins/crypter/PastebinCom.py
Python
gpl-3.0
1,621
0
# -*- coding: utf-8 -*- ############################################################################ # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as # # published by th
e Free Softw
are Foundation, either version 3 of the # # License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even ...
jgravois/ArcREST
src/arcrest/hostedservice/service.py
Python
apache-2.0
68,352
0.006525
import json from .._abstract.abstract import BaseAGOLClass, BaseSecurityHandler from ..security import security ######################################################################## class Services(BaseAGOLClass): """ The administration resource is the root node and initial entry point into a Spatia...
else: raise AttributeError("Admin only supports AGOL, ArcGIS, Portal, NTLM, LDAP, PKI and OAuth security handlers")
else: raise AttributeError("Admin only supports AGOL, ArcGIS, Portal, NTLM, LDAP, PKI and OAuth security handlers") if initialize: self.__init() #---------------------------------------------------------------------- def __init(self): """ init...
quantwizard-com/pythonbacktest
pythonbacktest/animation/ipythonchartanimation.py
Python
apache-2.0
1,578
0.003169
from IPython.display import display from matplotlib import animation, rc import abc class IPythonChartAnimation(object): __metaclass__ = abc.ABCMeta VIDEO_TAG = """<video controls> <source src="data:video/x-m4v;base64,{0}" type="video/mp4"> Your browser does not support the...
self.__number_of_frames = None self.__interval = None @abc.abstractmethod def _init_animation(self): raise NotImplementedError() def _start_animation(self, animation_callback, init_an
imation_callback, target_canvas, frames=100, interval=200): anim = animation.FuncAnimation(target_canvas, animation_callback, init_func=init_animation_callback, frames=frames, interval...
kinnla/racetrack
racetrack.py
Python
mit
8,945
0.029514
import tkinter import sys import getopt import time import threading import os import random import enum import racemap import racecar import racecolor def callback(event): """ Reacts to a user click on the window """ # switch on the status global status # if still initializing, ignore the click and don't do a...
mber, dr=car.get_driver_name(), c=car.color, r=car.total_moves, t=car.total_time, d=map.get_distance(car.position))) status = Status.finished def draw_map(): """ draws the map on the canvas """ # iterate on all cells for x in range(map.width): for y in range(map.height): # default cell color is white ...
ance to finish, if there is a distance if d is not None: color = '#' + hex(0xBBBB00 + 0xFF * (map.max_distance - d) // map.max_distance)[2:] else: # determine color by the cell type if cell == 's': color = 'light grey' elif cell == 'f': color = 'pale green' # draw rectangle...
cocagne/multi-paxos-example
replicated_value.py
Python
mit
8,017
0.014469
# This module provides a base class for maintaining a single replicated # value via multi-paxos. The responsibilities of this class are: # # * Loading and saving the state to/from disk # * Maintaining the integrity of the multi-paxos chain # * Bridging the composable_paxos.PaxosInstance object for the current ...
essenger): self.messenger = messenger def save_state(self, instance_number, current_value, promised_id, accepted_id, accepted_value): ''' For crash recovery purposes, Paxos requires that some state be saved to persistent media prior to sending Promise and Accepted messages....
er = instance_number self.current_value = current_value self.promised_id = promised_id self.accepted_id = accepted_id self.accepted_value = accepted_value tmp = self.state_file + '.tmp' with open(tmp, 'w') as f: f.write( json.dumps( dict(i...
DavidAndreev/indico
indico/modules/events/abstracts/models/related_tracks.py
Python
gpl-3.0
2,264
0
# This file is part of Indico. # Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN). # # Indico 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 (a...
reviewed_for_tracks = db.Table( 'reviewed_for_tracks', db.metadata, db.Column( 'abstract_id', db.Integer, db.ForeignKey('event_abstracts.abstracts.id'),
primary_key=True, autoincrement=False, index=True ), db.Column( 'track_id', db.Integer, db.ForeignKey('events.tracks.id'), primary_key=True, autoincrement=False, index=True ), schema='event_abstracts' ) _submitted_for_tracks = db.Table( ...
rafasis1986/EngineeringMidLevel
flaskiwsapp/auth/jwt.py
Python
mit
1,655
0.001208
from flaskiwsapp.users.controllers.userControllers import get_user_by_id, get_user_by_email from flaskiwsapp.snippets.customApi import DUMMY_ERROR_CODE from flask_jwt import JWTError from flask import jsonify from flaskiwsapp.snippets.exceptions.userExceptions import UserInactiveException, UserDoesNotExistsException fr...
try: user = get_user_by_email(email) if user and user.check_password(password.encode('utf-8')): if not user.is_active: raise UserInactiveException(email) return user except (UserDoesNotExistsException, UserInactiveException) as e: raise JWTError(e...
se_dict = {'data': {}} error = {} if isinstance(e, JWTError): error.update({'status': e.status_code}) error.update({'title': e.error}) error.update({'detail': 'Auth Failed: {}'.format(e.description)}) error.update({'code': DUMMY_ERROR_CODE}) response_dict['data'] = error ...
LCOGT/valhalla
valhalla/sciapplications/migrations/0017_timerequest_semester.py
Python
gpl-3.0
605
0.001653
# Generated by Django 2.0.2 on 2018-03-13 23:48 from django.db import migrations, models import django.db
.models.deletion class Migration(migrations.Migration): dependencies = [ ('proposals', '0012_proposal_non_science'), ('sciapplications', '0016_remove_scienceapplication_moon'), ] operations = [ migrations.AddField( model_name='timerequest', name='semester'...
eld=models.ForeignKey(default='2018A', on_delete=django.db.models.deletion.CASCADE, to='proposals.Semester'), preserve_default=False, ), ]
Netuitive/netuitive-client-python
netuitive/sample.py
Python
apache-2.0
1,267
0
class Sample(object): """ A data point of the Metric :param metricId: Metric FQN :type metricId: string :param timestamp: Timestamp for the sample :type timestamp: int :param value: Value of the sample :type value: float :param min: Minimum of the sa...
stamp = timestamp if val is not None: self.val = val if max is not None: self.max =
max if avg is not None: self.avg = avg if cnt is not None: self.cnt = cnt if min is not None: self.min = min if sum is not None: self.sum = sum
antoinecarme/pyaf
tests/model_control/detailed/transf_Anscombe/model_control_one_enabled_Anscombe_Lag1Trend_Seasonal_WeekOfYear_SVR.py
Python
bsd-3-clause
161
0.049689
import t
ests.model_control.test_o
zone_custom_models_enabled as testmod testmod.build_model( ['Anscombe'] , ['Lag1Trend'] , ['Seasonal_WeekOfYear'] , ['SVR'] );
concentricsky/badgr-server
apps/mainsite/management/commands/generate_token_scopes.py
Python
agpl-3.0
970
0.003093
from
django.core.management.base import BaseCommand from django.utils import timezone from mainsite.models import AccessTokenProxy,
AccessTokenScope class Command(BaseCommand): def handle(self, *args, **options): self.stdout.write('Splitting all scopes on tokens') chunk_size = 5000 page = 0 self.stdout.write('Deleting AccessTokenScopes') AccessTokenScope.objects.all().delete() self.s...
thom-at-redhat/cfme_tests
cfme/web_ui/toolbar.py
Python
gpl-2.0
7,066
0.002547
"""A set of functions for dealing with the toolbar buttons The main CFME toolbar is accessed by using the Root and Sub titles of the buttons. Usage: tb = web_ui.toolbar tb.select('Configuration', 'Add a New Host') """ import cfme.fixtures.pytest_selenium as sel from selenium.webdriver.common.by import By fr...
lbar button in the middle of a page change sel.wait_for_ajax() if isinstance(root, dict): root = version.pick(root) if sub is not None and isinstance(sub, dict):
sub = version.pick(sub) root_obj = version.pick({'5.4': 'miq_toolbars', '5.5.0.7': 'ManageIQ.toolbars'}) if sub: search = sub_loc(sub) else: search = root_loc(root) try: idd = sel.get_attribute(search, 'idd') except sel.NoSuchElementException: raise Toolbar...
brainstorm/bcbio-nextgen
bcbio/qc/kraken.py
Python
mit
4,087
0.002447
"""Contamination detection using Kraken. https://ccb.jhu.edu/software/kraken/ """ import os import shutil from bcbio import bam, install, utils from bcbio.distributed.transaction import file_transaction, tx_tmpdir from bcbio.log import logger from bcbio.provenance import do from bcbio.pipeline import datadict as dd f...
p_dir, "kraken_out") out_stats = os.path.join(tx_tmp_dir, "kraken_stats") cat = "zcat" if fn_file.endswith(".gz") else "cat"
cl = ("{cat} {fn_file} | {kraken_cmd} --db {db} --quick " "--preload --min-hits 2 " "--threads {num_cores} " "--out {out} --fastq-input /dev/stdin 2> {out_stats}").format(**locals()) do.run(cl, "kraken: %s" % dd.get_sample_name(dat...
hanezu/cs231n-assignment
assignment1/cs231n/classifiers/linear_classifier.py
Python
mit
5,634
0.009052
import numpy as np from cs231n.classifiers.linear_svm import * from cs231n.classifiers.softmax import * class LinearClassifier(object): def __init__(self): self.W = None def train(self, X, y, learning_rate=1e-3, reg=1e-5, num_iters=100, batch_size=200, verbose=False): """ Train this linea...
ts derivative. Subclasses will override this. Inputs: - X_batch: A numpy array of shape
(N, D) containing a minibatch of N data points; each point has dimension D. - y_batch: A numpy array of shape (N,) containing labels for the minibatch. - reg: (float) regularization strength. Returns: A tuple containing: - loss as a single float - gradient with respect to self.W; an array of ...
ceb8/astroquery
astroquery/utils/progressbar.py
Python
bsd-3-clause
1,948
0
# Licensed under a 3-clause BSD style license - see LICENSE.rst import gzip import sys from io import StringIO from urllib.request import build_opener from astropy.io import fits __all__ = ['chunk_report', 'chunk_read'] def chunk_report(bytes_so_far, chunk_size, total_size): if total_size > 0: percent =...
ut.write('\n') break if report_hook: report_hook(bytes_so_far, chunk_size, total_size) return result_string def retrieve(url, outfile, opener=None, overwrite=False): """ "retrieve" (i.e., download to file) a URL. """ if opener is None: opener = build_open...
ad(page, report_hook=chunk_report) S = StringIO(results) try: fitsfile = fits.open(S, ignore_missing_end=True) except IOError: S.seek(0) G = gzip.GzipFile(fileobj=S) fitsfile = fits.open(G, ignore_missing_end=True) fitsfile.writeto(outfile, clobber=overwrite)
dooleykh/ProjectEuler
4.py
Python
mit
192
0.010417
#Python 2.7 can
didates = set([str(a * b) for a in range(100, 1000) for b in range(100, 1000)]) candidates = filter(lambda x: x == x[::-1], candidates)
print max([int(x) for x in candidates])
awuth/bot-mv-telegram
modules/fa.py
Python
gpl-3.0
3,863
0.001813
from modules.tools import GetHtml from bs4 import BeautifulSoup as bs def search(query): url = 'https://www.filmaffinity.com/es/search.php?stext=%s' % (query.replace(" ", "+").lower()) html = GetHtml(url).content soup = bs(html, "html.parser") list_pelis = soup.findAll("div", {"class": "movie-card mov...
i(d_link_soup) msg['info'] = FormatMsgInfo(info) return msg def FiAf(query):
msg = {'Msg': "", 'error': None} result = search(query) if type(result) is list: msg['list'] = result elif 'Búsqueda' in result.title.text: msg['Msg'] = "nope :(" else: info = GetInfoPeli(result) msg['Msg'] = FormatMsgInfo(info) return msg
jampekka/pydatacube
pydatacube/pcaxis/__init__.py
Python
mit
2,093
0.041627
# encoding: utf-8 from collections import OrderedDict import string from pydatacube.pydatacube import _DataCube import px_reader # A bit scandinavian specific default_translate = dict(zip( u"äöä -", u"aoa__" )) class Sluger(object): def __init__(self, translate=default_translate): self.given_out = {} self.tra...
= slug # Hopefully won't happen while realslug in self.given_out: realslug = realslug + '_' return realslug PxSyntaxError = px_reader.PxSyntaxError def to_cube(pcaxis_data, origin_url=None, Sluger=Sluger): px = px_reader.Px(pcaxis_data) cube = OrderedDict() metadata = OrderedDict() def setmeta(target,...
t hasattr(px, src): return metadata[target] = getattr(px, src) setmeta('title', 'title') setmeta('source', 'source') if origin_url: metadata['origin_url'] = origin_url if hasattr(px, 'last-updated'): metadata['updated'] = getattr(px, 'updated_dt').isoformat() setmeta('note', 'note') cube['metadata'] = ...
matthiasplappert/motion_classification
src/tests/test_fhmm.py
Python
mit
9,592
0.002815
import unittest import timeit import itertools import os from scipy.io import loadmat import numpy as np from hmmlearn.hmm import GaussianHMM import hmmlearn.fhmmc as fhmmc from sklearn.mixture.gmm import log_multivariate_normal_density from toolkit.hmm.impl_hmmlearn import SequentialGaussianFHMM from toolkit.hmm.imp...
[-299.5184, 0.1605], [-313.1509, -4.3836], [ -15.0993, 94.9669], [-102.5866, 65.8045], [ -88.9765, 70.3412], [-135.6746, 54.7751], ...
[-33.4946, 88.8351], [-148.7870, 50.4043]]) means = means.reshape((n_chains, n_states, n_features)) covar = 1.0e+03 * np.array([[9.1968, 3.0656], [3.0656, 1.0219]]) transmat = np.array([[0.3660, 0.0045, 0.0072, 0.6223], ...
abid-mujtaba/BitcoinTracker-python
bitcoin/utilities/push_transactions.py
Python
apache-2.0
1,634
0.005508
# Copyright 2014 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 law or agreed to in wri...
API and stores the relevant information (timestamp, rate, price, amount) from the # relevant entries (exchange) in the sqlite3 database. import sqlite3 import bitcoin import bitcoin.
client from bitcoin.utilities import unix_timestamp def push(log=True): """ Fetches transactions from BitStamp and pushes them in to the sqlite3 database where they are used to determine the latest buy and sell prices. """ conn = sqlite3.connect( bitcoin.get_db() ) cursor = conn.cursor() ...
eadgarchen/tensorflow
tensorflow/compiler/tests/xla_test.py
Python
apache-2.0
9,399
0.005426
# Copyright 2017 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...
f all_tf_types(self): name = '{}.{}'.format(type(self).__name__, self._testMethodName) tf_types = set([dtypes.as_dtype(t)
for t in self._method_types_filter.get(name, set())]) return self._all_tf_types - tf_types @property def float_types(self): name = '{}.{}'.format(type(self).__name__, self._testMethodName) return self._float_types - self._method_types_filter.get(name, set()) @property def float_tf_type...
dondrake/smartframes
tests/test_SmartFrames.py
Python
apache-2.0
5,541
0.005956
# Copyright 2015 Don Drake don@drakeconsulting.com # # 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 a...
s1.float1 = 1 s1.float2 = 2.2 s1.byte = 100 s1.integer = 10000 s1.along
= 10000 s1.short = 10 numRows = 10000 rows = [] start = time.clock() for n in xrange(numRows): rows.append(deepcopy(s1.createRow())) end = time.clock() print "Duration for ", numRows, " is ", (end - start) df = self.sqlCtx.createDataFrame(self...
spierepf/mpf
tests/test_EventManager.py
Python
mit
21,387
0.000047
from MpfTestCase import MpfTestCase class TestEventManager(MpfTestCase): def __init__(self, test_map): super(TestEventManager, self).__init__(test_map) self._handler1_args = tuple() self._handler1_kwargs = dict() self._handler1_called = 0 self._handler2_args = tuple() ...
self._queue.wait() self._queue.clear() def event_handler_clear_queue(self): self._handlers_called.append(self.event_handler_clear_queue) self._queue.clear() def queue_callback(self, *args, **kwargs): self._queue_callback_args = args self._queue_callback_kwargs = ...
self._queue_callback_called += 1 self._handlers_called.append(self.queue_callback) def test_event(self): # tests that a handler responds to a regular event post self.machine.events.add_handler('test_event', self.event_handler1) self.advance_time_and_run(1) self.machi...
sveetch/Sveetoy
project/sitemap.py
Python
mit
4,546
0.00242
# -*- coding: utf-8 -*- """ Sitemap builder """ import json, os from treelib import Tree from optimus.conf import settings class SitemapError(Exception): pass class PageSitemap(object): """ Construct ressource page to build and published sitemap """ def __init__(self, tree, view, with_root=Fal...
names as ressource filename url. * Filenames and directory starting
with "_" are ignored; * Expect an "index.html" file in each directory (except ignored ones) which will take the directory name; Return a treelib.Tree of finded pages """ tree = Tree() tree.create_node("root", "root", data={ 'id': "root", 'link': 'index.html', 'is_dir':...
mick88/samp-client
samp_client/exceptions.py
Python
mit
601
0.001664
class SampError(Exception): pass class RconError(SampError): pass class InvalidRconPas
sword(RconError): pass class ConnectionError(SampError): def __init__(self, socket_error): self.socket_error = socket_error self.err_no = socket_error.args[0] self.message = socket_error.args[1] if self.err_no == 10054: args = 'Server appears to be offline' ...
se: args = socket_error.args super(ConnectionError, self).__init__(args)
BdEINSALyon/resa
bookings/views/occurrences.py
Python
gpl-3.0
11,880
0.002947
import datetime import logging from html import escape import dateutil.parser from dateutil.relativedelta import relativedelta from django.contrib import messages from django.contrib.auth.decorators import login_required, permission_required from django.http import HttpResponseRedirect from django.shortcuts import get...
('resources').items(): if resource.count_available(start_time, end_time) >= count: if not occurrence.pk: o
ccurrence.save() OccurrenceResourceCount.objects.create(occurrence=occurrence, resource=resource, count=count) messages.success( self.request, mark_safe( _('Occurrence créée : <a href=...
joshainglis/pyley
pyley.py
Python
mit
8,373
0.000836
""" pyley Python client for an open-source graph database Cayley :copyright: (c) 2014 by Ziya SARIKAYA @ziyasal. :license: MIT, see LICENSE for more details. """ import json import requests __title__ = 'pyley' __version__ = '0.1.1-dev' __author__ = 'Ziya SARIKAYA @ziyasal' __license__ = 'MIT' __copyright__ = 'Copyri...
raise Exception("Invalid parameter in followr query") self._put("FollowR(%s)", query) return self def build(self): return str(self) class _Vertex(_Path): def All(self): self._put("All()") return self
def GetLimit(self, limit): self._put("GetLimit(%d)", limit) return self class _Morphism(_Path): pass class _QueryDefinition(object): def __init__(self, token, *parameters): self.token = token
Mierzen/Dam-Simulation
simulations/Verification/Part 1/simulation_M2.py
Python
gpl-3.0
385
0.002597
import modules.pumpingsystem as ps import numpy as np import pandas as pd # Inflow into dam inflow = pd.read_csv('M2_dam_inflow_profiles.csv.gz') inflow = np.reshape(inflow['
0 Inflow'].values, (24, 2)) pump_system = ps.PumpSystem('M2') pump_system.add_level(ps.PumpingLevel('0', 1000000, 10, 0, 0, np.zeros((1, 3)), 0, inflow)) pump_system.perform_simulation('1-factor', save=True)
raj808569/homeautomationIOT
d.py
Python
mit
139
0.021583
import RPi.GPIO as GPIO impor
t time GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(3,GPIO.OUT) state=
True GPIO.output(3,True)
mlperf/training_results_v0.5
v0.5.0/google/research_v3.32/gnmt-tpuv3-32/code/gnmt/model/t2t/tensor2tensor/models/research/transformer_vae_test.py
Python
apache-2.0
2,344
0.002133
# coding=utf-8 # Copyright 2018 The Tensor2Tensor 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...
gth = 0 p_hparams = problem_hparams.test_problem_hparams(vocab_size, vocab_size, hparams) hparams.problem_hparams = p_hparams inputs = -1 + np.random.random_integers( vocab_size, size=(batch_siz...
size, size=(batch_size, target_length, 1, 1)) features = { "inputs": tf.constant(inputs, dtype=tf.int32), "targets": tf.constant(targets, dtype=tf.int32), "target_space_id": tf.constant(1, dtype=tf.int32), } tf.train.create_global_step() model = transformer_vae.TransformerAE(hpar...
cloudera/ibis
ibis/backends/base/file/__init__.py
Python
apache-2.0
5,137
0
import abc import warnings from pathlib import Path import pandas as pd import ibis import ibis.expr.types as ir from ibis.backends.base import BaseBackend, Database from ibis.backends.pandas.core import execute_and_reset # Load options of pandas backend ibis.pandas class FileDatabase(Database): def __init__(s...
f, path, expr, **kwargs): pass @abc.abstractmethod def table(self, name, path): pass def database(self, name=None, path=None): if name is None: self.path = path or self.path return super().database(name) if path is None: path = self.root...
raise AttributeError(name) new_name = f"{name}.{self.extension}" if (self.root / name).is_dir(): path /= name elif not str(path).endswith(new_name): path /= new_name self.path = path return super().database(name) def execute(self, expr, param...
rogerhil/flaviabernardes
flaviabernardes/flaviabernardes/shop/views.py
Python
apache-2.0
1,517
0
from django.shortcuts import render from django.views.generic import ListView from ..cms.models import Page from ..utils import JsonView from .models import Original, Print class ShopOriginalsView(ListView): context_object_name = 'shop_items' queryset = Original.objects.filter(disable=False).order_by('-order...
index
item.save() index -= 1
bjuvensjo/scripts
vang/maven/pom.py
Python
apache-2.0
1,319
0.005307
#!/usr/bin/env python3 """ Maven pom utilities. """ from glob import glob from os.path import realpath, normpath from xml.etree.ElementTree import parse NAME_SPACES = {'ns': 'http://maven.apache.org/POM/4.0.0'} def get_pom_paths(root): """ Returns the absolute path of poms that recursively are found in root""" ...
spaces=NAME_SPACES) or e.findtext('version'), 'packaging': e.findtext('ns:packaging', namespaces=NAME_SPACES) or e.findtext('packaging') or 'jar' } if not info['group_id']: info['group_id'] = e.findtext('ns:parent/ns:groupId', namespaces=NAME_SPACES) or e.findtext('parent/groupI
d') if not info['version']: info['version'] = e.findtext('ns:parent/ns:version', namespaces=NAME_SPACES) or e.findtext('parent/version') return info
tonihr/pyGeo
Tiempo/UTC2GPS.py
Python
gpl-2.0
1,716
0.018681
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Created on 2/3/2015 @author: Antonio Hermosilla Rodrigo. @contact: anherro285@gmail.com @organization: Antonio Hermosilla Rodrigo. @copyright: (C) 2015 by Antonio Hermosilla Rodrigo @version: 1.0.0 ''' def UTC2GPS(fecha): ''' @brief: Método para convertir un ...
="Jueves": return 345600+int(fecha.strftime('%H'))*3600+int(fecha.strftime('%M'))*60+int(fecha.strftime('%S')) if name=="Friday" or name=="Viernes": return 432000+int(fecha.strftime('%H'))*3600+int(fecha.strftime('%M'))*60+int(fecha.strftime('%S')) if name=="Saturday" or name=="Sábado": ...
4,10,28,17,0,0))) if __name__=="__main__": main()
asedunov/intellij-community
python/testData/completion/propertyType.py
Python
apache-2.0
128
0.054688
class C(object): def __init__(self): sel
f._x = [] @property def
x(self): return self._x c = C() c.x.app<caret>
qPCR4vir/orange3
Orange/widgets/io.py
Python
bsd-2-clause
4,645
0.001292
from PyQt4 import QtGui, QtCore, QtSvg from PyQt4.QtCore import QMimeData from PyQt4.QtGui import QGraphicsScene, QGraphicsView, QWidget, QApplication from Orange.data.io import FileFormat class ImgFormat(FileFormat): @staticmethod def _get_buffer(size, filename): raise NotImplementedError @stat...
Bytes=True) mimedata = QMimeData() mimedata.setData("image/png", buffer) QApplication.clipboard().setMimeData(mimedata) class SvgFormat(ImgFormat): EXTENSIONS = ('.svg',) DESCRIPTION = 'Scalable Vector Graphics' PRIORITY = 100 @staticmethod def _get_buffer(size, filename):...
Size(int(size.width()), int(size.height()))) return buffer @staticmethod def _get_target(scene, painter, buffer, source): return QtCore.QRectF(0, 0, source.width(), source.height()) @staticmethod def _save_buffer(buffer, filename): pass @staticmethod def _get_exporter(...
menify/sandbox
tags/aql_working_copy_16022008/tools/aql_deftool_cc.py
Python
mit
880
0.034091
import os.path import SCons.Tool import aql #//----------------------------------------------------------------------
-----// _Warning = aql.Warning _Tool = SCons.Tool.Tool #//---------------------------------------------------------------------------// d
ef generate( env ): toolsets = ( "aql_tool_gcc", "aql_tool_msvc", #~ "aql_tool_bcc" ) for tool in toolsets: tool = _Tool( tool ) if tool.exists( env ): tool( env ) return ...
peterhogan/python
logtest.py
Python
mit
177
0.00565
import logging logging.basicConfig(filenam
e='test-logfile.log', level=logging.DEBUG) top = 50 for i in range(top): print(i) logging.info('Loop complet
ed, reached %s' % top)
zeffii/sublimetext_productivity
Packages/User/add_file_to_git.py
Python
mit
843
0
import sublime import sublime_plugin import os import subprocess import threading class AddFileToGit(sublime_plugin.TextCommand): def run(self, edit): view = self.view filepath = view.file_name() dirna
me = os.path.dirname(filepath) print('git add', filepath) # th = GnomeTerminalThread(dirname) # th.start() subprocess.Popen(['git', 'add', filepath, '-f'], cwd=dirname) def enabled(self): return True if self.view.file_name() else False # class GnomeTerminalThread(threadin...
name # threading.Thread.__init__(self) # def run(self): # if self.dirname: # fpc = "--working-directory={0}".format(self.dirname) # subprocess.call(['gnome-terminal', fpc])
wpjesus/codematch
ietf/utils/test_runner.py
Python
bsd-3-clause
23,631
0.005755
# Copyright The IETF Trust 2007, All Rights Reserved # Portion Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). # All rights reserved. Contact: Pasi Eronen <pasi.eronen@nokia.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the fol...
s provided # with the distribution. # # * Neither the name of the Nokia Corporation and/or its # subsidiary(-ies) nor the names of its contributors may be used # to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYR...
BUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSE...
linkedin/naarad
src/naarad/__init__.py
Python
apache-2.0
20,029
0.009486
# coding=utf-8 """ Copyright 2013 LinkedIn Corp. 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 applicable l...
trieval :return: currently always returns CONSTANTS.OK. Maybe enhanced in future to return additional status """ for metric in metrics: self._analyses[test_id].stats_data[metric.label] = metric.summary_stats return CONSTANTS.OK def _create_output_directories(self, analysis): """ Create ...
try: os.makedirs(analysis.output_directory) except OSError as exception: if exception.errno != errno.EEXIST: raise try: resource_directory = os.path.join(analysis.output_directory, analysis.resource_path) os.makedirs(resource_directory) except OSError as exception: i...
dragonloverlord/PyPad
pylibs/menubar.py
Python
gpl-3.0
227
0.004405
__author
__ = 'dragonloverlord' from gi.repository import Gtk def menubar(pad): pad.main_grid.menubar = Gtk.MenuBar() pad.main_grid.menubar.set_hexpand(True) pad.main_grid.attach(pad.ma
in_grid.menubar, 0, 0, 1, 1)
Early-Modern-OCR/emop-dashboard
ext/scripts/failure_results.py
Python
apache-2.0
3,406
0.002055
#!/usr/bin/env python import json import os import re import ConfigParser import logging import requests import sys from urlparse import urljoin config_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'config.ini') Config = ConfigParser.ConfigParser() Config.read(config_path) api_version = Config.ge...
def parse_results(job_queue_results): results = [] for job_queue_result in job_queue_results: result = job_queue_result.splitl
ines()[0] m = re.search('^SLURM JOB [0-9]+:\s(.*)$', result) if m: full_result = m.group(1) parsed_result = re.sub(r'^(.*)(/dh/data/shared/[A-Za-z0-9\/_\.-]+)(.*)$', r'\1FILE\3', full_result) results.append(parsed_result) else: logger.debug(result)...
pikeszfish/Leetcode.py
leetcode.py/SymmetricTree.py
Python
mit
748
0.001337
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return a boolean def isSymmetric(self, root): if not root: return T...
ef isSym(self, left, right): if (not left) and (not right): return True if (not left) and right: return False if left and (not right): return False if left.val != right.val: return False return self.isSym(left.left, right.
right) and self.isSym(left.right, right.left)
PetePriority/home-assistant
homeassistant/components/amcrest/camera.py
Python
apache-2.0
3,307
0
""" This component provides basic support for Amcrest IP cameras. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/camera.amcrest/ """ import logging from homeassistant.components.amcrest import ( DATA_AMCREST, STREAM_SOURCE_LIST, TIMEOUT) from homeas...
The snapshot implementation is
handled by the parent class if self._stream_source == STREAM_SOURCE_LIST['snapshot']: return await super().handle_async_mjpeg_stream(request) if self._stream_source == STREAM_SOURCE_LIST['mjpeg']: # stream an MJPEG image stream directly from the camera websession = ...
openplans/shareabouts-api
src/remote_client_user/migrations/0001_initial.py
Python
gpl-3.0
751
0.002663
# -*- coding: utf-8 -*- from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('oauth2', '__first__'), ] operations = [ migrations.CreateModel( name='Clie
ntPermissions', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('allow_remote_signin', models.BooleanField(default=False)), ('allow_remote_signup', models.BooleanField(default=False)), ...
), ]
lmazuel/azure-sdk-for-python
azure-mgmt-servicebus/azure/mgmt/servicebus/models/resource.py
Python
mit
1,296
0
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
e': {
'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__(self): super(Resource, self).__init__() self.id = None ...
Azure/azure-sdk-for-python
sdk/storage/azure-storage-blob/tests/test_large_block_blob.py
Python
mit
16,306
0.002453
# 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. # --------------------------------------------------------------------...
# Assert self.assertIsNot(len(block_list), 0) self.assertBlobEqual(self.container_name, blob_name, data) self._teardown(FILE_PATH) @pytest.mark.live_test_only @BlobPreparer() def t
est_create_large_blob_from_path_with_md5(self, storage_account_name, storage_account_key): # parallel tests introduce random order of requests, can only run live self._setup(storage_account_name, storage_account_key) blob_name = self._get_blob_reference() blob = self.bsc.get_blob_client...
rooty/django-test
djtest/blog/models.py
Python
gpl-3.0
1,274
0
# -*- coding: utf-8 -*- from django.db import models from django.db.models import signals class Post(models.Model): title = models.CharField(max_length=60) short_body = models.TextField(max_length=255) body = models.TextField() comment_count = models.IntegerField(editable=False, default=0) created...
.CharField(max_length=60) body = models.TextField() created = models.DateTimeField(auto_now_add=True) confirmed = models.BooleanField(default=False) def __unicode__(self): return u'%s: %s' % (self.post, self.aut
hor) def countcommentonsave(sender, instance, created, **kwargs): post = instance.post post.comment_count = \ Comment.objects.filter(post__id=post.id, confirmed=True).count() post.save() def countcommentondelete(sender, instance, **kwargs): post = instance.post post.comment_count = \ ...
JonatanAntoni/CMSIS_5
CMSIS/DSP/SDFTools/sdf/nodes/py/host/FileSink.py
Python
apache-2.0
1,868
0.013383
########################################### # Pro
ject: CMSIS DSP Library # Title: FileSink.py # Description: Node for creating file sinks # # $Date: 30 July 2021 # $Revision: V1.10.0 # # Target Processor: Cortex-M and Cortex-A cores # -------------------------------------------------------------------- */ # # Copyright (C) 2010-2021 ARM Limi...
l rights reserved. # # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the License); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
espressif/esptool
test/efuse_scripts/esp32/test_efuse_script.py
Python
gpl-2.0
2,269
0.003085
# flake8: noqa espefuse(esp, efuses, args, "burn_efuse JTAG_DISABLE 1 DISABLE_SDIO_HOST 1 CONSOLE_DEBUG_DISABLE 1") espefuse(esp, efuses, args, "burn_key flash_encryption ../../images/efuse/256bit --no-protect-key") espefuse(esp, efuses, args, "burn_key_digest ../../secure_images/rsa_secure_boot_signing_key.pem") espef...
() or not efuses["BLOCK1"].is_writeable(): raise esptool.FatalError("BLOCK1 sh
ould be readable and writeable") if efuses["BLOCK2"].get_meaning() != "cb 27 91 a3 71 b0 c0 32 2b f7 37 04 78 ba 09 62 22 4c ab 1c f2 28 78 79 e4 29 67 3e 7d a8 44 63": raise esptool.FatalError("BLOCK2 was not set correctly") if not efuses["BLOCK2"].is_readable() or efuses["BLOCK2"].is_writeable(): raise esp...
dmpetrov/dataversioncontrol
dvc/system.py
Python
apache-2.0
3,817
0
import errno import logging import os import platform import stat import sys logger = logging.getLogger(__name__) if os.name == "nt" and sys.version_info < (3, 8): # NOTE: using backports for `os.path.realpath` # See https://bugs.python.org/issue9949 for more info. # pylint: disable=import-error, no-name...
from dvc.utils.fs import umask source, link_name = os.fspath(source),
os.fspath(link_name) system = platform.system() if system == "Darwin": System._reflink_darwin(source, link_name) elif system == "Linux": System._reflink_linux(source, link_name) else: raise OSError( errno.ENOTSUP, f"ref...
mattpap/sympy-polys
sympy/mpmath/tests/test_functions2.py
Python
bsd-3-clause
66,026
0.022991
import math from sympy.mpmath import * def test_bessel(): mp.dps = 15 assert j0(1).ae(0.765197686557966551) assert j0(pi).ae(-0.304242177644093864) assert j0(1000).ae(0.0247866861524201746) assert j0(-25).ae(0.0962667832759581162) assert j1(1).ae(0.440050585744933516) assert j1(pi).ae(0.284...
26702430692j) assert hankel1(-1,0.5).ae(-0.2422684576748738864+1.4714723926702430692j) assert hankel1(1.5,0.5).ae(0.0917016996256513026-2.5214655504213378514j) assert hankel1(1.
5,3+4j).ae(0.0066806866476728165382-0.0036684231610839127106j) assert hankel2(0,0.5).ae(0.93846980724081290423+0.44451873350670655715j) assert hankel2(1,0.5).ae(0.2422684576748738864+1.4714723926702430692j) assert hankel2(-1,0.5).ae(-0.2422684576748738864-1.4714723926702430692j) assert hankel2(1.5,0.5)....
GiorgosMethe/SLP-Demand_Decomposition_Tool
test.py
Python
mit
3,350
0.02806
import os import random import matplotlib.pyplot as plt import numpy as np import extra import lpd import synthetic def main(): # """ # Main function of test python module # """ # random.seed(os.urandom(345634)) # initialize random generator # t = np.linspace(0.0, 24.0, 96.0) # define the time axis of a day,...
t, p_d, consumption_axis, p_k, p_t_0) # synthetic_profile_1 = lpd.synthetic_profile(D, t, p_d, consumption_axis, p_k, p_t_0) # # expected value of D processes # q_e_e = lpd.infer_q_e(t, p_t_0, p_d, E_k, D) # # plot # plt.step(t, synthetic_profile, "g-") # plt.step(t, q_e_e, "b--") # # """ # 2nd Approach, s...
s is a continuous propapibility density function # """ # # synthetic profile of D processes # ts, cs = lpd.continous_synthetic_profile(D, t, p_d, consumption_axis, p_k, p_t_0) # plt.step(ts / len(t) * t[-1], cs, where='post', c='r') # plt.xlim(0, 24.0) # plt.legend(["synthetic", "expected", "continuous"], loc=0) ...
rohitranjan1991/home-assistant
homeassistant/components/zha/entity.py
Python
mit
11,331
0.000706
"""Entity for Zigbee Home Automation.""" from __future__ import annotations import asyncio from collections.abc import Awaitable import functools import logging from typing import Any from homeassistant.const import ATTR_NAME from homea
ssistant.core import CALLBACK_TYPE, Event, callback from homeassistant.helpers import entity from homeassistant.helpers.debounce import Debouncer from homeassistant.helpers.device_registry import CONNECTION_ZIGBEE from homeassistant.helpers.dispatcher import ( async_dispatcher_connect, async_dispatcher_sen
d, ) from homeassistant.helpers.event import async_track_state_change_event from homeassistant.helpers.restore_state import RestoreEntity from .core.const import ( ATTR_MANUFACTURER, ATTR_MODEL, DATA_ZHA, DATA_ZHA_BRIDGE_ID, DOMAIN, SIGNAL_GROUP_ENTITY_REMOVED, SIGNAL_GROUP_MEMBERSHIP_CHANG...
leyyin/university
computational-logic/src-number-converter/ui/console.py
Python
mit
5,104
0.001567
""" @author: Daniel Butum, Group 911 """ from domain.number import Number, NumberException from utils.number import convert_to_int class Console: def __init__(self): pass def run(self): """ Run the console gui """ # print initial help menu print(self._get_hel...
menu """ return """Basic operations and conversions by Daniel Butum 1. Add two numbers 2. Subtract two numbers 3. Multiplication by one digit 4. Division by one digit Base conversion using: 5. substitution method 6. successive divisions method 7. rapid conve...
""" Improved input Return: string - user command """ try: return input(message).strip() except KeyboardInterrupt: # handle CTRL + C interrupt return exit('CTRL + D') except EOFError: # handle CTRL + D return exit('CTRL + ...
yangke/cluehunter
parse/LineOfCode.py
Python
gpl-3.0
1,542
0.018158
''' Created on Sep 6, 2015 @author: yangke ''' import re class LineOfCode: def __init__(self, line, func_call_info): lineNumPattern = re.compile(r'^[1-9][0-9]*') lineNumStr = re.findall(lineNumPattern,line)[0] self.codestr_with_comments = line.lstrip(lineNumStr)#note that there ar...
_(self,obj): return isinstance(obj,LineOfCode) and str(self)==str(o
bj)\ and self.func_call_info == obj.func_call_info #and self.expand_code_list == obj.expand_code_list def __hash__(self): return hash(str(self))^hash(self.func_call_info)
mitdbg/aurum-datadiscovery
ontomatch/no_matcher.py
Python
mit
4,608
0.003255
import time from nltk.corpus import stopwords from ontomatch import glove_api from dataanalysis import nlp_utils as nlp from ontomatch.matcher_lib import get_ban_indexes, remove_banned_vectors from knowledgerepr import fieldnetwork from modelstore.elasticstore import StoreHandler from ontomatch import ss_utils as SS ...
if token not in stopwords.words('english'): sv = glove_api.get_embedding_for_word(token) if sv is not None: svs.append(sv) names.append(('class', (reference_name, original_cl_name), svs)) print("N equals: " + str(len(names))) pos_matchings...
ames)): for idx_rel in range(0, num_attributes_inserted): # Compare only with classes ban_index1, ban_index2 = get_ban_indexes(names[idx_rel][1][2], names[idx_class][1][1]) svs_rel = remove_banned_vectors(ban_index1, names[idx_rel][2]) svs_cla = remove_banned_vectors(ban_ind...
rohitranjan1991/home-assistant
homeassistant/components/synology_srm/device_tracker.py
Python
mit
4,397
0.001137
"""Device tracker for Synology SRM routers.""" from __future__ import annotations import logging import
synology_srm import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as DEVICE_TRACKER_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import ( CONF_HOST, CONF_PASSWORD, CONF_PORT,
CONF_SSL, CONF_USERNAME, CONF_VERIFY_SSL, ) from homeassistant.core import HomeAssistant import homeassistant.helpers.config_validation as cv from homeassistant.helpers.typing import ConfigType _LOGGER = logging.getLogger(__name__) DEFAULT_USERNAME = "admin" DEFAULT_PORT = 8001 DEFAULT_SSL = True DEFAULT_...
ShaheenHossain/eagle-medical
medical_medicament/__manifest__.py
Python
agpl-3.0
1,827
0
# -*- coding: utf-8 -*- ############################################################################## # # This file is part of medical_medicament, # an Odoo module. # # Copyright (c) 2015 ACSONE SA/NV (<http://acsone.eu>) # # medical_medicament is free software: # you can redistribute it and/or mod...
nt_view.xml', 'views/medical_drug_form_view.xml', 'views/medical_drug_route_view.xml', ],
'installable': True, 'application': True, }
harterj/moose
python/mms/ConvergencePlot.py
Python
lgpl-2.1
3,697
0.005139
#* This file is part of the MOOSE framework #* https://www.mooseframework.org #* #* All rights reserved, see COPYRIGHT for full restrictions #* https://github.com/idaholab/moose/blob/master/COPYRIGHT #* #* Licensed under LGPL 2.1, please see LICENSE for details #* https://www.gnu.org/licenses/lgpl-2.1.html import matp...
ted_points is not No
ne: coeffs = self._fit(x[-num_fitted_points:], y[-num_fitted_points:]) else: coeffs = self._fit(x, y) slope = coeffs[0] intercept = coeffs[1] self.label_to_slope.update({this_label:slope}) self.label_to_intercept.update({this_l...
dsoprea/PySecure
pysecure/log_config.py
Python
gpl-2.0
382
0.002618
from logging import getLogger, Formatter, DEBUG, WARNING, StreamHandler from pysecure.config import IS_DEVELOPMENT defaul
t_logger = getLogger() default_logger.se
tLevel(DEBUG if IS_DEVELOPMENT else WARNING) log_console = StreamHandler() log_format = '%(name)-12s %(levelname)-7s %(message)s' log_console.setFormatter(Formatter(log_format)) default_logger.addHandler(log_console)
bvancea/data-mining-project-2014
lsh/code/check.py
Python
gpl-3.0
1,087
0.00092
#!/usr/bin/env python import sys from sets import Set true_dups = Set() reported_dups = Set() if len(sys.argv) < 3: print "Usage: python check.py reported_duplicates true_duplicates" exit(-1) reported_duplicates_file = sys.argv[1] true_duplicates_file = sys.argv[2] with open(true_duplicates_file, "r") as ...
dd(line.strip()) tp = fp = fn = 0 for pair in reported_dups: if pair in true_dups: tp += 1 else: fp += 1 for pair in true_dups: if pair not in reported_dups:
fn += 1 print "TP =", tp, "FP =", fp, "FN =", fn if tp + fp == 0: precision = 0 else: precision = 1.0 * tp / (tp + fp) if tp + fn == 0: recall = 0 else: recall = 1.0 * tp / (tp + fn) if precision + recall == 0: print ("Both precision and recall are 0.") else: f1 = 2.0 * precision * recall...
bendk/thesquirrel
editor/video.py
Python
agpl-3.0
2,532
0.00158
# thesquirrel.org # # Copyright (C) 2015 Flying Squirrel Community Space # # thesquirrel.org is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published by the # Free Software Foundation, either version 3 of the License, or (at your # option) any la...
ct() else: return None class HTML5VideoRule(object): valid_extensions = set(['ogv', 'ogg', 'mp4', 'm4v', 'webm']) name = 'html5' def test(self, url): if url.rsplit('.', 1)[-1] in self.valid_extensions: return { 'url': url, 'video_id':...
le('youtube', 'youtu.be', r'/(?P<video_id>[\w-]+)'), VideoHostRule('vimeo', 'vimeo.com', r'/(channels/\w+/)?(?P<video_id>\d+)'), VideoHostRule('dailymotion', 'dailymotion.com', r'/video/(?P<video_id>[\w-]+)'), HTML5VideoRule(), ] def render_video_for_url(url): for rule in video_rules:...
deralexxx/maltego-viper
src/viper/transforms/common/entities.py
Python
gpl-2.0
804
0.011194
#!/usr/bin/env python from canari.maltego.message import Entity, EntityField, EntityFieldType, MatchingRule __author__ = 'jaegeral' __copyright__ = 'Copyright 2014, Viper Project' __credits__ = [] __license__ = 'GPL' __version__ = '0.1' __maintainer__ = 'jaegeral' __email__ = 'mail@alexanderjaeger.de' __status__ = '...
s viperentity(Entity): _namespace_ = 'viper' @EntityField(
name='hashtype', propname='hashtype', displayname='Hash Type') class viperhash(viperentity): pass #TODO: Remove class MyViperEntity(viperentity): pass class viperfile(viperentity): pass class vipername(viperentity): pass class vipertag(viperentity): pass
catsky/rebang
1/BBS/myskoda/myskoda/1/common.py
Python
mit
12,534
0.014571
# -*- coding: utf-8 -*- import logging import os.path import re import tornado.web from time import mktime, time from datetime import datetime, timedelta import tenjin from tenjin.helpers import * from tenjin.html import nl2br from setting import * import pylibmc mc = pylibmc.Client() ### def cur_time(): retur...
for x in newdict.iteritems()) def decode_dict(my_string): return dict(x.split("\x1f") for x in my_string.split("\x1e")) def dict2utf8(
my_dict): newdict = {} for k in my_dict: newdict[str(k)] = str(my_dict[k]).encode('utf-8') #newdict[str(k)] = my_dict[k].encode('utf-8') if isinstance(my_dict[k], unicode) else str(my_dict[k]) return newdict _re_html=re.compile('<.*?>|\&.*?\;', re.UNICODE|re.I|re.M|re.S) def textilize(s): ...