content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
#!/usr/bin/python
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Created by: Anderson Brito
# Email: andersonfbrito@gmail.com
#
# singleChain.py -> This code splits a multichain PDB file into its
# multiple individual chains, saving them as output.
#
# Usage: python singleC... | python |
import random as python_random
def safe_sample_edges(nodes, edges, sample_size):
edges = set(edges)
nodes = list(nodes)
edge_label = {}
node2edges = {node : [] for node in nodes}
for edge in edges:
node2edges[edge[0]].append(edge)
node2edges[edge[1]].append(edge)
edge_label... | python |
import json
import os
from pb.homing_motor import HomingMotor, build_from_config, build
def init_motors(config: dict) -> list:
try:
x = build_from_config(config, 'x')
except RuntimeError:
x = build("x", dir_pin=5, step_pin=6, ms1_pin=26, ms2_pin=19, ms3_pin=13, sensor_pin=24,
... | python |
from django.conf.urls import url
from dal_queryset_sequence.fields import QuerySetSequenceModelField
from queryset_sequence import QuerySetSequence
from dal_select2_queryset_sequence.widgets import QuerySetSequenceSelect2
from dal_select2_queryset_sequence.views import Select2QuerySetSequenceAutoView
class Select2... | python |
##
# \file data_anonymizer.py
#
# \author Michael Ebner (michael.ebner.14@ucl.ac.uk)
# \date Dec 2016
#
# Import libraries
import string
import random
import string
import cPickle
import datetime
import os
import re
# Import modules
import pysitk.python_helper as ph
class DataAnonymizer(object):
def... | python |
#!/usr/bin/env python3
import contextlib
import functools
import re
import itertools
import argparse
import os
import io
import copy
import json
from importlib import resources
from collections import UserDict
from typing import Optional, Sequence, Mapping, Any, IO
# TODO is this actually safe?
import mktcmenu_schema... | python |
#! /usr/bin/env python3
import subprocess
import sys
from config_loader import ConfigLoader
from write_tfvars import TfVarWriter
from setup_class_loader import load_class
"""
Setup.py sets up and runs the initial terraform deployment. It's broken into
3 parts:
1) Load and Validate Inputs
2) Run Setup scripts
3) Te... | python |
def spam(divide_by):
return 42 / divide_by
print(spam(0))
"""
Traceback (most recent call last):
File "/Users/moqi/Documents/Code/automate-the-boring-stuff/c03/p053_zero_devide.py", line 5, in <module>
print(spam(0))
File "/Users/moqi/Documents/Code/automate-the-boring-stuff/c03/p053_zero_devide.py", lin... | python |
class Line(object):
def __init__(self, line_num, line_real,line_altered):
self.num = line_num
self.real = line_real
self.altered = line_altered
def __repr__(self):
return str(self.num)+": "+self.real.rstrip()
| python |
## To use this example:
# curl -d '{"name": "John Doe"}' localhost:8000
from sanic import Sanic
from sanic.response import html
from jinja2 import Template
template = Template('Hello {{ name }}!')
app = Sanic(__name__)
#
# 异步响应:
# - 使用 jinja2 模板:
#
@app.route('/')
async def test(request):
data = request.json... | python |
# -*- coding=utf-8 -*-
import random
import os,pickle
import pygame
from globals import *
from matrix import Matrix
class VirtualHintBox(object):
pid = 0
block_manage=None
next_block= None
def __init__(self, pid, block_manage):
#print pid
self.pid = pid
self.block_manage = block... | python |
from app import celery
from celery.utils.log import get_task_logger
from bridge.bridge_manager import BridgeManager
from models.modelDetail import AiModelDetail
from models.receiveJobs import ReceiveJobs
from models.category import Category
from models.subcategory import SubCategory
from models.compliance import Shelf... | python |
class Agent:
def __init__(self, size, velocity, k):
self.size = size
self.velocity = velocity
self.k = k
def model(self, q, t, u):
pass
def controller(self, q, qref, uref):
pass
def bloating(self, n):
pass
def run_model(self, q0, t, qref, uref):
pass | python |
from path import Path
| python |
"""
Task to orchestrate scaling for a ECS Service
"""
import boto3
from decorators import with_logging
ecs = boto3.client("ecs")
@with_logging
def handler(event, context):
cluster = event["Cluster"]
max_tasks = event["DeletionTasksMaxNumber"]
queue_size = event["QueueSize"]
service = event["DeleteSe... | python |
from .interactive import Interactive
from .hardcoded import Hardcoded
| python |
#
# Copyright (C) 2018 ETH Zurich and University of Bologna
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | python |
from .ranges import * # NOQA
| python |
from spade.behaviour import OneShotBehaviour
from spade.message import Message
from driftage.base.conf import getLogger
class FastNotifyContacts(OneShotBehaviour):
_logger = getLogger("fast_notify_contacts")
async def run(self):
"""[summary]
"""
for contact in self.agent.available_co... | python |
"""
vg plot command
make plot of flybys using SPICE data
To use, need SPICE kernels - download the following files and put them in the /kernels folder:
ftp://naif.jpl.nasa.gov/pub/naif/generic_kernels/lsk/naif0012.tls
ftp://naif.jpl.nasa.gov/pub/naif/generic_kernels/spk/satellites/a_old_versions/jup100.bsp
ftp://nai... | python |
import codecs
import hashlib
import json
import os
import tempfile
import unittest
from pathlib import Path
import tifffile
import numpy as np
from slicedimage._compat import fspath
import slicedimage
from slicedimage import ImageFormat
from slicedimage._dimensions import DimensionNames
from tests.utils import build_... | python |
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"\n",
"import pandas as pd\n",
"import numpy as np\n",
"\n",
"import sqlalchemy\n",
"from sqlalchemy.ext.automap import automap_base\n",
"from sqlalche... | python |
#!/usr/bin/env PYTHONHASHSEED=1234 python3
from analysis.utils import inspect
from frontend.utils import inspect # Overwrites!
'frontend' in inspect.__module__
print(inspect.__module__) | python |
try:
from local_settings import *
except ImportError:
pass
from azure.devops.connection import Connection
from msrest.authentication import BasicAuthentication
import threading, queue
class QueryResultStatus():
CHECKING = "Checking"
BUILD_COMPLETE = "Build Complete"
BUILD_IN_PROGRESS = "Building... | python |
import os
try:
from configparser import ConfigParser
except ImportError:
from ConfigParser import SafeConfigParser as ConfigParser
class ConfigParameter(object):
def __init__(self, name, value_type):
self.name = name
self.value_type = value_type
def __repr__(self):
return "Co... | python |
from .vector import Vector
from pygame import Rect
import pygame
from .util import BASE_PATH
pygame.font.init()
DEMIBOLD_BIG = pygame.font.Font(BASE_PATH + '/../lightsouls/data/LucidaSansDemiBold.ttf', 20)
DEFAULT_COLOR = GREEN = (128, 255, 128, 0)
class Frame:
"""
Rectangular piece of the screen.
Manag... | python |
import pylab as pl
fig = pl.figure()
fig.subplots_adjust(bottom=0.025, left=0.025, top = 0.975, right=0.975)
pl.subplot(2, 1, 1)
pl.xticks(()), pl.yticks(())
pl.subplot(2, 3, 4)
pl.xticks(())
pl.yticks(())
pl.subplot(2, 3, 5)
pl.xticks(())
pl.yticks(())
pl.subplot(2, 3, 6)
pl.xticks(())
pl.yticks(())
pl.show()
| python |
from .FeatureDescriptionLabel import *
from .FeatureExtractionLogic import *
from .FeatureWidgets import *
| python |
'''
The np.npv() function estimates the present values for a given set of future cash
flows. The first input value is the discount rate, and the second input is an array of
future cash flows. This np.npv() function mimics Excel's NPV function. Like Excel,
np.npv() is not a true NPV function. It is actually a PV fu... | python |
from tempfile import NamedTemporaryFile
import boto3
from rivet import inform, s3_path_utils
from rivet.s3_client_config import get_s3_client_kwargs
from rivet.storage_formats import get_storage_fn
def write(obj, path, bucket=None,
show_progressbar=True, *args, **kwargs):
"""
Writes an object to a... | python |
import pandas as pd
import numpy as np
import tensorflow as tf
from tensorflow import keras
tf.random.set_seed(2021)
from models import DNMC, NMC, NSurv, MLP, train_model, evaluate_model
df = pd.read_csv('http://pssp.srv.ualberta.ca/system/predictors/datasets/000/000/032/original/All_Data_updated_may2011_CLEANED.cs... | python |
# test return statement
def f():
return
print(f())
def g():
return 1
print(g())
def f(x):
return 1 if x else 2
print(f(0), f(1))
print("PASS") | python |
from contextlib import suppress
import warnings
import urllib.parse
import calendar
from cromulent import model, vocab
from cromulent.model import factory
from cromulent.extract import extract_physical_dimensions
from pipeline.util.cleaners import ymd_to_datetime
factory.auto_id_type = 'uuid'
vocab.add_art_setter()
... | python |
import logging
import os
import random
from collections import defaultdict, namedtuple
from threading import Lock, Thread
from time import sleep
from consul import Consul
instance = namedtuple('serviceinstance', ['address', 'port'])
service = namedtuple('service', ['ts', 'instances'])
class ServiceInstance(instance... | python |
from django.urls import path
from material.admin.sites import site
urlpatterns = [
path('', site.urls, name='base')
]
| python |
## this version of get_freq collects %AT-richness, gene expression data and SumFreq statistic on top of the data collated by get_freq.py
import pandas as pd
import numpy as np
## NOTE: All filenames are placeholders
raw = pd.read_csv("REDItools_processed_dedup-filt.genann.txt", header = 0, sep = "\t")
exp = pd.read_cs... | python |
"""
Pipeline code for training and evaluating the sentiment classifier.
We use the Deepmoji architecture here, see https://github.com/bfelbo/DeepMoji for detail.
"""
import re
import codecs
import random
import numpy as np
import sys
import json
import argparse
import pandas as pd
import glob, os
import matplotlib.pyla... | python |
# SPDX-License-Identifier: MIT
# Copyright (C) 2021 Max Bachmann
from rapidfuzz.cpp_process import extract, extractOne, extract_iter
try:
from rapidfuzz.cpp_process_cdist import cdist
except ImportError:
def cdist(*args, **kwargs):
raise NotImplementedError("implementation requires numpy to be install... | python |
from django.shortcuts import render, redirect
from hujan_ui import maas
from hujan_ui.maas.utils import MAAS
from .forms import VlanForm, VlanEditForm
from django.utils.translation import ugettext_lazy as _
import sweetify
from hujan_ui.maas.exceptions import MAASError
def index(request):
try:
vlans = maa... | python |
# Generated by Django 2.1.7 on 2019-03-01 13:53
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('news', '0002_auto_20161125_0846'),
]
operations = [
migrations.AlterModelOptions(
name='news',
options={'ordering': ('pub_da... | python |
import datetime
import re
import socket
from jwt.exceptions import ExpiredSignatureError, InvalidSignatureError
from mongoengine.errors import (
DoesNotExist,
NotUniqueError,
ValidationError as MongoValidationError,
)
from pymongo.errors import DocumentTooLarge
from thriftpy2.thrift import TException
from ... | python |
from data_interface import Dataset, Data_Interface
from utils import functions as ufunc
import geopandas as gpd
import matplotlib.pyplot as plt
import numpy as np
import os
import rasterio as rio
import rasterio.mask as riom
import shapely
from IPython import embed
import sys
sys.path.append('/home/seba/Projects/swis... | python |
#!/usr/bin/env python3
# Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
# Invoke the `tools/generate_package_config.dart` script.
import os
import os.path... | python |
# -*- coding: UTF-8 -*-
"""
cookie_parser.py
Copyright 2015 Andres Riancho
This file is part of w3af, http://w3af.org/ .
w3af 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 version 2 of the License.
w3af is di... | python |
""" The variables submodule.
This module contains symbolic representations of all ARTS workspace variables.
The variables are loaded dynamically when the module is imported, which ensures that they
up to date with the current ARTS build.
TODO: The group names list is redudant w.rt. group_ids.keys(). Should be remove... | python |
from collections import OrderedDict
from time import time
import unittest
try:
from django.test.runner import DiscoverRunner
except ImportError:
raise("Django 1.8 or 1.9 needs to be installed to use this test runner.")
from .tabulate import tabulate
class Bcolors:
MAGENTA = '\033[95m'
BLUE = '\033[1;... | python |
#!/usr/bin/env python
# Copyright (C) 2013 Apple Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of... | python |
import click
import requests
from bs4 import BeautifulSoup
from ....utils.logging import logger
url = "https://www.codechef.com"
def login_web(self):
global codechef_session
codechef_session = self.session
username = click.prompt('username')
password = click.prompt('password', hide_input=True)
lo... | python |
import socket, argparse, termcolor, threading
open_ports = []
def get_open_ports(host, ports):
global open_ports
for port in ports:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(0.5)
s.connect((host, port))
open_ports.appe... | python |
from urllib.parse import ParseResult, urlencode, urlparse
class URLUtility(object):
"""Contains different helper methods simplifying URL construction."""
@staticmethod
def build_url(base_url, query_parameters):
"""Construct a URL with specified query parameters.
:param base_url: Base URL... | python |
import sys
from queue import PriorityQueue
from utils import Point
import numpy as np
class Astar(object):
def __init__(self):
self.N = 0
self.V = []
self.E = []
self.closed = set([])
def goalTest(self, u):
return u == self.N - 1
def moveGen(self, u):
r... | python |
import os
import re
import tempfile
import subprocess
import typing
from typing import Any
import logging
from rever.tools import replace_in_file
from conda_forge_tick.xonsh_utils import indir
from conda_forge_tick.utils import eval_cmd
from conda_forge_tick.recipe_parser import CondaMetaYAML
from conda_forge_tick.mi... | python |
from argparse import ArgumentParser
from functools import partial
from traceback import StackSummary
import asyncio
import enum
import logging
import ssl
import time
import os
from stem import CircStatus # type: ignore
from stem.control import Controller, EventType # type: ignore
from stem.response.events import Circ... | python |
from collections import Counter
def read_sequence(datapath):
protein_sequence = []
cleavage_site = []
# Loop condition conveniently discards the description lines
with open(datapath, 'r') as f:
while f.readline() is not '':
# Slicing with :-1 to discard "\n" character
... | python |
리스트 = [100,200,300]
for i in 리스트:
print(i+10)
menu = ["김밥","라면","튀김"]
for i in menu:
print("오늘의 메뉴:", i)
리스트 = ["하이닉스","삼성전자","LG전자"]
for i in 리스트:
print(len(i))
리스트 = ['dog','cat', 'parrot']
for i in 리스트:
print(i[0])
리스트 = [1,2,3]
for i in 리스트:
print("3 x ", i)
리스트 = [1,2,3]
for i in 리스트:
... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 17 09:17:38 2021
@author: maxmhuggins
"""
import matplotlib.pyplot as plt
PV_i = 640
k = .25
time = range(0, 24)
PV = [PV_i]
for i in range(0, len(time)-1):
PV.append(PV[i-1]*k+PV[i-1])
plt.plot(time, PV)
print('Final value: %.2f' % PV[-1... | python |
#! python3
# imageSiteDownloader.py
'''
Write a program that goes to a photo-sharing site like Flickr or Imgur,
searches for a category of photos, and then downloads all the resulting
images. You could write a program that works with any photo site that has
a search feature.
'''
import requests, bs4, os, ppri... | python |
# Python RegExp Syntax to Javascript RegExp Syntax Translator
# This code was pulled from the repository at:
# https://github.com/GULPF/rescrypt
# Original license was MIT but was converted to Apache v2 for
# ease of integrating with the Transcrypt project
#
# XXX: don't redefine those here
T = (1<<0)
TEMPLATE = T
... | python |
from deepmath.deephol import predictions
def _proof_state_from_search(predictor, node):
return predictor.ProofState(goal='goal')
| python |
from matplotlib import pyplot as plt
import numpy as np
from math import ceil
def comp_dist(sample: list):
y = list()
for i in range(len(sample)):
y.append(i)
y = np.array(y)
sample_ = np.array(sample)
plot = plt.plot(y, sample_, 'r.', markersize=1)
plt.ylabel('Complexity')
axis_x... | python |
# Copied from the uvloop project. If you add a new unittest here,
# please consider contributing it to the uvloop project.
#
# Portions copyright (c) 2015-present MagicStack Inc. http://magic.io
import asyncio
import logging
import os
import threading
import time
import weakref
from unittest import mock
import pyte... | python |
"""Numpy to Javascript (JSON) conversion
Assumes numpy matrices are nx8 where first 3 columns contain x, y, z
respectively. Checks for `data/*.npy` by default, below. Uses the filename,
stripped, for the data dictionary key.
Remember that classes 1, 2, 3 are colored red, green, blue respectively.
All other classes ar... | python |
from setuptools import setup
setup(
name = 'objectDetectionD3MWrapper',
version = '0.1.0',
description = 'Keras implementation of RetinaNet as a D3M primitive.',
author = 'Sanjeev Namjoshi',
author_email = 'sanjeev@yonder.co',
packages = ['o... | python |
import sys
import interpreter
from interpreter.main import Interpreter
# main
def main():
# check passed parameter length
if len(sys.argv) != 2:
return
code = ''
with open(sys.argv[1], "r") as file:
code = file.read()
i = Interpreter(code)
msg, code, _, _ = i.run()
print('\nReturned with code ' +... | python |
from mmdet.apis import init_detector, inference_detector, show_result
config_file = 'configs/faster_rcnn_r50_fpn_1x.py'
checkpoint_file = 'checkpoints/faster_rcnn_r50_fpn_1x_20181010-3d1b3351.pth'
# build the model from a config file and a checkpoint file
# model = init_detector(config_file, checkpoint_file, device='... | python |
import setuptools
setuptools.setup(
name = 'django-livereload-notifier',
keywords = 'django, development, server, runserver, livereload',
description = 'LiveReload with the Django development server',
long_description = open('README.md').read(),
author ... | python |
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from data_refinery_api.test.test_api_general import API_VERSION
from data_refinery_common.models import (
ComputationalResult,
Organism,
OrganismIndex,
Processor,
Sample,
SampleResultAs... | python |
"""
Zeroing out gradients in PyTorch
================================
It is beneficial to zero out gradients when building a neural network.
This is because by default, gradients are accumulated in buffers (i.e,
not overwritten) whenever ``.backward()`` is called.
Introduction
------------
When training your neural ne... | python |
#
# Copyright (c) 2016, deepsense.io
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | python |
import sys
sys.path.append('../pycaruna')
import json
import os
from datetime import date, datetime, timedelta
from pycaruna import Caruna, Resolution
def make_min_hour_datetime(date):
return datetime.combine(date, datetime.min.time())
def make_max_hour_datetime(date):
return datetime.combine(date, dateti... | python |
import FWCore.ParameterSet.Config as cms
from RecoBTag.Skimming.btagDijet_SkimPaths_cff import *
from RecoBTag.Skimming.btagElecInJet_SkimPaths_cff import *
from RecoBTag.Skimming.btagMuonInJet_SkimPaths_cff import *
from RecoBTag.Skimming.btagGenBb_SkimPaths_cff import *
| python |
import math
def get_divisors(n):
divisors = 0
max = math.sqrt(n)
i = 1
while i <= max:
if n % i == 0:
divisors += 2
i += 1
return divisors
triangle = 1
counter = 2
testing = True
while testing:
if get_divisors(triangle) >= 500:
print(triangle)
test... | python |
#
# ECE 5725 final project
# RPi Robot Mover
# Fall 2021
# Authors: Xu Hai (xh357), Yaqun Niu (yn232)
#
import cv2
import colorList
import picamera
import io
import os
import time
import threading
import numpy as np
from piecamera import PieCamera
import pygame.mixer
# Capture the main color in fr... | python |
#!/usr/bin/env python
#
# PyUSBtmc
# get_data.py
#
# Copyright (c) 2011 Mike Hadmack
# This code is distributed under the MIT license
import numpy
import sys
from matplotlib import pyplot
from pyusbtmc import RigolScope
""" Capture data from Rigol oscilloscope and write to a file
usage: python save_channel.py <fil... | python |
"""Script to load model from file"""
import pickle
from sympy.utilities.lambdify import lambdify
from mihifepe.simulation import model
# pylint: disable = invalid-name
config_filename = "GEN_MODEL_CONFIG_FILENAME_PLACEHOLDER" # This string gets replaced by name of config file during simulation
with open(config_fi... | python |
from django.urls import path
from . import views
urlpatterns=[
path('', views.index,name='index'),
path('login/',views.login, name='login'),
path('register/', views.register, name='register'),
path('profile/', views.profile, name='profile'),
path('logout/', views.logout, name='logout'),
path('n... | python |
import pandas as pd
import matplotlib.pyplot as plt
from datetime import date
lower_limit = 25
date = str(date.today())
df = pd.read_excel(date + ".xlsx")
lower_limit_list = []
for i in df['Sr No.']:
lower_limit_list.append(lower_limit)
plt.figure()
plt.subplot(3, 1, (1, 2))
plt.plot(df['Sr No.'], df['Ready To B... | python |
import cv2
import urllib.request as req
url = 'http://uta.pw/shodou/img/28/214.png'
req.urlretrieve(url, '../datasets/opencv/downimage.png')
img = cv2.imread('../datasets/opencv/downimage.png')
print(img)
import matplotlib.pyplot as plt
img = cv2.imread('../datasets/opencv/test.jpg')
plt.imshow(cv2.cvtColor(img, cv2... | python |
def menu():
print("")
print("")
print(" Welcome to Hotel Database Management Software")
print("")
print("")
print("1-Add new customer details")
print("2-Modify already existing customer details")
print("3-Search customer details")
print("4-View all customer... | python |
#!/usr/bin/env python
# coding: utf-8
# pipenv install grpcio==1.42.0 flask gunicorn keras-image-helper
# USE:
# (base) ➜ ~ curl -X POST -d "{\"url\":\"http://bit.ly/mlbookcamp-pants\"}" -H 'Content-Type: application/json' localhost:9696/predict
# {
# "dress": -1.8682903051376343,
# "hat": -4.761245250701904,
... | python |
#!/usr/bin/python3
"""Manage the image disk."""
import os
import argparse
from azure.mgmt.compute import ComputeManagementClient
from azure.common.credentials import ServicePrincipalCredentials
def connect():
"""Set up Azure Login Credentials from Environmental Variables."""
credentials = ServicePri... | python |
from django.urls import path
from blog.views import *
from blog.feeds import LatestEntriesFeed
app_name = 'blog'
urlpatterns = [
path('' , blog_view , name="index"),
path('<int:pid>' , blog_single , name="single"),
path('category/<str:cat_name>' , blog_view , name="category"),
path('tag/<str:tag_name>' ... | python |
from django.conf.urls import patterns, url
from django.contrib import admin
from django.views.generic import TemplateView
admin.autodiscover()
urlpatterns = patterns('brainstorming.views',
url(r'^$', 'index', name='home'),
url(r'^(?P<brainstorming_id>\w{12})/notification$... | python |
import torch
from torch import nn
from .mobilenet_v2 import MobileNetV2
class Block(nn.Module):
def __init__(self, num_residual_layers, in_channels, out_channels,
kernel_size=3, stride=2, padding=1, remove_last_relu=False):
super(Block, self).__init__()
if remove_last_relu and num... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module that contains tpDcc-tools-scripteditor client implementation
"""
from __future__ import print_function, division, absolute_import
from tpDcc.core import client
class ScriptEditorClient(client.DccClient, object):
PORT = 43451
def get_dcc_completion_... | python |
import re, sys
import base64
import json
def start_item(line):
regex = r"<item><type>(([A-Fa-f0-9]{2}){4})</type><code>(([A-Fa-f0-9]{2}){4})</code><length>(\d*)</length>"
matches = re.findall(regex, line)
typ = matches[0][0].decode('hex')
code = matches[0][2].decode('hex')
length = int(matches[0][4... | python |
# The Hirst Paining Project
# Create a painting with 10 by 10 rows of spots
# Each dot should be 20 in size and 50 spacing between them
from turtle import Turtle, Screen
import random
def main():
# Color palette
color_list = [
(203, 164, 109),
(154, 75, 48),
(223, 201, 135),
(... | python |
import os
import db
from datetime import datetime
import logging
from config import Environment
from fuzzywuzzy import process, fuzz
import nltk
import multiprocessing
ev = Environment()
logger = logging.getLogger(ev.app_name)
# nltk punkt sentence trainer.
nltk.download('punkt')
detector = nltk.data.load('tokenizers... | python |
"""
Manual script for merging csvs into one large CSV per state with plan info.
FIXME: Incorporate this into a script with arguments.
"""
import gc
import logging
import pandas as pd
logging.basicConfig(level=logging.INFO)
HEALTHCARE_GOV_PATH = '/home/jovyan/work/data/healthcare_gov'
state = 'FL'
# Hard coded du... | python |
import cairo
import vector
import rectangle
from .widget import Widget
class CheckBox(Widget):
_on_image = None
_off_image = None
_clicked_image = None
_disabled_image = None
_clicked = False
_moused = False
clickable = True
mousable = True
text = None
toggled_responder ... | python |
from django.shortcuts import render
from django.views.generic.base import View
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.contrib.auth import login, logout
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib import messages
from .forms import Login... | python |
#!/usr/bin/env python3
""" Lightmon Data Read Command
This script reads the data from the light sensor.
"""
import lm
import argparse
import time
import numpy
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Verify the calibration table')
parser.add_argument('-p',
... | python |
from . import transformer
from . import bert
| python |
#! /usr/bin/jython
# -*- coding: utf-8 -*-
#
# sqlite3_read.py
# Jan/12/2011
#
# ----------------------------------------------------------------
#
import sys
import string
from java.lang import System
#
import java
from java.sql import DriverManager
#
# -------------------------------------------------------------... | python |
import contextlib
import logging
import os
from django import test
from django.test import Client
from djangae.environment import get_application_root
from google.appengine.api import apiproxy_stub_map, appinfo
from google.appengine.datastore import datastore_stub_util
from google.appengine.tools.devappserver2.appli... | python |
import uuid
from yggdrasil.tests import assert_raises, assert_equal
import yggdrasil.drivers.tests.test_ConnectionDriver as parent
from yggdrasil import runner, tools
class TestServerParam(parent.TestConnectionParam):
r"""Test parameters for ServerDriver class."""
def __init__(self, *args, **kwargs):
... | python |
from performance.ConfusionMatrix import ConfusionMatrix
from performance.ConfusionMatrixToConfusionTable import ConfusionMatrixToConfusionTable
import numpy as np
class ModelPerformance:
BETA = 1
def __init__(self, model, test_set):
self.confusion_matrix = ConfusionMatrix(model, test_set)
sel... | python |
"""Support for Nest devices."""
from datetime import datetime, timedelta
import logging
import threading
from nest import Nest
from nest.nest import APIError, AuthorizationError
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.config_entries import ConfigEntry
from homeassistant.c... | python |
>>> print(*map(''.join, zip('abc', 'ABC', '123')), sep='\n')
aA1
bB2
cC3
>>>
| python |
from BS.utils import get_string_list_from_file, save_list_to_file
def fix_adjusted_participles():
socket_group_28_01 = list(get_string_list_from_file(
'src_dict/БГ 28.01.21 изм.txt', encoding='cp1251'))
socket_group_23_01 = list(get_string_list_from_file(
'src_dict/БГ 23.01.21.txt', encoding='... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.