content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... | python |
# -*- coding: utf-8 -*-
"""
This module contains the Parameters class that is used to specify the input parameters of the tree.
"""
import numpy as np
class Parameters():
"""Class to specify the parameters of the fractal tree.
Attributes:
meshfile (str): path and filename to obj file name... | python |
from .fixup_resnet_cifar import *
from .resnet_cifar import *
from .rezero_resnet_cifar import *
from .rezero_dpn import *
from .dpn import *
from .rezero_preact_resnet import *
from .preact_resnet import *
| python |
import os.path
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from ui.mainwindow import Ui_MainWindow
from ui.worldview import WorldView
from world import World
class PsychSimUI(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
self.world = None
super(PsychSimUI, self).__init__(pa... | python |
from torch.optim import Optimizer
class ReduceLROnLambda():
def __init__(self, optimizer, func, factor=0.1,\
verbose=False, min_lr=0, eps=1e-8):
if factor >= 1.0:
raise ValueError('Factor should be < 1.0.')
self.factor = factor
if not isinstance(optimizer, Optimizer):
raise TypeError('{} is not an O... | python |
# --------------
import pandas as pd
from sklearn import preprocessing
#path : File path
# Code starts here
# read the dataset
dataset = pd.read_csv(path)
# look at the first five columns
print(dataset.head())
# Check if there's any column which is not useful and remove it like the column id
dataset = dataset.drop... | python |
import errno
import os
from tqdm import tqdm
from urllib.request import urlretrieve
def maybe_makedir(path: str) -> None:
try:
# Create output directory if it does not exist
os.makedirs(path)
except OSError as e:
if e.errno != errno.EEXIST:
raise
def download_file(url: st... | python |
from typing import Union
import numpy as np
import pandas as pd
from fedot.api.api_utils.data_definition import data_strategy_selector
from fedot.core.data.data import InputData
from fedot.core.repository.tasks import Task, TaskTypesEnum
from fedot.core.pipelines.pipeline import Pipeline
class ApiDataHelper:
def ... | python |
#!/usr/bin/env python
import pandas as pd
import os
import numpy as np
import SNPknock.fastphase as fp
from SNPknock import knockoffHMM
from joblib import Parallel, delayed
import utils_snpko as utils
logger = utils.logger
def make_knockoff(chromosome=None, grouped_by_chromosome=None, df_SNP=None,
... | python |
import datetime
import json
import time
from fate_manager.db.db_models import DeployComponent, FateSiteInfo, FateSiteCount, FateSiteJobInfo, ApplySiteInfo
from fate_manager.entity import item
from fate_manager.entity.types import SiteStatusType, FateJobEndStatus
from fate_manager.operation.db_operator import DBOperato... | python |
from . import ShapeNet, SetMNIST, SetMultiMNIST, ArCH
def get_datasets(args):
if args.dataset_type == 'shapenet15k':
return ShapeNet.build(args)
if args.dataset_type == 'mnist':
return SetMNIST.build(args)
if args.dataset_type == 'multimnist':
return SetMultiMNIST.build(args)
... | python |
# flake8: noqa: W291
# pylint: disable=too-many-lines,trailing-whitespace
"""
AbstractAnnoworkApiのヘッダ部分
Note:
このファイルはopenapi-generatorで自動生成される。詳細は generate/README.mdを参照
"""
from __future__ import annotations
import abc
import warnings # pylint: disable=unused-import
from typing import Any, Optional, Union # py... | python |
#!/usr/bin/env python
from setuptools import setup, os
setup(
name='PyBabel-json-md',
version='0.1.0',
description='PyBabel json metadef (md) gettext strings extractor',
author='Wayne Okuma',
author_email='wayne.okuma@hpe.com',
packages=['pybabel_json_md'],
url="https://github.com/wkoathp... | python |
# Tai Sakuma <tai.sakuma@gmail.com>
import pytest
has_no_ROOT = False
try:
import ROOT
except ImportError:
has_no_ROOT = True
from alphatwirl.roottree import Events
if not has_no_ROOT:
from alphatwirl.roottree import BEvents as BEvents
##_________________________________________________________________... | python |
import qimpy as qp
import numpy as np
from scipy.special import sph_harm
from typing import Sequence, Any, List, Tuple
def get_harmonics_ref(l_max: int, r: np.ndarray) -> np.ndarray:
"""Reference real solid harmonics based on SciPy spherical harmonics."""
rMag = np.linalg.norm(r, axis=-1)
theta = np.arcco... | python |
# Copyright (c) nexB Inc. and others. All rights reserved.
# http://nexb.com and https://github.com/nexB/vulnerablecode/
# The VulnerableCode software is licensed under the Apache License version 2.0.
# Data generated with VulnerableCode require an acknowledgment.
#
# You may not use this software except in compliance ... | python |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui/app_ui.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, Qt... | python |
from cloudshell.shell.core.resource_driver_interface import ResourceDriverInterface
from cloudshell.shell.core.context import InitCommandContext, ResourceCommandContext
import cloudshell.api.cloudshell_api as api
from natsort import natsorted, ns
import ipcalc
import json
class IpcalcDriver (ResourceDriverInterface):
... | python |
"""
Routine to create the light cones shells
L1 L2 L3 u11 u12 u13 u21 u22 u23 u31 u32 u33 (periodicity)
C2 '2.2361', '1.0954', '0.4082', '2', '1', '0', '1', '0', '1', '1', '0', '0', '(1)'
C15 '1.4142', '1.0000', '0.7071', '1', '1', '0', '0', '0', '1', '1', '0', '0', '(12)'
C6 '5.9161', '0.4140', '0.4082', '5... | python |
# This module is avaible both in the Python and Transcrypt environments
# It is included in-between the __core__ and the __builtin__ module, so the latter can adapt __envir__
# In Transcrypt, __base__ is available inline, it isn't nested and cannot be imported in the normal way
class __Envir__:
def __init__ (... | python |
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 3.0.12
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info as _swig_python_version_info
if _swig_python_version_info >= (2, 7, 0):
def swig_im... | python |
import hashlib
class HashUtils(object):
@staticmethod
def md5(string: str):
md5 = hashlib.md5(string.encode("utf-8"))
return md5.hexdigest()
@staticmethod
def sha1(string: str):
sha1 = hashlib.sha1(string.encode("utf-8"))
return sha1.hexdigest()
... | python |
#!/bin/python
# Solution for https://www.hackerrank.com/challenges/jumping-on-the-clouds-revisited
import sys
n,k = raw_input().strip().split(' ')
n,k = [int(n),int(k)]
c = map(int,raw_input().strip().split(' '))
E = 100
current = 0
time = 0
while not (time > 0 and current == 0):
current += k
... | python |
import pickle
import pandas as pd
import numpy as np
import time
from sklearn.model_selection import TimeSeriesSplit, GridSearchCV
from sklearn.ensemble import RandomForestClassifier
import os
def feat_eng(df_fe):
'''
Función que realiza la selección de los features que serán utilizdos para la clasificación
... | python |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: transaction/v4/transaction_service.proto
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import s... | python |
# MIT License
#
# Copyright (c) 2020 Airbyte
#
# 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, publ... | python |
import libsinan
from libsinan import handler, output, jsax
class VersionCheckTaskHandler(output.SimpleTaskHandler):
def __init__(self):
output.SimpleTaskHandler.__init__(self)
self.version = None
def object_end(self):
""" We only get one object per right now so
lets print it ... | python |
import urllib.request, json
from .models import News_Update
from .models import Article
api_key = None
base_url = None
articles_url = None
def configure_request(app):
global api_key, base_url, articles_url
api_key = app.config['NEWS_API_KEY']
base_url = app.config['NEWS_API_BASE_URL']
articles_url =... | python |
# -*- coding: UTF-8 -*-
from django.shortcuts import render
from rest_framework import authentication, viewsets
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.response import Response
from rest_framework import stat... | python |
""" Docstring for the app_test.py module.
"""
import pytest
from app import app
@pytest.fixture
def client():
"""
Method to yield a test client from app.
"""
app.config['TESTING'] = True
client = app.test_client()
yield client
def test_ping(client):
"""
Function to test debug route.... | python |
#!/usr/bin/python
# An example vendordata server implementation for OpenStack Nova. With a giant
# nod in the direction of Chad Lung for his very helpful blog post at
# http://www.giantflyingsaucer.com/blog/?p=4701
import json
import sys
from webob import Response
from webob.dec import wsgify
from paste import https... | python |
#PYTHON 3.6
#coding : utf8
from tkinter import *
class Aplication(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.msg = Label(self, text='Hello World')
self.msg.pack()
self.bye = Button(self, text="Bye", command=self.quit)
self.bye.pack()
self.pack()
... | python |
# %matplotlib notebook
import os, re, sys, urllib, requests, base64, IPython, io, pickle, glob
import itertools as itt
import numpy as np
import subprocess as sb
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import roadrunner
from bs4 import BeautifulSoup as BS
from IPython.displ... | python |
from datetime import datetime, timedelta
from freezegun import freeze_time
from pyobjdb import PyObjDB
def test_basic(tmp_path):
db = PyObjDB(str(tmp_path / 'test.db'))
db.put('key_str', 'foo')
assert db.get('key_str') == 'foo'
assert db.get(b'key_str') == 'foo'
db.put('key_str', 'bar')
ass... | python |
""" This file contains tests for partition explainer.
"""
import tempfile
import pytest
import numpy as np
import shap
def test_serialization_partition():
""" This tests the serialization of partition explainers.
"""
AutoTokenizer = pytest.importorskip("transformers").AutoTokenizer
AutoModelForSeq2SeqL... | python |
"""
This module handles teams - collections of Characters
"""
from maelstrom.util.serialize import AbstractJsonSerialable
import functools
class Team(AbstractJsonSerialable):
"""
stores and manages Characters
"""
def __init__(self, **kwargs):
"""
Required kwargs:
- name: s... | python |
# tifffile/__main__.py
"""Tifffile package command line script."""
import sys
from .tifffile import main
sys.exit(main())
| python |
import pygame
import sys
import numpy as np
pygame.init()
WIDTH = 600
HEIGHT = 600
LINE_WIDTH = 15
WIN_LINE_WIDTH = 15
BOARD_ROWS = 3
BOARD_COLS = 3
SQUARE_SIZE = 200
CIRCLE_RADIUS = 60
CIRCLE_WIDTH = 15
CROSS_WIDTH = 25
SPACE = 55
BG_COLOR = (255,0,0)
LINE_COLOR = (0,0,0)
CIRCLE_COLOR = (239, 231... | python |
from nnrecsys.models.metrics import mean_reciprocal_rank
import tensorflow as tf
def model_fn(features, labels, mode, params):
print(features)
input_layer, sequence_length = tf.contrib.feature_column.sequence_input_layer(features, params['feature_columns'])
with tf.name_scope('encoder'):
def rnn_... | python |
import numpy as np
import torch
def default_collate_fn(batch):
batch, targets = zip(*batch)
batch = np.stack(batch, axis=0).astype(np.float32)
batch = torch.from_numpy(batch).permute(0, 3, 1, 2).contiguous()
for i, target in enumerate(targets):
for k, v in target.items():
if isinst... | python |
from random import randint
from django.contrib.auth.models import User
from .models import Analytic, Group
def get_client_ip(request):
x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR")
if x_forwarded_for:
ip = x_forwarded_for.split(",")[0]
else:
ip = request.META.get("REMOTE_ADD... | python |
from __future__ import absolute_import, print_function, division
import os
import numpy
import theano
from theano.compat import PY3
from theano import config
from theano.compile import DeepCopyOp
from theano.misc.pkl_utils import CompatUnpickler
from .config import test_ctx_name
from .test_basic_ops import rand_gpua... | python |
import os
import sys
myfolder = os.path.dirname(os.path.abspath(__file__))
def rpienv_source():
import subprocess
if not os.path.exists(str(myfolder) + '/.rpienv'):
print("[ ENV ERROR ] " + str(myfolder) + "/.rpienv path not exits!")
sys.exit(1)
command = ['bash', '-c', 'source ' + str(myfo... | python |
# ===============================================================================
# Copyright 2020 ross
#
# 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/LICE... | python |
from lib import action
class ConsulParseNodesAction(action.ConsulBaseAction):
def run(self, data):
nodes = []
# Loop through the keys, and return the needful
return nodes
| python |
from fastapi import FastAPI
import routes
from middleware import auth_check
from starlette.middleware.base import BaseHTTPMiddleware
app = FastAPI()
# TO RUN THE APP SPECIFY THIS INSTANCE OF THE FastApi class
# uvicorn file_name:instance name --reload
app.include_router(routes.router)
app.add_middleware(BaseHTTPMidd... | python |
import os
import os.path as op
from ..externals.six.moves import cPickle as pickle
import glob
import warnings
import numpy as np
from numpy.testing import assert_array_equal, assert_array_almost_equal
from nose.tools import assert_true, assert_raises
from mne.datasets import sample
from mne import (label_time_course... | python |
from django.contrib import admin
from .models import MataKuliah, Tugas
# Register your models here.
admin.site.register(MataKuliah)
admin.site.register(Tugas)
| python |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2020-02-16 14:41
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('folio', '0007_auto_20200216_1720'),
]
operations = [
migrations.AddField(
... | python |
@bot.command(brief="Kicks a server member", description="b!kick <member> [reason]")
@commands.has_permissions(kick_members=True)
async def kick(ctx, member: discord.Member, *, reason=None):
try:
await member.kick(reason=reason)
await ctx.send(f'User {member} has been kicked.')
except:
await ct... | python |
#!/usr/bin/env python3
""" Python module to assist creating and maintaining docker openHab stacks."""
import crypt
from enum import Enum
from typing import NamedTuple
import logging
import os
import sys
import json as pyjson
from hashlib import md5
from shutil import copy2
from subprocess import PIPE, run
from time imp... | python |
import os
from bs4 import BeautifulSoup
bicycle = {'Price':'------','Brand':'------','Model':'------','Frame': '------', 'Color': '------', 'Size': '------', 'Fork': '------', 'Headset': '------', 'Stem': '------', 'Handlebar': '------', 'Grips': '------', 'Rear Derailleur': '------', 'Front Derailleur': '------', 'Sh... | python |
a=int(input("enter a number"))
for i in range(a+1):
if(i>1):
for j in range(2,i):
if(i%j==0):
break
else:
print(i)
| python |
from spinn_front_end_common.utilities.notification_protocol.\
notification_protocol import NotificationProtocol
import logging
logger = logging.getLogger(__name__)
class FrontEndCommonNotificationProtocol(object):
""" The notification protocol for external device interaction
"""
def __call__(
... | python |
#!/usr/bin/env python
# Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import hashlib
import optparse
import os
import urllib2
import sys
import time
# Print a dot every time this number of bytes is r... | python |
import RPi.GPIO as GPIO
from queue import Queue
EventClick = 'C'
class ButtonWorker(object):
def __init__(self, pin):
self.gpio = GPIO
self.gpio.setwarnings(False)
self.queue = Queue()
self.pin = pin
self.gpio.setmode(GPIO.BCM)
self.gpio.s... | python |
from pyrogram.types import InlineQueryResultArticle,InputTextMessageContent
from uuid import uuid4
class InlineQueryResults(list):
def __init__(self):
self.results = list()
super().__init__(self.results)
def add(self,title,message_text,message_parse_mode = None,message_disable_web_page_previe... | python |
from .FSError import *
class ProtectFlags:
FIBF_DELETE = 1
FIBF_EXECUTE = 2
FIBF_WRITE = 4
FIBF_READ = 8
FIBF_ARCHIVE = 16
FIBF_PURE = 32
FIBF_SCRIPT = 64
flag_txt = "HSPArwed"
flag_num = len(flag_txt)
flag_none = 0xF # --------
empty_string = "-" * flag_num
def __in... | python |
# -*- coding: utf-8 -*-
"""
tipfyext.mako
~~~~~~~~~~~~~
Mako template support for Tipfy.
Learn more about Mako at http://www.makotemplates.org/
:copyright: 2011 by tipfy.org.
:license: BSD, see LICENSE.txt for more details.
"""
from __future__ import absolute_import
from cStringIO import Stri... | python |
# coding=utf-8
import unittest
import sys
from helpers import xroad, auditchecker
from main.maincontroller import MainController
from tests.xroad_configure_service_222 import configure_service
class XroadDeleteService(unittest.TestCase):
"""
SERVICE_15 Delete a Security Server Client's WSDL
RIA URL: https... | python |
from typing import Callable, Tuple
import numpy as np
from fedot.core.data.data import InputData
from fedot.core.validation.compose.metric_estimation import metric_evaluation
from fedot.core.validation.split import ts_cv_generator
def ts_metric_calculation(reference_data: InputData, cv_folds: int,
... | python |
#
# PySNMP MIB module TRAPEZE-NETWORKS-BASIC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TRAPEZE-NETWORKS-BASIC-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:27:11 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version ... | python |
#!/usr/bin/env python2.7
# Copyright 2016, Google 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:
#
# * Redistributions of source code must retain the above copyright
# notice, this lis... | python |
"""Module with implementation of the Grid classes."""
from bubblebox.library.create import Dataset,Block,Data
from bubblebox.library.utilities import Action
import numpy
import pymorton
class GridBase(Dataset):
"""Base class for the Grid."""
type_ = 'base'
def __init__(self, varlist, nx, ny, xmin, xmax,... | python |
COLUMNS = [
'TIPO_REGISTRO',
'NRO_RV_ORIGINAL',
'NRO_CARTAO',
'NRO_PV_ORIGINAL',
'DT_TRANSACAO_CV',
'NRO_NSU',
'VL_TRANSACAO_ORIGINAL',
'NRO_AUTORIZACAO',
'TID',
'NRO_PEDIDO'
] | python |
"""Setup script"""
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup, find_packages
from Cython.Build import cythonize
import numpy as np
my_modules = cythonize("pysparselp/*.pyx", annotate=True)
libname = "pysparselp"
setup(
name=libna... | python |
import pandas as pd
class HelperDataFrame(pd.DataFrame):
"""Inherits from a Pandas Data Frame and adds a couple methods."""
def __init__(self, df):
super().__init__(data=df)
# self.random_state = 42
def randomize(self):
"""Shuffles observations of a dataframe"""
return self... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
app
~~~~~~~~~~~
The Flask application module.
:author: Jeff Kereakoglow
:date: 2014-11-14
:copyright: (c) 2014 by Alexis Digital
:license: MIT, see LICENSE for more details
"""
import os
from utils import prepare_json_response
from flask imp... | python |
"""
This falls into my "bad idea that I'm playing with" category. Withold judgement and ye lunches.
Upgraded to plausible.
"""
from importlib import import_module
class Singleton(type):
instance_list = {}
def __call__(klass, *args, **kwargs):
if not klass in klass.instance_list:
... | python |
# -*- coding: utf-8 -*-
# @FILE : consts.py
# @AUTH : model_creater
| python |
#!/usr/bin/env python
import numpy as np
import math
from multi_link_common import *
#height is probably 0 from multi_link_common.py
#total mass and total length are also defined in multi_link_common.py
num_links = 8.0
link_length = total_length/num_links
link_mass = total_mass/num_links
ee_location = np.matrix([0.,... | python |
import streamlit as st
st.sidebar.subheader("About dspy")
st.sidebar.info("A webapp that is running on python and teaching python!")
st.sidebar.markdown("""
<img src="https://media.giphy.com/media/3o7527pa7qs9kCG78A/giphy.gif" width="200">
""", unsafe_allow_html=True)
st.title("`dspy` - Data Science with Python")
st.... | python |
#! /usr/bin/env python3
import sys
import os
import cmd2
import logging
import inspect
# local modules
import subcmd
from subcmdfactory import SubCmdFactory
from config import Config, Observer, Subject
class QsmShell(cmd2.Cmd, Observer):
intro = 'Type help or ? to list the command.\n'
def emptyline(self)... | python |
import os
import time
import gpustat
import numpy as np
from redlock import Redlock
GPU_LOCK_TIMEOUT = 5000 # ms
class GPUManager(object):
def __init__(self, verbose: bool=False):
self.lock_manager = Redlock([{"host": "localhost", "port": 6379, "db": 0}, ])
self.verbose = verbose
def get_f... | python |
from matplotlib import pyplot as plt
from matplotlib import animation
import random
import numpy as np
from boids.flock import Flock
from boids.flight import Flight
from argparse import ArgumentParser
import yaml
import os
from nose.tools import assert_equal
from nose.tools import assert_raises
| python |
import orca
import numpy as np
from urbansim.utils import misc
def register_skim_access_variable(
column_name, variable_to_summarize, impedance_measure,
distance, skims_table, agg=np.sum, log=False):
"""
Register skim-based accessibility variable with orca.
Parameters
----------
co... | python |
import chainer
from chainer.dataset import dataset_mixin
from chainercv.chainer_experimental.datasets.sliceable import GetterDataset
import chainercv
from collections import defaultdict
import glob
import os
import numpy as np
import xml.etree.ElementTree as ET
class DogDataset(dataset_mixin.DatasetMixin):
def __... | python |
#! /usr/bin/env python
import numpy as np
import cv2
import glob
import yaml
class CameraCalib :
def __init__(self,img_path='/tmp',CHESSX=8,CHESSY=6,extension=".jpg"):
"""
Initialize Camera Calibration Class
@param: img_path = [path to get images], CHESSX = [chessboard corners in X directi... | python |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from edward.util.tensorflow import get_control_variate_coef
class test_get_control_variate_coef(tf.test.TestCase):
def test_calculate_correct_coefficient(self):
with self.test_... | python |
# Copyright 2020 Jiang Shenghu
# SPDX-License-Identifier: Apache-2.0
from tvm import topi
from ..poly import TensorTable, Statement, ScheduleTree
from .conv import PlainConv2d, Conv2d
def schedule(**kwargs):
init_t = 'stmt_init[n, c, h, w]'
calc_t = 'stmt_calc[n, c, h, w, i, j, k]'
output_constraints = '... | python |
# =============================================================================
# SIMULATION-BASED ENGINEERING LAB (SBEL) - http://sbel.wisc.edu
# University of Wisconsin-Madison
#
# Copyright (c) 2020 SBEL
# All rights reserved.
#
# Use of this source code is governed by a BSD-style license that can be found
# at http... | python |
"""
Write a function with a list of ints as a paramter. /
Return True if any two nums sum to 0. /
>>> add_to_zero([]) /
False /
>>> add_to_zero([1]) /
False /
>>> add_to_zero([1, 2, 3]) /
False /
>>> add_to_zero([1, 2, 3, -2]) /
True /
"""
| python |
# encoding=utf-8
# A collection of regular expressions for parsing Tweet text. The regular expression
# list is frozen at load time to ensure immutability. These reular expressions are
# used throughout the Twitter classes. Special care has been taken to make
# sure these reular expressions work with Tweets in all la... | python |
# !/usr/bin/env python
# -*-coding:utf-8 -*-
# PROJECT : algorithm_mad
# Time :2020/12/22 11:06
# Warning :The Hard Way Is Easier
import random
"""
堆排序
"""
'''堆化'''
def heapify(array, length, i):
largest = i
left = 2 * i + 1
right = 2 * i + 2
if left < length and array[largest] < array[le... | python |
from concurrent.futures import Future
from typing import Any, Callable, TypeVar
from threading import Lock
from amino import do, Do, IO, Map, Dat
from amino.logging import module_log
from ribosome.rpc.error import RpcReadError
from ribosome.rpc.data.rpc import ActiveRpc
A = TypeVar('A')
log = module_log()
PendingR... | python |
# Copyright 2021 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
from django.contrib.auth.models import User
from uw_gws.utilities import fdao_gws_override
from uw_pws.util import fdao_pws_override
from uw_uwnetid.util import fdao_uwnetid_override
def get_user(username):
try:
user = ... | python |
from Jumpscale import j
import os
# import copy
# import sys
import inspect
import types
class JSBase:
def __init__(self, parent=None, topclass=True, **kwargs):
"""
:param parent: parent is object calling us
:param topclass: if True means no-one inherits from us
"""
self._... | python |
# -*- coding: utf-8 -*-
"""
Protocol implementation for `Tokyo Tyrant <http://1978th.net/tokyotyrant/>`_.
Let's assume some defaults for our sandbox::
>>> TEST_HOST = '127.0.0.1'
>>> TEST_PORT = 1983 # default port is 1978
"""
import math
import socket
import struct
import exceptions
# Pyrant constant... | python |
import h2o
h2o.init()
weather_hex = h2o.import_file("weather.csv")
# To see a brief summary of the data, run the following command.
weather_hex.describe()
| python |
from Tkinter import Tk, Label, Button
def update_label():
global n
n += 1
l["text"] = "Number of clicks: %d" % n
w = Tk()
n = 0
l = Label(w, text="There have been no clicks yet")
l.pack()
Button(w, text="click me", command=update_label).pack()
w.mainloop()
| python |
# -*- coding: utf-8 -*-
# cython: language_level=3
# Copyright (c) 2020 Nekokatt
# Copyright (c) 2021-present davfsa
#
# 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, inc... | python |
import json
import os
import copy
__author__ = 'nekmo'
class Field(object):
def __call__(self, value):
return self.parse(value)
def parse(self, value):
raise NotImplementedError
class IntegerField(Field):
def parse(self, value):
return int(value)
class BooleanField(Field):
... | python |
import logging.config
import os
class Config(object):
SERVER_NAME = '127.0.0.1:5000'
LOGGING_CONFIG_FILE = 'logging-config.ini'
@classmethod
def init_app(cls, app):
logging_config_path = os.path.normpath(
os.path.join(
os.path.dirname(__file__), cls.LOGGING_CONFIG_F... | python |
"""
InputReader
--------------------------------------------------
Input Reader that loads previous output files
"""
import yaml
import json
def load_previous_outputs_as_inputs(file_paths: list) -> dict:
print("Start loading input files...")
previous_records = {}
for file_path in file_paths:
prin... | python |
from robo_ai.resources.assistants import AssistantsResource
from robo_ai.resources.client_resource import ClientResource
from robo_ai.resources.oauth import OauthResource
class BaseResource(ClientResource):
def _register_resources(self):
self._add_resource('assistants', AssistantsResource)
self._a... | python |
# sdspy
import configparser
import datetime
import json
from performance_counters import PerformanceCounters as PC
from sds_client import SdsClient
from sds_stream import SdsStream
from sds_type import SdsType
from sds_type_code import SdsTypeCode
from sds_type_data import SdsTypeData
from sds_type_property import Sds... | python |
import matplotlib
# Force matplotlib to not use any Xwindows backend.
matplotlib.use('Agg')
import pickle
import operator
from random import randint
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
import data_io.settings as Settings
from data_io.testdata import sliding_window
f... | python |
class CircularQueue:
""" Queue implementation using circularly linked list for storage """
#-------------------------------------------------------------------------------------
#-------------------------------------------------------------------------------------
class _Node:
""" LightWwight, non public cl... | python |
# -*- coding: utf-8
from __future__ import unicode_literals, absolute_import
import django
DEBUG = True
USE_TZ = True
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "uh-v-hc=h7=%4(5g&f13217*!ja%osm%l0oyb$^n2kk^ij#&zj"
DATABASES = {
"default": {
"ENGINE": "django.db.backen... | python |
import os
import pytest
from helpers.cluster import ClickHouseCluster
from helpers.network import PartitionManager
from helpers.test_tools import assert_eq_with_retry
CLICKHOUSE_DATABASE = 'test'
def initialize_database(nodes, shard):
for node in nodes:
node.query('''
CREATE DATABASE {data... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.