code stringlengths 1 199k |
|---|
import matplotlib.pyplot as pl
import numpy as np
import math
from matplotlib.collections import LineCollection
from matplotlib.colors import colorConverter
def plot(X, m, x_star, t, z_t):
fig = pl.figure(figsize=(10,10))
# Draw the grid first
ax = pl.axes()
ax.set_xlim(-4,20)
ax.set_ylim(-4,20)
... |
from unittest import skipIf
from django.conf import settings
def skipIfDefaultUser(test_func):
"""
Skip a test if a default user model is in use.
"""
return skipIf(settings.AUTH_USER_MODEL == "auth.User", "Default user model in use")(
test_func
)
def skipIfCustomUser(test_func):
"""
... |
from django import forms
from django.contrib.auth.models import User
from .models import Perfil,SolicitudColaboracion
class SolicitudColaboracionForm(forms.ModelForm):
class Meta:
model = SolicitudColaboracion
fields = ('name','licenciatura_leyes','telefono','fecha_nacimiento') |
"""
voice_nav.py allows controlling a mobile base using simple speech commands.
Based on the voice_cmd_vel.py script by Michael Ferguson in the pocketsphinx ROS package.
"""
import roslib; #roslib.load_manifest('pi_speech_tutorial')
import rospy
from geometry_msgs.msg import Twist
from std_msgs.msg import String
fr... |
from tabulate import tabulate
class Response():
message = None;
data = None;
def print(self):
if self.message:
if type(self.message) == "str":
print(self.message)
elif type(self.message) == "list":
for message in self.message:
... |
"""Add user
Revision ID: 13a57b7f084
Revises: None
Create Date: 2014-05-11 17:12:17.244013
"""
revision = '13a57b7f084'
down_revision = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_table('user',
sa.Column('id', sa.In... |
import time
import json
import unittest
from project.server import db
from project.server.models import User, BlacklistToken
from project.tests.base import BaseTestCase
def register_user(self, email, password):
return self.client.post(
'/auth/register',
data=json.dumps(dict(
email=email,... |
"""
[DEPRECATED] Run a single container in debug mode
"""
import typer
from controller import print_and_exit
from controller.app import Application
@Application.app.command(help="Replaced by run --debug command")
def volatile(
service: str = typer.Argument(
...,
help="Service name",
shell_co... |
import sys
from pydoc import help
import os
from collections import defaultdict
from math import log, sqrt
import operator
class ProbModel:
"""
Implements probabilitistic models for information retrieval.
"""
def __init__(self, directory):
"""
Arguments:
directory - Directory of documents to be searched.
... |
from typing import NamedTuple, List
from data import crossword
class Clue(str):
def __init__(self, value) -> None:
super(Clue, self).__init__(value)
self._tokens = crossword.tokenize_clue(value)
class _Node(object):
_clue: Clue
_occupied: int
def __init__(self, clue: Clue, occupied: int) -> None:
se... |
from collections import defaultdict
from datetime import datetime, timedelta
from django.contrib.auth.models import User
from django.db import models
from django.db.models import Q, Count, Sum, Max, Min
from django.db.models.signals import pre_save
from django.dispatch import receiver
from hashlib import sha1
from pros... |
from django.contrib import admin
from simulation.models import SimulationStage, SimulationStageMatch, SimulationStageMatchResult
class SimulationStageAdmin(admin.ModelAdmin):
list_display = ["number", "created_at"]
list_filter = ["created_at"]
class SimulationStageMatchAdmin(admin.ModelAdmin):
list_display ... |
import os
import common_pygame
import random
pygame = common_pygame.pygame
screen = common_pygame.screen
class Bonus():
def __init__(self, sounds, menu):
self.menu = menu
self.sounds = sounds
self.bonusType = 0
self.bonusAnim = 0
self.font = pygame.font.Font(None, 64)
... |
"""
https://en.wikipedia.org/wiki/Square_root_of_a_matrix
B is the sqrt of a matrix A if B*B = A
"""
import numpy as np
from scipy.linalg import sqrtm
from scipy.stats import special_ortho_group
def denman_beaver(A, n=50):
Y = A
Z = np.eye(len(A))
for i in range(n):
Yn = 0.5*(Y + np.linalg.inv(Z))
... |
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
u, i=np.genfromtxt('Rohdaten/Daten_1_5.txt', unpack=True)
i=np.log(i)
u=np.log(u)
def f(u, a, b):
return a * u + b
params, covariance = curve_fit(f, u, i)
errors = np.sqrt(np.diag(covariance))
print('a =', params[0], '+-', error... |
"""
Internet Relay Chat (IRC) protocol client library.
This library is intended to encapsulate the IRC protocol in Python.
It provides an event-driven IRC client framework. It has
a fairly thorough support for the basic IRC protocol, CTCP, and DCC chat.
To best understand how to make an IRC client, the reader more
or ... |
ano_eleicao = '2014'
rede =f'rede{ano_eleicao}'
csv_dir = f'/home/neilor/{rede}'
dbschema = f'rede{ano_eleicao}'
table_edges = f"{dbschema}.gephi_edges_com_ipca_2018"
table_nodes = f"{dbschema}.gephi_nodes_com_ipca_2018"
table_receitas = f"{dbschema}.receitas_com_ipca_2018"
table_candidaturas = f"{dbschema}.candidatura... |
from setuptools import setup, find_packages
version = '0.2.4'
setup(
name='lolbuddy',
version=version,
description='a cli tool to update league of legends itemsets and ability order from champion.gg',
author='Cyrus Roshan',
author_email='hello@cyrusroshan.com',
license='MIT',
keywords=['lol'... |
from code_intelligence import graphql
import fire
import github3
import json
import logging
import os
import numpy as np
import pprint
import retrying
import json
TOKEN_NAME_PREFERENCE = ["INPUT_GITHUB_PERSONAL_ACCESS_TOKEN", "GITHUB_PERSONAL_ACCESS_TOKEN", "GITHUB_TOKEN"]
for token in TOKEN_NAME_PREFERENCE:
if os.ge... |
import os
from typing import List
import click
from valohai_yaml.lint import lint_file
from valohai_cli.ctx import get_project
from valohai_cli.exceptions import CLIException
from valohai_cli.messages import success, warn
from valohai_cli.utils import get_project_directory
def validate_file(filename: str) -> int:
"... |
import sys
import os
import shlex
sys.path.insert(0, os.path.abspath(".."))
import uflash
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.viewcode",
]
templates_path = ["_templates"]
source_suffix = ".rst"
master_doc = "index"
project = "uFlash"
copyright = "2015, Nicholas H.Tollervey"
author = "Nicholas H.Tol... |
from copy import deepcopy
from typing import Any, Awaitable, Optional, TYPE_CHECKING
from azure.core.rest import AsyncHttpResponse, HttpRequest
from azure.mgmt.core import AsyncARMPipelineClient
from msrest import Deserializer, Serializer
from .. import models
from ._configuration import ContainerRegistryManagementClie... |
""" RUN RUN RUN !
"""
from buttersalt import create_app
from flask_script import Manager, Shell
app = create_app('default')
manager = Manager(app)
def make_shell_context():
return dict(app=app)
manager.add_command("shell", Shell(make_context=make_shell_context))
@manager.command
def test():
"""Run the unit test... |
""" patrol_smach_iterator.py - Version 1.0 2013-10-23
Control a robot using SMACH to patrol a square area a specified number of times
Created for the Pi Robot Project: http://www.pirobot.org
Copyright (c) 2013 Patrick Goebel. All rights reserved.
This program is free software; you can redistribute it a... |
"""
This module contains various "context" definitions, which are essentially flags
set during the tokenization process, either on the current parse stack (local
contexts) or affecting all stacks (global contexts). They represent the context
the tokenizer is in, such as inside a template's name definition, or inside a
... |
from django.conf import settings
from django.db import models
import jsonfield
class Feed(models.Model):
name = models.CharField(max_length=1024)
url = models.URLField()
homepage = models.URLField()
etag = models.CharField(max_length=1024, blank=True)
last_modified = models.DateTimeField(blank=True,... |
import unittest
import markovify
import os
import operator
def get_sorted(chain_json):
return sorted(chain_json, key=operator.itemgetter(0))
class MarkovifyTestBase(unittest.TestCase):
__test__ = False
def test_text_too_small(self):
text = "Example phrase. This is another example sentence."
... |
import json
import os
import unittest
from collections import OrderedDict
from bs4 import BeautifulSoup
from ddt import ddt, data, unpack
from elifetools import parseJATS as parser
from elifetools import rawJATS as raw_parser
from elifetools.utils import date_struct
from tests.file_utils import (
sample_xml,
js... |
from direct.directnotify import DirectNotifyGlobal
from toontown.parties.DistributedPartyActivityAI import DistributedPartyActivityAI
from direct.task import Task
import PartyGlobals
class DistributedPartyJukeboxActivityBaseAI(DistributedPartyActivityAI):
notify = DirectNotifyGlobal.directNotify.newCategory("Distri... |
import sys, unittest, os
sys.path.append(os.path.realpath(os.path.dirname(__file__))+'/lib')
tests_folder = os.path.realpath(os.path.dirname(__file__))+'/tests'
from tests import ConsoleTestRunner
def load_tests(loader, tests, pattern):
suite = unittest.TestSuite()
pattern='test_*.py'
for dirname, dirnames, filen... |
"""
WSGI config for bball_intel project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bball_intel.settings.base")
from djan... |
import re
import sys
import requests
from django.conf import settings
from django.core.management import BaseCommand
from requests.exceptions import InvalidJSONError, RequestException
from .import_measures import BadRequest
from .import_measures import Command as ImportMeasuresCommand
from .import_measures import Impor... |
import unittest
from fire_risk.models import DIST
class TestDISTModel(unittest.TestCase):
def test_dist_import(self):
floor_extent = False
results = {'floor_of_origin': 126896L,
'beyond': 108959L,
'object_of_origin': 383787L,
'room_of_origin':... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.ndimage import gaussian_filter
from srxraylib.plot.gol import plot
from oasys.util.oasys_util import write_surface_file
from srxraylib.metrology.profiles_simulation import slopes
def get_shadow_h5(file_name):
"""Function to get an h5 ... |
from rest_framework.decorators import list_route
from rest_framework.permissions import IsAuthenticated
from rest_framework import viewsets
from .models import User
from .serializers import UserSerializer
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
... |
''' Wrapper around session access. Keep track of session madness as the app grows. '''
import logging
logger = logging.getLogger("pyfb")
FB_ACCESS_TOKEN = "fb_access_token"
FB_EXPIRES = "fb_expires"
FB_USER_ID = "fb_user_id"
def get_fb_access_token(request, warn=True):
token = request.session.get(FB_ACCESS_TOKEN)
... |
"""test_Read.py to test the Read class.
Requires:
python 2 (https://www.python.org/downloads/)
nose 1.3 (https://nose.readthedocs.org/en/latest/)
Joy-El R.B. Talbot Copyright (c) 2014
The MIT License (MIT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associat... |
"""
@file
@brief This extension contains various functionalities to help unittesting.
"""
import os
import stat
import sys
import re
import warnings
import time
import importlib
from contextlib import redirect_stdout, redirect_stderr
from io import StringIO
def _get_PyLinterRunV():
# Separate function to speed up i... |
import re
from LUIObject import LUIObject
from LUISprite import LUISprite
from LUILabel import LUILabel
from LUIInitialState import LUIInitialState
from LUILayouts import LUIHorizontalStretchedLayout
__all__ = ["LUIInputField"]
class LUIInputField(LUIObject):
""" Simple input field, accepting text input. This input... |
grid = [[0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 1, 0],
[0, 0, 1, 0, 1, 0],
[0, 0, 1, 0, 1, 0]]
init = [0, 0]
goal = [len(grid)-1, len(grid[0])-1]
cost = 1
delta = [[-1, 0 ], # go up
[ 0, -1], # go left
[ 1, 0 ], # go down
[ 0, 1 ]] # go right
delta... |
from distutils.core import setup
setup(
name = 'pmdp',
packages = ['pmdp'],
version = '0.3',
description = 'A poor man\'s data pipeline',
author = 'Dan Goldin',
author_email = 'dangoldin@gmail.com',
url = 'https://github.com/dangoldin/poor-mans-data-pipeline',
download_url = 'https://github.com/dangoldi... |
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
import pytest
from dataproperty import get_integer_digit, get_number_of_digit
nan = float("nan")
inf = float("inf")
class Test_get_integer_digit:
@pytest.mark.parametrize(
["value", "expected"],
[
[0, 1],
... |
import os, random
from guru.globals import GURU_PORT, GURU_NOTEBOOK_DIR
import sagenb.notebook.notebook as notebook
from sagenb.misc.misc import find_next_available_port
import flask_server.base as flask_base
def startServer(notebook_to_use=None, open_browser=False, debug_mode=False):
#notebook_directory = os.path.... |
"""
search.py
"""
from flask import Flask, request, redirect, abort, make_response
from flask import render_template, flash
import bibserver.dao
from bibserver import auth
import json, httplib
from bibserver.config import config
import bibserver.util as util
import logging
from logging.handlers import RotatingFileHandl... |
import json
import os
import avasdk
from zipfile import ZipFile, BadZipFile
from avasdk.plugins.manifest import validate_manifest
from avasdk.plugins.hasher import hash_plugin
from django import forms
from django.core.validators import ValidationError
from .validators import ZipArchiveValidator
class PluginArchiveField... |
from django.core.management.base import BaseCommand
from optparse import make_option
from django.utils import timezone
from orcamentos.proposal.models import Proposal
class Command(BaseCommand):
help = ''' Conclui orçamento. '''
option_list = BaseCommand.option_list + (
make_option('--num', help='número... |
"""
Django settings for paulpruitt_net project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
import os
from secrets import SECRET_KEY, DB_USER, DB_PASSWORD
BASE_DI... |
"""
HTTP handeler to serve specific endpoint request like
http://myserver:9004/endpoints/mymodel
For how generic endpoints requests is served look
at endpoints_handler.py
"""
import json
import logging
import shutil
from tabpy.tabpy_server.common.util import format_exception
from tabpy.tabpy_server.handlers import Mana... |
input('Press \'Enter\' to exit') # Задержка вывода консоли
"""> python -m idlelib.idle """ # запуск IDLE из командный строки для текущей папки
"""> cd 1D\Python\ """
"""
pip --proxy http://192.168.1.37:2718
pip install --proxy=http://192.168.1.37:2718 package
pip install --proxy=http://192.168.1.37:2718 xlwings # exl
... |
from boto3.dynamodb.conditions import Attr
def update_users_followers(username, follower_id, table, remove=False):
'''
Find all the users that %username% follows and
update their "followers" list and "followers_count" amount
'''
item = table.get_item(Key={'username': username}).get('Item', False)
... |
'''
My Diary Web App - CLI for client
'''
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import requests
from bs4 import BeautifulSoup
import re
HELP = '''
Input h/help/? for help.
Input q/quit to quit the process.
Input s/sync to sync the diary log.
Input lt/ListTags to list all tags.
Input st:TAG to set or de... |
from pytest import fixture
from functional.core import (
builder,
PreparedImagesOutputChecker,
PDFDocumentChecker,
DjVuDocumentChecker)
@fixture()
def checker_classes():
""" Run all checkers in one test for optimization reason. """
return [
PreparedImagesOutputChecker,
... |
import collections
import contextlib
import copy
import json
import warnings
import numpy
import six
from chainer.backends import cuda
from chainer import configuration
from chainer import serializer as serializer_module
from chainer import variable
def _copy_variable(value):
if isinstance(value, variable.Variable)... |
import scrapenhl_globals
import scrape_game
def scrape_games(season, games, force_overwrite = False, pause = 1, marker = 10):
"""
Scrapes the specified games.
Parameters
-----------
season : int
The season of the game. 2007-08 would be 2007.
games : iterable of ints (e.g. list)
T... |
import os
import sys
sys.path.append('/var/www/vehicle-journal/vjournal')
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "vjournal.settings.prod")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
from __future__ import unicode_literals
"""build query for doclistview and return results"""
import frappe, json
import frappe.permissions
from frappe.model.db_query import DatabaseQuery
from frappe import _
@frappe.whitelist()
def get():
args = get_form_params()
data = compress(execute(**args), args = args)
return ... |
import datetime
import time
import calendar
from django.core.urlresolvers import reverse
from django.http import Http404
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.http import Http404
from django.shortcuts import render, redirect
from rolepermission... |
'''
==================
RBF SVM parameters
==================
This example illustrates the effect of the parameters ``gamma`` and ``C`` of
the Radial Basis Function (RBF) kernel SVM.
Intuitively, the ``gamma`` parameter defines how far the influence of a single
training example reaches, with low values meaning 'far' and... |
import pytest
from named_dates.named_dates import\
day_of_nth_weekday, NoNthWeekdayError
def test_weekday_equals_first_of_month():
# Tests that day_of_nth_weekday works when the requested weekday is the
# first weekday is the month.
assert day_of_nth_weekday(2015, 10, 3, nth=1) == 1
assert day_of_nt... |
import re
import sys
import dns.resolver
import collections
NSEEDS=512
MAX_SEEDS_PER_ASN=2
MIN_BLOCKS = 337600
with open("suspicious_hosts.txt", mode="r", encoding="utf-8") as f:
SUSPICIOUS_HOSTS = {s.strip() for s in f if s.strip()}
PATTERN_IPV4 = re.compile(r"^((\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})):(\d+)$")... |
class Node:
def __init__(self, value):
self.value = value
self.next = None
self.prev = None
class OldestUnique:
def __init__(self):
self.uniq = {}
self.seen = set()
self.head = None
self.tail = None
def feed(self, value):
if value in self.uniq:... |
"""
MIT License
Copyright (c) 2017 cgalleguillosm, AlessioNetti
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, me... |
u"""歌詞コーパスの取得
"""
import argparse
import requests
import logging
import urllib, urllib2
import re
import time
from BeautifulSoup import BeautifulSoup
verbose = False
logger = None
def init_logger():
global logger
logger = logging.getLogger('GetLyrics')
logger.setLevel(logging.DEBUG)
log_fmt = '%(asctime... |
class OutputParser(object):
def __init__(self, fmt, file_to_parse):
self.fmt = fmt.upper()
self.file_to_parse = file_to_parse
def parse(self):
""" Wrapper function in case I want to be able to parse other formats at some time """
if self.fmt == "GFF3":
return self.par... |
from AutoDoApp.parser.ParserCommunicator import ParserCommunicator
import os
import codecs
import git
import stat
from django.conf import settings
class Parser(ParserCommunicator):
def __init__(self):
self.git_dir = ""
self.dir_dict = {}
self.class_dict = {} # key: full path file_name, valu... |
"""
<DefineSource>
@Date : Fri Nov 14 13:20:38 2014 \n
@Author : Erwan Ledoux \n\n
</DefineSource>
A Grouper establishes a group of parenting nodes for which
each level is setted in equivalent hdf5 structure.
"""
import ShareYourSystem as SYS
BaseModuleStr="ShareYourSystem.Hdformaters.Hdformater"
DecorationModuleStr="S... |
"""
问题描述:给定一个正数数组arr,其中所有的值都为整数,以下是最小不可组成和的概念:
1)把arr每个子集内的所有元素加起来会出现很多值,其中最小的记为min,最大的记为max.
2)在区间[min,max]上,如果有数不可以被arr某一个子集相加得到,那么其中最小的那个数是
arr的最小不可组成和.
3)在区间[min,max]上,如果所有的数都可以被arr的某一个子集相加得到,那么max+1是arr
的最小不可组成和.
请写函数返回正数数组arr的最小不可组成和.
举例:
arr=[3, 2, 5],子集{2}相加产生2为min,子集{3, 2, 5}相加产生10为max.在区间[2, 10]
上,4、6和9不能被任何子... |
"""
General EasyBuild support for installing FastQC
@author: Emilio Palumbo
"""
import os
import stat
from easybuild.tools.filetools import run_cmd
from easybuild.easyblocks.generic.packedbinary import PackedBinary
class EB_FastQC(PackedBinary):
"""Easyblock implementing the build step for FastQC,
this is just ... |
"""
object file io is a Python object to single file I/O framework. The word
'framework' means you can use any serialization/deserialization algorithm here.
- dump: dump python object to a file.
- safe_dump: add atomic writing guarantee for ``dump``.
- load: load python object from a file.
Features:
1. ``compress``: bu... |
'''Template filters
'''
def j(s):
"""Escape for JavaScript or encode as JSON"""
pass
try:
from cjson import encode as _json
except ImportError:
try:
from minjson import write as _json
except ImportError:
import re
_RE = re.compile(r'(["\'\\])')
def _json(s):
return repr(_RE.sub(r'\\\1', ... |
import sys
import re
import Config
from Config import exit_err
macro_list = {};
def init_list(redef_opt):
def_macro = Macro("@def");
set_macro = Macro("@set");
let_macro = Macro("@let");
null_macro = Macro("@null");
_def_macro = Macro("@__def__");
_set_macro = Macro("@__set__");
_let_macro = Macro("@__let__");
... |
from staffjoy.resource import Resource
from staffjoy.resources.worker import Worker
from staffjoy.resources.schedule import Schedule
from staffjoy.resources.shift import Shift
from staffjoy.resources.shift_query import ShiftQuery
from staffjoy.resources.recurring_shift import RecurringShift
class Role(Resource):
PA... |
"""
WSGI config for eyrie project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
from whitenoise.django import DjangoWhiteN... |
import os
import dec
print 'Building HOG feature extractor...'
os.system('python setup_features.py build')
os.system('python setup_features.py install')
print 'Preparing stl data. This could take a while...'
dec.make_stl_data() |
import pygame
import rospy
import time
from std_msgs.msg import Float64
from std_msgs.msg import Float64MultiArray
pygame.init()
pygame.display.set_mode([100,100])
delay = 100
interval = 50
pygame.key.set_repeat(delay, interval)
robot_namespace = "qubo/"
effort = 50
num_thrusters = 8
rospy.init_node('keyboard_node', an... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('catalogue', '0001_initial'),
]
operations = [
migrations.RenameModel(
old_name='Cd',
new_name='Release',
),
] |
'subclass demo 继承和多态'
class Animal(object):
def run(self):
print('Animal is running......')
class Dog(Animal):
def run(self):
print('Dog is running.....')
def eat(self):
print('dog is eating......')
class Cat(Animal):
pass
dog = Dog()
dog.run() |
"""Project Euler - Problem 27 Module"""
def problem27(ab_limit):
"""Problem 27 - Quadratic primes"""
# upper limit
nr_primes = 2 * ab_limit * ab_limit + ab_limit
primes = [1] * (nr_primes - 2)
result = 0
for x in range(2, nr_primes):
if primes[x - 2] == 1:
# x is Prime, elimi... |
from myhdl import *
from UK101AddressDecode import UK101AddressDecode
def bench():
AL = Signal(intbv(0)[16:])
MonitorRom = Signal(bool(0))
ACIA = Signal(bool(0))
KeyBoardPort = Signal(bool(0))
VideoMem = Signal(bool(0))
BasicRom = Signal(bool(0))
Ram = Signal(bool(0))
dut = UK101AddressD... |
import copy
import json
from psycopg2.extensions import AsIs
from psycopg2.extras import RealDictCursor
from pg4nosql import DEFAULT_JSON_COLUMN_NAME, DEFAULT_ROW_IDENTIFIER
from pg4nosql.PostgresNoSQLQueryStructure import PostgresNoSQLQueryStructure
from pg4nosql.PostgresNoSQLResultItem import PostgresNoSQLResultItem
... |
from __future__ import unicode_literals, division, absolute_import
import logging
from flexget import plugin
from flexget.event import event
from flexget.manager import Session
try:
from flexget.plugins.api_trakt import ApiTrakt
lookup_series = ApiTrakt.lookup_series
lookup_episode = ApiTrakt.lookup_episode... |
import re
def snake_to_camel(snake, upper_first=False):
# title-cased words
words = [word.title() for word in snake.split('_')]
if words and not upper_first:
words[0] = words[0].lower()
return ''.join(words)
def camel_to_snake(camel):
# first upper-cased camel
camel = camel[0].upper() + ... |
class Optimizer:
def __init__(self, model, params=None):
self.model = model
if params:
self.model.set_params(**params)
self.params = self.model.get_params()
self.__chain = list()
def step(self, name, values, skipped=False):
if not skipped:
self.__c... |
import sys
import os
import re
try:
path = sys.argv[1]
length = int(sys.argv[2])
except:
print >>sys.stderr, "Usage: $0 <path> <length>"
sys.exit(1)
path = re.sub(os.getenv('HOME'), '~', path)
while len(path) > length:
dirs = path.split("/");
# Find the longest directory in the path.
max_i... |
from rapt.treebrd.attributes import AttributeList
from ...treebrd.node import Operator
from ..base_translator import BaseTranslator
class SQLQuery:
"""
Structure defining the building blocks of a SQL query.
"""
def __init__(self, select_block, from_block, where_block=''):
self.prefix = ''
... |
from .fft_tools import zoom
import numpy as np
import matplotlib.pyplot as pl
def iterative_zoom(image, mindiff=1., zoomshape=[10,10],
return_zoomed=False, zoomstep=2, verbose=False,
minmax=np.min, ploteach=False, return_center=True):
"""
Iteratively zoom in on the *minimum* position in an image... |
"""Tests for IPython.lib.display.
"""
from tempfile import NamedTemporaryFile, mkdtemp
from os.path import split, join as pjoin, dirname
import sys
try:
import pathlib
except ImportError:
pass
from unittest import TestCase, mock
import struct
import wave
from io import BytesIO
import nose.tools as nt
import num... |
import os
import sys
import organizations
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
os.system('python setup.py bdist_wheel upload')
sys.exit()
readme = open('README.rst').read()
histo... |
"""A set of AST classes with types and aliases filled in."""
import collections
import type_context
class Select(collections.namedtuple(
'Select', ['select_fields', 'table', 'where_expr', 'group_set',
'limit', 'type_ctx'])):
"""A compiled query.
Fields:
select_fields: A list o... |
"""
Init
"""
from __future__ import unicode_literals
import datetime
import os
import subprocess
VERSION = (2, 2, 13, 'final', 0)
def get_version(version=None):
"""
Returns a PEP 386-compliant version number from VERSION.
"""
if not version:
version = VERSION
else:
assert len(version... |
import os
def emulator_rom_launch_command(emulator, rom):
"""Generates a command string that will launch `rom` with `emulator` (using
the format provided by the user). The return value of this function should
be suitable to use as the `Exe` field of a Steam shortcut"""
# Normalizing the strings is just removing... |
import sys
from sdcclient import SdcClient
if len(sys.argv) != 4:
print(('usage: %s <sysdig-token> team-name user-name' % sys.argv[0]))
print('You can find your token at https://app.sysdigcloud.com/#/settings/user')
sys.exit(1)
sdc_token = sys.argv[1]
sdclient = SdcClient(sdc_token, sdc_url='https://app.sys... |
class Solution(object):
def minDistance(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: int
"""
row = len(word1) + 1
col = len(word2) + 1
dp = [[0] * col for _ in range(row)]
for i in range(col):
dp[0][i] = i
... |
from linkedlist import SinglyLinkedListNode
def reverseList(head):
tail=None
last=None
tempNode = head
while tempNode is not None:
currentNode, tempNode = tempNode, tempNode.next
currentNode.next = tail
tail = currentNode
return tail
def reverseListKNode(head,k):
tempHead... |
import unittest
import warnings
from collections import OrderedDict
import jsonmerge
import jsonmerge.strategies
from jsonmerge.exceptions import (
HeadInstanceError,
BaseInstanceError,
SchemaError
)
from jsonmerge.jsonvalue import JSONValue
import jsonschema
try:
Draft6Validator = jsonschema.validators... |
from django.core.management.base import BaseCommand, CommandError
from annotations.models import Corpus
from annotations.exports import export_fragments
from core.utils import CSV, XLSX
class Command(BaseCommand):
help = 'Exports existing Fragments for the given Corpus and Languages'
def add_arguments(self, par... |
from pymongo import MongoClient
from pymongo.collection import Collection
from pymongo.errors import AutoReconnect
from django.conf import settings
from types import FunctionType
import functools
import time
__all__ = ("connection", "connections", "db", "get_db")
"""
Goals:
* To provide a clean universal handler for Mo... |
import json
from django.http import HttpResponse
from django.shortcuts import render
from aircraft_config import AC_WQAR_CONFIG
from list2string_and_echarts_function import Echarts_option
from list2string_and_echarts_function import LIST_to_STR
from influxdb_function import influxDB_interface
from main_web.models impor... |
"""
Run Regression Test Suite
This module calls down into individual test cases via subprocess. It will
forward all unrecognized arguments onto the individual test scripts, other
than:
- `-extended`: run the "extended" test suite in addition to the basic one.
- `-win`: signal that this is running in a Windows e... |
from django.contrib.auth.models import User
from django.db import models
from django.utils import timezone
import jsonfield
from .hooks import hookset
from .utils import load_path_attr
class UserState(models.Model):
"""
this stores the overall state of a particular user.
"""
user = models.OneToOneField(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.