text
string
size
int64
token_count
int64
from matplotlib import pyplot as plt from autolens.data.array.plotters import plotter_util from autolens.lens.plotters import lens_plotter_util def plot_fit_subplot( fit, should_plot_mask=True, extract_array_from_mask=False, zoom_around_mask=False, positions=None, should_plot_image_plane_pix=True, ...
6,634
2,424
import pytest from ..cell import Cell from ..exceptions import CellOccupiedError def test_is_empty(): c = Cell('00') assert c.is_empty c.move('X') assert not c.is_empty def test_str(): c = Cell('00') assert str(c) == '-' c.move('X') assert str(c) == 'X' def test_error_on_double_...
793
329
from flask import Flask, request from flask_httpauth import HTTPBasicAuth from flaskr.title_search import get_title_content from werkzeug.security import generate_password_hash, check_password_hash from redisearch import Client, Query, TextField, IndexDefinition import redis from redis import ResponseError import json ...
3,065
954
def gcd_optimal_euclidean(a: int, b: int) -> int: if b == 0: return a a, b = b, a % b return gcd_optimal_euclidean(a, b) def lcm_optimal_euclidean(a: int, b: int) -> int: """Return a LCM (Lowest Common Multiple) of given two integers using euclidean algorithm This function uses euclidean ...
1,044
456
from tool.runners.python import SubmissionPy def get_coords(steps): x, y = 0, 0 coords = set() for step in steps.split(","): if step[0] == "R": for i in range(x, x + int(step[1:])): coords.add((i, y)) x = x + int(step[1:]) elif step[0] == "L": ...
1,135
413
import os import tensorflow as tf from niftynet.application.regression_application import \ RegressionApplication, SUPPORTED_INPUT from niftynet.engine.sampler_uniform import UniformSampler from niftynet.engine.sampler_weighted import WeightedSampler from niftynet.engine.application_variables import NETWORK_OUTPU...
5,104
1,423
def test_empty(): # Empty test that only imports eegnb, to make `pytest` pass import eegnb
99
33
import datetime from threading import RLock class Status: def __init__(self): self.rlock = RLock() self.status_data = {} self.created_at = datetime.datetime.now() def start_tunnel(self, tunnel_name): with self.rlock: if tunnel_name in self.status_data: ...
723
217
from __future__ import absolute_import import urlparse from django.conf import settings from django.core.exceptions import PermissionDenied from django.core.urlresolvers import reverse from django.template import RequestContext, Variable from django.template.defaultfilters import capfirst from django.utils.safestring...
2,037
629
from copy import deepcopy from math import ceil from pyramid.httpexceptions import HTTPForbidden from pyramid.view import view_config from sqlalchemy import and_ from ..models import Image from ..session import require_logged_in from ..config import ANNOTATIONS, JOKE_METADATA from ..translation import _ @view_config...
3,237
878
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
1,357
472
#!/usr/bin/env python2 # vim: set syntax=none nospell: import subprocess import os import fnmatch import datetime from bottle import default_app, route, run, template, response, redirect, debug, error, static_file from wraphtml import WrapHtml # for WSGI use: application = default_app() # config option # debug(Tru...
6,877
2,270
from django.contrib import admin # Register your models here. from appgestion.models import Cliente,Articulo,Pedido admin.site.register(Articulo) admin.site.register(Cliente) admin.site.register(Pedido)
207
69
a = [1, 2, 'a'] try: print ("Second element = %d" %a[1]) # Throws error since there are only 3 elements in array print ("thirdFourth element = %s" %a[2]) print("fourth element=%d"%a[4]) except Exception as e: print ("Exception ",e)
263
101
import unittest from expression_builder.expression_builder import ExpressionBuilder class BracketsTests(unittest.TestCase): # noinspection PyPep8Naming def setUp(self): self.exp = ExpressionBuilder() def test_one(self): result = self.exp.run_statement("(2 + 4) * 2") self.assertEq...
1,381
483
from conan.tools.google.toolchain import BazelToolchain from conan.tools.google.bazeldeps import BazelDeps from conan.tools.google.bazel import Bazel from conan.tools.google.layout import bazel_layout
201
66
# -*- coding: utf-8 -*- """ Created on Thu Mar 11 11:25:26 2021 @author: jsalm """ import matplotlib.pyplot as plt import numpy as np from sympy import symbols from sympy.physics import mechanics from sympy import Dummy, lambdify from scipy.integrate import odeint #animation functions from matplotlib import animati...
6,343
2,420
def find_captains_room(rooms, size): all_guests = list(map(int, rooms)) unique_guests = set(all_guests) sum_all_guests = sum(all_guests) # Get the sum of all the unique room numbers sum_unique_guests = sum(unique_guests) # Get the difference, in the sum: the captains room will cause this difference te...
722
267
#!/usr/local/bin/python # -*- coding: utf-8 -*- import wx #import wx.lib.buttons as buttons import PyDatabase import images import string import MyValidator from PhrResource import ALPHA_ONLY, DIGIT_ONLY, strVersion, g_UnitSnNum import MyThread import time import datetime import types import os import matplotlib.pypl...
16,196
6,049
import asyncio import logging from .base import Transport, log_ssl_detail logger = logging.getLogger(__name__) class RawSocket(Transport): def __init__(self, reader, writer, chunk_size=2 ** 16): self.reader = reader self.writer = writer self._closed = False self.chunk_size = chun...
2,050
610
class Solution: def convertToTitle(self, n): """ :type n: int :rtype: str """ ans = '' while n != 0: n -= 1 digit = n % 26 ans = chr(ord('A') + digit) + ans n = n // 26 return ans
297
94
#!/usr/bin/env python # https://python-essentials.readthedocs.io/en/latest/echo.html while True: user_input = input("Enter some text: ") try: is_user_input_of_type_int = int(user_input) print("You entered an integer " + user_input) continue except ValueError: if user_input == 'quit': prin...
434
145
''' 和为K的子数组 给定一个整数数组和一个整数 k,你需要找到该数组中和为 k 的连续的子数组的个数。 说明 : 数组的长度为 [1, 20,000]。 数组中元素的范围是 [-1000, 1000] ,且整数 k 的范围是 [-1e7, 1e7]。 ''' from typing import List from collections import defaultdict ''' 思路:前缀和+哈希 依次从左到右计算前缀和,如果前缀和presum = k,则满足要求的子数组数量ans+1 如果以往的子数组前缀和等于presum-k,因为以往的子数组是从0..x,而当前前缀和是从0..i,i>x,必然有当前子数组前缀和减去...
1,021
686
# noqa: D205,D400 """ SDBA Diagnostic Testing Module ============================== This module is meant to compare results with those expected from papers, or create figures illustrating the behavior of sdba methods and utilities. """ from __future__ import annotations import numpy as np from scipy.stats import gaus...
5,139
2,100
# SPDX-License-Identifier: Apache-2.0 # # Copyright (C) 2021 Micron Technology, Inc. All rights reserved. from pathlib import Path from tools.dbbench import DBbenchTest name = Path(__file__).stem cli_params = "--num=900000000 --threads=32 --value_size=400" cmdlist = [ f"--benchmarks=fillseq {cli_params} --histog...
648
259
# Generated by Django 3.0.3 on 2020-04-14 07:08 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('main', '0005_auto_20200413_2105'), ] operations = [ migrations.AlterField( model_name='block', ...
910
303
import torch import pdb import torch.nn as nn import torch.nn.functional as F import math from torch.autograd import Variable from torch.autograd import Function import numpy as np def get_centroid(input, grain_size, num_bits, M2D): if len(input.size()) == 2: print(input.size()) print(grain_size) ...
4,973
1,810
#!/usr/bin/python3 # coding: utf-8 import util print("Content-Type: application/json\n\n") def newuser(jsonPayload): import pymysql try: firstname = jsonPayload['firstname'] lastname = jsonPayload['lastname'] username = jsonPayload['username'] password = jsonPayload['p...
2,133
594
# coding=utf-8 # Copyright 2020 The Google Research 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 applicab...
1,816
600
import logging import struct import typing from pymobiledevice3.exceptions import PyMobileDevice3Exception from pymobiledevice3.lockdown import LockdownClient class DtFetchSymbols(object): SERVICE_NAME = 'com.apple.dt.fetchsymbols' MAX_CHUNK = 1024 * 1024 * 10 # 10MB CMD_LIST_FILES_PLIST = struct.pack('...
1,430
480
#!/usr/bin/env python """ Read registers from a node connected to the vscp daemon. This module can be used to test the speed of the register update. // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foun...
4,460
1,485
__version__ = "1.0.0a" __author__ = "Paul le Roux" from .conductivity import * from .gap_energy import *
106
43
import os from flask import Blueprint, flash, redirect, abort from database.study_models import Study from libs.admin_authentication import authenticate_admin_study_access from libs.sentry import make_error_sentry from pipeline.boto_helpers import get_boto_client from pipeline.configuration_getters import get...
1,939
592
#!/usr/bin/env python # This document is part of CrowdProjects # https://github.com/skytruth/CrowdProjects # =========================================================================== # # # Copyright (c) 2014, SkyTruth # All rights reserved. # # Redistribution and use in source and binary forms, with or without...
22,106
6,751
# -*- coding: utf-8 -*- import requests def send_message_telegram(msg, chat_id, token): """Send a message to a telegram user. The token can be generated talking with @BotFather on telegram. Args: msg (str): Message. chat_id (str): Number. token (str): Authentication Key. Returns:...
561
174
from kafka import KafkaConsumer import json from TimestampEvent import TimestampEvent consumer = KafkaConsumer('timestamp', bootstrap_servers='localhost:9092', value_deserializer=lambda x: json.loads(x.decode('utf-8'))) for message in consumer: timestampEvent = TimestampEvent(**(message.value)) print("Receiv...
354
105
__all__ = ["degree_days"] from to_numpy import to_numpy from from_numpy import from_numpy import numpy def degree_days(T_base, Max, Min, NoData_Value, outpath = False, roof = False, floor = False): """ Inputs rasters for maximum and minimum temperatures, calculates Growing Degree Days this function is ...
4,133
1,151
from ...Fields import UInt8Field, Int16Field from ...Fields.Enums import EVeinType16 from . import Model, Int32Field, FloatField class VeinData(Model): version = UInt8Field() id = Int32Field() veinType = EVeinType16() modelIndex = Int16Field() groupIndex = Int16Field() amount = Int32Field() ...
564
208
__author__ = 'Maosen' import torch import torch.nn as nn import torch.nn.functional as F import utils from utils import pos2id, ner2id import sys from tqdm import tqdm class LSTM(nn.Module): def __init__(self, args, rel2id, word_emb=None): super(LSTM, self).__init__() # arguments hidden, vocab_size, emb_dim, po...
3,277
1,455
import os filt_path = os.path.abspath(__file__) father_path = os.path.abspath(os.path.dirname(filt_path) + os.path.sep + ".") GPU_ID = "cpu" dbnet_short_size = 960 det_model_type = "dbnet" pse_scale = 1 model_path = os.path.join(father_path, "models/dbnet.onnx") # crnn相关 nh = 256 crnn_vertical_model_path = os.path....
898
424
import pandas as pd import logging from .validate_options import validate_options from .merge_dataframes import merge_dataframes_multiple_columns, merge_dataframes_single_column def merge_files(left_file: str, right_file: str, columns: list, keep: str = 'none', keep_missing: str = 'none') -> pd.DataFrame: """ ...
1,265
384
# Generated by Django 2.2.10 on 2021-07-01 04:34 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0006_auto_20210701_0346'), ] operations = [ migrations.AddField( model_name='invoice', name=...
993
344
import os from typing import Dict from os.path import join as pathjoin __ALL__ = ['get_dataset_path_by_name'] def get_dataset_path_by_name(dataset_name:str) -> Dict[str, str]: root_dir = os.path.dirname(__file__) if dataset_name not in "DUT-OMRON DUTS PASCAL-S SOD".split(" "): raise NameError(f"the da...
1,231
462
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Oct 9 16:46:40 2021 @author: bing """ import copy ## The code only works for lists without repeated elements def permute(nums, node=[], permutations=[]): if len(node)==len(nums): permutations.append(node[:]) return for n in ...
961
386
#!/usr/bin/env python import cv2 import rospy import numpy as np from sensor_msgs.msg import CompressedImage class CameraNode(object): def __init__(self, camera=0, nb=0, buggy_nb=0, node_name="camera_node"): self.vc = cv2.VideoCapture(camera) # Initialise instance of...
1,579
446
import cv2 import numpy def write_MNIST_files(): file_object = open('../data/data.csv', 'r') file_object.readline() counters = {_ : 0 for _ in range(10)} folders = { 0 : 'zero', 1 : 'one', 2 : 'two', 3 : 'three', 4 : 'four', 5 : 'five', 6 : 'six', 7 : 'seven', 8 : 'eight', 9 : 'nine' } for line in fil...
680
303
import unittest from app.models import Blog,User from flask_login import current_user from app import db class TestBlogs(unittest.TestCase): def setUp(self): self.user_Derrick = User(username="derrokip34",password="zlatan",email="derrokip@gmail.com") self.new_blog = Blog(blog_title="Batman",blog_c...
1,119
384
import os from restfly.session import APISession from pyzscaler import __version__ from .admin_and_role_management import AdminAndRoleManagementAPI from .audit_logs import AuditLogsAPI from .config import ActivationAPI from .dlp import DLPAPI from .firewall import FirewallPolicyAPI from .locations import LocationsAP...
5,196
1,527
import os import json import torch from tqdm import tqdm from pytorchDL.tasks.image_segmentation.predictor import Predictor from pytorchDL.tasks.image_segmentation.data import Dataset from pytorchDL.metrics import ConfusionMatrix class Evaluator(Predictor): def __init__(self, test_data_dir, out_dir, ckpt_path,...
2,769
902
""" urlresolver XBMC Addon Copyright (C) 2011 t0mm0 This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ...
2,457
785
from wintools import print_files_info, print_info FILES = ["./tests/resources/test.iso"] class TestFile: def test_print_files_info(self): print_files_info(FILES) def test_print_info(self): print_info("./tests")
240
82
import setuptools with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() setuptools.setup( name="PatternPackage-Polamreddykrishnareddy", version="0.0.1", author="Polamreddykrishnareddy", author_email="krishnareddy40900@gmail.com", description="I Build the python Patt...
1,232
373
words=['about','above','abuse','actor','acute','admit','adopt','adult','after','again','agent','agree','ahead','alarm','album','alert','alike','alive','allow','alone','along','alter','among','anger','Angle','angry','apart','apple','apply','arena','argue','arise','array','aside','asset','audio','audit','avoid','award','...
3,832
1,244
# import sys import os import io from setuptools import setup, find_packages, Command, Extension from os import path root = 'singlecell' name = 'singlecell' version = '0.1.0' here = path.abspath(path.dirname(__file__)) description = ('SingleCell: A Python/Cython Package for Processing ' 'Single-Cell ...
5,548
1,872
def remove_punctuation(input_string): """Return a str with punctuation chars stripped out""" tran_table = str.maketrans('','', '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~') output_string = input_string.translate(tran_table) return output_string pass
276
104
from Crypto.Cipher import AES from Xor import xorPlain from set2.PkcsPadding import pkcs7_pad def decrypt_ecb(ciphertxt, key): encryptor = AES.new(key, AES.MODE_ECB) return encryptor.decrypt(ciphertxt) def encrypt_ecb(plaintxt, key): encryptor = AES.new(key, AES.MODE_ECB) if len(plaintxt)%len(key) !...
1,322
577
# Copyright Collab 2014-2016 # See LICENSE for details. """ Tests for the :py:mod:`encode.models` module. """ from __future__ import unicode_literals from django.core.files.base import ContentFile from encode.models import Audio, Video, EncodingProfile from encode.tests.helpers import WEBM_DATA, FileTestCase clas...
1,234
383
from bflib import units from bflib.characters import classes from bflib.spells import listing from bflib.spells.base import Spell from bflib.spells.duration import SpellDuration from bflib.spells.range import Touch @listing.register_spell class Darkvision(Spell): name = "Darkvision" class_level_map = { ...
431
145
from pytorch_pretrained_bert.tokenization import BertTokenizer tokenlizer = None ''' Convert a input line from input_file to a tuple: [index, line_raw_data , inputs_id, segments_id, mask] record id_line process inputs_id, segments_id, mask record line_data(raw string in line from input_fi...
5,589
1,819
# -*- coding: UTF-8 -*- import requests import urllib3 import threading import json import os from bs4 import BeautifulSoup class IpSpider: url = 'http://www.xicidaili.com/nn/' page = 1 maxPage = 10 checkUrl = 'https://www.ip.cn/' needIpNum = 10 ipNum = 0 filePath = 'db/' fileName = 'i...
3,653
1,203
import Block; class BlockSim: def process(self, loc, count): listofBlocks = [] filename = "./planning/" + str(loc) + ".txt" f = open(filename, 'r') data = f.read() #print line lines = data.split('\n') #print len(lines) for i in range(len(lines)): items = lines[i].split() blk = Block.Block(...
617
272
from bottle import request, route, run, static_file chats = [] @route('/ping') def ping(): print chats return "pong" @route('/chat', method = 'POST') def save_chat(): if request.forms.get('user') is not None: chats.append({ 'user': request.forms.get('user'), 'at': long(requ...
960
327
import cv2 import numpy as np from task2 import fit, l1_grad_descent origin_image = cv2.imread('./data/lena.jpg') n, m, channel = origin_image.shape sigma = 20 noise_image = np.uint8(np.clip(np.random.normal(0, sigma, origin_image.shape) + origin_image, 0, 255)) cv2.imwrite('./data/nois...
1,349
525
def main(): # Maximum value needed to get calculate # 9**5 == 59049 # 59049 * 5 == 295245 power = 5 start = 2 stop = power * 9**5 matches = [] for x in xrange(start, stop+1): xstr = str(x) xsum = 0 for y in xrange(len(xstr)): xsum += int(...
619
247
#!/usr/bin/env python ''' This is a very short script intended to help the user undersand what datafiles are, how to use them & how datafiles affect your script's normal execution. First, run this script by itself: bash$ python testscript.py Now, add datafile: bash$ python testscript.py -datafile data/simple_...
2,513
875
import enum class ETradeOfferState(enum.IntEnum): Invalid = 1 Active = 2 Accepted = 3 Countered = 4 Expired = 5 Canceled = 6 Declined = 7 InvalidItems = 8 NeedsConfirmation = 9 CanceledBySecondFactor = 10 Escrow = 11 class EItemQuality(enum.IntEnum): Normal = 0 Ge...
950
483
import sys input = sys.stdin.readline sys.setrecursionlimit(10 ** 7) n, x = map(int, input().split()) point = list(map(int, input().split())) diff = [0] * n for i in range(n): diff[i] = abs(point[i] - x) def gcd(big, small): if small == 0: return big else: return gcd(small, big % small) i...
372
147
from abc import abstractmethod from typing import Callable, Generic, NoReturn, TypeVar from returns.primitives.hkt import KindN _FirstType = TypeVar('_FirstType') _SecondType = TypeVar('_SecondType') _ThirdType = TypeVar('_ThirdType') _UpdatedType = TypeVar('_UpdatedType') _LashableType = TypeVar('_LashableType', bo...
1,369
416
import os import time import glob import numpy as np import argparse from detection_evaluation.nuscenes_eval_core import NuScenesEval from detection_evaluation.label_parser import LabelParser import co_utils as cu def parse_args(): parser = argparse.ArgumentParser(description='arg parser') # parser.add_argumen...
6,875
2,851
import collections import math def unalikeability(measurements: [int]) -> float: """ Unalikeability returns the unalikability measure for `measurements`, assuming that `measurements` is an array describing a collection of measurements of a categorical variable (i.e: perhaps the results of runnin...
1,158
454
from ....file_utils import get_filepath from ...server_utils import parse_variant from flask import url_for from pathlib import Path import urllib.parse import itertools import re import copy import sqlite3 from typing import List,Dict,Any,Optional,Iterator # TODO: sort suggestions better. # - It's good that hitting...
8,769
2,658
import logging import uvicorn from fastapi import FastAPI, HTTPException from starlette.middleware.cors import CORSMiddleware from rest_api.controller.errors.http_error import http_error_handler from rest_api.config import ROOT_PATH logging.basicConfig(format="%(asctime)s %(message)s", datefmt="%m/%d/%Y %I:%M:%S %p"...
1,314
492
import tensorflow as tf class RnnTextClassifier: def __init__(self, batch_size, sentence_length, embedding, cell_layer_size, cell_layer_num, num_classes, lam=1, lr=0.001): self.batch_size = batch_size self.sentence_length = sentence_length self.embedding = embedding ...
4,603
1,482
#!/usr/bin/env python # # run.py # # References: # # * Masek J. 2013. Single interval showtwave radiation scheme with # parametrized optical saturation and spectral overlaps. # import sys import os from tempfile import NamedTemporaryFile import subprocess import numpy as np from StringIO import StringIO impo...
4,705
2,191
from docusign_rooms import ApiClient def create_rooms_api_client(access_token): """Create API client and construct API headers""" api_client = ApiClient(host="https://demo.rooms.docusign.com/restapi") api_client.set_default_header( header_name="Authorization", header_value=f"Bearer {access...
357
110
#!/usr/bin/env python3 """ App to generate music. Copyright 2020 Thomas Jackson Park & Jeremy Pavier """ import os import argparse import sys from pathlib import Path from GenerIter.app.clibase import CLIBase from GenerIter.selector import Selector from GenerIter.config import Config from GenerIter.factory import Pr...
4,776
1,179
from flask import Flask, render_template, request, url_for, redirect, session import pymongo import mail from location import lat, log #, location, city, state import messagebird import credentials #set app as a Flask instance app = Flask(__name__) #encryption relies on secret keys so they could be run app.secret_ke...
6,566
1,902
from django.contrib import admin from apps.porteiros.models import Porteiro admin.site.register(Porteiro)
107
32
from .services.hazard_assessor import HazardMeter from .services.ocr import ImageOCR from .serializers import IngredientsSerializer, ProductSerializer, DetailsIngredientSerializer from .services.text_blocks_screening import IngredientsBlockFinder from .services.db_tools import DBQueries from .services.ocr_settings impo...
2,118
621
"""d04 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based vie...
1,181
374
""" TreeTree is a wrapper over `easygit.EasyTree` that provides more efficient storage of lists. Keys must be strings made up of digits, and they should be as close as possible to the indices of a list. """ class TreeTree(object): is_tree = True def __init__(self, container, prefix='tt'): self.contain...
3,122
862
from telegram.ext import Updater, PicklePersistence from config import BOT_TOKEN updater = Updater( BOT_TOKEN, persistence=PicklePersistence(filename="data") ) dp = updater.dispatcher def main(): from handlers import all_handlers for handler in all_handlers: if len(handler) == 2: ...
737
228
# # VScodeで入力をテキストから読み込んで標準入力に渡す import sys import os f=open(r'.\D\D_input.txt', 'r', encoding="utf-8") # inputをフルパスで指定 # win10でファイルを作るとs-jisで保存されるため、読み込みをutf-8へエンコードする必要あり # VScodeでinput file開くとutf8になってるんだけど中身は結局s-jisになっているらしい sys.stdin=f # # 入力スニペット # num = int(input()) # num_list = [int(item) for item in input().s...
951
469
import time import math class ComplementaryFilter(object): def __init__(self, gyroWeight=0.95): self.gyroWeight = gyroWeight self._reset() def _reset(self): self.last = 0 self.accelPos = [0, 0, 0] self.gyroPos = [0, 0, 0] self.filterPos = [0, 0, 0] def inp...
1,769
630
import sys sys.path.append("../") import json import cv2, os import numpy as np import tensorflow as tf from make_better_dataset_for_deepfake.main_data_creator import FaceExtractor class Engine: def load_image(self, path): image = tf.io.read_file(path) image = tf.image.decode_jpeg(image, channels=3) image = ...
3,008
1,357
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/11/15 10:51 # @Author : Dengsc # @Site : # @File : schedule.py # @Software: PyCharm from django.db import models from django.utils.translation import ugettext_lazy as _ from django_celery_beat.models import (CrontabSchedule, IntervalSchedule) fro...
3,668
1,110
# Copyright 2020 Miljenko Šuflaj # # 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...
18,110
5,316
import discord from discord.ext import commands from discord.ext.commands import Bot client: Bot = commands.Bot(command_prefix=['-'], case_insensitive=True, description="Train an AI to send messages.") guilds = [] guild_ids = [] @client.event async def on_ready(): await client.change_presence(activity=discord.Ga...
2,024
681
from pyhcl import * from .sirv_gnrl_dffl import sirv_gnrl_dffl from .sirv_gnrl_dfflr import sirv_gnrl_dfflr from .sirv_gnrl_dfflrs import sirv_gnrl_dfflrs def carray(el, len): ary = [] for i in range(len): ary.append(el) return ary def sirv_gnrl_fifo(CUT_READY: int = 0, ...
6,920
3,042
# ==================================================================== # # # # DATASET / DATALOADER # # # # ==========================...
6,600
1,827
from collections import Counter import numpy as np from flask import (Blueprint, flash, jsonify, redirect, render_template, request, url_for) from flask_login import current_user, login_required from app import db from app.auth.email import send_password_reset_email from app.auth.forms import Reset...
5,100
1,525
from django.apps import AppConfig class MeetingbotapiConfig(AppConfig): name = 'meetingbotapi'
101
32
import pytest @pytest.fixture def people_descriptor(): people_descriptor = { "api": { "resource": "people", "methods": [ { "get": {"enabled": True, "secured": False, "grants": ["get:users"]}, "post": {"enabled": True, "secured...
5,762
1,250
# Software License Agreement (BSD License) # # Copyright (c) 2018, Fraunhofer FKIE/CMS, Alexander Tiderko # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code mu...
3,652
1,177
iii fff ff qqqq 'fenzhi'
27
19
import uvicorn import src.main if __name__ == '__main__': uvicorn.run(src.main.app, host='0.0.0.0', port=8000)
117
55
import importlib import time import fibo # import fibo as fib """ 注解 出于效率的考虑,每个模块在每个解释器会话中只被导入一次。因此,如果你更改了你的模块,则必须重新启动解释器, 或者,如果它只是一个要交互式地测试的模块,请使用 importlib.reload(),例如 import importlib; importlib.reload(modulename) """ fibo.fib(1000) fibo.fib2(100) print(fibo.__name__) time.sleep(20) ## 去修改fibo.py ,能看到修改后的结果 import...
2,556
2,096
#!/usr/bin/python3 import csv import sys batsman = "" bowler = "" runs = None reader = [] myfile = sys.stdin for line in myfile: line = line.strip() row = line.split(',') if(row[0] == "ball"): batsman = row[4] bowler = row[6] runs = int(row[7]) + int(row[8]) print("%s,%s,%d" % (batsman, bowler, runs))
319
147
import zmq context = zmq.Context() socket = context.socket(zmq.SUB) socket.connect("tcp://localhost:5555") socket.setsockopt_string(zmq.SUBSCRIBE, “weather”) while True: wtr = socket.recv_string() print(“the weather is: “ + wtr)
240
94
try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse import logging import os import mmap import numpy as np import vaex.utils import vaex.file DEFAULT_BLOCK_SIZE = 1024*1024*1 # 1mb by default logger = logging.getLogger("vaex.file.cache") class MMappedFile: """Sma...
6,876
2,193