content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
# Manipulating Python Lists # import math import os # Create a Python List # cars=["Toyota","Chevrolet","Ford","Honda","Brabus"] print(cars) # Basic Operations on Python List # # Arithmetic Operations on a Python List # # print(math.pi)
nilq/baby-python
python
""" ???+ note "Intermediate classes based on the functionality." """ import numpy as np from bokeh.models import CDSView, IndexFilter from bokeh.palettes import Category20 from bokeh.layouts import row from hover import module_config from hover.utils.misc import current_time from hover.utils.bokeh_helper import bokeh_h...
nilq/baby-python
python
########################################################################## # # Copyright (c) 2013, Image Engine Design 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: # # * Redistrib...
nilq/baby-python
python
import concurrent.futures class Epochs: def __init__(self, sfcContract, database): self.__sfcContract = sfcContract self.__database = database self.__data = [] def __getEpochValidator(self, epochId, validatorId): data = self.__sfcContract.getEpochValidator(epochId, validatorId...
nilq/baby-python
python
import matplotlib.pyplot as plt import umap import umap.plot from matplotlib.offsetbox import OffsetImage, AnnotationBbox import numpy as np def plot_umap(features, labels, save_path = None, annotation = False): ''' :param features: :param labels: :param save_path: :param annotation: dictionary, wi...
nilq/baby-python
python
from sys import stderr from queue import LifoQueue as stack from queue import PriorityQueue as p_queue from queue import SimpleQueue as queue import networkx as nx import pylab as plt from IPython.core.display import HTML, display, Image # import pygraphviz # from networkx.drawing.nx_agraph import graphviz_layout # ...
nilq/baby-python
python
from collections import OrderedDict import copy import json import io import yaml import os import progressbar import warnings warnings.filterwarnings("ignore", message="numpy.dtype size changed") warnings.filterwarnings("ignore", message="numpy.ufunc size changed") warnings.filterwarnings("ignore", message="Polyfit m...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Created on Mon Jan 19 11:23:32 2015 @author: Wasit """ mytuple=(1,2,3,'my tuple') print mytuple[-1]
nilq/baby-python
python
from typing import List class Solution: def maximumProduct(self, nums: List[int]) -> int: nums.sort(reverse = True) return max(nums[0] * nums[1] * nums[2], nums[0] * nums[-1] * nums[-2])
nilq/baby-python
python
def addition(firstNumber, secondNumber): answer = firstNumber + secondNumber return answer def subtraction(firstNumber, secondNumber): answer = firstNumber - secondNumber return answer def multiplication(firstNumber, secondNumber): answer = firstNumber * secondNumber return answer def divisio...
nilq/baby-python
python
import socket import struct # thrift does not support unsigned integers def hex_to_i16(h): x = int(h) if (x > 0x7FFF): x-= 0x10000 return x def i16_to_hex(h): x = int(h) if (x & 0x8000): x+= 0x10000 return x def hex_to_i32(h): x = int(h) if (x > 0x7FFFFFFF): x-= 0x100000000 return x...
nilq/baby-python
python
# the main optimization function def main(districts_orig, blocks_dict_orig): import numpy as np import statistics as st import random from classes import Block, SchoolDistr from copy import deepcopy current_best_cumul_zvalue = None current_best_distr_division = None ...
nilq/baby-python
python
__version__ = '0.15.2rc0'
nilq/baby-python
python
# Copyright (c) 2019 Erwin de Haan. 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 applic...
nilq/baby-python
python
#!/usr/bin/env python3 """ Send reports artifacts by email """ import logging import os import tempfile import zipfile from json.decoder import JSONDecodeError import requests from megalinter import Reporter, config class FileIoReporter(Reporter): name = "FILEIO" scope = "mega-linter" def __init__(self,...
nilq/baby-python
python
# Copyright 2019 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations from enum import Enum from typing import Iterable from pants.base import deprecated from pants.engine.rules import Rule, collect_rules, rule from pants...
nilq/baby-python
python
import cc_dat_utils #Part 1 input_dat_file = "data/pfgd_test.dat" #Use cc_dat_utils.make_cc_data_from_dat() to load the file specified by input_dat_file #print the resulting data if __name__ == '__main__': # Reading from input dat file dat_file = "data/pfgd_test.dat" result = cc_dat_utils.make_cc_data_...
nilq/baby-python
python
# 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 # d...
nilq/baby-python
python
""" 471. Top K Frequent Words https://www.lintcode.com/problem/top-k-frequent-words/description?_from=ladder&&fromId=37 hash map: o(n) time o(n) extra space idea: only record the maximum kth occurance of words in the heap, keep the minmum occurance if incoming words occurance > min occurance for the current kth mos...
nilq/baby-python
python
from models.model_factory import RegisterModel import torchvision.models as models import torch.nn as nn import torch @RegisterModel('resnet18') class Resnet18(nn.Module): def __init__(self, args): super(Resnet18, self).__init__() self._model = models.resnet18(pretrained= args.trained_on_imagenet) ...
nilq/baby-python
python
# # Copyright (c) 2019 UAVCAN Development Team # This software is distributed under the terms of the MIT License. # Author: Pavel Kirienko <pavel.kirienko@zubax.com> # """ This module contains implementations of various CRC algorithms used by the transports. `32-Bit Cyclic Redundancy Codes for Internet Applications (...
nilq/baby-python
python
from django.shortcuts import render, redirect, get_object_or_404 from django.utils import timezone from .models import Lost # Create your views here. def home(request): stuffs = Lost.objects.all() return render(request, 'lost.html', {'stuffs' : stuffs}) def new(request): if request.method == 'POST': ...
nilq/baby-python
python
import numpy as np import torch from torchvision import datasets import torchvision.transforms as transforms import matplotlib.pyplot as plt from skimage.measure import compare_psnr, compare_ssim from skimage.transform import resize from skimage.restoration import denoise_nl_means, estimate_sigma import PIL import skim...
nilq/baby-python
python
from MergeIndependent import *
nilq/baby-python
python
import numpy as np from netCDF4 import Dataset from scipy.interpolate import griddata from collections import defaultdict lon_high = 101.866 lon_low = 64.115 lat_high= 33. lat_low=-6.79 numpy_cube=np.load('/nfs/a90/eepdw/Data/Observations/Satellite/GSMAP_Aug_Sep_2011/GSMAP_EMBRACE.npz') # Load land sea mask. T...
nilq/baby-python
python
import json, re, os, platform, subprocess, sys from pathlib import Path from flask import Flask, request, redirect, url_for, Response, send_file, render_template # from pegpy.main import macaron # from datetime import datetime import transpiler app = Flask(__name__) # horizontalBar = r"---" # reHorizontalBar = re.c...
nilq/baby-python
python
# Copyright 2022 MTS (Mobile Telesystems) # # 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
import cv2 import numpy as np import scipy.io as sio import matplotlib.pyplot as plt from sklearn.neighbors import NearestNeighbors from scipy import interpolate import math NN_RATIO = 0.7 NUM_IAC_ITER = 200 ransac_thr = 10 ransac_iter = 1000 RANDOM_SEED = 42 # Matches SIFT features in template to nearest neighbours...
nilq/baby-python
python
import numpy as np import cudarray as ca from .. import expr as ex if ca.float_ == np.float32: eps = 1e-04 else: eps = 1e-06 def allclose(a, b, rtol=None, atol=None): if ca.float_ == np.float32: rtol = 1e-03 if rtol is None else rtol atol = 1e-04 if atol is None else atol else: ...
nilq/baby-python
python
""" Check the tutorial for comments on the code. """ import sys from direct.showbase.ShowBase import ShowBase class Application(ShowBase): def __init__(self): sys.path.insert(0, "render_pipeline") from rpcore import RenderPipeline self.render_pipeline = RenderPipeline() self.re...
nilq/baby-python
python
# Parts of the code in this file have been borrowed from: # https://github.com/facebookresearch/habitat-api import os import numpy as np import torch from habitat.config.default import get_config as cfg_env from habitat.datasets.pointnav.pointnav_dataset import PointNavDatasetV1 from habitat import Config, Env, RLEn...
nilq/baby-python
python
from util.Docker import Docker from util.Api import Api import os import unittest class Dredd: image = 'sls-microservices/openapi' container_name = '' def test_against_endpoint(self, service, api_endpoint, links=[], env=[]): self.container_name = Docker().random_container_name('openapi') co...
nilq/baby-python
python
""" This file can generate all the figures used in the paper. You can run it with -h for some help. Note that: - you need to have produced the data to be able to plot anything. """ import numpy as np import pandas as pd from scipy.stats import permutation_test # ===================================================...
nilq/baby-python
python
# get data from txt file with calibration import numpy as np from scipy import interpolate calib_data = np.genfromtxt('Turb_calib.txt', dtype='float', skip_header= 1) # get txt file (ignores 1st row) x = calib_data[:, 0] y = calib_data[:, 1] turb_interpolate = interpolate.interp1d(x, y, kind= 'linear', bounds_erro...
nilq/baby-python
python
# Uses python3 n = int(input()) a = [int(x) for x in input().split()] assert(len(a) == n) i, j = 0, 1 for k in range(n): if a[i] < a[k]: i, j = k, i print(a[i]*a[j])
nilq/baby-python
python
import urllib import urllib2 import urlparse import json import logging class APIClient: def __init__(self, api_root, debug=False): self.api_root = api_root self.debug = debug def __call__(self, path, params, body=None, headers={}): full_url = urlparse.urljoin(self.api_root, path) ...
nilq/baby-python
python
import numpy as np from sympy.solvers import solve from sympy import Symbol from scipy.interpolate import interp1d from scipy.integrate import trapz def steel_specific_heat_carbon_steel(temperature): """ DESCRIPTION: [BS EN 1993-1-2:2005, 3.4.1.2] Calculate steel specific heat acco...
nilq/baby-python
python
# Copyright 2015 Janos Czentye <czentye@tmit.bme.hu> # # 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 a...
nilq/baby-python
python
import numpy as np import math from domains.environment import Environment import copy class SimpleEnv(Environment): def __init__(self, branch, solution_path, printp=False): self._branch = branch # branching factor self._solution_path = solution_path # path to unique solution self._path ...
nilq/baby-python
python
import alphanum def test_no_string_length(): foo = alphanum.generate() assert len(foo) == 1 def test_with_string_length(): foo = alphanum.generate(10) assert len(foo) == 10 def test_subsequent_strings_differ(): foo = alphanum.generate(10) bar = alphanum.generate(10) assert foo != bar
nilq/baby-python
python
from tkinter import* janela = Tk() janela.title('contagem') janela['bg']='Black' segundos = None #dimisões da janela largura = 230 altura = 250 #resolução do sistema largura_screen = janela.winfo_screenwidth() altura_screen = janela.winfo_screenheight() #posição da janela posX = largura_screen/2 - largura/2 posY...
nilq/baby-python
python
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXX XXXX XXXXX XXXXXX XXXX XXXX X XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXX XXXXXXXX XXXXXX XXXXX XXXXXXXXXXXXXX X XXXXXXXXXXXXXXXXXXXX XXXX XXXX XXXXX XXXXX X XXXXXX XXXXXXXX XXXXXXXXXXXX XXX XXXXX XXX XXX X XXXXXXXXXX XXX XX XXXXXX XXXXX XXXX XXX XXXX XXXXXXXXX XX XXX XXXX...
nilq/baby-python
python
from discord import Game, Member, TextChannel, CategoryChannel, PermissionOverwrite, Message, Status, ActivityType from random import randint from ..bunkbot import BunkBot from ..channel.channel_service import ChannelService from ..core.bunk_user import BunkUser from ..core.daemon import DaemonHelper from ..cor...
nilq/baby-python
python
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import logging import torch import torch.nn as nn from ..interface import BaseOperator ''' This file contains the torch implementation of operators ''' #---------------------- convolution layer ----------------------# class Conv(BaseOperator):...
nilq/baby-python
python
from django.db.models import Sum, Q from drf_writable_nested import WritableNestedModelSerializer from rest_framework import serializers from api.serializers.submissions import SubmissionLeaderBoardSerializer from competitions.models import Submission, Phase from leaderboards.models import Leaderboard, Column from .f...
nilq/baby-python
python
from ravendb.infrastructure.entities import User from ravendb.tests.test_base import TestBase class LoadTest(TestBase): def setUp(self): super(LoadTest, self).setUp() def test_load_document_and_expect_null_user(self): with self.store.open_session() as session: null_id = None ...
nilq/baby-python
python
import subprocess import sys import time if len(sys.argv) < 5: raise "Must input u_size, v_size, dataset, models to train" #subprocess.run("source ~/env/bin/activate", shell=True) u_size = int(sys.argv[3]) v_size = int(sys.argv[4]) dataset = sys.argv[2] model = sys.argv[5] n_encoding_layers = sys.argv[-2] proble...
nilq/baby-python
python
#!/usr/bin/env python from concurrent.futures import ThreadPoolExecutor from optparse import OptionParser from collections import OrderedDict import os import sys import json import urllib3 import urllib3.contrib.pyopenssl import xmltodict import traceback import certifi prog = os.path.basename(__file__) base_dir = o...
nilq/baby-python
python
#!/usr/bin/env python ################################ Import modules ################################ import argparse import msprime import allel import numpy as np import pandas as pd ############################### Define functions ############################### def read_args(): ''' This function parses ...
nilq/baby-python
python
# Location of the self-harm annotation file. LABEL_FILE = "gold-transcripts/self-harm-annotations.txt" # Location of gold TXT with the hash filename. TXT_DIR = "gold-transcripts/gold-final_2019-04-08_anno" # Location of the word-level GT.json and pred.json files. JASA_DIR = "jasa_format/v7s" # Output directory to st...
nilq/baby-python
python
from setuptools import setup setup( name="PyStructPro", version="1.0", description="A small project used to generate directory skeleton for personal projects", url="https://github.com/roberttk01/pystructpro.git", author="Thomas Kyle Robertson", author_email="roberttk01@gmail.com", license="...
nilq/baby-python
python
#!/usr/bin/env python import unittest from spdown.spotify import Spotify class TestSpotifyExtraction(unittest.TestCase): pass if __name__ == "__main__": unittest.main()
nilq/baby-python
python
# import functools import bcrypt from flask import Flask, jsonify, request from flask_restful import Api, Resource from pymongo import MongoClient # print = functools.partial(print, flush=True) app = Flask(__name__) api = Api(app) client = MongoClient("mongodb://my_db:27017") db = client.projectDB users = db["Users"...
nilq/baby-python
python
class bidict(dict): """ Implementation of bidirectional dictionary. This kind of dictionary stores {key: key} pair. The main idea is to access each key using sibling key. Current implementation stores 1 pair of key-value in self dictionary, like a regular dict, but it is possible to obtain key ...
nilq/baby-python
python
# coding=utf-8 """ In the card game poker, a hand consists of five cards and are ranked, from lowest to highest, in the following way: High Card: Highest value card. One Pair: Two cards of the same value. Two Pairs: Two different pairs. Three of a Kind: Three cards of the same value. Straight: All cards are consecutiv...
nilq/baby-python
python
from django.apps import AppConfig class ForumEngineConfig(AppConfig): name = 'forum_engine'
nilq/baby-python
python
if True: s = "<selection>foo</selection>"
nilq/baby-python
python
import gym, argparse import numpy as np import itertools import tensorflow as tf from tf_rl.common.utils import AnnealingSchedule, eager_setup from tf_rl.common.filters import Particle_Filter from tf_rl.common.wrappers import MyWrapper_revertable eager_setup() class Model(tf.keras.Model): def __init__(self, num_...
nilq/baby-python
python
from runner.run_description import RunDescription, Experiment, ParamGrid _params = ParamGrid([]) _experiments = [ Experiment( 'battle_fs4_pbt', 'python -m algorithms.appo.train_appo --env=doom_battle --train_for_env_steps=300000000000 --algo=APPO --env_frameskip=4 --use_rnn=True --ppo_epochs=1 --r...
nilq/baby-python
python
## --------------------------------------------------------------------------- ## Abstract syntax tree YAML tools. ## --------------------------------------------------------------------------- import string, re, sys, yaml, tools from tools import warning, error def decl (type, name): "Return the concatenation of ...
nilq/baby-python
python
""" Compares spectrogram computations with TensorFlow and Vesper. As of 2018-11-09, Vesper is a little more than three times faster than TensorFlow at computing spectrograms with a DFT size of 128. """ import functools import time import numpy as np import tensorflow as tf import vesper.util.data_windows as data_w...
nilq/baby-python
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import urllib.request import sys import time import urllib import os.path from struct import pack from sklearn import preprocessing import numpy as np import pandas as pd import fact.io import progressbar N = 200000 factLevel2URL = "https://factdata.app.tu-dortmund.de...
nilq/baby-python
python
def treemap( df, fig_filepath, scale=1.5, columns=None, treemap=None, layout=None, update_layout=None, **kwargs, ): # textinfo = "label+value+percent parent+percent root" # import plotly.express as px import plotly.graph_objects as go labels = list(df[columns.label].to_l...
nilq/baby-python
python
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
nilq/baby-python
python
# -*- coding: utf-8 -*- # # This file is part of reana. # Copyright (C) 2019 CERN. # # REANA is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Reana workflow factory helper functions.""" import json import logging import os import s...
nilq/baby-python
python
import sys sys.path.append("../../") from appJar import gui def fDeleteRow(dRow): app.deleteTableRow("entryTable", dRow) def fAddRow(): app.addTableRow("entryTable", app.getTableEntries('entryTable')) with gui() as app: app.addTable("entryTable", [["Item", "Description"]], action=fDeleteRow, addRow=fAddRow, acti...
nilq/baby-python
python
import requests import time import json import threading import queue import yaml from sqlalchemy import create_engine from sqlalchemy.types import BigInteger, Integer import pandas as pd def split_list(l, n): for i in range(0, len(l), n): yield l[i:i + n] def worker_get_owned_games(lst_user_id, api_key,...
nilq/baby-python
python
from dataclasses import dataclass from infrastructure.cqrs.ICommand import ICommand @dataclass class DeleteJobRequest(ICommand): Id: int = None
nilq/baby-python
python
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2019-07-25 19:52 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('commands', '0001_add-js-commands'), ] operations = [ migrations.RunSQL([ ...
nilq/baby-python
python
# -*- coding: utf-8 -*- """Top-level package for Pull Webhook.""" __author__ = """Dario Iacampo""" __email__ = 'dario@jntstudio.net' __version__ = '0.1.7' from .pull_webhook import Puller from .pull_webhook import main __all__ = [Puller, main]
nilq/baby-python
python
from tests import base from tests import factories as f outbox_len = 0 password = '123123' def test_workshop_create(base_url, browser, outbox): """ """ f.create_usertype(slug='tutor', display_name='tutor') poc_type = f.create_usertype(slug='poc', display_name='poc') state = f.create_state() u...
nilq/baby-python
python
from pydantic import BaseModel class ThingWithId(BaseModel): id: str @property def isNone(self): return self.id == "none" @classmethod def create_none(cls): return cls(id="none")
nilq/baby-python
python
from IPython.display import display, HTML import numpy as np import seaborn as sns def display_html(html: str): display(HTML(html)) def get_color_palette(prepend_neutral_color:bool=False): colors = sns.color_palette('Set1') if prepend_neutral_color: colors = colors[-1:] + colors[:-1] return ...
nilq/baby-python
python
# Copyright 2009-2015 MongoDB, 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
nilq/baby-python
python
# Generated by Django 2.1.1 on 2018-10-23 09:29 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('places', '0029_auto_20181017_1252'), ] operations = [ migrations.RemoveField( model_name='place'...
nilq/baby-python
python
#导入 GPIO库 import RPi.GPIO as GPIO import time import ui,main import threading distmin=25 whiletime=1 distmax=1 #设置 GPIO 模式为 BCM GPIO.setmode(GPIO.BCM) #定义 GPIO 引脚 GPIO_TRIGGER = 20 GPIO_ECHO = 21 #设置 GPIO 的工作方式 (IN / OUT) GPIO.setup(GPIO_TRIGGER, GPIO.OUT) GPIO.setup(GPIO_ECHO, GPIO.IN) def distance(): # 发送高电平信...
nilq/baby-python
python
from torch import nn class GeneralSequential(nn.Module): def __init__(self, *layers): super().__init__() self.layers = nn.ModuleList(layers) def forward(self, *args): for layer in self.layers: args = layer(*args) return args
nilq/baby-python
python
sopa = open("sopa.txt") m = input("Introduzca numero de filas: ") n = input("Introduzca numero de columnas: ") matriz = [] y = 0 while y < m: x = 0 fila = [] while x < n: fila.append(sopa.read((y*n)+x)) x += 1 matriz.append(fila) y += 1 print matriz
nilq/baby-python
python
#!/usr/bin/env python """Series example Demonstrates series. """ from sympy import Symbol, cos, sin, pprint def main(): x = Symbol('x') e = 1/cos(x) print print "Series for sec(x):" print pprint(e.series(x, 0, 10)) print "\n" e = 1/sin(x) print "Series for csc(x):" print ...
nilq/baby-python
python
# ProDy: A Python Package for Protein Dynamics Analysis # # Copyright (C) 2010-2011 Ahmet Bakan # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your...
nilq/baby-python
python
"""Module contains functions and classes for noisy EEG data detection.""" import mne import numpy as np from mne.channels.interpolation import _make_interpolation_matrix from mne.preprocessing import find_outliers from psutil import virtual_memory from scipy.stats import iqr from statsmodels.robust.scale import mad ...
nilq/baby-python
python
""" Event module """ # Import modules import numpy as np import datetime import math import time import json import sys from obspy import Stream, Trace, UTCDateTime from glob import glob import ast from warnings import warn import logging import boto3 from botocore.exceptions import ClientError __author__ = "Vaclav ...
nilq/baby-python
python
import argparse import pygame import random import math import heapq import grid as Grid import sketcher as Sketcher import re def defineArgs(): parser = argparse.ArgumentParser( description='simple script to find an optimal path using A*' ) parser.add_argument( '-gw', '--gridWidth', ...
nilq/baby-python
python
from typing import Any, Dict, List, Optional, Tuple, Union, cast # NB: we cannot use the standard Enum, because after "class Color(Enum): RED = 1" # the value of Color.RED is like {'_value_': 1, '_name_': 'RED', '__objclass__': etc} # and we need it to be 1, literally (that's what we'll get from the client) class En...
nilq/baby-python
python
""" This is the main functionality of our package. it implements the logic necessary to fetch the next event from the server and return it as a time delta for us to use. """ from datetime import datetime, timedelta, timezone import requests def get_time_difference(from_time: datetime = None) -> timedelta: """Fe...
nilq/baby-python
python
import ast import datetime as dt import os import time import cv2 import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import tensorflow as tf from keras.models import Model, load_model from tensorflow import keras from common import * # os.environ['CUDA_VISIBLE_DEVICES'] = '-...
nilq/baby-python
python
import torch import src.Python.exportsd as exportsd class BasicConv1d(torch.nn.Module): def __init__(self, in_channels, out_channels, **kwargs): super().__init__() self.stack = torch.nn.Sequential( torch.nn.Conv1d(in_channels, out_channels, kernel_size=3, bias=False, **kwargs), ...
nilq/baby-python
python
# -*- coding: utf-8 -*- from __future__ import division from builtins import range def merge_dictionary(dst, src): """Recursive merge two dicts (vs .update which overwrites the hashes at the root level) Note: This updates dst. Copied from checkmate.utils """ stack = [(dst, src)] while sta...
nilq/baby-python
python
import queue from chess.board import Board from chess.figure import Figure PRE = 0 SOLVING = 1 class Game: def __init__(self, board_size=(8, 8)): self.board = Board(board_size) self.state = PRE self.judge = False self.score = 0 self.pre_solve_figures_queue = queue.Queue...
nilq/baby-python
python
# AUTOGENERATED! DO NOT EDIT! File to edit: source_nbs/00_1_params.ipynb (unless otherwise specified). __all__ = ['Params'] # Cell from .base_params import BaseParams from .embedding_layer.base import (DefaultMultimodalEmbedding, DuplicateAugMultimodalEmbedding) from .loss_stra...
nilq/baby-python
python
from sklearn.datasets import make_blobs import matplotlib.pyplot as plt import numpy as np sample_size = 100 X, y = make_blobs(n_samples = sample_size, centers = 2, random_state = 1) y[y == 0] = -1 print(f"X Shape: {X.shape}") print(f"y Shape: {y.shape}") # THE PERCEPTRON ALGORITHM def perceptron(t, D, y): ...
nilq/baby-python
python
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
nilq/baby-python
python
import unittest import pygal from pymongo import MongoClient import driveshare_graph.minmax as minmax class MinMax(unittest.TestCase): def test_minmax_chart(self): client = MongoClient('localhost', 27017) collection = client['GroupB']['totalStorage'] graph = minmax.minmax_chart(collection)...
nilq/baby-python
python
"""Test the MCP9808 temperature sensor""" from meerkat import base, mcp9808 dev = mcp9808.MCP9808(bus_n=base.i2c_default_bus) print() print('Current MCP9808 Status:') print('-----------------------') dev.print_status() print() print('One measurement') print('---------------') print(dev.get_temp()) print() print('M...
nilq/baby-python
python
# coding: utf-8 # # Function dctmatrix # # ## Synopse # # Compute the Kernel matrix for the DCT Transform. # # - **A = dctmatrix(N)** # # - **A**:output: DCT matrix NxN. # - **N**:input: matrix size (NxN). # In[1]: import numpy as np def dctmatrix(N): x = np.resize(range(N), (len(range(N)), len(range...
nilq/baby-python
python
import os import yaml import jsonschema import argparse SCHEMA = os.path.join(os.path.dirname(os.path.abspath(__file__)), "yaml_schema.yaml") def validate_yaml(yaml_file: str): """ Validates the syntax of the yaml file. Arguments: yaml_file: path to yaml file to be validate...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Coletor Web Realiza a coleta dos comentários associados a determinado Tweet. Utiliza o selenium - Necessário instalação de arquivo externo chromedriver """ import sys import coletor_web.coletor_comentarios as comment import core.database as db def main(banco_dados, colecao): """Cole...
nilq/baby-python
python
""" Provides a set of filter classes used to inject code into actions. """ import inspect from flask import request from .exceptions import ValidationError, UnsupportedMediaType from .fields import Schema from .results import BadRequestResult, ForbiddenResult, UnauthorizedResult, UnsupportedMediaTypeResult class Fi...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'SerialPort.ui' # # Created by: PyQt5 UI code generator 5.12.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): Main...
nilq/baby-python
python
#All these functions are for dummy purposes import nltk from nltk.tokenize import sent_tokenize from numpy.random import randint,uniform # from sklearn.feature_extraction.text import TfidfVectorizer # from preprocessing import * def chunker1(paragraph): ''' Creates a "lengths" list having a distribution of l...
nilq/baby-python
python