content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
from antlr4 import InputStream, CommonTokenStream, ParseTreeWalker
from parse.MATLABLexer import MATLABLexer
from parse.MATLABParser import MATLABParser
from TranslateListener import TranslateListener
from error.ErrorListener import ParseErrorExceptionListener
from error.Errors import ParseError
def parse(in_str):
... | nilq/baby-python | python |
import cv2
import numpy as np
from matplotlib import cm
from matplotlib import pyplot as plt
from CS_data_generate import cs_data_generate
from deciVAT import deciVAT
from decVAT import decVAT
from dunns_index import dunns_index
from inciVat import inciVAT
from incVat import incVAT
def length(mat):
return np.max... | nilq/baby-python | python |
from django.urls import path
from . import views
urlpatterns = [
path('iniciar-jogo/', views.JogoAPIView.as_view()),
path('finalizar-jogo/<int:id>', views.JogoAPIView.as_view()),
path('buscar-jogo/<int:id>', views.JogoAPIView.as_view()),
] | nilq/baby-python | python |
import numpy
import os
import sys
def testing(l1, l2):
outputData = str(19) + ' ' + str(0) + '\n'
taken = [0, 0, 1, 1]
outputData += ' '.join(map(str, taken))
return outputData
def solveIt(inputData):
lines = inputData.split('\n')
l1, l2 = map(list, zip(*(s.split(" ") for s in lines)))
r... | nilq/baby-python | python |
"""
CAR CONFIG
This file is read by your car application's manage.py script to change the car
performance.
EXMAPLE
-----------
import dk
cfg = dk.load_config(config_path='~/d2/config.py')
print(cfg.CAMERA_RESOLUTION)
"""
import os
#PATHS
CAR_PATH = PACKAGE_PATH = os.path.dirname(os.path.realpath(__file__))
DAT... | nilq/baby-python | python |
import wpilib.command
from wpilib import Timer
from data_logger import DataLogger
from profiler import TrapezoidalProfile
from pidcontroller import PIDController
from drivecontroller import DriveController
class ProfiledForward(wpilib.command.Command):
def __init__(self, distance_ft):
super().__init__("P... | nilq/baby-python | python |
from typing import Any, Dict
__all__ = (
"UserPublicMetrics",
"TweetPublicMetrics",
)
class UserPublicMetrics:
"""Represent a PublicMetrics for a User.
This PublicMetrics contain public info about the user.
.. versionadded:: 1.1.0
"""
def __init__(self, data: Dict[str, Any] = {}):
... | nilq/baby-python | python |
"""The Labeled Faces in the Wild (LFW) dataset.
from dltb.thirdparty.datasource.lfw import LabeledFacesInTheWild
lfw = LabeledFacesInTheWild()
lfw.prepare()
lfw.sklearn is None
"""
# standard imports
import logging
import importlib
# toolbox imports
from dltb.datasource import DataDirectory
# logging
LOG = logging... | nilq/baby-python | python |
import FWCore.ParameterSet.Config as cms
muonTrackProducer = cms.EDProducer("MuonTrackProducer",
muonsTag = cms.InputTag("muons"),
inputDTRecSegment4DCollection = cms.InputTag("dt4DSegments"),
inputCSCSegmentCollection = cms.InputTag("cscSegments"),
selectionTags = cms.vstring('TrackerMuonArbitrated'),
... | nilq/baby-python | python |
'''
This file
'''
import logging
import urllib.parse
import requests
import datetime
import argparse
import json
import jwt
import pytz
import time
import math
class API(object):
def __init__(self, clientid=None, clientsecret=None,username=None, password=None,timezone=None):
assert clientid is not No... | nilq/baby-python | python |
"""URLS for accounts"""
from django.urls import path
import django.contrib.auth.views
from . import views
# pylint: disable=invalid-name
app_name = 'accounts'
urlpatterns = [
path('login/', views.SocialLoginView.as_view(), name='login'),
path('login/native/', views.NativeLoginView.as_view(), name='login-na... | nilq/baby-python | python |
# Copyright (c) Techland. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
"""Contains the Analyser class, used to run analysis on the dependency graph."""
import logging
import os
from collections import defaultdict
import networkx as nx
from cppbuil... | nilq/baby-python | python |
#!/usr/bin/env python
#
# Copyright (c) 2010 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# runclient.py gets the chromoting host info from an input arg and then
# tries to find the authentication info in the .chromoti... | nilq/baby-python | python |
import numpy as np
import scipy.integrate as spi
import matplotlib.pyplot as plt
#t is the independent variable
P = 3. #period value
BT=-6. #initian value of t (time begin)
ET=6. #final value of t (time end)
FS=1000 #number of discrete values of t between BT and ET
#the periodic real-valued function f(t) with period ... | nilq/baby-python | python |
#first, we import the required libraries
import threading, os, time, requests, yaml
from tkinter.filedialog import askopenfilename
from tkinter import Tk
from concurrent.futures import ThreadPoolExecutor
from console.utils import set_title
from timeit import default_timer as timer
from datetime import timedelta,... | nilq/baby-python | python |
# This is a dummy test file; delete it once the package actually has tests.
def test_import():
import qutip_tensornetwork
assert qutip_tensornetwork.__version__
| nilq/baby-python | python |
import abc
from smqtk.utils.plugin import Pluggable
class DummyInterface (Pluggable):
@abc.abstractmethod
def inst_method(self, val):
""" test abstract method. """
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
from django.db import migrations
def backfill_91_other_meetings(apps, schema_editor):
Meeting = apps.get_model('meeting', 'Meeting')
Schedule = apps.get_model('meeting', 'Schedule')
ScheduledSess... | nilq/baby-python | python |
import csv
import os
import time
import pytest
from conftest import params
from pygraphblas import *
from src.RegularPathQuering import rpq
@pytest.mark.parametrize('impl,graph,regex', params)
def test_benchmark_rpq(impl, graph, regex):
impl_name = impl['name']
g = impl['impl'].from_txt(graph['graph'])
... | nilq/baby-python | python |
"""
Allen-Zhu Z, Ebrahimian F, Li J, et al. Byzantine-Resilient Non-Convex Stochastic Gradient Descent[J].
arXiv preprint arXiv:2012.14368, 2020.
"""
import torch
import random
from .base import _BaseAggregator
from ..utils import log
class Safeguard(_BaseAggregator):
"""[summary]
Args:
_BaseAggr... | nilq/baby-python | python |
import os
import re
import logging
import importlib
import itertools
import contextlib
import subprocess
import inspect
from .vendor import pather
from .vendor.pather.error import ParseError
import avalon.io as io
import avalon.api
import avalon
log = logging.getLogger(__name__)
# Special naming case for subproces... | nilq/baby-python | python |
import numpy as np
import pytest
from numpy.testing import assert_raises
from numpy.testing import assert_allclose
from sklearn import datasets
from inverse_covariance import (
QuicGraphicalLasso,
QuicGraphicalLassoCV,
QuicGraphicalLassoEBIC,
quic,
)
def custom_init(X):
init_cov = np.cov(X, rowv... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from tests import AbstractTestCase
class FeaturesTestCase(AbstractTestCase):
"""
Test case for the methods related to the font features.
"""
def test_get_features(self):
font = self._get_font("/Roboto_Mono/static/RobotoMono-Regular.ttf")
features = font.get_fe... | nilq/baby-python | python |
from flask import Flask, render_template, request
from transformers import pipeline
from transformers import RobertaTokenizer, RobertaForSequenceClassification
tokenizer = RobertaTokenizer.from_pretrained("pdelobelle/robBERT-base")
model = RobertaForSequenceClassification.from_pretrained("dbrd_model2_copy")
app = Flas... | nilq/baby-python | python |
__author__ = 'Michael Foord'
| nilq/baby-python | python |
from __future__ import annotations
import ast
import json
from django.contrib import admin
from django.utils.safestring import mark_safe
from command_log.models import ManagementCommandLog
def pretty_print(data: dict | None) -> str:
"""Convert dict into formatted HTML."""
if data is None:
return ""... | nilq/baby-python | python |
bicycle = {'Price': '------', 'Brand': '------', 'Model': '------', 'Frame': '------', 'Color': '------', 'Size': '------', 'Fork': '------', 'Headset': '------', 'Stem': '------', 'Handlebar': '------', 'Grips': '------', 'Rear Derailleur': '------', 'Front Derailleur': '------', 'Shifter': '------', 'Brake': '------'... | nilq/baby-python | python |
from PyMdlxConverter.common.binarystream import BinaryStream
from PyMdlxConverter.parsers.mdlx.tokenstream import TokenStream
from PyMdlxConverter.parsers.mdlx.extent import Extent
from PyMdlxConverter.parsers.errors import TokenStreamError
class Sequence(object):
def __init__(self):
self.name = ''
... | nilq/baby-python | python |
import threading
from app.crawler.indeed_job_posting import IndeedJobPostingCrawler
from app.crawler.indeed_job_search_result import IndeedJobSearchResultCrawler
class CrawlerManager:
""" Crawler manager """
@classmethod
def start(cls):
crawlers = [
IndeedJobPostingCrawler(),
... | nilq/baby-python | python |
#Code for acessment of the external coils at equatorial plane
#Andre Torres
#21-12-18
from getMirnov import *
%matplotlib qt4
#SDAS INFO
shotN=44835 #44409
ch_rad_u = 'MARTE_NODE_IVO3.DataCollection.Channel_141'
ch_vertical= 'MARTE_NODE_IVO3.DataCollection.Channel_142'
ch_rad_b = 'MARTE_NODE_IVO3.DataCollection.Channe... | nilq/baby-python | python |
import math, csv, re
def check_negative(freq):
if freq < 0:
raise ValueError("negative frequency")
def cent_diff(freq1, freq2):
"""Returns the difference between 2 frequencies in cents
Parameters
----------
freq1 : float
The first frequency
freq2 : float
The second fre... | nilq/baby-python | python |
import itertools
N = int(input())
pairs = []
for x in range(N):
input_ = input().split()
pairs.append([input_[0], input_[len(input_)-1]])
random = ['Beatrice', 'Sue', 'Belinda', 'Bessie', 'Betsy', 'Blue', 'Bella', 'Buttercup']
perm = list(itertools.permutations(random))
possible_list = []
for x in ... | nilq/baby-python | python |
""" written by Joel
file from previous assignment with some changes to fit the new one
contains all the magic numbers for the boid class created in the Pacman game
"""
import numpy as np
# if True the objects that passes through the screen will
# appear on a random spot on the other side.
RANDOM_MODE ... | nilq/baby-python | python |
# Generated by Django 2.1.7 on 2019-04-01 15:18
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('webapp', '0039_auto_20190317_1533'),
('webapp', '0040_merge_20190312_1600'),
]
operations = [
]
| nilq/baby-python | python |
import logging
import random
import numpy as np
from transformers import BertConfig
logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')
logger = logging.getLogger(__name__)
class InputFeatures(object):
"""A single set of original_features of data."""
def __init__(self, input_ids, i... | nilq/baby-python | python |
import pytest
from stix2 import TLP_AMBER, Malware, exceptions, markings
from .constants import FAKE_TIME, MALWARE_ID
from .constants import MALWARE_KWARGS as MALWARE_KWARGS_CONST
from .constants import MARKING_IDS
"""Tests for the Data Markings API."""
MALWARE_KWARGS = MALWARE_KWARGS_CONST.copy()
MALWARE_KWARGS.u... | nilq/baby-python | python |
# Copyright 2018 ICON Foundation
#
# 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 writi... | 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... | nilq/baby-python | python |
class Grill:
"""
This is grill.
"""
| nilq/baby-python | python |
import torch
from torch import nn
from copy import deepcopy
from utils import visualize_batch
class LLL_Net(nn.Module):
""" Basic class for implementing networks """
def __init__(self, model, remove_existing_head=False):
head_var = model.head_var
assert type(head_var) == str
assert no... | nilq/baby-python | python |
import json
from django.conf import settings
import requests
class SalsaException(Exception):
pass
class SalsaAPI(object):
'''
Wrapper for supporter methods:
https://help.salsalabs.com/hc/en-us/articles/224470107-Engage-API-Supporter-Data
'''
HOSTNAME = 'https://api.salsalabs.org'
SAMP... | nilq/baby-python | python |
from typing import Literal
from beartype._decor.main import beartype
from pglet.control import Control
POSITION = Literal[None, "left", "top", "right", "bottom"]
class Spinner(Control):
def __init__(
self,
label=None,
id=None,
label_position: POSITION = None,
size=None,
... | nilq/baby-python | python |
from django.conf.global_settings import AUTH_USER_MODEL
from django.contrib.auth.models import User
from django.db import models
from django.utils import timezone
class Environment(models.Model):
name = models.CharField(max_length=150)
active = models.BooleanField(default=True)
def set_environment_into_s... | nilq/baby-python | python |
from django.urls import path
from .views import UserApi, CrimeMap, EntertainmentMap, EventMap, ArtMap, DirtinessMap
from rest_framework.authtoken import views
urlpatterns = [
path('user/', UserApi.as_view(), name="user-detail"),
path('login/', views.obtain_auth_token),
path('crime/', CrimeMap.as_view(), na... | nilq/baby-python | python |
from ixnetwork_restpy.base import Base
from ixnetwork_restpy.files import Files
class PimdmStateRefresh(Base):
__slots__ = ()
_SDM_NAME = 'pimdmStateRefresh'
_SDM_ATT_MAP = {
'HeaderVersion': 'pimdmStateRefreshMessage.header.version-1',
'HeaderType': 'pimdmStateRefreshMessage.header.type-2... | nilq/baby-python | python |
from binary_search_tree.e_search_bst import BinarySearchTree
from binarytree import build
class TestBinarySearchTree:
def test_null_node(self):
bst = BinarySearchTree()
ans = bst.searchBST(None, 10)
assert ans is None
def test_root_node(self):
bst = BinarySearchTree()
... | nilq/baby-python | python |
# Generated by Django 4.0.3 on 2022-03-21 06:04
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('inadimplentes', '0010_alter_inquilino_status_de_pagamentos'),
]
operations = [
migrations.RemoveField(
model_name='inquilino',
... | nilq/baby-python | python |
'''
线性回归:
输入 输出
0.5 5.0
0.6 5.5
0.8 6.0
1.1 6.8
1.4 7.0
...
y = f(x)
预测函数:y = w0+w1x
x: 输入
y: 输出
w0和w1: 模型参数
所谓模型训练,就是根据已知... | nilq/baby-python | python |
"""Implementation of Rule L020."""
import itertools
from sqlfluff.core.rules.base import BaseCrawler, LintResult
class Rule_L020(BaseCrawler):
"""Table aliases should be unique within each clause."""
def _lint_references_and_aliases(
self,
table_aliases,
value_table_function_aliases... | nilq/baby-python | python |
from django.db import models
class ExchangeRateManager(models.Manager):
def get_query_set(self):
return super(ExchangeRateManager, self).get_query_set()\
.select_related('source', 'target')
def get_rate(self, source_currency, target_currency):
return self.get(source__code=source_c... | nilq/baby-python | python |
import base64
class Module:
def __init__(self, mainMenu, params=[]):
# metadata info about the module, not modified during runtime
self.info = {
# name for the module that will appear in module menus
'Name': 'CreateDylibHijacker',
# list of one or more authors ... | nilq/baby-python | python |
import dash_html_components as html
import dash_core_components as dcc
import dash_bootstrap_components as dbc
from dash.dependencies import Output,Input,State
from dash import no_update
import random
from flask_login import current_user
import time
from functools import wraps
from server import app
login_alert = dbc... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""Namespace Service
The namespace service is responsible for
* Providing the default namespace from config
* Providing list of all known namespaces
"""
from typing import List
from brewtils.models import Garden, Request, System
import beer_garden.db.api as db
import beer_garden.config as co... | nilq/baby-python | python |
from dancingshoes.helpers import GlyphNamesFromFontLabFont, AssignFeatureCodeToFontLabFont
from myFP.features import MakeDancingShoes
f = fl.font
fl.output = ''
glyphnames = GlyphNamesFromFontLabFont(f)
shoes = MakeDancingShoes(glyphnames)
AssignFeatureCodeToFontLabFont(f, shoes)
# Verbose output
if sh... | nilq/baby-python | python |
# Copyright 2018 Xanadu Quantum Technologies Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agre... | nilq/baby-python | python |
#!/usr/bin/env python
# encoding: utf-8
# File : test_processor.py
# Author : Ben Wu
# Contact : benwu@fnal.gov
# Date : 2019 Mar 06
#
# Description :
import sys
import os
sys.path.insert(1, "%s/../.." % os.path.dirname(os.path.abspath(__file__)))
from NanoUpTools.framework import processor
f... | nilq/baby-python | python |
#!/bin/python3
import os
# Complete the maximumPeople function below.
def maximumPeople(p, x, y, r):
# Return the maximum number of people that will be in a sunny town after removing exactly one cloud.
import operator
# make list of cloud tuples with start and end
clouds = []
for location_cloud,... | nilq/baby-python | python |
from .subsample import ExtractPatches
from .augment import Flip_Rotate_2D, Shift_Squeeze_Intensities, Flip_Rotate_3D, MaskData | nilq/baby-python | python |
import requests
class Config:
ak = "PmkYQbXLGxqHnQvRktDZCGMSHGOil2Yx"
ride_url_temp = "http://api.map.baidu.com/direction/v2/riding?origin={},{}&destination={},{}&ak={}"
baidu_map_url_temp = "http://api.map.baidu.com/geocoding/v3/?address={}&output=json&ak={}"
wm_get_url = "https://apimobile.meituan.c... | nilq/baby-python | python |
import datetime
import time
import iso8601
import psycopg2
from temba_client.v2 import TembaClient
RAPIDPRO_URL = "https://rapidpro.prd.momconnect.co.za/"
RAPIDPRO_TOKEN = ""
DB = {
"dbname": "ndoh_rapidpro",
"user": "ndoh_rapidpro",
"port": 7000,
"host": "localhost",
"password": "",
}
if __nam... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2006-2009 Edgewall Software
# Copyright (C) 2006 Matthew Good <matt@matt-good.net>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac... | nilq/baby-python | python |
#!/usr/bin/env python
# -- coding: utf-8 --
"""
@AUTHOR : zlikun <zlikun-dev@hotmail.com>
@DATE : 2019/03/01 17:03:55
@DESC : 两数相加
"""
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# ... | nilq/baby-python | python |
#-*- coding: utf-8 -*-
from api.management.commands.importbasics import *
def import_idols(opt):
local, redownload = opt['local'], opt['redownload']
idols = models.Idol.objects.all().order_by('-main', '-main_unit')
for idol in raw_information.keys():
card = models.Card.objects.filter(name=idol).ord... | nilq/baby-python | python |
#-*- coding:utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# Copyright (C) 2013-2015 Akretion (http://www.akretion.com)
from . import wizard
| nilq/baby-python | python |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: rastervision/protos/task.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import ref... | nilq/baby-python | python |
from rest_framework.serializers import ModelSerializer
from .models import UploadedFile
class UploadedFileSerializer(ModelSerializer):
class Meta:
model = UploadedFile
fields = ("id" , "user_id" , "file" , "size" , "type" )
def __init__(self, *args, **kwargs):
super(UploadedFi... | nilq/baby-python | python |
# Data sources
tissues = {
'TCGA': ['All'],
'GDSC': ['All']
}
projects = {
'TCGA':[None],
'GDSC': None
}
data_sources = ['GDSC', 'TCGA']
data_types = ['rnaseq']
genes_filtering = 'mini'
source = 'GDSC'
target = 'TCGA'
# TRANSACT analysis
kernel_surname = 'rbf_gamma_0_0005'
kernel_name = 'rbf'
kernel... | nilq/baby-python | python |
import unittest
from mocks import MockUser
class TestUser(unittest.TestCase):
def testEmailNickname(self):
user = MockUser(email="foo@example.com")
self.assertEquals(str(user), "foo")
def testNicknameOverride(self):
user = MockUser(email="foo@example.com", nickname="bar")
self.assertEquals(str... | nilq/baby-python | python |
#!/usr/bin/env python3
import sys
def main(phone_map, abbreviations):
phone_map = {v[0]: v[1].strip()
for v in (l.split(None, 1)
for l in open(phone_map, encoding='utf-8'))}
abbr_map = {v[0]: v[1].strip().split(',')
for v in (l.split(None, 1)
... | nilq/baby-python | python |
"""Tests for the HTMLSanitize preprocessor"""
from .base import PreprocessorTestsBase
from ..sanitize import SanitizeHTML
from nbformat import v4 as nbformat
class TestSanitizer(PreprocessorTestsBase):
"""Contains test functions for sanitize.py"""
maxDiff = None
def build_preprocessor(self):
... | nilq/baby-python | python |
'''Dois times, Cormengo e Flaminthians,
participam de um campeonato de futebol,
juntamente com outros times. Cada vitória
conta três pontos, cada empate um ponto.
Fica melhor classificado no campeonato
um time que tenha mais pontos. Em caso
de empate no número de pontos, fica
melhor classificado o time que tiver
maior ... | nilq/baby-python | python |
"""
Класс данных БД
"""
import sqlite3
import os
class DbLib:
def __init__(self,namefile):
if not os.path.exists(namefile):
self.conn = sqlite3.connect(namefile, check_same_thread=False)
self.c = self.conn.cursor()
# Create table
... | nilq/baby-python | python |
from discord.ext import commands as cmd
import os
import util.Modular as mod
class Setup(cmd.Cog):
def __init__(self, panda):
self.panda = panda
@cmd.Cog.listener()
async def on_ready(self):
print('Successfuly initalized Panda™'+'\n'*5)
@cmd.command(help='Basic inform... | nilq/baby-python | python |
import time
# You can edit this code and run it right here in the browser!
# First we'll import some turtles and shapes:
from turtle import *
from shapes import *
# Creating a window
window = turtle.Screen()
window.setup(400, 400)
# Create a turtle named Tommy:
tommy = Turtle()
tommy.shape("turtle")
tommy.speed(0)
# s... | nilq/baby-python | python |
ACTION_CLEAN = 'clean'
ACTION_CREATE_USERDEF = 'createuserdef'
ACTION_PREPARE = 'prepare'
ACTION_BUILD = 'build'
ACTION_BACKUP = 'backup'
ACTION_CREATE_NUGET = 'createnuget'
ACTION_PUBLISH_NUGET = 'publishnuget'
ACTION_UPDATE_SAMPLE = 'updatesample'
ACTION_RELEASE_NOTES = 'releasenotes'
ACTION_UPLOAD_BACKUP = 'uploadb... | nilq/baby-python | python |
# AI_Javaher
# this is the first session of GDAL/OGR tutorial
# install GDAL video : https://www.youtube.com/watch?v=YsdHWT-hA4k&list=PLFhf3UaNX_xc8ivjt773rAjGNoAfz_ELm&index=2
# check the video of this code in youtube :https://www.youtube.com/watch?v=F1jaX9vmhIk
# you can find the list of videos about GDAL tutorial in... | nilq/baby-python | python |
# Builtin
import os
import unittest
# Internal
from nxt import stage, nxt_layer
class TestReferences(unittest.TestCase):
def test_reference_by_path(self):
test_dir = os.path.dirname(__file__)
empty_path = os.path.join(test_dir, 'empty.nxt')
pre_test = stage.Stage.load_from_filepath(empty_... | nilq/baby-python | python |
from Utilities import *
def convert_type(in_type: str) -> str:
if in_type == 'bit':
return 'boolean'
if in_type == 'datetime':
return 'Date'
if in_type == 'mediumtext':
return 'String'
if in_type == 'nonnegativeinteger':
return 'int'
if in_type == 'phone':
r... | nilq/baby-python | python |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^(?P<pk>[0-9]+)$', views.DocumentDetailView.as_view(), name='document_detail'),
url(r'^create/$', views.DocumentCreate.as_view(), name='document_create'),
url(r'^update/(?P<pk>[0-9]+)$', views.DocumentUpdate.as_view(), name='docume... | nilq/baby-python | python |
from django.db import models
class StatisticsMemory(models.Model):
value = models.FloatField()
| nilq/baby-python | python |
""" AUTHTAB.DIR file parser. """
from pybycus.file import File
class AuthTab(File):
""" The Author List (with the filename AUTHTAB.DIR) contains
descriptive information for each text file on the disc. The
purpose of the Author Table is to allow the user to ask for
the author Plato, for example, withou... | nilq/baby-python | python |
"""
Get an admin token for KeyCloak.
"""
import logging
from functools import partial
import requests
from rest_tools.server import from_environment
from rest_tools.client import RestClient
def get_token(url, client_id, client_secret, client_realm='master'):
url = f'{url}/auth/realms/{client_realm}/protocol/open... | nilq/baby-python | python |
import scrapy
import codecs
import re
import json
from ..items import WebcrawlerItem
def unmangle_utf8(match):
escaped = match.group(0) # '\\u00e2\\u0082\\u00ac'
hexstr = escaped.replace(r'\u00', '') # 'e282ac'
buffer = codecs.decode(hexstr, "hex") # b'\xe2\x82\xac'
try:
... | nilq/baby-python | python |
raise ValueError('character must be a single string')
raise ValueError('width must be greater than 2')
try
....
except ValueError as err:
print(str(err))
# if we want to log errors that are not crashers:
import traceback
now = datetime.datetime.now()
now = now.strftime('%Y-%m-%d %H:%M:%S')
except:
err... | nilq/baby-python | python |
## predict iris dataset
## imports
import numpy as np
import pandas as pd
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
import neptune
import os
from dotenv import load_dotenv
load_dotenv()
## setup neptune account
NEPTUNE_API_KEY... | nilq/baby-python | python |
# Generated by Django 3.2.12 on 2022-04-13 19:51
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('crypto', '0004_alert_user'),
]
operations = [
migrations.RenameField(
model_name='asset',
... | nilq/baby-python | python |
# coding: utf-8
"""
ThingsBoard REST API
For instructions how to authorize requests please visit <a href='http://thingsboard.io/docs/reference/rest-api/'>REST API documentation page</a>. # noqa: E501
OpenAPI spec version: 2.0
Contact: info@thingsboard.io
Generated by: https://github.com/swagger-... | nilq/baby-python | python |
import graphene
import pytest
from ....tests.utils import get_graphql_content
QUERY_GIFT_CARDS = """
query giftCards($filter: GiftCardFilterInput){
giftCards(first: 10, filter: $filter) {
edges {
node {
id
displayCode
}
... | nilq/baby-python | python |
import sqlalchemy as sa
import aiopg.sa
meta = sa.MetaData()
question = sa.Table(
'question', meta,
sa.Column('id', sa.Integer, nullable=False),
sa.Column('question_text', sa.String(200), nullable=False),
sa.Column('pub_date', sa.Date, nullable=False),
# Indexes
sa.PrimaryKeyConstraint('id',... | nilq/baby-python | python |
import json
import argparse
def main():
parser = argparse.ArgumentParser(description='Conversion IO')
parser.add_argument("--input_file", dest="input_file", type=argparse.FileType('r', encoding='UTF-8'), required=True)
parser.add_argument("--output_file", dest="output_file", type=argparse.FileType('w', enc... | nilq/baby-python | python |
import xml.etree.ElementTree as ET
import sys
tree = ET.parse(sys.argv[1])
# the xml tree is of the form
# <expr><list> {all options, each an attrs} </list></expr>
options = list(tree.getroot().find('list'))
def sortKey(opt):
def order(s):
if s.startswith("enable"):
return 0
if s.start... | nilq/baby-python | python |
from typing import Tuple, Union
import torch
def make_dense_volume(
ind: torch.Tensor,
voxel_res: Union[int, Tuple[int, int, int]]
) -> torch.Tensor:
if isinstance(voxel_res, int):
voxel_res = (voxel_res, voxel_res, voxel_res)
grid = torch.zeros(voxel_res, dtype=torch.bool)
grid[ind[:, ... | nilq/baby-python | python |
import os
from django.http import FileResponse
from wsgiref.util import FileWrapper
from settings.static import MEDIA_URL
# from django.core.servers.basehttp import FileWrapper
from django.views.generic import TemplateView
from django.shortcuts import render_to_response, render, redirect, get_object_or_404
from django.... | nilq/baby-python | python |
from functools import cached_property
from ..typing import TYPE_CHECKING, Any, Callable, Catchable
if TYPE_CHECKING:
from .fn import fn
def as_method(method, name):
method.__name__ = name
method.__qualname__ = f"fn.{name}"
method.__doc__ = "Auto generated, see :func:`sidekick.functions.{name}`"
... | nilq/baby-python | python |
import requests
from typing import Dict, NamedTuple, NoReturn
from bs4 import BeautifulSoup
class WorkshopError(Exception):
def __init__(self, error: str):
self.error = error
def __str__(self) -> str:
return self.error
class Script(NamedTuple):
"""Encapsulate a numworks workshop pyth... | nilq/baby-python | python |
import json
import os
import random
import bottle
from api import ping_response, start_response, move_response, end_response
@bottle.route('/')
def index():
return '''
Battlesnake documentation can be found at
<a href="https://docs.battlesnake.io">https://docs.battlesnake.io</a>.
'''
@bottle.route... | nilq/baby-python | python |
import json
import itertools as it
from collections import defaultdict
import textwrap
from itertools import chain
COURSE_LIST_FILENAME = 'course_list.json'
REVERSE_KDAM_FILENAME = 'reverse_kdam.json'
REVERSE_ADJACENT_FILENAME = 'reverse_adjacent.json'
def read_json_to_dict(filename=COURSE_LIST_FILENAME):
with op... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# created: 2021-06-22
# creator: liguopeng@liguopeng.net
import asyncio
from gcommon.aio.gasync import maybe_async
def sync_call():
print("sync")
return "1"
async def async_call():
await asyncio.sleep(1)
print("async")
return "2"
async def test():
r = await maybe_... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from peewee import *
from telegram import User as TelegramUser
import util
from model.user import User
from model.basemodel import BaseModel
class APIAccess(BaseModel):
user = ForeignKeyField(User)
token = CharField(32)
webhook_url = CharField(null=True)
| nilq/baby-python | python |
"""Module to test reset password"""
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from django.contrib.auth import get_user_model
from django.contrib.auth.tokens import default_token_generator
class ResetPassword(APITestCase):
def setUp(self):
... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.