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
mehmoodz/Influenzr
publishers/resources/simple_ws.py
Python
mit
818
0.01956
from tornado import websocket, web, ioloop, autoreload import json import sys new_msg='' old_msg='' def send_response(): print 'msg' if new_msg<>old_msg: print new_msg class SocketHandler(websocket
.WebSocketHandler): ''' websocket handler ''' def open(self): ''' ran once an open ws connection is made''' self.send('Opened') socket=self def send(self,message): self.write_message(message) def on_close(s
elf): ''' on close event, triggered once a connection is closed''' self.send('Closed') app = web.Application([ (r'/ws', SocketHandler), ]) if __name__ == '__main__': app.listen(8888) autoreload.add_reload_hook(send_response) autoreload.start() new_msg='boo' ioloop.IO...
python-provy/provy
provy/more/debian/security/iptables.py
Python
mit
10,980
0.004098
from provy.core import Role from provy.more.debian.package.aptitude import AptitudeRole ''' Roles in this namespace are meant to provide `iptables <http://www.netfilter.org/>`_ management utilities for Debian distributions. ''' class IPTablesRole(Role): ''' This role provides `iptables <http://www.netfilter....
rom provy.more.debian import IPTablesRole class MySampleRole(
Role): def provision(self): with self.using(IPTablesRole) as iptables: iptables.allow(port=11211, direction="out", protocol="udp") # allow UDP connections to an external Memcached server. ''' self.__change_rule("ACCEPT", port, direction, protoc...
rmcauley/rainwave
api_requests/admin/enable_perks.py
Python
gpl-2.0
1,012
0.003953
from libs import db import
api.web from api.urls import handle_api_url from api import fieldtypes from api.exceptions import APIException fro
m libs import config PRIVILEGED_GROUP_IDS = (18, 5, 4) @handle_api_url("enable_perks_by_discord_ids") class UserSearchByDiscordUserIdRequest(api.web.APIHandler): auth_required = False sid_required = False description = "Accessible only to localhost connections, for wormgas." help_hidden = True fie...
mindriot101/bokeh
examples/reference/models/Diamond.py
Python
bsd-3-clause
815
0.001227
import numpy as np from bokeh.models import ColumnDataSource, Plot, LinearAxis, Grid from bokeh.models.markers import Diamond from bokeh.io import curdoc, show N = 9 x = np.
linspace(-2, 2, N) y = x**2 sizes = np.linspace(10, 20, N) source = ColumnDataSource(dict(x=x, y=y, sizes=sizes)) plot = Plot( title=None, plot_width=300, plot_height=300, h_symmetry=False, v_symmetry=False, min_border=0, toolbar_location=None) glyph = Diamond(x="x", y="y", size="sizes", line_color="#1c9099"...
d_layout(Grid(dimension=0, ticker=xaxis.ticker)) plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker)) curdoc().add_root(plot) show(plot)
pureqml/qmlcore
test/lit.py
Python
mit
381
0.002625
#!/usr/bin/env python # https://medium.com/@mshockwave/using-llvm-lit-out
-of-tree-5cddada85a78 # To run lit-based test suite: # cd xyz/qmlcore/test && ./lit.py -va . from lit.main import main import os if __name__ == '__main__': if not os.path.exists(".cache/core.I
tem"): print("Note that first run may take quite a while .cache/core.* is populated...") main()
vfaronov/turq
tests/conftest.py
Python
isc
3,212
0
import socket import subprocess import sys import time import h11 import pytest import requests @pytest.fixture def turq_instance(): return TurqInstance() class TurqInstance: """Spins up and controls a live instance of Turq for testing.""" def __init__(self): self.host = 'localhost' #...
self.extra_args = [] self.wait = True self._process = None self.console_output = None def __enter__(self): args = [sys.executable, '-m', 'turq.main', '--bind', self.host, '--mock-port', str(self.mock_port), '--editor-port', str(self.editor_port)...
args += self.extra_args self._process = subprocess.Popen(args, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) if self.wait: self._wait_for_server() return self def _...
kb2ma/adagios
adagios/pnp/views.py
Python
agpl-3.0
1,427
0
# -*- coding: utf-8 -*- # # Adagios is a web based Nagios configuration interface # # Copyright (C) 2010, P
all Sigurdsson <palli@opensource.is> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distri...
General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from django.core.context_processors import csrf from django.shortcuts import render_to_response from django.shortcuts import Http...
saltmine/redis-gadgets
tests/test_set_theory.py
Python
mit
17,869
0.000112
""" Tests for set_theory cached multi-set query library """ import time import redis from nose.tools import (raises, eq_, with_setup, assert_in, assert_not_in, assert_not_equal, make_decorator) # TODO: prefix test keys for keyspace find and delete instead of flushing # TODO: Add missing test do...
tTheory(db) temp_hash_control = st.zset_fetch([('TEST_1',), ('TEST_3',)], return_key=True, ttl=5, operator="union") control_results = st.zset_fetch([(temp_hash_control,), ('TEST_2',)], start=0, ...
) eq_('19', control_results[0], "GUARD: 19 not first element of %s" % control_results) # now for the actual weighting experiment # now make a weighted union to test TEST_1 trumps TEST_3 temp_hash_weighted = st.zset_fetch([('TEST_1', 1000), ('TEST_3',)], re...
google-code-export/dojango
dojango/decorators.py
Python
bsd-3-clause
5,423
0.007376
from django.http import HttpResponseNotAllowed, HttpResponseServerError from django.utils import simplejson as json from util import to_json_response from util import to_dojo_data try: from functools import wraps except ImportError: from django.utils.functional import wraps # Python 2.3, 2.4 fallback. def e...
ly nested objects or even classes inside json_ret = to_json_response(ret, func_name, use_iframe) except E
xception, e: print '\n\n===============Exception=============\n\n'+str(e)+'\n\n' print ret print '\n\n' return HttpResponseServerError(content=str(e)) return json_ret
Boussadia/weboob
modules/societegenerale/browser.py
Python
agpl-3.0
4,686
0.001707
# -*- coding: utf-8 -*- # Copyright(C) 2010-2011 Jocelyn Jaubert # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at yo...
CardsList): for card_link in self.page.iter_cards(): self.location(card_link) transactions += list(self.page.iter_transactions(coming=True)) elif self.is_on_page(AccountHistory): transactions += list(self.page.iter_transactions(coming=(accoun
t.type == account.TYPE_CARD))) else: self.logger.warning('This account is not supported') def key(tr): # Can't compare datetime and date, so cast them. try: return tr.rdate.date() except AttributeError: return tr.rdate ...
we-inc/mms-snow-white-and-the-seven-pandas
webserver/apps/users/migrations/0001_initial.py
Python
mit
2,969
0.004715
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-10-27 19:05 from __future__ import unicode_literals import django.contrib.auth.models import django.contrib.auth.validators from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): initial = True ...
length=254, verbose_name='Email')), ('first_name', models.CharField(max_length=50, verbose_name='First Name')), ('last_name', models.CharField(max_length=50, verbose_name='Last Name')), ('phone', models.CharField(max_length=20, verbose_name='Phone')), ('gr...
er belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')), ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set'...
open-telemetry/opentelemetry-python
exporter/opentelemetry-exporter-otlp-proto-http/src/opentelemetry/exporter/otlp/proto/http/__init__.py
Python
apache-2.0
2,513
0.000398
# Copyright The OpenTelemetry 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 ...
TER_OTLP_TRACES_CERTIFICATE` - :envvar:`OTEL_EXPORTER_OTLP_TIMEOUT` - :envvar:`OTEL_EXPORTER_OTLP_PROTOCOL` - :envvar:`OTEL_EXPORTER_OTLP_HEADERS` - :envvar:`OTEL_EXPORTER_OTLP_ENDPOINT` - :envvar:`OTEL_EXPORTER_OTLP_COMPRESSION` - :envvar:`OTEL_EXPORTER_OTLP_CERTIFICATE` .. _OTLP: https://github.com/open-telemetry/op...
import trace from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter from opentelemetry.sdk.resources import Resource from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor # Resource can be required for some back...
ychen820/microblog
y/google-cloud-sdk/platform/google_appengine/lib/django-1.5/django/forms/widgets.py
Python
bsd-3-clause
35,106
0.002193
""" HTML Widget classes """ from __future__ import absolute_import, unicode_literals import copy import datetime from itertools import chain try: from urllib.parse import urljoin except ImportError: # Python 2 from urlparse import urljoin from django.conf import settings from django.forms.util import fla...
media_attrs = media.__dict__ else: media_attrs = kwargs self._cs
s = {} self._js = [] for name in MEDIA_TYPES: getattr(self, 'add_' + name)(media_attrs.get(name, None)) # Any leftover attributes must be invalid. # if media_attrs != {}: # raise TypeError("'class Media' has invalid attribute(s): %s" % ','.join(media_attrs.keys(...
hackcyprus/jobber
schema/versions/26e3340ce799_create_categories_ta.py
Python
mit
961
0.001041
"""create categories table Revision ID: 26e3340ce799 Revi
ses: 34a1034caa3b Create Date: 2013-11-02 10:46:23.617628 """ from alembic import op import sqlalchemy as sa import json revision = '26e3340ce799' down
_revision = '34a1034caa3b' # Load categories fixture file. # TODO: create an abstraction for this. with open('schema/initial/categories.json') as fixture: categories = json.loads(fixture.read()) def upgrade(): """Creates and populates the `categories` table.""" columns = ( sa.Column('id', sa.Inte...
trep/opentrep
gui/django/webapps/opentrep_w_db/api/handlers.py
Python
lgpl-2.1
1,494
0.031459
from piston.handler import BaseHandler import json # class TrepHandler (BaseHandler): def read (self, r
equest, airportCodeURL=None): # Default values, corresponding to the default inventory dump # file loaded by the inventory server airportCode = 'LHR' # Extract the requested action from the query string (if any) airportCodeQuery = request.GET.get ('ac') # If the airport parameter i
s given within the URL (e.g., # http://localhost:8000/api/display/place/SFO) # take it into account if airportCodeQuery: airportCode = airportCodeQuery # If the airport parameter is given as part of the query # string (e.g., http://localhost:8000/api/display/place?ac=LAX) # take it into account. It has the...
pkimber/crm
example_crm/base.py
Python
apache-2.0
6,691
0
# -*- encoding: utf-8 -*- """ Django settings """ from django.core.urlresolvers import reverse_lazy DEBUG = True TESTING = False SESSION_COOKIE_SECURE = False CSRF_COOKIE_SECURE = False ADMINS = ( ('admin', 'code@pkimber.net'), ) MANAGERS = ADMINS # Local time zone for this installation. Choices can be found h...
EPT_REDIRECTS': False, 'ENABLE_STACKTRACES': True, } # http://www.django-rest-framework.org/api-guide/authentication#tokenauthentication REST_FRAMEWORK = { 'COERCE_DECIMAL_TO_STRING': True, # not sure if this is required or not #
'DATETIME_FORMAT': '%Y%m%dT%H%M%SZ', 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAdminUser', ), 'TEST_REQUEST_DEFAULT_FORMAT': 'json', } # https://github.com/johnsensible/d...
Antelox/mhn
server/mhn/common/clio.py
Python
lgpl-2.1
16,259
0.004182
""" Clio Mnemosyne Client Library ThreatStream 2014 """ import pymongo from dateutil.parser import parse as parse_date from collections import Counter from bson import ObjectId, son import json import datetime class Clio(): """ Main interface for Clio - Mnemosyne Client Library - Usage: clio = Clio...
ifier', 'date', 'event_count',) def get_count(self, identifi
er, date=None): query = {'identifier': identifier} if date: query['date'] = date return int(sum([rec['event_count'] for rec in self.collection.find(query)])) class Session(ResourceMixin): collection_name = 'session' expected_filters = ('protocol', 'source_ip', 'source_port'...
pydanny/dj-paginator
example_project/example_project/settings.py
Python
bsd-3-clause
2,669
0
""" Django settings for example_project project. Generated by 'django-admin startproject' using Django 1.8.3. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Bu...
ect.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME':
os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ ...
edwardbadboy/vdsm-ubuntu
tests/netinfoTests.py
Python
gpl-2.0
7,176
0
# # Copyright 2012 Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in th...
bonding_path = os.path.join(di
r_fixture, 'jbond/bonding') os.makedirs(bonding_path) with open(os.path.join(bonding_path, 'slaves'), 'w') as f: f.write('me0 me1') return dir_fixture def _config_setup(self): """ Returns an instance of a config stub. With patterns: * hid* fo...
salv-orlando/MyRepo
nova/tests/api/ec2/test_middleware.py
Python
apache-2.0
4,748
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compli...
l_forbid) def tearDown(self): # pylint: disable=C0103 utils.clear_time_override() super(LockoutTe
stCase, self).tearDown() def _send_bad_attempts(self, access_key, num_attempts=1): """Fail x.""" for i in xrange(num_attempts): req = webob.Request.blank('/?AWSAccessKeyId=%s&die=1' % access_key) self.assertEqual(req.get_response(self.lockout).status_int, 403) def _is_l...
zedshaw/learn-python3-thw-code
ex52/gothonweb/gothonweb/planisphere.py
Python
mit
4,537
0.002425
class Room(object): def __init__(self, name, description): self.name = name self.description = description self.paths = {} def go(self, direction): return self.paths.get(direction, None) def add_paths(self, paths): self.paths.update(paths) central_corridor = Ro...
Gothons of Planet Percal #25 have invaded your ship and destroyed your entire crew. You are the last surviving member and your last mission is to get the neutron destruct bomb from the Weapons Armory, put it in the bridge, and blow the ship up after getting i
nto an escape pod. You're running down the central corridor to the Weapons Armory when a Gothon jumps out, red scaly skin, dark grimy teeth, and evil clown costume flowing around his hate filled body. He's blocking the door to the Armory and about to pull a weapon to blast you. """) laser_weapon_armory = Room("Las...
ghostwords/localore
localore/home/migrations/0024_homepagefeaturedpage.py
Python
mpl-2.0
1,191
0.004198
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import modelcluster.fields class Migration(migrations.Migration): dependencies = [ ('wagtailcore', '0028_merge'), ('home', '0023_
remove_homepage_live_feed_intro'), ] operations = [ migrations.CreateModel( name='HomePageFeaturedPage', fields=[ ('id', mo
dels.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)), ('sort_order', models.IntegerField(blank=True, null=True, editable=False)), ('title', models.CharField(blank=True, max_length=255, help_text='Leave blank to use page title.')), ('sub...
Ruide/angr-dev
angr/angr/factory.py
Python
bsd-2-clause
18,703
0.006683
from .sim_state import SimState from .calling_conventions import DEFAULT_CC, SimRegArg, SimStackArg, PointerWrapper from .callable import Callable import logging l = logging.getLogger("angr.factory") _deprecation_cache = set() def deprecate(name, replacement): def wrapper(func): def inner(*args, **kwargs)...
ookNode(addr, size, self._project.hooked_by(addr)) else: return self.block(addr, **block_opts).codenode # pylint: disable=no-member def successors(self, state, ad
dr=None, jumpkind=None, inline=False, default_engine=False, engines=None, **kwargs): """ Perform execution using any applicable engine. Enumerate the current engines and use the first one that works. Return a SimSuccessors object classi...
tokuhirom/ycmd
ycmd/handlers.py
Python
gpl-3.0
7,766
0.039403
#!/usr/bin/env python # # Copyright (C) 2013 Google Inc. # # This file is part of YouCompleteMe. # # YouCompleteMe 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...
rget', None ) if completer_target == 'identifier': return _server_state.GetGeneralCompleter()
.GetIdentifierCompleter() elif completer_target == 'filetype_default' or not completer_target: return _server_state.GetFiletypeCompleter( request_data[ 'filetypes' ] ) else: return _server_state.GetFiletypeCompleter( [ completer_target ] ) @atexit.register def ServerShutdown(): _logger.info( 'Server shu...
williamjacksn/rainwave
api_requests/admin_web/developer.py
Python
gpl-2.0
4,050
0.021975
from time import time as timestamp import hashlib from api.web import APIHandler from api.exceptions import APIException from api.server import handle_api_url from libs import config from libs import db @handle_api_url("test/create_anon_tuned_in/(\d+)") class CreateAnonTunedIn(APIHandler): description = "Creates a ...
and user_id < 2: user_id = user_id + 1 db.c.update("INSERT INTO phpbb_users (username, user_id, group_id) VALUES ('Test" + str(user_id) + "', %s, 5)", (user_id,)) elif not user_id: user_id = 2 db.c.update("INSERT INTO phpbb_users (username, user_id, group_id)
VALUES ('Test" + str(user_id) + "', %s, 5)", (user_id,)) self.set_cookie(config.get("phpbb_cookie_name") + "_u", user_id) session_id = db.c.fetch_var("SELECT session_id FROM phpbb_sessions WHERE session_user_id = %s", (user_id,)) if not session_id: session_id = hashlib.md5(repr(timestamp())).hexdigest() db...
YaoQ/faceplusplus-demo
recognition.py
Python
gpl-2.0
1,492
0.015416
#!/usr/bin/env python2 # Import system libraries and define helper functions import time import sys import os import os.path from pprint import pformat # First import the API class from the SDK from facepp import API from facepp import File def print_result(hint, result): def encode(obj): if type(obj) is ...
e(i) for i in obj] return obj print hint result = encode(result) print '\n'.join([' ' + i for i in pformat(result, width = 75).split('\n')]) def init(): fdir = os.path.dirname(__file__) with open(os.path.join(fdir, 'apikey.cfg')) as f: exec(f.read()) srv = locals().get('SERVE...
ath>' sys.exit() group = sys.argv[1] IMAGE_DIR = sys.argv[2] rst = api.recognition.identify( group_name = group,img = File(IMAGE_DIR)) #print 'The person with highest confidence:', \ # rst['face'][0]['candidate'][0]['person_name'] if rst['face']: print 'The person with highest confidence:', \ rs...
FRBs/DM
frb/surveys/dlsurvey.py
Python
bsd-3-clause
5,919
0.008616
""" DataLab survey class. Gets data from any survey available through the NOAO datalab-client. """ import pdb import numpy as np import warnings from astropy.table import Table from astropy import units import warnings import sys, os try: from dl import queryClient as qc, authClient as ac from dl.helpers.util...
ut=120, verbose=False): """ Get images from the catalog if available for a given fov and band. Args: imsize (Quantity): FOV for the desired image band (str): Band for the image (e.g. 'r') timeout (int, optional): Time to wait in seconds before tim...
c.value fov = imsize.to(units.deg).value if band.lower() not in self.bands and band not in self.bands: raise TypeError("Allowed filters (case-insensitive) for {:s} photometric bands are {}".format(self.survey,self.bands)) table_cols, col_vals, bandstr = self._parse_cat_band...
pabulumm/neighbors
budget/forms.py
Python
bsd-3-clause
408
0.046569
from .m
odels import Budget, Expense from django import forms class BudgetForm(forms.ModelForm): class Meta: model = Budget fields = ( 'title', 'residence_fee', 'neighborhood', ) class ExpenseForm(forms.ModelForm): class Meta: model = Expense fields = ( 'title', 'descriptio...
'types', 'budget', )
deluxghost/DelogX
DelogX/defaults/plugins/delog_readmore/__init__.py
Python
lgpl-3.0
1,320
0
# -*- coding: utf-8 -*- import re from DelogX.utils.i18n import I18n from DelogX.utils.path import Path from DelogX.utils.plugin import Plugin class DelogReadMore(Plugin): i18n = None def run(self): conf = self.blog.default_conf self.i18n = I18n( Path.format_url(s...
return content_split = re.split(r'<[Hh][Rr](?:\
s+\/)?>', post.content, 1) if len(content_split) == 2: summary, more = content_split else: summary = content_split[0] more = '' post_url = self.blog.runtime.get('url_prefix.post') post_url = Path.format_url(post_url, Path.urlencode(post.url)) ...
coufon/neon-distributed
neon/backends/kernels/cuda/roipooling.py
Python
apache-2.0
9,019
0.000887
# ---------------------------------------------------------------------------- # Copyright 2016 Nervana Systems Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.o...
nthreads); index += blockDim.x * gridDim.x){ // (c, h, w, n) coords in bottom data on feature map int n = index % img_count; int w = (index / img_count) % width; int h = (index / img_count / width) % height; int c = index / img_count/ width / height; float gradient = 0; ...
const float* offset_bottom_rois = bottom_rois + roi_n * 5; int roi_batch_ind = offset_bottom_rois[0]; // Skip if ROI's batch index doesn't match n if (n != roi_batch_ind) { continue; } int roi_start_w = round(offset_bottom_rois[1] * spatial_scale); ...
ruchee/vimrc
vimfiles/bundle/vim-python/submodules/pylint/tests/functional/d/defined_and_used_on_same_line.py
Python
mit
703
0.01707
"""Check for definitions and usage happ
ening on the same line.""" #pylint: disable=missing-docstring,multiple-statements,no-absolute-import,parameter-unpacking,wrong-import-position,unnecessary-comprehension from __future__ import print_function print([index
for index in range(10)]) print((index for index in range(10))) FILTER_FUNC = lambda x: not x def func(xxx): return xxx def func2(xxx): return xxx + func2(1) import sys; print(sys.exc_info()) for i in range(10): print(i) j = 4; LAMB = lambda x: x+j FUNC4 = lambda a, b: a != b # test https://www.logila...
JA-VON/python-helpers-msbm
converter.py
Python
mit
10,280
0.01216
# coding=utf-8 __author__ = 'javon' import sys rdfTemplate = """<?xml version="1.0" encoding="UTF-8"?> <rdf:RDF xmlns="http://vocab.cdmk-caribbean.net/cdmk#" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" xmlns:owl="http://www.w3.org/2002/07/owl#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns...
:created rdf:datatype="xsd:http://www.w3.org/2001/XMLSchema#dateTime">2016-03-31T04:32:05Z</dct:created> <dct:modified rdf:datatype="http://www.w3.org/2001/XMLSchema#dateTime">2016-03-31T04:32:05Z</dct:modified> </rdf:Description> <rdf:Description rdf:a
bout="http://vocab.cdmk-caribbean.net/cdmk#c_893a08ac1%(count)d"> <dct:modified rdf:datatype="http://www.w3.org/2001/XMLSchema#dateTime">2016-03-31T04:32:05Z</dct:modified> </rdf:Description> <rdf:Description rdf:about="http://vocab.cdmk-caribbean.net/cdmk#c_893a08ac1%(count)d"> <skos:definition rdf:resource="http:/...
xingyepei/edx-platform
openedx/core/djangoapps/user_api/forms.py
Python
agpl-3.0
189
0
#
pylint: disable=unused-import # TODO: eventually move this implementation into the user_api """ Djan
go Administration forms module """ from student.forms import PasswordResetFormNoActive
century-arcade/xd
crossword/__init__.py
Python
mit
397
0
# -*
- coding: utf-8 -*- __title__ = 'crossword' __version__ = '0.1.2' __author__ = 'Simeon Visser' __email__ = 'simeonvisser@gmail.com' __license__ = 'MIT' __copyright__ = 'Copyright 2014 Simeon Visser' from crossword.core import Crossword from crossword.exceptions import CrosswordException from crossword.format_ipuz imp...
_puz import from_puz, to_puz
mapnik/mapnik
scons/scons-local-4.1.0/SCons/Variables/BoolVariable.py
Python
lgpl-2.1
2,855
0.002452
# MIT License # # Copyright The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, ...
the string. If the string can't be converted, the original value will be returned. See '__true_strings' and '__false_strings' for values considered 'true' or 'false respectively. This is usable as 'converter' for SCons' Variables. """ lval = val.lower() if lval in __true_
strings: return True if lval in __false_strings: return False raise ValueError("Invalid value for boolean option: %s" % val) def _validator(key, val, env): """ Validates the given value to be either '0' or '1'. This is usable as 'validator' for SCons' Variables. """ if not env[key] in...
PhillyNJ/SAMD21
cryptoauthlib/python/cryptoauthlib/atcacert.py
Python
mit
7,650
0.00549
from ctypes import Structure, c_int, c_uint8, c_uint16, c_char, POINTER, Array from .atcab import get_cryptoauthlib from .atcaenum import AtcaEnum import binascii class atcacert_cert_type_t(AtcaEnum): """Types of certificates""" CERTTYPE_X509 = 0 # Standard X509 certificate CERTTYPE_CUSTOM = 1 ...
cert_convert_enum(kwargs, 'sn_source', atcacert_cert_sn_src_t) _atcacert_convert_enum(kwargs, 'issue_date_format', atcacert_date_format_t)
_atcacert_convert_enum(kwargs, 'expire_date_format', atcacert_date_format_t) _atcacert_convert_bytes(kwargs, 'cert_template', POINTER(c_uint8)) for f in self._fields_: if type(f[1]) == type(Structure): _atcacert_convert_structure(kwargs, f[0], f...
will-iam/Variant
casepy/eulerRuO2/nNoh4194304x1/chars.py
Python
mit
473
0.012685
import sys, os sys.path.insert(1, os.path.join(sys.path[0], '../../../')) import script.rio as io import scrip
t.initial_condition.noh1D as noh1D # Domain properties lx = 1.0 ly = 1.0 Nx = 4194304 Ny = 1 # Scheme execution options T = 0.6 CFL = 0.5 gamma = 5./3. BClayer = 1 quantityList = ['rho', 'rhou_x', 'rhou_y', 'rhoE'] def buildme(quantityDict, coords_to_uid, coords_to_bc): noh1D.bui
ld(quantityDict, coords_to_uid, coords_to_bc, Nx, Ny, lx, ly, BClayer)
FrodeSolheim/fs-uae-launcher
amitools/scan/ADFSScanner.py
Python
gpl-2.0
2,106
0.017094
"""Scan an ADF image an visit all files""" import io from amitools.fs.blkdev.BlkDevFactory import BlkDevFactory from amitools.fs.ADFSVolume import ADFSVolume class ADF
SScanner: def __init__(self): self.factory = BlkDevFactory() def can_handle(self, scan_file): base_name
= scan_file.get_basename().lower() for ext in self.factory.valid_extensions: if base_name.endswith(ext): return True return False def handle(self, scan_file, scanner): if scan_file.is_seekable(): sf = scan_file else: sf = scanner.promote_scan_file(scan_file, seekable=True) ...
LLNL/spack
var/spack/repos/builtin/packages/bird/package.py
Python
lgpl-2.1
1,198
0.002504
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Bird(AutotoolsPackage): """The BIRD project aims to develop a dynamic IP routing daemon wi...
l route filtering language, primarily targeted on (but not limited to) Linux and other UNIX-like systems and distributed under the GNU General Public License.""" homepage = "https://bird.network.cz/" url = "https://github.com/BIRD/bird/archive/v2.0.2.tar.gz" version('2.0.2', sha256='bd42d48fb...
f1183cd98193ff15b792d332ff45f386b0180b09335') version('2.0.1', sha256='cd6ea4a39ca97ad16d364bf80f919f0e75eba02dd7fe46be40f55d78d022244a') depends_on('autoconf', type='build') depends_on('automake', type='build') depends_on('libtool', type='build') depends_on('m4', type='build') depends_o...
rjschwei/WALinuxAgent
tests/common/osutil/test_nsbsd.py
Python
apache-2.0
3,180
0.003145
# Copyright 2019 Microsoft Corporation # # 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...
pid_list = NSBSDOSUtil().get_dhcp_pid() self.assertEquals(pid_list, []) # # PID file is empty # original_isfile = path.isfile def mock_isfile(path): return True if path == self.dhclient_pid_file else original_isfile(path) ...
def mock_read_file(file, *args, **kwargs): return "" if file == self.dhclient_pid_file else original_read_file(file, *args, **kwargs) with patch("os.path.isfile", mock_isfile): with patch("azurelinuxagent.common.osutil.nsbsd.fileutil.read_file", mock_read_file): ...
timm/timmnix
pypy3-v5.5.0-linux64/lib-python/3/test/test_urllib2.py
Python
mit
61,813
0.001844
import unittest from test import support import os import io import socket import array import sys import urllib.request # The proxy bypass method imported below has logic specific to the OSX # proxy config data structure but is testable on all platforms. from urllib.request import Request, OpenerDirector, _proxy_byp...
ssertEqual(find_user_pass("Some Realm", "c.e
xample.com:3128"), ('3', 'c')) self.assertEqual( find_user_pass("Some Realm", "http://c.example.com:3128"), ('3', 'c')) self.assertEqual(find_user_pass("Some Realm", "d.example.com"), ('4', 'd')) self.assertEqual(find_user...
pascalweiss/SearchEngine
model/test_model.py
Python
cc0-1.0
1,742
0.002308
import unittest import os from model.index import Index from model.page import Page class TestPage(unittest.TestCase): def test_str_outputStringIsAsExpected(self): test_page = Page() test_page.title = 'D01' test_page.content = 'Bla Bla Blub' expected_output = os.linesep.join([ ...
index = self.get_dummy_index() posting_list = index.get_posting_list('daDadA') self.assertListEqual(posting_list, ['d01']) posting_list = index.get_posting_list('DaDaDa', 'dumDIDum') self.assertListEqua(posting_list, ['d{0:02}'.format(n) for n in range(1, 4)]) def get_dummy_i...
n('DaDaDa', 'd01') dummyIndex.register_Token('DumDiDum', 'd02') dummyIndex.register_Token('DumDiDum', 'd03') return dummyIndex if __name__ == '__main__': unittest.main()
marcin-bakowski-dev/rest-api-mock-server
mock_rest_app/mock_api/callbacks.py
Python
mit
710
0.004225
import logging from django.conf import settings from mock_api.h
ttp_utils import make_request logger = logging.getLogger(__name__) def run_api_endpoint_callbacks(api_endpoint): responses = [] for api_callback in api_endpoint.callbacks.all(): logger.debug("Make callback: %s", api_callback) response = make_request(method=api_callback.method, url=api_callbac...
BACK_REQUEST_TIMEOUT) if response: logger.debug("Callback response status code: %s", response.status_code) responses.append(response) return responses
dud225/incubator-airflow
airflow/contrib/hooks/gcp_dataproc_hook.py
Python
apache-2.0
5,322
0.000752
# -*- coding: utf-8 -*- # # 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 ...
str(self.job['status']['state'])) time.sleep(5) def raise_error(self, message=None): if 'ERROR' == self.job['status']['state']: if message is None: message = "Google DataProc job has error" raise Exception(message + ": " + str(self...
def get(self): return self.job class _DataProcJobBuilder: def __init__(self, project_id, task_id, dataproc_cluster, job_type, properties): name = task_id + "_" + str(uuid.uuid1())[:8] self.job_type = job_type self.job = { "job": { "reference": { ...
aaxelb/osf.io
admin_tests/base/test_utils.py
Python
apache-2.0
3,856
0.000519
from nose.tools import * # flake8: noqa from django.db.models import Q from tests.base import AdminTestCase from osf_tests.factories import SubjectFactory from osf.models import Subject from osf.models.preprint_provider import rules_to_subjects from admin.base.utils import get_subject_rules import logging logger...
rules = [ [
[self.parent_one._id, self.child_one_1._id], False] ] subject_queryset_ideal = Subject.objects.filter(Q(id=self.parent_one.id) | Q(id=self.child_one_1.id)) returned_subjects = rules_to_subjects(rules) self.assertItemsEqual(subject_queryset_ideal, returned_subjects)
krishnaku/ec2x
ec2x/console.py
Python
mit
1,600
0.000625
from . import name_binding, tasks import argh from argh.decorators import arg from fabric.tasks import execute from functools import reduce def rehash(): """Update the binding of instance names to instance_id and public_dns_names and also update the name_binding cache. """ name_binding.export_name_bin...
<instance_name> ps ax :show the processes running on the remote instance <instance> ec2x remote <instance_name> \"ps ax | grep ssh\" :run the piped command sequence on the remote instance """ execute(tasks.remote_run, _concat(command), instance_name) @arg('comm...
me bindings in the environment Example: ec2x local echo "The public dns name of the instance named euler is " $euler """ tasks.local(_concat(command)) def _concat(command): return reduce(lambda out, s: out + s + ' ', command, '') def __main__(): argh.dispatch_commands( [ ssh...
wattlebird/ranking
rankit/Ranker/__init__.py
Python
mit
344
0.008721
from .UnsupervisedRanker import MasseyRanker, ColleyRanker, Keene
rRanker, MarkovRanker, ODRanker, DifferenceRanker from .TimeSeriesRanker import EloRanker, TrueSkillRanker, GlickoRanker __all__ = ["MasseyRanker", "
ColleyRanker", "KeenerRanker", "MarkovRanker", "ODRanker", "DifferenceRanker", "EloRanker", "TrueSkillRanker", "GlickoRanker"]
Chris35Wills/Chris35Wills.github.io
courses/examples/Beginners_python/conditions.py
Python
mit
826
0.01937
# Past examples are programmatically insecure # You require arguments to be passed in but what if the wrong arguments are provided? # Look at the timestable solution which changes numbers to text - what happens
if you provide the number 30? # # One way of controlling these things uses conditions # These enable specific operations to be carried out "if" something is the case or "else" something else is the case a = 5 # first condition trial if a >= 5: print("Value is greater than 5") else: print("Value is less than 5") #...
is 5") # if and (2 conditions) a=3 b=5 if (a==3) and (b==5): print("a and b are as expected - great :)") else: print("a and b not as expected - not great :(")
adamreeve/npTDMS
nptdms/utils.py
Python
lgpl-3.0
1,733
0.001154
from functools import wraps import logging import time try: from collections import OrderedDict except ImportError: try: # ordereddict available on py
pi for P
ython < 2.7 from ordereddict import OrderedDict except ImportError: # Otherwise fall back on normal dict OrderedDict = dict def cached_property(func): """ Wraps a method on a class to make it a property and caches the result the first time it is evaluated """ attr_name = '_cach...
raildo/keystone
keystone/tests/test_utils.py
Python
apache-2.0
8,700
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 OpenStack Foundation # # 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 # # Unle...
.Equals(expected_rv)) def test_deprecating_a_method_returns_correct_value(self): class C(object): @utils.deprecated(as_of=utils.deprecated.ICEHOUSE) def outdated_method(self, *args): return ar
gs retval = C().outdated_method(1, 'of anything') self.assertThat(retval, matchers.Equals((1, 'of anything'))) def test_deprecated_with_unknown_future_release(self): @utils.deprecated(as_of=utils.deprecated.ICEHOUSE, in_favor_of='different_stuff()') def ...
lyndonnixon/LSI
enricher.py
Python
apache-2.0
1,636
0.003667
#!/usr/bin/env python # -*- coding: UTF-8 -*- """Periodically enrich the metadata of media resources by invoking Named Entity Recognition Services. .. moduleauthor:: Dong Liu <liu.dong66@gmail.com> """ import config import esclient import ner import model import json import logging import lsilog from time import sleep...
while True: if enriched_count >= media_count: break media_list = elastic_search_client.find_media_by_status('crawled') for media in ner.enrich(media_list, keep_ner_log=True): media.status = 'enriched' sleep(1) if isinstance(media, model.VideoTra...
VideoEncoder)) elif isinstance(media, model.Image): enriched_image += 1 elastic_search_client.update_image(media.id, json.dumps(media, cls=model.ImageEncoder)) enriched_count += 1 logger = logging.getLogger("enricher") logger.info('Enriched ' + str(enriche...
rebortyang/flask_blog
app/auth/__init__.py
Python
mit
111
0.036036
_
_author__ = 'yangjiebin' from flask import Blueprint auth = Blueprint('auth',__name__) from . import views
alexissmirnov/donomo
donomo_archive/lib/reportlab/test/test_pdfbase_encodings.py
Python
bsd-3-clause
10,317
0.00979
from reportlab.test import unittest from reportlab.test.utils import makeSuiteForClasses, outputfile, printLocation, NearTestCase from reportlab.pdfgen.canvas import Canvas from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from reportlab.pdfbase import pdfutils from reportlab.platy...
8671875) def testUtf8Canvas(self): """Verify canvas declared as utf8 autoconverts. This assumes utf8 input. It converts to the encoding of the underlying font, so both text lines APPEAR the same."""
c = Canvas(outputfile('test_pdfbase_encodings_utf8.pdf')) c.drawString(100,700, testUTF8) # Set a font with UTF8 encoding c.setFont('Luxi', 12) # This should pass the UTF8 through unchanged c.drawString(100,600, testUTF8) # and this should convert from Unicode t...
mathiasose/celery_dill_serializer
celery_dill_serializer/__init__.py
Python
mit
525
0
from dill import dill from kombu.serialization import pickle_loads,
pickle_protocol, registry from kombu.utils.encoding import str_to_bytes def register_dill(): def encode(obj, dumper=dill.dumps): return dumper(obj, protocol=pickle_protocol) def decode(s): return pickle_loads(str_to_bytes(s), load=dill.load) registry.register( name='dill', ...
content_encoding='binary' )
jjuanda/cuco
cuco/SupervisorJob.py
Python
gpl-2.0
2,735
0.004022
from jinja2 import Template class SupervisorJob(object): """docstring for SupervisorJob""" def __init__(self, config): """ Specify the configuration options for a job. 'config' must be a dictionary containing the following keys: - env_vars: dict containing the key/value pairs ...
mmand = {{cmd}} directory = {{base_dir}} autostart = true autorestart = true stopsignal = KILL killasgroup = true stopasgroup = true environment = {{env}} std
out_logfile = {{stdout}} stderr_logfile = {{stderr}} """ env = Template(config) return env.render({ "program_name" : self.config['name'], "base_dir" : self.config['base_dir'], "env" : self.get_env_str(), "cmd" : self.config['cmd']...
psydrake/bicreditsnew
qa/rpc-tests/txn_doublespend.py
Python
mit
4,976
0.002814
#!/usr/bin/env python2 # Copyright (c) 2014 The Bitcredit Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Test proper accounting with malleable transactions # from test_framework import BitcreditTestFramework ...
cks(self.nodes[0:2]) tx1 = self.nodes[0].gettransaction(txid1) tx2 = self.nodes[0].gettransaction(txid2) # Node0's balance should be starting balance, plus 50BTC for another # matured block, minus 1210, minus 20, and minus transaction fees: expected = starting_balance i...
nt"] + tx1["fee"] expected += tx2["amount"] + tx2["fee"] assert_equal(self.nodes[0].getbalance(), expected) # foo and bar accounts should be debited: assert_equal(self.nodes[0].getbalance("foo"), 1220+tx1["amount"]+tx1["fee"]) assert_equal(self.nodes[0].getbalance("bar"), 30+tx2...
amigos-do-gesiel/iespv-administrativo
users/forms.py
Python
mit
597
0.031826
from .models import Donor from django.forms import ModelForm, TextInput class DonorForm(ModelForm): class Meta: model = Donor fields = [ "email", "donation_date", "phone_number", "address", "observations" ] widgets = { 'donation_date': TextInput(attrs={'class': 'form-control'
}), 'phone_number': TextInput(attrs={'class': 'form-control'}), 'address': TextInput(attrs={'class': 'form-control'}), 'email': TextInput(attrs={'class': 'form-control'}), 'observations': TextInput(attrs={'class': 'form-control
'}), }
foobarbazblarg/stayclean
stayclean-2018-march/serve-signups-with-flask.py
Python
mit
8,581
0.003613
#!/usr/bin/env python import subprocess import praw from hashlib import sha1 from flask import Flask from flask import Response from flask import request from cStringIO import StringIO from base64 import b64encode from base64 import b64decode from ConfigParser import ConfigParser import OAuth2Util import os import mar...
t></small>') # if ParticipantCollection().participantNamed(authorName).isStillIn: # stringio.write(' <small><font color="green">(in)</font></small>') # else: # stringio.write(' <small><font color="red">(out)</font></small>') else: ...
ame">') stringio.write('<input type="submit" name="actiontotake" value="Signup" style="color:white;background-color:green">') # stringio.write('<input type="submit" name="actiontotake" value="Signup and checkin">') # stringio.write('<input type="submit" name="actiontotake" value="Rel...
jainpranav/Turing_Machine_Simulator
Simulator/tmbuilder.py
Python
apache-2.0
7,293
0.009187
# -*- coding: utf-8 -*- from tm import TuringMachine class TuringMachineBuilder: """ Creates a turing machine step by step by retrieving all the necessary information. By default (can be specified)
sets the halt state to 'HALT and the blank symbol to '#' """ def __init__(self): """ Initialize a new TuringMachineBuilder with the specified haltstate and blank symbol. haltstate takes as default value 'HALT' blnak takes as default value '#' and must b...
= None self._fstates = set() self._blank = None self._haltstate = None # # def clean(self): """ Clear all the previous stored data """ self._states = set() self._in_alphabet = set() self._trans_function = {} se...
nfomon/shok
parser/shokparser/LexToken.py
Python
gpl-3.0
757
0.015852
# Copyright (C) 2013 Michael Biggs. See the COPYING file at the top-level # directory of this distribution and at http://shok.io/code/copyright.html # Tokens that come from the Lexer are either pairs or tuples: # colno:type # colno:type:value class LexToken: colno = 0 ttype = '' tvalue = '' def __init__(s...
self.tvalue = t[2] def __repr__(self): if '' == self.tvalue: return "<%s:%s>" % (self.colno, self.ttype) else:
return "<%s:%s:%s>" % (self.colno, self.ttype, self.tvalue) def NewlineToken(): return LexToken('0:NEWL')
ow2-proactive/agent-linux
palinagent/daemon/controller.py
Python
agpl-3.0
3,298
0.004245
#! /usr/bin/env python # -*- coding: UTF-8 -*- ################################################################# # # ProActive Parallel Suite(TM): The Java(TM) library for # Parallel, Distributed, Multi-Core Computing for # Enterprise Grids & Clouds # # Copyright (C) 1997-2011 INRIA/University of # ...
logger.debug("Controller is scheduling an event -> type:%s start:%s duration:%s" % (self.cur_event.type, self.cur_event.epoch_
date, self.cur_event.duration)) self.cur_event.schedule() # FIXME: sleep shouldn't be used. It should be event based ! sleep_time = max(0, int((self.cur_event.epoch_date + self.cur_event.duration) - time.time())) logger.debug("Controller...
RaoUmer/python-fundamentals
challenges/04-Functions/test_A_checking_again.py
Python
apache-2.0
936
0.005342
import pytest import A_checking_again as A def test_can_drink(): '''This is a much clearer test now that we're using functions!''' assert A.can_drink(21) == True assert A.can_drink(22) == True assert A.can_drink(20) == False def test_enforce(capsys): '''Notice that we're not restricted to the dat...
his isn't right!" assert lines[2] == "Checking Bob!" assert lines[3] == "OK!" assert lines[4] == "" # Advanced users should note that the above tests co
uld be made even more # efficient using the "parametrize" decorator from pytest!
castelao/CoTeDe
cotede/qctests/bin_spike.py
Python
bsd-3-clause
2,677
0.002988
#!/usr/bin/env python # -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ """ import numpy as np from numpy import ma def bin_spike(x, l): """ l is the number of points used for comparison, thus l=2 means that each point will be compared only against t...
oo small. Maybe use pstsd instead? Dummy way to avoid warnings when x[ini:fin] are all masked. Improve this in the future. """ assert x.ndim == 1, "I'm not ready to deal with multidimensional x" assert l%2 == 0, "l must be an even integer" N = len(x) bin = ma.masked_all(N...
lf_window) fin = min(N, i + half_window) # At least 3 valid points if ma.compressed(x[ini:fin]).size >= 3: bin[i] = x[i] - ma.median(x[ini:fin]) # bin_std[i] = (np.append(x[ini:i], x[i+1:fin+1])).std() bin[i] /= (np.append(x[ini:i], x[i+1:fin+1])).std() r...
adazey/Muzez
libs/soundcloud/tests/test_client.py
Python
gpl-3.0
5,660
0
import soundcloud from soundcloud.tests.utils import MockResponse try: from urllib import urlencode except ImportError: from urllib.parse import urlencode from nose.tools import eq_, raises from fudge import patch def test_kwargs_parsing_valid(): """Test that valid kwargs are stored as pr...
{ 'User-Agent
': soundcloud.USER_AGENT, 'Accept': 'application/json' } (fake_request.expects_call() .with_args(expected_url, headers=headers, proxies=proxies, allow_redirects=True) .returns(Mo...
rwgdrummer/maskgen
tests/batch/test_batch_converter.py
Python
bsd-3-clause
772
0
# =====================================================================
======== # Authors: PAR Government # Organizati
on: DARPA # # Copyright (c) 2016 PAR Government # All rights reserved. # ============================================================================== from tests.test_support import TestSupport from maskgen.scenario_model import ImageProjectModel from maskgen.batch.batch_journal_conversion import BatchConverter from ...
0-wHiTeHand-0/CTFs
made_faqin2k18/heap/flag.py
Python
gpl-2.0
413
0.031477
import sys #Se le pasa la flag deseada, y devuelve lo que hay que escribir en el binario. CUIDADO CON LAS BACKSLASHES; hay que
escaparlas if len(sys.argv) != 2: print "Syntax: python2 flag.py <FLAG>" sys.exit(0) fl
ag = sys.argv[1] i = 0 j = len(flag)-1 l = j flag2 = "" while (i<l+1): if i <= l/2: c = 7 else: c = 10 flag2 += chr(ord(flag[j])+c) i = i+1 j = j-1 print flag2
CreditEaseDBA/Themis
rule_analysis/rule/obj/table_record_length.py
Python
apache-2.0
2,563
0.001951
# -*- coding: utf-8 -*- def f_get_byte_length(data_type, character_octet_length, numeric_precision, numeric_scale): case_data_type = { 'tinyint': 1, 'smallint': 2, 'mediumint': 3, 'int': 4, 'integer': 4, 'bigint': 8, 'float': 4, 'double': 8, ...
sql.replace("@table_name@", table_name).replace("@username@", username) db_cursor.execute(sql) cur_columns = db_cursor.fetchall() tmp_column_length = 0 for rec_col in cur_columns: data_type = rec_col[1] character_octet_length = rec_col[2] numeric_pre...
c_col[4] if tmp_column_length: tmp_column_length = tmp_column_length + f_get_byte_length(data_type, character_octet_length, numeric_precision, numeric_scale) if tmp_column_length > record_length: return_tabs.append([rec_tab[0], rec_tab[1], tmp_column_length]) return ...
jose36/plugin.video.live.ProyectoLuzDigital-
servers/adfly.py
Python
gpl-2.0
2,142
0.021942
# -*- coding: utf-8 -*- #------------------------------------------------------------ # pelisalacarta - XBMC Plugin # Conector para adfly (acortador de url) # http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/ #------------------------------------------------------------ import urlparse,urllib2,urllib,re import os...
# Parche porque python no parece reconocer bien la cabecera phpsessid body,response_headers = scrapertools.read_body_and_headers(url,post=post,headers=request_headers) n = 1 while True: for name,value in response_headers: if name=="set-cookie": logger.info("S
et-Cookie: "+value) cookie_name = scrapertools.get_match(value,'(.*?)\=.*?\;') cookie_value = scrapertools.get_match(value,'.*?\=(.*?)\;') request_headers.append(["Cookie",cookie_name+"="+cookie_value]) body,response_headers = scrapertools.read_body_and_headers(u...
NicoVarg99/daf-recipes
ckan/ckan/ckan/ckanext/multilingual/tests/test_multilingual_plugin.py
Python
gpl-3.0
8,793
0.000114
# encoding: utf-8 import ckan.plugins import ckanext.multilingual.plugin as mulilingual_plugin import ckan.lib.helpers import ckan.lib.create_test_data import ckan.logic.action.update import ckan.model as model import ckan.tests.legacy import ckan.tests.legacy.html_check import routes import paste.fixture import pylon...
'title'
: 'russian', 'description': 'Roger likes these books.'} ckan.tests.legacy.call_action_api(cls.app, 'organization_create', apikey=cls.sysadmin_user.apikey, **cls.org) dataset = {'name': 'test_org_datase...
SimonHerrera/rock-island-independents
api/rii_Api/migrations/0002_auto_20160912_2314.py
Python
mit
1,025
0.000976
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2016-09-13 04:14 from __future__ import unicode_literals from django.db import m
igrations, models class Migration(migrations.Migration):
dependencies = [ ('rii_Api', '0001_initial'), ] operations = [ migrations.AlterField( model_name='location', name='state', field=models.CharField(max_length=2), ), migrations.AlterField( model_name='location', name='ven...
khanhduong95/Open-Tux-World
scripts/fall.py
Python
gpl-3.0
1,747
0.004579
# # Copyright (C) 2016 Dang Duong # # This file is part of Open Tux World. # # Open Tux World 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 op...
y() v = Vector((own["v_x"], own["v_y"], own["v_z"])) dv = Vector(own.worldLinearVelocity) - v v += dv speed = common.getDistance([dv.x, dv.y, dv.z]) own["v_x"] = v.
x own["v_y"] = v.y own["v_z"] = v.z if speed > common.DANGER_SPEED: if speed > common.FATAL_SPEED: own["health"] = 0 else: own["health"] -= speed * (common.HIGH_DAMAGE_RATE if speed > common.HIGH_DANGER_SPEED else common.DAMAGE_RATE) own.state = logic.KX_STAT...
rtfd/recommonmark
tests/sphinx_custom_md/conf.py
Python
mit
794
0.003778
# -*- coding: utf-8 -*- from recommonmark.parser import CommonMarkParser from recommonmark.transform import AutoStructify templates_path = ['_templates'] source_suffix = '.markdown' source_parsers = { '.markdown': CommonMarkParser } master_doc = 'index' project = u'sphinxproj' copyright = u'2015, rtfd' author = u'rt...
ath = ['_static'] htmlhelp_ba
sename = 'sphinxproj' def setup(app): app.add_config_value('recommonmark_config', { 'enable_eval_rst': True, 'commonmark_suffixes': ['.markdown', '.hpp'], }, True) app.add_transform(AutoStructify)
scieloorg/opac
opac/tests/test_interface_TOC.py
Python
bsd-2-clause
11,514
0.000961
# coding: utf-8 import flask from flask import url_for from .base import BaseTestCase from . import utils class TOCTestCase(BaseTestCase): # TOC def test_the_title_of_the_article_list_when_language_pt(self): """ Teste para verificar se a interface do TOC esta retornando o título no ...
interface utils.makeOneCollection() issue = utils.makeOneIssue({'journal': journal}) translated_titles = [] utils.makeOneArticle({ 'issue': issue, 'title': 'Article Y', 'translated_titles': translated_titles }...
'main.issue_toc', url_seg=journal.url_segment, url_seg_issue=issue.url_segment) } set_locale_url = url_for('main.set_locale', lang_code='es') response = c.get(set_locale_url, headers=header, follow_redirects=True) self.as...
lzhang10/maxent
python/setup.py
Python
lgpl-2.1
2,832
0.016949
#!/bin/env python # This is the building script for Python maxent extension module. # Simply type "python setup.py build" at command line to build the extension. # After that you can type "python setup.py install" to install the extension # module. # # The script assume you use gcc on unix and msvc on win32 platform. ...
ntropy Modeling toolkit in python", long_description = """Max
ent is a powerful, flexible, and easy-to-use Maximum Entropy Modeling library for Python. The core engine is written in C++ with speed and portability in mind. The win32 version of this module was compiled with MSVC7.1, Intel Fortran 8.0, STLPort 4.6. """, license = "LGPL", packages = ['maxent'], e...
smallswan267/octoplus
selenium/webdriver/chrome/webdriver.py
Python
mit
3,175
0.00315
#!/usr/bin/python # # Copyright 2011-2013 Software freedom conservancy # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
bilities=desired_capabilities, keep_alive=True) except: self.quit() raise self._is_remote = False def quit(self): """ Closes the browser and shuts down the ChromeDriver executable that is started when starting the ChromeDriver ...
lly: self.service.stop()
algorhythms/LintCode
Segment Tree Query II.py
Python
apache-2.0
1,529
0.003924
""" For an array, we can build a SegmentTree for it, each node stores an extra attribute count to denote the number of elements in the the array which value is between interval start and end. (The array may not fully filled by elements) Design a query method with three parameters root, start and end, find the number o...
if s <= root.start and e >= root.end: return root.count if s > root.end or e < root.start: return DEFAULT l = self.query(root.left, s, e)
r = self.query(root.right, s, e) return f(l, r)
prisonersDilemma/orionscripts
whois/whois/tests/__init__.py
Python
gpl-2.0
65
0.015385
#!/usr/bin/env python3.6 if __name__
== '__main__':
pass
anhstudios/swganh
data/scripts/templates/object/static/structure/general/shared_prp_junk_s4.py
Python
mit
449
0.046771
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object i
mport * def create(kernel): result = Static() result.template = "object/static/structure/general/shared_prp_junk_s4.iff" result.attribute_template_id = -1 result.stfName("obj_n","unknown_object") #### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS #### return result
OCA/manufacture
mrp_production_serial_matrix/wizards/mrp_production_serial_matrix.py
Python
agpl-3.0
13,579
0.001178
# Copyright 2021 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import _, api, fields, models from odoo.exceptions import UserError, ValidationError from odoo.tools.float_utils import float_compare, float_is_zero class MrpProductionSerialMat...
inished_lot.name, } ) e
lif isinstance(number, int): res.update( { "finished_lot_name": _("(New Lot %s)") % number, } ) return res @api.onchange("finished_lot_ids") def _onchange_finished_lot_ids(self): for rec in self: matrix_line...
ryfeus/lambda-packs
Rasterio_osgeo_shapely_PIL_pyproj_numpy/source/rasterio/rio/rasterize.py
Python
mit
10,025
0.0002
import json import logging from math import ceil import os import click import cligj from .helpers import resolve_inout from . import options import rasterio from rasterio.errors import CRSError from rasterio.transform import Affine from rasterio.coords import disjoint_bounds logger = logging.getLogger('rio') # C...
e( ctx, files, output, driver, like, bounds, dimensions, res, src_crs, all_touched, default_value, fill,
prop, force_overwrite, creation_options): """Rasterize GeoJSON into a new or existing raster. If the output raster exists, rio-rasterize will rasterize feature values into all bands of that raster. The GeoJSON is assumed to be in the same coordinate reference system as the outpu...
marrow/web.db
test/test_sqlalchemy.py
Python
mit
1,437
0.03897
# encoding: utf-8 from __future__ import unicode_literals import pytest from web.core.context import Context from web.db.sa import SQLAlchemyConnection from sqlalchemy import Column, String, Integer, ForeignKey from sqlalchemy.orm import relationship from sqlalchemy.ext.declarative import declarative_base Base = ...
class TestSQLAlchemy(object): def test_lifecycle(self, sa): pass def test_repr(self): sa = SQLAlchemyConnection
('sqlite://', 'test') assert repr(sa) == 'SQLAlchemyConnection(test, "sqlite://")' def test_use(self, sa): engine, session = sa Base.metadata.create_all(engine) p = Person(name='person') session.add(p) a = Address(address='address', person=p) session.add(a) session.commit() p = sessi...
dcooper2/Swanson_Bot
swanson_bot.py
Python
mit
2,143
0.005133
#!/usr/bin/python import praw import re import os import pickle from array import * import random #REPLY = "I want all the bacon and eggs you have." REPLY = array('i',["I want all the bacon and eggs you have", "I know what I'm about son", "I'm not interested in caring about people", "Is this not rap?"]) if not os.pat...
x = random.randi
nt(0,3) submission.add_comment(REPLY[x]) print "Bot replying to submission: ", submission.id replies.append(submission.id) print "Checking comments" flat_comments = praw.helpers.flatten_tree(submission.comments) for comment in flat_comments: if comment.id not in r...
kako-nawao/django-group-by
test_app/query.py
Python
mit
141
0
from django_group_by import GroupByMixin from django.db.models.query import QuerySet class BookQuerySet(QuerySet, Group
ByMixin): pass
mhmurray/cloaca
cloaca/test/tests.py
Python
mit
3,034
0.004285
#!/usr/bin/env python import unittest import logging import logging.config import sys import argparse DESCRIPTION=""" Harness for tests in the cloaca/tests/ directory. Run all tests with '--all' or provide a list dotted names of specific tests (eg. legionary.TestLegionary.test_legionary). """ # Set up logging. See l...
formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--all', action='store_true', help='Run all tests instead of matching pattern.') parser.add_argument('pattern', nargs='*', help=('pattern(s) to match against, eg. "buildings" or ' '"a...
, help='Use verbose test result reporting.') parser.add_argument('-q', '--quiet', action='store_true', help=('Suppress individual test result reporting. Still reports ' 'summary information. Overrides --verbose.')) parser.add_argument('--log-level', default='WARNING', ...
opencobra/memote
src/memote/suite/cli/reports.py
Python
apache-2.0
14,140
0.000283
# -*- coding: utf-8 -*- # Copyright 2017 Novo Nordisk Foundation Center for Biosustainability, # Technical University of Denmark. # # 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...
s import partial from multiprocessing import Pool, cpu_count import click import git from libsbml import SBMLError from sqlalchemy.exc import ArgumentError import memote.suite.api as api import memote.suite.cli.callbacks as callbacks import memote.suite.results as managers import memote.utils as utils from memote.sui...
rt(): """Generate one of three different types of reports.""" pass @report.command(context_settings=CONTEXT_SETTINGS) @click.help_option("--help", "-h") @click.argument( "model", type=click.Path(exists=True, dir_okay=False), envvar="MEMOTE_MODEL" ) @click.option( "--filename", type=click.Path(exis...
tzanetos/graphs
graphs/libs/ubigraph/UbiGraph-alpha-0.2.4-Linux64-Ubuntu-8.04/examples/Python/architecture.py
Python
mit
689
0.044993
import ubigraph, sys #Omit U = ubigraph.Ubigraph() U.clear() U.defaultVertexStyle.set(fontsize=14) engine = U.newVertex(color="#ffff00",shape="dodecahedron",label="LayoutEngine") server = U.newVertex(color="#8080ff",shape="cube",label="XMLRPC Server") engine_server_edge = U.newEdge(server,engine,width=3,arrow=True,or...
tex(color="#ff0080",shape="cube",label="Client App") U.newEdge(clientVertex,clientXVertex,arrow=True,oriented=True) U.newEdge(clientXVertex,server,arrow=True,oriented=True) for i in range(0,3):
client() sys.stdin.readline()
makelove/OpenCV-Python-Tutorial
ch200_Extra_modules/aruco/Camera Calibration using ChArUco and Python/calibrateCamera2.py
Python
mit
2,398
0
# -*- coding: utf-8 -*- # @Time : 2017/7/27 18:04 # @Author : play4fun # @File : calibrateCamera2.py # @Software: PyCharm """ calibrateCamera2.py: """ import cv2 import numpy as np def draw_axis(img, charuco_corners, charuco_ids, board): vecs = np.load("./calib.npz") # I already calibrated the camera ...
ers, ids) if ids
is not None and corners is not None \ and len(ids) > 0 and len(ids) == len(corners): diamond_corners, diamond_ids = \ cv2.aruco.detectCharucoDiamond(img, corners, ids, 0.05 / 0.03, cameraMatrix=mtx, ...
henla464/WiRoc-Python-2
testOLED.py
Python
gpl-3.0
6,908
0.001158
# Copyright (c) 2014 Adafruit Industries # Author: Tony DiCola # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use
, copy, modify, merge, publish, 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 following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of th...
FTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN A...
elijh/bitmask_client
src/leap/bitmask/services/eip/eipconfig.py
Python
gpl-3.0
10,587
0.000094
# -*- coding: utf-8 -*- # eipconfig.py # Copyright (C) 2013 LEAP # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # T...
ed = eip_config.loaded() if not loaded: eip_config_path = get_eipconfig_path(domain) api_version = provider_config.get_api_version() eip_conf
ig.set_api_version(api_version) loaded = eip_config.load(eip_config_path) return loaded class VPNGatewaySelector(object): """ VPN Gateway selector. """ # http://www.timeanddate.com/time/map/ equivalent_timezones = {13: -11, 14: -10} def __init__(self, eipconfig, tz_offset=None): ...
iwm911/plaso
plaso/parsers/plist_plugins/airport_test.py
Python
apache-2.0
2,576
0.001941
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2014 The Plaso Project Authors. # Please see the AUTHORS file for details on individual 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 L...
t unittest # pylint: disable=unused-import from plaso.formatters import plist as plist_formatter from plaso.lib import event from plaso.parsers import plist from plaso.parsers.plist_plugins import airport from plaso.parsers.plist_plugins import test_lib class AirportPluginTest(test_lib.PlistPluginTestCase): """Tes...
used throughout the test.""" self._plugin = airport.AirportPlugin(None) self._parser = plist.PlistParser(event.PreprocessObject(), None) def testProcess(self): """Tests the Process function.""" test_file = self._GetTestFilePath(['com.apple.airport.preferences.plist']) plist_name = 'com.apple.air...
Natalia-28028/kpk2016
task_dm4.py
Python
gpl-3.0
328
0.006098
from drawman import * from time
import sleep scale = 100 def f(x): return x**2 x = 0 y = 0 dx = 0.1 while x < 3: dy = f(x + dx) - y x = x + dx y = f(x) shift(dx*scale, dy*scale) x = 0 y = 0 dx = -0.1 while x > -3: dy = f(x + dx) - y x = x + dx y = f(x) shift
(dx*scale, dy*scale) sleep(1)
cbrichford/async-mock
async_mock/coroutine.py
Python
bsd-3-clause
3,037
0.001317
import asyncio from unittest.mock import MagicMock def SimpleCoroutineMock(f=lambda *args, **kwargs: None): builder = CoroutineMockBuilder() return builder.addDelegate(f).build().mock() class CoroutineMock(object): # Handy for debugging failing tests in the debugger. __blocking_dict = {} def __...
self.__startingEvent.clear() self.__endingEvent.set() return MagicMock(wraps=cr) def start(self): return self.__startingEvent def end(self): return self.__endingEvent def unblock(self):
self.__block.set() def mock(self): return self.__mock async def waitForSingleCall(self): await self.start().wait() self.unblock() await self.end().wait() class CoroutineMockBuilder(object): def __init__(self): self.__block = None self.__returnSequence = ...
tijptjik/thegodsproject
plugins/i18n_subsites/i18n_subsites.py
Python
mit
17,012
0.00047
"""i18n_subsites plugin creates i18n-ized subsites of the default site This plugin is designed for Pelican 3.4 and later """ import os import six import logging import posixpath from copy import copy from itertools import chain from operator import attrgetter from collections import OrderedDict from contextlib impo...
'''Transform a Page to a hidden Page''' page.status = 'hidden' return page class GeneratorInspector(object): '''Inspector of generator instances''' generators_info = { ArticlesGenerator: { 'tran
slations_lists': ['translations', 'drafts_translations'], 'contents_lists': [('articles', 'drafts')], 'hiding_func': article2draft, 'policy': 'I18N_UNTRANSLATED_ARTICLES', }, PagesGenerator: { 'translations_lists': ['translations', 'hidden_translations'], ...
angus-ai/angus-service-facedetection
angus/services/__init__.py
Python
apache-2.0
915
0
# -*- coding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
aw 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 # under the License. """ Service for face detection. "...
odevsp/ckanext-api_basic_functions
setup.py
Python
agpl-3.0
3,241
0.001543
from setuptools import setup, find_packages # Always prefer setuptools over distutils from codecs import open # To use a consistent encoding from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the relevant file with open(path.join(here, 'README.rst'), encoding='utf-8') as...
ypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ # How mature is this project? Common values are # 3 - Alpha # 4 - Beta # 5 - Production/Stable 'Development Status :: 4 - Beta', # Pick your license as you wish (should match "licens
e" above) 'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)', # Specify the Python versions you support here. In particular, ensure # that you indicate whether you support Python 2, Python 3 or both. 'Programming Language :: Python :: 2.6', 'Pro...
McGillX/edx_data_research
edx_data_research/reporting/basic/forum_body_extraction_for_word_cloud.py
Python
mit
1,989
0.004525
''' This module extracts all of the comments and comment threads from the forum of a given course. Using NLTK, all of the comments and comment threads will be parsed into a list of words which will be then used to create a word cloud using http://www.wordle.net/create Usage: python forum_body_extraction_for_word_...
'http', 'https
'] tokens = [] for item in body_data: words = [] for word in nltk.word_tokenize(item): clean_word = word.lower().encode('utf-8').strip('\'\"\-,.:;!?()[]{}=#*_$/%+&<>') if clean_word and clean_word not in stopwords.words('english') and len(clean_word) > 2 and '\'' not in clean_word and clean_word...
SachinKonan/Windows-RPI-Vision-Framework
HttpServer/check.py
Python
mit
95
0.010526
from urllib.request import urlopen html = urlopen("http://12
7.0.0.1:9090/cam.mjpg"
) print(html)
Fritzip/AGGP
src/main.py
Python
gpl-2.0
997
0.016048
#! /usr/bin/python # -*- coding: utf-8 -*- # Dependancies : networkx, numpy, graphviz, matplotlib ## python main.py -h ## usage: main.py [options] ## Biological Graph Generator ## optional arguments: ## -h, --help show this help messag
e and exit ## -p, --param Ask for every parameters of the simulation ## -v, --verbose ## -q, --quiet ## --no-progress Disable the progress bar ## -f FREQ, --freq FREQ Frequency of displaying informations ## -s, --no-save Do not save and plot individuals ## -t, --stat ...
stats graphs ## -d, --delete Delete all output (files, graphs and pictures) from ## previous run from population import * #################################################################### # Main ##########################################...
Paytokens/paytokensd
lib/callback.py
Python
mit
6,281
0.00462
#! /usr/bin/python3 """Callback a callable asset.""" import struct import decimal D = decimal.Decimal from . import (util, config, exceptions, litecoin, util) from . import order FORMAT = '>dQ' LENGTH = 8 + 8 ID = 21 def validate (db, source, fraction, asset, block_time, block_index, parse): cursor = db.curso...
ex'], tx['source'], asset, callback_total, action='callback', event=tx['tx_hash']) # Holders. for output in outputs: assert call_price * output['callback_quantity'] == int(call_price * output['callback_quantity']) util.debit(db, tx['block_index'], output['address'], asset, outpu...
['address'], config.XPT, int(call_price * output['callback_quantity']), action='callback', event=tx['tx_hash']) # Add parsed transaction to message-type–specific table. bindings = { 'tx_index': tx['tx_index'], 'tx_hash': tx['tx_hash'], 'block_index': tx['block_index'], 'source':...
hecchi777/S3-SlaacSecuritySolution
impacket-0.9.11/impacket/eap.py
Python
apache-2.0
1,437
0.011134
# Copyright (c) 2003-2013 CORE Security Technologies # # This software is provided under under a slightly modified version # of the Apache Software License. See the accompanying LICENSE file # for more information. # # $Id$ # # Description: # EAP packets # # Author: # Aureliano Calvo from impacket.helper import Pro...
anded(ProtocolPacket): """EAP expanded data according to RFC 3748, section 5.7""" WFA_SMI = 0x00372a SIMPLE_CONFIG = 0x00000001 header_size = 7 tail_size = 0 vendor_id = ThreeBytesBigEndian(0) vendor_type = Long(3, ">") class EAPR(ProtocolPacket): """It represents a request o...
EXPANDED = 0xfe header_size = 1 tail_size = 0 type = Byte(0) class EAP(ProtocolPacket): REQUEST = 0x01 RESPONSE = 0x02 SUCCESS = 0x03 FAILURE = 0x04 header_size = 4 tail_size = 0 code = Byte(0) identifier = Byte(1) length = Word(2, ">") ...