content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
#!/usr/bin/python3
"""Explode an LLVM IR dump.
Given a debug dump generated from the -print-debug-all option, split out the
dumps into multiple files, one for each phase/procedure. Example usage:
clang -c -O3 -mllvm -print-before-all mumble.c 1> err.txt 2>&1
rm -rf /tmp/dumps ; mkdir /tmp/dumps
explode-llvm-ir-... | nilq/baby-python | python |
# https://github.com/RaRe-Technologies/gensim/blob/develop/docs/notebooks/Corpora_and_Vector_Spaces.ipynb
from gensim import corpora
# This is a tiny corpus of nine documents, each consisting of only a single sentence
documents = ["Human machine interface for lab abc computer applications",
"A survey of u... | nilq/baby-python | python |
# Copyright (c) 2013 by Gilbert Ramirez <gram@alumni.rice.edu>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# Th... | nilq/baby-python | python |
# Author: Deepak Pathak (c) 2016
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# from __future__ import unicode_literals
import numpy as np
from PIL import Image
import time
import argparse
import os
import pyflow
parser = argparse.ArgumentParser(
des... | nilq/baby-python | python |
from rect import Rect
from math import floor
class HashMap(object):
"""
Hashmap is a broad-phase collision detection strategy, which is quick
enough to build each frame.
"""
def __init__(self, cell_size):
self.cell_size = cell_size
self.grid = {}
@classmethod
def from_objec... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
drawmap.py
@Purpose: draw a current map from a hdf mohid or netcdfoutput
@version: 1.0
@python version: 3.9
@author: Pedro Montero
@license: INTECMAR
@requires: matplotlib, numpy, toolkits.basemap
@date 2021/10/13
@history:
"""
import os
from common.readers.read... | nilq/baby-python | python |
a,b=map(int,input().split())
print(-~(a+b)//2) | nilq/baby-python | python |
# script to create relationship classes in a GeMS database
#
# Somebody who uses relationship classes more than I should look at this.
# Particularly, are the Forward and Backward labels named as usefully as possible?
# Are there other issues?
#
# Note that Validate Database script can be used to maintain refere... | nilq/baby-python | python |
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('Paint')
self.setWindowIcon(QIcon('Images/Paint.png'))
self.setMaximumSize(860, 720)
self... | nilq/baby-python | python |
# Run detection in real-time setting on a COCO-format dataset
import argparse, json, pickle
from os.path import join, isfile
from time import perf_counter
from tqdm import tqdm
import numpy as np
import torch
from pycocotools.coco import COCO
from mmcv.runner import load_checkpoint
import sys; sys.pa... | nilq/baby-python | python |
import os
import glob
from imageai.Detection.Custom import DetectionModelTrainer
execution_path = os.getcwd()
models_path = os.path.join(execution_path, "doge-identification/models/")
data_path = os.path.join(execution_path, "doge-identification/")
# This will force tensorflow to run on the cpu
os.environ["CUDA_VISIBL... | nilq/baby-python | python |
# This file is part of the CERN Indico plugins.
# Copyright (C) 2014 - 2020 CERN
#
# The CERN Indico plugins are free software; you can redistribute
# them and/or modify them under the terms of the MIT License; see
# the LICENSE file for more details.
from __future__ import unicode_literals
from wtforms.fields import... | nilq/baby-python | python |
"""Error handlers."""
from werkzeug.http import HTTP_STATUS_CODES
from flask import jsonify
from muckr_api.extensions import database
class APIError(Exception):
def __init__(self, status_code, message=None, details=None):
super().__init__()
error = HTTP_STATUS_CODES.get(status_code, "Unknown err... | nilq/baby-python | python |
from django.conf.urls import url
from .views import Dashboard
urlpatterns = [
url(r'^$', Dashboard.as_view()),
]
| nilq/baby-python | python |
##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS I... | nilq/baby-python | python |
from typing import List
import msgpack
from pydantic import BaseModel
import ormsgpack
class Member(BaseModel):
id: int
active: bool
class Object(BaseModel):
id: int
name: str
members: List[Member]
objects_as_pydantic = [
Object(
id=i, name=str(i) * 3, members=[Member(id=j, activ... | nilq/baby-python | python |
#!/usr/bin/env python
from breakmywork.application import main
main()
| nilq/baby-python | python |
import inferpy as inf
def test_parameter_in_pmodel():
# test that random variables in pmodel works even if no name has been provided
@inf.probmodel
def model():
inf.Parameter(0)
v = list(model().params.values())[0]
assert v.name.startswith('parameter')
# assert also is_datamodel is fa... | nilq/baby-python | python |
import FWCore.ParameterSet.Config as cms
from Configuration.Eras.Era_Phase2C11I13_cff import Phase2C11I13
from Configuration.Eras.Modifier_phase2_3DPixels_cff import phase2_3DPixels
from Configuration.Eras.Modifier_phase2_GE0_cff import phase2_GE0
Phase2C11I13T25M9 = cms.ModifierChain(Phase2C11I13, phase2_3DPixels, p... | nilq/baby-python | python |
import numpy as np
class RandomParameters:
"""
Example params are in JSON format:
{
"booster": ["gbtree", "gblinear"],
"objective": ["binary:logistic"],
"eval_metric": ["auc", "logloss"],
"eta": [0.0025, 0.005, 0.0075, 0.01, 0.025, 0.05, 0.075, 0.1]
}
"""
@sta... | nilq/baby-python | python |
import sys,os,pygame
| nilq/baby-python | python |
# Generated by Django 3.0.6 on 2020-05-25 00:02
import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL)... | nilq/baby-python | python |
from tests.save_restore_cursor import SaveRestoreCursorTests
import esccmd
from escutil import knownBug
class DECSETTiteInhibitTests(SaveRestoreCursorTests):
def __init__(self):
SaveRestoreCursorTests.__init__(self)
def saveCursor(self):
esccmd.DECSET(esccmd.SaveRestoreCursor)
def restoreCursor(self):
... | nilq/baby-python | python |
from domain.rules import game_loops
connect_game = game_loops.Game_Loops()
''' here we call the game loop function'''
connect_game.connect_four_game()
| nilq/baby-python | python |
from flask import Flask, request, render_template, url_for, send_file
import qrcode
from PIL import Image
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/result', methods=["POST", "GET"])
def result():
if request.method == "POST":
input = request.f... | nilq/baby-python | python |
# python peripherals
import os
import numpy
import random
import queue
from multiprocessing import Process, Queue, cpu_count
# torch
import torch
from torch.utils.data import Dataset
# deep_signature
from deep_signature.data_generation import curve_generation
from deep_signature.data_generation import dataset_generat... | nilq/baby-python | python |
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
# standard library
# django
from django.contrib import admin
from django.core.urlresolvers import NoReverseMatch
from django.core.urlre... | nilq/baby-python | python |
import pandas as pd
from modules.locale_generator.data import LocaleOutData
from helper.utils.utils import read_sheet_map_file
class LocaleProcessor:
def __init__(self, language_name, english_column_name):
self.language_name = language_name
self.english_column_name = english_column_name
... | nilq/baby-python | python |
from unittest import mock
from bgmi.downloader.deluge import DelugeRPC
from bgmi.website.model import Episode
_token = "token:2334"
@mock.patch("bgmi.config.DELUGE_RPC_PASSWORD", _token)
@mock.patch("bgmi.downloader.deluge.DelugeRPC._call")
def test_init(call):
DelugeRPC(
download_obj=Episode(name="n", ... | nilq/baby-python | python |
'''
a = input("First number")
b = input("Second number")
a = int(a)
b = int(b)
print(a+b)
print(a-b)
print(a*b)
print(a/b)
result = a/b
print(type(result))
print(result)
print(a**2)
'''
# Логические операции
a = True
b = False
# Отрицание
print(not a)
# Логическое И
print(a and b)
# Логическое ИЛИ
print(a or b)
a ... | nilq/baby-python | python |
from mypackage import shazam
shazam() | nilq/baby-python | python |
# query_parser_test.py
# Author: Thomas MINIER - MIT License 2017-2018
import pytest
from query_engine.sage_engine import SageEngine
from query_engine.optimizer.query_parser import parse_query
from database.hdt_file_connector import HDTFileConnector
from tests.utils import DummyDataset
import math
hdtDoc = HDTFileCon... | nilq/baby-python | python |
import sys
import time
from http.client import HTTPSConnection
from typing import List
def main(argv: List[str]):
time.sleep(3)
for i in range(3):
for j in argv:
connection = HTTPSConnection(j)
connection.request('GET', '/')
connection.getresponse().read()
... | nilq/baby-python | python |
# -*- encoding: utf-8 -*-
# Copyright (c) 2015 b<>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/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | nilq/baby-python | python |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
from common.Utilities import execute_command, get_file_extension_list, error_exit
from ast import ASTGenerator, AST
import Mapper
import Finder
import Logger
import Extractor
import Emitter
def merge_var_info(var_expr_map, var_value_map):
Logger.trace(_... | nilq/baby-python | python |
# CONTADOR DE CÉDULAS
value = int(input('Digite o valor a ser sacado: '))
total = value # Pegando o valor a ser sacado
ced = 50 # Começando na cedula de 50
totced = 0 # Total de cedula por valor
while True:
if total >= ced: # Enquanto puder retirar o valor da cedula do valor total
total -= ced # R... | nilq/baby-python | python |
"""
Generate static HTML files for eduid-IdP in all supported languages.
"""
import os
import sys
import six
import pkg_resources
from six.moves import configparser
from jinja2 import Environment, PackageLoader
from babel.support import Translations
__version__ = '0.1'
__copyright__ = 'SUNET'
__organization__ = 'SUN... | nilq/baby-python | python |
import pywikibot
from openpyxl import load_workbook
site = pywikibot.Site()
'''
page = pywikibot.Page(site, u"Project:Sandbox")
text = page.text
#page.text = u"DarijaBot kheddam daba"
page.save(page.text+u"\n\nawwal edit dial DarijaBot")
'''
sandbox = pywikibot.Page(site, 'User:' + site.user() + '/Project:Sandbox'... | nilq/baby-python | python |
import numpy as np
from .agent import Agent
class RandomAgent(Agent):
def __init__(self, actions):
super(RandomAgent, self).__init__(actions)
def act(self, obs):
return np.random.randint(0, self.num_actions)
| nilq/baby-python | python |
from rA9.neurons.LIF import LIF
def LIF_recall(tau, Vth, dt, x, v_current):
model = LIF(tau_m=tau, Vth=Vth, dt=dt)
spike_list, v_current = model.forward(x, v_current=v_current)
return spike_list, v_current
def LIF_backward(tau, Vth, x, spike_list, e_grad, time):
model = LIF(tau_m=tau, Vth=Vth)
... | nilq/baby-python | python |
from meido.libs.yuntongxun.sms import CCP
from celery_tasks.main import app
@app.task(name='send_sms_code')
def send_sms_code(mobile, sms_code):
ccp = CCP()
ccp.send_template_sms(mobile, [sms_code, '5'], 1)
@app.task()
def test_print():
print(2222)
| nilq/baby-python | python |
#!/usr/bin/env python3
def naive_search(l,x):
for i in range(len(l)):
if l[i]==x:
return i
n = int(input())
l = list(range(n))
cnt = 0
for x in range(n):
i = naive_search(l,x)
cnt += 1
print("#query=%d"%cnt)
| nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module that contains artellapipe-tools-welcome view implementation
"""
from __future__ import print_function, division, absolute_import
import os
import random
from functools import partial
from Qt.QtCore import Qt, QSize, QTimer, QByteArray, QBuffer
from Qt.QtWidge... | nilq/baby-python | python |
from flask_cors import cross_origin
from app.blueprints.base_blueprint import (
Blueprint,
BaseBlueprint,
request,
Security,
Auth,
)
from app.controllers.user_employment_controller import UserEmploymentController
url_prefix = "{}/user_employment_history".format(BaseBlueprint.base_url_prefix)
user_... | nilq/baby-python | python |
from django.test import TestCase
from django.contrib.auth.models import User
from .models import Thread, Message
# Create your tests here.
class ThreadTestCase(TestCase):
def setUp(self):
self.user1 = User.objects.create_user("user1", None, "test1234")
self.user2 = User.objects.create_user("user2", None, "te... | nilq/baby-python | python |
#!/usr/bin/env python
import argparse
import sys
import Tools
from Bio import SeqIO
from Bio import SeqRecord
from Bio import Seq
ap = argparse.ArgumentParser(description="Take an inversion bed file, and print the sequences in inverted format with some flanking part of the genome.")
ap.add_argument("bed", help="Input... | nilq/baby-python | python |
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.views.generic import ListView
from django.http import JsonResponse
from api.models import Country, City
class CountryView(LoginRequiredMixin, UserPassesTestMixin, ListView):
model = Country
response_class = JsonRespons... | nilq/baby-python | python |
from .triplet_generators import generator_from_neighbour_matrix, \
TripletGenerator, UnsupervisedTripletGenerator, SupervisedTripletGenerator
from .generators import KerasSequence
| nilq/baby-python | python |
import setuptools
with open("./README.md", "r") as f:
description = f.read()
setuptools.setup(
name="blive",
version="0.0.5",
author="cam",
author_email="yulinfeng000@gmail.com",
long_description=description,
long_description_content_type="text/markdown",
url="https://github.com/yulinf... | nilq/baby-python | python |
from .md5_database import MD5DB
from .paper_database import paperDB | nilq/baby-python | python |
import socket
def resolv(hostname):
try:
return socket.gethostbyname(hostname)
except socket.gaierror as e:
raise Exception('Cloud not resolv "%s": %s' % (hostname, e))
class FilterModule(object):
filter_map = {
'resolv': resolv,
}
def filters(self):
return {'res... | nilq/baby-python | python |
import unittest
import mutable_test
class TestRemoveShared(unittest.TestCase):
'''Tests for function duplicates.remove_shared.'''
def test_general_case(self):
'''
Test remove_shared where there are items that appear in both lists,
and items that appear in only one or the other list... | nilq/baby-python | python |
import numpy as np
from .preprocessing import *
from .sequence_alignment import *
class SemAlign(object):
def __init__(self, embeddings_path, kernel_size=1, delimiter=',', verbose=True):
self.lookup = load_embeddings(embeddings_path, delimiter)
self.kernel_size = kernel_size
self.verbose =... | nilq/baby-python | python |
from enum import Enum, auto
class Color(Enum):
BLACK = 0
WHITE = 1
RED = 2
BLUE = 3
# class TestEnum(Enum):
# ONE = 0
# ONE = 1
class TestNewEnum(Enum):
ZERO = auto()
ONE = auto()
TWO = auto()
if __name__ == "__main__":
print(Color.BLACK)
print(Color.BLACK.name)
pri... | nilq/baby-python | python |
# Update the paths according to your environemnt
OPT = "/data/guide/Trident/llvm-2.9-build/bin/opt"
LLVMGCC = "/data/Trident/llvm-gcc4.2-2.9-x86_64-linux/bin/llvm-gcc"
LLVMLINK = "/data/guide/Trident/llvm-2.9-build/bin/llvm-link"
LLVMPASS_FOLDER = "/data/guide/Trident/llvm-2.9-build/lib/"
LLI = "/data/guide/Triden... | nilq/baby-python | python |
def pour(jug1, jug2):
capacityA = 5
capacityB = 7
Measure = 4
print("%d \t %d" % (jug1, jug2))
if jug2 is Measure: # jug2 has "measure" amount of water stop
return
elif jug2 is capacityB:
pour(0, jug1)
elif jug1 != 0 and jug2 is 0:
pour(0, jug1)
... | nilq/baby-python | python |
def isExistingClassification(t):
pass
def getSrcNodeName(dst):
"""
Get the name of the node connected to the argument dst plug.
"""
pass
def getCollectionsRecursive(parent):
pass
def disconnect(src, dst):
pass
def findVolumeShader(shadingEngine, search='False'):
"""
Returns ... | nilq/baby-python | python |
import scanpy as sc
import numpy as np
import pandas as pd
from scdcdm.util import cell_composition_data as ccd
#%%
adata_ref = sc.datasets.pbmc3k_processed() # this is an earlier version of the dataset from the pbmc3k tutorial
print(adata_ref.X.shape)
#%%
cell_counts = adata_ref.obs["louvain"].value_counts()
print... | nilq/baby-python | python |
"""
:type: tuple
:Size: 1.295MB
:Package Requirements: * **sklearn**
Vec-colnames and neighber matrix used in Substitute DECS. See :py:class:`.DCESSubstitute` for detail.
"""
import os
import pickle
from OpenAttack.utils import make_zip_downloader
NAME = "AttackAssist.DCES"
URL = "https://cdn.data.thunlp.org/TAAD... | nilq/baby-python | python |
#coding:utf-8
"""
@file: db_config
@author: lyn
@contact: tonylu716@gmail.com
@python: 3.3
@editor: PyCharm
@create: 2016-11-20 12:18
@description:
sqlalchemy 配置数据库
"""
from JsonConfig import DB_Config
for path in ['.','..']:
try:
db = DB_Config(
json_file_path=
... | nilq/baby-python | python |
import os
import datetime
import dropbox
from app import db
from app.models import SystemLog
from app.enums import LogStatus, LogType
from flask import current_app
def download(dbx, folder, subfolder, name):
"""Download a file.
Return the bytes of the file, or None if it doesn't exist.
"""
path = '/%s/... | nilq/baby-python | python |
NumOfRows = int(input("Enter number of rows: "))
coeffcient = 1
for i in range(1, NumOfRows+1):
for space in range(1, NumOfRows-i+1):
print(" ",end="")
for j in range(0, i):
if j==0 or i==0:
coeffcient = 1
else:
coeffcient = coeffcient * (i - j)//j
print(... | nilq/baby-python | python |
import abc
class ORMDB(abc.ABC):
@abc.abstractmethod
def parse_sql(self, sql_str):
pass
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""This python program converts various parts of glowscript from the most
convenient format for modification into the most convenient format for
deployment.
* Take shaders from shaders/*.shader and combine them into lib/glow/shaders.gen.js
* Extract glowscript libraries list from ``untrusted/r... | nilq/baby-python | python |
# Copyright (c) 2021 Graphcore Ltd. All rights reserved.
import argparse
import io
import numpy as np
import os
from PIL import Image
import requests
import time
import yacs
import torch
from poptorch import inferenceModel, Options
from models.detector import Detector
from models.yolov4_p5 import Yolov4P5
from utils.... | nilq/baby-python | python |
from datetime import datetime
import bs4
from bs4 import BeautifulSoup
from django.contrib.auth.models import User
from bookmarks.models import Bookmark, parse_tag_string
from bookmarks.services.tags import get_or_create_tags
def import_netscape_html(html: str, user: User):
soup = BeautifulSoup(html, 'html.pars... | nilq/baby-python | python |
###exercicio 49
n = int(input('digite um numero: '))
for c in range (1, 11):
print (' {} * {} = {}'.format(n, c, n*c))
print ('Fim!!!') | nilq/baby-python | python |
import cv2
import numpy as np
from PyQt5.QtCore import Qt, QObject, pyqtSignal
from PyQt5.QtGui import QImage, QPixmap, QDropEvent
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QLabel, QSizePolicy
class QMapCommunicate(QObject):
drop_event = pyqtSignal(QDropEvent)
class PsQMapWidget(QWidget):
def __init... | nilq/baby-python | python |
# coding: utf-8
import torch
import torch.nn.functional as F
from helpers.utils import int_type, add_noise_to_imgs
class NumDiffAutoGradFn(torch.autograd.Function):
"""
A custom backward pass for our [s, x, y] vector when using hard attention
grid = torch.Size([16, 32, 32, 2])
grad_output_shape = ... | nilq/baby-python | python |
import os
import shutil
# Create a new dummy store to run tests on
from tests._stores_for_tests import _TestFixStore
# recs = [
# {'fix_id': 'Fix1', 'operands': {'arg1': '1'}, 'ncml': '<NcML1>'},
# {'fix_id': 'Fix2', 'operands': {'arg2': '2'}, 'ncml': '<NcML2>'}
# ]
recs = [
{
"fix_id": "Fix1",
... | nilq/baby-python | python |
import os
import lldb
class ConcurrentLazyFormatter:
def __init__(self, valobj, dict):
self.valobj = lldb.value(valobj)
def get_child_index(self, name):
return 0 # There is only ever one child
def num_children(self):
if self.has_value:
return 1
return 0
def get_child_at_index(self, index):
if inde... | nilq/baby-python | python |
import os
import re
from .models import Photo
def generate_photo(file_path):
photo_path, width, height = image_utils.fit_and_save(file_path)
thumb_path = image_utils.generate_thumbnail(photo_path)
photo_path, thumb_path = (relp(rp(p), PARENT_DIR) for p in (photo_path, thumb_path))
photo = Photo(image_... | nilq/baby-python | python |
# project/users/forms.py
from flask_wtf import Form
from wtforms import StringField, PasswordField
from wtforms.validators import DataRequired, Length, EqualTo, Email
class RegisterForm(Form):
email = StringField('Email', validators=[DataRequired(), Email(), Length(min=6, max=40)])
password = PasswordField(... | nilq/baby-python | python |
from .libfm import (
RegressionCallback,
ClassificationCallback,
OrderedProbitCallback,
LibFMLikeCallbackBase,
)
| nilq/baby-python | python |
import tensorflow as tf
import numpy as np
from tensorflow import keras
# Use simple nearest neighbour upsampling, 9x9, 1x1 and 5x5 convolutional layers. MSE: 0.0028712489
# Described in https://towardsdatascience.com/an-evolution-in-single-image-super-resolution-using-deep-learning-66f0adfb2d6b
# Article: https://ar... | nilq/baby-python | python |
import logging
import os
import re
from robobrowser import RoboBrowser
logger = logging.getLogger(__name__)
id_re = re.compile("\(([^)]+)\)")
def scrape_snotel_sites(url=None):
if not url:
url = "http://www.wcc.nrcs.usda.gov/nwcc/yearcount?network=sntl&counttype=statelist&state="
browser = RoboBrowse... | nilq/baby-python | python |
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
import scipy.io
from torch.utils.data import Dataset
import pickle
import os
import sys
# Data Processing
def load_file(path_to_file):
return np.genfromtxt(path_to_... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: Donny You(donnyyou@163.com)
# Loss Manager for Object Detection.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from loss.modules.det_modules import SSDFocalLoss, SSDMultiBoxLoss
from loss.modules.det... | nilq/baby-python | python |
a = []
# append element at the end.
a.append(2)
a.append(3)
print(a)
# insert at a specific location.
a.insert(0, 5)
a.insert(10, 5)
print(a)
# when specified a position not in list, it inserts at the end.
a.insert(100, 6)
print(a)
# Deleting elements from a list.
a.remove(5) # removes the first occurence of value pa... | nilq/baby-python | python |
from .Ticket import Ticket, StateTicket
################################################################################
################################################################################
################################################################################
###############################... | nilq/baby-python | python |
import numpy as np
from sklearn.cluster import MeanShift, estimate_bandwidth
import matplotlib.pyplot as plt
from PIL import Image
import cv2
from copy import deepcopy
# image_path = '/home/kshitij/PycharmProjects/Computer_Vision/Assignment_3/Question_2/iceCream1.jpg'
# image_path = '/home/kshitij/PycharmProjects/Comp... | nilq/baby-python | python |
import random
import networkx as nx
import matplotlib.pyplot as plt
class graph:
__dg = None
def __init__(self):
#self.__dg = nx.DiGraph()
self.__dg = nx.Graph()
def add_nodes(self, nodes):
for i in range(0, len(nodes)):
self.__dg.add_node(nodes[i])
def add_edges... | nilq/baby-python | python |
# coding: utf-8
"""
TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-节点管理(BlueKing-BK-NODEMAN) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
from alphalogic_api.protocol import rpc_pb2
from alphalogic_api.attributes import Visible, Access
from alphalogic_api.multistub import MultiStub
from alphalogic_api import utils
from alphalogic_api.logger import log
from alphalogic_api.u... | nilq/baby-python | python |
from unittest.mock import ANY, patch
from arcsecond import ArcsecondAPI
from click.testing import CliRunner
from oort.cli.cli import upload
from oort.server.errors import InvalidOrgMembershipOortCloudError, UnknownOrganisationOortCloudError
from oort.shared.models import Organisation
from tests.utils import (
TEL... | nilq/baby-python | python |
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('../../MNIST_data', one_hot=True)
import tensorflow as tf
x = tf.placeholder(tf.float32,[None,784])
| nilq/baby-python | python |
from aiogram import types
from asyncio import sleep
from typing import Union
import NekoGram
async def default_start_function(message: Union[types.Message, types.CallbackQuery]):
neko: NekoGram.Neko = message.conf['neko']
if not await neko.storage.check_user_exists(user_id=message.from_user.id):
lang ... | nilq/baby-python | python |
import os
import pandas as pd
import nltk
import re
import spacy
from sklearn.feature_extraction.text import CountVectorizer
from data_module.corpus import data_operations as do
from data_module.corpus.clean import remove_single_quotes
def get_top_n_words(corpus, n=None):
"""
List the top n words in a vocabul... | nilq/baby-python | python |
import unittest
from config import TEST_DB_PATH
from repositories.item_repository import ItemRepository
from utilities.csv_utilities import clear_csv, read_csv
class TestItemRepository(unittest.TestCase):
def setUp(self):
clear_csv(TEST_DB_PATH)
self.item_repo = ItemRepository(TEST_DB_PATH)
... | nilq/baby-python | python |
#!/usr/bin/env python3
import sys
import subprocess
import requests
from datetime import datetime
def main(args):
if len(args) < 2:
print('usage: sync-cloudflare.py [output path]')
return
output = args[1]
now = datetime.utcnow().isoformat()
ips = []
resp = requests.get('https://... | nilq/baby-python | python |
import os
import sys
from urllib2 import urlopen
import json
import ConfigParser
config = ConfigParser.ConfigParser()
config.readfp(open(r'config.txt'))
apikey = config.get('Sonarr Config', 'apikey')
host = config.get('Sonarr Config', 'host')
port = config.get('Sonarr Config', 'port')
url = 'http://'+host+':'+port+'... | nilq/baby-python | python |
#!/usr/bin/env python
from kivy.app import App
from kivy.animation import Animation
from kivy.uix.floatlayout import FloatLayout
from kivy.graphics import Line
from kivy.gesture import Gesture, GestureDatabase
from kivy.vector import Vector
from kivy.properties import NumericProperty,BooleanProperty
from museol... | nilq/baby-python | python |
import numpy as np
from sympy import simplify, integrate, zeros, S, Matrix, symbols, pi, cos, sin
from .funcs_aproximacion import producto_asecas
def producto_escalar_trigono(f, g, var=symbols('x'), a=-pi, b=pi, I=None, numeric=False):
"""Aplica el producto escalar <f,g> = 1/(2pi) ∫_[-pi]^[pi] f.g
Args:
... | nilq/baby-python | python |
from ..util.conversion import physical_compatible
from ..util import config, conversion
class df(object):
"""Top-level class for DF classes"""
def __init__(self,ro=None,vo=None):
"""
NAME:
__init__
PURPOSE:
initialize a DF object
INPUT:
ro= (None)... | nilq/baby-python | python |
#!/usr/bin/python3
# Copyright (c) 2021 by Fred Morris Tacoma WA
#
# 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 appli... | nilq/baby-python | python |
from enum import Enum
class Emoji(Enum):
PLAY = "*play*"
FACE_HEARTS = "<3"
FACE_TONGUE = ":P"
FACE_SMILE = ":D"
FACE_CRY_LAUGH = "xD"
FACE_HALO = "=D"
FACE_NERDY = "*nerdy*"
FACE_TEAR = "*cry*"
FACE_SAD = ":("
FACE_ZZZ = "*sleep*"
FACE_ROLLING_EYES = "*rolling-eyes*"
F... | nilq/baby-python | python |
"""Dependency injector resource provider unit tests."""
import asyncio
import unittest2 as unittest
from dependency_injector import containers, providers, resources, errors
# Runtime import to get asyncutils module
import os
_TOP_DIR = os.path.abspath(
os.path.sep.join((
os.path.dirname(__file__),
... | nilq/baby-python | python |
# coding: utf-8
# This block of code fetches the data, and defines a function that
# splits the data into test/train, and into batches.
# Note that this function will only download the data once. Subsequent
# calls will load the data from the hard drive
def MNIST_Loaders(train_batch_size, test_batch_size=None):
i... | nilq/baby-python | python |
import sqlite3
# Configure database
connection = sqlite3.connect('map.db')
# Cursor for execute DB command
c = connection.cursor()
# CREATE TABLE
# c.execute("""CREATE TABLE map (
# id integer,
# lat real,
# lng real,
# comment text
# )""")
# INSERT VALU... | nilq/baby-python | python |
from .models import Language
from rest_framework import serializers
class LanguageSerializer(serializers.ModelSerializer):
class Meta:
model = Language
fields = ('id', 'name', 'paradigm') | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.