content string |
|---|
"""
test_experiments.py: Allow a user to test all experiments in the container.
The experiments are assumed to be installed at /scif/apps
Copyright (c) 2017, Vanessa Sochat
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provide... |
import numpy as np
import matplotlib.pyplot as plt
import utilities.imaging.man as man
import utilities.imaging.fitting as fit
import scipy.ndimage as nd
from linecache import getline
import astropy.io.fits as pyfits
import pdb
def readCylScript(fn,rotate=np.linspace(.75,1.5,50),interp=None):
"""
Load in data ... |
# -*-coding:Utf-8 -*
# ----------------------------------------------------------------------
# Plot correlations between the parameters
# ----------------------------------------------------------------------
# External libraries
# ----------------------------------------------------------------------
import sys
imp... |
#!/usr/bin/python
# vim: set expandtab tabstop=4 shiftwidth=4:
#
# Converts an items.txt (from INVedit) into a YAML format
#
# Does some special processing on a few magic numbers, alas.
#
# Really we should use PyYAML to do the writing, but I didn't feel
# like taking the time to figure out how to get the output
# for... |
from qisrc.test.conftest import TestGitWorkTree
import qisrc.manifest
def test_check(qisrc_action, git_server):
# Get a correct xml file from the server:
manifest_url = git_server.manifest_url
git_server.create_repo("foo.git")
qisrc_action("init", manifest_url)
# copy it to an other place, make a... |
import datetime
import http.cookiejar as cookielib
import json
import re
import sys
import urllib
import urllib.request as urllib2
import requests
from lxml import html
from pyquery import PyQuery
from termcolor import colored
from .. import model
class TweetManager:
def __init__(self):
pass
@stat... |
"""
map functions for APL operators
UNDER DEVELOPMENT
The functions in this module implement APL operators. Typically, they use
an iterator object or function defined in operatorIterators.
Operators are APL's equivalent of higher order functions: they operate
on APL functions and quantities... |
"""
Lyle Scott, III
<EMAIL>
http://digitalfoo.net
Copyright (c) 2012 Lyle Scott, III
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
t... |
# -*- coding: utf-8 -*-
from helper import IcebergUnitTestCase, get_api_handler
from helpers.login_utils import IcebergLoginUtils
class ClientMerchant(IcebergUnitTestCase):
@classmethod
def setUpClass(cls):
"""
my_context_dict: Create a context dictionary to share some results between tests
... |
"""Hosts an interface for the BIG-IP Monitor Resource.
This module references and holds items relevant to the orchestration of the F5
BIG-IP for purposes of abstracting the F5-SDK library.
"""
# coding=utf-8
#
# Copyright (c) 2017-2021 F5 Networks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"... |
# -*- coding: utf-8 -*-
#import re
from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.safestring import mark_safe
from django.core.mail import send_mail
import entrez
from entrez.settings import *
from entrez.managers import EntrezEntr... |
from math import pi
from math import radians
import numpy as np
from numpy import dot
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # NOQA
from prototype.utils.euler import euler2rot
from prototype.models.gimbal import GimbalModel
from prototype.viz.common import axis_equal_3dplot
class P... |
import re
import time
import os
import requests
import json
from shutil import copyfile
from subprocess import run, Popen, check_output
from os.path import join as pjoin
import pio_tests.globals as globals
def srun(command):
""" Runs a shell command given as a `str`
Raises: `subprocess.CalledProcessError` when exi... |
"""Flower command"""
import os
import signal
import daemon
from daemon.pidfile import TimeoutPIDLockFile
from airflow.configuration import conf
from airflow.utils import cli as cli_utils
from airflow.utils.cli import setup_locations, sigint_handler
@cli_utils.action_logging
def flower(args):
"""Starts Flower, C... |
import numpy as np
import re
import math
from haversine import haversine
from data import sensors
from scipy.interpolate import spline, interp1d
from scipy.stats import spearmanr
from itertools import izip
from lxml import etree
def remove_cancelled_data(c_cancelled_ids, c_data, r_cancelled_ids, r_data):
r_data ... |
"""
Represents a Paraview State-fime (pvsm) and manipulates it
"""
from xml.dom.minidom import parse
import xml.dom
from os import path
import os
import shutil
import glob
from PyFoam.Error import error
from PyFoam import configuration as config
from tempfile import mkstemp
class StateFile(object):
"""The actual... |
class Header(object):
"""A header to specify specific handling instructions for your email.
If the name or value contain Unicode characters, they must be properly
encoded. You may not overwrite the following reserved headers:
x-sg-id, x-sg-eid, received, dkim-signature, Content-Type,
Content-Transf... |
__author__ = 'abhishekanurag'
'''
Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:
Only one letter can be changed at a time
Each intermediate word must exist in the dictionary
For example,
Given:
start = "hit"
end = "cog"
dict = ["ho... |
import time
from typing import Optional, Tuple
from h11._receivebuffer import ReceiveBuffer
from mitmproxy import http, connection
from mitmproxy.net import server_spec
from mitmproxy.net.http import http1
from mitmproxy.proxy import commands, context, layer, tunnel
from mitmproxy.utils import human
class HttpUpstr... |
import unittest
import sys
import os
sys.path.append('bin')
from umdinst import wrap
class TestRunProgram(unittest.TestCase):
def setUp(self):
self.tempfilename = 'emptyfile' # This is in createfile.sh
self.failIf(os.path.exists(self.tempfilename))
# Find the "touch" program
if os.path.exists('... |
#!/usr/bin/env python
"""Downloads GitHub Actions release artifacts."""
import argparse
import io
import pathlib
import zipfile
import requests
WORKFLOW_RUN_ARTIFACTS_URL = "https://api.github.com/repos/indygreg/python-zstandard/actions/runs/{run_id}/artifacts"
def download_artifacts(token: str, run_id: str, dest... |
import sys
import time
from pandaharvester.harvestercore.queue_config_mapper import QueueConfigMapper
from pandaharvester.harvestercore.job_spec import JobSpec
queueName = sys.argv[1]
queueConfigMapper = QueueConfigMapper()
queueConfig = queueConfigMapper.get_queue(queueName)
jobSpec = JobSpec()
jobSpec.jobParams =... |
"""Defines the flask web server app."""
import constants
import database_reader
import database_writer
import json
import news_fetcher
from flask import Flask, request
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
@app.route("/updateStories")
def update_stories():
"""Update the database."""
n... |
import sys
import pkg_resources
import psoap
def main():
"""
Available from command line as ``psoap-initialize``
"""
import argparse
parser = argparse.ArgumentParser(description="Initialize a new directory to do inference.")
parser.add_argument("--check", action="store_true", help="To help ... |
from django.db import models
class ProductionDatasetsExec(models.Model):
name = models.CharField(max_length=200, db_column='NAME', primary_key=True)
taskid = models.DecimalField(decimal_places=0, max_digits=10, db_column='TASK_ID', null=False, default=0)
status = models.CharField(max_length=12, db_column='... |
# -*- coding: utf-8 -*-
"""all procedures for recipes"""
import logging
from typing import List
import pandas as pd
from .. helpers import debuggable
from .. model.ingredient import DataPointIngredient
from .. model.chef import Chef
logger = logging.getLogger('trend_bridge')
@debuggable
def trend_bridge(chef: Ch... |
import pandas as pd
def parse_string(string):
"""
Normalize a string by stripping out whitespace and converting to uppercase.
In case the string contains annotations for a mutated region (denoted by
characters between underscores (i.e. "QYY_LS_YY"), parse out the start/stop
of the mutated region. I... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import socket
from netaddr import IPNetwork
from lib.tools import NmapScanner
from .base import BaseInspector
from ..arin.request import NetworksArinRequest, NetworkArinRequest
from ..geolocation import IpGeolocator
from lib import FilesystemHelper
clas... |
import itertools
from django.conf import settings
from django.db import models
from django.db.models.sql import compiler
from django.db.models.sql.constants import LOUTER
from django.db.models.sql.datastructures import Join
from django.utils import translation as translation_utils
def order_by_translation(qs, fieldn... |
# encoding: utf-8
from owslib.etree import etree
from owslib import crs, util
from owslib.util import testXMLValue, testXMLAttribute, nspath_eval, xmltag_split, dict_union, extract_xml_list
from owslib.namespaces import Namespaces
def get_namespaces():
n = Namespaces()
namespaces = n.get_namespaces(["sml","gm... |
import logging
log = logging.getLogger(__name__)
from pyramid.view import (
view_config,
view_defaults,
)
from pyramid.exceptions import BadCSRFToken
from pyramid.httpexceptions import (
HTTPSeeOther,
HTTPNotFound,
HTTPBadRequest,
)
from pyramid.security impor... |
"""A simple tool to decode a CFSR register from the command line
Example usage:
$ python -m pw_cpu_exception_cortex_m.cfsr_decoder 0x00010100
20210412 15:09:01 INF Exception caused by a usage fault, bus fault.
Active Crash Fault Status Register (CFSR) fields:
IBUSERR Bus fault on instruction fetch.
UN... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'toolManager.ui'
#
# by: PyQt4 UI code generator 4.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
... |
__author__ = 'Ostico <<EMAIL>>'
import struct
import sys
from ..exceptions import PyOrientBadMethodCallException, \
PyOrientCommandException, PyOrientNullRecordException
from ..otypes import OrientRecord, OrientRecordLink, OrientNode
from ..hexdump import hexdump
from ..constants import BOOLEAN, BYTE, BYTES, CHA... |
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.utils import timezone
import logging
import json
import provider.oauth2
from provider.oauth2.models import AccessToken
# OAuth exception class
class OAuthError(RuntimeError):
def __init__(self, message='OAuth err... |
# coding: utf-8
from abc import ABCMeta
import asyncio
import json
from aiohttp import web, MsgType
from bson import json_util
from django.conf import settings
from django.utils.timezone import now
from parkkeeper import models
from parkkeeper.event import async_recv_event, get_sub_socket
from parkkeeper.const import M... |
# coding: utf-8
"""
Phaxio API
API Definition for Phaxio
OpenAPI spec version: 2.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
# import models into model package
from .account_status import AccountStatus
from .account_status_da... |
"""Utilities related to loggers and logging."""
from contextlib import contextmanager
import logging
import sys
import threading
try:
import colorlog
except ImportError:
colorlog = None
DEBUG = 'debug'
INFO = 'info'
LOG_LEVELS = {
DEBUG: logging.DEBUG,
INFO: logging.INFO
}
class ThreadLogContext(objec... |
# -*- coding: utf-8 -*-
"""CA Observer
Copyright (C) 2014 Michael Davidsaver
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 ver... |
# -*- coding: utf-8 -*-
import sys
import abc
import json
from six import with_metaclass
from payplug import config, exceptions
from payplug.__version__ import __version__
class HttpRequest(with_metaclass(abc.ABCMeta)):
"""
Generic interface to abstract an HTTP Request.
"""
def _raise_unrecoverable_er... |
import sys
import colorama
import urllib2
import socket
import time
# Static vars
backup = ['technical problem,12,99','with score web server,12,88','service will be resumed,12,77','soon!! lots of apologies!!,12,77','errot monkey,0,1']
errotmonkey = "errot monkey,-999,-999";
# Argument error checking
if len(sys.argv) ... |
'''
Created on 19/12/2013
@author: Nacho
'''
from lpentities.measurement_unit import MeasurementUnit
class Indicator(object):
"""
classdocs
"""
#Simulated Enum Values
INCREASE = "increase"
DECREASE = "decrease"
IRRELEVANT = "irrelevant"
#Possible topics
_topics_set = ['CLIMATE_... |
"""Allows to configuration ecoal (esterownik.pl) pumps as switches."""
import logging
from typing import Optional
from homeassistant.components.switch import SwitchDevice
from . import AVAILABLE_PUMPS, DATA_ECOAL_BOILER
_LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add_entities, discovery_... |
"""
Module for generating distractors
"""
from knowledge.namespaces import ONTOLOGY, TERM
from random import sample, shuffle, random
# some terms to use if there is not enough of them in the article context
TERMS_OF_TYPE = {
ONTOLOGY['Agent']: [
TERM['Popeye_the_Sailor_Man'],
TERM['Asterix'],
... |
#!/usr/bin/env python2.7
# settings are read from the files mirror_url and mirror_path. These
# files should just contain url and path, respectively, without
# anything else.
# #### IMPORTANT NOTE ####
# In mirror_url and mirror_path, please provide URL and path without
# trailing slashes!
import hashlib, requests, o... |
import time
import numpy as np
import tensorflow as tf
import awesome_gans.image_utils as iu
import awesome_gans.infogan.infogan_model as infogan
from awesome_gans.datasets import CelebADataSet as DataSet
from awesome_gans.datasets import DataIterator
np.random.seed(1337)
results = {'output': './gen_img/', 'model':... |
from twisted.internet.protocol import Protocol, ClientFactory
from twisted.web.proxy import Proxy, ProxyRequest
from twisted.python import log
import urlparse
class ConnectProxyRequest(ProxyRequest):
"""HTTP ProxyRequest handler (factory) that supports CONNECT"""
connectedProtocol = None
def process(se... |
from django.test import TestCase
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from tasks import models
class ExtTestCase(TestCase):
def create_and_log_in_user(self):
user = User.objects.create(username='test_user', email='<EMAIL>')
user.set_password('pw'... |
""" Implements base unit conversion style programming
by monkey patching Pint
"""
# Modified:
# ------------------------------------------------------------
# Imports
# ------------------------------------------------------------
from unit import UnitRegistry
from quantity import _Quantity
Units = UnitRegist... |
number = '''
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
3... |
import sys
import socket
from socket import timeout as SocketTimeout
try: # Python 3
from http.client import HTTPConnection as _HTTPConnection, HTTPException
except ImportError:
from httplib import HTTPConnection as _HTTPConnection, HTTPException
class DummyConnection(object):
"Used to detect a ... |
from gettext import translation
from bottle import *
from jinja2 import Environment, FileSystemLoader
from services.hocrService import HocrService
from services.imageService import ImageService
from services.mailService import MailService
from services.projectService import ProjectService
from services.queueService im... |
import shutil,os, stat,shlex, ntpath,argparse,fileinput, sys
class MvLnFile:
def __init__(self, src, dst):
self.src = src
self.dst = dst
class Converter:
def __init__(self,str):
self.str = str
def getLines(self):
return self.str.splitlines()
def splitLine(line):
srcdest = line.split(" ")
retu... |
from abc import ABCMeta, abstractmethod
import logging
from django.urls import resolve
from six import add_metaclass
logging.getLogger("").addHandler(logging.NullHandler())
# pylint: disable=unused-argument
# This class specifies method signatures; while pylint is intelligent enough to ignore unused args in abstra... |
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import sys
import time
import numpy as np
import tensorflow as tf
import tensorflow_datasets as tfds
from nmt.bert_tokenization import *
from nmt.transformer import *
from nmt.translate import *
MAX_SEQ_LENGTH = 128
BUFF... |
"""Classes relating to widgets."""
__author__ = 'Sean Lip'
import os
from core.domain import obj_services
from core.domain import rule_domain
import feconf
import jinja_utils
import utils
import json
class AnswerHandler(object):
"""Value object for an answer event stream (e.g. submit, click, drag)."""
de... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
Filename : hello.py
author : Crow
creat time: 2017-06-03
updata time: 2017-06-03
'''
import sys
import datetime
sys.path.append('/Volumes/DATA/virtualboxHost/ubuntu16.04_64/x12_engine/bin')
import x12_python
def smartserverinit():
#print("this is smartserverini... |
import logging
import tornado.web
import tornado.wsgi
import tornado.ioloop
import tornado.options
from tornado.httpserver import HTTPServer
from tornado.web import FallbackHandler, url
import django.core.handlers.wsgi
from pkg_resources import resource_filename
from krum.content.streamer import StreamingContentHandler... |
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
"""
Test creation of a Tex document with nested includes in a
subdir that needs to create a fig.pdf.
Test courtesy Rob Managan.
"""
import TestSCons
test = TestSCons.TestSCons()
latex = test.where_is('latex')
epstopdf = test.where_is('epstopdf')
if not... |
from django.views.generic import ListView, DetailView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.utils.decorators import method_decorator
from django.core.urlresolvers import reverse, reverse_lazy
from django.contrib.auth.decorators import login_required
from models import *
fr... |
from pycp2k.inputsection import InputSection
from ._each353 import _each353
class _total_dipole4(InputSection):
def __init__(self):
InputSection.__init__(self)
self.Section_parameters = None
self.Add_last = None
self.Common_iteration_levels = None
self.Filename = None
... |
# -*- coding: utf-8 -*-
''' Drawing of diagrams showing a law of internal
forces (or any other input) on linear elements
'''
__author__= "Luis C. Pérez Tato (LCPT) Ana Ortega (AOO)"
__copyright__= "Copyright 2015, LCPT AOO"
__license__= "GPL"
__version__= "3.0"
__email__= "<EMAIL> <EMAIL>"
import vtk
class LUT... |
import unittest
from mapserv.lyric.table import Table
from mapserv.query.util import make_target
from mapserv.lyric.expression import *
from mapserv.lyric.render import *
from mapserv.interfaces.query.ttypes import *
class RenderSelectTestCase(unittest.TestCase):
def setUp(self):
super(RenderSelectTestCas... |
from collections import defaultdict
from itertools import chain
from flask import flash
from flask import redirect
from flask import render_template
from sqlalchemy import func
from tracker import db
from tracker import tracker
from tracker.advisory import advisory_extend_model_from_advisory_text
from tracker.advisor... |
import Tkinter as tk
class simpleapp_tk(tk.Tk):
def __init__(self,parent):
tk.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def initialize(self):
self.grid()
self.entryVariable = tk.StringVar()
self.entry = tk.Entry(self, textvariable=self.ent... |
import redis
import lastfmapi
from pylast import *
from app.lastfmAPI import artist
from app.querys import querys
class lastQuerys():
def __init__(self):
self.redis_db = redis.StrictRedis(host="lastfmredis", port=6379, db=0, charset="utf-8", decode_responses=True)
# self.redis_db = redis.StrictR... |
"""convert OpenDocument (ODF) files to Gettext PO localization files"""
import cStringIO
import zipfile
import lxml.etree as etree
from translate.storage import factory
from translate.storage.xml_extract import unit_tree
from translate.storage.xml_extract import extract
from translate.storage.xml_extract import gene... |
from __future__ import absolute_import
from __future__ import print_function
import json
import logging
import sys
from .command import ClusterManagerCmd
class PreferredReplicaElectionCmd(ClusterManagerCmd):
def __init__(self):
super(PreferredReplicaElectionCmd, self).__init__()
self.log = logg... |
"""Add fields from BIOS registry
Revision ID: 2bbd96b6ccb9
Revises: ac00b586ab95
Create Date: 2021-04-29 08:52:23.938863
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '2bbd96b6ccb9'
down_revision = 'ac00b586ab95'
def upgrade():
op.add_column('bios_settin... |
"""
Salamander ALM
Copyright (c) 2016 Djuro Drljaca
This Python module is free software; you can redistribute it and/or modify it under the terms of the
GNU General Public License as published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
This Python module ... |
"""
Drop in serializer mixins.
"""
class FieldPermissionSerializerMixin(object):
"""
Mixin to your serializer class as follows:
class PersonSerializer(FieldPermissionSerializerMixin, serializers.ModelSerializer):
family_names = fields.CharField(permission_classes=(IsAuthenticated(), ))
... |
import copy
from logs import StockLog, CoinsLog, OrderLog, CashLog, EndOrderLog
from drink import Drink
from coins import Coins, NoChangePossibleException
from machine_interfaces import MachineFunc, MachineMaintenance
class InvalidOrderException(Exception): pass
class NotEnoughStockException(Exception): pass
class M... |
#!/usr/bin/env python
from nose.tools import *
from nose import SkipTest
import networkx as nx
from networkx.algorithms import bipartite
from networkx.testing.utils import assert_edges_equal
class TestBiadjacencyMatrix:
@classmethod
def setupClass(cls):
global np, sp, sparse, np_assert_equal
t... |
import numpy as np
from pypcsim import *
from pool import NeuronsPool
from psp import createPSPShape
class Network:
def __init__(self, simulationSettings, modelSettings):
ss, ms = simulationSettings, modelSettings
self.dt = ss.dt
self.simulationRNGSeed = ss.simulationRNGSeed
self.... |
#-*- coding: utf-8 -*-
""" EOSS catalog system
Connects to AWS sqs system and polls notifications created by sentinel2/landsat s3 ingestion processes
"""
__author__ = "Thilo Wehrmann, Steffen Gebhardt"
__copyright__ = "Copyright 2016, EOSS GmbH"
__credits__ = ["Thilo Wehrmann", "Steffen Gebhardt"]
__license__ = "GPL"... |
import os
import hashlib
import gevent
from shemutils.logger import Logger
from shemutils.colors import *
class Checksum(object):
"""
to use this class you need to pass a valid path and a string or int denoting a valid hash algorithm
examples:
checksum = Checksum("file.pdf", 0) or Checksum("file.pdf... |
#!/usr/bin/env python2
from __future__ import print_function
import yaml, os.path, sys
# from https://stackoverflow.com/questions/5574702/how-to-print-to-stderr-in-python
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def parse_page_dict(errors_detected, kv):
(header, pages) = kv
if... |
"""searchio user [options] [<query>]
View and edit user searches.
Usage:
searchio user [-t] [<query>]
searchio -h
Options:
-t, --text Print results as text, not Alfred JSON
-h, --help Display this help message
"""
from __future__ import print_function, absolute_import
from operator import a... |
from telemetry import decorators
from telemetry.testing import tab_test_case
class AboutTracingIntegrationTest(tab_test_case.TabTestCase):
@decorators.Disabled('android',
'win', # https://crbug.com/632871
'chromeos') # https://crbug.com/654044
def testBasicTra... |
import pytest
import gzip
from pprint import pprint as pp
from loqusdb.utils.vcf import (get_vcf, get_file_handle, check_vcf)
from cyvcf2 import VCF
def test_get_file_handle(vcf_path):
## GIVEN the path to a vcf
## WHEN geting the file handle
vcf = get_file_handle(vcf_path)
## THEN assert t... |
'''
Entry point module to run a file in the interactive console.
'''
import os
import sys
import traceback
from pydevconsole import do_exit, InterpreterInterface, process_exec_queue, start_console_server, init_set_return_control_back, \
activate_mpl_if_already_imported
from _pydev_imps._pydev_saved_modules import t... |
#!/usr/bin/python
# @Und3rf10w - 20150618
import socket
from sys import exit,argv
from subprocess import Popen, PIPE, STDOUT
# Defining the connection
def sendbuffer(host,port,buffer):
try:
print "\nSending unique evil buffer to %s:%s" % (host,port)
s = socket.socket(socket.AF_INET, socket.SOCK_STRE... |
# -*- coding: utf-8 -*-
#------------------------------------------------------------
import sys
PY3 = False
if sys.version_info[0] >= 3: PY3 = True; unicode = str; unichr = chr; long = int
if PY3:
import urllib.parse as urlparse # Es muy lento en PY2. En PY3 es nativo
else:
import... |
#!/usr/bin/env python
from pydgutils_bootstrap import use_pydgutils, download
use_pydgutils()
import os
import os.path
import sys
import shutil
import logging
import fnmatch
import pydgutils
from setuptools import setup, find_packages
package_name = 'rabird.auto'
# Convert source to v2.x if we are using python 2.x.... |
from osgeo import ogr, osr
from spatial_reference_tools import shp_proj4_spatial_reference
def lat_lon_to_ogr_point(lon, lat):
""" Converts (lon, lat) to ogr Geometry
:param lon: Longitude, float
:param lat: Latitude, float
:return: osgeo.ogr.Geometry
"""
point = ogr.Geometry(ogr.wkbPoint)
... |
import os
import deluge.component as component
from deluge._libtorrent import lt
from deluge.common import utf8_encoded
from deluge.core.torrent import TorrentOptions
from yarss2.lib import requests
from yarss2.util import common, http, torrentinfo
from yarss2.util.common import GeneralSubsConf, TorrentDownload
from ... |
from __future__ import absolute_import
import os
from django.conf import settings
class UnsupportedMediaPathException(Exception):
pass
def fetch_resources(uri, rel):
"""
Callback to allow xhtml2pdf/reportlab to retrieve Images,Stylesheets, etc.
`uri` is the href attribute from the html link elemen... |
#!/usr/bin/env python
import os
import time
import proctest
import mozunit
from mozprocess import processhandler
here = os.path.dirname(os.path.abspath(__file__))
class ProcTestKill(proctest.ProcTest):
""" Class to test various process tree killing scenatios """
# This test should ideally be a part of te... |
import fcntl
import logging
import os
import struct
import sys
import termios
# Allow from-the-start debugging (vs toggled during load of tasks module) via
# shell env var
if os.environ.get('INVOKE_DEBUG'):
logging.basicConfig(level=logging.DEBUG)
# Add top level logger functions to global namespace. Meh.
log = ... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting model 'Crash'
db.delete_table(u'AppDistribution_crash')
# Removing unique constraint on... |
from codecs import open
from strongsup.example import Context, Example
from strongsup.example_factory import ExampleFactory
from strongsup.rlong.state import RLongAlchemyState, RLongSceneState, RLongTangramsState, RLongUndogramsState
from strongsup.rlong.value import RLongStateValue
from strongsup.rlong.world import R... |
import sys
from PySide import QtGui, QtCore
# Add the pyflowgraph module to the current environment if it does not already exist
import imp
try:
imp.find_module('pyflowgraph')
found = True
except ImportError:
import os, sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(os.path.realpat... |
import sys, json
from PyQt4 import QtGui, QtCore
import unicodedata
class TextSearch:
#Removes accents and lowers the cases.
def normalizeText(self, text):
return ''.join((c for c in unicodedata.normalize('NFD', text) if unicodedata.category(c) != 'Mn')).lower()
def normalStringSearch(self, search... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
'''
数据预处理时的工具
'''
import numpy as np
from PIL import Image
class ImageHelper(object):
'图像助手'
def __init__(self, data=None):
if data is not None:
# 只接受np.ndarray类型
assert isinstance(data, np.ndarray)
# 只接受图像
assert... |
#!/usr/bin/env python
import optparse
import logging
import sys
import os
import gscholar as gs
logger = logging.getLogger('gscholar')
logging.basicConfig(
format='%(asctime)s %(levelname)s %(name)s %(message)s',
level=logging.WARNING
)
def main():
usage = 'Usage: %prog [options] {pdf | "search terms"... |
import expect
from environment import File, Directory
from glslc_test_framework import inside_glslc_testsuite
from placeholder import FileShader
MINIMAL_SHADER = '#version 310 es\nvoid main() {}'
EMPTY_SHADER_IN_CWD = Directory('.', [File('shader.vert', MINIMAL_SHADER)])
ASSEMBLY_WITH_DEBUG_SOURCE = [
'; SPIR-V\n... |
# coding: utf-8
from itertools import groupby, takewhile, dropwhile
from calendar import monthrange
import datetime
import json
import logging
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import AuthenticationForm,... |
"""
Gaussian deconvolution.
"""
from math import sin, cos, atan, sqrt, pi
def deconv(fmaj, fmin, fpa, cmaj, cmin, cpa):
"""
Deconvolve a Gaussian "beam" from a Gaussian component.
When we fit an elliptical Gaussian to a point in our image, we are
actually fitting to a convolution of the physical shap... |
# Powered by Python 2.7
# Export the graph as a JSON object
# Run from the graph you want to export
# To cancel the modifications performed by the script
# on the current graph, click on the undo button.
# Some useful keyboards shortcuts :
# * Ctrl + D : comment selected lines.
# * Ctrl + Shift + D : uncommen... |
from django.test import TestCase
from ajax_select import fields
class TestAutoCompleteSelectWidget(TestCase):
def test_render(self):
channel = 'book'
widget = fields.AutoCompleteSelectWidget(channel)
out = widget.render('book', None)
self.assertTrue('autocompleteselect' in out)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.