content stringlengths 5 1.05M |
|---|
from werkzeug.contrib.cache import NullCache
from app import cache, settings
from tests.integration.integration_test_case import IntegrationTestCase
class TestApplicationVariables(IntegrationTestCase):
def setUp(self):
settings.EQ_ENABLE_CACHE = False
IntegrationTestCase.setUp(self)
def tea... |
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
"""Unit tests for the JMeter CSV tests collector."""
from .base import JMeterCSVTestCase
class JMeterCSVTestsTest(JMeterCSVTestCase):
"""Unit tests for the JMeter CSV tests collector."""
METRIC_TYPE = "tests"
async def test_no_transactions(self):
"""Test that the number of tests is 0 if there a... |
# -*- coding: utf-8 -*-
#################################################################################
# Author : Webkul Software Pvt. Ltd. (<https://webkul.com/>)
# Copyright(c): 2015-Present Webkul Software Pvt. Ltd.
# License URL : https://store.webkul.com/license.html/
# All Rights Reserved.
#
#
#
# This pr... |
'''
1) ๋ธ๋ฃจ์ค ํฌํธ๋ก ํ๋ฉด O(n*n)
2) 2 ํฌ์ธํฐ๋ก ํ์ดํ ์ ์์ ๋ฏ?
'''
from typing import List
class SolutionTwoPointer:
def maxArea(self, height: List[int]) -> int:
left = 0
right = len(height) - 1
max_volume = 0
while left < right:
max_volume = max(min(height[left], height[right]) * (ri... |
import matplotlib
matplotlib.use('Agg')
import datetime
import os
import random
import time
import gc
import numpy as np
from PIL import Image
from skimage import io as skio
import torch
import torchvision.transforms as standard_transforms
import torchvision.utils as vutils
from torch import optim
from torch.autogra... |
#!/usr/bin/env python
from __future__ import print_function
"""
Process a FireEye alerts API export csv and convert each row to an incident report and submitting to TruSTAR:
"""
import json
import sys
import time
import pandas as pd
from trustar import TruStar, Report
# Set to false to submit to community
do_encl... |
from tkinter import *
# ๅฏผๅ
ฅttk
from tkinter import ttk
from tkinter import colorchooser
import math
class App:
def __init__(self, master):
self.master = master
# ไฟๅญ่ฎพ็ฝฎๅๅง็่พนๆกๅฎฝๅบฆ
self.width = IntVar()
self.width.set(1)
# ไฟๅญ่ฎพ็ฝฎๅๅง็่พนๆก้ข่ฒ
self.outline = 'black'
# ไฟๅญ่ฎพ็ฝฎๅๅง... |
"""
Start Project Cars, run python standing.py while doing a race.
"""
import carseour
import time
game = carseour.live()
while True:
for player in game.standing():
print(str(player['position']) + '. ' + player['name'] + ' (' + str(player['lap']) + "/" +
str(game.mLapsInEvent) + ') (' + str... |
import numpy as np
nan = np.nan
index_to_label = [
12,
-1,
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
-1,
-1,
11,
]
index_to_label = np.array(index_to_label, dtype='int32')
def index_t... |
n = int(input().rstrip())
def fib(count):
if count == 0 or count == 1:
return 1
else:
return fib(count - 1) + fib(count - 2)
result = [1, 1] + [None]*(n-1)
def fibByMemo(count):
global result
if count == 0 or count == 1:
return result[count]
if result[count] != None:
... |
# coding=utf-8
from __future__ import absolute_import, division, print_function, \
unicode_literals
import filters as f
from iota.commands import FilterCommand, RequestFilter
from iota.filters import AddressNoChecksum
__all__ = [
'WereAddressesSpentFromCommand',
]
class WereAddressesSpentFromCommand(FilterComm... |
temprature = int(input('Temprature: '))
if temprature < 20:
print("Khonake!")
elif temprature == 20:
print("Mizuneh!")
else:
print("Garme!")
|
import torch
from torch import nn
import torch.nn.functional as F
from models.core_layers import SpectralNorm, ConditionalBatchNorm2d
from models.basic_module import init_xavier_uniform
## Generator ResBlockใฎPost Activation version(original = pre-act)
class GeneratorResidualBlockPostAct(nn.Module):
def __init__(se... |
import itertools
import math
from typing import Callable, Optional, Sequence
import numpy as np
import dp_variance
def naive_k_min_variance_subset(k: int, sample: Sequence[float]) -> np.ndarray:
canditate, var = None, math.inf
for k_subset in itertools.combinations(sample, k):
_k_subset = np.array(k... |
# list(map(int, input().split()))
# int(input())
def main():
N, K = list(map(int, input().split()))
P = list(map(int, input().split()))
P.sort()
print(sum(P[:K]))
if __name__ == '__main__':
main()
|
# Generated by Django 3.1.6 on 2021-02-19 13:36
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('CyberUser', '0004_auto_20210219_1930'),
]
operations = [
migrations.RemoveField(
model_name='news',
name='comments',
... |
from django import forms
from django.contrib.auth import login as auth_login
from django.contrib.auth.hashers import make_password
from django.core.exceptions import ValidationError
from django.forms.utils import ErrorList
from django.http import HttpResponseRedirect
from django.views.generic.base import RedirectView
f... |
#!/usr/bin/python
#coding: utf-8
__AUTHOR__ = "Fnkoc"
__LICENSE__= "MIT"
"""
MIT License
Copyright (c) 2017 Franco Colombino
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,... |
from reader import read_data
b = 2 ** 2 * 3 ** 2 * 5 ** 2 * 7 ** 2 * 13
ulamki = read_data()
# ulamki = [("1", "2"), ("2", "3"), ("5", "3"), ("2", "4"), ("15", "5")]
suma_ulamkow = 0
for ulamek in ulamki:
licznik = int(ulamek[0])
mianownik = int(ulamek[1])
nowy_ulamek = (licznik * b) / mianownik
suma... |
# import torch
import numpy as np
import os
import pandas as pd
from sklearn.model_selection import train_test_split
os.chdir("/home/vglasov/Reseach/LU-Net-pytorch/")
import config
from tools import preprocess #custom class
from tools import dataloader_tools as data_loader
import open3d as o3d
import torch
from tor... |
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 24 10:08:00 2022
@author: D.Albert-Weiss
inspired by https://lbolla.info/pipelines-in-python.html
"""
from contextlib import contextmanager
class StopPipeline(Exception):
pass
@contextmanager
def close_on_exit(n):
try:
yield
except Generat... |
import argparse
from ssd_project.functions.detection import *
from ssd_project.functions.multiboxloss import *
from ssd_project.model.ssd import *
from ssd_project.utils.global_variables import *
from ssd_project.utils.helpers import *
from ssd_project.utils.transformations import *
from ssd_project.utils.utils import ... |
from .modules import *
from . import utils
__version__ = 1.2 |
import sqlite3
import traceback
#
# class consumator / consumer to send in background process.
#
class SqliteProcess:
def __init__(self):
self._error = False
self.errorException = None
self.conn = sqlite3.connect('process.db')
self._createtable()
##############################... |
from touchio import TouchIn
from digitalio import DigitalInOut
from audioio import WaveFile, AudioOut
import board
def enable_speakers():
speaker_control = DigitalInOut(board.SPEAKER_ENABLE)
speaker_control.switch_to_output(value=True)
def play_file(speaker, path):
file = open(path, "rb")
audio = Wa... |
#!/usr/bin/env python
# coding:utf-8
from django.db import models
class Resume(models.Model):
company = models.CharField(u'ๅ
ฌๅธ', max_length=200, help_text='ๅฐฑ่ๅ
ฌๅธ')
position = models.CharField(u'่ไฝ', max_length=200)
entry_time = models.DateField(u'ๅ
ฅ่ๆถ้ด')
time_of_separation = models.DateField(u'็ฆป่ๆถ้ด', nu... |
class Numbers:
MULTIPLIER = 3.5
def __init__(self, x, y):
self.x = x
self.y = y
def add(self):
return self.x + self.y
@classmethod
def multiply(cls, a):
return cls.MULTIPLIER * a
@staticmethod
def substract(b, c):
return b - c
@property
de... |
import sys
import logging
from functools import partial
from threading import Thread
from flask import Flask
from .settings import Configuration
from .worker import async_worker
from .automata import automata
from . import providers
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger("webhooks")
app... |
"""
Copyright (c) 2018, Salesforce.com, 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 list of conditions and the foll... |
import numpy as np
from unittest import TestCase
from cmaes.cma import _decompress_symmetric, _compress_symmetric
class TestCompressSymmetric(TestCase):
def test_compress_symmetric_odd(self):
sym2d = np.array([[1, 2], [2, 3]])
actual = _compress_symmetric(sym2d)
expected = np.array([1, 2, ... |
from password_manager.encryption.key_generator import KeyGenerator
def test_generate():
generator = KeyGenerator("password")
key, metadata = generator.generate()
assert len(key) == 32
assert metadata.iterations == 1000_000
assert metadata.hmac == 'SHA512'
|
"""
Functions for reading and writing files
"""
from pathlib import Path
import time
import numpy as np
import pandas as pd
def load_array(files):
"""Create a 3D numpy array from a list
of ascii files containing 2D arrays.
Parameters
----------
files : sequence
List of text files. Array l... |
#! /usr/bin/env python
import os, subprocess, shutil, random, optparse
comp = {
'bz2': 'cjf',
'xz' : 'cJf',
'gz' : 'czf',
}
def read_wafdir():
try:
os.listdir('waflib')
except:
raise ImportError('please provide a waflib directory in the current folder')
d = 'waflib'
lst = [d + os.sep + x for x in os.list... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('forum', '0004_auto_20160530_0354'),
]
operations = [
migrations.AlterField(
model_name='forumpost',
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/12/18 12:50
# @Author : Eiya_ming
# @Email : eiyaming@163.com
# @File : v10_serial.py
import serial #ๅฏผๅ
ฅๆจกๅ
import serial.tools.list_ports
port_list = list(serial.tools.list_ports.comports())
print(port_list)
if len(port_list) == 0:
print('ๆ ๅฏ็จไธฒๅฃ')... |
#####################################
# Developed for studies #
# Developed by: Lyon kevin #
#####################################
import socket
#sock
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#Control not to generate DOS
som = 0
while True:
#Send only one message
if so... |
x = "your"
y = "mom"
print(x + y) |
import json
from collections import OrderedDict
from .helpers import to_b64
class DictToBase64Normaliser():
def __init__(self, dictionary):
self.__dictionary = dictionary
def normalise(self):
"""
Normalise a python dictionary, encode it as JSON return it base64
encoded.
... |
# Copyright 2014 CERN.
#
# 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 wr... |
import logging
import os
log_format = "%(asctime)s: %(filename)s %(funcName)s :%(lineno)s => %(message)s"
logging.basicConfig(level=logging.DEBUG, format=log_format)
log = logging.getLogger("http_server")
if not os.path.exists("logs"):
os.makedirs("logs")
file_handler = logging.FileHandler(f"logs/httpserver.log... |
from abc import ABCMeta, abstractmethod
class Detector:
"""
This class is an abstract class for general error detection,
it requires for every sub-class to implement the
get_clean_cells and get_noisy_cells method
"""
__metaclass__ = ABCMeta
def __init__(self, name):
"""
C... |
# Generated by Django 3.2.4 on 2021-08-27 14:05
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('doublecount', '0002_auto_20210824_1438'),
]
operations = [
migrations.AlterField(
model_name='d... |
import subprocess
import sys
import os
import setup_util
def start(args, logfile, errfile):
setup_util.replace_text("cpoll_cppsp/www/connectioninfo.H", "\\#define BENCHMARK_DB_HOST \".*\"", "#define BENCHMARK_DB_HOST \"" + args.database_host + "\"")
subprocess.check_call("make", shell=True, cwd="cpoll_cppsp", std... |
#-----------------Libraries-------------------------
###System I.O Lib. Need to be Added for Later Usage
import hashlib
#-----------------Variables-------------------------
##Var. for Input File (No New Line -> tr -d '\n')
###Additional Code Required for Asking for User's Input
infile = '8H'
##Open Filestream (infil... |
class MyBomb:
def __init__(self, start):
print(f'Activating the bomb and it will explode in {start} seconds')
self.start = start
def __iter__(self):
return MyBombIterator(self.start)
class MyBombIterator:
def __init__(self, count):
self.count = count
def __next__(se... |
import json
import subprocess
def docker_names():
"""Get docker names"""
command = 'docker ps --format "{{.Names}}"'
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
names = process.stdout.readlines()
if names:
names = [s.decode('ascii').replace('\n', '') for s in na... |
import numpy as np
from numba.decorators import jit, autojit
import hickle
import os, gzip
def binary_search(a, x):
lo = 0
hi = a.shape[0]
while lo < hi:
mid = (lo + hi) // 2
midval = a[mid]
if midval < x:
lo = mid + 1
elif midval > x:
hi = mid
... |
#
# PySNMP MIB module A3COM-HUAWEI-LB-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/A3COM-HUAWEI-LB-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 16:50:48 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... |
from requests import Request
def say(text):
host = "https://tts.chez.work/say"
params = {
"text": f"{text}",
"voice": "aleksandr",
"format": "opus",
"rate": "55",
"pitch": "10",
"volume": "70"
}
return Request("GET", host, params=params).prepare().url
|
from inspect import Signature, iscoroutinefunction
from typing import Any, Dict, List, Optional, Union, cast
from pydantic import validate_arguments
from pydantic.typing import AnyCallable
from starlite.exceptions import ImproperlyConfiguredException
from starlite.handlers.base import BaseRouteHandler
from starlite.t... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
from runtime import runtime_pb2 as runtime_dot_runtime__pb2
class RuntimeStub(object):
"""Missing associated documentation comment in .proto file."""
... |
import numpy as np
from numpy import abs, cos, exp, mean, pi, prod, sin, sqrt, sum
from autotune import TuningProblem
from autotune.space import *
import os
import sys
import time
import json
import math
import ConfigSpace as CS
import ConfigSpace.hyperparameters as CSH
from skopt.space import Real, Integer, Categoric... |
import numpy as np
import gdspy as gd
import gds_tools as gtools
#================================================
# Define healing function for transmission lines \\
#=========================================================================
# Initialization: radius : radius of healing circle ||
# ... |
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' #๋ด ๋งฅ๋ถ์์ ๋ฐ์๋๋ ์๋ฌ๋ฅผ ์์ ๊ธฐ ์ํ ์ฝ๋
import tensorflow as tf
X = [1, 2, 3]
Y = [1, 2, 3]
W = tf.Variable(5.)
hypothesis = X * W
#๋ฏธ๋ถ์ ์ํ ์์
gradient = tf.reduce_mean((W * X - Y) * X) * 2
cost = tf.reduce_mean(tf.square(hypothesis - Y))
optimizer = tf.train.GradientDescentOpt... |
# -*- coding: utf8 -*-
# Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. 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... |
# Copyright (c) 2011, Roger Lew [see LICENSE.txt]
# This software is funded in part by NIH Grant P20 RR016454.
import unittest
import warnings
import os
import math
from random import shuffle, random
from collections import Counter,OrderedDict
from dictset import DictSet,_rep_generator
from math import isnan, isinf,... |
# -*- encoding: utf-8 -*-
"""
Copyright (c) 2019 - present glastheim.pe
"""
from dataclasses import fields
from django import forms
from apps.certify.models import soat, citv, src, svct
class SOATForm(forms.ModelForm):
class Meta:
model = soat
fields = [
'policy',
'certif... |
from config.celery_conf import celery_app
|
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'instadownload.ui'
#
# Created by: PyQt5 UI code generator 5.13.0
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
import requests
import urllib.request
from selenium import webdriver
from ... |
class InvaldSudoku(Exception):
pass
class NoNSolvable(Exception):
pass
def checksquare(num, i, j, grid):
squarerow = i//3
squarecol = j//3
for rown in range(3):
for coln in range(3):
if grid[int(squarerow*3) + rown][j] == num:
return False
if grid[i][... |
from numpy.testing import *
import pymc
import os
# This is a function, not a test case, because it has to be run from inside
# the source tree to work well.
mod_strs = ['IPython', 'pylab', 'matplotlib', 'scipy','Pdb']
def test_dependencies():
dep_files = {}
for mod_str in mod_strs:
dep_files[mod_str]... |
# -*- coding: utf-8 -*-
'''
SNS type: status, user, comment
'''
import hashlib
import utils
from errors import snserror
from snsconf import SNSConf
from snslog import SNSLog as logger
class BooleanWrappedData:
def __init__(self, boolval, data=None):
self.boolval = boolval
self.data = data
... |
from pathlib import Path
from typing import Optional
import nbformat
from nbclient.client import (
CellExecutionError,
CellTimeoutError,
NotebookClient,
)
from nbformat import NotebookNode
from .nb_result import NotebookError, NotebookResult
NB_VERSION = 4
class NotebookRun:
filename: Path
verb... |
import dlib
from imutils import face_utils
import cv2
import time
colors = [(19, 199, 109), (79, 76, 240), (230, 159, 23),
(168, 100, 168), (158, 163, 32),
(163, 38, 32), (180, 42, 220), (79, 76, 240), (230, 159, 23),
(168, 100, 168), (158, 163, 32),
(163, 38, 32), (180, 42, 220), (79, 76, 240), (230, 159, ... |
# 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
# distributed under th... |
# coding: utf-8
from flask import render_template, flash, redirect,request,url_for,current_app
import os
# os.chdir(r'D:\ไฝไธ\ๅฐๅญฆๆPython\nlp\NLP\resource\learning_nlp\chapter-8\classification')
import numpy as np
from sklearn.cross_validation import train_test_split
import numpy as np
import jieba
from app import app
fr... |
import datetime
from types import resolve_bases
from cryptography.fernet import Fernet
from flask import Flask
import sli_database
from flask import request
import requests
from flask_cors import CORS, cross_origin
import random
from dotenv import load_dotenv
import os
from flaskext.mysql import MySQL
import pymysql
im... |
# Input:
# graph[][] = { {0, 5, INF, 10},
# {INF, 0, 3, INF},
# {INF, INF, 0, 1},
# {INF, INF, INF, 0} }
# which represents the following graph
# 10
# (0)------->(3)
# | /|\
# 5 | |
# | ... |
from django.db import models
class Picture(models.Model):
""" Picture manages media and set alt tags. """
def __str__(self):
return self.alt
img = models.ImageField(upload_to='img/', null=True, blank=True)
alt = models.CharField(max_length=100)
|
import numpy as np
from random import randint, uniform
from . import intelligence
class aba(intelligence.sw):
"""
Artificial Bee Algorithm
"""
def __init__(self, n, function, lb, ub, dimension, iteration):
"""
:param n: number of agents
:param function: test fun... |
"""Commands to be executed from command line."""
# pylint: disable=E0012,C0330,R0913
import click
from .autoimports.cli import autoimports
from .s3_import.cli import s3_import
@click.group()
def s3(): # pylint: disable=C0103
"""S3 imports managements commands.
Setup guide: https://docs.gencove.com/main/s3-i... |
"""
Copyright (c) 2020 Jun Zhu
"""
import copy
import numpy as np
import torch
from torch import optim
import torch.nn.functional as F
from agent_base import _AgentBase, Memory
from utilities import copy_nn, soft_update_nn, OUProcess
device = torch.device("cuda:0") if torch.cuda.is_available() else "cpu"
class D... |
from scipy.spatial.distance import jaccard
import numpy as np
import pandas as pd
# Computing Jaccard Distance of two 5D-Rectangles
# Issues to deal with:
# Normalizing values?
# Input format correct?
# Weighting of the different dimensions?
def jaccard_distance(datFr, name, pred):
"""
Should return the "c... |
class Solution(object):
def plusOneUnoptimized(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
first = True
carry = 1
counter = 1
digit_len = len(digits)
while carry and counter <= digit_len:
digits[counter*-1] = di... |
from conehead import (
Source, Block , SimplePhantom, Conehead
)
import numpy as np
import pydicom
from scipy.interpolate import RegularGridInterpolator
# Load test plan
plan = pydicom.dcmread("RP.3DCRT.dcm", force=True)
# Choose source
source = Source("varian_clinac_6MV")
source.gantry(0)
source.collimator(0)
#... |
from .predictor import BasePredictor, SegPredictor, ImSpecPredictor, Locator
from .epredictor import EnsemblePredictor, ensemble_locate
__all__ = ["BasePredictor", "SegPredictor", "ImSpecPredictor",
"EnsemblePredictor", "ensemble_locate", "Locator"]
|
import sys
from xml.etree import ElementTree
html = ElementTree.Element("html")
body = ElementTree.Element("body")
html.append(body)
div = ElementTree.Element("div")
body.append(div)
span = ElementTree.Element("span")
div.append(span)
span.text = "Hello World"
string = ElementTree.tostring(html).decode()
file = open... |
default_app_config = 'ore.projects.apps.ProjectsConfig'
|
from .avocent_request import AvocentRequest
from ..models import LoginResult
class LoginRequest(AvocentRequest):
username = ""
password = ""
def __init__(self, username, password):
super().__init__()
self.username = username
self.password = password
def get_body(self):
str = '<avtrans><sid></sid><action>... |
from django.contrib import admin
from .models import *
class MaDrivers(admin.ModelAdmin):
list_display = ('name', 'location', 'availability', 'description')
class ContactUsAdmin(admin.ModelAdmin):
list_display = ('name', 'phone')
#
#
# class basket(admin.ModelAdmin):
# list_display = ('user', 'status')
... |
This is experiment 2 homework 2
|
"""
Autopsy Forensic Browser
Copyright 2016-2020 Basis Technology Corp.
Contact: carrier <at> sleuthkit <dot> org
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 . import (
analysers,
configuration,
connectors,
inertia,
multibody,
output,
rigidbody,
)
|
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
result = []
self.dfs(n, 0, 0, "", result)
return result
def dfs(self, n, left, right, node, result):
if left == n and right == n:
result.append(node)
if left < n:
self.dfs(n, left + 1, right, node + "(", result)
... |
from flask_wtf import FlaskForm
from wtforms.fields import StringField, PasswordField, HiddenField, IntegerField, BooleanField
from wtforms.validators import DataRequired
from wtforms.widgets import HiddenInput
class LoginForm(FlaskForm):
username = StringField("username", validators=[DataRequired()])
passwor... |
"""Loss modules"""
from .semseg_loss import SemSegLoss
from .cross_entropy import CrossEntropyLoss
from .focal_loss import FocalLoss
from .smooth_L1 import SmoothL1Loss
__all__ = ['SemSegLoss', 'CrossEntropyLoss', 'FocalLoss', 'SmoothL1Loss']
|
from app.config import settings
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
from sqlalchemy.ext.declarative import declarative_base
# BASE
'''
declarative_base() is a factory function that constructs a base class
for declarative class definitions.
Ref : https://docs.... |
'''
Parsing - Exercise 16
The script reads a multiple sequence file in FASTA format and
only write to a new file the records the Uniprot ACs of which
are present in the list created in Exercise 14).
'''
# We need two input files
cancer_file = open('cancer-expressed.txt')
human_fasta = open('SwissProt-Human.fasta'... |
# Created By: Virgil Dupras
# Created On: 2006/10/06
# Copyright 2010 Hardcoded Software (http://www.hardcoded.net)
#
# This software is licensed under the "BSD" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.hardcoded.net/licens... |
#!/usr/bin/env python
# Copyright 2019 Pascal Audet & Helen Janiszewski
#
# This file is part of OBStools.
#
# 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 wi... |
def basis_set_setter(element_symbol):
"""
:param element_symbol: string, element symbol
:return: string, Basis set name
"""
#HERE I should define all the elements and all the basis set
if element_symbol=='H':
return "TZV2PX-MOLOPT-GTH"
elif element_symbol=='F':
ret... |
# Generated by Django 2.1.3 on 2019-04-25 11:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('post', '0007_auto_20190425_0312'),
]
operations = [
migrations.AlterField(
model_name='post',
name='thumb',
... |
"""Test the WebOS Tv config flow."""
import dataclasses
from unittest.mock import Mock, patch
from aiowebostv import WebOsTvPairError
import pytest
from homeassistant import config_entries
from homeassistant.components import ssdp
from homeassistant.components.webostv.const import CONF_SOURCES, DOMAIN, LIVE_TV_APP_ID... |
# mode: run
# tag: generator
import sys
def _next(it):
if sys.version_info[0] >= 3:
return next(it)
else:
return it.next()
def test_generator_frame_cycle():
"""
>>> test_generator_frame_cycle()
("I'm done",)
"""
testit = []
def whoo():
try:
yield
... |
# MIT License
#
# Copyright (c) 2022 Ecco Sneaks & Data
#
# 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, ... |
from __future__ import print_function
from cStringIO import StringIO
import sys
from rdkit.Chem.rdmolfiles import (
MolFromMol2Block,
MolToPDBBlock,
)
def main(args, stdin=sys.stdin, stdout=sys.stdout):
if len(args) > 0:
path = args[0]
with open(path) as f:
structure = MolFrom... |
from mcpi.minecraft import Minecraft
mc = Minecraft.create()
length = 20
width = 10
height = 5
x,y,z = mc.player.getTilePos()
x2 = x+length
y2 = y+height
z2 = z+width
mc.setBlocks(x,y,z,x2,y2,z2,8)
mc.setBlocks(x+1,y+1,z+1,x2-1,y2-1,z2-1)
|
import torch
import numpy as np
import argparse
import pybulletgym
from cont_skillspace_test.grid_rollout.rollout_tester_plot_thes \
import RolloutTesterPlotThes
from cont_skillspace_test.grid_rollout.grid_rollouter \
import GridRollouter
from cont_skillspace_test.utils.load_env import load_env
import rlkit.t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.