content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
from MainWindow import Ui_MainWindow
from PyQt6 import QtWidgets
import sys
class CalcWindow(Ui_MainWindow, QtWidgets.QMainWindow):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setupUi(self)
self.equalButton.clicked.connect(self.calculation)
self.cBu... | nilq/baby-python | python |
from tornado.web import HTTPError
class APIError(HTTPError):
def __init__(
self,
status_code: int,
reason: str,
message: str = None,
details: dict = None,
):
log_message = ': '.join(map(str, filter(None, [message, details]))) or None
super().__init__(
... | nilq/baby-python | python |
#!/usr/bin/python
# Report generator
import api
import fn
import sys
import dumper
def main(argv):
config = {}
config["usagetext"] = ("repgen.py (-s SEARCHPREFIX|-a) [-c CONFIGFILE]\n"+
" This script generates a report for all servers if -a is used,\n"+
"or just the servers with SEARCH... | nilq/baby-python | python |
import os
import logging
import json
from codecs import open
from collections import Counter
import numpy as np
import spacy
from tqdm import tqdm
"""
The content of this file is mostly copied from https://github.com/HKUST-KnowComp/R-Net/blob/master/prepro.py
"""
nlp = spacy.blank("en")
def word_tokenize(sent):
... | nilq/baby-python | python |
'''
Clase principal, contiene la logica de ejecución del servidor y rutas para consumo de la API
'''
from entities.profile import Profile
from flask import Flask, jsonify, request
from flask_restful import Resource, Api
from flask_httpauth import HTTPBasicAuth
from datetime import datetime
import pandas as pd
import nu... | nilq/baby-python | python |
from glitchtip.permissions import ScopedPermission
class ReleasePermission(ScopedPermission):
scope_map = {
"GET": ["project:read", "project:write", "project:admin", "project:releases"],
"POST": ["project:write", "project:admin", "project:releases"],
"PUT": ["project:write", "project:admin... | nilq/baby-python | python |
# StandAlone Version
"""
Created on Thu Apr 2 19:28:15 2020
@author: Yao Tang
"""
import arcpy
import os
arcpy.env.overwriteOutput = True
arcpy.env.addOutputsToMap = True
## Specify workspace(Usually the folder of the .mxd file)
arcpy.env.workspace = "L:/Projects/3020/006-01/6-0 DRAWINGS AND FIGURES/6-... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="crudini",
version="0.9.3",
author="Pádraig Brady",
author_email="P@draigBrady.com",
description=("A utility for manipulating ini fi... | nilq/baby-python | python |
def abc209d():
from collections import deque
n, Q = map(int, input().split())
g = [list() for _ in range(n)]
for _ in range(n - 1):
a, b = map(int, input().split())
a, b = a - 1, b - 1
g[a].append(b)
g[b].append(a)
c = [-1] * n
q = deque([0])
c[0] = 0
whil... | nilq/baby-python | python |
from sim.agents.agents import *
from sim.agents.multiagents import *
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Copyright (c) 2016, French National Center for Scientific Research (CNRS)
# Distributed under the (new) BSD License. See LICENSE for more info.
from pyqtgraph.Qt import QtCore
import pyqtgraph as pg
from pyqtgraph.util.mutex import Mutex
import numpy as np
from ..core import (Node, register_... | nilq/baby-python | python |
"""
Copyright 2018 The Johns Hopkins University Applied Physics Laboratory.
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 applicabl... | nilq/baby-python | python |
"Thread safe RLock defined for lru cache."
# https://stackoverflow.com/questions/16567958/when-and-how-to-use-pythons-rlock
def RLock():
"""
Make the container thread safe if running in a threaded context.
"""
import threading
return threading.RLock()
| nilq/baby-python | python |
import logging
_LOGGER = logging.getLogger(__name__)
def decode(packet):
"""
https://github.com/telldus/telldus/blob/master/telldus-core/service/ProtocolEverflourish.cpp
"""
data = packet["data"]
house = data & 0xFFFC00
house >>= 10
unit = data & 0x300
unit >>= 8
unit += 1
... | nilq/baby-python | python |
# script to copy history from a FITS table to the FITS header
# FITS images only, works in current directory
# Argument:
# 1) Name of input FITS
# example:
# Python scriptHi2Header.py myImage.fits
import sys, Obit, Image, History, OSystem, OErr
# Init Obit
err=OErr.OErr()
ObitSys=OSystem.OSystem ("Hi2Header", 1, 100,... | nilq/baby-python | python |
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'superDigit' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. STRING n
# 2. INTEGER k
#
def superDigit(n, k):
if((len(n) == 1)and(k>1)):
n,k = str... | nilq/baby-python | python |
#
# Copyright 2015-2020 Andrey Galkin <andrey@futoin.org>
#
# 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 applicabl... | nilq/baby-python | python |
import stringcase
from importlib import import_module
from .metadata import Metadata
from .resource import Resource
from .package import Package
from . import helpers
from . import errors
class Pipeline(Metadata):
"""Pipeline representation
API | Usage
-------- | --------
Public | `from fricti... | nilq/baby-python | python |
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import re
from contextlib import contextmanager
from dataclasses import dataclass
from textwrap import dedent
from typing import Any
from pants.engine.internals.engine_testutil import (
... | nilq/baby-python | python |
# Copyright 2016 Pavle Jonoski
#
# 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 |
f = open('3_input.txt').read().splitlines()
def life_support_rating(o2, co2):
return o2 * co2
def filter(list, i=0, co2=False): # where `i` is the bit position
if len(list) == 1:
return list[0]
count = 0
for item in list:
count += int(item[i])
dom_num = 1 if count >= len(list) / 2 ... | nilq/baby-python | python |
import pytest
import numpy
from thinc.layers import Embed
from ...layers.uniqued import uniqued
from numpy.testing import assert_allclose
from hypothesis import given
from hypothesis.strategies import integers, lists, composite
ROWS = 10
# This test uses a newer hypothesis feature than the skanky flatmap-style
# I us... | nilq/baby-python | python |
from datasets.SOT.dataset import SingleObjectTrackingDatasetSequence_MemoryMapped
from ._common import _check_bounding_box_validity
class SOTSequenceSequentialSampler:
def __init__(self, sequence: SingleObjectTrackingDatasetSequence_MemoryMapped):
assert len(sequence) > 0
self.sequence = sequence
... | nilq/baby-python | python |
from django.db import models
from django.urls import reverse
class ImportantDate(models.Model):
date = models.DateField()
desc = models.CharField(max_length=100)
def __str__(self):
return "{} - {}".format(self.date, self.desc)
def get_absolute_url(self):
return reverse('formschapter:... | nilq/baby-python | python |
from django.contrib import admin
from purchasing.models import PurchasedOrder
class PurchasedOrderAdmin(admin.ModelAdmin):
readonly_fields = ['expiration_date']
admin.site.register(PurchasedOrder)
| nilq/baby-python | python |
from typing import Dict, Optional
from sqlalchemy import column, literal_column, select
from panoramic.cli.husky.core.sql_alchemy_util import (
quote_identifier,
safe_identifier,
sort_columns,
)
from panoramic.cli.husky.service.blending.blending_taxon_manager import (
BlendingTaxonManager,
)
from pano... | nilq/baby-python | python |
import theano
import theano.tensor as T
import treeano
from treeano.sandbox.nodes import bttf_mean
fX = theano.config.floatX
@treeano.register_node("bachelor_normalization")
class BachelorNormalizationNode(treeano.NodeImpl):
hyperparameter_names = ("bttf_alpha",
"alpha",
... | nilq/baby-python | python |
print("My name is John")
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Copyright 2013 Simonas Kazlauskas
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation
from os import path, makedirs
from hashlib import sha1
from gi.repository... | nilq/baby-python | python |
# Edit by Tianyu Ma
# coding: utf-8
"""
=====
Third step: merge csv files
=====
"""
| nilq/baby-python | python |
import json
import string
import csv
fname = './data/obama_speech.txt'
fhand = open(fname, 'r')
text = fhand.read()
lines = text.split('\n')
line_count = len(lines)
word_count = 0
for line in lines:
words = line.split()
for word in words:
if word == " ":
continue
word_count += 1
pr... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-10-23 21:38
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Words... | nilq/baby-python | python |
# for循环是一种遍历列表的有效方式, 但在for循环中不应修改列表, 否则将导致Python难以跟踪其中的元素.
# 要在遍历列表的同时对其进行修改, 可使用while循环.
# 在列表之间移动元素
unconfirmed_users = ['alice', 'brian', 'candace'] # 待验证用户列表
confirmed_users = [] # 已验证用户列表
# 遍历列表对用户进行验证
while unconfirmed_users: # 当列表不为空时返回True, 当列表为空时, 返回False
current_user = unconfirmed_users.pop() # 取... | nilq/baby-python | python |
from datetime import datetime
from lib import d,t
def main():
r = t.t()
r = (r+(' '+(d.d())))
print(f'{r} :)')
return(0x01)
if(__name__==('__main__')): main()
| nilq/baby-python | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Script to help in managing Usenet hierarchies. It generates control
# articles and handles PGP keys (generation and management).
#
# signcontrol.py -- v. 1.4.0 -- 2014/10/26
#
# Written and maintained by Julien ÉLIE.
#
# This script is distributed under the MIT License. P... | nilq/baby-python | python |
with open('p11_grid.txt', 'r') as file:
lines = file.readlines()
n = []
for line in lines:
a = line.split(' ')
b = []
for i in a:
b.append(int(i))
n.append(b)
N = 0
for i in range(20):
for j in range(20):
horizontal, vertical, diag1, diag2 = 0, 0,... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
#
# COMMON
#
page_action_basket = "Корзина"
page_action_enter = "Войти"
page_action_add = "Добавить"
page_action_cancel = "Отмена"
page_action_yes = "Да"
page_action_save = "Сохранить"
page_action_action = "Действие"
page_action_modify = "изменить"
page_action_remove = "удалить"
page_message_e... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*-coding: utf-8 -*-
"""
.. invisible:
_ _ _____ _ _____ _____
| | | | ___| | | ___/ ___|
| | | | |__ | | | |__ \ `--.
| | | | __|| | | __| `--. \
\ \_/ / |___| |___| |___/\__/ /
\___/\____/\_____|____/\____/
Created on October 14, 2014
█████████████... | nilq/baby-python | python |
from typing import List
# ------------------------------- solution begin -------------------------------
class Solution:
def canWinNim(self, n: int) -> bool:
return n % 4 == 0
# ------------------------------- solution end - --------------------------------
if __name__ == '__main__':
input = 4
print("In... | nilq/baby-python | python |
bat = int(input('bateria = '))
def batery (bat):
if bat == 0:
print('morri')
elif bat > 0 and bat < 21:
print('conecte o carreador')
elif bat > 20 and bat < 80:
print('carregando...')
elif bat > 79 and bat < 100:
print('estou de boa')
elif bat == 100:
print('p... | nilq/baby-python | python |
#coding:utf8
'''
Created on 2016年4月20日
@author: wb-zhaohaibo
'''
import MySQLdb
print MySQLdb
conn = MySQLdb.Connect(
host="127.0.0.1",
port=3306,
user="root",
passwd="admin",
db="testsql... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Script for updating pymoprhy2 dictionaries (Russian and Ukrainian).
Please note that it is resource-heavy: it requires > 3GB free RAM and about
1GB on HDD for temporary files.
Usage:
update.py (ru|uk) (download|compile|package|cleanup) ...
update.py (ru|uk) al... | nilq/baby-python | python |
import Selenium_module as zm
print("Zillow Downloader")
url = input("URL: ")
image_links, title = zm.get_links(url)
zm.get_images(image_links, title)
zm.cleanup_exit()
| nilq/baby-python | python |
from flask_wtf import FlaskForm
from datetime import datetime
from wtforms import BooleanField, DateTimeField, HiddenField, SelectField, StringField, SubmitField, ValidationError
from wtforms.ext.sqlalchemy.fields import QuerySelectField
from wtforms.validators import Required, Optional
from .. models import Element, E... | nilq/baby-python | python |
import numpy as np
import os
import cv2
import sys
import time
import dlib
import glob
import argparse
import voronoi as v
def checkDeepFake(regions):
return True
def initialize_predictor():
# Predictor
ap = argparse.ArgumentParser()
if len(sys.argv) > 1:
predictor_path ... | nilq/baby-python | python |
r""" FSS-1000 few-shot semantic segmentation dataset """
import os
import glob
from torch.utils.data import Dataset
import torch.nn.functional as F
import torch
import PIL.Image as Image
import numpy as np
class DatasetFSS(Dataset):
def __init__(self, datapath, fold, transform, split, shot, use_original_imgsize)... | nilq/baby-python | python |
# The Python print statement is often used to output variables.
# To combine both text and a variable, Python uses the '+' character:
x = "awesome"
print("Python is " + x)
# You can also use the '+' character to add a variable to another variable:
x = "Python is "
y = "awesome"
z = x + y
print(z)
# For numbers, the '... | nilq/baby-python | python |
from keras.applications.resnet50 import ResNet50 as RN50
from keras.preprocessing import image
from keras.models import Model
from keras.layers import Flatten
from keras.layers import Dense, GlobalAveragePooling2D
from keras import backend as K
from keras.utils import plot_model
from keras.preprocessing.image import Im... | nilq/baby-python | python |
import ctypes
# Implements the Array ADT using array capabilities of the ctypes module.
class Array :
# Creates an array with size elements.
def __init__( self, size ):
assert size > 0, "Array size must be > 0"
self._size = size
# Create the array structure using the ctypes module.
... | nilq/baby-python | python |
#!/usr/bin/env python3
# Copyright (c) 2021 PaddlePaddle 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
#
# U... | nilq/baby-python | python |
# Unit test set_out_sample_residuals ForecasterAutoreg
# ==============================================================================
import numpy as np
import pandas as pd
from skforecast.ForecasterAutoreg import ForecasterAutoreg
from sklearn.linear_model import LinearRegression
def test_predict_interval_output_w... | nilq/baby-python | python |
import os
import gzip
import cPickle
from config import config
for fold in range(5):
filename = os.path.join(config.data_dir, 'atis.fold' + str(fold) + '.pkl.gz')
with gzip.open(filename, 'rb') as f:
train_set, valid_set, test_set, dicts = cPickle.load(f)
labels2idx_, tables2idx_, words2idx_ =... | nilq/baby-python | python |
import unittest
from bsim.connection import *
class TestConnectionMethods(unittest.TestCase):
def test_data(self):
c = Connection(debug=False)
c.delay_start = [0, 0, 3, 0, 1, 0, 0, 0, 0, 2, 0, 0]
c.delay_num = [1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0]
c.rev_delay_start = [0, 0, 0, 1, ... | nilq/baby-python | python |
class History(object):
def __init__(self, name, userID):
self.name = name
self.userID = userID
self.history = []
def logMessage(self, lastMessage):
if len(self.history) > 10:
self.history.pop()
self.history.append(lastMessage)
def getLastMessages(self, n... | nilq/baby-python | python |
import logging
__title__ = 'django_nine.tests.base'
__author__ = 'Artur Barseghyan'
__copyright__ = '2015-2019 Artur Barseghyan'
__license__ = 'GPL-2.0-only OR LGPL-2.1-or-later'
__all__ = (
'LOG_INFO',
'log_info',
)
logger = logging.getLogger(__name__)
LOG_INFO = True
def log_info(func):
"""Logs some... | nilq/baby-python | python |
import os
import datetime
import MySQLdb
con = MySQLdb.connect(host='DBSERVER', user='DBUSER', passwd='DBPASSWD', db='DB')
cur = con.cursor()
cur.execute("SHOW TABLES")
data = "SET FOREIGN_KEY_CHECKS = 0; \n"
tables = []
for table in cur.fetchall():
tables.append(table[0])
for table in tables:
if table != "f... | nilq/baby-python | python |
from .data_parallel import CustomDetDataParallel
from .sync_batchnorm import convert_model
| nilq/baby-python | python |
import os
from setuptools import setup
setup(name='NNApp01',
version='0.1.0',
description='NN Programming Assignment ',
author='Dzmitry Buhryk',
author_email='dzmitry.buhryk@gmail.com',
license='MIT',
install_requires=['flask', 'werkzeug'],
tests_require=['requests', 'flask',... | nilq/baby-python | python |
from multiprocessing import Process
import envServer
from distutils.dir_util import copy_tree
from random import shuffle
import sys
sys.path.append("../pyutil")
sys.path.append("..")
import signal
import parseNNArgs
import traceback
import threading
import pickle
import shutil
import glob
import os
import random
im... | nilq/baby-python | python |
#!/usr/bin/env python3
#-*- encoding: UTF-8 -*-
def main():
try:
nota1 = float(input("1ª nota: "))
nota2 = float(input("2ª nota: "))
except:
print("Apenas valores numéricos devem ser informados!")
if(nota1 < 0 or nota1 > 10 or nota2 < 0 or nota2 > 10):
print("Notas inválidas... | nilq/baby-python | python |
from . import util
ut = util.Util()
reload(util)
class ViewerMarlin():
def open_file(self, path):
with open(path) as f:
l = f.readlines()
# print(type(l))
# print(len(l))
# print(l)
return l
def get_value_move(self, str_):
... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of tofbot, a friendly IRC bot.
# You may redistribute it under the Simplified BSD License.
# If we meet some day, and you think this stuff is worth it,
# you can buy us a beer in return.
#
# Copyright (c) 2011,2015 Etienne Millon <etienne.millon@gmail.... | nilq/baby-python | python |
# Copyright 2016 Peter Dymkar Brandt 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 ... | nilq/baby-python | python |
from numpy import absolute, isnan, where
from scipy.spatial.distance import correlation
def compute_correlation_distance(x, y):
correlation_distance = correlation(x, y)
if isnan(correlation_distance):
return 2
else:
return where(absolute(correlation_distance) < 1e-8, 0, correlation_di... | nilq/baby-python | python |
# This sample tests the case where a subclass of Dict uses
# a dictionary literal as an argument to the constructor call.
from collections import Counter, defaultdict
from typing import Callable, Generic, Mapping, Optional, TypeVar
c1 = Counter({0, 1})
reveal_type(c1, expected_text="Counter[int]")
for i in range(256... | nilq/baby-python | python |
# Sequência dos termos numéricos de uma função arbitrária.
# Printa a sequência dos termos da função X^2 até um termo escolhido.
n = int(input())
for i in range(0,n):
print(i*i)
i = i+1
# Printa a sequência dos termos da função X^3 até um termo escolhido
y = int(input())
for i in range (0,y... | nilq/baby-python | python |
from bisect import bisect
from contextlib import closing, contextmanager
from itertools import accumulate, chain, islice, zip_longest
from multiprocessing import Lock, RawValue, Process
from os import cpu_count
from re import sub
from sys import argv, stdout
output_file = open("bench_output-fasta_bg.txt", mode="wb", b... | nilq/baby-python | python |
# ______ _ _ _ _ _ _ _
# | ___ \ | | | | (_) (_) | | (_)
# | |_/ / __ ___ | |__ __ _| |__ _| |_ ___| |_ _ ___
# | __/ '__/ _ \| '_ \ / _` | '_ \| | | / __| __| |/ __|
# | | | | | (_) | |_) | (_| | |_) | | | \__ \ |_| | (__
# \_| |_| \___/|_.__/ \__,_|... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
drift - Logging setup code
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Set up logging based on config dict.
"""
from __future__ import absolute_import
import os
import logging
from logging.handlers import SysLogHandler
import logging.config
import json
import datetime
import s... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
'''
Created on 2017/09/14
@author: yuyang
'''
import os
import urllib
import uuid
from docx.shared import Pt
from docx.shared import RGBColor
from docx.shared import Inches
JPEG_EXTENSION = '.jpg'
PNG_EXTENSION = '.png'
GIF_EXTENSION = '.gif'
SPLIT_STRING = '///'
def add_author(document, a... | nilq/baby-python | python |
"""
Views for the app
"""
from __future__ import absolute_import
from __future__ import division
import os
import uuid
from auth import constants
from auth.forms import \
CategoryForm, \
CountryForm, \
CurrencyForm, \
GatewayForm, \
LoginVoucherForm, \
MyUserForm, \
NetworkForm, \
Ne... | nilq/baby-python | python |
# Copyright (c) Naas Development Team.
# Distributed under the terms of the Modified BSD License.
import os
c = get_config()
c.NotebookApp.ResourceUseDisplay.track_cpu_percent = True
c.NotebookApp.ResourceUseDisplay.mem_warning_threshold = 0.1
c.NotebookApp.ResourceUseDisplay.cpu_warning_threshold = 0.1
# We rely o... | nilq/baby-python | python |
#FUNÇÕES (FUNCTION)
#EXEMPLO SEM O USO DE FUNÇÃO :(
rappers_choice = ["L7NNON", "KB", "Trip Lee", "Travis Scott", ["Lecrae", "Projota", "Tupac"], "Don Omar"]
rappers_country = {"BR":["Hungria", "Kamau", "Projota", "Mano Brown", "Luo", "L7NNON"],
"US":["Tupac", "Drake", "Eminem", "KB", "Kanye West", "Lecrae", "Tra... | nilq/baby-python | python |
from __future__ import print_function
import numpy as np
import time, os, sys
import matplotlib.pyplot as plt
from scipy import ndimage as ndi
from skimage import color, feature, filters, io, measure, morphology, segmentation, img_as_ubyte, transform
import warnings
import math
import pandas as pd
import argparse
impor... | nilq/baby-python | python |
#!/usr/bin/env python3
"""This script adds Type B uncertainties to those given in the .apu file.
"""
from sys import exit
from glob import glob
from numpy import matrix
from math import radians, sin, cos, sqrt, atan2, degrees
def dd2dms(dd):
minutes, seconds = divmod(abs(dd) * 3600, 60)
degrees, minutes = d... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# MIT License
#
# Copyright (c) 2018 ZhicongYan
#
# 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 us... | nilq/baby-python | python |
from ctypes import *
import threading
import json
import os
tls_var = threading.local()
import csv
csv.field_size_limit(500000)
from G2Exception import TranslateG2ModuleException, G2ModuleNotInitialized, G2ModuleGenericException
def resize_return_buffer(buf_, size_):
""" callback function that resizs return buff... | nilq/baby-python | python |
import torch.nn as nn
import torch.nn.functional as F
class CNN(nn.Module):
# https://github.com/rensutheart/PyTorch-Deep-Learning-Tutorials/blob/master/part3_MNIST.py
def __init__(self, n_classes):
super(CNN, self).__init__()
# define all the components that will be used in the NN (these can ... | nilq/baby-python | python |
# Copyright 2014 - Red Hat Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | nilq/baby-python | python |
from .R2 import R2
| nilq/baby-python | python |
import os
def handle_headers(frame, request, response):
# Send a 103 response.
resource_url = request.GET.first(b"resource-url").decode()
link_header_value = "<{}>; rel=preload; as=script".format(resource_url)
early_hints = [
(b":status", b"103"),
(b"link", link_header_value),
]
... | nilq/baby-python | python |
# Copyright 2018 The Cirq Developers
#
# 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 ... | nilq/baby-python | python |
from rest_framework import serializers
from .models import Product
class ProductSerializer(serializers.ModelSerializer):
# Get the image url by serializing `ImageField`
image = serializers.ImageField(max_length=None, allow_empty_file=False, allow_null=True, required=False)
class Meta:
# Model to... | nilq/baby-python | python |
import os
import platform
import time
import sys
import importlib
import glob
import subprocess
import selectors
import multiprocess
import paramiko
from comm.platform import linux_win, run_cmd_list, run_cmd
from compute import Config_ini
from compute.log import Log
def get_local_path():
"""
:return:Get... | nilq/baby-python | python |
# coding: utf-8
from django.core.management.base import BaseCommand, CommandError
from ...models import Account, Tweet
class Command(BaseCommand):
"""Generates the HTML version of all the Tweets.
Does this by re-saving every Tweet, one-by-one.
For one account:
./manage.py generate_tweet_html --accou... | nilq/baby-python | python |
import pytest
@pytest.fixture
def supply_AA_BB_CC():
aa=25
bb =35
cc=45
return [aa,bb,cc] | nilq/baby-python | python |
#!/usr/pkg/bin/python2.7
from __future__ import print_function
# grep: serach for string patterns in files
import sys
import os
import argparse
import re
def _fg(file, pattern, ops):
with open(file, 'r') as f:
text = f.readlines()
z = len(text)
for i in range(z):
line = text[i]
result = patt... | nilq/baby-python | python |
from collections import defaultdict
import dill
import numpy as np
import time
import torch.multiprocessing as mp
mp.set_sharing_strategy('file_system')
from starter_code.infrastructure.log import renderfn
from starter_code.sampler.hierarchy_utils import flatten_rewards, build_interval_tree, set_transformation_ids, ge... | nilq/baby-python | python |
# Copyright (c) 2018 PaddlePaddle 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 appli... | nilq/baby-python | python |
#-*- coding:utf-8 -*-
# 2.2 变量
message = "Hello Python world!"
print(message)
message = "现在的时间是:2021年6月11日21:07:18"
print(message)
# 2.3 字符串
name = "ada love lace"
print(name.title())
print(name.upper())
print(name.lower())
first_name = "ada"
last_name = "love lace"
full_name = first_name + last_name
print(full_name... | nilq/baby-python | python |
from .model_108_basicDdSt import BasicDdSt
| nilq/baby-python | python |
import numpy as np
from py_wake.site._site import UniformWeibullSite
from py_wake.wind_turbines import OneTypeWindTurbines
wt_x = [134205, 134509, 134813, 135118, 135423]
wt_y = [538122, 538095, 538067, 538037, 538012]
power_curve = np.array([[3.0, 0.0],
[4.0, 15.0],
[... | nilq/baby-python | python |
import unittest
class Solution:
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
if not citations:
return 0
citations.sort(reverse=True)
h = 0
for i in citations:
if i > h:
h += 1
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""Console script for rps."""
import click
from .log import get_log
import asyncio
from .server import Site
from .api import start
def validate_url(ctx, param, value):
try:
return value
except ValueError:
raise click.BadParameter('url need to be format: tcp://ipv4:por... | nilq/baby-python | python |
from .controllers.product import ProductController
from .models import commerce
from .models import inventory
from django import forms
from django.db.models import Q
class ApplyCreditNoteForm(forms.Form):
required_css_class = 'label-required'
def __init__(self, user, *a, **k):
''' User: The user wh... | nilq/baby-python | python |
from typing import Tuple
from hypothesis import given
from gon.base import (Compound,
Geometry)
from gon.hints import Scalar
from tests.utils import (equivalence,
robust_invert)
from . import strategies
@given(strategies.geometries_with_coordinates_pairs)
def test_basi... | nilq/baby-python | python |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from math import fabs
import compas
import numpy as np
import scipy as sp
import scipy.linalg
import scipy.sparse
import scipy.sparse.linalg
def compute_displacement_x(mesh, gate_points, x_size, z_size, coeff... | nilq/baby-python | python |
"""
A class to hold polytopes in H-representation.
Francesc Font-Clos
Oct 2018
"""
import numpy as np
class Polytope(object):
"""A polytope in H-representation."""
def __init__(self, A=None, b=None):
"""
Create a polytope in H-representation.
The polytope is defined as the set of
... | nilq/baby-python | python |
import udfalcon
def test_outputs_return_results():
assert isinstance(udfalcon.fly({'output': 'return', 'mode': 'test'}), dict)
| nilq/baby-python | python |
import re
def main():
eventRegex = r'\s*\n*-{50,}\s*\n*'
placeRegex = r'(?i)(?:place|yer|location|mekan)\s*:\s+(.*?)\s*?[\n\r]'
dateRegex = r'(?i)(?:date|tarih|deadline)\s*:\s+(.*?)\s*?[\n\r]'
timeRegex = r'(?i)(?:time|zaman)\s*:\s+(.*?)\s*?[\n\r]'
testData = getTestData()
for i in range... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.