content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
#from time import sleep class SessionHelper(): def __init__(self, app): self.app = app def login(self, user_email, password): driver = self.app.driver self.app.open_page() #driver.find_element_by_id("email").click() driver.find_element_by_id("email").send_keys(user_ema...
nilq/baby-python
python
#!/bin/env python # Copyright 2021 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
nilq/baby-python
python
# vim: set tabstop=4 shiftwidth=4 expandtab ############################################################################## # Written by: Brian G. Merrell <bgmerrell@novell.com> # Date: 12/03/2008 # Description: helpprovider.py wrapper script # Used by the helpprovider-*.py tests ###################...
nilq/baby-python
python
import warnings import numpy as np from scipy._lib.six import callable, string_types from scipy._lib.six import xrange from scipy.spatial import _distance_wrap from scipy.linalg import norm import MyTimer _SIMPLE_CDIST = {} def _copy_array_if_base_present(a): """ Copies the array if its base points to a par...
nilq/baby-python
python
class Color(object): RESET = '\x1b[0m' BLACK = 0 RED = 1 GREEN = 2 YELLOW = 3 BLUE = 4 MAGENTA = 5 CYAN = 6 WHITE = 7 NORMAL = 0 BOLD = 1 @staticmethod def to_color_string(string, foreground = 7, ...
nilq/baby-python
python
import os import unittest import pytest from github import GithubException from ogr import GithubService from ogr.abstract import PRStatus, IssueStatus from ogr.persistent_storage import PersistentObjectStorage from ogr.exceptions import GithubAPIException DATA_DIR = "test_data" PERSISTENT_DATA_PREFIX = os.path.join...
nilq/baby-python
python
# django from django import forms # local django from exam.models import CustomExam from exam.validators import CustomExamValidator class CreateCustomExams(forms.ModelForm): """ Form to create a custom exam. """ description = forms.CharField(widget=forms.Textarea) class Meta: # Define m...
nilq/baby-python
python
# Generated by Django 2.2 on 2020-08-09 06:03 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('coupons', '0003_coupon_max_discount'), ] operations = [ migrations.AlterField( model_name='coupon', name='max_discount...
nilq/baby-python
python
import threading from Queue import Empty, Full from multiprocessing import Process, Queue, Value import datetime import os import zmq import logging from logging import handlers from platformData import * from BEMOSSThread import BThread, BProcess from commandProcessor import processCommand import cgitb cgitb.enable...
nilq/baby-python
python
from tabulate import tabulate table = [['one','two','three'],['four','five','six'],['seven','eight','nine']] print(tabulate(table, tablefmt='html')) """Generate Report Function""" with open('example.log') as f: lines = f.readlines() print lines print(lines[2]) HTML_file= open("Report.html","w+") HTML_...
nilq/baby-python
python
''' Environment simulators. ''' from models.simulator import POMDPSimulator from models.simulator_momdp import MOMDPSimulator from models.tiger import TigerPOMDP from models.rock_sample import RockSamplePOMDP from models.tools.belief import DiscreteBelief
nilq/baby-python
python
""" Uma matriz de confusão. Não confundir com uma tabela de confusão. A matrix de confusão possui mais do que uma duas linhas e duas colunas, por isso difere da tabela de confusão, que possui duas linhas e duas colunas Para criar a matriz de confusão escolhi o formato de dictionary da seguinte maneira...
nilq/baby-python
python
## process_rootroopnft.py # first let's just check how many tweets it grabbed. with open("rootroopnft.txt", "r") as fid: line = fid.read() # end with open line = line.split("Tweet(url=") print("line[0]: ", line[0]) print("line[-1]: ", line[-1]) last_date = line[-1].split("date=datetime.datetime(")[1].split(", tzin...
nilq/baby-python
python
import cv2 import numpy as np class ColorTrack(): def __init__(self): pass def detect_green(self,frame): return self.detect_color(frame,np.array([33,80,40]),np.array([102, 255, 255])) def detect_red(self,frame): return self.detect_color(frame,np.array([78, 43, 46]), np.array([99,...
nilq/baby-python
python
from __future__ import print_function, absolute_import import sys import subprocess from distutils.errors import DistutilsPlatformError import semantic_version class Binding: """ Binding Options """ # https://github.com/PyO3/PyO3 PyO3 = 0 # https://github.com/dgrunwald/rust-cpython RustCP...
nilq/baby-python
python
# imports from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from bs4 import BeautifulSoup import time import re import csv # easy function for viewing list def printlist(list): length=len(list) for i in range(length): ...
nilq/baby-python
python
"""The SquonkServer class handles get, post and delete requests against the squonk base_url using the SquonkAuth class to refresh the authentication token when required. """ import requests import json import logging from email.policy import default from collections import namedtuple try: from .Squo...
nilq/baby-python
python
# -*- coding: utf-8 -*- import logging from mathutils import Vector class BlockDef(object): class _BlockItem(object): def __init__(self, name="", color=(0, 0, 0), block_def=(35, None)): self._name = name self._color = color self._block_def = block_def @property...
nilq/baby-python
python
from flask_wtf import FlaskForm from wtforms import StringField, DateField, SubmitField from wtforms.validators import DataRequired class QuestionsForm(FlaskForm): class Meta: csrf = False # Example of defining a field. A in depth description can be found. # field_name = FieldType(label, descriptio...
nilq/baby-python
python
import numpy as np import torch import torch.nn as nn from torch.autograd import Variable from scipy.special import factorial2 class Hermite: def __init__(self, num_pol = 5): self.h = [] def h0(x): return torch.ones_like(x) self.h.append(h0) def h1(x): return x sel...
nilq/baby-python
python
import numpy as np import math import cv2 class PSNR(): def __init__(self, range=1): self.range = range def __call__(self, img1, img2): mse = np.mean((img1 - img2) ** 2) return 20 * math.log10(self.range / math.sqrt(mse)) class SSIM(): def __init__(self, range=1): self.r...
nilq/baby-python
python
from excursion.sampler import * from excursion.models import ExcursionModel, SKLearnGP from excursion.acquisition import * from excursion.excursion import ExcursionProblem, ExcursionResult # # move this into the excursion result, unless we add scikit learn implementation # # def build_result(details: ExcursionProble...
nilq/baby-python
python
def settings (): # Input manually all extensions and copy settings extensions = [] key = "Y" while (key != "N"): extension = str(input("Enter a extension to search and organize: ")).strip().replace(".", "").lower() extensions.append(extension) key = str(input("Continue? Y/N: ")...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'resources/treeDialog.ui' # # Created by: PyQt5 UI code generator 5.13.0 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_TreeDialog(object): def setupUi(self, TreeDialog): ...
nilq/baby-python
python
# Crie um programa que leia algo e mostre seu tipo pimitivo e todas as informações possíveis sobre ele. print('=-'*7, 'DESAFIO 4', '=-'*7) n = input('Digite algo: ') print('O tipo primitivo desse valor é {}.'.format(type(n))) # Ponto de melhoria! print('Só tem espaços? {}'.format(n.isspace())) print('É um número? {}'....
nilq/baby-python
python
import sys import math import json class Point: def __init__(self, x, y, z, index): self.x = x self.y = y self.z = z self.index = index def getDist(a, b): return math.sqrt((a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y) + (a.z - b.z)*(a.z - b.z)) for arg in sys.argv: fi...
nilq/baby-python
python
from scipy import interp import numpy as np from itertools import cycle from sklearn.metrics import roc_curve, auc from sklearn.metrics import precision_recall_curve from sklearn.metrics import average_precision_score from itertools import cycle import matplotlib.pyplot as plt def plot_roc_pr( y_pred : np.ndar...
nilq/baby-python
python
class withdelta(object): """ Wraps any object into the `value` property, and adds a `delta` floating point property that can be used to store extra information, such as percentage of improvement over a over a different values. All the attributes are forwarded to `value`, except for `value` and `del...
nilq/baby-python
python
class Dummy(object): def purge(self, path): pass
nilq/baby-python
python
""" cluster_graph.py ClusterGraph are a class for tracking all possible smirks decorators in a group (or cluster) of molecular fragments. Moving forward these will be used to find the minimum number of smirks decorators that are required to have a set of smirks patterns that maintain a given clustering of fragments. "...
nilq/baby-python
python
from abc import ABC from typing import Any class IWord(ABC): command: Any class Word(IWord): def __init__(self, command=None): self.command = command self.address = 0 def dump(self): return self.command.dump() @property def original(self): return self.command.original def ...
nilq/baby-python
python
#!/usr/bin/env python3 import argparse import os def main(dir): with open(os.path.join(dir, 'text'), 'w', encoding='utf-8') as out_f: for line in open(os.path.join(dir, 'text.ort2'), encoding='utf-8'): key, sent = line.strip().split(None, 1) if len(sent) > 0 and sent[0] == "*": ...
nilq/baby-python
python
import json import unittest import urllib.request from multiprocessing.dummy import Pool from tests.gunicorn_utils import run_gunicorn def run_code_in_snekbox(code: str) -> tuple[str, int]: body = {"input": code} json_data = json.dumps(body).encode("utf-8") req = urllib.request.Request("http://localhost...
nilq/baby-python
python
import numpy as np import tensorflow as tf import random as rn from keras.layers import multiply,concatenate,Embedding from keras.layers.merge import dot from keras import backend as K from keras.models import Sequential # The below is necessary in Python 3.2.3 onwards to # have reproducible behavior for certain hash...
nilq/baby-python
python
from __future__ import print_function import os import sys from burlap import ServiceSatchel from burlap.constants import * from burlap.decorators import task class ApacheSatchel(ServiceSatchel): name = 'apache' post_deploy_command = 'reload' templates = [ '{site_template}', ] @proper...
nilq/baby-python
python
import requests import nels_master_api def get_nels_ids(): try: ids = [] response = requests.get(nels_master_api.get_full_url("users/ids" ),auth=(nels_master_api.CLIENT_KEY, nels_master_api.CLIENT_SECRET)) if(response.status_code == requests.codes.ok): json_response = response....
nilq/baby-python
python
import pandas as pd import math data = pd.read_csv('data/DATALOG2.CSV', delimiter=",", names=['date', 'time', 'lat', 'lon', 'vgps', 'velocity', 'course', 'heading', 'pitch', 'roll']) # data['vhead'] = data['velocity']*math.cos(math.pi/180*(data['course']-data['heading'])) data['drift'] = data.apply(...
nilq/baby-python
python
import logging import multiprocessing import multiprocessing_logging import os log_level_from_env = os.environ.get('LOGLEVEL', '').upper() log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s %(message)s' log_level = logging.DEBUG if log_level_from_env == 'DEBUG' else logging.INFO logging.basi...
nilq/baby-python
python
## Data and Visual Analytics - Homework 4 ## Georgia Institute of Technology ## Applying ML algorithms to detect seizure import numpy as np import pandas as pd import time from sklearn.model_selection import cross_val_score, GridSearchCV, cross_validate, train_test_split from sklearn.metrics import accuracy_score, cl...
nilq/baby-python
python
#!/usr/bin/env python from __future__ import absolute_import import os import shutil import time import datetime from flask.ext.script import Manager from modelconvert import create_app from modelconvert.utils import fs app = create_app() manager = Manager(app) @manager.command def run(): app.run(threaded=Tr...
nilq/baby-python
python
"""Configuration classes for ``varfish-cli case *`` commands.""" import attr import uuid import typing from ..common import CommonConfig @attr.s(frozen=True, auto_attribs=True) class CaseConfig: """Configuration for the ``varfish-cli case`` command.""" #: Global configuration. global_config: CommonCon...
nilq/baby-python
python
import subprocess import sys import os import time import cProfile def prepare_io(list_of_files, exe_file, input_path, output_path, job_number): # read file names with open(list_of_files, "r") as files_to_read: list_files = files_to_read.read().split("\n") job_number = int(job_number) - 1 inpu...
nilq/baby-python
python
import numpy as np # Collection of activation functions # Reference: https://en.wikipedia.org/wiki/Activation_function class Sigmoid(): def __call__(self, x): return 1 / (1 + np.exp(-x)) def gradient(self, x): return self.__call__(x) * (1 - self.__call__(x)) class Softmax(): def __call__...
nilq/baby-python
python
#!/usr/bin/env python3.7 import sys from blist import blist from collections import defaultdict # Solution to the day 9 puzzle from Advent of Code 2018. # https://adventofcode.com/2018/day/9 def parse_data(filename): """ Load the data from FILENAME. """ data = list() with open(filename) as f: el...
nilq/baby-python
python
import time import hashlib import requests import urllib3 from lxml import etree urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) def xdl_proxy(orderno, secret, host, port): host_port = host + ":" + port # get sign timestamp = str(int(time.time())) string = "" str...
nilq/baby-python
python
# -*- coding: utf8 -*- """ ====================================== Project Name: NLP File Name: utils Author: czh Create Date: 2021/8/6 -------------------------------------- Change Activity: ====================================== """ import torch import torch.nn as nn import torch.nn.functional as ...
nilq/baby-python
python
''' Author: Mario Liu Description: Module to detect faces with R200 camera. Adapted from https://docs.opencv.org/3.4.3/d7/d8b/tutorial_py_face_detection.html ''' import logging logging.basicConfig(level=logging.INFO) import time import numpy as np import cv2 import pyrealsense as pyrs face_cascade = cv2.CascadeClass...
nilq/baby-python
python
import cv2 import numpy as np from matplotlib import pyplot as plt img = cv2.imread('sud2.jpeg',0) img = cv2.medianBlur(img,5) ret,th1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY) th2 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,\ cv2.THRESH_BINARY,11,2) th3 = cv2.adaptiveThreshold(img,255...
nilq/baby-python
python
# # Imported module functions # #https://camo.githubusercontent.com/582226b9ba41bcbc13eaa81d2764092abb443bd416578c175bc2c1c5742d0647/68747470733a2f2f692e696d6775722e636f6d2f6b7a6978316a492e706e67 # Use our SimpleRequests module for this experimental version. from SimpleRequests import SimpleRequest from SimpleRequests....
nilq/baby-python
python
from __future__ import annotations from spark_auto_mapper_fhir.fhir_types.uri import FhirUri from spark_auto_mapper_fhir.value_sets.generic_type import GenericTypeCode from spark_auto_mapper.type_definitions.defined_types import AutoMapperTextInputType # This file is auto-generated by generate_classes so do not edi...
nilq/baby-python
python
import json from itertools import groupby from operator import itemgetter import django from django import forms from django.conf import settings from django.contrib.admin.views.decorators import staff_member_required from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ObjectD...
nilq/baby-python
python
# Sum Compare # Get 3 numbers from the user. Find the # biggest number and add them all together. # If the sum is bigger than 2 times the # biggest of the 3 numbers, then print the sum. # If it's smaller, multiply the sum by 3 and print the product. # write code here
nilq/baby-python
python
import tensorflow as tf import math class BatchNormalization(tf.keras.layers.BatchNormalization): """Make trainable=False freeze BN for real (the og version is sad). ref: https://github.com/zzh8829/yolov3-tf2 """ def call(self, x, training=False): if training is None: training =...
nilq/baby-python
python
""" Some simple code to make particle flux spectrograms with matplotlib @author: Liam M. Kilcommons (minor modifications R. Redmon, A.G. Burrell) """ import numpy as np import matplotlib.pyplot as pp import datetime as dt def dmsp_spectrogram(times, flux, channel_energies=None, lat=None, lt=None, ...
nilq/baby-python
python
from django.apps import apps from django.forms.models import ModelChoiceField, ModelMultipleChoiceField from django.forms import ChoiceField from smart_selects.widgets import ChainedSelect, ChainedSelectMultiple try: from django.utils.encoding import force_text except ImportError: from django.utils.encoding imp...
nilq/baby-python
python
class Person(object): def demo(self): print('888')
nilq/baby-python
python
import datetime import json import argparse from typing import Any, Dict import pytz from astral import LocationInfo, Observer, sun options = argparse.ArgumentParser() options.add_argument( "-n", "--name", dest="name", default="Somewhere", help="Location name (free-form text)", ) options.add_argu...
nilq/baby-python
python
n, m = map(int, input().split()) if n == 1: if m == 0: print(1, 2) else: print(-1) exit() if m < 0 or m + 2 > n: print(-1) else: print(1, 2 * (m + 2)) for i in range(1, m + 2): print(2 * i, 2 * i + 1) for j in range(m + 2, n): print(2 * j + 1, 2 * j + 2)
nilq/baby-python
python
from sklearn import preprocessing from tqdm import tqdm import time import pandas as pd import numpy as np import torch import torch.nn as nn from sklearn.metrics import accuracy_score, recall_score from sklearn.metrics import precision_score, f1_score from sklearn.metrics import classification_report from core.utils...
nilq/baby-python
python
#Actualizado Lunes,28 de mayo dos mil diez y ocho #Autor: Rosnel Alejandro Leyva-Cortes# import os import re import sys import struct import socket import urllib import time from subprocess import Popen, PIPE import json as m_json try: from urllib.parse import urlparse except ImportError: from urlparse import u...
nilq/baby-python
python
import pymysql from sshtunnel import SSHTunnelForwarder class Database: def initialize(self, server_name): self.server = SSHTunnelForwarder( '51.75.163.1', ssh_username='karthik', ssh_password='btm56Vy.3', remote_bind_address=('127.0.0.1', 3306) ...
nilq/baby-python
python
class Station: def __init__(self, station_id, direction, stop_name, station_name, accessible, red, blue, green, brown, purple, purple_exp, yellow, pink, orange, latitude, longitude): self.station_id = station_id self.direction = direction self.stop_name = stop_name self.station_name ...
nilq/baby-python
python
meses = {'January': 1, 'February': 2, 'March': 3, 'April': 4, 'May': 5, 'June': 6, 'July': 7, 'August': 8, 'September': 9, 'October': 10, 'November': 11, 'December': 12} #entrada mes = int(input()) #processamento & saída for k, v in meses.items(): if v == mes: print(k) break
nilq/baby-python
python
from gruffy import AccumulatorBar g = AccumulatorBar() g.title = "Gruffy's Graph" g.data("add", [10, 50, 150, 20]) g.hide_legend = True g.labels = {0: '2003', 1: '2004', 2: '2005', 3: '2006'} g.transparent = 0.7 g.y_axis_increment = 50 g.maximum_value = 300 g.write('gruffy-accumulatorbar.png')
nilq/baby-python
python
from sym_lis3 import GlobalEnv import pytest def test_dyn(): g = GlobalEnv() g.eval_str('(define "foo" (lambda (x y) (if (in? dyn_env x) y 0)))') assert not g.eval_str('(in? root_env "x")') assert g.eval_str('(foo "x" 1)') == 1 assert g.eval_str('(foo "+" 1)') == 0 assert g.eval_str('(foo ...
nilq/baby-python
python
class BaseEngine: def __init__(self, world): self.world = world self._cull_method = self.default_cull_method def check_collision(self, entity, collider): raise NotImplementedError('Nope.') def resolve_collision(self, entity, collider): raise NotImplementedError('No...
nilq/baby-python
python
from ..typecheck import * from . layout import Layout from . image import Image from . css import css, div_inline_css, icon_css, none_css class element: def __init__(self, is_inline: bool, width: Optional[float], height: Optional[float], css: Optional[css]) -> None: super().__init__() self.layout = None #type: O...
nilq/baby-python
python
from django.core.mail import send_mail, EmailMessage from django.forms import modelformset_factory from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404, render from django.urls import reverse from django.views import generic from .models import Question, Choice, FilePathFieldForm ...
nilq/baby-python
python
from ...utils.IndexedRect import IndexedRect class IndexedRectBuilder(object): def __init__(self): self.last_rect = None self.initial_point = None self.reset() def set_initial_point(self, x, y): self.initial_point = (x,y) def get_initial_point(self): return self.i...
nilq/baby-python
python
# -*- coding: utf-8 -*- import binarybrain as bb import binarybrain.core as core import numpy as np from typing import List class Optimizer(bb.Object): """Optimizer の基本クラス """ def __init__(self, core_optimizer=None): super(Optimizer, self).__init__(core_object=core_optimizer) ...
nilq/baby-python
python
#coding:utf8 # Author : tuxpy # Email : q8886888@qq.com # Last modified : 2015-03-26 13:14:11 # Filename : gale/utils.py # Description : from __future__ import unicode_literals try: # py2 from urlparse import urlsplit from urllib import unquote_plus from urllib import quote...
nilq/baby-python
python
import cv2 import numpy as np from matplotlib import pyplot as plt # calculer difference entre les deux flow optique adjacents def diffimage(lastframe, nextframe, size): diff_frame = nextframe - lastframe ABS = abs(diff_frame) diff_value = (ABS.sum(axis = 0)).sum(axis = 0)/size return diff_frame, dif...
nilq/baby-python
python
import pytest from mcanitexgen.animation.parser import Duration, ParserError, Time, Timeframe, Weight class Test_Timeframe_init: @pytest.mark.parametrize( "start, end, duration, expected_timeframe", [ # Deduce end and duration (0, None, None, Timeframe(0, 1, 1)), ...
nilq/baby-python
python
#!/usr/bin/env python3 from yaml import load class ComposePlantuml: def __init__(self): pass def parse(self, data): return load(data) def link_graph(self, compose, notes=False): result = 'skinparam componentStyle uml2\n' for component in sorted(self.components(compose))...
nilq/baby-python
python
# Generated by Django 3.2.7 on 2021-09-09 18:17 import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('auctions', '0008_add_expiry_alter_category_on_listing'), ] operations = [ migrations.A...
nilq/baby-python
python
import pytest from astropy.io import fits import numpy as np from numpy.testing import assert_array_equal from lightkurve import search_lightcurve from lightkurve.io.qlp import read_qlp_lightcurve from lightkurve.io.detect import detect_filetype @pytest.mark.remote_data def test_qlp(): """Can we read in QLP lig...
nilq/baby-python
python
__version__ = 0.1 import os import logging import configparser import daiquiri import daiquiri.formatter _ROOT = os.path.dirname(os.path.abspath(__file__)) _CONFIG = os.path.join(_ROOT, 'config.ini') FORMAT = ( "%(asctime)s :: %(color)s%(levelname)s :: %(name)s :: %(funcName)s :" "%(message)s%(color_stop)...
nilq/baby-python
python
import numpy as np from ._CFunctions import _Cgcpm import DateTimeTools as TT def GCPM(x,y,z,Date,ut,Kp=1.0,Verbose=False): ''' Calculates the Global Core Plasma Model at some given position(s) and time(s). Inputs ====== x : float scalar or array of x_SM (Solar Magnetic coordinates) component of the posit...
nilq/baby-python
python
# Generated by Django 3.1.5 on 2021-01-23 02:13 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Cliente', fields=[ ('id', models.AutoField(...
nilq/baby-python
python
# Natural Language Processing # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('googleplaystoreuserreviews.csv') dataset.dropna(inplace=True) X = dataset.iloc[:,0].values # Cleaning the texts import re import nltk nltk.do...
nilq/baby-python
python
from linebot.models import TextSendMessage, FlexSendMessage from app.config import CELEBRATING_TARGET from app.crud.leaderboard import update_amount, get_list_of_amount from . import line_bot_api, exception_handler @exception_handler def celebrating_birthday(line_event): group_id = line_event.source.group_id ...
nilq/baby-python
python
#!/usr/bin/env python3 import unittest import timeout_decorator from challenges.codility.lessons.q019.stone_wall_v001 import * MAX_N = 100000 MIN_ELEMENT = 1 MAX_ELEMENT = 1000000000 class StoneWallTestCase(unittest.TestCase): def test_description_examples(self): self.assertEqual(7, solution([8, 8, 5, 7, 9...
nilq/baby-python
python
# Create CSS using GitHub's colour scheme from a JSON source like (https://github.com/doda/github-language-colors) import json with open('github_colors.json') as colors: with open('github_colors.css', 'w') as css: m = json.loads(colors.read()) for lang in m: color = m[lang] lang_saf...
nilq/baby-python
python
TRAINING_DATA = [ ( "i went to amsterdem last year and the canals were beautiful", {"entities": [(10, 19, "TOURIST_DESTINATION")]}, ), ( "You should visit Paris once in your life, but the Eiffel Tower is kinda boring", {"entities": [(17, 22, "TOURIST_DESTINATION")]}, ), ...
nilq/baby-python
python
""" @leofansq Basic function: show_img(name, img): Show the image find_files(directory, pattern): Method to find target files in one directory, including subdirectory Load function: load_calib_cam2cam(filename, debug=False): Only load R_rect & P_rect for need load_calib_lidar2cam(filename, debug=Fal...
nilq/baby-python
python
from dotenv.main import find_dotenv import tweepy import time import random from dotenv import load_dotenv import os import requests load_dotenv(find_dotenv()) API_KEY = os.getenv('API_KEY') API_SECRET_KEY = os.getenv('API_SECRET_KEY') ACCESS_TOKEN = os.getenv('ACCESS_TOKEN') ACCESS_TOKEN_SECRET = os.getenv('ACCESS_TO...
nilq/baby-python
python
# Copyright 2017 Hosang Yoon # # 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 ...
nilq/baby-python
python
from .mlp_score_head import MLPScoreHead __all__ = [ 'MLPScoreHead' ]
nilq/baby-python
python
import pytest from game import seed_grid, parse_args, print_grid, get_neighbours, live_or_die def test_parser(): with pytest.raises(BaseException): parse_args(["-x", "-y", "-c"]) args = parse_args(["-x 10", "-y 20", "-c (1,1),(2,2),(5,4)"]) assert args.x == 10 assert args.y == 20 assert a...
nilq/baby-python
python
# -*- coding: utf-8 -*- import scrapy import pandas as pd class FirstSpider(scrapy.Spider): name = 'first' def start_requests(self): urls = ['https://www.worldometers.info/coronavirus/#countries'] for url in urls: yield scrapy.Request(url=url, callback=self.parse) def parse(self, response): table = pd....
nilq/baby-python
python
from future import standard_library standard_library.install_aliases() import datetime import json import os import re import time from collections import namedtuple, defaultdict from urllib.parse import urlparse, urljoin from io import BytesIO import flask import sqlalchemy.sql from flask import abort from flask impo...
nilq/baby-python
python
import os from datetime import datetime import numpy import xarray as xr from esdl.cate.cube_gen import CateCubeSourceProvider class OzoneTemisProvider(CateCubeSourceProvider): def __init__(self, cube_config, name='ozone_temis', dir=None, resampling_order=None): super().__init__(cube_config, name, dir, ...
nilq/baby-python
python
# # This example demonstrates using Lark with a custom lexer. # # You can use a custom lexer to tokenize text when the lexers offered by Lark # are too slow, or not flexible enough. # # You can also use it (as shown in this example) to tokenize streams of objects. # from lark import Lark, Transformer, v_args from lar...
nilq/baby-python
python
import json from .errors import JrsNodeNotFound from .refs_resolver import RefsResolver class Context(object): def __init__(self): self.schemas = {} self.nodes = {} self.refsResolver = RefsResolver(self) def addSchema(self, schema): self.schemas[schema.id] = schema def ...
nilq/baby-python
python
# Given a list of dominoes, dominoes[i] = [a, b] is equivalent to dominoes[j] = [c, d] if and only if either (a==c and b==d), or (a==d and b==c) - that is, one domino can be rotated to be equal to another domino. # Return the number of pairs(i, j) for which 0 <= i < j < dominoes.length, and dominoes[i] is equivalent t...
nilq/baby-python
python
from ralph.accounts.api import RalphUserSimpleSerializer from ralph.api import RalphAPIViewSet, router from ralph.assets.api.serializers import RalphAPISerializer from ralph.sim_cards.models import CellularCarrier, SIMCard, SIMCardFeatures class CellularCarrierSerializer(RalphAPISerializer): class Meta: m...
nilq/baby-python
python
"""Test runway.config.components.runway._test_def.""" # pylint: disable=no-self-use,protected-access # pyright: basic import pytest from pydantic import ValidationError from runway.config.components.runway import ( CfnLintRunwayTestDefinition, RunwayTestDefinition, ScriptRunwayTestDefinition, YamlLintR...
nilq/baby-python
python
""""@package This package enables the research group usage for the database. """ from src.models.employee import EmployeeDataAccess class ResearchGroup: """ This class defines a research group """ def __init__(self, name, abbreviation, logo_location, description_id, address, telephone_number, ...
nilq/baby-python
python
# MIT License # # Copyright (C) IBM Corporation 2018 # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated # documentation files (the "Software"), to deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge...
nilq/baby-python
python
import jimi, requests def reloadModule(module): # Apply system updates clusterMembers = jimi.cluster.getAll() for clusterMember in clusterMembers: headers = { "x-api-token" : jimi.auth.generateSystemSession() } requests.get("{0}{1}system/update/{2}/".format(clusterMember,jimi.api.base,jimi....
nilq/baby-python
python