content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
import math import numpy as np import viz def is_collinear(p1, p2, p3): return (p2[0] - p3[0]) * (p1[1] - p2[1]) == (p2[1] - p3[1]) * (p1[0] - p2[0]) def on_segment(p1, p2, p3): return (p1[0] < p3[0] < p2[0]) or (p1[0] > p3[0] > p2[0]) def orientation(p, q, r): return (q[1] - p[1]) * (r[0] - q[0]) -...
nilq/baby-python
python
""" Texext package """ from . import math_dollar from . import mathcode from ._version import get_versions __version__ = get_versions()['version'] del get_versions def setup(app): math_dollar.setup(app) mathcode.setup(app)
nilq/baby-python
python
from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext ext_modules = [ Extension( "qdr.ranker", sources=['qdr/ranker.pyx'], extra_compile_args=['-std=c++0x'], language="c++"), ] setup(name='qdr', version='0.0', de...
nilq/baby-python
python
from django.shortcuts import render from twobuntu.routers import ReadOnlyError class ReadOnlyMiddleware(object): """ Catch ReadOnlyError exceptions and display the appropriate error page. """ def process_exception(self, request, exception): if isinstance(exception, ReadOnlyError): ...
nilq/baby-python
python
import re from django import forms from .models import ( Filtro, ClasseFiltro, ItemFiltro ) class BaseModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for key in self.fields: field = self.fields[key] if type(fi...
nilq/baby-python
python
import os import logging from .app import app from .weather_services import OpenWeatherMapAPI, FakeWeatherAPI DEBUG = os.environ.get("FLASK_ENV", "production") == "dev" logging.basicConfig( level=logging.DEBUG if DEBUG else logging.INFO, format="[%(levelname)-5s] <%(name)-10s> %(lineno)-4s - %(message)s'", )...
nilq/baby-python
python
######################################################################### # File Name: test.py # Author: Walker # mail:qngskk@gmail.com # Created Time: Thu Dec 9 11:25:59 2021 ######################################################################### # !/usr/bin/env python3 import numpy as np import pandas as pd impor...
nilq/baby-python
python
import bpy, os from math import * def MAT_texture_new(name,size, colorspc, q_alpha = True): tex = bpy.data.images.get(name) if tex is None: tex = bpy.data.images.new(name, width=size[0], height=size[1], alpha = q_alpha) tex.colorspace_settings.name = colorspc else: #change re...
nilq/baby-python
python
from typing import TypedDict import re from xml.etree import ElementTree as ET ET.register_namespace("", "http://www.w3.org/2000/svg") class License(TypedDict): """License information for each icon.""" type: str url: str class Icon: """An icon with all relevant data and methods.""" def __init...
nilq/baby-python
python
import argparse class BaseEngine(object): def __init__(self, opt) -> None: self.opt = opt @staticmethod def modify_commandline_options(parser: argparse.ArgumentParser, additional_args=None): return parser
nilq/baby-python
python
from enum import Enum import pygame from pygame.locals import * import random from cell import Cell from pprint import pprint as pp from utils import _time class MouseBtnState(Enum): LEFT_BTN = 1 RIGHT_BTN = 3 NOTHING = 0 class GameOfLife: def __init__(self, width: int = 640, ...
nilq/baby-python
python
from app import app from flask import flash, redirect, url_for, render_template, request from app.forms import URLForm, LoginForm from app.pulltext import pull_text @app.route("/", methods=['GET','POST']) @app.route("/index", methods=['GET','POST']) def index(): form = URLForm() if form.validate_on_submit(): ...
nilq/baby-python
python
import mysql.connector class Database: mydb = mysql.connector.connect( host="localhost", user="root", passwd="Piku123.", database="datascience" ) mycursor = mydb.cursor() def __init__(self): pass def execute_query_with_params(self, query, params): ...
nilq/baby-python
python
# Copyright (C) 2017, 2018 International Business Machines Corporation # All Rights Reserved import os import sys import json import streamsx.rest ################### parameters used in this script ############################ here = os.path.dirname(os.path.realpath(__file__)) vcapFilename = here + '/vcap.json' #...
nilq/baby-python
python
import os relative_path = "../hierarchical_localization/Hierarchical-Localization/datasets/inloc/query/iphone7/" image_paths = [relative_path + f for f in os.listdir(relative_path) if f.endswith(".JPG")] with open("image_list_inloc.txt", 'w') as f: f.write("\n".join(map(str, image_paths)))
nilq/baby-python
python
# Copyright 2016 Euclidean Technologies Management LLC 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 requi...
nilq/baby-python
python
import DistConvGAN as model import lbann.contrib.launcher import lbann.contrib.args import argparse import os from lbann.core.util import get_parallel_strategy_args import lbann import lbann.modules as lm def list2str(l): return ' '.join([str(i) for i in l]) def construct_lc_launcher_args(): parser = argpars...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """django-sqlprint-middleware - pretty-print Django's SQL statments. """ import io from setuptools import setup version = '0.1.3' setup( name='django-sqlprint-middleware', version=version, packages=['django_sqlprint_middleware'], install_requires=[ ...
nilq/baby-python
python
from dirutility import DirPaths from looptools.timer import Timer def test_case(case): test_cases = { 'projects': { 'rootpath': '/Volumes/Storage/HPA Design', 'exclude': [ '20080081_Rosenfeld_Realty', '20080082_Clarewood_Homes_WEB', '20080083_Dipersio_WE...
nilq/baby-python
python
from graphviz import Digraph from nujo.autodiff._node import _Node from nujo.autodiff.tensor import Tensor class ComputationGraphPlotter: ''' Computation Graph Plotter Uses graphviz. ''' def __init__(self, **kwargs): self.computation_graph = Digraph(**kwargs) @staticmethod def ...
nilq/baby-python
python
import math def cal_pmv(ta=None, tr=None, rh=None, v=None, clo=None, met=None, top=None, w=0): """ This function is used to calculated Predicted Mean Vote(PMV) through environmental parameters cal_pmv(ta=None, tr=None, rh=None, v=None, clo=None, met=None, top=None, w=0) ta: Air temp...
nilq/baby-python
python
from pydantic import ValidationError from one_time_secret.app import schemas def test_good_argument(): validation_model = schemas.SecretKey( secret_key="984ae013e1304e54a5b2a1aec57fac36", ) expected = "984ae013e1304e54a5b2a1aec57fac36" assert validation_model.secret_key == expected def test...
nilq/baby-python
python
input() l = list(map(int, input().split())) l_ = [str(i) for i in range(len(l))] again = True while again: again = False for i in range(len(l)-1): if l[i] > l[i+1]: l[i], l[i+1], l_[i], l_[i+1] = l[i+1], l[i], l_[i+1], l_[i] again = True print(" ".join(l_))
nilq/baby-python
python
from boa.interop.Neo.App import RegisterAppCall CalculatorContract = RegisterAppCall(b'W\xa7\x18\x08MZh\xbdu\xb7%\x88\x8e\x19J\x9e\xd4|\xe1\xe3\xaa', 'operation', 'a', 'b') def Main(operation, a, b): result = CalculatorContract(operation, a, b) return result
nilq/baby-python
python
import numpy as np import config class Trajectory: """ Trajectory class using trajectory generation with via points, with constant velocity segments and continous acceleration blends. For more info on this check out W.Khalils book Modeling, identification and control of robots Formulas and c...
nilq/baby-python
python
import numpy as np np.random.seed(38) def generate_synth_part_circle_dataset(boundary, N_data=1000000, dataset_save_path_prefix_name='circle_random'): """ Generate 2 datasets on a circle of radius 1.0 (unit circle): [1] Training dataset: between boundary and 2*pi ...
nilq/baby-python
python
import logging from submission_broker.submission.entity import Entity from submission_broker.submission.submission import Submission from submission_broker.validation.base import BaseValidator from submission_validator.services.ena_taxonomy import EnaTaxonomy class TaxonomyValidator(BaseValidator): def __init__...
nilq/baby-python
python
__author__ = 'Tom Schaul, tom@idsia.ch' from pybrain.rl.agents.agent import Agent class OptimizationAgent(Agent): """ A simple wrapper to allow optimizers to conform to the RL interface. Works only in conjunction with EpisodicExperiment. """ def __init__(self, module, learner): self.module...
nilq/baby-python
python
import register while True: cadastro = [ register.registro() ] historico_paciente = register.historico() break salvar = register.cria_arquivo(cadastro, historico_paciente)
nilq/baby-python
python
# Contributed by t0rm3nt0r (tormentor2000@mail.ru) to the Official L2J Datapack Project # Visit http://www.l2jdp.com/forum/ for more details. import sys from com.l2jserver.gameserver.model.quest import State from com.l2jserver.gameserver.model.quest import QuestState from com.l2jserver.gameserver.model.quest.jython imp...
nilq/baby-python
python
import os import sys from scrapy.cmdline import execute from .settings import TEMPLATES_DIR def main(): argv = sys.argv if len(argv) > 1: cmdname = argv[1] if cmdname == 'genspider': argv += ['-s', f'TEMPLATES_DIR={TEMPLATES_DIR}'] execute(argv=argv) if __name__ == "__main_...
nilq/baby-python
python
"""Check that static assets are available on consumerfinance.gov""" import argparse import logging import sys import time import requests from bs4 import BeautifulSoup as bs logger = logging.getLogger('static_asset_smoke_tests') logger.setLevel(logging.ERROR) shell_log = logging.StreamHandler() shell_log.setLevel(lo...
nilq/baby-python
python
import numpy as np import os import pickle import torch from torch.utils.data import Dataset import bball_data.cfg as cfg from bball_data.utils import normalize DATAPATH = cfg.DATAPATH N_TRAIN = cfg.N_TRAIN N_TEST = cfg.N_TEST SEQ_LENGTH = cfg.SEQUENCE_LENGTH X_DIM = cfg.SEQUENCE_DIMENSION class BBallData(Dataset...
nilq/baby-python
python
transitions = None events = None commands = None def reset_events(_): pass def actions(_): pass def state(_): pass initial_state = state
nilq/baby-python
python
import pyb import data_logger kill_switch = data_logger.SoftSwitch() pyb.Switch().callback(lambda:kill_switch.press()) log = data_logger.logger_Rx(6, 1, 32, kill_switch, '/sd/data-set.bin', \ pyb.LED(4)) def main(): pyb.LED(3).on() log.begin() log.end(5000) pyb.LED(3).off...
nilq/baby-python
python
#!/usr/bin/env python """ ipmongo Author: wal1ybot <https://github.com/wal1ybot/ipmongo> Please refer to readme for details. <https://github.com/wal1ybot/ipmongo/blob/master/README.md> Please refer to the following LICENSE file for licence information. <https://github.com/wal1ybot/ipmongo/blob/master/LICENSE> """...
nilq/baby-python
python
import os import re # resolves name to an object has in the repo from util.ref_handling.ref_resolver import ref_resolver from util.repo_handling.repo_dir import repo_dir def object_resolve(repo, name): candidates = list() hashReg = re.compile(r"^[0-9A-Fa-f]{1.16}$") smallHashReg = re.compile(r"^[0-9A-Fa-f...
nilq/baby-python
python
import unittest class JoystickTypeTest(unittest.TestCase): def todo_test_Joystick(self): # __doc__ (as of 2008-08-02) for pygame.joystick.Joystick: # pygame.joystick.Joystick(id): return Joystick # create a new Joystick object # # Create a new joystick to...
nilq/baby-python
python
# from rest_framework.parsers import JSONParser # from rest_framework.decorators import api_view from rest_framework import generics from rest_framework.response import Response from rest_framework.reverse import reverse from rest_framework import status from .models import Dog from .models import Breed from .serializ...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # Created on 9/18/19 by Pat Daburu """ .. currentmodule:: synolo_flask.apis .. moduleauthor:: Pat Daburu <pat@daburu.net> This package contains the API descriptions. """ from .api import api, API_ROOT
nilq/baby-python
python
#PyBank Script import os import csv import numpy as np #Get the filename to open fileName = "budget_data_1.csv" #set paths for files bankBudget_csv = os.path.join("raw_data", fileName) #Variables to track budget totMonths = 0 totRev = 0 lmRev = 0 revChg = 0 revChgLst = [] #create a list to store the monthly rev ch...
nilq/baby-python
python
import torch from allrank.data.dataset_loading import PADDED_Y_VALUE from allrank.models.losses import DEFAULT_EPS """Here are the NDCGLoss1 and NDCGLoss2(++) losses from The LambdaLoss Framework for Ranking Metric Optimization. Please note that we are sticking to array operations most of the time, only applying a pa...
nilq/baby-python
python
import os.path import fipy as fp import matplotlib.pyplot as plt import numpy as np from .dicttable import DictTable class _BaseViewer(object): def plot(self, indices=[0], filename=None, times=None, cutoffvalue=-1, mirror=False, cutoff=True, labels=False, show=True, xlim=12e-6, ylim=-60e-6): self.mirror ...
nilq/baby-python
python
# -*- coding: utf-8 -*- import datetime import difflib import time import re def allmusic_albumfind(data, artist, album): data = data.decode('utf-8') albums = [] albumlist = re.findall('class="album">\s*(.*?)\s*</li', data, re.S) for item in albumlist: albumdata = {} albumartist = re.s...
nilq/baby-python
python
import json import random import copy activity_dict_file = open('/media/minhhieu/DATA/HOC/Thesis/reinforcement_bot/reinforcement_learning_bot/activity_dict.json',encoding='utf-8') activity_dict = json.load(activity_dict_file) activity_list = [activity for activity in list(activity_dict[0].keys()) if activity != 'othe...
nilq/baby-python
python
# author: Bartlomiej "furas" Burek (https://blog.furas.pl) # date: 2022.03.30 # [python - How to export scraped data as readable json using Scrapy - Stack Overflow](https://stackoverflow.com/questions/71679403/how-to-export-scraped-data-as-readable-json-using-scrapy) import time import scrapy #import json from scrapy....
nilq/baby-python
python
from django.core.exceptions import ObjectDoesNotExist from rest_framework import status from rest_framework.response import Response from crosswalk.authentication import AuthenticatedView from crosswalk.models import Domain, Entity class DeleteMatch(AuthenticatedView): def post(self, request, domain): ""...
nilq/baby-python
python
# -*- coding: utf-8 -*- import sys sys.path.append('..') import ecopann.ann as ann import ecopann.coplot.plot_contours as plc import ecopann.cosmic_params as cosmic_params import simulator import matplotlib.pyplot as plt import numpy as np #%% observational data fid_params = [-1, 0.3] sim_mu = simulator.sim_SNe(fid...
nilq/baby-python
python
from Chamaeleo.methods.default import AbstractCodingAlgorithm from Chamaeleo.utils.indexer import connect from Chamaeleo.methods import inherent ''' Typical values that we use are p = 8, q = 10, s = 46, so that p + q + s = 64 bits s bits of "salt" low q bits of index i p bits of previous bits ''' class HEDGES(Abst...
nilq/baby-python
python
from projects.models.k8s import * from projects.models.project import *
nilq/baby-python
python
import argparse import skorch import torch from sklearn.model_selection import GridSearchCV import data from model import RNNModel from net import Net parser = argparse.ArgumentParser(description='PyTorch PennTreeBank RNN/LSTM Language Model') parser.add_argument('--data', type=str, default='./data/penn', ...
nilq/baby-python
python
import pytest from kopf.structs.references import EVERYTHING, Resource, Selector @pytest.fixture() def resource(): return Resource( group='group1', version='version1', preferred=True, plural='plural1', singular='singular1', kind='kind1', shortcuts=['shortcut1', 'shortcut2'], categ...
nilq/baby-python
python
# Copyright (c) 2015. Mount Sinai School of Medicine # # 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 o...
nilq/baby-python
python
"""Behave environment setup commands""" import os import shutil import stat import tempfile from pathlib import Path from features.steps.sh_run import run from features.steps.util import create_new_venv def before_scenario(context, scenario): # pylint: disable=unused-argument """Environment preparation before ...
nilq/baby-python
python
import json class FileService: ''' Contains methods responsible with handling files. ''' def __init__(self, filepath): ''' Configure the filepath for use in methods. ''' self.filepath = filepath def read_appsettings(self): ''' Reads the a...
nilq/baby-python
python
''' Tests the io functions of prysm. ''' from pathlib import Path import pytest from prysm.io import read_oceanoptics def test_read_oceanoptics_functions(): # file, has 2048 pixels p = Path(__file__).parent / 'io_files' / 'valid_sample_oceanoptics.txt' data = read_oceanoptics(p) # returns dict with...
nilq/baby-python
python
from django.urls import path from django.shortcuts import render from . import views app_name = 'api' urlpatterns = [ path('network/online', views.network_online), path('node/<yagna_id>', views.node), path('website/globe_data', views.globe_data), path('website/index', views.golem_main_website_index), ...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/7/9 15:45 # @Author : Hyperwd # @contact : 435904632@qq.com # @File : sign.py # @description : 华为云基于AK,SK的认证 # This version makes a GET request and passes the signature in the Authorization header. import datetime import hashl...
nilq/baby-python
python
# uncompyle6 version 3.7.4 # Python bytecode 3.7 (3394) # Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] # Embedded file name: T:\InGame\Gameplay\Scripts\Server\routing\portals\portal_cost.py # Compiled at: 2017-10-12 02:00:35 # Size of source mod 2**32: 1719 b...
nilq/baby-python
python
import numpy as np from numpy.testing import assert_raises from pysplit import make_trajectorygroup def test_bogus_signature(): signature = './nothing_to_see_here*' assert_raises(LookupError, make_trajectorygroup, signature) def test_bogus_filenames(): filenames = ['./not_a_trajectory0', ...
nilq/baby-python
python
#!/usr/bin/env python # coding: utf8 """Example of training spaCy's entity linker, starting off with a predefined knowledge base and corresponding vocab, and a blank English model. For more details, see the documentation: * Training: https://spacy.io/usage/training * Entity Linking: https://spacy.io/usage/linguistic-...
nilq/baby-python
python
import text_plus_image import os ''' Test cases: image_size text_word_number 40 x 40 1 60 x 400 2 400 x 600 * 5 600 x 40 10 600 x 400 100 ''' image = ["40_40.jpg", "60_400.jpg", "400_600.jpg", "600_40.jpg", "600_400.jpg"] text = ['c...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/10/30 下午6:07 # @Author : Lee才晓 # @Site : www.rich-f.com # @File : dict_view.py # @Software: 富融钱通 # @Function: 字典模块逻辑操作 import io import time import xlrd import xlwt import logging from flask import Blueprint, render_template, request, json, make_res...
nilq/baby-python
python
def BLEU_score(gt_caption, sample_caption): """ gt_caption: string, ground-truth caption sample_caption: string, your model's predicted caption Returns unigram BLEU score. """ reference = [x for x in gt_caption.split(' ') if ('<END>' not in x and '<START>' not in x and '<UNK>' ...
nilq/baby-python
python
# -*- coding: utf-8 -*- ''' Created on 2020.05.19 @author: Jiahua Rao, Weiming Li, Hui Yang, Jiancong Xie ''' import os import json import yaml import pickle import logging import numpy as np import pandas as pd from tqdm import tqdm from pathlib import Path import torch import torch.nn as nn from rdkit import C...
nilq/baby-python
python
import json import os import sys import click from rich import print_json from labfunctions import client, defaults from labfunctions.client.diskclient import DiskClient from labfunctions.conf import load_client from labfunctions.context import create_dummy_ctx from labfunctions.executors import jupyter_exec from lab...
nilq/baby-python
python
from django.shortcuts import render from product.models import Product # Create your views here. def index(request): ''' Disp the home page ''' context = {'product': Product.objects.all().filter(on_sale=True)} context['loop_times'] = range(0, len(context['product'])) return render(request, 'captain/ind...
nilq/baby-python
python
import pyotp from datetime import datetime import hashlib from random import randint from wallet.models import Transaction def getOTP(): sysotp = pyotp.TOTP('base32secret3232') sysotp = int(sysotp.now()) time = datetime.now() time = str(time) hash = hashlib.sha3_512(time.encode('utf-8')).hexdige...
nilq/baby-python
python
import requests import time import math # insert api token api_token = "" # called in _get_user_data. Returns all pages that a user follows def _get_user_subscriptions(user_id): try: # The VK api returns 1000 results a time so we need to make multiple requests to collect all data amou...
nilq/baby-python
python
from .http import Http import json class Friends: def getFriendList(id, page): try: res = Http.sendRequest("https://api.roblox.com/users/" + str(id) + "/friends?page=" + str(page)) res_decoded = res.decode("utf-8") res_loads = json.loa...
nilq/baby-python
python
# Generated by Django 3.2 on 2021-09-04 13:13 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('deals', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='deal', name='deal_date', ), ]
nilq/baby-python
python
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2018-05-21 14:31 from __future__ import unicode_literals from django.db import migrations, models import localflavor.us.models class Migration(migrations.Migration): dependencies = [ ('business', '0005_business_status'), ] operations = [ ...
nilq/baby-python
python
# Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. import json import os import warnings from unittest import mock import nose.tools as nt from IPython.core import display from IPython.core.getipython import get_ipython from IPython.utils.io import capture_output fr...
nilq/baby-python
python
""" Copyright 2020-2021 Nocturn9x, alsoGAMER, CrisMystik 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 t...
nilq/baby-python
python
from .caffeNetFaceDetector import CaffeNetFaceDetector
nilq/baby-python
python
__version__ = "4.1" __build__ = "GIT_COMMIT" import logging logger = logging.getLogger(__name__) try: import subprocess import os import platform FNULL = open(os.devnull, 'w') if platform.system() == "Windows": args = ['git', 'describe', '--tags'] else: args = ['git describe --...
nilq/baby-python
python
N = int(input()) A = list(map(int, input().split())) if A.count(0) >= 1: print(0) exit(0) L = 10**18 ans = A[0] for i in range(1, N): ans *= A[i] if ans > L: print(-1) exit(0) print(ans)
nilq/baby-python
python
from django.contrib.auth.models import AbstractUser from django.db.models import IntegerChoices, Model, IntegerField, CharField, TextField, ForeignKey, ManyToManyField, \ FileField, DateTimeField, CASCADE from django.utils.functional import cached_property from martor.models import MartorField class AppUser(Abst...
nilq/baby-python
python
from _thread import RLock from datetime import datetime from io import TextIOWrapper, StringIO from logging import Logger, LogRecord from logging.handlers import MemoryHandler from unittest import TestCase from unittest.mock import patch import pytest from osbot_utils.utils.Json import json_load_file from osbot_utils...
nilq/baby-python
python
import json from dinofw.utils.config import MessageTypes, ErrorCodes, PayloadStatus from test.base import BaseTest from test.functional.base_functional import BaseServerRestApi class TestDeleteAttachments(BaseServerRestApi): def test_payload_status_updated(self): group_message = self.send_1v1_message( ...
nilq/baby-python
python
import os from yaml import ( SafeLoader, load ) from pydantic import ( BaseSettings, BaseModel ) from typing import Any from pathlib import Path def default_yaml_source_settings(settings: BaseSettings): curr_dir = os.path.dirname(os.path.abspath(__file__)) return load( Path(f"{curr_dir}/defaults.yml"...
nilq/baby-python
python
class Solution: def XXX(self, s: str) -> bool: s1='' AZ='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' for c in s: if c in AZ : s1+=c.upper() if s1==s1[::-1]: return True else: return False
nilq/baby-python
python
# Copyright 1999-2017 Tencent Ltd. # # 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 writ...
nilq/baby-python
python
import time users = {} status = "" def mainMenu(): global status status = input("Do you have an existing account (Y/N)?\nPress Q to quit.\n") if status == "y" or "Y": existingUser() elif status == "n" or "N": newUser() elif status == "q" or "Q": quit() ...
nilq/baby-python
python
class StatsHandler(object): def __init__(self): self._core = {} self.ingredient_num = 0 def add_entry(self, ingredients): self.ingredient_num += len(ingredients) for entry in ingredients: if not entry in self._core.keys(): self._core[entry] = {} for e in ingredients: if entry == e: conti...
nilq/baby-python
python
from collections import Counter ACC = "acc" JMP = "jmp" NOP = "nop" class CycleError(Exception): ... class Computer: def __init__(self, data): self.data = data def load(self): head = acc = 0 while True: op, value = yield head, acc if op == ACC: ...
nilq/baby-python
python
# Copyright (c) 2017 Ansible, Inc. # All Rights Reserved. from django.urls import re_path from awx.api.views import ( AdHocCommandList, AdHocCommandDetail, AdHocCommandCancel, AdHocCommandRelaunch, AdHocCommandAdHocCommandEventsList, AdHocCommandActivityStreamList, AdHocCommandNotification...
nilq/baby-python
python
from buildtest.menu.build import discover_buildspecs tagname = ["tutorials"] print(f"Searching by tagname: {tagname}") included_bp, excluded_bp = discover_buildspecs(tags=tagname) print("\n Discovered buildspecs: \n") [print(f) for f in included_bp]
nilq/baby-python
python
from collections import defaultdict def concept2dict(concepts): d = defaultdict(list) for c in concepts: d[c.index].append(c._asdict()) return d
nilq/baby-python
python
# Copyright 2016-present CERN – European Organization for Nuclear Research # # 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...
nilq/baby-python
python
# GENERATED BY KOMAND SDK - DO NOT EDIT import komand import json class Input: DAYS_BACK = "days_back" EXCLUDE = "exclude" LIMIT = "limit" QUERY = "query" class Output: RESPONSE = "response" class RegistrantMonitorInput(komand.Input): schema = json.loads(""" { "type": "object"...
nilq/baby-python
python
from flask import Flask, render_template, request from models import db, User import psycopg2, logging app = Flask(__name__) output_file = open("query.sql", "w+") output_file.close() POSTGRES = { 'user': 'postgres', 'db': 'airportdb', 'host': 'localhost', 'port': '5432', } app.config['DEBUG'] = True app.config['S...
nilq/baby-python
python
from __future__ import print_function import argparse import torch import torch.utils.data from torch import nn, optim from torch.nn import functional as F from torchvision import datasets, transforms from torch.utils.data import DataLoader from torchvision.utils import save_image from vmodel import * from vdataset imp...
nilq/baby-python
python
dias = int(input('Quantos dia foram alugados? ')) quilometros = float(input('Quantos Km foram rodados?')) total = (dias*60)+(quilometros*0.15) print('O valor a ser pago do aluguel é de R${:.2f}'.format(total))
nilq/baby-python
python
from django.apps import AppConfig class CalorieConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'calorie' def ready(self): #new import calorie.signals #new
nilq/baby-python
python
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str __all__ = ['stmts_from_json', 'stmts_from_json_file', 'stmts_to_json', 'stmts_to_json_file', 'draw_stmt_graph', 'UnresolvedUuidError', 'InputError'] import json import logging from indra.state...
nilq/baby-python
python
#!/usr/bin/env python3 # Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 import argparse import sys from scripts_lib import start_riscv_dv_run_cmd, run_one def main() -> int: parser = argparse.ArgumentParser() ...
nilq/baby-python
python
"""JWT Helper""" import json import time from jose import jwt def create_jwt(config, payload={}): with open(config["AssertionKeyFile"], "r") as f: assertion_key = json.load(f) header = { "alg": "RS256", "typ": "JWT", "kid": assertion_key["kid"], } _payload = { ...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """Script to generate GZIP file specimens.""" from __future__ import print_function from __future__ import unicode_literals import argparse import gzip import os import sys def Main(): """The main program function. Returns: bool: True if successful or False if ...
nilq/baby-python
python
from abc import ABC from typing import Generic, TypeVar from .serializers import serializer from .backends import storage_backend T = TypeVar("T") class KeyValueStore(Generic[T]): """ KeyValueStore ============= Abstract class for a key-value store combining a storage backend with a serializer-d...
nilq/baby-python
python