content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
import re
from fsrtools.simulation_tools._manager_utils import integer_filter
def product_combination_generator(iterate_dict):
total_length = 1
length_dict = {}
combination_list = []
if len(iterate_dict.keys()):
for key in iterate_dict.keys():
length_dict[key] = len(iterate_dict[ke... | nilq/baby-python | python |
############### usha/ssd_distplot_seaborn.ipynb
import csv
import os.path
my_path = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', '..'))
path = os.path.join(my_path, 'documents/Leadss.csv')
fpath = os.path.join(my_path, 'static/images/distplot')
import pandas as pd
import numpy as np
import seaborn ... | nilq/baby-python | python |
{
"includes": [
"../common.gypi"
],
"targets": [
{
"target_name": "libgdal_jpeg_frmt",
"type": "static_library",
"sources": [
"../gdal/frmts/jpeg/jpgdataset.cpp",
"../gdal/frmts/jpeg/libjpeg/jcapimin.c",
"../gdal/frmts/jpeg/libjpeg/jcapistd.c",
"../gdal/frmts/jpeg/libjpeg/jccoefct.c",
... | nilq/baby-python | python |
import datetime
import numpy as np
import cv2
import pickle
import face_recognition
# -------------------------------------------------------------------
# Parameters
# -------------------------------------------------------------------
CONF_THRESHOLD = 0.5
NMS_THRESHOLD = 0.4
IMG_WIDTH = 416
IMG_HEIGHT = 416
# Defa... | nilq/baby-python | python |
#!/usr/bin/python3
# encoding: utf-8
"""
@author: m1n9yu3
@license: (C) Copyright 2021-2023, Node Supply Chain Manager Corporation Limited.
@file: web_server.py
@time: 2021/4/27 13:41
@desc:
"""
from flask import *
from huluxiaThirdflood_api import get_random_imageurl
import conf
app = Flask(__name__)
@app.route('... | nilq/baby-python | python |
import UDPComms
import numpy as np
import time
from pupper.Config import Configuration
from src.State import BehaviorState, State, ArmState
from src.Command import Command
from src.Utilities import deadband, clipped_first_order_filter
class JoystickInterface:
def __init__(
self, config: Configuration, ud... | nilq/baby-python | python |
import cv2
from je_open_cv import template_detection
image_data_array = template_detection.find_object("../test.png", "../test_template.png", detect_threshold=0.9, draw_image=True)
print(image_data_array)
if image_data_array[0] is True:
height = image_data_array[1][2] - image_data_array[1][0]
width = image_... | nilq/baby-python | python |
from __future__ import division
from itertools import izip, count
import matplotlib.pyplot as plt
from numpy import linspace, loadtxt, ones, convolve
import numpy as np
import pandas as pd
import collections
from random import randint
from matplotlib import style
style.use('fivethirtyeight')
#tab csv
data = loadtxt("d... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import mock
import pytest
from h.interfaces import IGroupService
from h.services.annotation_json_presentation import AnnotationJSONPresentationService
from h.services.annotation_json_presentation import annotation_json_presentation_service_factory
@py... | nilq/baby-python | python |
from flask import Flask
from flask_restful import Resource, Api
from flask_cors import CORS
from api.db_utils import *
from api.Culprit_api import *
app = Flask(__name__) #create Flask instance
CORS(app)
api = Api(app) #api router
api.add_resource(CaseSetup,'/case-setup')
api.add_resource(Session, '/key')
api.add_r... | nilq/baby-python | python |
from ._sw import Controller
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import (
absolute_import, division, print_function, unicode_literals)
import json
try:
from urllib import parse as urlparse
except ImportError:
import urlparse
from operator import itemgetter
import yaml
from flask import jsonify, request, Blueprint
from builtin... | nilq/baby-python | python |
import yaml
import rclpy
import std_msgs.msg as std
import geometry_msgs.msg as geom
from msg_printer.std_yaml import YamlHeader
class YamlAccel(yaml.YAMLObject):
yaml_tag = u"!Accel"
def __init__(self, a: geom.Accel):
self._dict = {
"linear": YamlVector3(a.linear).dict,
"an... | nilq/baby-python | python |
import os
import sys
import time
import argparse
from naoqi import ALProxy
import robot_behavior_pb2
from os.path import dirname
from os.path import abspath
def register_motions(name,parameterServerAddress,motions):
behaviorModule = robot_behavior_pb2.RobotBehaviorModule()
behaviorModule.name = name
for... | nilq/baby-python | python |
#!/usr/bin/env python
domain_name = os.environ['DOMAIN_NAME']
admin_server_listen_address = os.environ['ADMIN_SERVER_LISTEN_ADDRESS']
admin_server_listen_port = os.environ['ADMIN_SERVER_LISTEN_PORT']
admin_username = os.environ['ADMIN_USERNAME']
admin_password = os.environ['ADMIN_PASSWORD']
#########################... | nilq/baby-python | python |
from django.db import models
import json
# Create your models here.
class weather(models.Model):
'''
溫度、最高溫、最低溫、露點溫度、相對濕度、最小相對濕度、降雨量、最大十分鐘降雨量、最大六十分鐘降雨量
'''
date = models.DateTimeField()
temperature = models.FloatField()
relativeHumidity = models.FloatField()
rainfall = models.FloatField()
... | nilq/baby-python | python |
class Solution:
#c1 is always opening type
def counter_part(self, c1: str, c2:str)->bool:
if c1 == '(' and c2 == ')':
return True
if c1 == '{' and c2 == '}':
return True
if c1 == '[' and c2 == ']':
return True
return False
def isVal... | nilq/baby-python | python |
from __future__ import unicode_literals
__VERSION__ = '0.1.1'
| nilq/baby-python | python |
import os
###############################################################################
def create_dir(path):
if not os.path.isdir(path):
os.makedirs(path)
###############################################################################
# SAVE A DICTIONARY
dict_ = {}
import json
with open(os.pa... | nilq/baby-python | python |
# KicadModTree 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 3 of the License, or
# (at your option) any later version.
#
# KicadModTree is distributed in the hope that it will be useful,
# bu... | nilq/baby-python | python |
import sys
from antlr4 import *
import graphGenerator
from MyVisitor import MyVisitor
from PythonLexer import PythonLexer
from PythonParser import PythonParser
import os
def testefunc(graph, code, function):
file = open("testfile.txt", "w")
file.write(code)
file.close()
input=FileStream("testfile.txt... | nilq/baby-python | python |
#!/usr/bin/python3
# Modifies the assembly output of compilation for control_mem_dtlb_store
# to provide necessary pattern for successful TLB/store attack on gem5
# See parse_tlb_logs.py for more details
# generated with gcc version 9.3.0 (Ubuntu 9.3.0-17ubuntu1~20.04)
# command: gcc src/control_mem_dtlb_store -S -o ... | nilq/baby-python | python |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | nilq/baby-python | python |
#-*- encoding: utf-8 -*-
import redis
r=redis.Redis(host='localhost',db=0)
p=r.pubsub()
p.subscribe('test')
for message in p.listen():
print(message) | nilq/baby-python | python |
# Holds permission data for a private race room
def get_permission_info(server, race_private_info):
permission_info = PermissionInfo()
for admin_name in race_private_info.admin_names:
for role in server.roles:
if role.name.lower() == admin_name.lower():
permission_info.admi... | nilq/baby-python | python |
"""
loader module provides actual implementation of the file savers.
.. warning:: This is an internal implementation. API may change without
notice in the future, so you should use
:class:`word_embedding_loader.word_embedding.WordEmbedding`
"""
__all__ = ["glove", "word2vec_bin", "word2vec_t... | nilq/baby-python | python |
# Stimulator class
# Imports
#from StimulationSignal import StimulationSignal
import crccheck.checksum
import numpy as np
import serial
import time
import struct
# channel_stim: list of active channels
# freq: main stimulation frequency in Hz (NOTE: this overrides ts1)
# ts1: main stimulati... | nilq/baby-python | python |
class Order(object):
def __init__(self, name, address, comments):
self.name = name
self.address = address
self.comments = comments
| nilq/baby-python | python |
"""Helper functions for all Solar Forecast Arbiter /sites/* endpoints.
"""
import time
from flask import current_app as app
from requests.exceptions import ChunkedEncodingError, ConnectionError
from sentry_sdk import capture_exception
from sfa_dash import oauth_request_session
from sfa_dash.api_interface.util impor... | nilq/baby-python | python |
from django.urls import path
from app.pages.views import (
display_customers_data_page,
display_customer_by_id_page,
display_home_page,
)
urlpatterns = [
path('', display_home_page),
path('customers/', display_customers_data_page, name="customers"),
path('customers_by_id/',
display_cu... | nilq/baby-python | python |
import pytest
from orders.models import Order
pytestmark = [pytest.mark.django_db]
def test_tinkoff_bank_is_called_by_default(call_purchase, tinkoff_bank, tinkoff_credit):
call_purchase()
tinkoff_bank.assert_called_once()
tinkoff_credit.assert_not_called()
def test_tinkoff_bank(call_purchase, tinkoff... | nilq/baby-python | python |
"""
This file contains the core methods for the Batch-command- and
Batch-code-processors respectively. In short, these are two different
ways to build a game world using a normal text-editor without having
to do so 'on the fly' in-game. They also serve as an automatic backup
so you can quickly recreate a world also aft... | nilq/baby-python | python |
from typing import Optional, Union
from .set_config import _get_config
class _Engine(object):
"""Indicates the database engine that is currently in use."""
ENGINE = 0
MYSQL = 1
SQLITE = 3
_created = False # Indicates whether the connection to the database has been created.
@classm... | nilq/baby-python | python |
import argparse
import confluent.client as cli
import sys
import time
c = cli.Command()
nodes = []
ap = argparse.ArgumentParser(description='Snake identify light through nodes')
ap.add_argument('noderange', help='Noderange to iterate through')
ap.add_argument('-d', '--duration', type=float, help='How long to have each ... | nilq/baby-python | python |
# Generated by Django 3.1.7 on 2021-03-12 13:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0010_genre_desc'),
]
operations = [
migrations.AlterField(
model_name='genre',
name='desc',
fiel... | nilq/baby-python | python |
import os
import sys
from pathlib import Path
from typing import List
import nox
nox.options.sessions = ["lint", "test-dist"]
PYTHON_ALL_VERSIONS = ["3.6", "3.7", "3.8", "3.9", "3.10"]
RUNNING_CI = "TRAVIS" in os.environ or "GITHUB_ACTIONS" in os.environ
@nox.session(python=["3.6"], reuse_venv=True)
def lint(sessi... | nilq/baby-python | python |
import pandas as pd
#given a word, search all cases and find caseNames which contain the word
#return as a dataframe
def search_scdb_cases_by_name(word,all_scdb_case_data):
return all_scdb_case_data[all_scdb_case_data['caseName'].str.contains(word,na=False)]
#try to convert case names from SCDB 'caseName' field t... | nilq/baby-python | python |
# MIT License
#
# Copyright (c) 2020 University of Oxford
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify... | nilq/baby-python | python |
"""
[summary]
[extended_summary]
"""
# region [Imports]
# * Standard Library Imports ---------------------------------------------------------------------------->
import os
import traceback
from datetime import datetime
from typing import Tuple
import re
# * Third Party Imports --------------------------------------... | nilq/baby-python | python |
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | nilq/baby-python | python |
# Copyright (c) 2012-2018 SoftBank Robotics. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the COPYING file.
import os
def test_simple(qidoc_action):
world_proj = qidoc_action.add_test_project("world")
build_dir = os.path.join(world_proj.path, "build... | nilq/baby-python | python |
from io import BytesIO
from .utils import Tools, Status, Network
from .config import highQuality
from .config import RESOURCES_BASE_PATH
from PIL import Image, ImageDraw, ImageFilter, ImageFont
class User():
def __init__(self, nickname, favorability, days, hitokoto):
self._userNickname = nickname
... | nilq/baby-python | python |
import time
import argparse
import numpy as np
import matplotlib.pyplot as plt
import torch
import torchvision
import torchvision.transforms as transforms
import n3ml.model
import n3ml.encoder
import n3ml.optimizer
np.set_printoptions(threshold=np.inf, linewidth=np.nan)
class Plot:
def __init__(self):
... | nilq/baby-python | python |
import numpy as np
from c4.tables import rev_segments, all_segments
PLAYER1 = 1
PLAYER2 = 2
DRAW = 0
COMPUTE = -1
class WrongMoveError(Exception):
pass
class Board(object):
def __init__(self, pos=None, stm=PLAYER1, end=COMPUTE, cols=7, rows=6):
if pos is None:
pos = np.zeros((cols, ro... | nilq/baby-python | python |
from math import sqrt
__author__ = "Samvid Mistry"
import time
from MAnimations.MAnimate import MAnimate
from PySide.QtGui import QApplication, QPainterPath
from PySide.QtCore import QPoint, QPointF
class MCircularReveal(MAnimate):
"""
Can be used to perform circular reveal or circular hide animation
on... | nilq/baby-python | python |
import tensorflow as tf
import numpy as np
import sys, os
import getopt
import random
import datetime
import traceback
import pandas as pd
import cfr.cfr_net as cfr
from cfr.util import *
''' Define parameter flags '''
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string('loss', 'l2', """Which loss function to use (l... | nilq/baby-python | python |
from compecon.tools import Options_Container, qzordered
import numpy as np
import pandas as pd
from compecon.tools import jacobian, hessian, gridmake, indices
__author__ = 'Randall'
class LQlabels(Options_Container):
""" Container for labels of the LQmodel variables
Attributes:
s labels for contin... | nilq/baby-python | python |
h1, m1, h2, m2 = map(int, input().split())
minutos = m2 - m1
horas = h2 - h1
if horas <= 0:
horas += 24
if minutos < 0:
horas -= 1
minutos = 60 + minutos
print("O JOGO DUROU {} HORA(S) E {} MINUTO(S)".format(horas, minutos))
| nilq/baby-python | python |
# grad.py
"""
Created on Fri May 25 19:10:00 2018
@author: Wentao Huang
"""
from torch.autograd import Function
class Grad(Function):
r"""Records operation history and defines formulas for differentiating ops.
Each function object is meant to be used only once (in the forward pass).
Attributes:
... | nilq/baby-python | python |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: Wang Zhiyi
@file: logger.py
@time: 6/20/2021
@version: 1.0
"""
import os
from pyspark.ml.pipeline import PipelineModel
from spark_manager import get_spark_session
_spark_session = get_spark_session()
_spark_context = _spark_session.sparkContext
def loa... | nilq/baby-python | python |
import tensorflow as tf
import numpy as np
from PIL import Image
import os
def maybe_download(directory, filename, url):
print('Try to dwnloaded', url)
if not tf.gfile.Exists(directory):
tf.gfile.MakeDirs(directory)
filepath = os.path.join(directory, filename)
if not tf.gfile.Exists(filepath):
filepath... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import scrapy
import json
from locations.items import GeojsonPointItem
from locations.hours import OpeningHours
class SprintSpider(scrapy.Spider):
name = "sprint"
allowed_domains = ["sprint.com"]
start_urls = (
'https://www.sprint.com/locations/',
)
def parse_hour... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2019 John J. Rofrano <rofrano@gmail.com>
# 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
#
# https://www.apache.org/licenses/L... | nilq/baby-python | python |
#!/usr/bin/python
'''
Created on Apr 19, 2016
@author: Rohan Achar
'''
import sys
import argparse
from spacetime.store_server import FrameServer
import cmd
import shlex
from flask import request
from threading import Thread as Parallel
class SpacetimeConsole(cmd.Cmd):
prompt = 'Spacetime> '
"""Command consol... | nilq/baby-python | python |
import dydra
##
# Represents a Dydra.com RDF repository.
#
# @see http://docs.dydra.com/sdk/python
class Repository(dydra.Resource):
"""Represents a Dydra.com RDF repository."""
##
# (Attribute) The repository name.
name = None
##
# @param name A valid repository name.
def __init__(self, name, **kwargs... | nilq/baby-python | python |
import cv2
import numpy as np
src = cv2.imread('data/src/lena.jpg')
mask = np.zeros_like(src)
print(mask.shape)
# (225, 400, 3)
print(mask.dtype)
# uint8
cv2.rectangle(mask, (50, 50), (100, 200), (255, 255, 255), thickness=-1)
cv2.circle(mask, (200, 100), 50, (255, 255, 255), thickness=-1)
cv2.fillConvexPoly(mask,... | nilq/baby-python | python |
"""Base test class for DNS authenticators."""
import configobj
import josepy as jose
import mock
import six
from acme import challenges
from certbot import achallenges
from certbot.compat import filesystem
from certbot.tests import acme_util
from certbot.tests import util as test_util
DOMAIN = 'example.com'
KEY = jo... | nilq/baby-python | python |
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
from torch import optim
from torch.utils.data import DataLoader
import torch
from dataloader import *
from model import *
from metric import *
import soundfile as sf
from semetrics import *
test_clean = "data/test_clean/"
test_noisy = "data/test_noisy/"
data_augment =... | nilq/baby-python | python |
#!venv/bin/python3
import logging
from logging.handlers import RotatingFileHandler
import sync_mongo
from sync_mongo import SyncMongo
__level = logging.DEBUG
logger = logging.getLogger(__name__)
uri = "repl1/localhost:27017,localhost:27018,localhost:27019"
def setup_logging():
FORMAT='%(asctime)s %(levelname)s:... | nilq/baby-python | python |
"""
Bilby
=====
Bilby: a user-friendly Bayesian inference library.
The aim of bilby is to provide a user-friendly interface to perform parameter
estimation. It is primarily designed and built for inference of compact
binary coalescence events in interferometric data, but it can also be used for
more general problems.... | nilq/baby-python | python |
from discord import Color, Embed, Member, Object
from discord.ext import commands
from discord.ext.commands import Context as CommandContext
PREMIUM_RULESBOT = 488367350274326528
ACTIVE_PATREON = 488774886043680769
class PremiumCog(object):
def __init__(self, bot: commands.Bot):
self.bot: commands.Bot = ... | nilq/baby-python | python |
"""Downloads the Forge MDK"""
import os
import zipfile
import shutil
import requests
from globals import *
import logger
import modfile
def download():
"""Downloads and extracts MDK"""
prefix = 'https://files.minecraftforge.net/maven/net/minecraftforge/forge/'
version = modfile.get('minecraft') + '-' ... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from django.db import migrations, models
import api.models
class Migration(migrations.Migration):
dependencies = [
('api', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='app',
name='id',
field=models.SlugF... | nilq/baby-python | python |
'''
Date: 2021-08-12 12:24:42
LastEditors: Liuliang
LastEditTime: 2021-08-12 18:28:35
Description:
'''
from typing import Optional
class Node():
def __init__(self, data) -> None:
self.data = data
self._next = None
# class LinkList():
# def __init__(self) -> None:
# self._head = None
... | 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 use ... | nilq/baby-python | python |
class Solution:
"""
@param arr: an array of integers
@return: the length of the shortest possible subsequence of integers that are unordered
"""
def shortestUnorderedArray(self, arr):
# write your code here
inc = dec = True
for i in range(len(arr) - 1):
if arr[i] ... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Copyright (c) 2018-2020 Niko Sandschneider
"""Module implementing Signals for communicating with the GUI."""
from functools import wraps
import logging
from PyQt5.QtCore import QObject, pyqtSignal
class Signals(QObject):
"""Class for signal communication between worker classes and G... | nilq/baby-python | python |
from django.contrib import admin
from main.models import StudentRegisterationForm
from django.http import HttpResponse
import csv
def show_email(obj):
email = obj.email
return '<a href="mailto:%s" target="_blank">%s</a>' % (email, email)
show_email.allow_tags = True
show_email.short_description = 'Email'
de... | nilq/baby-python | python |
############################################################################
# Copyright ESIEE Paris (2018) #
# #
# Contributor(s) : Benjamin Perret #
# ... | nilq/baby-python | python |
from collections import defaultdict, namedtuple
from numba import njit, jitclass
from numba import types
import numba
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np
from matplotlib.ticker import (AutoMinorLocator, MultipleLocator)
import argparse
parser = argparse.ArgumentParse... | nilq/baby-python | python |
"""
Quickly load ROOT symbols without triggering PyROOT's finalSetup().
The main principle is that appropriate dictionaries first need to be loaded.
"""
from __future__ import absolute_import
import ROOT
from .. import log; log = log[__name__]
from .module_facade import Facade
__all__ = []
root_module = ROOT.modul... | nilq/baby-python | python |
from contextlib import contextmanager
from flask_login import UserMixin
import markdown
from markdown.extensions.toc import TocExtension
from sqlalchemy import create_engine
from sqlalchemy import Column, Integer, String, DateTime
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarati... | nilq/baby-python | python |
__author__ = 'DafniAntotsiou'
import numpy as np
from gym import spaces
# universal prefix for the different networks
def get_il_prefix():
return 'il_'
def get_semi_prefix():
return 'semi_'
# add auxiliary actions to env observation space for semi network
def semi_ob_space(env, semi_size):
if semi_si... | nilq/baby-python | python |
#
# Copyright (c) 2018 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... | nilq/baby-python | python |
from .annotation import Sentence
from nltk.tokenize.punkt import PunktParameters
from nltk.tokenize.punkt import PunktSentenceTokenizer
from .ru.processor_tokenizer_ru import _ru_abbrevs
from .en.processor_tokenizer_nltk_en import _en_abbrevs
from itertools import combinations
class ProcessorSentenceSplitter:
"""... | nilq/baby-python | python |
import datetime
from django.db import IntegrityError
from django.db.models import Min, Max
from django.utils.timezone import make_aware
from zabiegi import models
def integruj_jednostki():
for w in (
models.WykazStrona1.objects.all()
.exclude(dane_operacji_jednostka_wykonująca_kod=None)
... | nilq/baby-python | python |
#!/usr/local/bin/python
#
# Copyright (c) 2009-2014 Sippy Software, Inc. All rights reserved.
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain th... | nilq/baby-python | python |
from datasets import load_dataset
cord = load_dataset("katanaml/cord")
#
labels = cord['train'].features['ner_tags'].feature.names
#
id2label = {v: k for v, k in enumerate(labels)}
label2id = {k: v for v, k in enumerate(labels)}
#
from PIL import Image
from transformers import LayoutLMv2Processor
from datasets i... | nilq/baby-python | python |
# Generated by Django 3.2.6 on 2021-09-18 04:13
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('registration', '0011_auto_20210917_0032'),
]
operations = [
migrations.DeleteModel(
name='Links',
),
migrations.RemoveFi... | nilq/baby-python | python |
# coding: utf-8
import scipy
import json
import re
import traceback
import allennlp
from allennlp.predictors.predictor import Predictor
import sys
from allennlp.commands.elmo import ElmoEmbedder
from spacy.lang.en import English
import numpy as np
# import tensorflow as tf
import torch
from hyperpara import *
impor... | nilq/baby-python | python |
import stoked
import numpy as np
from functools import partial
import matplotlib.pyplot as plt
def harmonic_force(time, position, orientation, stiffness):
return -stiffness*position
nm = 1e-9
us = 1e-6
stiffness = 2e-6
radius = 25*nm
N = 15
initial = np.random.uniform(-300*nm, 300*nm, size=(N,2))
Q = 1e-18
bd =... | nilq/baby-python | python |
# Test the unicode support! 👋
ᚴ=2
assert ᚴ*8 == 16
ᚴ="👋"
c = ᚴ*3
assert c == '👋👋👋'
import unicodedata
assert unicodedata.category('a') == 'Ll'
assert unicodedata.category('A') == 'Lu'
assert unicodedata.name('a') == 'LATIN SMALL LETTER A'
assert unicodedata.lookup('LATIN SMALL LETTER A') == 'a'
assert unic... | nilq/baby-python | python |
from pathlib import Path
from typing import Union
import click
import matplotlib.pyplot as plt
from ertk.dataset import read_features
@click.command()
@click.argument("input", type=click.Path(exists=True, dir_okay=False, path_type=Path))
@click.argument("instance", type=str, default="2")
def main(input: Path, insta... | nilq/baby-python | python |
import nbconvert, git, yaml, inspect; from pathlib import Path
class FrontMatters(nbconvert.exporters.MarkdownExporter):
def from_notebook_node(self, nb, resources=None, **kw):
nb, resources = super().from_notebook_node(nb, resources, **kw)
md = dict(resources['metadata'])
md['author'] = au... | nilq/baby-python | python |
import random
from arcade import Sprite, load_texture, check_for_collision_with_list
from activities import explore, backtrack, follow_the_food, find_the_food
from path import Path
class Ant(Sprite):
def __init__(self, x, y, arena, colony, scale=1, activity="wander"):
super().__init__(center_x=x, center_y... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 29 13:52:01 2017
@author: User
"""
import re
aPara = "this is a list of words. and here is another"
aList = []
print(aPara.split()) # splits into words
print(len(aPara.split())) # count of words
for item in re.split('[.]', aPara): #splits into sentences
... | nilq/baby-python | python |
## Copyright 2015-2019 Ilgar Lunin, Pedro Cabrera
## 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... | nilq/baby-python | python |
import argparse
from typing import Optional
from typing import Sequence
BLACKLIST = [
b'\x64\x6e\x63', #dnc
]
def main(argv: Optional[Sequence[str]] = None) -> int:
parser = argparse.ArgumentParser()
parser.add_argument('filenames', nargs='*', help='Filenames to check')
args = parser.parse_args(argv)... | nilq/baby-python | python |
# coding=utf-8
"""update_xml_verses.py
"""
from __future__ import print_function
import sys, re,codecs
sys.path.append('../step3e')
# the Entry object
from transcode import xml_header,read_entries
class Edit(object):
def __init__(self,lines):
self.lines = lines
assert lines[0] == '<edit>'
assert lines[-1] == ... | 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 us... | nilq/baby-python | python |
from subprocess import call
from core import kde
from core.action import has_dependency
class IconTheme4(kde.KDE4Action):
"""Change KDE's icon theme."""
def arguments(self):
return [
('theme', 'Icon theme name.')
]
def execute(self, theme):
kde.writeconfig("Icons", "Th... | nilq/baby-python | python |
import logging
import progressbar
from django.core.management.base import BaseCommand
from contentcuration.models import Channel
from contentcuration.utils.nodes import generate_diff
from contentcuration.utils.nodes import get_diff
logging.basicConfig()
logger = logging.getLogger('command')
class Command(BaseComma... | nilq/baby-python | python |
import os
import re
import json
import random
import codecs
import argparse
from template_config import *
from nltk import word_tokenize
from collections import defaultdict
from transformers.tokenization_roberta import RobertaTokenizer
ADD_INDEX_ID = 0.7
ADD_INDEX_NAME = 0.3
OP_VAL_EQUAL = 0.4
USE_TABLE_... | nilq/baby-python | python |
"""
Tests for exact diffuse initialization
Notes
-----
These tests are against four sources:
- Koopman (1997)
- The R package KFAS (v1.3.1): test_exact_diffuse_filtering.R
- Stata: test_exact_diffuse_filtering_stata.do
- Statsmodels state space models using approximate diffuse filtering
Koopman (1997) provides anal... | nilq/baby-python | python |
# Generated from astLogic/propositional.g4 by ANTLR 4.7.2
# encoding: utf-8
from antlr4 import *
from io import StringIO
from typing.io import TextIO
import sys
def serializedATN():
with StringIO() as buf:
buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\3\f")
buf.write("B\4\2\t\2\3\2\... | nilq/baby-python | python |
frase = " Amo Física, é a mãe de todas as ciências asd "
# atribuição duma string à uma variável
# print(frase[2])
# print(frase[0:4]) # vai do caractere 0 ao 4, excluindo o 4
# print(frase[0:10])
# print(frase[0:15:2]) # vai do crc.0 ao crc.15 saltando de 2 em 2
# print(frase[:13]) # começa do caractere inicial ... | nilq/baby-python | python |
"""Syntax checks
These checks verify syntax (schema), in particular for the ``extra``
section that is otherwise free-form.
"""
from . import LintCheck, ERROR, WARNING, INFO
class extra_identifiers_not_list(LintCheck):
"""The extra/identifiers section must be a list
Example::
extra:
ide... | nilq/baby-python | python |
#
# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
# its licensors.
#
# For complete copyright and license terms please see the LICENSE at the root of this
# distribution (the "License"). All use of this software is governed by the License,
# or, if provided, by the license below or th... | nilq/baby-python | python |
from cStringIO import StringIO
import tldextract
import web
try:
import json
except ImportError:
from django.utils import simplejson as json
urls = (
'/api/extract', 'Extract',
'/api/re', 'TLDSet',
'/test', 'Test',
)
class Extract:
def GET(self):
url = web.input(url='').ur... | nilq/baby-python | python |
#!/usr/bin/env python3
# import many libraries
from __future__ import print_function
import pickle
import os.path
import io
import subprocess
import urllib, json
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
impor... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.