index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
988,300
cb5531a6176e2c6c642a310e4973708266ef0722
# Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. # # Examples: # # s = "leetcode" # return 0. # # s = "loveleetcode", # return 2. # First Approach: class Solution(object): def firstUniqChar(self, s): """ :type s: str :rtyp...
988,301
b13c3b63d58a7cfdfd968c40c78dbe4a68512fe1
""" Authors: Sean Moloney and Jon Killinger Class: CS 415 Assignment: Project 3 Description: This project implents FFT, IFFT and component multiplication. Executes by running: python2 project3.py """ import random import cmath import math import sys import timeit import time #sys.setrecursionlimit(10000000) def app...
988,302
0f6622c19338d8cd1b2e2a0ac05b08a57531b745
"""Radio frequency types and allocators.""" import itertools from dataclasses import dataclass from typing import Dict, Iterator, List, Set @dataclass(frozen=True) class RadioFrequency: """A radio frequency. Not currently concerned with tracking modulation, just the frequency. """ #: The frequency i...
988,303
3690568bb1aced10755a166a66e085a91abbe1f7
#import our library import pyshorteners #Get url from user/client url = input("Enter your url: ") #printing out short link :) print("Your url: ", pyshorteners.Shortener().tinyurl.short(url))
988,304
6747cd3f7f70fccfed192ed30d9d18b0a3056e53
# 2020/03/08 MySQL 練習 4 -- rollback() # # 每次更動的最後的要 cursor.commit() 來提交結果 # 但當更動失敗的時候,可以透過 rollback() 來返回 import pymysql from os import getpid print('該程式 pid:', getpid()) # 打印出執行程式的 pid,用來對照是否連線成功 db = pymysql.connect( host = "localhost", # 欲連接的 Server IP port = 3306, # 該 Server 的 port user = "root"...
988,305
0479d0485c545b291a3053fe56c4f98df9f445ce
#import requests # #url = "https://skyscanner-skyscanner-flight-search-v1.p.rapidapi.com/apiservices/browsedates/v1.0/US/USD/en-US/SFO-sky/LAX-sky/2021-06-22" # #querystring = {"inboundpartialdate":"2021-06-23"} # #headers = { # 'x-rapidapi-key': "e5eb6fe9efmshdc31df18adcf9acp183317jsndafb7aac79e2", # 'x-rapidapi...
988,306
0a8f9b87fee127aa2bba0348dcd26c826bf31606
import sys for i in sys.stdin: a = i.split() nums = [int(a[0]), int(a[1])] if( len(nums) == 2): upperLim = nums[0] * nums[1] test = upperLim / nums[0] while( test > nums[1] - 1 ): upperLim = upperLim - 1 test = upperLim / nums[0] print(upperLim+1)
988,307
b3e6799de0148a1cf96e08a7b1fa2649241f2b82
#!/usr/local/bin/python # author: Gary Wang import subprocess import sys import time import fcntl import struct import termios import random as rand class matrix(object): def __init__(self): # constants self.height, self.width = struct.unpack('hh', fcntl.ioctl(1, termios.TIOCGWINSZ, '1234')) ...
988,308
f9c018385247cf917085980e17228ac18781c4f3
# # Copyright (c) 2013-2021 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # # vim: tabstop=4 shiftwidth=4 softtabstop=4 from django.conf.urls import include # noqa from django.conf.urls import url from starlingx_dashboard.dashboards.admin.inventory.cpu_functions import \ views as cpu_function...
988,309
96e37c50cbce2b7b3718a71c8f0b931be95b85fb
from google.cloud import datastore from constants import PROJECT_ID, DATASTORE_DATA_KIND datastore_client = None def initialize_datastore_client(): global datastore_client if datastore_client is None: datastore_client = datastore.Client(PROJECT_ID) def save_to_datastore(name, values): initializ...
988,310
99a1f4e03f69437b656528308403e3b9b1551e66
import random from typing import Iterable, Tuple, List from cities.city import get_cities from distances.helpers import keep_in_circle,\ DistanceCalculator, BatchCalculator, GPSPoint from distances.haversine.haversine import haversine, time_estimation from here_wrapper.wrapper import Routing def get_random_path(r...
988,311
5eccdad56306755960eb260438b0b15a9288a713
# @Author: Andrés Gúrpide <agurpide> # @Date: 20-05-2021 # @Email: agurpidelash@irap.omp.eu # @Last modified by: agurpide # @Last modified time: 25-06-2021 # Script to compute extinction map from astropy.io import fits import argparse import os import numpy as np import astropy.units as u import glob class C00: ...
988,312
a01923acaf864bc63e4b07b3af8a7ca2356af469
def towerofhanoi(n,beg,end,aux): if n==1: print('move disc',n,'from rod',beg,'to rod',end) return else: towerofhanoi(n-1,beg,aux,end) print('move disc',n,'from rod',beg,'to rod',end) towerofhanoi(n-1,aux,end,beg) n=int(input('enter no of disks ')) towerofhanoi(n,'A','C'...
988,313
06231e7803a9ad774bc5cd99b2ea14a9f34d1188
N = int(input()) T,A = map(int,input().split()) H = list(map(int,input().split())) C = 999 for i in H: tmp = T - 0.006 * i a = abs(tmp - A) if a < C: C = a x = int(H.index(i))+1 print(x)
988,314
8adc475573705442312a86272f0b6d9e313f765f
def merge(P,Q): ip = 0 iq = 0 res = [] while True: if ip >= len(P) or iq >= len(Q): break if P[ip] > Q[iq]: res.append(Q[iq]) iq += 1 elif P[ip] <= Q[iq]: res.append(P[ip]) ip += 1 if ip < len(P): res.extend(P[ip:]) if iq < len(Q): res.extend(Q[iq:]) print str(P) + "+"+str(Q) + "=" +str...
988,315
1734c852a4c9bbf477864a086ad4b08da4e9d99b
from sqlalchemy import Column, Integer, String from app.models.base import Base class Lab(Base): id = Column(Integer, primary_key=True, index=True) name = Column(String) title = Column(String) content = Column(String)
988,316
4e65916ed88ac12e8ca70137648ad8077f5b70f1
from Rank import Rank from functools import total_ordering class HandIterator: def __init__(self, hand): self._hand = hand self._index = 0 def __next__(self): if self._index < (len(self._hand)): self._index += 1 return self._hand[self._index - 1] raise ...
988,317
29012dadb46ae840f1ac7a2abf795fb522205812
#!/usr/bin/env python3 print(sum(i == j for i, j in zip(*open(0).read().split())))
988,318
e022921a41dcd73921a01f784c979202d803c5f1
""" Мини сервер с использованием asyncio. Из-за нового синтаксиса async/await нужен python 3.5 для запуска Получает запрос в формате MSGPACK, Проверяет поле test_date на соответствие заданному формату Отсылает результат проверки в формате msgpack """ import re import msgpack from aiohttp import web from msgpack.except...
988,319
7da6e3c8461e4074b097bd71e0f437c1cb31163c
from typing import Tuple import pandas as pd import numpy as np from scipy import stats def remove_outliers(df: pd.DataFrame, numerical_variables: list, strategy: str = 'IQR') -> pd.DataFrame: """Remove rows of the input dataframe having at least one variable with outlier Args: df (pd.DataFrame): In...
988,320
7599bf414480dc5086a14a17d451ad39f90119e0
class Solution: def countSquares(self, matrix: List[List[int]]) -> int: res=0 if len(matrix)==0: return 0 for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j]==1: if i==0 or j==0: ...
988,321
fd6cede6fde193ec7ac76c627f49d0ea2ba6d57c
import streamlit as st import time from load_css import local_css import os, sqlite3 import pandas as pd st.set_page_config( page_title="SPI:Calc", page_icon="😸", layout="centered", initial_sidebar_state="collapsed", ) local_css("style.css") ############### SQLITTE ############### def create_table(...
988,322
e0d1dbd780c33356ce48f4f5ce48176d0673dc4e
#!/usr/bin/env python import collections import contextlib import datetime from . import delay_record import errno import fcntl import logging import os from . import ozwd_get_value from . import ozwd_set_value from . import ozwd_util import pickle from . import spicerack import time LEVEL_FILE = '/var/lib/homeaut...
988,323
dd524258a4fd68a0b6b66c1b2ff95aca00e68fc8
from commands.pre_1_13.cmdex import CMDEx from commands.upgrader.utils import command_upgrader_base from ..utils import selector CMDEXS = [ CMDEx('gc help'), CMDEx('gc reload'), CMDEx('gc fulllevelup {selector:player}'), CMDEx('gc resetinfo {selector:player}'), CMDEx('gc getclan {selector:player...
988,324
8eda5e5d881a3f3725cdbe4eeac0d08ee03a209d
from flask_injector import Binder from jamaah.provider import PROVIDERS def configure(binder: Binder): for provider in PROVIDERS: binder.bind(provider, to=provider)
988,325
14fd8f85ce8d7ceec16c75cb9a6bb2d1ef4fdde4
import sys from ckeditor.fields import RichTextField from django.db import models from django.utils.timezone import make_aware from django.contrib.auth.models import User # from ckeditor.fields import RichTextField import datetime class Student(User): andrewid = models.CharField(max_length=20, blank = True, defau...
988,326
5553b3154bcb10289752d92a962dc8ac19e32829
# -*- coding: utf-8 -*- # Created by #chuyong, on 2019/11/19. # Copyright (c) 2019 3KWan. # Description : import unittest def hello(): class TestSomething(unittest.TestCase): def test_add(self): print("test add") def test_2(self): print("test 2") suite = unittest.m...
988,327
eac669c0072cedc0e428614c82c8e9923b205ae1
def solve(s, k): count = 0 s = list(s) for i in range(len(s)-k + 1): if s[i] == '-': count += 1 for j in range(i, i+k): if s[j] == '+': s[j] = '-' else: s[j] = '+' if '-' in s: return 'IMPOSS...
988,328
1acaf9638d657e15b5b576c05d51cd7614c728d0
import filter_keys import boto3 from botocore.exceptions import ClientError def get_service(function, dict_key, fields, extra_options={}): return filter_keys.filter_key('application-autoscaling', function, dict_key, fields, extra_options) def get_all(remove_empty=False): # ...
988,329
86b77f3666760ba1f3275714748034c073a12347
""" #Computer programmers refer to blocks of text as strings. In our last exercise, we created the string “Hello world!”. In Python a string is either surrounded by double quotes ("Hello world") or single quotes ('Hello world'). #It doesn’t matter which kind you use, just be consistent. """ print('Anupriya')
988,330
c86683a3e1cfae7e99cb25895cb9669db67995de
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2018-09-29 09:51 from __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('mainapp', '0008_auto_20180927_1156'), ] operations = ...
988,331
7a642246656c5bd015a566df3b3e3ff3f67ba91f
""" https://leetcode.com/problems/multiply-strings/ 43. Multiply Strings Medium -------------------- Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string. Note: You must not use any built-in BigInteger library or convert the inputs to in...
988,332
1e7b6c473d4c7b54dbabb77a4cafab3afcec70c5
from apscheduler.schedulers.background import BackgroundScheduler from datetime import datetime # BlockingScheduler scheduler = BackgroundScheduler() # 输出时间 @scheduler.scheduled_job('cron', id='my_job_id', hour=17,minute=0,second=0) def job(): print(datetime.now().strftime("%Y-%m-%d %H:%M:%S")) def aa(): print(...
988,333
293fde634357d0aab780913fa7a0591776bd8437
import pytest import yaml from tests.commands.run_test_utils import ALTERNATIVE_YAML, RunAPIMock, RunTestSetup from tests.fixture_data import CONFIG_YAML, PROJECT_DATA from valohai_cli.commands.execution.run import run from valohai_cli.ctx import get_project from valohai_cli.models.project import Project adhoc_mark =...
988,334
ca09162407e3d71412b3c0517c78cdba72dc8835
from math import ceil import pygame as pg from functions import get_surface from models.Float import Float from models.GameObject import GameObject class BarIndicatorColor: def __init__(self, background, border, full, empty): self.background = background self.border = border self.full = f...
988,335
b913ea5e7b86e3913c38a1fe38d62178ff7d2fef
import argparse import os import pathlib import json import math import numpy as np from tqdm import tqdm from functools import reduce from yellowbrick.text import TSNEVisualizer from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer from sklearn.decomposition import PCA from sklearn.manifold imp...
988,336
07e0899543767e59993565fcfd0239dba18544d4
import cv2 import numpy as np import imutils def nothing(x): pass def main(): cap = cv2.VideoCapture(0) cv2.namedWindow("Trackbars") cv2.createTrackbar("L - H", "Trackbars", 0, 179, nothing) cv2.createTrackbar("L - S", "Trackbars", 0, 255, nothing) cv2.createTrackbar("L - V", "Trackbars", 0, 255...
988,337
5d8555a54e50efe44538ac3e05e0ea54ad2f22bc
import sys sys.path.append('../') import argparse import configparser import numpy as np from sklearn.metrics import make_scorer, f1_score, accuracy_score, recall_score, precision_score, classification_report, precision_recall_fscore_support from sklearn.ensemble import GradientBoostingClassifier, RandomForestCl...
988,338
b14e9b1a5a96a285941e0a6856b2141c6ea23ee5
import time import jwt import config class JwtUtil(object): @staticmethod def create_token(username): payload = { "iat": int(time.time()), "exp": int(time.time()) + 86400 * 7, "username": username, "scopes": ['open'] } token = str(jwt.e...
988,339
0da7db33f7b7c1f09747e234f7d39c01386d547c
from state_machine import State,Event,acts_as_state_machine,after,before,InvalidStateTransition @acts_as_state_machine class Process: created=State(initial=True) waiting=State() running=State() terminated=State() blocked=State() swapped_out_waiting=State() swapped_out_blocked=State() wait = Event(fro...
988,340
873afe542c4d17b2e530eb07917ff5884ea6b544
import sys from parser import * ST = [] truthTable = ["True"] class STV: def __init__(self, ident, lineNum): self.ident = ident self.lineNum = lineNum def verify(ident, lineNum): global ST verified = False for x in range(0,len(ST)): if(ident == S...
988,341
dd7a909c3891ad761d91e8a2fe37cd6fe009c2a4
#!/usr/bin/env python """ recognizer.py is a wrapper for pocketsphinx. parameters: ~lm - filename of language model ~dict - filename of dictionary ~mic_name - set the pulsesrc device name for the microphone input. e.g. a Logitech G35 Headset has the following device name: alsa_input.usb-L...
988,342
16fafa4284e597a2a01e213ced28df989d564c9d
from django.contrib.auth.models import User from rest_framework import generics, permissions from oauth2_provider.contrib.rest_framework import (TokenHasReadWriteScope, TokenHasScope) from api.models import Product, Address from api.serializers import ProdListSerializer, ManufacturerSerializer, AdressSerializer, ProdDe...
988,343
1e95b27ce7d7d91d1c0b02a5ad1dc1a6aa715772
from main.fusioncharts import FusionCharts from main.models import * from main.apis import get_customer_used,get_customer_money def customer_used_chart(customer=None,r = 12): times = Month.objects.all() top_times = times[:r] top_times = top_times.reverse() labels = [{'label': '%s / %s'%(time.month,tim...
988,344
d5ded2130fe21dbac19bc4d6587dd1f2626fe84c
dic = {1,2,3,4,7,5} sum = 0 for i in dic: sum = sum + i print(sum)
988,345
3e266941ac2420c79cc51da63d1b82470156d81f
import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg import csv import sys tmp = [] with open('jk3.xyz') as csvfile: r = csv.reader(csvfile, delimiter=' ') # header = next(r) for line in r: p = list(map(float, line)) #-- convert each str to a float tmp.append...
988,346
fa8a0890dfb994c6fc210d652b148aaac555463c
from __future__ import print_function import os from bleualign.align import Aligner if __name__ == '__main__': current_path = os.path.dirname(os.path.abspath(__file__)) options = { # source and target files needed by Aligner # they can be filenames, arrays of strings or io objects. 'srcfile':os.path.join(curre...
988,347
a183cd565e917668b11ffd6321d09d7e1e355460
""" Copyright (c) 2023, Florian GARDIN All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. """ from .constants import * class Melody: """ Main class to write a melody in MusicLang. A melody is a serie of notes ...
988,348
ef2dc3ca51f1027bc4c953fa212fec484defe9bb
story = "Harry is good.\nHe\tis ve\\ry good" print(story) # \n stands for new line # \t stands for an extra step # \\ add one backslash
988,349
7cc0e354ee70591104e4b3c5664da25fdc49a855
import pandas as pd import csv data_dir = "data/province_bps_crosswalk/" rows = [["province_code", "province"]] with open(data_dir+"pasted.txt", "r") as file: lines = file.readlines() line_num = 1 for line in lines: if line_num > 8: # roughly with eyes line = line.strip() if line.startswith("21"): num = 21 ...
988,350
317b40ae8161e838eca364679104dd3e4212ecf1
from main.utils.graph import get_connected_components from main.utils.read_csv import read_relationship_csv, read_grid_csv import main.utils.data_pathnames as data_pathnames import random import os import pickle def find_non_ancestor_same_comp_negatives(dict_grid2comp, dict_comp2grid, dict_comp2ancestors): ''' ...
988,351
f334ace0f62634e2103b7197416decb839d10be5
#!/usr/bin/env python3 """ Test the performance of the 2D costmap_monitor layer by sending a very large get plan cost service request. This is a useful baseline for comparing its performance with the 3D version. """ import sys import math import random import rospy import tf2_ros import tf2_geometry_msgs import tf.tra...
988,352
252b5415aeb413e64e87b927c93f63474bf5ce65
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Nov 5 20:59:18 2020 @author: Odegov Ilya """ import os import sys current_dir = os.path.dirname(os.path.realpath(__file__)) parent_dir = os.path.dirname(current_dir) if parent_dir not in sys.path: sys.path.append(parent_dir) from time import time...
988,353
3a97cbdbc6e4cef8fced45e4b97c1fce34bf20d4
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import copy import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload fr...
988,354
7fdb9d0813784f341760f30f7a9547884975133c
import unittest class TestEnvs(unittest.TestCase): """Tests for the environment generation methods.""" def test_grid_env(self): """ """ pass def test_merge_env(self): """ """ pass def test_ring_env(self): """ """ pass class T...
988,355
852cdcb1fd42958f436af3afe6972159f7585509
from analyse import read_data import numpy as np import matplotlib.pyplot as plt import glob def main(): plot_jupiter_stability() def plot_jupiter_stability(): filenames = [f for f in glob.glob('out/EJS_unfix/*') if f.endswith('.bin')] fig, [ax1,ax2] = plt.subplots(2, sharex=True, figsize=(6,4)) ...
988,356
26e8753696e8729abafd9a467f89773d5552b744
import torch from allennlp.nn.util import masked_softmax, masked_log_softmax from pytorch_pretrained_bert.modeling import BertPreTrainedModel, BertModel from torch import nn from torch.nn import functional as F from bert_model import layers class BertQAYesnoHierarchicalNegHalf(BertPreTrainedModel): """ BertF...
988,357
f1e5226200ec7f6fa7b9f2558cdc9619ca2ee8e4
import os import shutil def allFilePath(rootPath,allFIleList): fileList = os.listdir(rootPath) for temp in fileList: if os.path.isfile(os.path.join(rootPath,temp)): allFIleList.append(os.path.join(rootPath,temp)) else: allFilePath(os.path.join(rootPath,temp),allFIleList) ...
988,358
dd4dec785be6afdf9aeca4afe1d7ae13672178ff
# class PeopleName: # def __init__(self): # self._names = ["XiaoWang", "ZhangSan", "LiYuan"] # def __len__(self): # return len(self._names) # def __getitem__(self, position): # return self._names[position] # class DogName: # def __init__(self): # self...
988,359
749438bc042cc6a9b875dd56c27ef3d4f966f751
# Copyright 2015 The LUCI Authors. All rights reserved. # Use of this source code is governed under the Apache License, Version 2.0 # that can be found in the LICENSE file. """Checks recipes for stylistic and hygenic issues. Currently only checks that recipes only import python modules from a whitelist. Imports are n...
988,360
65d5db3a40f96abc95504efc9448ad80544d25b9
from my_task.main import app # 任务队列的链接地址 broker_url = "redis://127.0.0.1:6379/11" # 结果队列的链接地址 result_backend = "redis://127.0.0.1:6379/12" # 定时任务调度 app.conf.beat_schedule = { 'check_order_status': { # 指定定时执行的哪个任务 直接写任务名 'task': 'check_order', # 定时任务执行的周期 'schedule': 30.0, ...
988,361
df44982c5639196ddc656660b963a5c0fb71f111
import neo4j driver = neo4j.GraphDatabase().driver('bolt://0.0.0.0:7687', auth=('neo4j', 'dupablada')) def get_stops(tx): q = "MATCH (n:STOP) RETURN n;" return tx.run(q) def get_connections(tx, f, t): q = "MATCH (f:STOP{name:'%s'}), (t:STOP{name:'%s'})" %(f,t) \ + " WITH f,t" \ + " MA...
988,362
974e970ed7cf5a0c33d8c37bcb42def346223a0c
'''Crie um programa que vai ler vários números e colocar em uma lista. Depois disso, mostre: A) Quantos números foram digitados. B) A lista de valores, ordenada de forma decrescente. C) Se o valor 5 foi digitado e está ou não na lista.''' numero = list() while True: n = int(input("Digite um valor: ")) if n not ...
988,363
5f3fc33169ee3ed427ad3de372c9407b2a3a2501
# ### Scaling and Resizing # # cv2.resize(image, dsize(output image size), x scale, y scale, interpolation) # # Import necessary libraries import cv2 import numpy as np # Read/load input image input_image = cv2.imread('62274667.jpg') cv2.imshow('Original Image', input_image) cv2.waitKey() # Making image 1/2 of it's...
988,364
4626698fce1c071893fe394d51c9d3159138fd3a
from .replay import ReplayMemory
988,365
7f5e8496aa695e841d0218d759054bc6d7d5f71c
import copy def Floyd(graph: list) -> list: ''' 弗洛伊德算法:最短路径 :param graph: whole graph :return: the graph of shortest paths ''' short_graph = copy.deepcopy(graph) n = len(graph) for k in range(n): for i in range(n): for j in range(n): print('Comparing s...
988,366
7f763bef98df0475675942884c4e17e1e5f0a558
from ..utils import extract_initial_data def test_index_no_login_no_data(app_blank_db): client = app_blank_db.test_client() response = client.get('/') assert response.status_code == 200 initial_data = extract_initial_data(response.data.decode()) assert initial_data is not None assert 'pins' ...
988,367
a24f798ae63d2c794b87f36ec35df5b48e4ddf88
from Graph import Graph def test_all_path(): graph = Graph.Graph() graph.add_path('June', 'Mary', 'cast away') path = graph.print_graph(None) assert path == ['June', 'Mary'] def test_from_one_path(): graph = Graph.Graph() graph.add_path('June', 'Mary', 'cast away') path = graph.print_gra...
988,368
41fc518152226477c57bd8a58705abb9dcd831c1
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None import queue class Solution: def verticalTraversal(self, root: TreeNode) -> List[List[int]]: levels = queue.Queue() nodes = queue.Queue(...
988,369
04abd810137376eb2938c3f0569805dd2dcf5365
# Name: Sergiy Ensary, Kyle Moses # Date: October 31st # Course: COSC 2316 Fall 2019 (Dr. Shebaro) # Program Description: Character Creation ######### Algorithm/Psuedocode ######## # 1. Menu to let user create or load a character or exit # 2. Method to ask for a player name # 3. Method to ask for a player gender # 4....
988,370
aa43ba4a40e1ecc12f07eda1f7f224fb15a9afbf
import facemesh as fm import cv2 def main(): #Instantiate the class fullSet = "C:/Users/fleis/Desktop/portraits" testSet = "C:/Users/fleis/Desktop/test" faceReader = fm.FaceMesh("shape_predictor_68_face_landmarks.dat") outputImgs = faceReader.align(fullSet) #Save all the alined images to outp...
988,371
651a7937a14eaf0a6e7e23590ddbdc285951a71f
# import datetime # import os # from datetime import datetime # import time # # from apscheduler.schedulers.blocking import BlockingScheduler # # # def TimeStampToTime(timestamp): # timeStruct = time.localtime(timestamp) # return time.strftime("%Y-%m-%d %H:%M:%S", timeStruct) # # # def get_FileCreateTime(filePath):...
988,372
899530e5a05c24a0204c69aef2ce28780946cfea
#!/usr/bin/env python """ Computes the min/max FMCW beat frequency expected for a given range vs. sweep time and RF bandwidth You might consider planning your sweep frequency and beat frequencies to land within the range of a PC sound card, say 200Hz - 24kHz (I try to avoid 60,120,180Hz for powerline harmonics) Refs:...
988,373
f4d86fa94038b2d22b83fce054179d810d75fc15
import numpy as np import torch from torch import nn from .head import NerdHead from .ops import init_weights from transformers import BertModel class NerdEncoder(nn.Module): def __init__(self): super().__init__() self.bert = BertModel.from_pretrained("hfl/chinese-roberta-wwm-ext") ...
988,374
96536f60f15b9f5683991a191ebbab88d9b67ea7
from flask import Flask ,render_template ,request import sys from dbconnect import connection import gc row=[3,3,4,4,5,6,10] col=[3,4,4,5,5,6,10] app = Flask(__name__) @app.route('/') def homepage(): return render_template('regular.html',h=2,r=2) @app.route('/regular/<int:t>') def regular(t): h=row...
988,375
fb5f87737a8d6c5987e26b272506f90add51be04
import random class QLearning(): # Learning Rate determines how quickly the agent tries to learn (closer to 0 means considering less info while closer to 1 means only considering more recent info) # Discount Rate determines how valuable the agent thinks each reward is (closer to 0 means considering short t...
988,376
a0537a16993d1424dfc38139d6d8679eb460559f
# encoding: UTF-8 import re import json import datetime # ro = {} # # p_text = re.compile(r'text\': u\'(\S+)\'') # for i in p_text.findall(str(ro)): # print i.decode('unicode_escape') # # p_resourceid = re.compile(r'resource-id\': u\'(\S+)\'') # for i in p_resourceid.findall(str(ro)): # print i # # #作者微信:25019...
988,377
7fa7a102a5f4ddabc868aa9b5f373affc240b98e
from __future__ import absolute_import from __future__ import division from __future__ import print_function from keras import Input, Model from keras.layers import Wrapper from attention import Attention, SelfAttention from ffn import FeedFowardNetwork from embedding import EmbeddingSharedWeights from model_utils im...
988,378
9f8636d86bc78ef879bfcf356750280aafe7be21
''' To drive mysql in Python3.x. Need mysqlclient # pip install mysqlclient ''' import pymysql pymysql.install_as_MySQLdb() # default_app_config = 'MetalFighter.apps.MetalfighterConfig'
988,379
4b3654ffe11c7ad4f4b9cf90fe0d271e7c52785b
import os, sys def make_fmt(formatter, specials): return lambda item: specials.get(item, formatter(item)) def make_seq_fmt(sep, item_fmt=str): return lambda items: sep.join([item_fmt(i) for i in items]) class ReadWrite: """ Utility class for Google CodeJam. Handles input/output, counting and f...
988,380
d502032c09e03a3205afd77173e8f96cfea37693
import os import matplotlib.pyplot as plt ppscanno_knl_folder = '/home/yche/mnt/luocpu8/nfsshare/share/python_experiments/ppSCANNO_knl' ppscan_knl_folder = '/home/yche/mnt/luocpu8/nfsshare/share/python_experiments/scalability_simd_paper2' thread_num_knl = 256 ppscanno_gpu23_folder = '/home/yche/mnt/gpu-23/projects/py...
988,381
1f6b0f2652081cdbb79075d23573a17d640f5829
from typing import List from pyVmomi import pbm, vim, vmodl from pyVmomi.VmomiSupport import ManagedObject class ReplicationManager(ManagedObject): def QueryReplicationGroups(self, entities: List[pbm.ServerObjectRef]) -> List[QueryReplicationGroupResult]: ... class QueryReplicationGroupResult(vmodl.DynamicData)...
988,382
0b898e0ad39cf756b7c395715e3b1ecd5e374565
from unittest import TestCase from simplefsabstraction import SimpleFS class TestSimpleFS(TestCase): def test_allowed_extension_fails(self): self.assertFalse(SimpleFS._check_extension('abc.png', ['jpg'])) def test_allowed_extension_succeed(self): self.assertTrue(SimpleFS._check_extension('ab...
988,383
b01973ba98ae2dc194ee68c83f7c971961dcff17
import sys sys.path.append('..') import numpy as np import os import argparse import numpy as np from dataset import * from objects import * from proposal import * import multiprocessing import shutil import matplotlib.pyplot as plt import copy import joblib def hit_target_in_path(zone_graph, depth, max_depth): ...
988,384
7272866a3fdc9fd3f7b6b7dc5ea3d1b2d9ee5d9e
'''Проверить, является ли введенная строка палиндромом. Палиндром - это слово, которое одинаково читается слева-направо и справа-налево''' message = input('Введите что-то: ').strip() print(message == message[::-1])
988,385
d9b232bc5946f73450f84a8916d18eb7ea151270
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2020 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/LICE...
988,386
66c5e566063525eb70aad8ff66b861bde3f5f246
import os b2c_tenant = os.getenv('TENANT_NAME') signupsignin_user_flow = os.getenv('SIGNUPSIGNIN_USER_FLOW') editprofile_user_flow = os.getenv('EDITPROFILE_USER_FLOW') resetpassword_user_flow = os.getenv('RESETPASSWORD_USER_FLOW') # Note: Legacy setting. # If you are using the new # "Recommended user flow" (https://...
988,387
9d87e0cf841a0a585c1d9d6f0593f3920ea98201
from datetime import datetime from pytz import timezone class Workbook: tz = timezone('Europe/Minsk') def __init__(self, user_id, user_first_name, subject, link, last_modified=None): self.user_id = user_id self.user_first_name = user_first_name self.subject = subject self.link...
988,388
f0954e8341fe9066968860a72d3663484251a3e8
from generics.utils import extract_a from generics.spiders import JAVSpider from . import get_article, article_json def studios(links): for url, t in extract_a(links): studio = get_article(url, t) article_json(studio) yield studio class StudioListSpider(JAVSpider): name = 'ave.studi...
988,389
f5ccf18e4d54b84a25cd4b327c4630549689ba4d
import math def is_int(n): return True if int(n) == n else False def dist(x, y): buf = 0 for i in range(len(x)): buf += (x[i] - y[i]) ** 2 return math.sqrt(buf) N, D = list(map(lambda a: int(a), input().split(" "))) X = [] for i in range(N): X.append(list(map(lambda x: int(x), input().split(" ")))...
988,390
4dd19f97f37ca5a2b53f6d09f127d40c75358f6d
# This scripts performs two split # The first group the labelled dataset per dialect and split into train, valid, # and test set. # The second does the same, but on the predictions from the entire twitter # module. ### Settings ################################################################# dataset_path = "data/tw...
988,391
b09012d71666be3f47ca1966a471a36642061a57
import numpy as np from os import listdir from os.path import isfile, join import pandas as pd import matplotlib.pyplot as plt from FFClust import IOFibers def get_list_of_files(directory): files = [f for f in listdir(directory) if isfile(join(directory, f))] dirs = [f for f in listdir(directory) if not isfile...
988,392
adf12dfc176142afee4e33f3943507654e29d758
#!/usr/bin/env python # # Project: Video Streaming with Flask # Author: Log0 <im [dot] ckieric [at] gmail [dot] com> # Date: 2014/12/21 # Website: http://www.chioka.in/ # Description: # Modified to support streaming out with webcams, and not just raw JPEGs # Modified by Jeff Bryant to support finding faces usin the Ope...
988,393
26911cc0ea0e86cf0be4add7d0ce5f537d26270e
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'dlgscore.ui' # # Created by: PyQt5 UI code generator 5.9 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Dialog(object): def setupUi(self, Dialog): Dialog...
988,394
51207780e4adf7aeded6eb5d2ce3ca4054e6ca7a
# Copyright 2011 Google 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 writing,...
988,395
b9023455b6737907164e56449465dfc1a4d5ed7c
from functools import wraps from flask import current_app, request, redirect, flash, url_for from flask_login import current_user def admin_required(func): @wraps(func) def decorated_view(*args, **kwargs): if not current_user.is_authenticated: return current_app.login_manager.unauthorize...
988,396
1be9d6a9c8a0dc1fbb744f1e07d6734afcd0cc56
t=int(input()) for i in range(0,t): x=input() n,m=x.split() n=int(n) m=int(m) if m%n==0: print("Yes") else: print("No")
988,397
d6ad08f853d524e0a028b2dea3291bc1374174bc
print "Hello, twat"
988,398
cec241f7477c9e2d069f07b1ebdbb3d35802bbef
import turtle import pandas screen = turtle.Screen() screen.title("U.S. States Game") image = "blank_states_img.gif" screen.addshape(image) turtle.shape(image) data = pandas.read_csv("50_states.csv") all_states = data.state.to_list() text = turtle.Turtle() text.hideturtle() text.penup() guessed_stat...
988,399
7d40de7e0b1173fd98fa49ab6de9ad28dc4d91c0
# -*- coding:utf-8 -*- # @Time : 2020/3/9 19:33 # @Author: wsp # 函数的参数 # 1.位置参数 def power(x): return x * x print(power(5)) # 递归函数:理论上所有的递归函数都可以写成循环函数,但是循环函数没有递归函数的逻辑清晰。 # point:使用递归时要注意防止栈溢出,在计算机中函数的调用是通过栈这种数据结构实现的,每当进入一个函数调用, # 栈就会加一层栈帧,每当函数返回,栈就会减一层栈帧。由于栈的大小不是无限的,所以,递归调用的次数过多,会导致栈溢出。可以试试fact(1000): def fa...