code stringlengths 1 199k |
|---|
'''
ÏÂÀý չʾÁËÒ»¸öʵÓÃС¹¤¾ß, Ëü¿ÉÒÔ°Ñ GIF ¸ñʽת»»Îª Python ½Å±¾, ±ãÓÚʹÓà Tkinter ¿â.
'''
import base64, sys
if not sys.argv[1:]:
print "Usage: gif2tk.py giffile >pyfile"
sys.exit(1)
data = open(sys.argv[1], "rb").read()
if data[:4] != "GIF8":
print sys.argv[1], "is not a GIF file"
sys.exit(1)
print ... |
import os,time,argparse,random,paramiko,socket,logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *
from datetime import datetime
def brute_pass(usr,passwd,ip,port):
print "Trying for "+usr+" - "+passwd
ssh=paramiko.SSHClient()
ssh.set_missing_ho... |
from setuptools import setup
setup(name='PyRankinity',
version='0.1',
description='Rankinity API Wrapper - See http://my.rankinity.com/api.en',
author='UpCounsel',
author_email='brad@upcounsel.com',
url='https://www.github.com/upcounsel/pyrankinity',
packages=['pyrankinity'],
i... |
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^external/', include('external.urls')),
url(r'^dev/', include('dev.urls')),
] |
from collections import defaultdict
import re
import sys
from stop_words import STOP_WORD_SET
from collections import Counter
PUNCTUATION_RE = re.compile("[%s]" % re.escape(
"""!"&()*+,-\.\/:;<=>?\[\\\]^`\{|\}~]+"""))
DISCARD_RE = re.compile("^('{|`|git@|@|https?:)")
def remove_stop_words(word_seq, stop_words):
... |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('contacts', '0006_auto_20180423_1629'),
]
operations = [
migrations.AddField(
model_name='contact',
name='recruiter',
field=models.BooleanField(default=False)... |
from __future__ import unicode_literals
import os
import socket
import traceback
from lineup.datastructures import Queue
class Node(object):
def __init__(self, *args, **kw):
self.initialize(*args, **kw)
def initialize(self, *args, **kw):
pass
@property
def id(self):
return '|'.jo... |
from flask import Blueprint
user = Blueprint('user', __name__)
from . import views |
import datetime
import os
import shutil
import time
from files_by_date.utils.logging_wrapper import get_logger, log_message
from files_by_date.validators.argument_validator import ArgumentValidator
logger = get_logger(name='files_service')
class FilesService:
def __init__(self):
raise NotImplementedError
... |
"""
Example taken from http://matplotlib.org/1.5.0/examples/showcase/xkcd.html
"""
import matplotlib.pyplot as plt
import numpy as np
with plt.xkcd():
# Based on "The Data So Far" from XKCD by Randall Monroe
# http://xkcd.com/373/
index = [0, 1]
data = [0, 100]
labels = ['CONFIRMED BY EXPERIMENT', '... |
"""Use python in a more object oriented, saner and shorter way.
First: A word of warning. This library is an experiment. It is based on a wrapper that aggressively
wraps anything it comes in contact with and tries to stay invisible from then on (apart from adding methods).
However this means that this library is probab... |
from collections import OrderedDict as odict
from values import decode_kv_pairs, encode_kv_pairs
from loops import decode_loops, encode_loops
def split_frames(lines):
'''
splits a list of lines into lines that are not part of a frame,
and a list of lines, where each list is part of the same frame.
frame... |
from lighthouse import app
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True) |
""" Python test discovery, setup and run of test functions. """
import re
import fnmatch
import functools
import py
import inspect
import sys
import pytest
from _pytest.mark import MarkDecorator, MarkerError
from py._code.code import TerminalRepr
try:
import enum
except ImportError: # pragma: no cover
# Only a... |
"""
This example uses OpenGL via Pyglet and draws
a bunch of rectangles on the screen.
"""
import random
import time
import pyglet.gl as GL
import pyglet
import ctypes
SCREEN_WIDTH = 700
SCREEN_HEIGHT = 500
RECT_WIDTH = 50
RECT_HEIGHT = 50
class Shape():
def __init__(self):
self.x = 0
self.y = 0
cla... |
import mock
from django.test import TestCase
from mediaviewer.views.signout import signout
class TestSignout(TestCase):
def setUp(self):
self.logout_patcher = mock.patch('mediaviewer.views.signout.logout')
self.mock_logout = self.logout_patcher.start()
self.addCleanup(self.logout_patcher.sto... |
"""
Created on Thu Aug 1 16:10:56 2013
@author: vterzopoulos, abrys
"""
import nibabel
import numpy
from dicom2nifti.image_volume import load, SliceType, ImageVolume
def reorient_image(input_image, output_image):
"""
Change the orientation of the Image data in order to be in LAS space
x will represent the ... |
from java.util import Arrays
from javax.faces.application import FacesMessage
from org.gluu.jsf2.message import FacesMessages
from org.gluu.oxauth.security import Identity
from org.gluu.oxauth.service import UserService, AuthenticationService
from org.gluu.oxauth.util import ServerUtil
from org.gluu.model.custom.script... |
from db_utils import deleteLinksByHost
from db_utils import deleteHost
from db_utils import addNewHost
from db_utils import getAllHosts
from error_message import showErrorPage
from error_message import ErrorMessages
import utils
import webapp2
from google.appengine.api import users
from google.appengine.ext import ndb
... |
from mdp import MDP
from grid import Grid
from scipy.stats import uniform
from scipy.stats import beta
from scipy.stats import expon
import numpy as np
import random
import pyprind
import matplotlib.pyplot as plt
class GridWorld(MDP):
"""
Defines a gridworld environment to be solved by an MDP!
"""
def __init__(se... |
from fam.buffer import buffered_db
cache = buffered_db |
"""
Created on Thu May 05 20:02:00 2011
@author: Tillsten
"""
import numpy as np
from scipy.linalg import qr
eps = np.finfo(float).eps
def mls(B, v, umin, umax, Wv=None, Wu=None, ud=None, u=None, W=None, imax=100):
"""
mls - Control allocation using minimal least squares.
[u,W,iter] = mls_alloc(B,v,umin,umax,[Wv,Wu... |
from __future__ import annotations
import contextlib
import os.path
import shutil
import sys
import pytest
from pre_commit import parse_shebang
from pre_commit.envcontext import envcontext
from pre_commit.envcontext import Var
from pre_commit.util import make_executable
def _echo_exe() -> str:
exe = shutil.which('e... |
r"""
# .---. .-----------
# / \ __ / ------
# / / \( )/ ----- (`-') _ _(`-') <-. (`-')_
# ////// '\/ ` --- ( OO).-/( (OO ).-> .-> \( OO) ) .->
# //// / // : : --- (,------. \ .'_ (`-')----. ,--./ ,--/ ,--.' ,-.
#... |
from django.db.models import fields, ForeignKey, ManyToOneRel, OneToOneRel
from .obj_types import clss
from .search_schema import schema as search_schema
def build_search_filters(cls):
"""Return list of dicts of options for a QueryBuilder filter.
See https://querybuilder.js.org/#filters for details.
"""
... |
"""VGG16 model for Keras.
- [Very Deep Convolutional Networks for Large-Scale Image Recognition](https://arxiv.org/abs/1409.1556)
"""
from __future__ import print_function
from __future__ import absolute_import
import warnings
from keras.models import Model
from keras.layers import Flatten, Dense, Input,Lambda
from ker... |
import gsd.hoomd
import argparse
import time
start = time.time()
parser = argparse.ArgumentParser(description='Subsamble GSD trajectory')
parser.add_argument('fname',metavar='input',type=str,help='trajectory file to be subsampled')
parser.add_argument('ofname',metavar='output',type=str,help='where to write subsampled t... |
"""
othello.py Humberto Henrique Campos Pinheiro
Game initialization and main loop
"""
import pygame
import ui
import player
import board
from config import BLACK, WHITE, HUMAN
import log
logger = log.setup_custom_logger('root')
class Othello:
"""
Game main class.
"""
def __init__(self):
""" Sho... |
"""
Usage:
run.py mlp --train=<train> --test=<test> --config=<config>
run.py som --train=<train> --test=<test> --config=<config>
Options:
--train Path to training data, txt file.
--test Path to test data, txt file.
--config Json configuration for the network.
"""
from redes_neurais.resources.manage... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import io
import string
import random
class StringBuf(object):
def __init__(self, s):
self.s = s
self.pos = 0
def peek(self):
return self.s... |
from __future__ import absolute_import, unicode_literals
from copy import copy
import json
from peewee import Model, CharField, ForeignKeyField, IntegerField
from utils.modules import BaseModule, modules
from utils.modules.api import api as pmb_api
from utils import db
class Action(Model):
class Meta:
datab... |
import _plotly_utils.basevalidators
class SourceattributionValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self,
plotly_name="sourceattribution",
parent_name="layout.mapbox.layer",
**kwargs
):
super(SourceattributionValidator, self).__init__(
... |
f = open("birds.txt", "r")
data = f.read()
f.close()
lines = data.split("\n")
print("Wrong: The number of lines is", len(lines))
for l in lines:
if not l:
# Can also do this: if len(l) == 0
lines.remove(l)
print("Right: The number of lines is", len(lines)) |
from boto.ses import SESConnection
import os
def sendmail(name, comment):
source = "patte.wilhelm@googlemail.com"
subject = "Kommentar eingegangen"
body = 'Es wurde ein neues Wetter bewertet. Von: ' + name + ': ' + comment
to_addresses = ["patte.wilhelm@googlemail.com"]
connection = SESConnection(aw... |
import os
import os.path
import sys
import pygame
from buffalo import utils
from buffalo.scene import Scene
from buffalo.label import Label
from buffalo.button import Button
from buffalo.input import Input
from buffalo.tray import Tray
from camera import Camera
from mapManager import MapManager
from pluginManager impor... |
"""Contains the drivers and interface code for pinball machines which use the Multimorphic R-ROC hardware controllers.
This code can be used with P-ROC driver boards, or with Stern SAM, Stern
Whitestar, Williams WPC, or Williams WPC95 driver boards.
Much of this code is from the P-ROC drivers section of the pyprocgame ... |
"""
Builder for Atmel AVR series of microcontrollers
"""
from os.path import join
from time import sleep
from SCons.Script import (COMMAND_LINE_TARGETS, AlwaysBuild, Default,
DefaultEnvironment, SConscript)
from platformio.util import get_serialports
def BeforeUpload(target, source, env): ... |
"""
[source](https://colab.research.google.com/github/google/eng-edu/blob/main/ml/cc/exercises/numpy_ultraquick_tutorial.ipynb?utm_source=mlcc)
> create/manipulate vectors and matrices
"""
import numpy as np
one_dim_array = np.array([1.3, 3.7, 4.3, 5.6, 7.9])
print(one_dim_array)
two_dim_array = np.array([[1.3, 3.7], [... |
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
SQLALCHEMY_TRACK_MODIFICATIONS = False
MAIL_SERVER = 'smtp.googlemail.com'
MAIL_PORT = 587
MAIL_USE_TLS = True
... |
"""TailorDev Biblio
Bibliography management with Django.
"""
__version__ = "2.0.0"
default_app_config = "td_biblio.apps.TDBiblioConfig" |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='SkipRequest',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=... |
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('snippets', '0006_snippet_last_used'),
]
operations = [
migrations.AlterModelOptions(
... |
import itertools, logging
from gibbs.models import CommonName, Compound, Enzyme
from haystack.query import SearchQuerySet
class Error(Exception):
pass
class IllegalQueryError(Error):
pass
class Match(object):
"""An object containing a string match and it's score."""
def __init__(self, key, value, score)... |
from sys import version_info
import copy
import types
try:
from collections import OrderedDict
except ImportError: # pragma: nocover
# Django < 1.5 fallback
from django.utils.datastructures import SortedDict as OrderedDict # noqa
if version_info < (2, 7, 0):
def _deepcopy_method(x, memo):
retu... |
import os, sys, re
import ConfigParser
import optparse
import shutil
import subprocess
import difflib
import collections
def parse_options():
'''
This function parses the command line arguments and returns an optparse object.
'''
parser = optparse.OptionParser("pddi.py [--dummy=DUMMY_DIR] -i INPUT_FILE ... |
from __future__ import print_function
import torch as th
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
from torch.nn.utils.rnn import PackedSequence, pack_padded_sequence, pad_packed_sequence
class Vocabulary(object):
def __init__(self, tokens,... |
import mongoengine as db
class User(db.Document):
user_id = db.StringField(required=True, unique=True)
created = db.DateTimeField(required=True)
last_login = db.DateTimeField()
nino = db.StringField()
linked_ids = db.ListField(db.ReferenceField('User'), default=[])
def link(self, other):
... |
'''
Module that update the software and its databases
'''
import os
import shutil
from sys import exit
import os.path
import tarfile
import requests
from bs4 import BeautifulSoup
from ...base import *
from ...sentry import sentry
from ...clint import progress
class Updater(object):
def __init__(self, path, ver, url... |
from venv import _venv
from fabric.api import task
@task
def migrate():
"""
Run Django's migrate command
"""
_venv("python manage.py migrate")
@task
def syncdb():
"""
Run Django's syncdb command
"""
_venv("python manage.py syncdb") |
import sys
import os.path
from xml.etree import ElementTree as et
if len(sys.argv) != 3:
raise Exception("Expected at least 2 args, {} given!".format(len(sys.argv) - 1))
version = sys.argv[1]
csprojPath = sys.argv[2]
if not os.path.isfile(csprojPath):
raise Exception("File {} does not exist!".format(csprojPath)... |
from setuptools import setup, find_packages
import sys
extra_install = []
if sys.version_info <= (3,1):
extra_install.append('futures')
if sys.version_info <= (3,6):
extra_install.append('pysha3')
setup(
name="moneywagon",
version='{{ version }}',
description='Next Generation Cryptocurrency Platform... |
from heapq import heapify, heapreplace
class Solution(object):
def kthSmallest(self, matrix, k):
"""
:type matrix: List[List[int]]
:type k: int
:rtype: int
"""
if len(matrix) is 1:
return matrix[0][0]
z = zip(*matrix[1:])
h = [(matrix[0][i]... |
import json, sys, glob, datetime, math, random, pickle, gzip
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import chainer
from chainer import computational_graph as c
from chainer import cuda
import chainer.functions as F
from chainer import optimizers
class AutoEncoder:
def __init__... |
""" This file contains code for working on lists and dictionaries. """
def moreThanOne(dict, key):
""" Checks if a key in a dictionary has a value more than one.
Arguments:
dict -- the dictionary
key -- the key
Returns:
True if the key exists in the dictionary and the value is at least one, otherwise false
... |
desc = 'Color bars'
phash = ''
def plot():
import matplotlib as mpl
from matplotlib import pyplot as pp
from matplotlib import style
import numpy as np
# Make a figure and axes with dimensions as desired.
fig, ax = pp.subplots(3)
# Set the colormap and norm to correspond to the data for whic... |
import lexer
s = "program id; var beto: int; { id = 1234; }"
lexer.lexer.input(s)
for token in lexer.lexer:
print token |
'''
Created on 2013-01-22
@author: levi
'''
import unittest
import time
from path_condition_generator import PathConditionGenerator
from t_core.matcher import Matcher
from t_core.rewriter import Rewriter
from t_core.iterator import Iterator
from t_core.messages import Packet
from t_core.tc_python.frule import FRule
fro... |
'''
plans.py
'''
from forex_python.converter import CurrencyCodes
from .base import Base
class Plan(Base):
'''
Plan class for making payment plans
'''
interval = None
name = None
amount = None
plan_code = None
currency = None
id = None
send_sms = True
send_invoices = True
... |
from __future__ import unicode_literals
from jcconv import kata2hira, hira2kata
from itertools import chain
from printable import PrintableDict, PrintableList
__by_vowels = PrintableDict(**{
u'ア': u'ワラヤャマハナタサカアァ',
u'イ': u'リミヒニちシキイィ',
u'ウ': u'ルユュムフヌツスクウゥ',
u'エ': u'レメヘネテセケエェ',
u'オ': u'ヲロヨョモホノトソコオォ',
}... |
import requests, os
from bs4 import BeautifulSoup
url = 'http://www.nytimes.com'
def extractArticles (url):
data = requests.get(url)
soup = BeautifulSoup(data.text, 'html.parser')
articles = []
for article in soup.find_all('article'):
if article.find('h2') != None and article.find('h2').find('a'... |
from base import IfbyphoneApiBase
class Addons(IfbyphoneApiBase):
def list(self):
"""List all purchased Addons for an account
"""
self.options['action'] = 'addons.list'
return self.call(self.options)
def purchase(self, **kwargs):
"""Purchase an addon for an account
... |
"""Utility functions.
"""
from collections import OrderedDict
from .bsd_checksum import bsd_checksum # make name available from this module
def n_(s, replacement='_'):
"""Make binary fields more readable.
"""
if isinstance(s, (str, unicode, bytearray)):
return s.replace('\0', replacement)
retur... |
import pytest
from tests import utils
from app import create_app
@pytest.yield_fixture(scope='session')
def flask_app():
app = create_app(flask_config_name='testing')
from app.extensions import db
with app.app_context():
db.create_all()
yield app
db.drop_all()
@pytest.yield_fixture()... |
import functools
from typing import Any, Callable, Dict, Generic, List, Optional, TypeVar
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transp... |
class Heap(object):
def __init__(self, data=[]):
if len(data) == 0:
self.data = [None] * 100
else:
self.data = data
self.__size = sum([1 if item is not None else 0 for item in self.data])
self.__heapify()
def size(self):
return self.__size
def ... |
from gi.repository import Gtk, Gdk
class MapEntity:
# self.x = None
# self.y = None
# self.name = None
# self.texture = None
def getCoords(self):
return self.x,self.y
def getx(self):
return self.x
def gety(self):
return self.y
def setCoords(self,xcoord,ycoord):
self.x = xcoord
self.y = ycoord
def get... |
"""
.. module:: test
test
*************
:Description: test
:Authors: bejar
:Version:
:Created on: 10/02/2015 9:50
"""
__author__ = 'bejar'
from MeanPartition import MeanPartitionClustering
from kemlglearn.datasets import cluster_generator
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs, load_iri... |
import eventmaster
import time
import random
import sys
import unittest
import sys
class InputsTestCase(unittest.TestCase):
def setUp(self):
self.s3 = E2S3.E2S3Switcher()
self.s3.set_verbose(0)
self.s3.set_CommsXML_IP("127.0.0.1")
self.s3.set_CommsXML_Port(9876)
if not self.s... |
""" synrcat
gaussian mixture model
"""
import sys
import os
import numpy as np
import logging
from collections import OrderedDict
from astropy.table import Table
from pypeline import pype, add_param, depends_on
from syn import Syn
from syncat.errors import NoPoints
import syncat.misc as misc
import syncat.fileio as fil... |
import re
from jinja2 import Environment
from .observable import Observable
def get_attribute(render_data, variable):
levels = variable.split('.')
r = render_data
for level in levels:
if hasattr(r, level):
r = getattr(r, level)
else:
r = r.get(level) or {}
if not ... |
import os
import os.path
import stat
import hashlib
import sys
SHA1_MAX_BYTES_READ_DEFAULT = float("inf") # defaults to read entire file
def sha1_hex_file(filepath, max_bytes=None):
"""
Returns the SHA1 of a given filepath in hexadecimal.
Opt-args:
* max_bytes. If given, reads at most max_bytes bytes fr... |
'''
Test
'''
import sys
sys.path.append('.')
from tornado.testing import AsyncHTTPSTestCase
from application import APP
class TestSomeHandler(AsyncHTTPSTestCase):
'''
Test
'''
def get_app(self):
'''
Test
'''
return APP
def test_index(self):
'''
Test in... |
from typing import Any
from azure.core.configuration import Configuration
from azure.core.pipeline import policies
from ._version import VERSION
class SynapseClientConfiguration(Configuration):
"""Configuration for SynapseClient
Note that all parameters used to create this instance are saved as instance
att... |
from django.db import models
from datetime import datetime
class Place(models.Model):
"""
Holder object for basic info about the rooms
in the university.
"""
room_place = models.CharField(max_length=255)
floor = models.IntegerField()
def __unicode__(self):
return self.room_place
clas... |
from cherrydo.utils import is_cherrydo_project
class CherryDoException(Exception):
pass
class BaseGenerator(object):
def __init__(self, name, params):
self.name = name
self.params = params
def formatted_name(self):
return self.name.replace('_', ' ').title().replace(' ', '')
def v... |
from libdotfiles.packages import try_install
from libdotfiles.util import HOME_DIR, PKG_DIR, copy_file
try_install("alacritty")
copy_file(
PKG_DIR / "alacritty.yml",
HOME_DIR / ".config" / "alacritty" / "alacritty.yml",
) |
from __future__ import print_function, division, absolute_import, unicode_literals
from grako.parsing import graken, Parser
from grako.util import re, RE_FLAGS
__version__ = (2015, 12, 26, 22, 15, 59, 5)
__all__ = [
'BParser',
'BSemantics',
'main'
]
class BParser(Parser):
def __init__(self,
... |
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.utils.html import format_html
from django.forms.util import flatatt
from django.utils.encoding import force_text
from mezzanine.conf import settings
from cartridge.shop.forms import OrderForm
from cartridge.shop import checkout... |
from impact.tests.api_test_case import APITestCase
from impact.tests.factories import JudgingRoundFactory
class TestJudgingRound(APITestCase):
def test_str(self):
judging_round = JudgingRoundFactory()
judging_round_string = str(judging_round)
assert judging_round.name in judging_round_string... |
__author__ = 'sarangis'
from src.ir.function import *
from src.ir.module import *
from src.ir.instructions import *
BINARY_OPERATORS = {
'+': lambda x, y: x + y,
'-': lambda x, y: x - y,
'*': lambda x, y: x * y,
'**': lambda x, y: x ** y,
'/': lambda x, y: x / y,
'//': lambda x, y: x ... |
"""
pyvisa.visa
~~~~~~~~~~~
Module to provide an import shortcut for the most common VISA operations.
This file is part of PyVISA.
:copyright: 2014 by PyVISA Authors, see AUTHORS for more details.
:license: MIT, see COPYING for more details.
"""
from __future__ import division, unicode_literals,... |
"""
Created on Sat May 21 16:43:47 2016
@author: Pratik
"""
from ftplib import FTP
import os
def ftpDownloader(filename, host="ftp.pyclass.com", user="student@pyclass.com", passwd="student123"):
ftp = FTP(host) # get the host url of ftp site
ftp.login(user, passwd) # login with username ... |
class PresentDeliverer:
present_locations = {}
def __init__(self, name):
self.name = name
self.x = 0
self.y = 0
self.present_locations[self.get_key()]=1
def get_key(self):
return str(self.x)+"-"+str(self.y)
def status(self):
print(self.name + " x: "+str(self.x)+" y: "+str(self.y))
def move(self,instruc... |
import json
from sets import Set
from sys import maxint
import math
def norm2 (a):
return dot(a, a)
def dot ( a, b ):
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
def area (a, b, c):
u = [ b[0] - a[0], b[1] - a[1], b[2] - a[2] ]
v = [ c[0] - a[0], c[1] - a[1], c[2] - a[2] ]
dot_uv = dot(u, v)
... |
__author__ = 'waroquiers'
import unittest
import numpy as np
from pymatgen.util.testing import PymatgenTest
from pymatgen.analysis.chemenv.coordination_environments.coordination_geometries import ExplicitPermutationsAlgorithm
from pymatgen.analysis.chemenv.coordination_environments.coordination_geometries import Separa... |
import logging
import os
import subprocess
import traceback
from zipfile import ZipFile
from os import listdir
from os.path import isfile, join
'''
A utility python module containing a set of methods necessary for this kbase
module.
'''
LEVELS = {'debug': logging.DEBUG,
'info': logging.INFO,
'warnin... |
import py
from rpython.flowspace.model import SpaceOperation, Constant, Variable
from rpython.rtyper.lltypesystem import lltype, llmemory, rffi
from rpython.translator.unsimplify import varoftype
from rpython.rlib import jit
from rpython.jit.codewriter import support, call
from rpython.jit.codewriter.call import CallCo... |
import importlib
import logging
import os
import pprint
import sys
import StringIO
import cherrypy
import requests
def full_path(*extra):
return os.path.join(os.path.dirname(__file__), *extra)
sys.path.insert(0, full_path())
import db
logging.basicConfig()
sorry = 'This is only for US Citizens. Sorry and thank you ... |
from battle_tested.beta.input_type_combos import input_type_combos |
import os
import sys
import numpy as np
import matplotlib.image as mpimg
from ..core.data import Data
from ..util import tryremove
URL = 'http://synthia-dataset.cvc.uab.cat/SYNTHIA_SEQS/'
SEQS = [ # SUMMER and WINTER from sequences `1 - 6`
'SYNTHIA-SEQS-01-SUMMER',
'SYNTHIA-SEQS-01-WINTER',
'SYNTHIA-SEQS-02... |
import sys
from genStubs import *
stub = Stubs( "systemMessages", sys.argv[1], sys.argv[2] )
stub.include( "nanopb/IMessage.h" )
stub.include( "systemMessages/AGLMsg.pb.h" )
stub.include( "systemMessages/AGLOffsetMsg.pb.h" )
stub.include( "systemMessages/AGLRawMsg.pb.h" )
stub.include( "systemMessages/AbortLaunchMsg.pb... |
import scipy.misc, numpy as np, os, sys
def save_img(out_path, img):
img = np.clip(img, 0, 255).astype(np.uint8)
scipy.misc.imsave(out_path, img)
def scale_img(style_path, style_scale):
scale = float(style_scale)
o0, o1, o2 = scipy.misc.imread(style_path, mode='RGB').shape
scale = float(style_scale)... |
from datetime import datetime
import hashlib
from extractor import Ways
from date import way_date
class Helpers:
'''
'''
@staticmethod
def make_id(website, timestamp):
'''
'''
m=hashlib.md5()
m.update(''.join([website, timestamp]).encode())
return m.hexdigest()
cl... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<quiz_slug>[-A-Za-z0-9_]+)/$', views.quiz, name='quiz'),
url(r'^(?P<quiz_slug>[-A-Za-z0-9_]+)/(?P<question_slug>[-A-Za-z0-9_]+)/$', views.question, name='question')
] |
import sys # this allows you to read the user input from keyboard also called "stdin"
import classOne # This imports all the classOne functions
import classTwo # This imports all the classTwo functions
import classThree # This imports all the classThree functions
import classFour # This imports all the classFour fun... |
import numpy
from srxraylib.plot.gol import plot_image, plot
import sys
from comsyl.scripts.CompactAFReader import CompactAFReader
def plot_stack(mystack,what="intensity",title0="X",title1="Y",title2="Z"):
from silx.gui.plot.StackView import StackViewMainWindow
from silx.gui import qt
app = qt.QApplication(... |
from django.conf.urls import url,include
from django.contrib import admin
from cn_device import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^send/(?P<id_ras>[0-9]+)/$',views.payam,name='send condition'),
url(r'^give/(?P<id_ras>[0-9]+)/(?P<bl>[0-1])/$', views.give_req, name='give condition'... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0008_auto_20150819_0050'),
]
operations = [
migrations.AlterUniqueTogether(
name='test',
unique_together=set([('owner', '... |
"""
Run latency & thruput tests on various server configurations.
"""
import glob
import os.path
import shutil
import time
from openmdao.main.mp_util import read_server_config
from openmdao.main.objserverfactory import connect, start_server
from openmdao.util.fileutil import onerror
MESSAGE_DATA = []
def init_messages(... |
import gdb
import pwndbg.abi
import pwndbg.color.chain as C
import pwndbg.color.memory as M
import pwndbg.color.theme as theme
import pwndbg.enhance
import pwndbg.memory
import pwndbg.symbol
import pwndbg.typeinfo
import pwndbg.vmmap
LIMIT = pwndbg.config.Parameter('dereference-limit', 5, 'max number of pointers to der... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.