content stringlengths 5 1.05M |
|---|
import os
import numpy as np
import cv2
from matplotlib import pyplot as plt
split = "test"
base_path = f"/home/nicolai/sra/code/clevr-dataset-gen/output/{split}/"
for index in range(1):
fig, ax = plt.subplots(4, 4)
for ii in range(4):
rgb = cv2.imread(
os.path.join(
base_p... |
#!/usr/bin/env python3
"""
Grid of buttons sending MIDI. A minimal touchscreen version of a MIDI Fighter
button controller.
Tested on Raspian python3 pygame 2.0.0 dev6
pip3 install pygame==2.0.0.0.dev6
"""
import sys
import json
import pygame
import pygame.midi
from pygame.locals import *
GridDef = json.load(open("gr... |
'''
Welcome. In this kata, you are asked to square every digit of a number and concatenate them.
For example, if we run 9119 through the function, 811181 will come out, because 9² is 81 and 1² is 1.
Note: The function accepts an integer and returns an integer
'''
def square_digits(num):
num = list(str(num))
... |
from typing import Dict
from typing import List
from typing import Set
from redisolar.dao.base import SiteGeoDaoBase
from redisolar.dao.base import SiteNotFound
from redisolar.dao.redis.base import RedisDaoBase
from redisolar.models import GeoQuery
from redisolar.models import Site
from redisolar.schema import FlatSit... |
"""
--- Ångström ---
Tests calculating molecular center for a trajectory.
"""
from angstrom import Trajectory
from angstrom.geometry import get_molecule_center
import numpy as np
import os
benzene_traj_x = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'benzene-traj-x.xyz')
def test_trajectory_center_of_be... |
from apps.cart.cart import Cart
from django.core.mail import send_mail
from .models import Order, OrderItem
from apps.product.models import Product
def checkout(request, firstname, lastname, email, address, city, state, postal_code, phone, amount, country):
cart = Cart(request)
order = Order.objects.create(f... |
import sys
import re
'''
Applies to one tsv file at a time, output is a txt file of the same name
'''
if len(sys.argv) < 4:
print("Usage: python recurrent_formatting.py input.tsv datatype rnnlm_model")
filename = sys.argv[1]
#outputdest = "recurrent/data/"+sys.argv[2]+"/"
if sys.argv[3] == 'ptb':
vocabfile... |
#!/usr/bin/env python
# coding: utf-8
"""validates discharge from CMF with observations from GRDC"""
import xarray as xr
from os.path import join
import numpy as np
import pandas as pd
from datetime import datetime, timedelta
import calendar
# local
import temp_stats as tstats
import skill_stats as sstats
# funct... |
from ... import ExternalProgramCaller
from ...core.feature_extractor import VmafexecFeatureExtractorMixin, FeatureExtractor
class PsnrhvsFeatureExtractor(VmafexecFeatureExtractorMixin, FeatureExtractor):
TYPE = 'PSNRHVS_feature'
VERSION = "1.0"
ATOM_FEATURES = ['psnr_hvs', 'psnr_hvs_y', 'psnr_hvs_cb', '... |
matriz = [[], [], []]
for i in range(0, 3):
for j in range(0, 3):
matriz[i].append(int(input(f'Digite o valor da posição [{i},{j}] ')))
for i in range(0, 3):
for j in range(0, 3):
print(f'[{matriz[i][j]:5^}]', end=' ')
print()
|
from ipaddress import ip_network, ip_address
from aiodns import DNSResolver
from asyncio import wait_for
from typing import Union
__all__ = ['is_ip', 'is_network', 'hostname_resolver']
async def hostname_resolver(hostname: str, resolver_timeout: int) -> Union[str, None]:
"""
Resolve fqdn, hostname -> ip addre... |
import argparse
from pprint import pprint
from train.classification import Classification
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--action', default='train', choices=['train', 'eval', 'fine-tune'],
help='classification experiments (default: ... |
essentials = ['water', 'iphone', 'food', 'shelter']
essentials.remove('iphone')
print(essentials)
|
"""Nexia Themostat."""
import logging
from .const import (
AIR_CLEANER_MODES,
HUMIDITY_MAX,
HUMIDITY_MIN,
SYSTEM_STATUS_IDLE,
SYSTEM_STATUS_WAIT,
)
from .util import find_dict_with_keyvalue_in_json, is_number
from .zone import NexiaThermostatZone
_LOGGER = logging.getLogger(__name__)
class Nexi... |
import pytest
import torch
from bgflow import (
make_conditioners, ShapeDictionary,
BONDS, FIXED, ANGLES, TORSIONS,
ConditionalSplineTransformer, AffineTransformer,
)
@pytest.mark.parametrize(
"transformer_type",
[
ConditionalSplineTransformer,
AffineTransformer,
# TODO: M... |
import datetime
import math
import pandas as pd
import re
#region Lipid subclass information
fatty_aclys = ['FA', 'NAGly', 'NAGlySer', 'NAOrn', 'NAE', 'CAR', 'FAHFA']
glycerolipids = ['DG', 'EtherDG', 'DGDG', 'EtherDGDG', 'MGDG', 'EtherMGDG',
'SQDG', 'EtherSMGDG' 'MG', 'ADGGA', 'DGCC', 'DGGA', 'DGTS... |
import logging
import sys
from flask_restful import Resource, marshal_with
from analyser.common.measurementcontroller import measurementFields
logger = logging.getLogger('analyser.measurements')
class Measurements(Resource):
def __init__(self, **kwargs):
self._measurementController = kwargs['measuremen... |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
print ("Import Successful")
model_conv = torchvision.models.inception_v3()
print ("Model created")
print (model_conv)
|
import pandas as pd
import random
import numpy as np
import torch
from torch.utils.data import IterableDataset, Dataset, DataLoader
from keras.preprocessing.sequence import pad_sequences
import math
class Base_Batchfier(IterableDataset):
def __init__(self, batch_size: int = 32, seq_len=512, minlen=50, maxlen: int ... |
__project__ = "IndependentTwitchDownloader"
__version__ = "0.1.0"
|
''' unit test for Ansible module: na_elementsw_node.py '''
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import json
import pytest
from ansible.module_utils import basic
from ansible.module_utils._text import to_bytes
from ansible_collections.netapp.elementsw.tests.unit.compat... |
from setuptools import setup
from setuptools import find_packages
package_name = 'ros2_adafruit_pwmhat_node'
setup(
name = package_name,
description = 'ROS2 Node for Adafruit Raspberry Pi 3 PWM 16-channel HAT',
keywords = [
'ROS2'
],
license = 'Apache License,... |
"""
AddDiscoveryReqeustForm.py - Add a discovery request to a discovery document.
Copyright (c) 2019 by Thomas J. Daley. All Rights Reserved.
"""
from wtforms import Form, StringField, TextAreaField, validators
class AddDiscoveryRequstItemForm(Form):
# number = StringField("Request number", [validators.required]... |
#!/usr/bin/env python3
# FreeRTOS Common IO V0.1.2
# Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# 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 res... |
import numpy as np
#NOTE be careful when using the Beam2D with the Truss2D because currently the
# Truss2D is derived with only 2 DOFs per node, while the Beam2D is defined
# with 3 DOFs per node
DOF = 3
class Beam2D(object):
__slots__ = ['n1', 'n2', 'E', 'rho', 'Izz1', 'Izz2', 'A1', 'A2',
'in... |
# Generated by Django 2.1.1 on 2018-10-04 10:56
from django.db import migrations, models
import django.utils.timezone
import model_utils.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Comment',
... |
# coding: utf-8
"""
Author: Soonyen Ju
Date: May 29th, 2018
Contact: soonyenju@foxmail.com
Description:
This code is designed for MLS auxillary files download and pack
"""
import re, os, tarfile
from ftplib import FTP
from datetime import *
def main():
print("testing...")
savepath = "E:/AIUS"
runTask(savepath, hour... |
temp= float(input('Informe a temperatura em ºC: '))
print(f'A temperatura de {temp}ºC corresponde a {temp*9/5+32:.2f}ºF') #aqui não é necessário parenteses devido a ordem
procedencia. |
# Copyright 2021 Microsoft Corporation
#
# 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... |
# Copyright 2010 Google Inc.
#
# 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, publish, dis-
# trib... |
def test_no_route_to_energy_meter_import_if_not_logged_in(browser):
browser.open('http://localhost/navigation')
assert 'energy_meter_import' not in str(browser.json['data'])
def test_route_to_access_authority_if_logged_in_as_admin(browser):
browser.login()
browser.open('http://localhost/navigation')... |
# classes for bayesian optimization (min)
# import relevant packages
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import RBF, ConstantKernel as C, WhiteKernel, Matern
from sklearn.metrics ... |
class Solution:
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
result = ''
while n:
result = chr(65 + (n - 1) % 26) + result
n = (n -1) // 26
return result
|
"""
Tests for the Music Player .csv file reader
"""
from pathlib import Path
import unittest
from player_tech_assignment.csv_reader import MusicPlayerCsvReader, MusicPlayerCsvReaderError
WORKING_DIR = Path.cwd()
TEST_DATA_DIR = WORKING_DIR / "tests" / "test_data"
TEST_CSV_FILE = TEST_DATA_DIR / "test_local_data.csv"
... |
import numpy as np
from src.si.util.scale import StandardScaler
import pandas as pd
class PCA:
def __init__(self, num_components=2, using="svd"):
self.numcomps = num_components
self.alg = using
def transform(self, dataset): # objeto Dataset
scaler = StandardScaler()
x_scaled =... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
from functools import wraps
from typing import Callable
from ....lib.patterns import formats
from ...encoding.ps1str import ps1str
def dq_unescape(string):
def unescape(match):
char = match[0]
return ps1str.UNESCAPE.get(char,... |
import unittest
from httpx import AsyncClient
import asyncio
class TestCanvasCourse(unittest.TestCase):
def setUp(self) -> None:
# self.client = AsyncClient()
pass
# def test_client_type(self):
# self.assertEqual(type(self.client), AsyncClient)
|
# coding: utf-8
import sys
import os
import json
import webbrowser
from collections import defaultdict
import sublime_plugin
import sublime
PY2 = sys.version_info < (3, 0)
try:
from .floo import sublime_ui
from .floo.common import api, reactor, msg, shared as G, utils
from .floo.common.exc_fmt import str... |
# ===============================================================================
# Copyright 2015 Jake 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... |
from reference import *
import reference
import hashlib
SECP256K1_ORDER = reference.n
def ckb_tagged_hash(tag: str, msg: bytes) -> bytes:
def blake2b(m):
return hashlib.blake2b(m, digest_size=32, person="ckb_default_hash".encode()).digest()
tag_hash = blake2b(tag.encode())
return blake2b(tag_hash... |
import random
from itertools import count
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# plt.style.use('fivethirtyeight')
x_values = []
y_values = []
index = count()
def animate(i):
x_values.append(next(index))
y_values.append(random.randint(0, 5))
plt.cla()
plt.pl... |
from typing import Union, List, Generator
import torch
from numpy import ndarray
from plus.config import ModelConfig, RunConfig
from plus.data.alphabets import Protein
from plus.data.dataset import Embedding_dataset, collate_sequences_for_embedding
from plus.model.plus_rnn import PLUS_RNN, get_embedding
from plus.trai... |
from copy import copy
from copy import deepcopy
from tqdm import tqdm
import yaml
import logger
from envs.toy_pokers import Node, KuhnPoker
def update_pi(node: Node, strategy_profile: dict, average_strategy_profile: dict, pi_mi_list: list, pi_i_list: list, true_pi_mi_list: list):
node.pi = pi_mi_list[node.playe... |
from discord import Embed
def parse_list(raw):
if raw.startswith("(("):
return raw[2:-2].split("),(")
return raw[1:-1].split(",")
def parse_recipe_item(raw):
components = raw.split(",")
component_map = {}
for component in components:
key_value = component.split("=")
compo... |
from typing import Optional
from arclet.alconna import AlconnaString, AlconnaFormat, AlconnaFire, AlconnaDecorate, delegate, Args
def test_koishi_like():
con = AlconnaString("con <url:url>")
assert con.parse("con https://www.example.com").matched is True
con_1 = AlconnaString("con_1", "--foo <foo:str:123... |
import argparse
import os
import os.path
import platform
import sys
import time
import traceback
import msg
import url
from config import Config
from linker import Linker
from website import Website
def parse_cli_args():
args_parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHel... |
'''
file overlap
Given two .txt files that have lists of numbers in them, find the numbers that are overlapping. One .txt file has a list of all prime numbers under 1000, and the other .txt file has a list of happy numbers up to 1000.
(If you forgot, prime numbers are numbers that can’t be divided by any other numbe... |
"""
base_lines.py - microscopy images class
update: 20191001 - modify gaussian fit function
"""
import os
import sys
from tqdm import tqdm_notebook
import numpy as np
import math
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import pandas as pd
from scipy.signal import argrelmax
# local librar... |
from django.test import TestCase
class CoreAppTest(TestCase):
"""Test for the Core App"""
def test_create_user(self):
print("dummy test")
|
import csv
import gzip
from argparse import Namespace
import pytest
from piicatcher.explorer.databases import PostgreSQLExplorer
from tests.test_databases import pg_conn
@pytest.fixture
def load_sample_data_2():
connection = pg_conn()[1]
create_table = """
CREATE TABLE SAMPLE_2(
ID VARCH... |
import PySimpleGUI as sg
import os
from typing import List
def tag(tags, cats, folder):
"""Yes, this is the function that displays the tag dialog box."""
results = []
if type(tags) is str:
tag_list = sorted([item.strip() for item in tags.split(",")])
else:
tag_list = tags
layout =... |
# Copyright 2015: Mirantis Inc.
# All Rights Reserved.
#
# 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 b... |
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
# Licensed under the Apache License, Version 2.0 https://aws.amazon.com/apache-2-0/
import boto3
import logging
import traceback
from utils.task_queue_common import TaskQueueException
from utils import gri... |
"""
Should test the connection to see if it is connected.
"""
from rhobot.components.commands.base_command import BaseCommand
class TestConnection(BaseCommand):
name = 'test_connection'
description = 'Test Connection'
dependencies = BaseCommand.default_dependencies.union({'neo4j_wrapper'})
def post_... |
# Part of measurement-kit <https://measurement-kit.github.io/>.
# Measurement-kit is free software. See AUTHORS and LICENSE for more
# information on the copying conditions.
""" Running WebConnectivity using the tx.py submodule """
from __future__ import print_function
from pprint import pprint
from measurement_kit... |
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 26 21:43:42 2019
@author: Preeti Sajjan
"""
import os
import sys
import Utils.common_utilities as utils
os.chdir("..")
os.chdir("data")
file = sys.argv[1]
train_input,train_output,test_input,test_output = utils.json_reader(file)
def solve(inputData):
array = inputD... |
import requests
import pandas as pd
from bs4 import BeautifulSoup
postcodeList = ['SE1 9SG', 'SW1A 0AA', 'G62 1ER', 'S11 8EQ', "gibberish", 'L4 0TH']
def Sainsburys_scraper(postcodeList):
'''Simple PUT request into Sainsburys API with the postcode as the payload, parses to BS4 then returns the result'''
da... |
import os
import openpyxl
from multiplication_table import multiplication_table
def test_generate_multiplication_table():
file = 'test_multiplication.xlsx'
multiplication_table.generate_multiplication_table(n=15, filename=file)
wb = openpyxl.load_workbook('test_multiplication.xlsx')
sheet = wb.acti... |
import ctypes
import pytest
c_lib = ctypes.CDLL('../solutions/0035-search-insert/search-insert.so')
@pytest.mark.parametrize('array, target, ans',
[([1,3,5,6], 5, 2),
([1,3,5,6], 2, 1),
([1,3,5,6], 7, 4),
([1,3,5,6], 0,... |
""" Problem 26:
ind the value of d < 1000 for which 1/d
contains the longest recurring cycle in its decimal fraction part. """
import itertools
def main():
l = 0
m = 0
for i in range(1, 1000, 1):
arr = {}
x = 1
pos = 0
while (x not in arr):
arr[x] = pos
... |
from typing import Optional
from deli.kubernetes.resources.const import VM_ID_LABEL
from deli.kubernetes.resources.v1alpha1.instance.model import Instance
from deli.kubernetes.resources.v1alpha1.network.model import Network
from deli.menu.metadata.vm_client import SandwichVMClient
from vmw_cloudinit_metadata.drivers.d... |
import json
from unittest.mock import patch
def test_github_webhook_endpoint(telegram_flask_bot, flask_client):
data = {
"action": "opened",
"pull_request": {
"html_url": "https://github.com/PythonistasBR/bot/pull/43",
"title": "Flask backend",
"user": {"login":... |
from ta.trend import *
from ta.volatility import *
from ta.momentum import ROCIndicator
from ta.momentum import RSIIndicator
from ta.momentum import WilliamsRIndicator
from ta.volatility import BollingerBands
from ta.volume import MFIIndicator
from ta.volume import ChaikinMoneyFlowIndicator
from ta.trend import WMAInd... |
#-*- coding:utf-8 -*-
from command import CheckCommand
from speech import MakeAudio, SpeechToText
from os import remove
from os.path import isfile
from keyboard import read_hotkey
if __name__ == "__main__":
print("음성인식을 하려면 Ctrl+Shift 를 눌러주세요.")
while True:
try:
rk = read_hotkey(suppress... |
from typing import TYPE_CHECKING, Optional
from uuid import UUID
from lakefs_client.models import CredentialsWithSecret
from sqlalchemy.schema import Column, ForeignKey
from sqlmodel import Field, Relationship, UniqueConstraint
from sqlmodel.sql.sqltypes import GUID
from starlette.concurrency import run_in_threadpool
... |
# SnakeClass.py
import pygame
import constants
from Position import Position
from Food import Food
class Snake():
#constructor
def __init__(self, initial_cell):
#check for valid parameters
if not isinstance(initial_cell, tuple):
raise TypeError("Argument initial_cell must be type... |
"""
_generic.py
I feel like I'm rewriting a lot of the same code- so let's define a master
class holding all the stuff we want to reuse between feature extractors.
"""
import os
import yaml
import numpy as np
import tensorflow as tf
from tqdm import tqdm
from sklearn.svm import LinearSVC
from sklearn.pr... |
"""
A dialect module for PostgreSQL.
"""
import re
from decimal import Decimal
from datetime import date, datetime, time, timedelta
from uuid import UUID
from itertools import groupby
from typing import *
from pyracmon.model import Table, Column, ForeignKey, Relations
from pyracmon.dialect.shared import Multi... |
def tax(taxable_income):
if taxable_income <= 250000:
return 0
elif taxable_income <= 500000:
return (taxable_income - 250000)*0.05
elif taxable_income <= 1000000:
return 12500 + (taxable_income - 500000)*0.2
else:
return 112500 + (taxable_income - 1000000)*0.3
def my_d... |
# -*- coding: utf-8 -*-
import pytest
import sys
import time
from collections import OrderedDict
from data_feeder_plugins.resilientfeed.resilientfeed import ResilientFeedDestination
from data_feeder_plugins.resilientfeed.resilient_common import Resilient
from rc_data_feed.lib.type_info import ActionMessageTypeInfo
TY... |
"""Utility functions for testing purpose with ``djangoes``."""
def setup_djangoes():
"""Setup ElasticSearch connections with ``djangoes`` for testing purpose.
When testing with ElasticSearch, used indices must not be the same as
the one used for live settings, ie. tests must use the TEST settings.
Th... |
from .data_funcs import *
from .gp_samples import *
|
import bisect
from collections import defaultdict
from kronos.conf.constants import ResultOrder
from kronos.core import marshal
from kronos.storage.base import BaseStorage
from kronos.utils.uuid import uuid_from_kronos_time
from kronos.utils.uuid import UUIDType
from kronos.utils.validate import is_pos_int
class Ev... |
# Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# Author: Kiall Mac Innes <kiall@hp.com>
#
# 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/L... |
dividendo=int(input("Ingresar dividendo: "))
divisor=int(input("Ingresar divisor: "))
if dividendo>0 and divisor>0:
cociente=0
residuo=dividendo
while(residuo>=divisor):
residuo-=divisor
cociente+=1
print(residuo)
print(cociente)
|
'''
A Salt runner module to mirror and aggregate the Salt execution module of the
same name
'''
# Import Python libs
import itertools
# Import salt libs
import salt.client
import salt.output
def __virtual__():
'''
Rename to sys
'''
return 'sys'
def doc():
'''
Collect all the sys.doc output ... |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 12 15:34:54 2021
Objective: test module for swap numbers in list
@author: Ashish
"""
import expr_swap_list_nums
def test_add_nums():
assert expr_swap_list_nums.add_nums(5) == 7
|
# a hot-recharge auth config class
from .HotRechargeException import ReferenceExceedLimit
class HRAuthConfig:
"""
a hot-recharge auth credentials config
`access_code`: account email as used on registration
`access_password`: account password as used on reg
`reference` (optional): any random char... |
import numpy as np
import matplotlib.pyplot as plt
##Log Probability MSE and MSE Train and test using particle gibbs
plt.figure(1)
plt.subplot(211)
N = 4
train_set = (19.956, 7.5 ,1.9,12.663 )
test_set = (22.084,7.9 , 1.9 ,11.719)
trainStd = (1, 1,1,1)
testStd = (1, 1,1,1)
ind = np.arange(N) # the x locations for t... |
import sqlite3
conn = sqlite3.connect("music.db")
#conn.row_factory = sqlite3.Row
cursor = conn.cursor()
sql = "SELECT * FROM albums WHERE artis=?"
cursor.execute(sql, [("Red")])
print cursor.fetchall() # or use fetchone()
print "\nHere's a listing of all the records in the table:\n"
for row in cursor... |
class PlayerDataException(Exception):
"""Handles PlayerData Exceptions"""
class PlayerData:
"""Handles Player Data requests"""
def __init__(self, season, player):
self.profile_data = self._get_profile(season, player)
self.match_data = self._get_match_data(season)
self.projected_da... |
print('Task 3 (like a chat-bot)')
while True:
print("========If you wonna quit, press 'x' for exit=========")
phrase = input("message: ")
if phrase == "x":
break
elif phrase == "Hello" or phrase == "Hi" or phrase == "qq":
print("Hello , how are you ?")
elif phrase == "fine thanks" o... |
myname = "JJ" #added value to a variable
myage = 16.10 #added value to a variable
myheightmete = 1.79 #added value to a variable
onesidesquare = 5 #added value to a variable
lengthrect = 40 #added value to a variable
heightrect = 12 #added value to a variable
ageinmon = myage*12 #executed simple mathematical function a... |
def split_compound_name(compoundname):
try:
namespace, name = compoundname.rsplit('::', 1)
except ValueError:
namespace, name = '', compoundname
return namespace, name
def return_list(func):
def wrapper(*args, **kwargs):
return list(func(*args, **kwargs))
return ... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
'''
/**
* This is the solution of No.236 problem in the LeetCode,
* the website of the problem is as follow:
* https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree
* <p>
* The description of problem is as follow:
* ===============================================================================... |
import os
from models import jobs
from models import apps
from models import deployments
from models import job_enqueueings
from models import webhooks, webhook_invocations
from botosts.aws_connection import AWSConnection
from ghost_tools import config, CURRENT_REVISION_NAME
# required. See http://swagger.io/specific... |
import itertools
import os
import pickle
import shutil
import numpy as np
import torch
from megatron import get_args
from megatron import mpu
def detach(tensor):
return tensor.detach().cpu().numpy()
class OpenRetreivalDataStore(object):
"""
Serializable data structure for holding data for blocks --
... |
import os
from celery import Celery
from flask import Flask
from flask_assets import Environment
from flask_compress import Compress
from flask_login import LoginManager
from flask_mail import Mail
from flask_rq import RQ
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import CSRFProtect
from config import confi... |
#!env/bin/python
import argparse
import pickle
import sys
import os
from attrdict import AttrDict #type:ignore
from typing import Any, Callable, Dict, Iterable, Iterator, List
sys.path.append(os.path.dirname(__file__) + '/../route_planner')
def main():
argp = argparse.ArgumentParser(description='Route binary v... |
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Rapidjson(CMakePackage):
"""A fast JSON parser/generator for C++ with both SAX/DOM style A... |
#!/usr/bin/env python3
"""
Author : donaldscoon
Date : 2019-04-11
Purpose: I actually prefer SPAM over Hamm
"""
import argparse
import sys
import os
import re
import logging
# --------------------------------------------------
def get_args():
"""get command-line arguments"""
parser = argparse.ArgumentParse... |
def verifica_primos(num):
#Esta função verifica se há números primos até o número digitado
#Variáveis de controle
aux2 = num
aux3 = 0
if aux2 >= 3:
#Caso o número digitado seja maior que 3, é impresso os dois primeiros números primos que existem de 0 a 100
print(2, 3, end=' ') ... |
# Copyright 2018 TNG Technology Consulting GmbH, Unterfoehring, Germany
# Licensed under the Apache License, Version 2.0 - see LICENSE.md in project root directory
# TODO IT-1: give this function some great functionality
def great_function():
pass
# TODO: give this function some greater functionality
def greate... |
from django.conf.urls import url
from .views import User_register
urlpatterns = [
url(r'^register', User_register),
]
|
"""
Server plugin services
This plugin module can define user-created services for the Server to
start.
This module must handle all imports and setups required to start a
twisted service (see examples in evennia.server.server). It must also
contain a function start_plugin_services(application). Evennia will
call thi... |
"""
Main script for models
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import torch.nn as nn
import torch.optim as optim
import numpy as np
from models import models
from train import test, train, params
from util import utils
from sklearn.manifold import TSNE
import argpars... |
import unittest
import numpy as np
from mtrack.graphs import G1
from mtrack.evaluation.voxel_skeleton import VoxelSkeleton
from mtrack.preprocessing import g1_to_nml
import pdb
class VoxelSkeletonBaseCase(unittest.TestCase):
def setUp(self):
self.vertices = 20
self.g1 = G1(self.vertices)
... |
import numpy as np
import torch
import os
import matplotlib.pyplot as plt
from PIL import Image
import cv2
import imageio
from tqdm import tqdm
def weights_init_normal(layer, mean = 0.0, std = 0.02):
layer_name = layer.__class__.__name__
if layer_name in ['Conv2d', 'Linear']:
layer.weight.data.normal_(... |
#!/usr/bin/env python
import subprocess
import sys
import os
from glob import glob
from ififuncs import diff_textfiles
import datetime
import time
import csv
import uuid
import lxml.etree as ET
from ififuncs import create_csv
from ififuncs import append_csv
from ififuncs import send_gmail
from ififuncs import hashlib_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.