content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
from app import db
import os
import requests
class Movies(db.Model):
"""
Models the data of movies related to a given location.
"""
id = db.Column(db.Integer, primary_key=True)
movies = db.Column(db.Text)
@staticmethod
def create_entry(query):
"""
Takes in a search query... | nilq/baby-python | python |
#
# Copyright (c) 2015-2021 Thierry Florac <tflorac AT ulthar.net>
# All Rights Reserved.
#
# 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 IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRAN... | nilq/baby-python | python |
from pydocstyle.checker import check
from pydocstyle.checker import violations
import testing
registry = violations.ErrorRegistry
_disabled_checks = [
'D202', # No blank lines allowed after function docstring
'D205', # 1 blank line required between summary line and description
]
def check_all_files():
... | nilq/baby-python | python |
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | nilq/baby-python | python |
# Generated by Django 3.0.2 on 2020-10-13 07:23
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('accounts', '0005_thirdpartycreds'),
]
operations = [
migrations.AlterModelOptions(
name='thirdpartycreds',
options={'verbose... | nilq/baby-python | python |
from skynet.common.base_daos import BaseDao
class BaseModel(object):
DEFAULT_DAO = BaseDao
def __init__(self, dao=None):
if dao is None:
dao = self.DEFAULT_DAO()
self.dao = dao
def populate(self, data):
for k, v in data.iteritems():
k_transl... | nilq/baby-python | python |
import os
import json
import html
from datetime import datetime, timedelta
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from starlette.requests import Request
from starlette.responses import JSONResponse
from auth import LEADERBOARD_API_TOKEN
app = FastAPI(redoc_url=... | nilq/baby-python | python |
# -*- encoding: utf-8 -*-
"""Handle root-services sessions endpoints."""
from .base import RootService
from ..decorators import dyndoc_insert, endpoint
from .responses.sessions import responses
@endpoint("openapi/root/v1/sessions/capabilities/")
class GetSessionCapabilities(RootService):
"""Get the sessions cap... | nilq/baby-python | python |
from __future__ import unicode_literals
from . import model
from . import collection
from . import fields
from . import related
| nilq/baby-python | python |
from collection.property_dictionary import PropertyDict
from collection.xml_interface import XMLError
from collection.xml_interface import XMLInterface
from metadata.metadata_api import MetadataError
from metadata.metadata_api import Metadata
from image.envi import ENVIHeader
| nilq/baby-python | python |
import json
import logging
import re
from datetime import datetime
from decimal import Decimal
from enum import Enum
from functools import singledispatch
from sys import version_info
from typing import Any, Optional, Tuple, Union
from urllib.parse import urlsplit
PY37 = version_info >= (3, 7)
class JSONEncoder(json.... | nilq/baby-python | python |
"""
Adapted from https://github.com/kirubarajan/roft/blob/master/generation/interactive_test.py to
process a batch of inputs.
"""
import argparse
import json
import numpy as np
import os
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
def main(args):
np.random.seed(args.random_seed)
... | nilq/baby-python | python |
#!/bin/python3
import math
count = 0
def count_inversions(a):
length = len(a)
if (length <= 1):
return a
else:
midP = int(math.floor(length / 2))
left = a[:midP]
right = a[midP:]
return merge(count_inversions(left), count_inversions(right))
def merge(left, right)... | nilq/baby-python | python |
import sklearn
from sklearn.linear_model import Perceptron
from sklearn.datasets import load_iris
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# load data
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['label'] = iris.target
df.columns = [
'sepal length', ... | nilq/baby-python | python |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""A basic unit test for the Python interface of the BMG C++ Graph.infer method"""
import unittest
import beanmachine.ppl as bm
from beanma... | nilq/baby-python | python |
# this brainfuck source code from https://github.com/kgabis/brainfuck-go/blob/master/bf.go
# and karminski port it to PHP
# and is ported to Python 3.x again
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
import sys
class Brainfuck:
# operators
op_inc_dp = 1
op_dec_... | nilq/baby-python | python |
import os
import platform
import getpass
if(platform.system() == "Windows"):
os.system("cls")
print(" _")
print("__ _____| | ___ ___ _ __ ___ ___ ")
print("\ \ /\ / / _ \ |/ __/ _ \| '_ ` _ \ / _ \ ")
print(" \ V V / __/ | (_| (_) | | | | | | __/ ")
print(" \_... | nilq/baby-python | python |
"""
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: MIT-0
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 limitat... | nilq/baby-python | python |
"""Utility code for argparse"""
import argparse
import yaml
#class StoreDictKeyPair(argparse.Action):
# """An action for reading key-value pairs from command line"""
# def __call__(self, parser, namespace, values, option_string=None):
# my_dict = {}
# for kv in values.split(","):
# k,v ... | nilq/baby-python | python |
# datastore transations and methods
from sqlalchemy.orm import load_only
from sqlalchemy.sql import text
def count_records(session, model, **kwargs):
row_count = session.query(model).filter_by(**kwargs).count()
return row_count
def delete_record(session, model, **kwargs):
instance = session.query(model... | nilq/baby-python | python |
import rclpy
from rclpy.node import Node
from rclpy.qos import qos_profile_sensor_data
from sensor_msgs.msg import Image # Image is the message type
import cv2 # OpenCV library
from cv_bridge import CvBridge # Package to convert between ROS and OpenCV Images
import numpy as np
# Naming the Output window
windowname = ... | nilq/baby-python | python |
from random import randint
import pygame as pg
from scripts import constants as const
class Bird(pg.sprite.Sprite):
SIZE = const.SPRITE_SIZE[0]
MIN_SPEED = 1
MAX_SPEED = 10
def __init__(self, bird_image):
pg.sprite.Sprite.__init__(self)
self.image = bird_image
self.rect = sel... | nilq/baby-python | python |
"""
Example showing for tkinter and ttk how to do:
-- Simple animation
-- on a tkinter Canvas.
References:
-- https://effbot.org/tkinterbook/canvas.htm
This is the simplest explanation,
but very old and possibly somewhat out of date.
Everywhere that it says "pack" use "grid" instead.
-- Th... | nilq/baby-python | python |
class LinkedList:
def __init__(self, head):
self.head = head
self.current_element = self.head
# Node navigation
def next(self):
if self.current_element.next is None:
return
self.current_element = self.current_element.next
def go_back_to_head(self):
... | nilq/baby-python | python |
import pandas as pd
import os
import subprocess as sub
import re
import sys
from Bio import SeqUtils
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats
# path = os.path.join(os.path.expanduser('~'),'GENOMES_BACTER_RELEASE69/genbank')
path = "."
# ['DbxRefs','Description','FeaturesNum','assemb... | nilq/baby-python | python |
from flask import *
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.schema import Sequence
app = Flask(__name__, static_url_path='/static') #referencing this while
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///App.sqlite3'
app.config['SECRET_KEY'] = "secret key"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS']... | nilq/baby-python | python |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import scriptcontext as sc
import compas_rhino
from compas_ags.rhino import SettingsForm
from compas_ags.rhino import FormObject
from compas_ags.rhino import ForceObject
__commandname__ = "AGS_toolbar_displa... | nilq/baby-python | python |
class DianpingConfig:
def __init__(self):
self.instance_name = "BERTModel.pt"
self.model_name = self.instance_name
self.BERT_MODEL = "bert-base-chinese"
self.max_sent_lens = 64
class SSTConfig:
def __init__(self):
self.instance_name = "BERTModel.pt"
self.model_na... | nilq/baby-python | python |
from __future__ import unicode_literals
from djangobmf.apps import ContribTemplate
class EmployeeConfig(ContribTemplate):
name = 'djangobmf.contrib.employee'
label = "djangobmf_employee"
| nilq/baby-python | python |
import eel
try:
from pyfirmata import Arduino, util
except:
from pip._internal import main as pipmain
pipmain(['install','pyfirmata'])
from pyfirmata import Arduino, util
#Get Operating System Type
import platform
currentOs = platform.system()
if "linux" in currentOs.lower():
curr... | nilq/baby-python | python |
from sys import argv
script, filename=argv
print(f"We're going to erase{filename}.")
print("If you don't want that,hit CTRL-C(^C).")
print("If you do want that,hit RETURN.")
input("?")
print("Opening the file..")
target=open(filename,'w')
print("Truncating the file,Goodbye!")
target.truncate()
print("Now I'm goin... | nilq/baby-python | python |
# =============================================================================== #
# #
# This file has been generated automatically!! Do not change this manually! #
# ... | nilq/baby-python | python |
#MenuTitle: Check glyphsets match across open fonts
'''
Find missing glyphs across fonts
'''
def main():
fonts = Glyphs.fonts
glyphsets = {}
try:
for font in fonts:
if font.instances[0].name not in glyphsets:
glyphsets[font.instances[0].name] = set()
... | nilq/baby-python | python |
initial = """\
.|||.#..|##.#||..#.|..|..||||..#|##.##..#...|.....
.|#.|#..##...|#.........#.#..#..|#.|#|##..#.#|..#.
#....#|.#|.###||..#.|...|.|.#........#.|.#.#|..#..
|..|#....|#|...#.#..||.#..||......#.........|....|
.|.|..#|...#.|.###.|...||.|.|..|...|#|.#..|.|..|.|
#.....||.#..|..|..||#.||#..|.||..||##.......#........ | nilq/baby-python | python |
from group import GroupTestCases
from user import UserTestCases
from permission import PermissionTestCases
from core import *
| nilq/baby-python | python |
'''
Defines the training step.
'''
import sys
sys.path.append('tfutils')
import tensorflow as tf
from tfutils.base import get_optimizer, get_learning_rate
import numpy as np
import cv2
from curiosity.interaction import models
import h5py
import json
class RawDepthDiscreteActionUpdater:
'''
Provides the training s... | nilq/baby-python | python |
'''
Given an array of integers, there is a sliding window of size k which is moving from the left side of the array to the right, one element at a time. You can only interact with the k numbers in the window. Return an array consisting of the maximum value of each window of elements.
'''
def sliding_window_max(arr, k)... | nilq/baby-python | python |
# terrascript/provider/chanzuckerberg/snowflake.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:27:17 UTC)
import terrascript
class snowflake(terrascript.Provider):
"""Terraform provider for managing Snowflake accounts"""
__description__ = "Terraform provider for managing Snowflake account... | nilq/baby-python | python |
def move_tower(height, from_pole, middle_pole, to_pole):
if height >= 1:
move_tower(height-1, from_pole, to_pole, middle_pole)
print "move disk from {} to {}".format(from_pole, to_pole)
move_tower(height-1, middle_pole, from_pole, to_pole)
| nilq/baby-python | python |
from getratings.models.ratings import Ratings
class NA_Karthus_Mid_Aatrox(Ratings):
pass
class NA_Karthus_Mid_Ahri(Ratings):
pass
class NA_Karthus_Mid_Akali(Ratings):
pass
class NA_Karthus_Mid_Alistar(Ratings):
pass
class NA_Karthus_Mid_Amumu(Ratings):
pass
class NA_Karthus_Mid_Anivia(Rating... | nilq/baby-python | python |
# WARNING: you are on the master branch; please refer to examples on the branch corresponding to your `cortex version` (e.g. for version 0.24.*, run `git checkout -b 0.24` or switch to the `0.24` branch on GitHub)
import mlflow.sklearn
import numpy as np
class PythonPredictor:
def __init__(self, config, python_c... | nilq/baby-python | python |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""PyVoiceChanger."""
import sys
from datetime import datetime
from subprocess import call
from time import sleep
from PyQt5.QtCore import QProcess, Qt, QTimer
from PyQt5.QtGui import QColor, QCursor, QIcon
from PyQt5.QtWidgets import (QApplication, QDial, QGraphicsDropSh... | nilq/baby-python | python |
from setuptools import setup
setup(
name='ctab',
version='0.1',
author='Thomas Hunger',
author_email='tehunger@gmail.com',
packages=[
'ctab',
]
)
| nilq/baby-python | python |
""" Methods to setup the logging """
import os
import yaml
import platform
import logging
import coloredlogs
import logging.config
from funscript_editor.definitions import WINDOWS_LOG_CONFIG_FILE, LINUX_LOG_CONFIG_FILE
from funscript_editor.utils.config import SETTINGS
def create_log_directories(config: dict) -> No... | nilq/baby-python | python |
#####################################################
# Read active and reactive power from the atm90e32 then
# store within mongodb.
#
# copyright Margaret Johnson, 2020.
# Please credit when evolving your code with this code.
########################################################
from FHmonitor.error_handling imp... | nilq/baby-python | python |
import torch
import numpy as np
from torch import Tensor
from torch.utils.data import Dataset, DataLoader
from torchvision import io
from pathlib import Path
from typing import Tuple
class Wound(Dataset):
"""
num_classes: 18
"""
# explain the purpose of the model
# where is it, how big it is,
... | nilq/baby-python | python |
#!/usr/bin/python3
def best_score(a_dictionary):
if a_dictionary:
return max(a_dictionary, key=a_dictionary.get)
| nilq/baby-python | python |
print("before loop")
for count in range(10):
if count > 5:
continue
print(count)
print("after loop")
| nilq/baby-python | python |
"""Application management util tests"""
# pylint: disable=redefined-outer-name
from types import SimpleNamespace
import pytest
import factory
from django.core.exceptions import ValidationError
from django.core.files.uploadedfile import SimpleUploadedFile
from mitol.common.utils import now_in_utc
from applications.api... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Copyright (c) 2020. Huawei Technologies Co.,Ltd.ALL rights reserved.
This program is licensed under Mulan PSL v2.
You can use it according to the terms and conditions of the Mulan PSL v2.
http://license.coscl.org.cn/MulanPSL2
THIS PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHO... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# @Time : 2022/2/20
# @Author : Zhelong Huang
# @File : client2.py
# @Description: client2
_POS = 2
import os, sys
sys.path.append(os.path.abspath('.'))
from coach import LoadCoach
import argparse
arg = argparse.ArgumentParser()
arg.add_argument('-r', '--render', default=True... | nilq/baby-python | python |
# A non-empty zero-indexed array A consisting of N integers is given.
#
# A permutation is a sequence containing each element from 1 to N once, and
# only once.
#
# For example, array A such that:
# A = [4, 1, 3, 2]
# is a permutation, but array A such that:
# A = [4, 1, 3]
# is not a permutation, because value... | nilq/baby-python | python |
"""Flexmock public API."""
# pylint: disable=no-self-use,too-many-lines
import inspect
import re
import sys
import types
from types import BuiltinMethodType, TracebackType
from typing import Any, Callable, Dict, Iterator, List, NoReturn, Optional, Tuple, Type
from flexmock.exceptions import (
CallOrderError,
E... | nilq/baby-python | python |
import bs4
import re
from common import config
# Regular expresion definitions
is_well_former_link = re.compile(r'^https?://.+$')
is_root_path = re.compile(r'^/.+$')
def _build_link(host, link):
if is_well_former_link.match(link):
return link
elif is_root_path.match(link):
return '{}{}'.form... | nilq/baby-python | python |
'''
Created on Apr 4, 2016
@author: Noe
'''
class MyClass(object):
'''
classdocs
'''
def __init__(self, params):
'''
Constructor
'''
| nilq/baby-python | python |
#!/usr/bin/python
from __future__ import absolute_import, division, print_function, unicode_literals
import pi3d
import ConfigParser
from PIL import Image
import sys
#read config
Config = ConfigParser.ConfigParser()
Config.read("config.ini")
xloc = int(Config.get("client",'x_offset'))
yloc = int(Config.get("client"... | nilq/baby-python | python |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
def solve(s):
open_p = ('[', '{', '(')
close_p = (']', '}', ')')
pair = dict(zip(close_p, open_p)) # key: close_p
stack = list()
for c in s:
if c in open_p:
stack.append(c)
if c in close_p:
if len(stack... | nilq/baby-python | python |
import aiohttp
import os
import pytest
from tokki.travis import TravisClient
from tokki.enums import Status
TOKEN = os.environ["TRAVISCI_TOKEN"]
AGENT = "Tests for Tokki +(https://github.com/ChomusukeBot/Tokki)"
@pytest.mark.asyncio
async def test_no_login():
with pytest.raises(TypeError, match=r": 'token'"):
... | nilq/baby-python | python |
import argparse
parse = argparse.ArgumentParser(description="test")
parse.add_argument('count' , action='store' , type = int)
parse.add_argument('units',action='store')
parse.add_argument('priseperunit' , action= 'store')
print(parse.parse_args()) | nilq/baby-python | python |
#!/usr/bin/env python3
import numpy
import cv2
import math
from entities.image import Image
from entities.interfaces.scene_interface import SceneInterface
from entities.aligned.aligned_band import AlignedBand
from entities.aligned.aligned_image import AlignedImage
from entities.aligned.aligned_true_color import Aligne... | nilq/baby-python | python |
import os
import json
import scipy.io
import pandas
import itertools
import numpy as np
from PIL import Image
from collections import OrderedDict
info = OrderedDict(description = "Testset extracted from put-in-context paper (experiment H)")
licenses = OrderedDict()
catgs = ['airplane','apple','backpack','banana',... | nilq/baby-python | python |
# See https://michaelgoerz.net/notes/extending-sphinx-napoleon-docstring-sections.html
# # -- Fixing bug with google docs showing attributes-------------
from sphinx.ext.napoleon.docstring import GoogleDocstring
# first, we define new methods for any new sections and add them to the class
def parse_keys_section(self,... | nilq/baby-python | python |
import re
import random
import string
from django import template
from django.template import Context
from django.template.loader import get_template
from django.contrib.auth.models import Group
from django.core.exceptions import PermissionDenied
from crm.models import Person
from cedar_settings.models import General... | nilq/baby-python | python |
import os
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.http import HttpResponseRedirect, HttpResponse, HttpResponseForbidden, Http404
from django.core.urlresolvers import reverse
from django.conf import settings
from django.core.exceptions im... | nilq/baby-python | python |
'''
Do a parcel analysis of the sounding and plot the parcel temperature
'''
from __future__ import print_function, division
from SkewTplus.skewT import figure
from SkewTplus.sounding import sounding
from SkewTplus.thermodynamics import parcelAnalysis, liftParcel
#Load the sounding data
mySounding = sounding("./exa... | nilq/baby-python | python |
from cmath import exp, pi, sin
from re import I
import matplotlib.pyplot as mplt
def FFT(P):
n = len(P)
if n == 1:
return P
else:
w = exp((2.0 * pi * 1.0j) / n)
Pe = []
Po = []
for i in range(0, n, 2):
Pe.append(P[ i ])
for i in range(1, n, 2... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019-04-15 18:21
# @Author : erwin
import pandas as pd
import numpy as np
from common.util_function import *
'''
缺失值处理
1. 采用均值/出现次数设置missing值。对于一列数字,要获取平均值。
2. 对于一列非数字,例如字符,要找到出现频率最高的字符赋值给missing值
3. 删除缺失值
http://pandas.pydata.org/pandas-docs/stable/generate... | nilq/baby-python | python |
"""
The sys command to manage the cmd5 distribution
"""
import glob
import os
import shutil
from cloudmesh.common.util import path_expand
from cloudmesh.shell.command import PluginCommand
from cloudmesh.shell.command import command
from cloudmesh.sys.manage import Command, Git, Version
class SysCommand(PluginCommand... | nilq/baby-python | python |
import numpy as np
from pypadre.pod.app import PadreApp
from sklearn.datasets import load_iris
from pypadre.examples.base_example import example_app
# create example app
padre_app = example_app()
def create_experiment1(app: PadreApp, name="", project="", auto_main=True):
@app.dataset(name="iris",
... | nilq/baby-python | python |
import socket
import pickle
import struct
import argparse
def send_msg(sock, msg):
msg_pickle = pickle.dumps(msg)
sock.sendall(struct.pack(">I", len(msg_pickle)))
sock.sendall(msg_pickle)
print(msg[0], 'sent to', sock.getpeername())
def recv_msg(sock, expect_msg_type = None):
msg_len = struct.un... | nilq/baby-python | python |
"""
NetCDF Builder
This is currently a test script and will eventuall be made into a module
"""
#==============================================================================
__title__ = "netCDF maker"
__author__ = "Arden Burrell (Manon's original code modified)"
__version__ = "v1.0(02.03.2018)"
__email__ ... | nilq/baby-python | python |
lista = enumerate('zero um dois três quatro cinco seis sete oito nove'.split())
numero_string=dict(lista)
string_numero={valor:chave for chave,valor in numero_string.items()}
print (numero_string)
print(string_numero)
def para_numeral(n):
numeros=[]
for digito in str(n):
numeros.append(numero_... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 20 00:59:05 2020
@author: Leonardo Saccotelli
"""
import numpy as np
import AlgoritmiAlgebraLineare as al
#------------------- TEST MEDOTO DI ELIMINAZIONE DI GAUSS
#Dimensione della matrice
n = 5000
#Matrice dei coefficienti
matrix = np.random.random((n, n)).astype(f... | nilq/baby-python | python |
"""Lists out the inbuilt plugins in Example"""
from src.example_reporter import ExampleReporter
from src.example_tool import ExampleTool
def get_reporters() -> dict:
"""Return the reporters in plugin"""
return {
"example-reporter": ExampleReporter,
}
def get_tools() -> dict:
"""Return the to... | nilq/baby-python | python |
"""
stanCode Breakout Project
Adapted from Eric Roberts's Breakout by
Sonja Johnson-Yu, Kylie Jue, Nick Bowman,
and Jerry Liao.
YOUR DESCRIPTION HERE
Click mouse to start the game.
When no live is remained or all bricks are cleared, game is over.
"""
from campy.gui.events.timer import pause
from breakoutgraphics impo... | nilq/baby-python | python |
#!/usr/bin/env python
'''
jRAT Rat Config Decoder
'''
__description__ = 'jRAT Rat Config Extractor'
__author__ = 'Kevin Breen http://techanarchy.net http://malwareconfig.com'
__version__ = '0.3'
__date__ = '2015/04/03'
#Standard Imports Go Here
import os
import sys
from base64 import b64decode
import string
from zip... | nilq/baby-python | python |
import json
import uuid
from datetime import datetime
from sqlalchemy.dialects.postgresql import UUID
from app import db
# person_team = db.Table(
# "person_team",
# db.Column(
# "person_id",
# UUID,
# db.ForeignKey("person.id", ondelete="CASCADE"),
# primary_key=True,
# )... | nilq/baby-python | python |
#!/usr/bin/env python
#
# Code to build the catalogue cache
#
# Usage: python build_cache.py
#
from __future__ import print_function
from sys import stdout
__author__ = "Yu Feng and Martin White"
__version__ = "1.0"
__email__ = "yfeng1@berkeley.edu or mjwhite@lbl.gov"
from imaginglss import DECALS
import numpy
from... | nilq/baby-python | python |
#Summe der Zahlen von 1 bis 5
summe=0
for i in [1,2,3,4,5]:
summe=summe+i #Beginn eines Blocks
print("Summe von 1 bis ", i,":",summe) #Ende eines Blocks
print("Ende der Rechnung")
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Miscellaneous utilities and tools
"""
import errno
import functools
import keyword
import logging
import os
import re
import shutil
import sys
import traceback
from contextlib import contextmanager
from pathlib import Path
from pkg_resources import parse_version
from . import __version__
... | nilq/baby-python | python |
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from odahuflow.sdk.models.base_model_ import Model
from odahuflow.sdk.models import util
class ExternalUrl(Model):
"""NOTE: This class is auto generated by the sw... | nilq/baby-python | python |
from bs4 import BeautifulSoup, SoupStrainer
import re
import requests
import json
strained = SoupStrainer('a', href=re.compile('saskatchewan.kijiji.ca/f.*QQ'))
soup = BeautifulSoup(requests.get('http://saskatchewan.kijiji.ca').text)
category_dict = {}
for a in soup.findAll(strained):
category_id = None
category =... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import datetime
from django.conf import settings
from django.db import connection, DatabaseError, transaction
import djang... | nilq/baby-python | python |
# src/chara/character.py
import enum
class C_type(enum.Enum):
PLAYER = 0
NPC = 1
OPPONENT = 2
BOSS = 3
class Character():
def __init__(self,name,c_type):
types = Character.__ty()
self.name = name
self.c_type = types[c_type]
# temporary function
def identity(self):... | nilq/baby-python | python |
from peewee import IntegerField, Model, CompositeKey, ForeignKeyField
from data.db import database
from data.user import User
class Buddies(Model):
buddy1 = ForeignKeyField(User, to_field="id")
buddy2 = ForeignKeyField(User, to_field="id")
class Meta:
database = database
primary_key = Com... | nilq/baby-python | python |
# Copyright 2019 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | nilq/baby-python | python |
""" Financial Modeling Prep Model """
__docformat__ = "numpy"
import pandas as pd
import FundamentalAnalysis as fa
from gamestonk_terminal import config_terminal as cfg
def get_rating(ticker: str) -> pd.DataFrame:
"""Get ratings for a given ticker. [Source: Financial Modeling Prep]
Parameters
----------... | nilq/baby-python | python |
#!/usr/bin/env python
"""tests for :mod:`online_pomdp_planning.mcts`"""
from functools import partial
from math import log, sqrt
from typing import Dict
import pytest
from online_pomdp_planning.mcts import (
ActionNode,
DeterministicNode,
MuzeroInferenceOutput,
ObservationNode,
backprop_running_q... | nilq/baby-python | python |
from itertools import product
import torch
import dgl
from dgl.data import citation_graph
from dgl.contrib.data import load_data
from dgl import DGLGraph
from runtime.dgl.gcn import GCN, GCNSPMV
from runtime.dgl.gat import GAT, GATSPMV
from runtime.dgl.rgcn import RGCN, RGCNSPMV
from runtime.dgl.train import train_ru... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
import threading
from datetime import date, datetime, timedelta
from psycopg2 import sql
from odoo import api, fields, models, tools, SUPERUSER_ID
from odoo.osv import expression
from odoo.tools.translate... | nilq/baby-python | python |
import sys
from schemas.input_conf import personal_info
from settings.base_conf import KOBO_PERSONAL_INFO_CSV_MAP
'''
json_structure - the json attributes that are to be extracted from the source json
mapping_format - see oldcuris_elastic_map for an example. import it here
input_format - default input of source json... | nilq/baby-python | python |
""" Test Metadata Tool """
from __future__ import unicode_literals, absolute_import
from tmt.base import Tree
__all__ = ["Tree"]
| nilq/baby-python | python |
import os
import matplotlib.pyplot as plt
from typing import List, Union, Tuple, Dict
import torch
import pickle
current_dir = os.path.dirname(os.path.realpath(__file__))
CATEGORY = List[Union[int, float]]
RUN_STATS = Dict[str, Union[int, float]]
def plot_score_and_acc_over_docs(
dir_name: str,
stats: List[Tu... | nilq/baby-python | python |
from molsysmt._private_tools.exceptions import *
from molsysmt.forms.common_gets import *
import numpy as np
from molsysmt.molecular_system import molecular_system_components
from molsysmt._private_tools.files_and_directories import tmp_filename
form_name='file:dcd'
is_form = {
'file:dcd':form_name
}
inf... | nilq/baby-python | python |
import mongolib
class a():
def aa(self):
a=mongolib.mongodb()
a.log_collect(msg='1gaejiusfuadaifuagusuifhiau afdu gaudf uisg uagsi gaug asyaigasydg aug iug ')
a.log_collect(msg='2')
a.log_input()
a.log_output()
aaaa=a()
aaaa.aa() | nilq/baby-python | python |
import inspect
import operator
import re
from datetime import datetime
from decimal import Decimal
from enum import Enum
from functools import reduce
import pymongo
from bson import ObjectId
from pymongo.collection import Collection, ReturnDocument
from pymongo.errors import CollectionInvalid
from appkernel.configura... | nilq/baby-python | python |
# Generated by Django 3.0.11 on 2021-01-22 10:13
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('cars', '0001_initial'),
('users', '0002_auto_20210122_0713'),
... | nilq/baby-python | python |
import math
N = int(input())
sqN = math.floor(math.sqrt(N))
yaku1 = 1
yaku2 = 1
for i in range(sqN, 0, -1):
if N % i == 0:
yaku1 = i
yaku2 = N // i
break
print(yaku1+yaku2-2)
| nilq/baby-python | python |
import asyncio
import pytest
import unittest
from unittest.mock import MagicMock, patch
from app import Application
@pytest.mark.asyncio
async def test_func1():
app = Application()
func2_stub = MagicMock(return_value='future result!')
func2_coro = asyncio.coroutine(func2_stub)
async with patch.object... | nilq/baby-python | python |
#先引入后面分析、可视化等可能用到的库
import tushare as ts
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sqlalchemy import create_engine
import psycopg2
#正常显示画图时出现的中文和负号
from pylab import mpl
mpl.rcParams['font.sans-serif']=['SimHei']
mpl.rcParams['axes.unicode_minus']=False
#设置token
token = '7dc39867da... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.