content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
import discord
from discord.ext import commands
import traceback
import datetime
import asyncio
import random
from datetime import datetime
from storage import *
pat_gifs = [
"https://cdn.discordapp.com/attachments/670153232039018516/674299983117156362/1edd1db645f55aa7f2923838b5afabfc863fc109_hq.gif",
"https:/... | nilq/baby-python | python |
import Tkinter as tk
import warnings
VAR_TYPES = {
int: tk.IntVar,
float: tk.DoubleVar,
str: tk.StringVar
}
class ParameterController(tk.Frame):
def __init__(self,parent, key, value):
tk.Frame.__init__(self, parent)
self.value_type = type(value)
self._var = VAR_TYPES[self.v... | nilq/baby-python | python |
import factory
import factory.fuzzy
from user.models import User
from company.tests.factories import CompanyFactory
class UserFactory(factory.django.DjangoModelFactory):
sso_id = factory.Iterator(range(99999999))
name = factory.fuzzy.FuzzyText(length=12)
company_email = factory.LazyAttribute(
lam... | nilq/baby-python | python |
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
# Using dfs to record all possible
def dfs(nums, path=None, res=[]):
if path is None:
path = []
if len(path) == k:
res += [path]
return res
for id... | nilq/baby-python | python |
from typing import Optional
import requests
from libgravatar import Gravatar
from bs4 import BeautifulSoup
def get_gravatar_image(email) -> Optional[str]:
"""Only will return a url if the user exists and is correct on gravatar, otherwise None"""
g = Gravatar(email)
profile_url = g.get_profile()
res =... | nilq/baby-python | python |
patterns = ['you cannot perform this operation as root']
def match(command):
if command.script_parts and command.script_parts[0] != 'sudo':
return False
for pattern in patterns:
if pattern in command.output.lower():
return True
return False
def get_new_command(command):
... | nilq/baby-python | python |
import json
import os
from py2neo import Graph
class GraphInstanceFactory:
def __init__(self, config_file_path):
"""
init the graph factory by a config path.
the config json file format example:
[
{
"server_name": "LocalHostServer",
"se... | nilq/baby-python | python |
from datetime import datetime
class mentions_self:
nom = 'я'; gen = ['меня', 'себя']; dat = ['мне', 'себе']
acc = ['меня', 'себя']; ins = ['мной', 'собой']; abl = ['мне','себе']
class mentions_unknown:
all = 'всех'
him = 'его'; her = 'её'; it = 'это'
they = 'их'; them = 'их'; us = 'нас'
nam... | nilq/baby-python | python |
from flask import (
Blueprint,
render_template,
)
from sqlalchemy import desc, func, or_, text
from .. import db
from ..models import (
Video,
Vote,
GamePeriod,
Reward,
)
game = Blueprint(
'game',
__name__,
template_folder='templates'
)
@game.route('/')
def index():
q = """
... | nilq/baby-python | python |
import torch
import torch.nn.utils.rnn as rnn
import numpy as np
import pandas
from torch.utils.data import Dataset
from sklearn.preprocessing import LabelEncoder
from parsers.spacy_wrapper import spacy_whitespace_parser as spacy_ws
from common.symbols import SPACY_POS_TAGS
import json
import transformers
from transfo... | nilq/baby-python | python |
# coding=utf-8
from selenium.webdriver.common.by import By
from view_models import certification_services, sidebar, ss_system_parameters
import re
import time
def test_ca_cs_details_view_cert(case, profile_class=None):
'''
:param case: MainController object
:param profile_class: string The fully qualifie... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Author: Niccolò Bonacchi
# @Date: Thursday, January 31st 2019, 1:15:46 pm
from pathlib import Path
import argparse
import ibllib.io.params as params
import oneibl.params
from alf.one_iblrig import create
from poop_count import main as poop
IBLRIG_DATA = Path().cwd().pare... | nilq/baby-python | python |
"""
Flask-Limiter extension for rate limiting
"""
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
from .errors import ConfigurationError, RateLimitExceeded
from .extension import Limiter, HEADERS
| nilq/baby-python | python |
from foldrm import Classifier
import numpy as np
def acute():
attrs = ['a1', 'a2', 'a3', 'a4', 'a5', 'a6']
nums = ['a1']
model = Classifier(attrs=attrs, numeric=nums, label='label')
data = model.load_data('data/acute/acute.csv')
print('\n% acute dataset', np.shape(data))
return model, data
de... | nilq/baby-python | python |
import tensorflow as tf
# 本节主要讲 placeholder
input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
# 原教程中为 mul, 我使用的版本为 multiply
output = tf.multiply(input1, input2)
with tf.Session() as sess:
print(sess.run(output, feed_dict={input1: [7.], input2: [2.]}))
| nilq/baby-python | python |
'''Statistical tests for NDVars
Common Attributes
-----------------
The following attributes are always present. For ANOVA, they are lists with the
corresponding items for different effects.
t/f/... : NDVar
Map of the statistical parameter.
p_uncorrected : NDVar
Map of uncorrected p values.
p : NDVar | None
... | nilq/baby-python | python |
class SelectionSort:
@staticmethod
def sort(a):
for i, v in enumerate(a):
minimum = i
j = i+1
while j < len(a):
if a[j] < a[minimum]:
minimum = j
j += 1
tmp = a[i]
a[i] = a[minimum]
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# @Time : 2019/1/18 15:40
| nilq/baby-python | python |
# 정수를 저장하는 큐를 구현한 다음, 입력으로 주어지는 명령을 처리하는 프로그램을 작성하시오.
# 명령은 총 여섯 가지이다.
# push X: 정수 X를 큐에 넣는 연산이다.
# pop: 큐에서 가장 앞에 있는 정수를 빼고, 그 수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다.
# size: 큐에 들어있는 정수의 개수를 출력한다.
# empty: 큐가 비어있으면 1, 아니면 0을 출력한다.
# front: 큐의 가장 앞에 있는 정수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다.
# back: 큐의 가장 뒤에 있는... | nilq/baby-python | python |
from clickhouse_orm import migrations
from ..test_migrations import *
operations = [migrations.AlterIndexes(ModelWithIndex2, reindex=True)]
| nilq/baby-python | python |
from functools import partial
import pytest
from stp_core.loop.eventually import eventuallyAll
from plenum.test import waits
from plenum.test.helper import checkReqNack
whitelist = ['discarding message']
class TestVerifier:
@staticmethod
def verify(operation):
assert operation['amount'] <= 100, 'a... | nilq/baby-python | python |
import torch
from torch import autograd
def steptaker(data, critic, step, num_step = 1):
"""Applies gradient descent (GD) to data using critic
Inputs
- data; data to apply GD to
- critic; critic to compute gradients of
- step; how large of a step to take
- num_step; how finely to discretize fl... | nilq/baby-python | python |
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
import pickle
import pprint
import datefinder
# What the program can access within Calendar
# See more at https://developers.google.com/calendar/auth
scopes = ["https://www.googleapis.com/auth/calendar"]
flow = Installe... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""binomial_mix.
Chen Qiao: cqiao@connect.hku.hk
"""
import sys
import warnings
import numpy as np
from scipy.special import gammaln, logsumexp
from .model_base import ModelBase
class MixtureBinomial(ModelBase):
"""Mixture of Binomial Models
This class implements... | nilq/baby-python | python |
from keras.layers import Conv2D, SeparableConv2D, MaxPooling2D, Flatten, Dense
from keras.layers import Dropout, Input, BatchNormalization, Activation, add, GlobalAveragePooling2D
from keras.losses import categorical_crossentropy
from keras.optimizers import Adam
from keras.utils import plot_model
from keras import cal... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import json
from ..models import PermissionModel as Model
from ..models import GroupPermissionModel
from .base_dao import BaseDao
class PermissionDao(BaseDao):
def add_permission(self, permission):
# 如果存在相同app codename,... | nilq/baby-python | python |
from itertools import permutations
with open("input.txt") as f:
data = [int(i) for i in f.read().split("\n")]
preamble = 25
for d in range(preamble + 1, len(data)):
numbers = data[d - (preamble + 1):d]
target = data[d]
sol = [nums for nums in permutations(numbers, 2) if sum(nums) == target]
... | nilq/baby-python | python |
import collections
import pathlib
import time
from multiprocessing import Process
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
from omegaconf import OmegaConf
from gdsfactory import components
from gdsfactory.config import CONFIG, logger
from gdsfactory.doe import get_settings_list
from gdsfac... | nilq/baby-python | python |
#!/usr/bin/env python
import os
import sys
import logging
import requests
import time
from extensions import valid_tagging_extensions
from readSettings import ReadSettings
from autoprocess import plex
from tvdb_mp4 import Tvdb_mp4
from mkvtomp4 import MkvtoMp4
from post_processor import PostProcessor
from logging.confi... | nilq/baby-python | python |
def do_print():
print "hello world"
def add(a, b):
return a + b
def names_of_three_people(a, b, c):
return a['name'] + " and " + b['name'] + " and " + c['name']
def divide(a, b):
return a / b
def float_divide(a, b):
return float(a) / float(b)
def func_return_struct(name, age, hobby1, hobb... | nilq/baby-python | python |
# ---------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# ---------------------------------------------------------
from marshmallow import fields, post_load, validate
from typing import Optional
from ..schema import PatchedSchemaMeta
from ..fields... | nilq/baby-python | python |
from typing import Union, List, Dict
from py_expression_eval import Parser # type: ignore
import math
from . import error
def add(num1: Union[int, float], num2: Union[int, float], *args) -> Union[int, float]:
"""Adds given numbers"""
sum: Union[int, float] = num1 + num2
for num in args:
... | nilq/baby-python | python |
#
# This file is part of DroneBridge: https://github.com/seeul8er/DroneBridge
#
# Copyright 2017 Wolfgang Christl
#
# 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.apac... | nilq/baby-python | python |
import errno
import gc
# from collections import namedtuple
import math
import os
import os.path
import time
from functools import lru_cache
from pathlib import Path
import numpy as np
import pandas as pd
import artistools as at
@lru_cache(maxsize=8)
def get_modeldata(inputpath=Path(), dimensions=None, get_abundanc... | nilq/baby-python | python |
#Codeacademy's Madlibs
from datetime import datetime
now = datetime.now()
print(now)
story = "%s wrote this story on a %s line train to test Python strings. Python is better than %s but worse than %s -------> written by %s on %02d/%02d/%02d at %02d:%02d"
story_name = raw_input("Enter a name: ")
story_line = raw_inpu... | nilq/baby-python | python |
import logging
import os
import json
from pprint import pformat
import pysftp
from me4storage.common.exceptions import ApiError
logger = logging.getLogger(__name__)
def save_logs(host, port, username, password, output_file):
cnopts = pysftp.CnOpts(knownhosts=os.path.expanduser(os.path.join('~','.ssh','known_hos... | nilq/baby-python | python |
import builtins
import traceback
from os.path import relpath
def dprint(*args, **kwargs):
"""Pre-pends the filename and linenumber to the print statement"""
stack = traceback.extract_stack()[:-1]
i = -1
last = stack[i]
if last.name in ('clearln', 'finish'):
return builtins.__dict__['oldp... | nilq/baby-python | python |
import config_cosmos
import azure.cosmos.cosmos_client as cosmos_client
import json
from dateutil import parser
def post_speech(speech_details, category):
speech_details = speech_details.copy()
collection_link = "dbs/speakeasy/colls/" + category
speech_details["id"] = speech_details["user_name"] + "_" + sp... | nilq/baby-python | python |
#!/usr/bin/env python
# Outputs the relative error in a particular stat for deg1 and deg2 FEM.
# Output columns:
# mesh_num medianEdgeLength deg1Error deg2Error
import sys, os, re, numpy as np
from numpy.linalg import norm
resultDir, stat = sys.argv[1:]
# Input data columns
meshInfo = ["mesh_num", "corner_angle", "me... | nilq/baby-python | python |
"""
Here we implement some simple policies that
one can use directly in simple tasks.
More complicated policies can also be created
by inheriting from the Policy class
"""
import logging
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import Categorical, Normal, Bernoulli
c... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('person', '__first__'),
]
operations = [
migrations.CreateModel(
name='Attendee',
fields=[
... | nilq/baby-python | python |
class GPSlocation:
"""used to translate the location system"""
_prop_ = 'GPSlocation'
import math
pi = 3.1415926535897932384626
a = 6378245.0
ee = 0.00669342162296594323
def gcj02_to_wgs84(self, lng, lat):
"""GCJ02 system to WGS1984 system"""
dlat = self._transformlat(lng - 1... | nilq/baby-python | python |
# -*- coding: utf-8 -
import re
import copy
import urllib
import urllib3
import string
import dateutil.parser
from iso8601 import parse_date
from robot.libraries.BuiltIn import BuiltIn
from datetime import datetime, timedelta
import pytz
TZ = pytz.timezone('Europe/Kiev')
def get_library():
return BuiltIn().get_l... | nilq/baby-python | python |
import sys
sys.path.append("C:\Program Files\Vicon\Nexus2.1\SDK\Python")
import ViconNexus
import numpy as np
import smooth
vicon = ViconNexus.ViconNexus()
subject = vicon.GetSubjectNames()[0]
print 'Gap filling for subject ', subject
markers = vicon.GetMarkerNames(subject)
frames = vicon.GetFram... | nilq/baby-python | python |
from jinja2 import DictLoader, Environment
import argparse
import json
import importlib
import random
import string
HEADER = """
#pragma once
#include <rapidjson/rapidjson.h>
#include <rapidjson/writer.h>
#include <rapidjson/reader.h>
#include <iostream>
#include <string>
#include <vector>
#include <map>
struct... | nilq/baby-python | python |
def summary(p,c=10,x=5):
print('-' * 30)
print(f'Value Summary'.center(30))
print('-' * 30)
print(f'{"analyzed price:"} \t{coins(p)}')
print(f"{'Half-price: '} \t{half(p, True)}")
print(f'{"double the price: "}\t{double(p, True)}')
print(f'{c}% {"increase: ":} \t{increase(p, c, True)... | nilq/baby-python | python |
from ._sha512 import sha384
| nilq/baby-python | python |
from app import app, api
from flask import request
from flask_restful import Resource
import json
import pprint
import os
import subprocess
import traceback
import logging
class WelcomeController(Resource):
def get(self):
return {'welcome': "welcome, stranger!"}
api.add_resource(WelcomeController, '/') | nilq/baby-python | python |
import os
from dotenv import dotenv_values
config = {
**dotenv_values(os.path.join(os.getcwd(), ".env")),
**os.environ
}
VERSION = "0.0.0-alfa"
APP_HOST = config['APP_HOST']
APP_PORT = int(config['APP_PORT'])
APP_DEBUG = bool(config['APP_DEBUG'])
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
""" Views for the stats application. """
# standard library
# django
# models
from .models import Stat
# views
from base.views import BaseCreateView
from base.views import BaseDeleteView
from base.views import BaseDetailView
from base.views import BaseListView
from base.views import BaseUpdat... | nilq/baby-python | python |
"""Session class and utility functions used in conjunction with the session."""
from .session import Session
from .session_manager import SessionManager
__all__ = ["Session", "SessionManager"]
| nilq/baby-python | python |
''' 046 Faça um programa que mostre na tela uma contagem regressiva para o estouro de fogos de artifício, indo de 10 até 0
, com um pausa de 1 seg entre eles'''
from time import sleep
for c in range(10, -1, -1):
print(c)
sleep(1)
print('Fogos !!!!!') | nilq/baby-python | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: Shun Arahata
"""
Imitation learning environment
"""
import pathlib
# import cupy as xp
import sys
import numpy as xp
current_dir = pathlib.Path(__file__).resolve().parent
sys.path.append(str(current_dir) + '/../mpc')
sys.path.append(str(current_dir) + '/../')
from ... | nilq/baby-python | python |
# -*- Python -*-
# Copyright 2021 The Verible Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | nilq/baby-python | python |
# https://github.com/ArtemNikolaev/gb-hw/issues/23
def run(array):
return [
array[i]
for i in range(1, len(array))
if array[i] > array[i-1]
]
test_input = [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55]
print(run(test_input))
| nilq/baby-python | python |
import glob
from hdf5_getters import *
import os
import numpy as np
from collections import Counter
from music_utils import *
tags_list = []
data_path = "/mnt/snap/data/"
count = 0
for root, dirs, files in os.walk(data_path):
files = glob.glob(os.path.join(root, '*h5'))
#if count > 1000: break
for f in fi... | nilq/baby-python | python |
#!/usr/bin/env python3
import time
from data_output import DataOutput
from html_downloader import HtmlDownloader
from html_parser import HtmlParser
__author__ = 'Aollio Hou'
__email__ = 'aollio@outlook.com'
class Spider:
def __init__(self):
self.downloader = HtmlDownloader()
self.parser = HtmlPa... | nilq/baby-python | python |
from django import forms
from .models import Project
class ProjectForm(forms.ModelForm):
class Meta:
model = Project
fields = ["title", "describe", "technology"]
| nilq/baby-python | python |
#!/usr/bin/env python
# encoding: utf-8
"""Terminal UI for histdata_downloader project."""
import os
import sys
import logging
import subprocess
from datetime import date
import time
import npyscreen
from histdata_downloader.logger import log_setup
from histdata_downloader.histdata_downloader import load_available_p... | nilq/baby-python | python |
# Copyright (c) The PyAMF Project.
# See LICENSE.txt for details.
"""
Jython example AMF server and client with Swing interface.
@see: U{Jython<http://pyamf.org/wiki/JythonExample>} wiki page.
@since: 0.5
"""
import logging
from wsgiref.simple_server import WSGIServer, WSGIRequestHandler
from pyamf.remoting.gatewa... | nilq/baby-python | python |
from autodisc.systems.lenia.classifierstatistics import LeniaClassifierStatistics
from autodisc.systems.lenia.isleniaanimalclassifier import IsLeniaAnimalClassifier
from autodisc.systems.lenia.lenia import *
| nilq/baby-python | python |
# MIT License
#
# Copyright (c) 2017 Anders Steen Christensen
#
# 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, mo... | nilq/baby-python | python |
import dash, os, itertools, flask
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
from pandas_datareader import data as web
from datetime import datetime as dt
import plotly.graph_objs as go
import pandas as pd
from random import randint
import p... | nilq/baby-python | python |
import tanjun
import typing
from hikari import Embed
from modules import package_fetcher
component = tanjun.Component()
@component.with_command
@tanjun.with_argument("repo_n", default="main")
@tanjun.with_argument("arch_n", default="aarch64")
@tanjun.with_argument("pkg_n", default=None)
@tanjun.with_parser
@tanjun.a... | nilq/baby-python | python |
# Copyright 2020 The FastEstimator Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | nilq/baby-python | python |
import data
from base import nbprint
from tokenizer.main import run_tokenizer
def check_requirements(info):
# Check if tokens file exists
if not data.tokenized_document_exists(info):
# Run Tokenizer
nbprint('Tokens missing.')
run_tokenizer(info)
# Check if it was successfull
... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###########################################################
# WARNING: Generated code! #
# ************************** #
# Manual changes may get lost if file is generated again. #
# Only code inside the [MANUAL] ta... | nilq/baby-python | python |
import numpy as np
a = input("enter the matrix with ; after each row : ")
m =np.matrix(a)
b = input("enter the matrix 2 with row matching with matrix 1 : ")
n =np.matrix(b)
print(m)
print(n)
m3 = np.dot(m,n)
print(m3) | nilq/baby-python | python |
#//////////////#####///////////////
#
# ANU u6325688 Yangyang Xu
# Supervisor: Dr.Penny Kyburz
# SPP used in this scrip is adopted some methods from :
# https://github.com/yueruchen/sppnet-pytorch/blob/master/cnn_with_spp.py
#//////////////#####///////////////
"""
Policy Generator
"""
import torch.nn as nn
from GAIL.... | nilq/baby-python | python |
#!/usr/bin/env python3
from __future__ import print_function
import sys
import os
import time
sys.path.append('..')
import childmgt.ChildMgt
def create_children(num_children=5):
for child_num in range(0, num_children):
child_pid = os.fork()
if child_pid == 0:
time.sleep(3)
s... | nilq/baby-python | python |
#!/usr/bin/env python
import rospy
from week2.srv import roboCmd, roboCmdResponse
import math as np
class Unicycle:
def __init__(self, x, y, theta, dt=0.05):
self.x = x
self.y = y
self.theta = theta
self.dt = dt
self.x_points = [self.x]
self.y_points = [self.y]
... | nilq/baby-python | python |
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
"""
Get Jc, RA, etc from measured parameter DB
BB, 2015
"""
import sqlite3
import numpy as np
import matplotlib.pyplot as plt
# display units
unit_i = 1e-6 # uA
unit_v = 1e-6 # uV
unit_r = 1 # Ohm
unit_i1 = 1e-3 # mA; control I
unit_v1 = 1e-3 # mV; cont... | nilq/baby-python | python |
#
# PySNMP MIB module ZHONE-COM-IP-DHCP-SERVER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZHONE-COM-IP-DHCP-SERVER-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:40:42 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python vers... | nilq/baby-python | python |
"""Implementation classes that are used as application configuration containers
parsed from files.
"""
__author__ = 'Paul Landes'
from typing import Dict, Set
import logging
import re
import collections
from zensols.persist import persisted
from . import Configurable, ConfigurableError
logger = logging.getLogger(__n... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import cv2
from test_utils.label_to_str_voc import convert_label_to_str
def render_boxs_info_for_display(image, net_out, select_index, net_score, image_size, label_out = None):
v... | nilq/baby-python | python |
import unittest
import numpy as np
from sca.analysis import nicv
class TestNicvUnit(unittest.TestCase):
def test_calculate_mean_x_given_y_matrix(self):
""" Tests whether the calculations of means work properly"""
traces = np.array([[1, 2, 3], [4, 5, 6], [7, 0.4, 9], [2, 3, 12]])
plain = ... | nilq/baby-python | python |
# coding: utf-8
# In[ ]:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from sklearn import tree
get_ipython().run_line_magic('matplotlib', 'inline')
# In[ ]:
def maybe_load_loan_data(threshold=1, path='../input/loan.csv', force='n'):
def load_data():
da... | nilq/baby-python | python |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as torch_models
class PerceptualLoss(nn.Module):
def __init__(self, rank):
super(PerceptualLoss, self).__init__()
self.rank = rank
self.vgg19 = torch_models.vgg19(pretrained=True)
self.vgg... | nilq/baby-python | python |
"""
Generates a powershell script to install Windows agent - dcos_install.ps1
"""
import os
import os.path
import gen.build_deploy.util as util
import gen.template
import gen.util
import pkgpanda
import pkgpanda.util
def generate(gen_out, output_dir):
print("Generating Powershell configuration files for DC/OS"... | nilq/baby-python | python |
#!/usr/bin/python3
#Self Written Module to Decrypt Files
#=========================================================
#This Module is Written to Reverse_Attack of Ransomeware
#=========================================================
# Reverse_Attack
# |____*****TAKES 1 ARGUMENTS, i.e. KEY *****
# |____Initia... | nilq/baby-python | python |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# ******************************************************
# @author: Haifeng CHEN - optical.dlz@gmail.com
# @date (created): 2019-12-12 09:07
# @file: memory_monitor.py
# @brief: A tool to monitor memory usage of given process
# @internal:
... | nilq/baby-python | python |
##序列解包
dict={"name":"jim","age":"1","sex":"male"}
key,value=dict.popitem();
print(key,value)
#使用*号收集多余的值
a,b,*rest=[1,2,3,4];
print(a,b,rest)
##链式赋值 x=y=somfunction()
##增强赋值 x+=1
###代码块
| nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import pydoc
import subprocess
import sys
import signal
from pkg_resources import get_distribution
from termcolor import colored
from projects import config
from projects import gui
from projects import paths
from projects import projectfile
__version__ = get_... | nilq/baby-python | python |
"""Frigate API client."""
from __future__ import annotations
import asyncio
import logging
import socket
from typing import Any, Dict, List, cast
import aiohttp
import async_timeout
from yarl import URL
TIMEOUT = 10
_LOGGER: logging.Logger = logging.getLogger(__name__)
HEADERS = {"Content-type": "application/json;... | nilq/baby-python | python |
import jieba
import jieba.posseg as pseg #词性标注
import jieba.analyse as anls #关键词提取
class Fenci:
def __init__(self):
pass
#全模式和精确模式
def cut(self,word,cut_all=True):
return jieba.cut(word, cut_all=True)
#搜索引擎模式
# def cut_for_search(self,word):
# return jieba.cut_for_search(w... | nilq/baby-python | python |
'''
Unit tests for the environments.py module.
'''
import boto3
import json
import pytest
from mock import patch
from moto import ( mock_ec2,
mock_s3 )
from deployer.exceptions import ( EnvironmentExistsException,
InvalidCommandException)
import depl... | nilq/baby-python | python |
#!/usr/bin/env python3
# coding: utf-8
# print の出力時に日本語でもエラーが出ないようにするおまじない
import sys
import io
sys.stdout = io.TextIOWrapper( sys.stdout.buffer, encoding='utf-8' )
# CGIとして実行した際のフォーム情報を取り出すライブラリ
import cgi
form_data = cgi.FieldStorage( keep_blank_values = True )
# MySQLデータベース接続用ライブラリ
import MySQLdb
con = None
cur =... | nilq/baby-python | python |
#!/usr/bin/env python3
# coding: utf-8
import os
import sys
import re
import numpy as np
#==============================================================================#
def atomgroup_header(atomgroup):
"""
Return a string containing info about the AtomGroup
containing the total number of atoms,
th... | nilq/baby-python | python |
from pydantic import BaseModel
class ConsumerResponse(BaseModel):
topic: str
timestamp: str
product_name: str
product_id: int
success: bool
| nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `te_python` module."""
import pytest
import requests
from te_python import te_python
def test_te_python_initialization():
response = te_python.email_get_details('a53b7747d6bd3f59076d63469d92924e00f407ff472e5a539936453185ecca6c')
assert isinstance(re... | nilq/baby-python | python |
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=64)
surname = models.CharField(max_length=64)
class Meta:
app_label = 'person'
db_table = 'person'
ordering = ('surname', 'first_name') | nilq/baby-python | python |
from util.Tile import Tile
from util.Button import Button
from util.Maze import Maze
from algorithms.BFS import BFS
from algorithms.DFS import DFS
from algorithms.GFS import GFS
from algorithms.AStar import AStar
from math import floor
import pygame
class Grid:
def __init__(self, width, height, tile... | 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 |
from discord.ext import commands
from discord_bot.bot import Bot
class Admin(commands.Cog):
"""Admin commands that only bot owner can run"""
def __init__(self, bot: Bot):
self.bot = bot
@commands.command(name="shutdown", hidden=True)
@commands.is_owner()
async def shutdow(self, ctx: com... | nilq/baby-python | python |
# coding=utf-8
# --------------------------------------------------------------------------
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from ... | nilq/baby-python | python |
from ctypes import CDLL, sizeof, create_string_buffer
def test_hello_world(workspace):
workspace.src('greeting.c', r"""
#include <stdio.h>
void greet(char *somebody) {
printf("Hello, %s!\n", somebody);
}
""")
workspace.src('hello.py', r"""
import ctypes
lib = ctypes.CDLL('./g... | nilq/baby-python | python |
from gui import GUI
program = GUI()
program.run() | nilq/baby-python | python |
#!/usr/bin/env python3
#
# RoarCanvasCommandsEdit.py
# Copyright (c) 2018, 2019 Lucio Andrés Illanes Albornoz <lucio@lucioillanes.de>
#
from GuiFrame import GuiCommandDecorator, GuiCommandListDecorator, GuiSelectDecorator
import wx
class RoarCanvasCommandsEdit():
@GuiCommandDecorator("Hide assets window", "Hide a... | nilq/baby-python | python |
#!/usr/bin/python3
"""
Module installation file
"""
from setuptools import Extension
from setuptools import setup
extension = Extension(
name='fipv',
include_dirs=['include'],
sources=['fipv/fipv.c'],
extra_compile_args=['-O3'],
)
setup(ext_modules=[extension])
| nilq/baby-python | python |
import os
import time
import hashlib
import gzip
import shutil
from subprocess import run
from itertools import chain
CACHE_DIRECTORY = "downloads_cache"
def decompress_gzip_file(filepath):
decompressed = filepath + ".decompressed"
if not os.path.exists(decompressed):
with gzip.open(filepath, 'rb') ... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.