content stringlengths 5 1.05M |
|---|
import sys
class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
self.curMax = 0
self.postOrder(root)
return self.curMax
def postOrder(self, root: TreeNode) -> int:
if not root:
return 0
left = self.postOrder(root.left)
ri... |
# Marcelo Campos de Medeiros
# ADS UNIFIP 2020.1
# 3 Lista
# Patos-PB maio/2020
'''
Escreva um programa que leia 2 valores X e Y e que imprima todos os valores entre eles cujo resto da
divisão dele por 5 for igual a 2 ou igual a 3.
Entrada
O arquivo de entrada contém 2 valores positivos inteiros quaisquer, não necess... |
import frappe
from frappe.utils import time_diff_in_hours
def get_tat_for_closed_ticket(start, end):
filters = [
["Request", "start_date", ">=", start],
["Request", "start_date", "<=", end],
["Request", "end_date", ">=", start],
["Request", "end_date", "<=", end],
["Request", "request_status","=","Close"]
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
editor: Aldrich
version: 21.121_released
description: A tool that can import a picture to convenient text.
"""
# Copyright 2021 (C) Aldrich | All Rights Reserved.
# Please download the model files and move them to "C://Users//YourName//.EasyOCR" use before.
... |
import time
def wait_pipe_len(sock, expected, timeout=10):
"""
Wait up to ``timeout`` seconds for the length of sock.pipes to become
``expected`` value. This prevents hardcoding sleep times, which should be
pretty small for local development but potentially pretty large for CI
runs.
"""
... |
import os
from datetime import datetime
from urllib.request import urlretrieve
from zipfile import ZipFile
from ndj_toolbox.fetch import (xml_df_internal, save_files)
url_base = 'http://www.al.sp.gov.br/repositorioDados/'
url_file = 'processo_legislativo/documento_regime.zip'
url = url_base + url_file
def main():
... |
"""
This component is an upgraded version of file sensor.
It has the same characteristics but it:
- expect a vecotr of data read from file in order to be able to interpret it.
- vector lenght is dependant to information of setup.
- It has an additional property that return the whole vector read.
"""
import os
imp... |
# -*- coding: utf-8 -*-
def main():
from itertools import permutations
import sys
input = sys.stdin.readline
s1 = list(input().rstrip())
s2 = list(input().rstrip())
s3 = list(input().rstrip())
s = set(s1) | set(s2) | set(s3)
if len(s) > 10:
print("UNSOLVABLE")
exit()... |
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution(object):
def levelOrder(self, root):
"""
:type root: Node
:rtype: List[List[int]]
"""
if root is None:
... |
"""
MIT License Block
Copyright (c) 2015 Alex Barry
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, merge, publi... |
import os
from os.path import expanduser
import base64
import binascii
import hmac
import itertools
import operator
import shutil
import sqlite3
import struct
import subprocess
import hashlib
from apps.server.modules.mod_interface import mod_interface
try:
xrange
except NameError:
# Python3 support.
# noin... |
# -*- coding: utf-8 -*-
"""
Filter database using Pharmacophore model.
Created on Mon Mar 16 10:11:53 2015
@author: Marta Stepniewska
"""
from pybel import readfile
from decaf import Pharmacophore
from decaf.toolkits.ob import phar_from_mol
from decaf.utils import similarity
from multiprocessing import Process, Manag... |
# -*- coding: utf-8 -*-
# @Author: CodyKochmann
# @Date: 2020-04-05 11:39:37
# @Last Modified by: CodyKochmann
# @Last Modified time: 2020-04-05 12:23:59
from typing import Set, Tuple, Dict
import sqlite3, inspect, logging, unittest
'''
FuzzResult structure
{
(int, int): {
True: [
([3, 5], 8),
([1, 1],... |
import os
import json
import shutil
import logging
import requests
import tempfile
from xml.etree.ElementTree import fromstring, tostring
from os.path import join, exists, basename, expanduser
from util.job_util import exec_command
from pm_proxy.pm_base import PackageManagerProxy
class MavenProxy(PackageManagerProxy... |
from django.utils.text import slugify
from rest_framework import serializers
from fragments.models import Post, Fragment
class FragmentSerializer(serializers.ModelSerializer):
"""
Serializer for Fragment instances
"""
class Meta:
model = Fragment
fields = (
'post',
... |
import assemblycalculator as ac
import multiprocessing as mp
import pickle
import pandas as pd
import os
def calculate_assembly_MC(inchi):
""" Calculate the assembly value of an inchi string using the monteCarlo assembly method
Args:
month (string): YYYY-MM description of the month where the compound... |
from enum import Enum, IntEnum
class Axe(IntEnum):
X = 0
Y = 1
Z = 2
class OdeSolver(Enum):
"""
Four models to solve.
RK is pretty much good balance.
"""
COLLOCATION = 0
RK = 1
CVODES = 2
NO_SOLVER = 3
class Instant(Enum):
"""
Five groups of nodes.
START: f... |
"""
Utils and functions to determine irrigation topology
Inne Vanderkelen - March 2021
"""
# import modules
import pfaf.pfafstetter as pfaf # decode package from Naoki, see https://github.com/nmizukami/pfaf_decode
import pandas as pd
import numpy as np
import geopandas as gpd
###################
# 1. Helper func... |
from collections import defaultdict
import csv
import json
from logging import Logger
import os
import sys
from typing import Callable, Dict, List, Tuple
import subprocess
import numpy as np
import pandas as pd
from .run_training import run_training
from chemprop.args import TrainArgs
from chemprop.constants import TE... |
import mindspore
import numpy as np
from mindspore import context, ms_function
from mindspore import nn, Tensor
from mindspore.ops import GradOperation, operations as P
context.set_context(device_target="CPU")
context.set_context(mode=context.GRAPH_MODE)
class OpNetWrapper(nn.Cell):
def __init__(self, op, *args,... |
"""A package of the implementation of the Conjugate Gradient solver for project 1.""" |
from spaceone.inventory.libs.schema.metadata.dynamic_field import TextDyField, SearchField, EnumDyField
from spaceone.inventory.libs.schema.cloud_service_type import CloudServiceTypeResource, CloudServiceTypeResponse, \
CloudServiceTypeMeta
cst_ta = CloudServiceTypeResource()
cst_ta.name = 'Check'
cst_ta.provider... |
import logging
import re
import pubchempy as pcp
import numpy as np
from matchms.utils import is_valid_inchikey
logger = logging.getLogger("matchms")
def pubchem_metadata_lookup(spectrum_in, name_search_depth=10, match_precursor_mz=False,
formula_search=False,
... |
#
# PySNMP MIB module SC5002-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SC5002-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:00:56 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:... |
# -*- mode: python; coding: utf-8; -*-
""" Custom exceptions """
class AjaxException(Exception):
"""Base class for AJAX exceptions"""
pass
class Ajax404(AjaxException):
"""Object not found"""
pass
class AjaxDataException(AjaxException):
"""
Use it to push json data to response
"""
d... |
'''Library of common utilities shared between notebooks in SIRF-Exercises.'''
# Author: Ashley Gillman
# Copyright 2021 Commonwealth Scientific and Industrial Research Organisation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... |
import pytest
from autoextract.aio.client import RequestProcessor
from autoextract.aio.errors import _QueryError
def test_request_processor_without_retries():
# Given an initial query with two items
initial_query = [
{
"url": "https://example.org/first",
"pageType": "article",... |
import voluptuous as vol
import esphomeyaml.config_validation as cv
from esphomeyaml.components import switch
from esphomeyaml.const import CONF_INVERTED, CONF_MAKE_ID, CONF_NAME
from esphomeyaml.cpp_generator import variable
from esphomeyaml.cpp_types import Application, App
MakeShutdownSwitch = Application.struct('... |
# -*- coding: utf-8 -*-
import zeep
# Webová služba pro práci s organizačními jednotkami a osobami
class OrganizationUnit(object):
__module__ = 'skautis'
def __init__(self, test):
if test:
self._client = zeep.Client('https://test-is.skaut.cz/JunakWebservice/OrganizationUnit.asmx?wsdl')
... |
import numpy as np
import cv2
import FeatureExtract
def seglist():
roiList = []
feature = []
img = cv2.imread('Pictures\\test1row.png')
#gray conversion of the image
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#image thresholding
ret, thresh = cv2.threshold(gray, 230, 255, cv2.THRESH_BINAR... |
from bpyutils.util import _dict |
from datetime import date
from django import forms
from django.http import HttpResponse
from django.contrib import admin
from models import DynamicFieldValue, DynamicField, DynamicFormFieldRelation, DynamicForm, DynamicFormData
from StringIO import StringIO
from zipfile import ZipFile
import csv
class DynamicFieldVal... |
import os
import os.path as osp
import numpy as np
from glob import glob
from tqdm import tqdm
import mmcv
def disp_modulate(disp_map, max_value=1):
""" Transfer the value of disp maps to the [img] range -1 ~ 1
"""
EPS = 1e-3
Gamma = 0.3
EXPAND = 10
disp_map = (disp_map * EXPAND).astype(np.floa... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# --------------------------------------------------------------------------------------------
# - Generated by tools/entrypoint_co... |
from talon import Context, Module
mod = Module()
ctx = Context()
ctx.matches = r"""
os: linux
tag: user.timer_manager
"""
# systemd is already in service_manager
# mod.tag("systemd", desc="systemd management")
mod.tag("timer_manager", desc="generic timer manager support")
mod.tag("cron", desc="non-systemd timer timer... |
import ezdxf
import svgwrite
import numpy as np
# https://www.desmos.com/calculator/rtkn6udxmy
# r=-\ 0.0\cdot\cos\left(2\cdot\theta\right)\ -\ \ 0.02\cdot\cos\left(4\cdot\theta\ \right)\ \ +\ 0.0\ \cos\ \left(6\cdot\theta\right)\ +\ 0.1\cos\left(8\cdot\left(\theta\right)\right)\ +\frac{5}{\left|\cos\left(\theta+\fr... |
import os
import pathlib
import datajoint as dj
import element_data_loader.utils #github.com/datajoint/element-data-loader
from adamacs import db_prefix, session, behavior
import scipy.io as spio
import numpy as np
schema = dj.schema(db_prefix + 'behavior_ingest')
@schema
class BehaviorIngest(dj.Imported):
defin... |
# Generated by Django 2.1.7 on 2020-01-17 09:51
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('contest', '0005_contestannouncement_update_time'),
]
operations = [
migrations.AlterFi... |
# -*- coding: utf-8 -*-
# Spearmint
#
# Academic and Non-Commercial Research Use Software License and Terms
# of Use
#
# Spearmint is a software package to perform Bayesian optimization
# according to specific algorithms (the “Software”). The Software is
# designed to automatically run experiments (thus the code name
... |
import mysql.connector
def conn():
conn = mysql.connector.connect(
host = "127.0.0.1",
user = "root",
password = "0000",
database = "future",
)
return conn |
from itertools import tee
from spacy.tokens import Doc
from spacy.tokens import Token
from spacy.language import Language
from text_complexity_analyzer_cm.constants import ACCEPTED_LANGUAGES
Doc.set_extension('feature_count', default=None, force=True)
@Language.factory('feature counter')
class FeatureCounter:
d... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import rospy
import cv2
from std_msgs.msg import String
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
import glob
class image_converter:
def __init__(self):
rospy.init_node('image_converter', anonymous=True)
... |
#!/usr/bin/env python3
# Copyright 2021 Flant JSC
#
# 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 ... |
#!/usr/bin/env python
import json
import logging
import os
import re
import sys
from time import sleep
import sesamclient
import fnmatch
from portal import PortalConnection
# define required and optional environment variables
required_env_vars = ["node_endpoint", "jwt", "rules"]
optional_env_vars = ["loglevel", "loc... |
import json
from elasticsearch import Elasticsearch, helpers
from collections import OrderedDict
from requests_html import HTMLSession
import urllib.parse as url_parse
index_name = "raw"
doc_type = "twitter"
es = Elasticsearch("http://127.0.0.1:9200/") #localhost = 127.0.0.1:9200
get_data = es.get(index = index_name... |
__author__ = "Vanessa Sochat"
__copyright__ = "Copyright 2021, Vanessa Sochat"
__license__ = "Apache-2.0 OR MIT"
# This is an example for doing a splicing (preliminary) analysis to make
# a prediction about whether a package will build or not. This means:
# 1. Starting with a package of interest
# 2. Getting all specs... |
from typing import List
class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
stack =[]
for ch in s:
if len(stack) != 0 and stack[-1][0] == ch:
tmp = stack.pop()
if tmp[1]+1 != k:
stack.append([tmp[0],tmp[-1]+1])
... |
from django.urls import path
from .views import BookListView, WriterListView, BookSubListView, WriterSubListView, \
SearchByGenres, CreateWriterView, CreateBookView, DeleteBookView, DeleteWriterView
urlpatterns = [
path('books/', BookListView.as_view(), name='Book'),
path('book/<item>/', BookSubListView.a... |
from django.test import TestCase
from testly.models import TestRun as Run
class TestRuns(TestCase):
def setUp(self):
self.test_run1 = Run.objects.create(requested_by='Jenkins', path='test_runs.py', environment=1)
self.test_run2 = Run.objects.create(requested_by='Jenkins', path='test_runs.py', env... |
""" Various generic env utilties. """
def center_crop_img(img, crop_zoom):
""" crop_zoom is amount to "zoom" into the image. E.g. 2.0 would cut out half of the width,
half of the height, and only give the center. """
raw_height, raw_width = img.shape[:2]
center = raw_height // 2, raw_width // 2
cro... |
#
# This file is part of LiteX-Boards.
#
# Copyright (c) 2020 David Corrigan <davidcorrigan714@gmail.com>
# Copyright (c) 2020 Alan Green <avg@google.com>
# SPDX-License-Identifier: BSD-2-Clause
from litex.build.generic_platform import *
from litex.build.lattice import LatticePlatform
from litex.build.lattice.programm... |
from datetime import datetime, timedelta
import pytest
from app.source import get_datetime, get_process_cycle_efficiency
from app.source.pivotal import Pivotal
def mock_pivotal_client(
mocker, project_info={}, iterations=[],
story_started="2018-11-01T12:00:00Z", stories=[],
story_blockers=[], story_activ... |
import json
with open('data/moon-data.json', 'r') as f:
data = json.load(f)
for planet in data:
planet['moons'].sort(key=lambda p: p['orbit'])
with open('data/moon-data.json', 'w') as f:
f.write(json.dumps(data, indent=4))
|
"""
Date: 2022.05.19 14:30:18
LastEditors: Rustle Karl
LastEditTime: 2022.05.20 10:20:18
"""
import traceback
def another_function():
lumberstack()
def lumberstack():
print("-" * 60)
traceback.print_stack()
print("-" * 60)
print(repr(traceback.extract_stack()))
print("-" * 60)
print(repr... |
from collections import namedtuple
from dataclasses import dataclass
from enum import Enum
from typing import Any, Dict, List, Optional, Sequence, Tuple
from uuid import UUID
from pydantic import BaseModel, validator
MIN_GRID_WIDTH = 3
MIN_GRID_HEIGHT = 3
MAX_GRID_WIDTH = 10
MAX_GRID_HEIGHT = 10
MIN_WINNING_LINE = 3... |
#!/usr/bin/env python
#
# This file is part of GreatFET
#
"""
Utility for flashing the onboard SPI flash on GreatFET boards.
"""
from __future__ import print_function
import os
import sys
import time
import errno
import argparse
import subprocess
import usb
from greatfet import GreatFET
from greatfet.errors imp... |
import numpy as np
import h5py
def save_to_h5(output_filepath, col_name, dataset, expand=True):
if expand:
dataset = np.expand_dims(dataset, axis=0)
# convert float64 to float32 to save space
if dataset.dtype == 'float64':
dataset = np.array(dataset, dtype='float32')
with h5py.Fil... |
from c0101_retrieve_ref import retrieve_ref
from c0102_build_path import build_path
from c0103_save_meta import save_meta
from c0104_retrieve_meta import retrieve_meta
from c0105_record_to_summary import record_to_summary
import os
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
im... |
from rest_framework.parsers import FormParser
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django.http import HttpResponse
import subprocess
import re
import os
class Track(APIView):
permission_classes = (IsAuthentica... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import colorsys
from ._tuya_api import _TuyaApi
from .exceptions import ModeNotSupported, FunctionNotSupported, ArgumentError
class Bulb(_TuyaApi):
"""
Allows you to control the operation of your smart light bulb.
:param client_id: your client i... |
from direct.directnotify import DirectNotifyGlobal
from direct.distributed.DistributedObjectAI import DistributedObjectAI
class DistributedPhaseEventMgrAI(DistributedObjectAI):
notify = DirectNotifyGlobal.directNotify.newCategory('DistributedPhaseEventMgrAI')
|
from ApplianceOwner import ApplianceOwner
from ApplianceOwner import HouseHold
import numpy
class Community():
def __init__(self,number_of_households,mean_residents,sd_residents):
self.number_of_households: int = number_of_households
self.mean_residents: float = mean_residents
self.sd_re... |
from __future__ import unicode_literals
from django.contrib import admin
from django.contrib.admin.models import LogEntry, ADDITION, CHANGE, DELETION
from django.utils.html import escape
from django.core.urlresolvers import reverse, NoReverseMatch
from django.contrib.auth.models import User
action_names = {
ADDIT... |
from .stroke import Stroke, StrokePosition
from .component import Component, ComponentInfo
from .stroke_path import *
from .shape import Pane
class StrokeSpec:
def __init__(self, typeName, parameters = None, segments = None,
splinePointsList = None):
self.typeName = typeName
self.parameters = parameters
sel... |
import socket
import threading
import time
import cv2
from easytello.stats import Stats
from functools import wraps
from playsound import playsound
import detect
import navigate
class Tello:
def __init__(self, tello_ip: str='192.168.10.1', debug: bool=True):
# Opening local UDP port on 8889 f... |
import os
import subprocess
import sys
import math
import string
import shutil
import json
import re
import shutil
# build pyramid from an input image
# return an array of level file names
def pyramid(input_file_path, num_levels):
filter = 'Lanczos';
blur = .9891028367558475;
# magick
if(not shutil.w... |
import sys
import asyncio
import aiohttp
from tornado.ioloop import IOLoop
from tornado.web import Application
from tornado.queues import Queue
from yamlparams.utils import Hparam
from loguru import logger
from models.implicitALS.dataloader import Loader
from models.implicitALS.singleton import SharedModel
from http_... |
import math
class DutyCycle:
def __init__(self, goal_temp, duration, outside_temp=75, wind=0):
self.temp_difference = goal_temp - outside_temp
self.duration = duration
self.wind = wind
self.goal_temp = goal_temp
self.outside_temp = outside_temp
self.duty_prop_max = mi... |
f = open('6_input.txt').read().split(",")
f = [int(x) for x in f]
for i in range(80):
f = [x-1 for x in f]
for j in range(len(f)):
if f[j] == -1:
f.append(8)
f[j] = 6
answer = len(f)
print(answer)
|
class MinCostToConnectAllPoints:
"""
https://leetcode-cn.com/problems/min-cost-to-connect-all-points/
"""
def minCostConnectPoints(self, points: List[List[int]]) -> int:
|
# encoding: utf-8
import os, uuid, time
import urwid
from urwid.raw_display import Screen
from zope.interface import Interface, Attribute, implementer
from twisted.application.service import Application
from twisted.application.internet import TCPServer
from twisted.cred.portal import Portal
from twisted.conch.interf... |
print('Digite o salário-base do funcioário, que tem 5% de gratificação sobre o salário '
'e que paga 7% de imposto sobre o salário')
salario_base = float(input('Salário Base: '))
gartificacao = salario_base * (5 / 100)
salario_gratificado = salario_base + gartificacao
imposto = salario_base * (7 / 100)
salario_im... |
from .countries import Country, CountryModel
aus = CountryModel(Country.AUSTRALIA)
phl = CountryModel(Country.PHILIPPINES)
COUNTRY_RUNNERS = [
"aus",
"phl",
]
|
# -*- coding: utf-8 -*-
"""
@file simpleTest.py
@author Simon Box, Craig Rafter
@date 29/01/2016
test Miller's algorithm
"""
import sys, os
sys.path.insert(0, '../sumoAPI')
import fixedTimeControl
import HybridVAControl
import sumoConnect
import readJunctionData
import traci
from routeGen import routeGen
from s... |
# -*- coding: utf-8 -*-
# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html
from scrapy import signals
from scrapy.http import HtmlResponse
import time
import random
from scrapy.downloadermiddlewares.useragent import UserAgent... |
import os
from pathlib import Path
from tensorflow.keras.callbacks import ModelCheckpoint
from model_new import MusicTransformer
from custom.layers import *
from custom import callback
import params as par
from tensorflow.keras.optimizers import Adam
from data import DataNew
import utils
import argparse
import dateti... |
import numpy as np
import pytest
from napari.utils.colormaps import Colormap
def test_linear_colormap():
"""Test a linear colormap."""
colors = np.array([[0, 0, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1]])
cmap = Colormap(colors, name='testing')
assert cmap.name == 'testing'
assert cmap.interpolation == ... |
import asyncio
import json
import unittest
from string import printable
from asynctest import CoroutineMock, patch
from graphql import parse
from hypothesis import given, strategies as st
import mock
from py2graphql import (
Aliased,
Client,
GraphQLEndpointError,
GraphQLError,
InfinityNotSuppor... |
import itertools
import pytest
import numpy as np
from panqec.bpauli import bcommute, bsf_wt
from panqec.codes import Toric3DCode
from panqec.decoders import Toric3DMatchingDecoder
from panqec.error_models import PauliErrorModel
class TestToric3DMatchingDecoder:
@pytest.fixture
def code(self):
return... |
import os
import traceback
import namedtupled
from functools import partial
from itertools import chain
import numpy as np
from scipy import stats
from sklearn.externals import joblib
from sklearn.preprocessing import LabelEncoder
import librosa
import h5py
from model.preproc.model import MelSpectrogramGPU
from m... |
import subprocess
import os
import time
import random
import string
def randomString(stringLength=10):
"""Generate a random string of fixed length """
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(stringLength))
files = []
command = "/bin/touch"
processes = set()
ma... |
import uuid
import requests
from django.contrib.auth.models import User
from django.core.files.base import ContentFile
from django.core.management.base import BaseCommand
from tqdm import tqdm
from slacker import Slacker
from staff.conf import settings
from staff.models import Profile
class Command(BaseCommand):
... |
from torch.utils.data import Dataset
import pandas as pd
from skimage.io import imread
from skimage.transform import resize
from config.data_utils import all_classes
import pickle
def load_pickle(path):
with open(path,'rb') as handle:
return pickle.load(handle)
class data_loader_classifier(Dataset):
... |
#!/usr/bin/env python3
# Tools for data that can be represented as tables with row and columns.
"""
Tools for translating delimited text to and from Python typed values.
This module uses the Python csv package as the foundation for more
elaborate operations with CSV text. csv.reader.
The features added by this modul... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2020 ANYbotics AG
#
# 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... |
'''
comp_slice_ is a terminal fork of intra_blob.
It traces blob axis by cross-comparing vertically adjacent Ps: horizontal slices across an edge blob.
These high-G high-Ma blobs are vectorized into outlines of adjacent flat or low-G blobs.
Vectorization is clustering of Ps + derivatives into PPs: patterns ... |
#!/usr/bin/env python
"""
sentry-sprintly
===============
An extension for Sentry which integrates with Sprint.ly.
:copyright: (c) 2014 by Matt Robenolt, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from setuptools import setup, find_packages
install_requires = [
'sentry>=5.0.0... |
import datetime
import json
import uuid
import unittest
import pandas as pd
from spylunking.log.setup_logging import test_logger
from celery_connectors.publisher import Publisher
log = test_logger(name='test_base')
class BaseTestCase(unittest.TestCase):
def setUp(
self):
"""setUp"""
... |
import inspect
import psyneulink as pnl
import pytest
from psyneulink.core.components.projections.modulatory.modulatoryprojection import ModulatoryProjection_Base
from psyneulink.core.components.projections.pathway.pathwayprojection import PathwayProjection_Base
# gather all Component classes (a set to ensure no dupl... |
#Standard Library Input
#Third Party Inputs
#Local Application Inputs
class Wrapper():
def BoldWrapper(self, message):
return f'**{message}**'
def UpperWrapper(self, message):
return message.upper()
def ItalicWrapper(self, message):
return f'*{message}*'
def AllAngryWra... |
#!/usr/bin/env python
# coding=utf-8
import math
def k_quantiles(items, k):
index = median_index(len(items))
if k == 1:
return []
elif k % 2:
n = len(items)
left_index = math.ceil((k // 2) * (n / k)) - 1
right_index = n - left_index - 1
left = select... |
from os import path, system
hosts = [ 'atat_21mer', 'g_tract_21mer', 'a_tract_21mer', 'gcgc_21mer',
'ctct_21mer', 'tgtg_21mer', 'tat_21mer', 'tat_1_21mer', 'tat_2_21mer', 'tat_3_21mer']
rootfolder = '/home/yizaochen/codes/dna_rna/all_systems'
fhelix_folder = '/home/yizaochen/codes/dna_rna/length_effect/find... |
"""
Test for testing runbook generated json against known json
"""
import os
from calm.dsl.runbooks import runbook_json
from decision_task import DslDecisionRunbook
from existing_endpoint import DslExistingEndpoint
from parallel import DslParallelRunbook
from runbook_variables import DslRunbookWithVariables
from simpl... |
import os
import shutil
import fileinput
from time import sleep
FOLDER1 = "/../client1/conf/Sync"
FOLDER2 = "/../client2/conf/Sync"
TEST_STRING = "This is a test string to verify that sharing works."
PWD = os.getcwd()
FILE1 = ('test.txt')
FILE2 = ('test2.txt')
STRING2 = "This is a second string."
STRING3 = "Even more... |
from numpy import argmax
from pickle import load
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from nltk.translate.bleu_score import corpus_bleu
# remove start/end sequence tokens from a summary
def cleanup_summary(summary):
# remove start of sequence token
i... |
import pytest
from auth_api.db import db
from auth_api.queries import UserQuery
from tests.auth_api.queries.query_base import TestQueryBase, USER_LIST
class TestUserQueries(TestQueryBase):
"""
Tests cases where a subject in written into the database
and can be returned if correct subject is called.
"... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
from dashboard.models import Node, Order
from .models import History_order
from django.contrib.auth.models import User
from django.utils import timezone
from datetime import datetime, timedelta
from .views import firewall_... |
import psycopg2
dbname = 'REDACTED'
user = 'REDACTED'
password = 'REDACTED'
host = 'REDACTED'
pg_conn = psycopg2.connect(database=dbname, user=user, password=password, host=host)
pg_curs = pg_conn.cursor()
print("Titanic questions")
print("\nHow many passengers survived, and how many died? (Percentage survival)")
pg_c... |
import os
from os.path import dirname, join, isabs, isdir, exists, abspath, realpath
import pytest
import sys
import datetime as dt
try:
thisdir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(thisdir, '..'))
except:
sys.path.append('..')
from dibs.settings import config, reso... |
import time
from datetime import datetime
import config
from web.models.models import Instance
from web.basehandler import BaseHandler
class InstancesHandler(BaseHandler):
def get(self):
print "running tasks" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.