content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import json
from logger import Logger
import xiaomi_data_json
import twilio_sms
import i_email
import schedule # pip install schedule
import socket
import sys
import os
import net_reconnect
import ding_talk_robot
import datetime
import global_config as gl
name = "MiGate... |
from .authenticator import Authenticator
from .websocket_client import WebSocketClient
from .constants import (
API_URL,
WEB_BASE_URL,
WS_BASE_URL,
START_SPLASH_TEXT,
END_SPLASH_TEXT,
codes,
)
from .tester import Tester
from .web_server import WebServer
from .logger import logger
class LocalSe... |
quantity = 3
item = 'widgets'
price = 4995.345
myorder = "I want {} pieces of {} for ${:,.2f}."
print(myorder.format(quantity, item, price))
>>>I want 3 pieces of widgets for $4,995.35.
# : is for formatting codes
# $ is outside of {}
# ,.2f means comma thousand separator, 2 decimal float16 number
# Strin... |
def combinationSum(candidates: list[int], target: int) -> list[list[int]]:
solutions = set()
checked = set()
stack = []
def recur(total):
seq = tuple(sorted(stack[:]))
if seq in checked:
return
checked.add(seq)
if total == target:
solution... |
import numpy as np
import tensorflow as tf
class Model(object):
def __init__(self, batch_size, num_rollouts, entTotal, relTotal, embedding_size, weight_decay, learning_rate):
self.batch_size = batch_size
self.num_rollouts = num_rollouts # neg_size == num_rollouts - 1 when negative sampling
... |
"""
Read esri filegdb and keep original objectid
"""
from arcgis.features import FeatureLayerCollection
import fiona
import geopandas as gpd
import pandas as pd
from tohydamogml.config import COLNAME_OID
from shapely.geometry import Point, LineString
import pyproj
import warnings
def read_featureserver(url, layer_in... |
# Print statements with syntax errors (fixed).
print('Hello, world!')
print('This is a series')
print('of print statements.')
print('The end!')
print("But not really!")
print("Here's another print statement!")
print("And here's another one!")
print("This will be the last one of these initial print statements.")
|
import os
from flask import Flask, render_template, request
import luigi
from luigi.contrib.gcs import GCSTarget, GCSClient
import subprocess
from merge_video import MergeVideoAndAudio
app = Flask(__name__)
@app.route('/')
def hello_world():
target = os.environ.get('TARGET', 'World')
return 'Hello {}!\n'.fo... |
"""
Snake, but multiplayer
Created by sheepy0125
2022-02-21
Client join state code
"""
### Setup ###
from multiplayer_snake.shared.common import pygame, Logger, hisock
from multiplayer_snake.shared.config_parser import parse
from multiplayer_snake.shared.shared_game import SharedGame
from multiplayer_snake.shared.pyg... |
class Clock:
DEFAULT_TIME = '00:00:00'
IS_AM = 0
IS_PM = 1
IS_24H = 2
COUNTDOWN_TIMER = 0
COUNTDOWN_TO_TIME = 1
ELAPSED_TIME = 2
def __init__(self, index, clock_info, client=None):
self.index = index
self._initialize_with_clock_info(
name=clock_info.get('cl... |
import os
import pytest
import mkdocs_jupyter
from mkdocs_jupyter.config import settings
pytestmark = [pytest.mark.pkg]
def test_import():
assert mkdocs_jupyter.__version__ is not None
assert mkdocs_jupyter.__version__ != "0.0.0"
assert len(mkdocs_jupyter.__version__) > 0
def test_assets_included():
... |
class RawArgs:
def __init__(self,
cols_features, col_treatment, col_outcome, col_propensity,
col_cate, col_recommendation, min_propensity, max_propensity,
verbose, uplift_model_params, enable_ipw, propensity_model_params,
index_name, partition_name, runner, conditionally_skip):
... |
import os
import ersa_utils
class BasicProcess(object):
"""
Process block is a basic running module for this repo, it will run the process by checking if function has been
ran before, or be forced to re-run the process again
"""
def __init__(self, name, path, func=None):
"""
:param... |
import asyncio
import datetime
from typing import Dict, Union, List, Any
import pandas as pd
import numpy as np
from math import nan
from .errors import QuikLuaException
class ParamWatcher:
"""
A special class that decides which params have to be updated based on given interval and time passed since last upd... |
import discord
from dotenv import load_dotenv
import logging
import os
from discord.ext import commands
extensions = [
"cogs.clan_battle",
"cogs.help"
]
load_dotenv()
DISCORD_BOT_TOKEN = os.getenv('DISCORD_BOT_TOKEN')
formatter = '%(levelname)s : %(asctime)s : %(message)s'
logging.basicConfig(filename='logs/... |
# Module version
version_info = (0, 6, 0)
# Module version stage suffix map
_specifier_ = {'alpha': 'a', 'beta': 'b', 'candidate': 'rc', 'final': ''}
# Module version accessible using ipyspeck.__version__
__version__ = '%s.%s.%s'%(version_info[0], version_info[1], version_info[2])
|
# DROP TABLES
staging_events_table_drop = "drop table if exists s_songplay_event;"
staging_songs_table_drop = "drop table if exists s_song;"
songplay_table_drop = "drop table if exists f_songplay;"
user_table_drop = "drop table if exists d_user;"
song_table_drop = "drop table if exists d_song;"
artist_table_drop = "dr... |
'''
Created on Sep 6, 2021
@author: mhindle
'''
import numpy as np
import numbers
from typing import Tuple, List, Dict, Union, Set
import itertools
from collections import defaultdict
import pandas as pd
class JointAllellicDistribution(object):
def __init__(self, snp_ordered, chromosome2snp=None, pseudocount = 1... |
import numpy as np
import scipy.stats as stats
import pylab as pl
h = sorted({2.083, 0.315, 1.00e-03, 3.27, 0.929, 2.251,
0.867, 2.727, 0.156, 0.023, 0.081, 6.157, 2.764, 0.586,
1.374, 0.025, 4.015, 0.064, 0.777, 1.783, 0.347, 0.782,
0.391, 3.807, 0.569, 0.344, 0.434, 4.266, 1.031, ... |
import random
import logging
import unittest
from unittest import mock
from talkgenerator.schema import slide_schemas
from talkgenerator import generator
from talkgenerator.slide import powerpoint_slide_creator
from talkgenerator.util import os_util
class TestTalkGenerator(unittest.TestCase):
def setUp(self):
... |
# Copyright (C) 2019 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
""" Model for labels association table."""
from sqlalchemy import orm
from sqlalchemy.orm import validates
from ggrc import db
from ggrc.models import mixins
from ggrc.models import reflection
from ggrc.mo... |
from django.utils.translation import ugettext_lazy as _
HTTP_STATUS_CODES = (
# Infomational
(100, _('Continue')),
(101, _('Switching Protocols')),
(102, _('Processing (WebDAV)')),
# Success
(200, _('OK')),
(201, _('Created')),
(202, _('Accepted')),
(203, _('Non-Authoritative Infor... |
from __main__ import db
#from app import db
class Prospect(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(120), nullable=True)
email = db.Column(db.String(120), nullable=False)
gender = db.Column(db.String(20), nullable=False)
age = db.Column(db.Integer, nullable... |
import unittest
from unittest.mock import Mock
import json
from pathlib import Path
from chris.types import CUBEAddress, CUBEToken
from caw.login.store import AbstractSecretStore, KeyringSecretStore, PlaintextSecretStore, use_keyring
from caw.login.manager import LoginManager
from tempfile import NamedTemporaryFile
... |
# RESPUESTA 1 paso 1
import constante
def gcl(x_n):
m = 232 # modulus
a = 1013904223 # multiplier
c = 1664525 # increment
x = ((a * x_n) + c) % m
return x
x_n = constante.SEMILLA
for _ in range(6):
x_n = gcl(x_n)
print(x_n)
|
import re
from typing import List
class SentenceTokenizer:
PERIOD = "。"
PERIOD_SPECIAL = "__PERIOD__"
PATTERNS = [
re.compile(r"(.*?)"),
re.compile(r"「.*?」"),
]
@staticmethod
def conv_period(item) -> str:
return item.group(0).replace(SentenceTokenizer.PERIOD, Sentenc... |
# SPDX-FileCopyrightText: 2018 Mikey Sklar for Adafruit Industries
#
# SPDX-License-Identifier: MIT
# Mindfulness Bracelet sketch for Adafruit Gemma. Briefly runs
# vibrating motor (connected through transistor) at regular intervals.
import time
import board
from digitalio import DigitalInOut, Direction
# vibrating... |
from torchutils.callbacks.callbacks import * |
# -*- coding: utf-8 -*-
from cadnano.extras.math.vector import normalToPlane, normalizeV3, applyMatrix3, applyMatrix4
from cadnano.extras.math.matrix3 import getNormalMatrix
from cadnano.extras.math.face import Face
class Solid(object):
def __init__(self, name):
self.name = name
self.vertices = ... |
#!/usr/bin/env python
import argparse
import sys
from collections import defaultdict
DEFAULT_OUT = "stackcollapse-merged.txt"
def merge(files, dst):
data = defaultdict(lambda: 0)
for file in files:
with open(file, "r") as fp:
for line in fp.readlines():
stack, hits = lin... |
# 023
# Ask the user to type in the first line of a nursery rhyme and display
# the length of the string. Ask for a starting number and an
# ending number and then display just that section of the text
# (remember Python starts counting from 0 and not 1).
rhyme = list()
while True:
try:
if not rhyme:
... |
from __future__ import division
import math
class RunningMean:
"""Compute running mean.
This class computes running mean.
Recoded from https://www.johndcook.com/blog/skewness_kurtosis/
Example
-------
>>> from RunningMean import RunningMean
>>> s = RunningMean()
>>> s.mean()
0.0
>>> s... |
#! /usr/bin/env python
"""HistToGNU.py
Convert saved binary pickle of histograms to gnu plot output
Usage: %(program)s [options] [histogrampicklefile ...]
reads pickle filename from options if not specified
writes to stdout
"""
globalOptions = """
set grid
set xtics 5
set xrange [0.0:100.0]
"""
dataSetOptio... |
import sys
import harold_packaging_example.util.utils as utils
def main():
for arg in sys.argv[1:]:
print(utils.translate(arg))
if __name__ == '__main__':
main()
|
import base64
import io
from fdk import response
import json
import logging
import oci
from .base import BaseDispatch
from .dispatch import Dispatcher
from .service import SlackService, Agent, Channel
from .text import Text
LOG = logging.getLogger(__name__)
SERVICE = None
TOKEN = None
TEAM = None
NAMESPACE, BUCKET ... |
from django.contrib import admin
from animals.models import Animal, Breed, Pet
class AnimalAdmin(admin.ModelAdmin):
list_display = ('name', 'scientific_name',)
search_fields = ('name', 'scientific_name',)
ordering = ('name',)
class BreedAdmin(admin.ModelAdmin):
list_display = ('name', 'animal',)
... |
# ------------------------------------------------------------------------------
# Copyright 2020 Forschungszentrum Jülich GmbH and Aix-Marseille Université
# "Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements; and to You under the Apache License,
# Version 2.0. "
#
# ... |
class Empleado(object):
puesto = ""
def factory(clase):
if clase == "Maestro":
return Maestro()
elif clase == "Vendedor":
return Vendedor()
elif clase == "Repatidor":
return Repartidor()
class Maestro(Empleado):
puesto = "Maestro"
def mensa... |
#!/usr/bin/env python
import math
import random
import scanpy.api as sc
import numpy as np
from granatum_sdk import Granatum
def main():
gn = Granatum()
adata = gn.ann_data_from_assay(gn.get_import("assay"))
num_cells_to_sample = gn.get_arg("num_cells_to_sample")
random_seed = gn.get_arg("random_se... |
'''
/*******************************************************************************
* Copyright 2016-2019 Exactpro (Exactpro Systems Limited)
*
* 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
... |
from turtle import Screen
from snake import Snake
from food import Food
from scoreboard import Scoreboard
import time
WIDTH = 600
HEIGHT = 600
COLLISION_SEG_SIZE = 15
X_COLLISION = WIDTH/2 - COLLISION_SEG_SIZE
Y_COLLISION = HEIGHT/2 - COLLISION_SEG_SIZE
# Set up game screen:
screen = Screen()
screen.setup(width=WIDT... |
__version__ = '0.9'
from ._vulkan import *
|
import logging
from datetime import datetime, timedelta
from typing import Any, Optional, Union
from privex.helpers.exceptions import CacheNotFound
from privex.helpers.settings import DEFAULT_CACHE_TIMEOUT
from privex.helpers.cache.CacheAdapter import CacheAdapter
log = logging.getLogger(__name__)
class MemoryCache... |
import os
import shutil
FILE_DIR = os.path.dirname(os.path.realpath(__file__))
ROOT_DIR = os.path.abspath(os.path.join(FILE_DIR, ".."))
shutil.rmtree(os.path.join(ROOT_DIR, "build"), ignore_errors = True)
shutil.rmtree(os.path.join(ROOT_DIR, "dist"), ignore_errors = True)
shutil.rmtree(os.path.join(ROOT_DIR, "happy.e... |
import functools
import urllib.parse
import tornado.web
from monstro.forms import forms
from monstro.views import mixins
__all__ = (
'View',
'RedirectView',
'TemplateView',
'ListView',
'DetailView',
'FormView',
'CreateView',
'UpdateView',
'DeleteView'
)
class View(tornado.web.R... |
import os
import pandas as pd
import numpy as np
import glob
def load_abs_data():
"""
Loads the data from the ABSdata.csv file.
"""
# print current directory
df = pd.read_csv('Utilities/DataframeCode/ABSdata.csv')
x = df['X'].values
x = x.reshape(-1, 1)
t = df['T'].values
t = t.re... |
#
# level1_sum.py
# programmers_training
#
# Created by Chanwoo Noh on 2018. 09. 09..
# Copyright © 2018년 Chanwoo Noh. All rights reserved.
#
def solution(a, b):
sum = 0
if a > b :
a,b=b,a
while a <= b :
sum += a
a+=1
return sum
# ... or more simply
# def solution(a, b):
# ... |
from .attribute import *
from .buffer_description import *
from .shader import *
from .shader_program import *
|
@cookery.action('')
def do(subject):
print('in do action with subject:', subject)
return subject
@cookery.action('(.*)')
def echo(subject, text):
return text
@cookery.subject('in', r'(.+)')
def file(path):
print('opening file:', repr(path))
f = open(path, 'r')
return f.read()
|
import unittest
from collections import OrderedDict
from robot.utils import DotDict
from robot.utils.asserts import (assert_equal, assert_false, assert_not_equal,
assert_raises, assert_true)
class TestDotDict(unittest.TestCase):
def setUp(self):
self.dd = DotDict([('z', ... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
# -*- coding: utf-8 -*-
"""Test the compute_current_source_density function.
For each supported file format, implement a test.
"""
# Authors: Alex Rockhill <aprockhill@mailbox.org>
#
# License: BSD (3-clause)
import os.path as op
import numpy as np
import pytest
from numpy.testing import assert_allclose
from scipy.... |
import requests
import re
import json
from bs4 import BeautifulSoup
import ssl
import time
from modules.helper import rnd, write_to_json_file
FID_URL = "https://accounts.ea.com/connect/auth?response_type=code&client_id=ORIGIN_SPA_ID&display=originXWeb/login&locale=en_US&release_type=prod&redirect_uri=https://www.orig... |
import os
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = os.path.realpath('.') + '/my_app/static/uploads'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
app... |
__author__ = 'Rodochenko'
import datetime
class rtsDailyOption:
def __init__(self, strike, opt_type, code, date, value):
self.strike = strike
self.code = code
self.mat_date = self.get_mat_date_from_code(self)
self.opt_type = opt_type
self.date = date
self... |
# coding=utf-8
"""
Cookbook Repository Management
"""
from oslo_log import log as logging
import svn.remote
LOG = logging.getLogger(__name__)
class SVNRepo:
"""
Cookbook Repository Object Model
"""
def __init__(self, url, user="default", pwd="default", ):
"""
Connects to a remote svn... |
#An odd number is an integer which is not a multiple of two
#An even number is an integer which is "evenly divisible" by two
def check_number(number):
if number % 2 != 0:
solution = 'Weird'
elif number % 2 == 0 and number in range(2, 5):
solution = 'Not Wierd'
elif number % 2 == 0 and numb... |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 24 17:11:22 2020
@author: chens
"""
#from os.path import dirname
import numpy as np
import geoist as gi
import geoist.others.fetch_data as data
from geoist.others.fetch_data import _retrieve_file as downloadurl
from geoist.others.fetch_data import usgs_catalog
from geois... |
CONFIG_PATH = "/home/lfhohmann/gcp-weather-and-forecast-scraper/config.yaml"
GOOGLE_DB_TABLE = "google_forecast"
GOOGLE_URL = "https://www.google.com/search?hl=en&lr=lang_en&ie=UTF-8&q=weather"
GOOGLE_HEADER = {
"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0",
"Lang... |
from collections import OrderedDict
import logging
from pyspark.sql.dataframe import DataFrame
from pyspark.sql.session import SparkSession
from typeguard import typechecked
from .logging_utils import _format_sql
from .settings import complete_settings_dict, ComparisonColumn
from .ordered_set import OrderedSet
logge... |
# Simple unit testing for prime servers. Run with -h for details.
#
# Tested with Python 3.6
#
# Eli Bendersky [http://eli.thegreenplace.net]
# This code is in the public domain.
import argparse
import itertools
import logging
import math
import queue
import random
import socket
import subprocess
import sys
import thre... |
#Program - Enter a point that is
#in a sphere of a chosen radius
#and find the magnetic field on it
import math
r= float(input("Radius:"))
ri=int(r)
while r>ri:
ri=ri+1
x= float(input("x-coordinate:"))
while x>r or x<-r:
print ("x-coordinate cannot be larger than radius")
x= float(input("x-coordinate:"))... |
# Easy to use offline chat archive.
#
# Author: Peter Odding <peter@peterodding.com>
# Last Change: August 1, 2018
# URL: https://github.com/xolox/python-chat-archive
"""
Usage: chat-archive [OPTIONS] [COMMAND]
Easy to use offline chat archive that can gather chat message
history from Google Talk, Google Hangouts, Sl... |
import pygame
from time import sleep
from random import randrange
pygame.init()
|
# Copyright (c) 2021 ralabo.jp
# This software is released under the MIT License.
# see https://opensource.org/licenses/mit-license.php
# ====================================================
from common import com, TargetDomain
from flow.flow_item import FlowItem
class FlowDependMachineSection(object):
"""... |
import itertools
import json
import os
import random
import sys
from os.path import isdir, isfile, join, basename
from math import cos, pi, sin, sqrt, acos
from tqdm import tqdm
import multiprocessing
import scipy.io as sio
import numpy as np
import cv2
from cv2 import resize as resize_, imread
from joblib import ... |
"""Unit test for the toppra.dracula.run_topp() wrapper."""
import glob
import os
import unittest
import numpy as np
import toppra.dracula as tdrac
class TestRunTopp(unittest.TestCase):
"""Test RunTopp()."""
# setup test data only once as they aren't modified
glob_regex = os.path.join(
os.path.... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
from _utils import parse, print_stats, URL_DS3
print(URL_DS3)
rows = parse(URL_DS3)
print_stats(rows)
"""
https://darksouls.fandom.com/ru/wiki/Боссы_(Dark_Souls_III)
NAME | HEALTH | SOULS
--------------... |
from django.db import transaction, OperationalError
from django.db.models import F, Q
from django.conf import settings
from django.utils import timezone
from celery import shared_task
import os
import shutil
import string, random
from datetime import timedelta
import oj
from main.judge import run_judge_in_docker, Jud... |
import os
import pickle
import numpy as np
np.random.seed(1000)
from utils.generic_utils import load_dataset_at
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
def load_embedding_matrix(embedding_path, word_index, max_nb_words, embedding_dim, print_error_words=T... |
from setuptools import setup, find_packages
setup(name='kfinny.finnpie',
version='1',
description='A simple library for packaging useful RE functions',
url='https://github.com/kfinny/finnpie',
author='Kevin Finnigin',
author_email='kevin@finnigin.net',
license='MIT',
packages=... |
#
# SPDX-FileCopyrightText: Copyright (c) 1993-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# 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... |
# -*- coding: utf-8 -*-
"""Test that samplers can be executed."""
import unittest
from typing import ClassVar, Type
import numpy
import torch
from pykeen.datasets import Nations
from pykeen.sampling import BasicNegativeSampler, BernoulliNegativeSampler, NegativeSampler
from pykeen.training.schlichtkrull_sampler imp... |
import pytest
def test_merge_call_order(rebase_remotes, mocker):
mocker.patch.object(rebase_remotes, 'git', return_value=1)
rr = rebase_remotes
target_branch = 'test'
rr.merge(target_branch)
calls = [
mocker.call('checkout {}'.format(target_branch), ignore_err=True),
mocker.call('... |
from ..builder import HEADS
from .posenc_cascade_roi_head import PositionalEncodingCascadeRoIHead
from mmdet.core import bbox2roilist
import torch
@HEADS.register_module()
class SpatialRelationCascadeRoIHead(PositionalEncodingCascadeRoIHead):
def _bbox_forward(self, stage, x, rois, n_imgs=1):
"""Box head f... |
# -*- coding: utf-8 -*-
"""
These functions actually aren't really used in the code for now.'
"""
import numpy as np
import scipy
from scipy.stats import truncnorm
from scipy.interpolate import NearestNDInterpolator
from scipy.interpolate.ndgriddata import _ndim_coords_from_arrays
def ltruncnorm(loc, scale, size, r... |
from pokermodules.convenience_hole import add_margins, range_plot, top_hands_pct
from sys import argv
fc2 = 1326
p = float(argv[1])
print "Top", p, 'pct of hands =', fc2 * (p / 100.0), 'hands'
thp = top_hands_pct(p)
t = {'pairs':0, 'suited':0, 'unsuited':0}
mul = {'pairs':6, 'suited':4, 'unsuited':12}
for h in thp:
... |
from pypy.lang.smalltalk import shadow, constants
from pypy.lang.smalltalk import constants
def bootstrap_class(instsize, w_superclass=None, w_metaclass=None,
name='?', format=shadow.POINTERS, varsized=False):
from pypy.lang.smalltalk import model
w_class = model.W_PointersObject(w_metaclas... |
import requests
import pandas as pd
import json
csv_csi = pd.read_csv('1_CSI.dat', skiprows=4,
names=['TIMESTAMP', 'RECORD', 'Temp_Enc', 'Batt_Volt', 'RH_Enc'])
csv_fws = pd.read_csv('1_FWS.dat', skiprows=4,
names=['TIMESTAMP', 'RECORD', 'AirTemp', 'Humidity', 'Baro', 'Lat_... |
from collections import defaultdict
from sys import argv
import pandas as pd
import re
import string
import numpy as np
from sklearn.cluster import DBSCAN
from collections import Counter
script, strain_name = argv
table1_df = pd.read_csv('%s_table1.csv' % strain_name, sep='\t')
table1_df['product'].fillna('None', inp... |
import sys
import os
import argparse
import torch
import logging
import time
from tqdm import tqdm
from image import *
from Models.lightUnetPlusPlus import lightUnetPlusPlus
def predict(model,
threshold,
device,
dataset,
output_paths,
color):
with tqdm(... |
# Beam In Vessel Test
import sys
import numpy as np
import matplotlib.pyplot as plt
import sys
import os
sys.path.append(os.path.join('../'))
from lib.BeamDynamicsTools.Boundary import Boundary
from lib.BeamDynamicsTools.Bfield import Bfield, BfieldTF, BfieldVF
from lib.BeamDynamicsTools.Trajectory import Trajectory
fr... |
# Copyright 2020 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
from enum import Flag, auto
class Context(Flag):
"""
Used to express either the data or program execution context.
"""
BATCH = auto()
STREAMING = auto()
ONLINE = auto()
def __str__(self):
return self.name
__repr__ = __str__
|
class Solution:
def solve(self, nums, k):
if not nums:
return 0
ans = 1
cur_sum = 0
maxes = []
j = -1
for i in range(len(nums)):
while maxes and maxes[0][1] < i:
heappop(maxes)
if j < i:
heappush(m... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import cv2
class Debugger(object):
def __init__(self, down_ratio=4):
self.imgs = {}
colors = [(color_list[_]).astype(np.uint8) \
for _ in range(len(color_list))]
se... |
from hypernets.reader.spectrum import Spectrum
class Spectra(object):
def __init__(self, filename, line=None, plt=None):
self.index = 0
self.offset = 0
self.line = line
self.plt = plt
with open(filename, 'rb') as fd:
self.data = fd.read()
self.update(... |
# -*- coding: utf-8 -*-
import io
import re
import tempfile
import unittest
from collections import OrderedDict
from datetime import datetime, date
from fractions import Fraction
from os.path import getsize
import six
from mock import patch
import cloudinary.utils
from cloudinary import CL_BLANK
from cloudinary.utils... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 1999-2020 Alibaba Group Holding 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-... |
from __future__ import print_function
import math, random
class AsymmetricCrypto:
def __init__(self):
pass
def gcd(self, a, b):
if b==0:
return a
return self.gcd(b,a%b)
def isPrime(self, n):
if n==2:
return True
if n%2==0:
... |
# 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 writing, software
# d... |
from gpiozero import Button
button = Button(2)
button2 = Button(3)
button.wait_for_press()
button2.wait_for_press()
print("Never gonna give you up never gonna let you down never gonna run around and desert you never gonna make you cry never gonna say goodbye never gonna tell a lie and hurt you")
|
# pylint: disable=redefined-outer-name
# pylint: disable=unused-argument
# pylint: disable=unused-variable
import json
from pathlib import Path
from typing import Dict
import pytest
import yaml
from service_integration.osparc_config import MetaConfig, RuntimeConfig
@pytest.fixture
def labels(tests_data_dir: Path, l... |
from django.contrib import admin
from .models import GenericContainerPlugin, CompareTwoThingsPlugin, GenericListPlugin, ImageWithThumbnailPlugin, HostService
#from .models import RenderableTextPlugin, GenericContainerPlugin, CompareTwoThingsPlugin, GenericListPlugin, ImageWithThumbnailPlugin, HostService
admin.site.re... |
import networkx as nx
import ndlib.models.ModelConfig as mc
import ndlib.models.CompositeModel as gc
import ndlib.models.compartments as ns
import time
from ndlib.utils import multi_runs
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
# Network Definition
for initialinfect in [1]:
for i... |
#!/usr/bin/env python
import os
from app import create_app
from flask_script import Manager, Shell, Server
from flask_migrate import Migrate, MigrateCommand
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)
def make_shell_context():
return dict(app=app, db=db, User=User, Role=Rol... |
def evaluate(self):
if self.getMapper().getName() == self.mate._("evaluation:versioned:testee"):
comparison_test = self.mate.getTestByMapperName(self.getName(), self.mate._("evaluation:versioned:base"))
testee_result = self.getRunResults()
comparison_result = comparison_test.getRunResults()
if testee_... |
"""
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
# Write your code here
t = int(input())
for _ in range(t):
n, ... |
import numpy as np
import multiprocessing as mp
import scipy.stats as stats
import os
os.environ['OMP_NUM_THREADS'] = str(1)
import statsmodels.sandbox.stats.multicomp as mc
import h5py
import nibabel as nib
from importlib import reload
import tools
import argparse
# Excluding 084
subjNums = ['013','014','016','017',... |
x = 2
y = 3
z = x + y
print(z)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.