content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
from abc import abstractmethod
from typing import List, Union, Tuple
import numpy as np
from sc2 import Result, UnitTypeId
from sharpy.managers.extensions import ChatManager
from sharpy.plans import BuildOrder
from sharpy.plans.acts import ActBase
from tactics.ml.agents import BaseMLAgent
REWARD_WIN = 1
REWARD_LOSE =... | python |
class HalfAdder(DynamicNetwork):
#-- This creator HalfAdder(a,b) takes two nodes a,b that
# are inputs to the half-adder.
def __init__(inst, a, b):
#-- Add the two input nodes to the set of nodes associated
# with the current full-adder network.
inst.addNodes(a, b... | python |
import json
import argparse
import matplotlib.pyplot as plt
import math
from typing import Dict
plt.switch_backend("agg")
def plot_bleu_score_data(bleu_score_dict: Dict, language_dict: Dict, picture_path: str):
fig_num_per_picture = 6
lang_list = list(bleu_score_dict.keys())
num_picture = int(math.cei... | python |
import pprint
from zolware_data import user_manager
from zolware_data import datasource_manager
from zolware_data import signal_manager
from zolware_data import datasource_reader
user_manager = user_manager.UserManager()
user = user_manager.find_user_by_email('snclucas@gmail.com')
datasource_manager = datasource_mana... | python |
# coding:utf-8
#
# The MIT License (MIT)
#
# Copyright (c) 2016-2018 yutiansut/QUANTAXIS
#
# 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 th... | python |
"""
file: 'time_align.py'
author: David Fairbairn
date: June 2016
The need for a script that looks at timestampdata (currently only relevant for
the Saskatoon SuperDARN radar) to the errlog files' erroneous timestamps
compelled me to write this script.
This script approaches the problem by identifying the times durin... | python |
# String; Backtracking
# Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
#
# A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
#
#
#
# Example:
#
# Input: "23"
# Outpu... | python |
from dagster import asset
# start_example
@asset(metadata={"cereal_name": "Sugar Sprinkles"})
def cereal_asset():
return 5
# end_example
| python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 4 18:26:36 2019
@author: Juan Sebastián Herrera Cobo
This code solves the scheduling problem using a genetic algorithm. Implementation taken from pyeasyga
As input this code receives:
1. T = number of jobs [integer]
2. ni = number of oper... | python |
import os
from pydu.dt import timer
class TestTimer(object):
def test_context_manager(self):
timeit = timer()
with timeit:
os.getcwd()
assert timeit.elapsed is not None
def test_decorator(self):
timeit = timer()
@timeit
def foo():
os.... | python |
# Imports
import sys
import torch
import os
import numpy as np
import time
from sbi.inference import SNRE_B, prepare_for_sbi
# Initial set up
lunarc = int(sys.argv[1])
seed = int(sys.argv[2])
print("Input args:")
print("seed: " + str(seed))
if lunarc == 1:
os.chdir('/home/samwiq/snpla/seq-posterior-approx-w-nf-d... | python |
class RMCError(Exception):
def __init__(self, message):
Exception.__init__(self, message)
self.__line_number=None
def set_line_number(self, new_line_number):
self.__line_number=new_line_number
def get_line_number(self):
return self.__line_number
... | python |
__author__ = 'Milo Utsch'
__version__ = '0.1.0'
from setuptools import setup, find_packages
from euler import __name__ as name
from euler import __author__ as author
from euler import __doc__ as doc
from euler import __email__ as author_email
from euler import __version__ as version
from euler import __license__ as l... | python |
# Masters Research Project
# Kenneth Young
# FSBF MIP Model of the SUALBSP-2
# This file contains:
# -A MIP model of the SUALBSP-2
# -This model was adapted from Esmaeilbeigi et al. (2016),
# specifically their FSBF-2 model.
# Packages
import sys
import pdb
import time
# import itertools
import csv
import argpars... | python |
# https://leetcode.com/problems/count-number-of-pairs-with-absolute-difference-k/
class Solution:
def countKDifference(self, nums: List[int], k: int) -> int:
count = 0
for i in range(0, len(nums)-1):
for j in range(i+1, len(nums)):
if abs(nums[i]-nums[j... | python |
import glob
import re
import time
import os
from utils.config_utils import *
from utils.colors import *
import shutil
from datetime import datetime
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import socket
import subprocess
current_path = os.path.dirname(os.path.abspath(__file__... | python |
__author__ = 'Benjamin Knight'
__license__ = 'MIT'
__version__ = '0.1'
| python |
#!/usr/bin/env python3
import yaml
import torch
import random
import argparse
import json
import numpy as np
import datetime
from pathlib import Path
from src.marcos import *
from src.mono_interface import MonoASRInterface
from src.utils import get_usable_cpu_cnt
import src.monitor.logger as logger
# Make cudnn det... | python |
from distutils.core import setup
setup(name='tf-easy-model-saving',
version='1.0',
author='Philippe Remy',
packages=['easy_model_saving'],
zip_safe=False)
| python |
# type: ignore
import colorsys
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Dict, List, Optional, Union, Type
from pydantic import constr
from labelbox.schema import project
from labelbox.exceptions import InconsistentOntologyException
from labelbox.orm.db_object import DbOb... | python |
from django.conf.urls import url, include
from . import views
from project import views
urlpatterns = [
url('signIn', views.signIn, name='signIn'),
url('signUp', views.signUp, name='signUp')
]
| python |
__version__ = u'0.1.2'
| python |
import os
import types
from ledger.util import STH
from ledger.ledger import Ledger
def checkLeafInclusion(verifier, leafData, leafIndex, proof, treeHead):
assert verifier.verify_leaf_inclusion(
leaf=leafData,
leaf_index=leafIndex,
proof=proof,
sth=STH(**treeHead))
def checkCons... | python |
from __future__ import absolute_import, print_function
from . import camx, cmaq
__all__ = ['camx', 'cmaq']
__name__ = 'models'
#
| python |
from bangtal import *
import time
setGameOption(GameOption.INVENTORY_BUTTON, False)
setGameOption(GameOption.MESSAGE_BOX_BUTTON, False)
game_scene = Scene('Othello', 'Images/background.png')
transparent_screen = Object('Images/transparent_screen.png')
BLANK = -1
BLACK = 0
WHITE = 1
BLACK_POS = 3
WHITE_POS = 4
BASE... | python |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 7 00:53:29 2019
@author: yoelr
"""
from ... import Unit
__all__ = ('extend_summary', )
def extend_summary(cls):
"""Extends the Unit class with the following abstract methods:
**_end():**
Finish setting purchase prices and utility costs.
... | python |
import os
import json
import pkgutil
import datetime
import ast
import yaml
from yaml import Loader
# Get version without importing module
mod = ast.parse(pkgutil.get_data(__name__, "__init__.py").decode())
assignments = [node for node in mod.body if isinstance(node, ast.Assign)]
__version__ = [node.value.s for node ... | python |
import os
import json
import base64
from urllib import request
from io import BytesIO
def _download_file(url, local_file_path):
response = request.urlopen(url)
with open(local_file_path, 'wb') as local_file:
local_file.write(BytesIO(response.read()).read())
def _upload_to_s3(s3_interface, local_soft... | python |
from runtime import *
"""list.pop(n)"""
def main():
a = list(range(10))
print a
b = a.pop()
print b
print a
assert( b==9 )
c = a.pop(0)
assert( c==0 )
d = ['A', 'B', 'C']
assert( d.pop(1)=='B' )
assert( len(d)==2 )
main()
| python |
# -*- coding: utf-8 -*-
import json
import re
from datetime import timedelta, datetime
from DictObject import DictObject
from luckydonaldUtils.logger import logging
from luckydonaldUtils.encoding import unicode_type, to_unicode as u, to_native as n
from luckydonaldUtils.functions import deprecated
from luckydonaldUtil... | python |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# 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 ... | python |
from math import trunc
num = float(input("Digite um valor: "))
print("\nO valor digitado foi {} e a sua porção inteira é {}".format(num, trunc(num))) | python |
from PyQt5 import QtWidgets
import difflib
from nixui.graphics import generic_widgets
class DiffedOptionListSelector(generic_widgets.ScrollListStackSelector):
ItemCls = generic_widgets.OptionListItem # TODO: remove break dependency with generic_widgets.py
def __init__(self, updates, *args, **kwargs):
... | python |
"""
This file will parse the input text file and get important
knowledge from it and create a database known as Knowledge Base
"""
import json
import os
from engine.components.knowledge import Knowledge
from engine.logger.logger import Log
class KnowledgeBaseParser:
"""
Class the parse the file and create t... | python |
# Generated by Django 3.1.2 on 2021-04-23 20:30
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('recruiters', '0002_auto_20210423_2028'),
]
operations = [
migrations.RemoveField(
model_name='job',
name='slug',
),
... | python |
"""
Ringing artifact reduction example
==================================
This example shows how to subtract the impulse response from a filter to
reduce ringing artifacts.
"""
import matplotlib.pyplot as plt
import numpy as np
from scipy.signal import butter, lfilter
from meegkit.detrend import reduce_ringing
# i... | python |
import numpy as np
import statsmodels.formula.api as smf
from patsy import dmatrix, build_design_matrices
from pandas import DataFrame
class QuantileSpline:
def __init__(self, quantiles=0.5, df=3):
self.quantiles = quantiles
self.df = df
self.label = 'Quantile Spline'
self.filename ... | python |
# Copyright 2008 German Aerospace Center (DLR)
#
# 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... | python |
from django.test import TestCase
from . import factories
from .. import models
class TestCard(TestCase):
model = models.Card
def test_str(self):
"""A card's str representation is its name."""
name = 'Leeroy Jenkins'
card = factories.CardFactory.create(name=name)
self.assertEq... | python |
from foolbox.zoo import git_cloner
import os
import hashlib
import pytest
from foolbox.zoo.git_cloner import GitCloneError
def test_git_clone():
# given
git_uri = "https://github.com/bethgelab/convex_adversarial.git"
expected_path = _expected_path(git_uri)
# when
path = git_cloner.clone(git_uri)
... | python |
# pip3 install 'gym[atari,accept-rom-license]==0.22.0'
import matplotlib.pyplot as plt
import gym
from gym import wrappers
import random
import numpy as np
env = gym.make('ALE/MsPacman-v5', render_mode='human')
height, width, channels = env.observation_space.shape
actions = env.action_space.n
episodes = 1
random_mo... | python |
from django import template
register = template.Library()
@register.filter
def mul(value, arg):
arg = int(arg)
return int(value * arg) | python |
############################################################
# -*- coding: utf-8 -*-
#
# # # # # # ####
# ## ## # ## # #
# # # # # # # # # ###
# # ## # ## ## #
# # # # # # ####
#
# Python-based Tool for interaction with the 10micron mounts
# GUI with PyQT5 ... | python |
import logging
import os
import arrow
from humanfriendly import parse_size
from .api import delete_file, get_all_results, upload_file
from .utils_fs import download_file, validate_metadata
MAX_SIZE_DEFAULT = '128m'
class OHProject:
"""
Work with an Open Humans Project.
"""
def __init__(self, master... | python |
# =============================================================================
#
# Copyright (c) Kitware, Inc.
# All rights reserved.
# See LICENSE.txt for details.
#
# This software is distributed WITHOUT ANY WARRANTY; without even
# the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
# PURPOSE.... | python |
tri = [
[0, 75, 0],
[0, 95, 64, 0],
[0, 17, 47, 82, 0],
[0, 18, 35, 87, 10, 0],
[0, 20, 4, 82, 47, 65, 0],
[0, 19, 1, 23, 75, 3, 34, 0],
[0, 88, 2, 77, 73, 7, 63, 67, 0],
[0, 99, 65, 4, 28, 6, 16, 70, 92, 0],
[0, 41, 41, 26, 56, 83, 40, 80, 70, 33, 0],
[0, 41, 48, 72, 33, 47, 32, 37, 16, 94, 29, 0],
[0, 53, 71, 44, 65,... | python |
from .model import (
set_db_path,
Model,
Field,
IntField,
DateTimeField,
StrField
)
| python |
from typing import Union, Optional
import torch
from falkon.options import FalkonOptions
from falkon.sparse.sparse_tensor import SparseTensor
from falkon.utils import TicToc, decide_cuda
from falkon.la_helpers import mul_triang, copy_triang, trsm, vec_mul_triang
from falkon.utils.tensor_helpers import create_same_str... | python |
from IPython import get_ipython
# %%
####################
# GRAPH GENERATION #
####################
# TODO: remove duplicate of nbIndividuals in viz
nbIndividuals = 1000 # number of people in the graph | nombre d'individus dans le graphe
initHealthy = 0.85 # proportion of healthy people at start | la proportion de per... | python |
# -*- coding: utf-8 -*-
import time
import tempfile,random,string
from common.common import BaseService
import HTMLParser
import imgkit
from common import logger
class BaseBot(BaseService):
type = None
'''
给指定的群组和用户发消息
由于目前,很少给用户发消息,所以,没必要定一个send(user,message)接口
group: QQ群名称、QQ讨论群名称、微... | python |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import datetime
from six import iteritems
import frappe
from frappe import _
from frappe.utils import flt, formatdate
from erpnext.controll... | python |
import sys
import os
import re
import networkx as nx
import random
import numpy as np
from alias_table_sampling import AliasTable as at
class BatchStrategy(object):
# G is a DiGraph with edge weights
def __init__(self, G, num_new, mapp, rmapp, num_modify, params = None):
self.edges = []
probs_... | python |
from django import forms
from .models import squirrel_data
class SquirreldataForm(forms.ModelForm):
'''
Class to handle ModelForms that are used in the Add Sighting form
'''
class Meta:
model = squirrel_data
fields = '__all__'
| python |
import logging
import pandas as pd
from flask import request
from mlpiper.components.connectable_component import ConnectableComponent
from datarobot_drum.drum.common import LOGGER_NAME_PREFIX
from datarobot_drum.drum.exceptions import DrumCommonException
from datarobot_drum.profiler.stats_collector import StatsColl... | python |
"""Adds config flow for NorwegianWeather."""
import logging
from homeassistant import config_entries
from homeassistant.core import callback
from homeassistant.helpers.aiohttp_client import async_create_clientsession
from homeassistant.const import CONF_MONITORED_CONDITIONS
from homeassistant.helpers import config_vali... | python |
count_weekday_years = survey_data.groupby([survey_data["eventDate"].dt.year, survey_data["eventDate"].dt.dayofweek]).size().unstack() | python |
import os;
import bvpl_octree_batch
import multiprocessing
import Queue
import time
import random
import optparse
import sys
from numpy import log, ceil
from xml.etree.ElementTree import ElementTree
class dbvalue:
def __init__(self, index, type):
self.id = index # unsigned integer
self.type = type # ... | python |
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from app.models import Question, Answer, Tag
CONFIRMATION = 'remove database'
class Command(BaseCommand):
help = 'Remove all data from the database'
requires_migrations_checks = True
def add_arguments(self, pa... | python |
import numpy
from PIL import Image
def get_origin(canny_img):
image = canny_img.load()
pixels_x = []
pixels_y = []
for x in range(0, canny_img.size[0]):
for y in range(0, canny_img.size[1]):
if image[x,y] != 0:
pixels_x.append(x)
pixels_y.append(y)
... | python |
"""A Python library for perturbation-based classifiers.
``Perturbation Classifier`` is a library containing the implementation of the Perturbation-based
Classifier (PerC) and subconcept Perturbation-based Classifier (sPerC).
Subpackages
-----------
subconcept
The implementation of subconcept Perturbation-based C... | python |
import goprolib.HERO4.HERO4 as HERO4
import datetime
import time
def main(path='/media/xyoz/XYOZ-INT1000E/Pictures/2016_07_13 GoPro Auto'):
h4 = HERO4.HERO4()
h4.download_all(delete_after_download=True, path=path)
if __name__ == '__main__':
while True:
try:
main('/media/xyoz/XYOZ-INT1... | python |
# GNU MediaGoblin -- federated, autonomous media hosting
# Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either versio... | python |
import re
import six
import ast
import json
import global_params
from utils import run_command
from ast_helper import AstHelper
class Source:
def __init__(self, filename):
self.filename = filename
self.content = self._load_content()
self.line_break_positions = self._load_line_break_positi... | python |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import os
import copy
from functools import partial
import math
import numpy as np
from pathlib import Path
import random
from typing import Callable, Dict, List, Tuple, Union
import torch
from torch.utils.data import Datase... | python |
from django import template
register = template.Library()
@register.filter(name='get_vulnerable_endpoints')
def get_vulnerable_endpoints(endpoints):
return endpoints.filter(remediated=False)
@register.filter(name='get_remediated_endpoints')
def get_remediated_endpoints(endpoints):
return endpoints.filter(re... | python |
class Node():
def __init__(self, key, data):
"""Create a new node
Arguments:
key {[type]} -- [description]
data {[type]} -- [description]
"""
self.key = key
self.data = data
self.next = None | python |
if __name__ == '__main__':
# print("a")
# ord: characters -> ASCII code
# print(ord('a'))
# chr: ASCII code -> characters
# print(chr(97))
result = chr(ord('a') + 1)
print(result) | python |
"""download and/or process data"""
import torch
import torch.nn as nn
import torchaudio
import pandas as pd
from sonopy import power_spec, mel_spec, mfcc_spec, filterbanks
class MFCC(nn.Module):
def __init__(self, sample_rate, fft_size=400, window_stride=(400, 200), num_filt=40, num_coeffs=40):
super(MFC... | python |
from substance.monads import *
from substance.logs import *
from substance import (Engine, Command)
from substance.exceptions import (SubstanceError)
class Env(Command):
def getUsage(self):
return "substance engine env [ENGINE NAME]"
def getHelpTitle(self):
return "Print the shell variables ... | python |
from PIL import Image
import math
import os
DATASET_PATH = 'A:/temp/temp'
output_path = 'image_resize/'
MAXIMUM_RESOLUTION = 1280*720
def img_resize(img, maximum_resolution):
img_width = img.width
img_height = img.height
img_definition = img_width * img_height
img_dpi = img.info['dpi']
if img_... | python |
from kivy.uix.screenmanager import Screen
from kivy.properties import BooleanProperty, StringProperty
from kivy.event import EventDispatcher
from kivy.network.urlrequest import UrlRequest
from kivy.app import App
from kivy.lang import Builder
from kivy.factory import Factory
import sys
sys.path.append("/".join(x for x ... | python |
"""A module that fails the tests"""
long_string = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
def bad_function(a: int) -> int:
"""Return input + 2
Parameters
----------
a : int
input integer
Returns
-------
int
input + 2
"""
return a ... | python |
TESTING=True
"""
TESTING=False IN CASE OF PRODUCTION
TESTING=True IN CASE OF TESTING
"""
from flask import (Flask, abort, jsonify, make_response, request)
from flask_sqlalchemy import SQLAlchemy
import secrets
import os
from __init__ import db, SECRET
from models import (NotReceived, User, #Product, Order, #Image,
d... | python |
import pickle
import numpy as np
import torch
from torch import Tensor
from torch.utils.data import Dataset
import arguments as args
class CrepeDataset(Dataset):
def __init__(self,
data_path: str,
sample_len: int,
scaler,
device: str
... | python |
def obter_dados_canal(lista):
for _ in range(lista):
nome,inscritos,monetizacao,ehpremium = input().split(';')
inscritos = int(inscritos)
monetizacao = float(monetizacao)
ehpremium = ehpremium == 'sim'
canais.append([nome, inscritos, monetizacao, ehpremium])
def calcular_bonificacao(valor... | python |
# -*- coding: utf-8 -*-
from datetime import datetime
from sqlalchemy import Column
from sqlalchemy.dialects.mysql import INTEGER, VARCHAR, TINYINT, TIMESTAMP
from webspider import constants
from webspider.models.base import BaseModel
class JobModel(BaseModel):
__tablename__ = 'job'
id = Column(INTEGER, nu... | python |
"""
:date_created: 2021-11-18
"""
from do_py.abc import ABCRestrictions
from db_able.base_model.database_abc import Database
from db_able.client import DBClient
@ABCRestrictions.require('save_params')
class Savable(Database):
"""
This is a mixin designed to access DB with a standard method action, `save`.
... | python |
from .orient import ImageOrienter
from recipes.dicts import pformat
class keep:
pass
class CalibrationImage:
"""Descriptor class for calibration images"""
# Orientation = ImageOrientBase
def __init__(self, name):
self.name = f'_{name}'
def __get__(self, instance, owner):
if in... | python |
import pandas as pd
import numpy as np
import math
import json
from tqdm import tqdm
from time import time
from datetime import datetime, timedelta
import sys
import warnings
if not sys.warnoptions:
warnings.simplefilter("ignore")
import matplotlib.pyplot as plt
import matplotlib.cm
from matplotlib.colors import ... | python |
import random
from donphan.utils import not_creatable
from tests.utils import async_test
from donphan import Column, Table, SQLType
from unittest import TestCase
class _TestAlterColumnsTable(Table):
a: Column[SQLType.Text] = Column(primary_key=True)
class AlterColumnsTest(TestCase):
def test_query_drop_col... | python |
import torch
class AutocastCPUTestLists(object):
# Supplies ops and arguments for test_autocast_* in test/test_cpu.py
def __init__(self, dev):
super().__init__()
n = 8
# Utility arguments, created as one-element tuples
pointwise0_bf16 = (torch.randn(n, dtype=torch.bfloat16, devi... | python |
from __future__ import print_function
from keras.preprocessing.image import ImageDataGenerator
import numpy as np
import os
import glob
import skimage.io as io
import skimage.transform as trans
khong = [0,0,0]
vua = [0,0,128]
nang = [0,128,0]
ratnang = [128,128,0]
lut = [128,0,0]
COLOR_DICT = np.array([khong,vua,na... | python |
# -*- coding: utf-8 -*-
# import general neural network model
from .dnn import NN
# import multilayer perceptron model
from .mlp import *
# import NEAT model
from .neat_model import NEATModel
# import convolutional neural network
from .cnn import *
# import recurrent neural network
from .rnn import *
# import aut... | python |
import django_tables2 as tables
from nautobot.utilities.tables import (
BaseTable,
ButtonsColumn,
ToggleColumn,
)
from dummy_plugin.models import DummyModel
class DummyModelTable(BaseTable):
"""Table for list view of `DummyModel` objects."""
pk = ToggleColumn()
name = tables.LinkColumn()
... | python |
from stonehenge import Application, Route, Router, run
from stonehenge.modules import DefaultModules
from stonehenge.admin import AdminRouter
from stonehenge.cms import CMSRouter
from blog import BlogModule
from handlers import home, about, portfolio, subpage, blog_handler, user_handler
class App(Application):
m... | python |
import pytorch_lightning as pl
from pytorch_lightning import loggers
from l5kit.configs import load_config_data
from raster.lyft import LyftTrainerModule, LyftDataModule
from pathlib import Path
import argparse
import torch
from raster.utils import boolify
import pandas as pd
parser = argparse.ArgumentParser(descripti... | python |
# Copyright (c) 2018 Steven R. Brandt
# Copyright (c) 2018 R. Tohid
#
# Distributed under the Boost Software License, Version 1.0. (See accompanying
# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
import phylanx
from phylanx import Phylanx
@Phylanx
def sumn():
n = 0
sum = 0
fo... | python |
from django.apps import AppConfig
class ScannerappConfig(AppConfig):
name = 'scannerapp'
| python |
"""
Developed by : Adem Boussetha
Email : ademboussetha@gmail.com
"""
import cv2
import datetime
import os
face_cascade = cv2.CascadeClassifier('cascades/data/haarcascade_frontalface_default.xml')
# Read the input image
#img = cv2.imread('test.png')
cap = cv2.VideoCapture(0)
print ("you're gonna be added to db face re... | python |
"""
523. Continuous Subarray Sum
Given a list of non-negative numbers and a target integer k,
write a function to check if the array has a continuous subarray of size at least 2 that sums up to the multiple of k,
that is, sums up to n*k where n is also an integer.
Example 1:
Input: [23, 2, 4, 6, 7], k=6
Output: ... | python |
#!/usr/bin/env python3
import xmlrpc.client
import time
test1 = xmlrpc.client.ServerProxy('http://localhost:8081')
print(test1.system.listMethods())
test1.start_trial()
test1.turnLeft()
test1.turnRight()
test1.end_trial()
| python |
class Solution:
def missingNumber(self, nums: [int]) -> int:
nums_set = set(nums)
for i in range(len(nums) + 1):
if i not in nums_set:
return i | python |
#
# gemini_python
#
# recipe_system.reduction
# reduceActions.py
# -----------------------------------------------------------------------... | python |
from fastapi import APIRouter
from fastapi import Depends, HTTPException, status
from fastapi.responses import ORJSONResponse
from fastapi.security import OAuth2PasswordRequestForm
from fastapidi import get_dependency
from app.modules.auth.depends import validate_jwt_token
from app.modules.auth.dtos.token import Toke... | python |
"""
fasta - manipulations with FASTA databases
==========================================
FASTA is a simple file format for protein sequence databases. Please refer to
`the NCBI website <http://www.ncbi.nlm.nih.gov/blast/fasta.shtml>`_
for the most detailed information on the format.
Data manipulation
---------------... | python |
from log import LOG
from .image import Image
from .digits import Digits
| python |
# V0
# V1
# https://blog.csdn.net/fuxuemingzhu/article/details/82083609
class Solution(object):
def numSpecialEquivGroups(self, A):
"""
:type A: List[str]
:rtype: int
"""
B = set()
for a in A:
B.add(''.join(sorted(a[0::2])) + ''.join(sorted(a[1::2])))
... | python |
# ======================================================================
# Dirac Dice
# Advent of Code 2021 Day 21 -- Eric Wastl -- https://adventofcode.com
#
# Python implementation by Dr. Dean Earl Wright III
# ======================================================================
# ===============================... | python |
from rest_framework import viewsets
from rest_framework.permissions import IsAdminUser
from src.apps.users.models import User
from src.apps.users.serializers import FullUserSerializer, LimitedUserSerializer
from src.contrib.permission import ReadOnly
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint... | python |
# -*- coding: utf-8 -*-
"""rackio/managers/api.py
Thi module implements API Manager.
"""
import falcon
from falcon import api_helpers as helpers
from falcon_auth import FalconAuthMiddleware, TokenAuthBackend
from falcon_multipart.middleware import MultipartMiddleware
from falcon_cors import CORS
from ..api import Ta... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.