content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
import subprocess import os from pathlib import Path import glob os.remove('text.txt') os.system('E:/ChromeCacheView.exe /scomma D:/Studies/nsfw_test/text.txt') fo = open("text.txt", "r") while True: line = fo.readline() if not line: break data=line.split(",",2) if "data_2...
nilq/baby-python
python
""" Global Template Variables """ # Standard Library import os # Local Library from app.modules.entity.option_entity import OptionEntity def globals(request): option_entity = OptionEntity() return { "google_account": option_entity.get_value_by_key("google_analytics_account", ""), "app_time...
nilq/baby-python
python
# get rid of this for python2.6+ import imp, sys, os def imp_path(): cwd = os.path.realpath('.') return [path for path in sys.path if os.path.realpath(path) != cwd] try: json = imp.load_module('json', *imp.find_module('json', imp_path())) loads, dumps = json.loads, json.dumps except ImportError: t...
nilq/baby-python
python
from enum import Enum class Trend(Enum): NONE = 0 DoubleUp = 1 SingleUp = 2 FortyFiveUp = 3 Flat = 4 FortyFiveDown = 5 SingleDown = 6 DoubleDown = 7 NotComputable = 8 RateOutOfRange = 9
nilq/baby-python
python
""" this is a practice file """ import math math.floor(3.4)
nilq/baby-python
python
import tensorflow as tf def loss_fn(y_true, y_pred): return tf.reduce_mean(tf.keras.losses.categorical_crossentropy(y_true, y_pred)) def accuracy_fn(y_true, y_pred): y_true = tf.cast(tf.argmax(y_true, axis=-1), tf.float32) y_pred = tf.cast(tf.argmax(y_pred, axis=-1), tf.float32) compare = tf.cast(tf...
nilq/baby-python
python
import django from django.conf import settings def pytest_configure(): settings.configure( INSTALLED_APPS=[ 'django.contrib.contenttypes', 'django.contrib.auth', ], ROOT_URLCONF='djangoapp.urls', STATIC_URL='/static/', LANGUAGE_CODE='en', SIT...
nilq/baby-python
python
#!/usr/bin/env python from matplotlib import pyplot as pp import numpy as np import sys def levenstein(source, target): if len(source) < len(target): return levenstein(target, source) if len(target) == 0: return len(source) source = np.array(tuple(source)) target = np.array(tuple(targ...
nilq/baby-python
python
__all__ = [ 'q1_collections_counter', 'q2_defaultdict_tutorial', 'q3_py_collections_namedtuple', 'q4_py_collections_ordereddict', 'q5_word_order', 'q6_py_collections_deque', 'q7_most_commons', 'q8_piling_up', ]
nilq/baby-python
python
""" Utility functions for plotting figures consistently across different parts of the project """ import matplotlib.pyplot as plt def set_font_size(): """ Function which sets a standardized font size for all figures. Call this prior to plotting to apply the standard """ SMALLER_SIZE = 10 MED_S...
nilq/baby-python
python
""" Status of the API. """ from flask import request from flask_restful import Resource class Working(Resource): """ Working reveals whether or not connection to API is working. """ def get(self): """ /working/ Args: xx Returns...
nilq/baby-python
python
# SPDX-License-Identifier: Apache-2.0 # # Copyright (C) 2016, ARM Limited and contributors. # # 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 # # ...
nilq/baby-python
python
from __future__ import absolute_import, division, print_function, unicode_literals from typing import List import tempfile from io import StringIO import pandas as pd from Bio import AlignIO, SeqIO, Phylo from Bio.Align import MultipleSeqAlignment from Bio.Align.Applications import ClustalOmegaCommandline from .Alig...
nilq/baby-python
python
import sys def input(): return sys.stdin.readline()[:-1] N, M = map(int, input().split()) tree = [[] for i in range(N)] for _ in range(M): a, b = map(int, input().split()) a -= 1 b -= 1 tree[a].append(b) tree[b].append(a) ans = [[] for i in range(N)] for target_no in range(N): for t_fri...
nilq/baby-python
python
import asyncio import re from functools import partial import pytest from dagster import ( AssetKey, AssetMaterialization, AssetObservation, DynamicOut, DynamicOutput, DynamicOutputDefinition, ExpectationResult, Failure, Field, In, InputDefinition, Materialization, ...
nilq/baby-python
python
from pytest import approx from CompAero.FannoFlowRelations import FannoFlowRelations as ffr from CompAero.internal import FlowState as FS class TestFannoClassFuncs: gamma = 1.4 # Test the Functions for Subsonic Case ####################################################################################### ...
nilq/baby-python
python
import json, os, copy def tag_check(resourceTags, include=True): checkTags = json.loads(os.environ['checkTags']) tagResults = copy.copy(checkTags) if include == True: for cTag in checkTags: for rTag in resourceTags: #Check each check Tag where there is both a key and val...
nilq/baby-python
python
import itertools def get_output_filename(input_filename): return input_filename.replace('input', 'output') class Checksum: day = 2 test = 2 def get_input_filename(self): return "day" + str(self.day).zfill(2) + ".input" def process(self, raw_input): input_spreadsh...
nilq/baby-python
python
from typing import Iterable, List from .syntax import Field, NodeType, Syntax from .node import Node class CField(Field): PATH = "path" NAME = "name" VALUE = "value" PARAMETERS = "parameters" directive = "directive" argument = "argument" OPERATOR = "operator" FUNCTION = "function" A...
nilq/baby-python
python
#from __future__ import unicode_literals from twisted.internet import reactor, endpoints from twisted.internet.defer import inlineCallbacks from ..transit_server import Transit class ServerBase: log_requests = False @inlineCallbacks def setUp(self): self._lp = None if self.log_requests: ...
nilq/baby-python
python
#execute(object) #object will be the python code a = "print('hiii')" print(exec(a))
nilq/baby-python
python
# -*- coding: utf-8 -*- """Walker that performs simple name-binding analysis as it traverses the AST""" import ast from .util import merge_dicts from .walkers import Walker from . import compat __all__ = ['Scoped'] @Walker def find_names(tree, collect, stop, **kw): if isinstance(tree, (ast.Attribute, ast.Subs...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # File: train.py import argparse import itertools import numpy as np import os import cv2 import six import shutil assert six.PY3, "FasterRCNN requires Python 3!" import tensorflow as tf import tqdm import tensorpack.utils.viz as tpviz from tensorpack import * from tenso...
nilq/baby-python
python
import csv import matplotlib.pyplot as plt import numpy as np def MC_size_dependence(): f = open("./size_dep.csv", 'r') x = csv.reader(f) size_MC = [] times = [] for i in x: size_MC.append(int(i[0])) times.append(int(i[1])) fig = plt.figure() plt.plot(size_MC, times) plt...
nilq/baby-python
python
# Copyright 2021 Katteli Inc. # TestFlows.com Open-Source Software Testing Framework (http://testflows.com) # # 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/lice...
nilq/baby-python
python
#!/bin/python ## subnetMask = input('Enter your subnet mask in dotted-decimal notation: ') o1 = int(subnetMask.split('.')[0]) o2 = int(subnetMask.split('.')[1]) o3 = int(subnetMask.split('.')[2]) o4 = int(subnetMask.split('.')[3]) print('Your subnet mask in binary is: {0:08b}.{1:08b}.{2:08b}.{3:08b}'.format(o1, o2, ...
nilq/baby-python
python
import time import numpy as np import cv2 import open3d as o3d from numba import njit, prange import pycuda.autoinit import pycuda.driver as cuda from pycuda import gpuarray from matplotlib import pyplot as plt from pf_pose_estimation.tsdf_lib import TSDFVolume from pf_pose_estimation.cuda_kernels import source_modul...
nilq/baby-python
python
import re import os import requests from xml.dom.minidom import ( parseString, parse as parseFile, Text as TextNode, ) from ...conventions import LOCAL_PATH from .. import readers class DNFRepositoryMetalink: def __init__(self, baseurl, repo, architecture): self.baseurl = baseurl self...
nilq/baby-python
python
# Generated by Django 3.1.5 on 2021-07-11 17:27 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('profiles', '0001_initial'), ('classroom', '0001_initial'), ] operations = [ migrations.AlterField( ...
nilq/baby-python
python
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
nilq/baby-python
python
from django.http import JsonResponse from django_filters.rest_framework import DjangoFilterBackend from rest_framework import permissions from rest_framework.decorators import action from rest_framework.response import Response from rest_framework.viewsets import ModelViewSet from django_cookie_app import models from...
nilq/baby-python
python
import os import re import numpy as np import pandas as pd FILE_ROOT_PATH = os.path.dirname(os.path.abspath(__file__)) source = os.path.join(FILE_ROOT_PATH, '9889.xlsx') output = os.path.join(FILE_ROOT_PATH, 'result_9889.xlsx') def merge_sheets(path: str) -> pd.DataFrame: '''将每个表格的sheet页中日期、期货成交汇总、期货持仓汇总聚集到一起 ...
nilq/baby-python
python
from ligeor import TwoGaussianModel as TwoG import numpy as np def test_initialize_filename(filename, data): model = TwoG(filename=filename, n_downsample=1, delimiter=',') assert(((model.phases == data[:,0]) & (model.fluxes == data[:,1]) & (model.sigmas == data[:,2])).all()) def test_initialize_data(dat...
nilq/baby-python
python
""" 小结 - 实例成员与类成员 创建 实例变量在构造函数中:对象.变量名 = 数据 实例方法: def 方法名(self): pass 类变量在类中方法外:变量名 = 数据 类方法: @classmethod def 方法名(cls): pass 使用 实例变量:对象.变量名 ...
nilq/baby-python
python
import argparse import json import os.path as pth import sys from glob import iglob from typing import Any, Callable, Dict from typing import MutableMapping as Map from typing import Optional, Type, Union, cast from ..core.fp import OneOf from ..core.io import CiTool, env, error_block from ..core.issue import Issue fr...
nilq/baby-python
python
import hashlib import os import pickle from urllib.request import urlretrieve import numpy as np from PIL import Image from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelBinarizer from sklearn.utils import resample from tqdm import tqdm from zipfile import ZipFile import math ...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Created on Fri Sep 7 13:10:58 2018 @author: Joseph Bell Geoscience Australia """ ''' reads a csv file and adds DGGS to it This is for placeNames Placenames is from 2018 A query was used to gather basic placename data into a csv Code fields were converted into their full te...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Copyright 2018 IBM. # # 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 agre...
nilq/baby-python
python
from scapy.all import * from flpr import FLPR, FLPR_PORT from ifaces import ifaces from util import ban_ip # verify that the last IP in history is the receiver's IP def ips_flpr_2(pkt): ip = pkt[IP] flpr = pkt[FLPR] print("flipper message received, ID = %s, CTR = %s, LIM = %s" % (flpr.id, flpr.ctr, flpr....
nilq/baby-python
python
#!/usr/bin/env python3 from boldui import Oplist, Expr, var, stringify_op, ProtocolServer from boldui.framework import Clear, Column, Padding, Center, SizedBox, Rectangle, Text, Flexible def main(): root = Clear( color=0xff202030, child=Column([ Padding( Text( ...
nilq/baby-python
python
from Services import ApiService from Services import DBService import logging logger = logging.getLogger('Roby') #This class can be viewd as an AbstractFactory # for the adapters, because the data source # can be different # Registry / Service container of the Classes that # can adapt to different data sources or ser...
nilq/baby-python
python
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import time import sys, signal import tensorflow as tf import utils as ut from agent import Agent from envs import create_env logger = ut.logging.get_logger() def train(args, server, cluster, env,...
nilq/baby-python
python
def sortedSquaredArray(array): # Write your code here. sortedSquared=[0 for _ in array] smallIndex =0 largeIndex=len(array)-1 for idx in reversed(range(len(array))): if abs(array[smallIndex])>abs(array[largeIndex]): sortedSquared[idx] = array[smallIndex]*array[smallIndex] ...
nilq/baby-python
python
import cv2 import os import scipy as scp import scipy.misc import numpy as np def triangStats(img, noHoles = False, minPercArea = 0.1): imggray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret, imbw = cv2.threshold(imggray, 10, 255, 0) _, contours, _ = cv2.findContours(imbw, 1, 2) maxArea = 0; Ax = ...
nilq/baby-python
python
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
nilq/baby-python
python
# Generated by Django 2.1.7 on 2019-09-20 15:49 from django.conf import settings import django.core.validators from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AU...
nilq/baby-python
python
import os import sys from collections import defaultdict, OrderedDict from geodata.encoding import safe_decode, safe_encode from geodata.i18n.unicode_paths import DATA_DIR from geodata.text.normalize import normalized_tokens, normalize_string from geodata.text.tokenize import tokenize, token_types from geodata.text.p...
nilq/baby-python
python
#!/usr/bin/python3 """cleaning gentx data """ import json import logging # ## Preface: python data tools import pandas as pd log = logging.getLogger(__name__) BORING = ['Verified', 'Task Type', 'Event', 'Submission Link'] def main(argv, stdout, cwd): log.info('versions: %s', dict(pandas=pd.__version__)) [p...
nilq/baby-python
python
from . import startup from . import models from . import services from fastapi.responses import JSONResponse import json import random app = startup.app redisDb = startup.redisDb card_collection = models.CardCollection(startup.source) @app.get("/decks") def get_decks(): """ Returns all deck types """ ...
nilq/baby-python
python
import sys input = lambda: sys.stdin.readline().rstrip() n, m = map(int, input().split()) s = {input() for _ in range(n)} l = [] for _ in range(m): t = input() if t in s: s.remove(t) l.append(t) l.sort() print(len(l), *l, sep="\n")
nilq/baby-python
python
""" Backward compatible behaviour with a primary key 'Id' and upper-case field names """ from django.db import models class User(models.Model): username = models.CharField(max_length=80) last_name = models.CharField(max_length=80) first_name = models.CharField(max_length=40, null=True, blank=True) e...
nilq/baby-python
python
from flask import render_template, jsonify, request, session, redirect from dataclasses import Test import forms from werkzeug.exceptions import HTTPException def home(): return render_template("home.html") def error(e): return render_template("error.html", error_num=e.code if isinstance(e, HTTPException) ...
nilq/baby-python
python
# Create your models here. from django.db import models from Graphic_reporter.models import Image class Published_Article(models.Model): slug = models.CharField(max_length=140) title = models.CharField(max_length=140) description = models.CharField(max_length=140) body = models.TextField() publish...
nilq/baby-python
python
# -*- coding: utf-8 -*- """Setup file for easy installation""" from os.path import join, dirname from setuptools import setup version = __import__('social_auth').__version__ LONG_DESCRIPTION = """ Django Social Auth is an easy to setup social authentication/registration mechanism for Django projects. Crafted using ...
nilq/baby-python
python
from django.urls import path, include from . import views urlpatterns = [ # Home Page URLs path('', views.home, name="home"), path(r'^logout/$', views.logoutUser, name="logout"), path('about/', views.about, name="about"), # Registrations path('customer-registration/', views.cusRegister, ...
nilq/baby-python
python
import abc import six @six.add_metaclass(abc.ABCMeta) class VarSet: @abc.abstractmethod def var_names(self, model): pass class VarSetFromSubH(VarSet): """Creates a VarSet from SubH instances specified in a model. Args: label (:class:`VarSet`): VarSet instance model (:class:...
nilq/baby-python
python
from mmdet.models.necks.fpn import FPN from .second_fpn import SECONDFPN from .second_fpn_ran import SECONDFPN_RAN from .second_fpn_mask import SECONDFPNMASK __all__ = ['FPN', 'SECONDFPN', 'SECONDFPN_RAN', 'SECONDFPNMASK']
nilq/baby-python
python
import time import datetime as dt date = {} date["Future"] = dt.datetime.now() + dt.timedelta(seconds = 10) if date["Future"] <= dt.datetime.now(): print("Succ\n")
nilq/baby-python
python
import re examples1 = { "2x3x4": 58, "1x1x10": 43 } examples2 = { "2x3x4": 34, "1x1x10": 14 } def day2a(test=False): if test: inputs = examples else: inputs = open("d2.txt", "r").read().strip().split("\n") real_total = 0 for item in inputs: wayall = 0 bl, bw, bh = re.match("^([0-9]+)x([0-9]+)x([0-9]+...
nilq/baby-python
python
# Copyright (c) OpenMMLab. All rights reserved. import os import time from mmdet.datasets import DATASETS from .base_sot_dataset import BaseSOTDataset @DATASETS.register_module() class UAV123Dataset(BaseSOTDataset): """UAV123 dataset of single object tracking. The dataset is only used to test. """ ...
nilq/baby-python
python
# -*- coding: utf-8 -*- informe_temp_atual = float(input("informe a temperatura atual: ")) if (informe_temp_atual > 0) and (informe_temp_atual <= 15): print ("Muito frio") elif (informe_temp_atual >= 16) and (informe_temp_atual <= 23): print ("Frio") elif (informe_temp_atual >= 24) and (informe_temp_atual <= 26): ...
nilq/baby-python
python
def merge_sort(arr): if len(arr) < 2: return arr # divide into 2 half divider = len(arr) // 2 arr1 = merge_sort(arr[0:divider]) arr2 = merge_sort(arr[divider:]) return merge(arr1, arr2) def merge(arra, arrb): i = j = 0 merge_list = [] while i < len(arra) and j < len(arrb): ...
nilq/baby-python
python
def anagrams(word, words): return [x for x in words if sorted(list(x)) == sorted(list(word))]
nilq/baby-python
python
from random import randint from compara_texto import ComparaTexto class GeradorStrings(): def nova(self, comprimento): comp = ComparaTexto() caracteres = comp.CARACTERES_POSSIVEIS() resultado = [] for _ in range(comprimento): aleatorio = randint(0, len(caracteres) - 1) ...
nilq/baby-python
python
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
nilq/baby-python
python
#!/usr/bin/env python3 # authors: RocaPiedra # # This work is licensed under the terms of the MIT license. # For a copy, see <https://opensource.org/licenses/MIT>. from __future__ import print_function import subprocess import glob import os import sys import random import time import numpy as np import cv2 import py...
nilq/baby-python
python
""" Copyright (c) 2022 Intel Corporation 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
# -*- coding: utf-8 -*- """CquenceR.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1iywElgfFio7e8VN1yZOemHm8hRV4IJHy # Clone CquenceR and PatchBundle """ !git clone https://github.com/SecureThemAll/PatchBundle.git !git clone https://github.com...
nilq/baby-python
python
"""Data Analysis ================ """ from os.path import exists import nixio as nix import numpy as np import numpy.linalg from typing import Dict, List, Tuple, Type, Union, Set, Any, Optional, Iterator import pandas as pd from collections import defaultdict from kivy_garden.collider import Collide2DPoly, CollideEll...
nilq/baby-python
python
#!../env/bin/python from db_models import db, ColorScheme # define columns columns = ['ColorSchemeName', 'NumCategories', 'CriticalValue' ,'CategoryNumber', 'RedValue', 'GreenValue', 'BlueValue', 'SchemeType'] # open file f = open('../assets/colorbrewer.csv','r') # generate inserts for each line for r in f.readline...
nilq/baby-python
python
import numpy as np import matplotlib.pyplot as plt from scipy.integrate import ode def f(phi, current_concentrations): # use simpler variable names s1 = current_concentrations[0] s2 = current_concentrations[1] v0 = 5.0 k1 = 3.0 k2 = 2.0 change_in_s1 = v0 - k1 * s1 change_in_s2 = k1 * s1 - k2*s2 return [chan...
nilq/baby-python
python
"""Tools that interact with Ilab's REST database.""" import re import copy import traceback from bs4 import BeautifulSoup from ua_ilab_tools import extract_custom_forms, ilab_api, api_types ONLY_INT_FIELDS = [ "Concentration_each_sample", "Concentration", "Volume (uL)", "Initial_Number_Slides_or_Punches_each_s...
nilq/baby-python
python
__copyright__ = ''' Copyright 2017 the original author or authors. 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 ...
nilq/baby-python
python
# George Adamson # 05/19/2020 fhand1 = open('dijkstraRoute_oceanEN_RD_50km_50.txt') fhand_out = open('dijkstraRoute_oceanEN_RD_50km_50.pg','w') # Read in Route lats = [] lons = [] for line in fhand1: route_data = line.split(',') lats.append(route_data[1]) lons.append(route_data[2].rstrip()) ...
nilq/baby-python
python
from rest_framework import serializers from .models import * class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = ['id', 'title', 'workspace', 'assigned_to', 'priority', 'task_status', 'description', 'planned_start_date', 'planned_end_date', 'file'] class WorkSpa...
nilq/baby-python
python
import json import random from django.utils.safestring import SafeString # debug ''' 1. Step 1: Put your libraries in the same directory as views.py 2. Step 2: Import your libraries here with a '.' ''' from .completeness_class import * from .outlier import * from .IntegrateFunction import * from dashboard.forms impo...
nilq/baby-python
python
""" Released under the MIT-license: Copyright (c) 2010 Earl Marcus 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, modif...
nilq/baby-python
python
""" argparse interface """ from argparse import ArgumentParser as _Parser from argparse import ArgumentDefaultsHelpFormatter as _HelpFormatter def parser(cmd_str, arg_lst): """ an argparse parser object :param cmd_str: the command string :type cmd_str: str :param arg_lst: args and kwargs for Argument...
nilq/baby-python
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jun 27 13:40:04 2017 @author: DangoMelon0701 """ import numpy as np class Funciones(object): def __init__(self,nombre,apellido,edad): self.name = nombre self.lastname = apellido self.age = edad def puto(self): ...
nilq/baby-python
python
from .base_classes import Attack from .closest_distance import ClosestDistanceAttack from .direct_linkage import DirectLinkage from .groundhog import Groundhog from .utils import load_attack
nilq/baby-python
python
from django.shortcuts import render,redirect from oauth_backend import OauthBackend from django.http import HttpResponse, HttpResponseForbidden from django.http import Http404 from django.utils.crypto import get_random_string from django.conf import settings from django.contrib.auth import authenticate, login from tuke...
nilq/baby-python
python
from pyramid.view import view_defaults from pyramid.response import Response from pyramid.httpexceptions import HTTPOk from pyramid.httpexceptions import HTTPNotFound, HTTPInternalServerError from .. catalog import install_package from .. logger import getLogger logger = getLogger(__name__) @view_defaults(route_na...
nilq/baby-python
python
import tensorflow as tf import matplotlib.pyplot as plt import numpy as np from matplotlib import gridspec from sklearn.metrics import accuracy_score # Plot some details about the dataset and show some example points def showDatasetExamples(xTrain, yTrain, xTest, yTest): fig = plt.figure(figsize=(6, 6)) fig.ca...
nilq/baby-python
python
from rest_framework.serializers import ModelSerializer from backend.models import Video, Like class VideoCreateSerializer(ModelSerializer): class Meta: model = Video fields = [ 'id', 'owner', 'video_bucket_id', 'title', 'description', ...
nilq/baby-python
python
import aiml from django.shortcuts import render, redirect kernel = aiml.Kernel() kernel.learn("./botbrains/*.aiml") kernel.saveBrain("siabrain.brn") def index(request): text = "" textreply = "" text = chat.text textreply = kernel.respond(str(text)) if textreply is not None: return render...
nilq/baby-python
python
import falcon.asgi from .api.tilt_resource import * # swagger ui - NO ASGI SUPPORT YET #from falcon_swagger_ui import register_swaggerui_app # register swagger ui - NO ASGI SUPPORT YET #register_swaggerui_app(api, SWAGGERUI_URL, SCHEMA_URL, page_title=PAGE_TITLE, #favicon_url=FAVICON_URL, # config={'supported...
nilq/baby-python
python
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data def mlp_model(x, n_input, n_hidden_1, n_hidden_2, n_class): weights = { 'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])), 'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])), 'out': tf.Va...
nilq/baby-python
python
#encoding:utf-8 import word_util import numpy as np import codecs def transform_wordseq_to_phrase_weighted(word_seq,word2vec_map,word_weighted_value = None,word_keys = None): phrase_distributed = np.zeros(256) word_freq = {} for word in word_seq: #print("0") if not word_keys: if ...
nilq/baby-python
python
#!/usr/bin/env python3 import contextlib import sys from pathlib import Path from typing import List, Type import pytest from qemu import QemuVm, VmImage, spawn_qemu from nix import notos_image, busybox_image from root import TEST_ROOT from vmsh import spawn_vmsh_command, VmshPopen sys.path.append(str(TEST_ROOT.pare...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ SPARQL Wrapper exceptions @authors: U{Ivan Herman<http://www.ivan-herman.net>}, U{Sergio Fernández<http://www.wikier.org>}, U{Carlos Tejo Alonso<http://www.dayures.net>} @organization: U{World Wide Web Consortium<http://www.w3.org>} and U{Foundation CTIC<http://www.fundacionctic.org/>}. @...
nilq/baby-python
python
import warnings from otp.ai.passlib.tests.test_crypto_builtin_md4 import _Common_MD4_Test __all__ = [ 'Legacy_MD4_Test'] class Legacy_MD4_Test(_Common_MD4_Test): descriptionPrefix = 'passlib.utils.md4.md4()' def setUp(self): super(Legacy_MD4_Test, self).setUp() warnings.filterwarnings('ignore...
nilq/baby-python
python
""" leetcode 15 Three Sum """ from typing import List """ simple solution T: O(N^3) S: O(1) result: time out """ def threeSum(self, nums: List[int]) -> List[List[int]]: if not nums: return [] res = [] for i in range(len(nums) - 2): for j in range(i, len(nums) - 1): for k in rang...
nilq/baby-python
python
# This file was auto generated; Do not modify, if you value your sanity! import ctypes try: # 3 from can_settings import can_settings from canfd_settings import canfd_settings from s_text_api_settings import s_text_api_settings except: from ics.structures.can_settings import can_settings from ics.s...
nilq/baby-python
python
class Grid: """ Creates a 2D array specified by row and column """ def __init__(self, X_SIZE, Y_SIZE, item=""): self.x_size = X_SIZE self.y_size = Y_SIZE self._grid = [[item for x in range(X_SIZE)] for y in range(Y_SIZE)] def __len__(self): re...
nilq/baby-python
python
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def insertionSortList(self, head: ListNode) -> ListNode: if not head or not head.next: return head dummy = List...
nilq/baby-python
python
import os import sys import csv import json OUTPUT_FORMATS = ('csv', 'json', 'yara', 'autofocus') def getHandler(output_format): output_format = output_format.lower() if output_format not in OUTPUT_FORMATS: print("[WARNING] Invalid output format specified.. using CSV") output_format = 'csv' ...
nilq/baby-python
python
# CONVERSION OF LINKED LIST TO ARRAY class Node: def __init__(self, value): self.value = value self.next = None class SinglyLinkedList: def __init__(self): self.head = None self.tail = None def add_last(self, value): temp = Node(value) if self.head==Non...
nilq/baby-python
python
from dataclasses import dataclass, field from typing import List, Any, Optional @dataclass() class Type: """ Abstract base representation of a data type. All intermediate representations of data types will either be instances of Type, or instances of subclasses of Type. All scalar data types are insta...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Created by crazyX on 2018/7/7 from ojcrawler.crawlers.poj import POJ from ojcrawler.crawlers.hdu import HDU from ojcrawler.crawlers.codeforces import Codeforces supports = { 'poj': POJ, 'hdu': HDU, 'codeforces': Codeforces, }
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = u"David Pärsson" __copyright__ = u"Copyright 2015, David Pärsson" __license__ = "MIT" __version__ = "1.0.0" __status__ = "Development" import re import sys import argparse def renumber(input_filename, output_filename): with open(input_filename, 'r') as ...
nilq/baby-python
python