content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
from __future__ import unicode_literals from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.utils.translation import ugettext_lazy as _ from datetime import datetime as ...
nilq/baby-python
python
#Much code directly from Google's TensorFlow """Library for creating sequence-to-sequence models.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from six.moves import xrange # pylint: disable=redefined-builtin import tensorflow as tf import inspect ...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Created on Sun Jun 28 13:06:28 2020 @author: tomvi """ import pandas as pd import math import statistics as stat import statsmodels.api as sm from statsmodels.stats.diagnostic import het_white as white, \ het_breuschpagan as bpt import numpy as np import matplotlib.pyplot...
nilq/baby-python
python
import torch from torch.nn.utils import clip_grad_value_ from torch.distributions import Categorical from radbm.utils.torch import torch_soft_hamming from radbm.search.elba import EfficientLearnableBinaryAccess def categorical_entropy(cat): """ -(cat*cat.log()).sum() without the annoying 0*inf Paramet...
nilq/baby-python
python
import Print import os import shutil import sq_tools import io import sys import listmanager import csv import requests try: import ujson as json except: import json from tqdm import tqdm # SET ENVIRONMENT squirrel_dir=os.path.abspath(os.curdir) NSCB_dir=os.path.abspath('../'+(os.curdir)) if os.p...
nilq/baby-python
python
"""Third-party commands enabled through drytoml.""" import importlib import os import shlex import subprocess as sp # noqa: S404 import sys import tempfile from contextlib import contextmanager from pathlib import Path from typing import IO from typing import Callable from typing import List from typing import Union ...
nilq/baby-python
python
# 313. Super Ugly Number # ttungl@gmail.com class Solution(object): def nthSuperUglyNumber(self, n, primes): """ :type n: int :type primes: List[int] :rtype: int """ # runtime: 535ms ugly = [1]*n i = [-1]*len(primes) v = [1]*len(primes) ...
nilq/baby-python
python
from django.core.management import call_command from unittest import mock from django_webpack_dev_server.management.generator import Generator class TestCommand: """ Test Class for testing the Command Class defined in the generate.py """ @mock.patch.object(Generator, "generate") def test_command(...
nilq/baby-python
python
""" """ import numpy as np from ..diffstar_ew_kernels import _calc_ew_from_diffstar_params_const_lgu_lgmet from ..diffstar_ew_kernels import _calc_ew_from_diffstar_params_const_lgmet from ..sfh_model import DEFAULT_MAH_PARAMS, DEFAULT_MS_PARAMS, DEFAULT_Q_PARAMS from ..mzr import DEFAULT_MZR_PARAMS from .retrieve_fake_...
nilq/baby-python
python
# ABC165A - We Love Golf def main(): # input K = int(input()) A, B = map(int, input().split()) # compute km=False for i in range(A,B+1): if i%K ==0: km=True # output if km: print("OK") else: print("NG") if __name__ == '__main__': main()
nilq/baby-python
python
# Adapted from https://github.com/opencv/opencv_contrib/blob/master/modules/aruco/samples/detect_markers.cpp import argparse import cv2 import utils def main(args): # Read camera parameters camera_params_file_path = utils.get_camera_params_file_path(args.camera_name) image_width, image_height, camera_matri...
nilq/baby-python
python
from unittest import TestCase from vision.flashless_utility import copy_backup_flashless_files, rollback_flashless_files from vision.constant import VisionException from mock import patch class TestFlashlessUtility(TestCase): @patch('os.path.isfile', return_value=True) @patch('shutil.copyfile') def tes...
nilq/baby-python
python
from mandaw import * mandaw = Mandaw("Window!", width = 800, height = 600, bg_color = (0, 0, 0, 255)) mandaw.loop()
nilq/baby-python
python
import uuid import unittest from TwitterSentimentAnalysis import ai, core, downloaders, datasets import numpy as np import os from sklearn.metrics import mean_squared_error class NeuralNetworksTweetsTestCase(unittest.TestCase): @classmethod def setUpClass(cls): base_dir = os.path.dirname(__file__) ...
nilq/baby-python
python
import os import discord from dotenv import load_dotenv load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN') GUILD = os.getenv('DISCORD_GUILD') client = discord.Client() @client.event async def on_ready(): guild = discord.utils.get(client.guilds, name=GUILD) print( f'{client.user} is connected to the fo...
nilq/baby-python
python
class NumArray(object): def __init__(self, nums): """ :type nums: List[int] """ self.prefixSum = [0] * (len(nums) + 1) currentSum = 0 for idx, num in enumerate(nums): currentSum += num self.prefixSum[idx + 1] = currentSum def sumRange(se...
nilq/baby-python
python
# -*- coding: utf-8 -*- from sqlalchemy import Column, ForeignKey, Integer, String, UniqueConstraint from sqlalchemy.orm import relationship from .models import BASE class CaseGenelistLink(BASE): """Link between case and gene list.""" __tablename__ = 'case_genelist_link' __table_args__ = (UniqueConstra...
nilq/baby-python
python
# Generated by Django 3.1 on 2020-09-26 19:45 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('projects', '0003_auto_20200912_1626'), ('delivery', '0001_initial'), ] operations = [ migrations.Alte...
nilq/baby-python
python
"""Monkey patch other python libraries.""" import numpy as np import jax from jax import core, lax, numpy as jnp from jax._src.lib import xla_client as xc from jax._src.lib.xla_bridge import get_backend as default_get_backend from jax.interpreters import partial_eval as pe from jax.interpreters.xla import (xops, jaxpr_...
nilq/baby-python
python
#coding: utf-8 import sys import os import re import argparse def process_file(input_file): log = {} log['clients'] = [] log['95per'] = [] log['min'] = [] log['med'] = [] log['max'] = [] for line in input_file: point = parse_line(line) if point: log['clients'].append(point['clients']) log['95per']...
nilq/baby-python
python
import numpy as np from small_text.data import Dataset, DatasetView from small_text.data.exceptions import UnsupportedOperationException from small_text.integrations.pytorch.exceptions import PytorchNotFoundError try: import torch from torchtext.vocab import Vocab except ModuleNotFoundError: raise Pytorc...
nilq/baby-python
python
# Generated by Django 3.2.5 on 2021-07-16 21:04 import colorfield.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('entertainment', '0001_initial'), ] operations = [ migrations.AlterField( model_name='article', ...
nilq/baby-python
python
import sys import time import json import theano import theano.tensor as T import numpy as np if __name__=='__main__': data_location = sys.argv[1] print 'thinking' class Layer(object): ''' The base layer object. an artificial neural network is composed of many of these objects connected. ...
nilq/baby-python
python
from unittest import TestCase from nestor_api.adapters.git.github_git_provider import GitHubGitProvider from nestor_api.adapters.git.provider import get_git_provider class TestProvider(TestCase): def test_get_git_provider_with_github(self): git_provider = get_git_provider({"git": {"provider": "github"}})...
nilq/baby-python
python
import tensorflow as tf def conv(filters, kernel_size, strides = 1, padding = "same", use_bias = True, kernel_initializer = "he_normal", **kwargs): return tf.keras.layers.Conv2D(filters, kernel_size, strides = strides, padding = padding, use_bias = use_bias, kernel_initializer = kernel_initializer, **kwargs) clas...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """integration pytests for :mod:`graypy` .. note:: These tests require an local instance of Graylog to send messages to. """ import requests def validate_local_graylog_up(): """Test to see if a localhost instance of Graylog is currently running""" try: ...
nilq/baby-python
python
import petsc4py import sys petsc4py.init(sys.argv) from petsc4py import PETSc def PCDKSPsetup(F, Q, A): # OptDB = PETSc.Options() # OptDB['pc_hypre_type'] = 'boomeramg' # OptDB['pc_hypre_boomeramg_strong_threshold'] = 0.5 # OptDB['pc_hypre_boomeramg_grid_sweeps_all'] = 1 kspF = PETSc.KSP() ...
nilq/baby-python
python
""" Reasoner based on the 'model theory' by Guerth: https://github.com/CognitiveComputationLab/cogmods/blob/master/modal/student_projects/2019_guerth/models/mmodalsentential/reasoner.py Modified by Kaltenbl for propositional reasoning """ import numpy as np from .assertion_parser import parse_all, facts from .model_bu...
nilq/baby-python
python
def find(db, user): """ find the notelist :param db: :param user: :return: """ document = db.notelist.find_one({"_id": user}) return document def find_all_lists(db, user): """ It finds all lists :param db: :param user: :return: """ document = db.notelist.fin...
nilq/baby-python
python
# -*- coding: utf-8 -*- from .dataObject import DataObject from .muscle import Muscle from .cell import Cell from .network import Network class Worm(DataObject): """ A representation of the whole worm. All worms with the same name are considered to be the same object. Attributes ---------- ...
nilq/baby-python
python
# This code is available under the MIT License. # (c)2010-2011 Nakatani Shuyo / Cybozu Labs Inc. # (c)2018-2019 Hiroki Iida / Retrieva Inc. import nltk import re import MeCab stopwords_list = nltk.corpus.stopwords.words('english') recover_list = {"wa":"was", "ha":"has"} wl = nltk.WordNetLemmatizer() def load_corpu...
nilq/baby-python
python
#coding=utf8 import logging import logging.handlers import time from django.conf import settings from django.core.management.base import BaseCommand import django_rq from redis_cache import get_redis_connection from dbss.cardspace.models import warp_update_index from dbss.daemonize import Daemonize def test(): ...
nilq/baby-python
python
from numpy import interp def rangeMap(num): return int(interp(num,[-32768,32768],[1,10])) while 1: print(rangeMap(int(input())))
nilq/baby-python
python
""" @brief test log(time=0s) """ import os import unittest from pyquickhelper.loghelper import fLOG from pyquickhelper.pycode import check_pep8 class TestCodeStyle(unittest.TestCase): def test_code_style_src(self): fLOG( __file__, self._testMethodName, OutputPrin...
nilq/baby-python
python
#!/usr/bin/env python # encoding: utf-8 """ Run the talus worker daemon, specifying the maximum number of cores to use, the maximum RAM available for the VMs, the AMQP host to connect to, and a plugins directory. """ # system imports import argparse import math import multiprocessing import os import sys # local i...
nilq/baby-python
python
from __future__ import annotations from dataclasses import is_dataclass, fields, MISSING from typing import Any def nub(x: Any) -> dict[str, Any]: assert is_dataclass(x) out: dict[str, Any] = {} for f in fields(x): a = getattr(x, f.name) if ( isinstance(a, dict | set | list) ...
nilq/baby-python
python
#! /usr/bin/env python # """CLI wrapper script, ensures that relative imports work correctly in a PyInstaller build""" from isolyzer.isolyzer import main if __name__ == '__main__': main()
nilq/baby-python
python
from io import StringIO from collections import UserDict, UserList import numpy as np import confiddler.json as json def test(): """ Our drop-in json replacement can encode custom mappings and sequences, and also numpy arrays. """ d = UserDict() d['l'] = UserList([1,2,3]) d['a'] = np.aran...
nilq/baby-python
python
from rick_roll_detector.image import verify_image import cv2 # vid_cap has to be a cv2.VideoCapture() def verify_video(vid_cap: cv2.VideoCapture) -> bool: success, image = vid_cap.read() while success: success, image = vid_cap.read() # If the video ended return false. if not success: ...
nilq/baby-python
python
from src.bsl_python.preprocessing.experiments.experiment import Experiment from src.bsl_python.preprocessing.processor.spiking_activity import DefaultSpikingActivity, MeanFilteredActivity, \ FilteredActivity from src.bsl_python.preprocessing.processor.tuning_curve import TuningCurve from collections import Counter ...
nilq/baby-python
python
#!/usr/bin/env python import rospy from std_msgs.msg import Bool from dbw_mkz_msgs.msg import ThrottleCmd, SteeringCmd, BrakeCmd, SteeringReport from geometry_msgs.msg import TwistStamped import math from twist_controller import Controller ''' You can build this node only after you have built (or partially built) th...
nilq/baby-python
python
#!/usr/bin/env python2 """Utilities for training.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import datetime import numpy as np from caffe2.python import utils as c2_py_utils from caffe2.python import workspa...
nilq/baby-python
python
import json AppSettings = dict() with open('app.config') as json_data: for k, v in json.load(json_data).items(): AppSettings[k] = v
nilq/baby-python
python
# assign this folder as a namespace __path__ = __import__('pkgutil').extend_path(__path__, __name__) # __all__ = ['flow']
nilq/baby-python
python
from os.path import expanduser, exists from ansible.parsing.vault import VaultLib, VaultSecret from yaml import load, SafeLoader class VaultReader: """ Read data from a vault file. """ def __init__(self, vault_file, vault_pass): """ Create a vault reader. :param vault_file: ...
nilq/baby-python
python
import pymongo import os def get_mongo_config(): config = { 'username':os.environ['MDBUSR'], 'password':os.environ['MDBPWD'], 'host':'mongo', 'port':27017, } return config def connect_to_mongodb(): config = get_mongo_config() try: mc = pymongo.MongoCl...
nilq/baby-python
python
from typing import List, Sequence def remove_redundant_fao_area_codes(s: Sequence[str]) -> List[str]: """Filters the input sequence of FAO areas to keep only the smallest non overlapping areas. This is useful to prune lists of FAO areas that result from intersecting a geometry (ports, vessel position...
nilq/baby-python
python
# Skill pour demander au robot de nous guider import core.robot as robot from core.skills.ArgSkill import ArgSkill from core.communication import * with open('core/map.json', encoding='utf-8') as data_file: map = json.load(data_file) phrases = [ "guide moi", "amène moi", "amene moi", "emmene moi"...
nilq/baby-python
python
import math import sys import time import pybullet as p import pybullet_data import model as m import util as ut BOUNCE = "bounce" ROLL = "roll" TIME_STEP_S = 0.01 def configPyBullet(): physicsClient = p.connect(p.GUI) p.setAdditionalSearchPath(pybullet_data.getDataPath()) # used by loadURDF p.resetSi...
nilq/baby-python
python
import datetime as dt import json from json import encoder import xarray as xr import numpy as np from pandas import to_datetime from collections import OrderedDict import dateutil import logging import six logging.basicConfig() encoder.FLOAT_REPR = lambda o: format(o, '.4f').rstrip('0').rstrip('.') AXIS_VAR=['time'...
nilq/baby-python
python
A, B = int(input()), int(input()) if A * B > 0: print(2 * max(abs(A), abs(B))) else: print(2 * abs(A) + 2 * abs(B))
nilq/baby-python
python
from Crypto.Cipher import AES from base64 import b64encode, b64decode BLOCK_SIZE = 16 PADDING = '{' pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING def encrypt(key, msg): cipher = AES.new(pad(key).encode('utf-8')) return b64encode(cipher.encrypt(pad(msg))).decode('utf-8') def decrypt(key, msg): ...
nilq/baby-python
python
"""Doxygen module. Create project's documentation. Website: http://www.doxygen.org """ import os def doxygen(loader, project=None, variant=None, *args): #pylint:disable=keyword-arg-before-vararg loader.setup_project_env(project, variant) loader.setup_virtualenv() loader.setup_shell_env() config = loa...
nilq/baby-python
python
import sys sys.path.insert(0, '..') import numpy as np import pandas as pd from itertools import combinations from scipy.stats import binom import scipy.special import matplotlib.pyplot as plt import matplotlib.patches as mpatches from IPython.display import display, HTML #sys.path.append("../") from FrameBuilder.eige...
nilq/baby-python
python
#!/usr/bin/env python3 import math import torch from torch.distributions import MultivariateNormal as TMultivariateNormal from torch.distributions.kl import register_kl from torch.distributions.utils import _standard_normal, lazy_property from .. import settings from ..lazy import LazyTensor, lazify from .distributi...
nilq/baby-python
python
import torch from torch.utils.data import DataLoader import torchvision from torchvision.transforms import ToTensor from appfl.misc.data import * DataSet_name = "MNIST" num_channel = 1 # 1 if gray, 3 if color num_classes = 10 # number of the image classes num_pixel = 28 # image size = (num_pixel, num_pixel) """...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys from shutil import copy import pyshanb from pyshanb.helper import windows, home, default_configfile try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python se...
nilq/baby-python
python
import os import time import queue import demomgr.constants as CNST from demomgr.filterlogic import process_filterstring, FILTERFLAGS from demomgr.helpers import readdemoheader from demomgr.threads.read_folder import ThreadReadFolder from demomgr.threads._threadsig import THREADSIG from demomgr.threads._base import _S...
nilq/baby-python
python
""" writen by stephen """ import os import numpy as np import tensorflow as tf from alexnet import AlexNet from datagenerator import ImageDataGenerator from datetime import datetime import glob from tensorflow.contrib.data import Iterator learning_rate = 1e-4 num_epochs = 100 # 代的个数 batch_size = 1024 dropout_rate = ...
nilq/baby-python
python
# -*- coding: utf-8 -*- # © 2016 Danimar Ribeiro, Trustcode # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from decimal import Decimal from datetime import date from datetime import datetime from unicodedata import normalize def normalize_str(string): """ Remove special characters and s...
nilq/baby-python
python
""" Test Runner class. Lets you setup testrail and run a bunch of tests one after the other """ import os,subprocess class Test_Runner_Class: "Test Runner class" def __init__(self,base_url='http://qxf2.com',testrail_flag='N',browserstack_flag='N',os_name='Windows',os_version='7',browser='firefox',browser_vers...
nilq/baby-python
python
import settings as S* from util import * import stress from genrig import * from graph import * from dist import * from numpy import * from scipy.linalg.basic import * from scipy.linalg.decomp import * v=8 d=2 E=array([[0,1],[0,2],[1,2],[1,4],[2,3],[2,5],[3,4],[3,7],[4,5],[5,6],[5,7],[6,7],[3,6],[0,4]], 'i') e=len(E) ...
nilq/baby-python
python
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def hasCycle(self, head): """ :type head: ListNode :rtype: bool """ p1 = head p2 = head # ...
nilq/baby-python
python
import os # Dates DATE_FORMAT: str = "%Y-%m-%d" # Default date format TIMESTAMP_FORMAT: str = '%Y-%m-%d %H:%M:%S.%f' # Default timestamp format # Paths DATA_PATH: str = os.path.join( os.path.dirname(os.path.dirname(__file__)), "data") # Order VAT: float = 1.21 # VAT tax applied in Order ORDER_TYPES = ['sale',...
nilq/baby-python
python
################################################################################### # # # Workflow logic will be coded here, just to get rid of dirty code in the models. # # ...
nilq/baby-python
python
def getStatusMessage(statusCode, default="Unknown status"): # TODO Add docs if not isinstance(statusCode, int): raise TypeError("Status code must be int") return { 100: 'Continue', 101: 'Switching Protocols', 102: 'Processing', 200: 'OK', 201: 'Created', ...
nilq/baby-python
python
n = int(input()) S = input() T = input() result = 0 for i in range(n): if S[i] != T[i]: result += 1 print(result)
nilq/baby-python
python
from django.core import validators from django.db import models from django.db.models.aggregates import Max from django.db.models.base import Model from django.core.validators import RegexValidator class entry(models.Model): pilot_name = models.CharField(max_length=200, blank=False, default="John Doe") pilot_i...
nilq/baby-python
python
# Generated by Django 3.1.13 on 2021-11-16 14:57 from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): dependencies = [ ('analysis', '0016_auto_20211115_0020'), ] operations = [ migrations.AlterField( mod...
nilq/baby-python
python
from __init__ import __version__ as version from __init__ import __author__ as author import requests author_name = requests.get("https://estra-api.herokuapp.com/ShowroomPY").json()["Author"] if author != author_name: print("Error: Incorrect author. Please do not change any of these attributes.") else: pass ...
nilq/baby-python
python
# Yes python, it's a package
nilq/baby-python
python
from typing import NoReturn from cryspy.A_functions_base.function_1_objects import \ form_items_by_dictionary from cryspy.B_parent_classes.cl_1_item import ItemN from cryspy.B_parent_classes.cl_2_loop import LoopN class Chi2(ItemN): """ Choise of the experimental data for the refinement procedure. ...
nilq/baby-python
python
#!/usr/bin/python3 import sys import json import queue import requests import threading import subprocess from .logger import log from .cmd_args import args from .test_utils import last_message_as_json, ws_to_http class CliWalletException(Exception): def __init__(self, _message): self.message = _me...
nilq/baby-python
python
def escreva(mens): t=len(m) print(f'~'*t) print(f'{mens}') print(f'~' * t) m=str(input('Quala Mensagem ? : ')) escreva(m)
nilq/baby-python
python
from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status, viewsets from profiles_api import serializer, models class HelloApiView(APIView): """Test API View""" serializer_class = serializer.HelloSerializer ...
nilq/baby-python
python
""" [caption] def=Cutting URL parameters ja=URLパラメータの切り取り """ import sys import io import tkinter import tkinter.ttk import tkinter.simpledialog import ctypes import ctypes.wintypes from urllib.parse import urlparse, parse_qsl, urlencode, urlunparse sys.stdin = io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8') sys...
nilq/baby-python
python
# coding: utf-8 from __future__ import unicode_literals from django.test import TestCase class ComputeIntersectionsTestCase(TestCase): def test_command(self): pass # @todo
nilq/baby-python
python
#!/usr/bin/env python # ---------------------------------------------------------------------------- # Copyright 2015-2016 Nervana Systems Inc. # 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 #...
nilq/baby-python
python
"""Define resize, blur, and related constants.""" from . import io from collections import namedtuple from numba import guvectorize import math import numpy as np RowOps = namedtuple('RowOps', 'tindices sindices fweights'.split()) GAUSSIAN_SCALE = 1.0 / np.sqrt(0.5 * np.pi) def hermite(x): x = np.clip(x, 0, 1) ...
nilq/baby-python
python
# Generic imports import os import random import shutil from datetime import datetime # Imports with probable installation required try: import progress.bar except ImportError: print('*** Missing required packages, I will install them for you ***') os.system('pip3 install progress') import progress.b...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Created on Tue Nov 2 10:54:54 2021 @author: po-po """ import numpy as np import matplotlib.pyplot as plt import pandas as pd import os #filename = r'C:\Users\po-po\Desktop\DOC\Fibras\Programas\data\dr2todr4e01121121.csv' filename = r'C:\Users\po-po\Desktop\DOC\Fibras\Program...
nilq/baby-python
python
# Copyright (c) 2022 Aiven, Helsinki, Finland. https://aiven.io/ import sys from unittest import mock import pytest from pghoard import postgres_command def test_restore_command_error(): with mock.patch("pghoard.postgres_command.http_request", return_value=500): with pytest.raises(postgres_command.PGCE...
nilq/baby-python
python
# This file is part of the Reference Data Repository (refdata). # # Copyright (C) 2021 New York University. # # refdata is free software; you can redistribute it and/or modify it under the # terms of the MIT License; see LICENSE file for more details. """Loader implementation for datasets that are given in Json format...
nilq/baby-python
python
from django.test import TestCase from whats_fresh.whats_fresh_api.models import Video from django.contrib.gis.db import models class VideoTestCase(TestCase): def setUp(self): self.expected_fields = { 'video': models.URLField, 'caption': models.TextField, 'name': models...
nilq/baby-python
python
import os import json import torch import numpy as np from PIL import Image import copy import os import logging from detectron2.data import detection_utils as utils from ..registry import DATASOURCES from .load_coco import load_coco_json @DATASOURCES.register_module class COCO_BOXES(object): def __init__(self,...
nilq/baby-python
python
from __future__ import absolute_import, division, print_function import os from pdfx import cli # import pytest curdir = os.path.dirname(os.path.realpath(__file__)) def test_cli(): parser = cli.create_parser() parsed = parser.parse_args(['-j', 'pdfs/valid.pdf']) assert parsed.json assert parsed.pdf ...
nilq/baby-python
python
#!/usr/bin/env python # # This script is experimental. # # Liang Wang @ Dept. Computer Science, University of Helsinki # 2011.09.21 # import os, sys import socket import pickle import random import Queue import time import threading import resource from khash import * from bencode import bencode, bdecode from common...
nilq/baby-python
python
import itertools import json import logging import os import subprocess import sys import warnings from collections import OrderedDict from pathlib import Path import click import pip_api import requests from cachecontrol import CacheControl # from pipdownload.settings import SETTINGS_FILE from pipdownload import logg...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Copyright (C) 2013-2017 Oliver Ainsworth # Modifications (remove py2) by (C) Stefan Tapper 2021 import enum import itertools import rf2settings.valve from rf2settings.valve import messages, util REGION_US_EAST_COAST = 0x00 REGION_US_WEST_COAST = 0x01 REGION_SOUTH_AMERICA = 0x02 REGION_EUROP...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: UTF-8 -*- import os import platform import re from setuptools import setup, Extension python_version = platform.python_version() system_name = platform.system() print("build for python{} on {}".format(python_version, system_name)) # Arguments actrie_dir = "" alib_dir = "" def ge...
nilq/baby-python
python
# @author kingofthenorth # @filename problemsearch.py # @description Assignment 2 # @class CS 550 # @instructor Roch # @notes N/A from collections import deque from basicsearch_lib02.queues import PriorityQueue from basicsearch_lib02.searchrep import (Node, Problem) from explored import Exp...
nilq/baby-python
python
# @name: Katana-DorkScanner # @repo: https://github.com/adnane-X-tebbaa/Katana # @author: Adnane-X-tebbaa (AXT) # Scada-file V2.2 # I used dorks for the most used PLCs """ MIT License Copyright (c) 2020 adnane tebbaa Permission is hereby granted, free of charge, to any person obtaining a copy of t...
nilq/baby-python
python
import sqlite3 from functools import partial import multiprocessing as mp def create(args): p,name,sql = args db = sqlite3.connect(name) db.execute(sql) class mydb: def __init__(self, w): self.pool = mp.Pool(w) def create(self, tab, name_tmpl, parts=[0]): sql = 'create table if not exists {}'.format(tab) ...
nilq/baby-python
python
#!/usr/bin/env python """ Hacky script for comparing output set to gold set. Usage: just run python compare_solution.py -h """ import argparse import fileinput import sys import re def compare_sets(s1, s2): """Compare the sets.""" if len(s1) != 0: # return s1 == s2 return s1 - s2 return ...
nilq/baby-python
python
import logging from airflow.decorators import dag, task from datetime import datetime, timedelta from airflow.utils.dates import days_ago from airflow.providers.amazon.aws.operators.dms_create_task import DmsCreateTaskOperator from airflow.providers.amazon.aws.operators.dms_start_task import DmsStartTaskOperator from ...
nilq/baby-python
python
import numpy as np s = '''73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 ...
nilq/baby-python
python
# step: build the vectorizer for year_month + general, f > 2, ngram = 3 # import os from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.linear_model import SGDClassifier import numpy as np import pickle from sklearn.metrics import classification_report, f1_score from scipy.sparse import lil_matrix...
nilq/baby-python
python
# --------------------------------------------------------------------------- # import os import filecmp from arroyo import utils import pytest # --------------------------------------------------------------------------- # # Asymmetric Key Tests from arroyo.crypto import KeyAlgorithmType, EncodingType from arr...
nilq/baby-python
python
""" Copyright 2020 The OneFlow Authors. 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 by applicable law or agr...
nilq/baby-python
python
def solution(arrows): answer = 0 coorL = [[0,0]] for each in arrows: if each == 0: a = [int(coorL[-1][0]), int(coorL[-1][1])+1] elif each == 1: a = [int(coorL[-1][0])+1, int(coorL[-1][1])+1] elif each == 2: a = [int(coorL[-1][0])+1, int(coorL[-1...
nilq/baby-python
python