content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
import topologylayer.nn import topologylayer.functional from topologylayer.functional.persistence import SimplicialComplex
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Created on Mon Jan 27 08:01:36 2020 @author: Ardhendu """ # -*- coding: utf-8 -*- """ Created on Thu Dec 13 10:33:32 2019 @author: Ardhendu """ from keras.layers import Layer #from keras import layers from keras import backend as K import tensorflow as tf #from Spectr...
nilq/baby-python
python
from typing import Union, List, Optional from pyspark.sql.types import ( StructType, StructField, StringType, ArrayType, DateType, DataType, ) # This file is auto-generated by generate_schema so do not edit manually # noinspection PyPep8Naming class DeviceSchema: """ This resource ide...
nilq/baby-python
python
# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved. import dace import numpy as np from dace.frontend.python.common import DaceSyntaxError @dace.program def for_loop(): A = dace.ndarray([10], dtype=dace.int32) A[:] = 0 for i in range(0, 10, 2): A[i] = i return A def ...
nilq/baby-python
python
import WebArticleParserCLI urls = ['http://lenta.ru/news/2013/03/dtp/index.html', 'https://lenta.ru/news/2017/02/11/maroder/', 'https://lenta.ru/news/2017/02/10/polygon/', 'https://russian.rt.com/world/article/358299-raketa-koreya-ssha-yaponiya-kndr-tramp', 'https://russian.rt.com/russia/news/358337-sk-proverka-gibel-...
nilq/baby-python
python
# # ida_kernelcache/build_struct.py # Brandon Azad # # A module to build an IDA structure automatically from code accesses. # import collections import idc import idautils import idaapi from . import ida_utilities as idau _log = idau.make_log(3, __name__) def field_name(offset): """Automatically generated IDA ...
nilq/baby-python
python
#! /usr/bin/python # -*- coding: utf-8 -*- # # data_test.py # Jun/05/2018 # --------------------------------------------------------------- import cgi import json # --------------------------------------------------------------- form = cgi.FieldStorage() # message = [] data_in = "" message.append("start") # if "ar...
nilq/baby-python
python
import numpy as np IS_AUTONOMOUS = False X_TARGET = 2.0 Y_TARGET = 2.0 STOP_THRESHOLD = 0.03 # Unit: m ROBOT_MARGIN = 130 # Unit: mm THRESHOLD = 3.6 # Unit: m MIN_THRESHOLD = 0.1 THRESHOLD_STEP = 0.25 THRESHOLD_ANGLE = 95 # Unit: deg, has to be greater than 90 deg ANG...
nilq/baby-python
python
# -*- coding: utf-8 -*- def relu(name, bottom, top, type="ReLU"): layer = "layer {\n" layer += " name: \"" + name + "\"\n" if type not in ["ReLU", "ReLU6", "CReLU"]: raise Exception("unknown relu: %s" % type) layer += " type: \"" + type + "\"\n" layer += " bottom: \"" + bottom + "\"\n" ...
nilq/baby-python
python
# Вступление # В этом руководстве вы узнали, как создать достаточно интеллектуального агента с помощью алгоритма минимакса. В # этом упражнении вы проверите свое понимание и представите своего агента для участия в конкурсе. # 1) Присмотритесь # Эвристика из учебника рассматривает все группы из четырех соседних местопо...
nilq/baby-python
python
# Copyright 2017 Insurance Australia Group Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
nilq/baby-python
python
import translate, command while 1: b=raw_input(">>>") a=open("console.txt","w") a.write(b) a.close() print(command.run(b))
nilq/baby-python
python
import xmlrpclib from tornado.options import options from ate_logger import AteLogger class BaseXmlRpcProcess(object): def __init__(self): self.logger = AteLogger('XmlRpcProcess') self._tf_status = False def status(self): self.logger.debug('Calling status') traceback = None ...
nilq/baby-python
python
import dash_core_components as dcc import dash_html_components as html import dash_bootstrap_components as dbc from plotly.subplots import make_subplots import plotly.graph_objects as go import plotly.express as px import price_loader as pl import spy_investments as spy from datetime import datetime import pandas a...
nilq/baby-python
python
from gym_network_intrusion.envs.network_intrusion_env_1 import NetworkIntrusionEnv from gym_network_intrusion.envs.network_intrusion_extrahard_env_1 import NetworkIntrusionExtraHardEnv
nilq/baby-python
python
from koans_plugs import * def test_has_true_literal(): """ У логического типа есть литерал, обозначающий истину """ a = True # попробуйте такие варианты: TRUE, true, True assert a def test_has_false_literal(): """ У логического типа есть литерал, обозначающий ложь """ a ...
nilq/baby-python
python
import csv import cv2 import numpy as np import re np.random.seed(0) # Load data csv file def read_csv(file_name): lines = [] with open(file_name) as driving_log: reader = csv.reader(driving_log) next(reader, None) for line in reader: lines.append(line) return lines ...
nilq/baby-python
python
from copy import deepcopy import json import os from uuid import uuid4 import pytest from starlette.testclient import TestClient from hetdesrun.utils import get_uuid_from_seed from hetdesrun.service.webservice import app from hetdesrun.models.code import CodeModule from hetdesrun.models.component import ( Comp...
nilq/baby-python
python
''' Title : Day 25: Running Time and Complexity Domain : Tutorials Author : Ahmedur Rahman Shovon Created : 03 April 2019 ''' def is_prime(n): if n == 2: return True if n%2 == 0 or n < 2: return False max_limit = int(n**0.5) + 1 for i in range(3, max_limit): i...
nilq/baby-python
python
from cassandra.cluster import Cluster def create_connection(): # TO DO: Fill in your own contact point cluster = Cluster(['127.0.0.1']) return cluster.connect('demo') def set_user(session, lastname, age, city, email, firstname): # TO DO: execute SimpleStatement that inserts one user into the table ...
nilq/baby-python
python
""" Tests for todos module """ import random import string from django.test import TestCase DEFAULT_LABELS = [ 'low-energy', 'high-energy', 'vague', 'work', 'home', 'errand', 'mobile', 'desktop', 'email', 'urgent', '5 minutes', '25 minutes', '60 minutes', ] class ...
nilq/baby-python
python
from .singleton import Singleton from .visitor import visitor
nilq/baby-python
python
#!/usr/bin/env python #-*- coding:utf-8 -*- import tornado.httpserver import tornado.ioloop import tornado.web import tornado.options import tornado.gen import os.path from tornado.options import define, options from cache_module import CacheHandler define("port", default=8888, help="run on the given port", type=int)...
nilq/baby-python
python
""" Exposes commonly used classes and functions. """ from .bencode import Bencode from .torrent import Torrent from .utils import upload_to_cache_server, get_open_trackers_from_local, get_open_trackers_from_remote
nilq/baby-python
python
import numpy as np import re #------------------------------------------------------------------------------ """ Correct positions in the vicon data to center on the middle of the enclosure. This is due to inexact positioning of the enclosure and/or the wand during motion capture, so this is only necessary to perform ...
nilq/baby-python
python
import csv import sys import urllib3 import json from urllib.parse import quote METAMAP = 'https://knowledge.ncats.io/ks/umls/metamap' DISAPI = 'https://disease-knowledge.ncats.io/api' DISEASE = DISAPI + '/search' def parse_disease_map (codes, data): if len(data) > 0: for d in data: if 'I_CODE...
nilq/baby-python
python
## # @file elasticsearch.py # @author Lukas Koszegy # @brief Elasticsearch klient ## from elasticsearch import Elasticsearch import json from time import time from database.schemes.mapping import mappingApp, mappingEvent import logging class ElasticsearchClient(): def __init__(self, host="127.0.0.1", port=9200, ss...
nilq/baby-python
python
from argparse import ArgumentParser import numpy as np import pytorch_lightning as pl from scipy.io import savemat from torch.utils.data import DataLoader from helmnet import IterativeSolver from helmnet.dataloaders import get_dataset class Evaluation: def __init__(self, path, testset, gpus): self.path ...
nilq/baby-python
python
import cv2 import numpy as np import pandas as pd date=datetime.datetime.now().strftime("%d/%m/20%y") faceDetect = cv2.CascadeClassifier("C:/Users/Administrator/Desktop/haarcascade_frontalface_default.xml") cam = cv2.VideoCapture(0) rec = cv2.face.LBPHFaceRecognizer_create() rec.read("C:/Users/Administrator/Desk...
nilq/baby-python
python
import numpy as np import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable import time import os import shutil import copy import datetime from layers import ConvNet import network_operators import utils # hyperparameters mutation_time_limit_hours = 23 n_models = 8 # ...
nilq/baby-python
python
import subprocess , os from tkinter import messagebox from tkinter import filedialog class Cmd: def __init__(self,tk, app): self.app = app self.tk = tk self.default_compileur_path_var = os.path.join(os.path.dirname(os.path.abspath(__file__)), "dart-sass\\sass.bat") self.opt...
nilq/baby-python
python
import math from typing import Optional import torch from torch import nn, Tensor from torch.autograd import grad from torch.nn import functional as F from adv_lib.utils.visdom_logger import VisdomLogger def ddn(model: nn.Module, inputs: Tensor, labels: Tensor, targeted: bool = False, ...
nilq/baby-python
python
#!/usr/bin/python def get_memory(file_name): # vmstat #procs - ----------memory - --------- ---swap - - -----io - --- -system - - ------cpu - ---- # r;b; swpd;free;buff;cache; si;so; bi;bo; in;cs; us;sy;id;wa;st memory_swpd = list() memory_free = list() memory_buff = ...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ from odoo.exceptions import ValidationError class CouponReward(models.Model): _name = 'coupon.reward' _description = "Coupon Reward" _rec_name = 'reward_description' ...
nilq/baby-python
python
""" ===================== Configuration Manager ===================== """ import os from configparser import ConfigParser from typing import Optional, Dict, TypeVar, Callable from PySide2 import QtWidgets WIDGET = TypeVar('QWidget') ######################################################################## class Con...
nilq/baby-python
python
import json import yaml from flask import jsonify, Blueprint, redirect from flask_restless import APIManager from flask_restless.helpers import * sqlalchemy_swagger_type = { 'INTEGER': ('integer', 'int32'), 'SMALLINT': ('integer', 'int32'), 'NUMERIC': ('number', 'double'), 'DECIMAL': ('number', 'doubl...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Created on Tue Jul 24 12:35:04 2018 @author: Matthias N. """ import requests from bs4 import BeautifulSoup from fake_useragent import UserAgent import asyncio import concurrent.futures import json, codecs async def speedcrawl(pages): data = [] for p in range(...
nilq/baby-python
python
from .src import dwarfgen def process(*args, **kwargs): return dwarfgen.process(*args, **kwargs)
nilq/baby-python
python
import tesseract api = tesseract.TessBaseAPI() api.SetOutputName("outputName"); api.Init("E:\\Tesseract-OCR\\test-slim","eng",tesseract.OEM_DEFAULT) api.SetPageSegMode(tesseract.PSM_AUTO) mImgFile = "eurotext.jpg" pixImage=tesseract.pixRead(mImgFile) api.SetImage(pixImage) outText=api.GetUTF8Text() print("OCR output:\n...
nilq/baby-python
python
import math import torch from torch import Tensor from .optimizer import Optimizer from typing import List, Optional class RAdam(Optimizer): r"""Implements RAdam algorithm. .. math:: \begin{aligned} &\rule{110mm}{0.4pt} \\ ...
nilq/baby-python
python
""" Author: Darren Date: 30/05/2021 Solving https://adventofcode.com/2016/day/6 Part 1: Need to get most frequent char in each column, given many rows of data. Transpose columns to rows. Find the Counter d:v that has the max value, keyed using v from the k,v tuple. Part 2: As part 1, but using mi...
nilq/baby-python
python
from flask import Flask, render_template, redirect from flask_pymongo import PyMongo, ObjectId from flask_wtf import FlaskForm from wtforms import StringField, SubmitField from wtforms.validators import ValidationError, URL app = Flask(__name__) app.config['SECRET_KEY'] = 'test' app.config["MONGO_URI"] = "mongodb://14...
nilq/baby-python
python
"""added date_read_date Revision ID: a544d948cd1b Revises: 5c5bf645c104 Create Date: 2021-11-28 20:52:31.230691 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'a544d948cd1b' down_revision = '5c5bf645c104' branch_labels = None depends_on = None def upgrade()...
nilq/baby-python
python
from django.contrib.auth import get_user_model from django.test import TestCase from src.activities.models import Activity from src.questions.models import Question, Answer class QuestionVoteTest(TestCase): def setUp(self): self.user = get_user_model().objects.create_user( username='test_user...
nilq/baby-python
python
#!/usr/bin/env python import astropy.units as u from typing import Union from dataclasses import dataclass, field, is_dataclass from cached_property import cached_property import copy from typing import ClassVar from schema import Or from tollan.utils.dataclass_schema import add_schema from tollan.utils.log import ge...
nilq/baby-python
python
from hashlib import md5 def mine(secret: str, zero_count=5) -> int: i = 0 target = '0' * zero_count while True: i += 1 dig = md5((secret + str(i)).encode()).hexdigest() if dig.startswith(target): return i if __name__ == '__main__': key = 'bgvyzdsv' print(f'Par...
nilq/baby-python
python
import json import os def setAccount( persAcc, money, input=True ): rez = True if input == True: persAcc += money else: if persAcc < money: rez = False else: persAcc -= money return persAcc, rez # ********************************************** def setH...
nilq/baby-python
python
# Databricks notebook source import pandas as pd import random # COMMAND ---------- # columns = ['id','amount_currency','amount_value','channel','deviceDetails_browser', # 'deviceDetails_device','deviceDetails_deviceIp','merchantRefTransactionId','paymentMethod_apmType', # 'paymentMethod_cardNum...
nilq/baby-python
python
import numpy as np import cv2 def handle_image(input_image, width=60, height=60): """ Function to preprocess input image and return it in a shape accepted by the model. Default arguments are set for facial landmark model requirements. """ preprocessed_image = cv2.resize(input_image, (width, height...
nilq/baby-python
python
class Solution: def isPalindrome(self, x: int) -> bool: if x < 0 or (x != 0 and x % 10 == 0): return False res = 0 # 1221 while x > res: res *= 10 res += x % 10 x //= 10 if x == res or x == res // 10: return True ...
nilq/baby-python
python
from model.contact import Contact from random import randrange def test_delete_some_contact(app): app.contact.ensure_contact_exists(Contact(fname="contact to delete")) old_contacts = app.contact.get_contact_list() index = randrange(len(old_contacts)) app.contact.delete_contact_by_index(index) asse...
nilq/baby-python
python
""" Number Mind """
nilq/baby-python
python
#!/usr/bin/env python3 # Up / Down ISC graph for ALL bins # Like SfN Poster Figure 2 # But now for all ROIs in Yeo atlas import tqdm import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import deepdish as dd from HMM_settings import * ISCdir = ISCpath+'shuff_Yeo_outlier_' figdir = figurepath+'up...
nilq/baby-python
python
""" Created Aug 2020 @author: TheDrDOS """ # Clear the Spyder console and variables try: from IPython import get_ipython #get_ipython().magic('clear') get_ipython().magic('reset -f') except: pass from time import time as now from time import perf_counter as pnow import pickle import numpy as np impo...
nilq/baby-python
python
# -*- coding: utf-8 -*- import cv2 # トラックバーの値を変更する度にRGBを出力する def changeColor(val): r_min = cv2.getTrackbarPos("R_min", "img") r_max = cv2.getTrackbarPos("R_max", "img") g_min = cv2.getTrackbarPos("G_min", "img") g_max = cv2.getTrackbarPos("G_max", "img") b_min = cv2.getTrackbarPos("B_min", "img") ...
nilq/baby-python
python
# Developed by Joseph M. Conti and Joseph W. Boardman on 1/21/19 6:29 PM. # Last modified 1/21/19 6:29 PM # Copyright (c) 2019. All rights reserved. import logging import logging.config as lc import os from pathlib import Path from typing import Union, Dict import numpy as np from yaml import load class Singleto...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Resource object code # # Created by: The Resource Compiler for PyQt5 (Qt v5.15.0) # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore qt_resource_data = b"\ \x00\x00\x07\x10\ \x89\ \x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ \x00\x00\x40\x...
nilq/baby-python
python
#!/usr/bin/python # (c) 2018 Jim Hawkins. MIT licensed, see https://opensource.org/licenses/MIT # Part of Blender Driver, see https://github.com/sjjhsjjh/blender-driver """Path Store unit test module. Tests in this module can be run like: python3 path_store/test.py TestInterceptProperty """ # Exit if run other tha...
nilq/baby-python
python
from unittest.case import TestCase from responsebot.handlers.base import BaseTweetHandler from responsebot.handlers.event import BaseEventHandler try: from mock import MagicMock, patch except ImportError: from unittest.mock import MagicMock class Handler(BaseTweetHandler): class ValidEventHandler(BaseEv...
nilq/baby-python
python
# coding: utf-8 from cms.plugin_pool import plugin_pool from cms.plugin_base import CMSPluginBase from cmsplugin_bootstrap_grid.forms import ColumnPluginForm from cmsplugin_bootstrap_grid.models import Row, Column from django.utils.translation import ugettext_lazy as _ class BootstrapRowPlugin(CMSPluginBase): mod...
nilq/baby-python
python
from scipy import spatial from . import design from .design import * from .fields import * schema = dj.schema('photixxx') @schema class Tissue(dj.Computed): definition = """ -> design.Geometry --- density : float # points per mm^3 margin : float # (um) margin to include on boundaries min_dis...
nilq/baby-python
python
# Copyright 2017 The KaiJIN 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 ...
nilq/baby-python
python
import pandas as pd from plotly.subplots import make_subplots import plotly.graph_objects as go import modules.load_data_from_database as ldd from db import connect_db # connection with database rdb = connect_db() def day_figure_update(df, bar): """ Update day figure depends on drop downs """ df_bar = df[df...
nilq/baby-python
python
import threading import json from socketIO_client import SocketIO, LoggingNamespace class Cliente(): def __init__(self, ip): self.socketIO = SocketIO(ip, 8000) self.errors = '' #thread_rcv= threading.Thread () #thread_rcv.daemon=True #thread_rcv.start() ...
nilq/baby-python
python
import ctypes import os import warnings from ctypes import ( byref, c_byte, c_int, c_uint, c_char_p, c_size_t, c_void_p, create_string_buffer, CFUNCTYPE, POINTER ) from pycoin.encoding.bytes32 import from_bytes_32, to_bytes_32 from pycoin.intbytes import iterbytes SECP256K1_FLAGS_TYPE_MASK = ((1 << 8) - 1) SECP...
nilq/baby-python
python
from smach_based_introspection_framework.offline_part.model_training import train_anomaly_classifier from smach_based_introspection_framework._constant import ( anomaly_classification_feature_selection_folder, ) from smach_based_introspection_framework.configurables import model_type, model_config, score_metric imp...
nilq/baby-python
python
from collections import deque from time import perf_counter def breadthFirstSearch(initialState, goalState, timeout=60): # Initialize iterations counter. iterations = 0 # Initialize visited vertexes as set, because it's faster to check # if an item exists, due to O(1) searching complexity on average ...
nilq/baby-python
python
/home/runner/.cache/pip/pool/fd/94/44/56b7be5adb54be4e2c5a3aea50daa6f50d6e15a013102374ffe3d729b9
nilq/baby-python
python
import FWCore.ParameterSet.Config as cms def useTMTT(process): from L1Trigger.TrackerDTC.Producer_Defaults_cfi import TrackerDTCProducer_params from L1Trigger.TrackerDTC.Format_TMTT_cfi import TrackerDTCFormat_params from L1Trigger.TrackerDTC.Analyzer_Defaults_cfi import TrackerDTCAnalyzer_params Track...
nilq/baby-python
python
from datetime import timedelta import matplotlib.gridspec as gridspec import matplotlib.pyplot as plt import matplotlib.ticker as ticker import numpy as np from matplotlib import rcParams __author__ = 'Ben Dichter' class BrokenAxes: def __init__(self, xlims=None, ylims=None, d=.015, tilt=45, su...
nilq/baby-python
python
# Copyright 2014-2015 ARM Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in w...
nilq/baby-python
python
from sklearn.cluster import KMeans from sklearn.mixture import GaussianMixture from sklearn.cluster import DBSCAN from .MetadataExtractor import Extractor from .DataCleaner import cleaner, limited_cleaner from joblib import dump, load def predictor(extractor, name): data = cleaner(extractor).drop_duplicates...
nilq/baby-python
python
# Copyright (c) 2021, Manfred Moitzi # License: MIT License from typing import ( Iterable, List, TYPE_CHECKING, Tuple, Iterator, Sequence, Dict, ) import abc from typing_extensions import Protocol from ezdxf.math import ( Vec2, Vec3, linspace, NULLVEC, Vertex, inter...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/12/30 21:02 # @Author : WIX # @File : 青蛙跳.py """ 青蛙跳台阶, 每次可以跳1级或2级,求青蛙跳上一个n级的台阶一共有多少种跳法? 当n > 2时,第一次跳就有两种选择: 1. 第一次跳1级,后面的跳法相当于剩下n-1级的跳法,即f(n-1) 2. 第一次跳2级,后面的跳法相当于剩下n-2级的跳法,即f(n-2) 即f(n) = f(n-1) + f(n-2) """ class Solution(object): def jumpfrog...
nilq/baby-python
python
# coding: utf-8 # import models into model package from .error_enveloped import ErrorEnveloped from .health_check_enveloped import HealthCheckEnveloped from .inline_response200 import InlineResponse200 from .inline_response200_data import InlineResponse200Data from .inline_response201 import InlineResponse201 from .in...
nilq/baby-python
python
__author__ = 'Bohdan Mushkevych' from odm.document import BaseDocument from odm.fields import StringField, ObjectIdField, DateTimeField TIMEPERIOD = 'timeperiod' START_TIMEPERIOD = 'start_timeperiod' END_TIMEPERIOD = 'end_timeperiod' FLOW_NAME = 'flow_name' STATE = 'state' CREATED_AT = 'created_at' STARTED_AT = 'sta...
nilq/baby-python
python
''' This module generates charts from cohort.pickle rather than from the cumulative csvs. ''' import os import pandas as pd import matplotlib.pyplot as plt from plot_practice_charts import * from ethnicities import high_level_ethnicities wave_column_headings = { "total": "All", "all_priority": "Priority grou...
nilq/baby-python
python
# nxpy_svn -------------------------------------------------------------------- # Copyright Nicola Musatti 2010 - 2018 # Use, modification, and distribution are subject to the Boost Software # License, Version 1.0. (See accompanying file LICENSE.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) # See https://git...
nilq/baby-python
python
# -*- Python -*- # license # license. """ Files opening and reading/writing functions. """ import sys, os, bz2, lzma, json import logging; module_logger = logging.getLogger(__name__) # ====================================================================== def open_for_reading_binary(filename): """Opens binary fi...
nilq/baby-python
python
# get largest continues sum def pair_sum(arr, target): seen = set() output = set() for num in arr: diff = target - num if diff not in seen: print('adding diff',diff) seen.add(num) else: print('adding output',diff, seen) outpu...
nilq/baby-python
python
#!/usr/bin/env python """Archive Now for python""" # import pyhesity wrapper module from pyhesity import * from datetime import datetime # command line arguments import argparse parser = argparse.ArgumentParser() parser.add_argument('-v', '--vip', type=str, required=True) # cluster to connect to parser.add_argu...
nilq/baby-python
python
# https://www.hackerrank.com/challenges/sherlock-and-anagrams/problem def anagramPairs(s): # Write your code here dic = {} res = 0 for k in range(1, len(s)): for i in range(len(s)-k+1): j = i+k strr = "".join(sorted(s[i:j])) dic[strr] = dic.get(strr,0)+1 f...
nilq/baby-python
python
""" /****************************************************************************** * * * Name: mylogger.py * * ...
nilq/baby-python
python
#!/usr/bin/env python """Celery worker to be run as follows: (venv) $ celery worker -A pili.entrypoints.celery.celery --loglevel=info Environment variables (such as MAIL_SERVER, MAIL_USERNAME, etc.) should be set using export: (venv) $ export MAIL_SERVER=smtp.youserver.com 'export' keyword in bash sets a variable t...
nilq/baby-python
python
import asyncio import http import aiohttp.client import urllib.robotparser import datetime import collections import logging import abc logger = logging.getLogger(__name__) import site_graph class RequestQueue: """A queue of pending HTTP requests, that maintains a minimum interval between outgoing requests I...
nilq/baby-python
python
import numpy as np from scratch_ml.utils import covariance_matrix class PCA(): """A method for doing dimensionality reduction by transforming the feature space to a lower dimensionality, removing correlation between features and maximizing the variance along each feature axis.""" def transform(self, ...
nilq/baby-python
python
import logging import argparse from s3push.connector import resource from s3push.uploader import upload from s3push.eraser import erase parser = argparse.ArgumentParser( description='Upload directories and files to AWS S3') parser.add_argument( 'path', type=str, help='Path to a directory of file tha...
nilq/baby-python
python
# parses vcontrold serial data import struct from scapy.packet import Packet, bind_layers from scapy.fields import * START_BYTE = 0x41 TYPES = { 0x00: "request", 0x01: "response", 0x03: "error" } COMMANDS = { 0x01: "readdata", 0x02: "writedata", 0x07: "functioncall" } class VS2Header(Packet...
nilq/baby-python
python
import os def exists_or_create_directory(temp_path: str) -> None: directory = os.path.dirname(temp_path) try: os.stat(directory) except Exception as exp: os.mkdir(directory) print(str(exp) + f" -> {directory} created...")
nilq/baby-python
python
from collections import defaultdict raw_template = [] rules = [] with open("input") as file: raw_template = list(next(file).strip()) for line in file: line = line.strip() if not line: continue left, right = line.split("->") left = left.strip() right = right....
nilq/baby-python
python
# 쿼드압축 후 개수 세기 def quadtree(arr): l = len(arr) if l == 1: return [1,0] if arr[0][0] == 0 else [0,1] lu = quadtree([a[:l//2] for a in arr[:l//2]]) ru = quadtree([a[l//2:] for a in arr[:l//2]]) ld = quadtree([a[:l//2] for a in arr[l//2:]]) rd = quadtree([a[l//2:] for a in arr[l//2:]]) if l...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Created on Thu Nov 11 16:31:58 2021 @author: snoone """ import os import glob import pandas as pd pd.options.mode.chained_assignment = None # default='warn' OUTDIR3= "D:/Python_CDM_conversion/monthly/cdm_out/cdm_head" OUTDIR2= "D:/Python_CDM_conversion/monthly/cdm_out/cdm_ob...
nilq/baby-python
python
#EsmeeEllson #Help #Class Attributes #You can instantiate with AsciiTable(table_data) or AsciiTable(table_data, 'Table Title'). #These are available after instantiating AsciiTable. Name Description/Notes table_data = List of list of strings. Same object passed to __init__(). title = Table title string....
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Created on Thu Oct 21 18:32:33 2021 @author: User """ # Expresiones generadoras # El módulo itertools itertools.chain(s1,s2) itertools.count(n) itertools.cycle(s) itertools.dropwhile(predicate, s) itertools.groupby(s) itertools.ifilter(predicate, s) itertools.imap(function, s1, ... sN) ite...
nilq/baby-python
python
"""Implementation of the Unet in torch. Author: zhangfan Email: zf2016@mail.ustc.edu.cn data: 2020/09/09 """ import torch import torch.nn as nn from network.blocks.residual_blocks import ResFourLayerConvBlock class UNet(nn.Module): """UNet network""" def __init__(self, net_args={"num_class": 1, ...
nilq/baby-python
python
import re from textwrap import dedent import black import autopep8 from pkg_resources import resource_string def get_snippet(name, decorator=True): 'Get a Python snippet function (as a string) from the snippets directory.' out = resource_string('matflow_defdap', f'snippets/{name}').decode() if not decor...
nilq/baby-python
python
# -*- coding:utf-8 -*- from timeit import default_timer import numpy as np import matplotlib.pyplot as plt from scipy.misc import face # Importing global thresholding algorithms from .global_th import otsu_threshold, p_tile_threshold,\ two_peaks_threshold, min_err_threshold # Importing global entropy threshold...
nilq/baby-python
python
#!/usr/bin/python import paho.mqtt.publish as publish import paho.mqtt.client as mqtt import ssl auth = { 'username':"ciscohackhub.azure-devices.net/lora1", 'password':"SharedAccessSignature sr=ciscohackhub.azure-devices.net%2Fdevices%2Flora1&sig=xxxx&se=1463048772" } tls = { 'ca_certs':"/etc/ssl/certs/ca-cert...
nilq/baby-python
python
def input1(type = int): return type(input()) def input2(type = int): [a, b] = list(map(type, input().split())) return a, b def input3(type = int): [a, b, c] = list(map(type, input().split())) return a, b, c def input_array(type = int): return list(map(type, input().split())) def input_string(): s = in...
nilq/baby-python
python
from sklearn.base import BaseEstimator, TransformerMixin import re class TextCleaner(BaseEstimator, TransformerMixin): ''' text cleaning : input can be str, list of sring, or pandas Series a minimal version, repacing only '\n' with ' ' ''' def __init__(self): print('') def f...
nilq/baby-python
python