text
string
size
int64
token_count
int64
# Crie um programa que leia a idade e o sexo de várias pessoas. A cada pessoa cadastrada, o programa deverá perguntar se o usuário quer ou não continuar. No final, mostre: # A) Quantas pessoas tem mais de 18 anos. # B) Quantos homens foram cadastrados. # C) Quantas mulheres tem menos de 20 anos. maisdezoito = 0 qtdmul...
1,683
644
import filecmp import shutil import tempfile import os from .context import entry TEST_ENTRY = os.path.join(os.path.dirname(__file__), "test_entry.md") TEST_ENTRY_CONTENT = """ Some content. ## A section in the content Content that looks like frontmatter: ``` +++ but this is not really frontmatter +++ ``` More c...
3,050
1,107
import random from PyQt5.QtCore import pyqtSignal, pyqtProperty, pyqtSlot, QObject class WindowController(QObject): label_changed = pyqtSignal() def __init__(self, app): super().__init__() self._app = app self._qml_engine = None self._label = 'whatever' self._figure =...
1,833
617
from training.emotional_training import emotional_training from training.facial_training import facial_training def train(): print('\n0: Emotional Training') print('1: Facial Training\n') choose = int(input("Type Number > ")) if choose == 0: emotional_training() if choose == 1: f...
337
103
import os from pathlib import Path import numpy as np # repack_fields is necessary since np 1.16 as selecting columns from a recarray returns an array with padding # that is difficult to work with afterwards. from numpy.lib import recfunctions as rf from nnaps.mesa import fileio from nnaps import __version__ def re...
9,190
2,571
#compdef deblaze.py local arguments arguments=( '--version[show programs version number and exit]' '(- * :)'{-h,--help}'[show this help message and exit]' {-u,--url}'[URL for AMF Gateway]' {-s,--service}'[remote service to call]' {-m,--method}'[method to call]' {-p,--params}'[parameters to send pipe seper...
1,022
352
import random, copy import cv2 as cv import numpy as np from scipy import interpolate from .augmenter import Augmenter class WhiteBalancer(Augmenter): ''' Augmenter that randomly changes the white balance of the SampleImages. ''' def __init__( self, min_red_rand, max_red_rand, min_blue_rand, ...
1,379
578
from .card import Card from .features import Number, Color, Shape, Style from math import floor class Deck(): def __init__(self): return @staticmethod def get_card_by_id(self, id): if id < 1 or id > 81: raise ValueError return Card( self.get_number(id), ...
824
278
from langpractice.utils.utils import * import unittest import torch.nn.functional as F class TestUtils(unittest.TestCase): def test_zipfian1(self): n_loops = 5000 low = 1 high = 10 order = 1 counts = {i:0 for i in range(low, high+1)} tot = 0 for i in range(n_...
27,777
10,163
#!/usr/bin/env python3 from .entity import Entity, EntitySchema, Base from sqlalchemy import Column, Integer, String, Sequence from marshmallow import Schema, fields, post_load class GitRepo(Entity, Base): __tablename__ = 'git_repo' id = Column(Integer, Sequence('git_repo_id_seq'), primary_key=True) des...
1,626
538
import torch import torch.nn as nn from torch.nn.utils import weight_norm """TCN adapted from https://github.com/locuslab/TCN""" class Chomp1d(nn.Module): def __init__(self, chomp_size): super(Chomp1d, self).__init__() self.chomp_size = chomp_size def forward(self, x): return x[:, :, ...
4,415
1,539
''' Author: your name Date: 2021-04-08 17:14:41 LastEditTime: 2021-04-09 09:13:28 LastEditors: Please set LastEditors Description: In User Settings Edit FilePath: \github\test\index.py ''' #!user/bin/env python3 # -*- coding: utf-8 -*- import psutil cpu_info = {'user': 0, 'system': 0, 'idle': 0, 'percent': 0} memo...
1,868
701
""" 编写一个算法来判断一个数 n 是不是快乐数。 「快乐数」定义为: 对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和。 然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。 如果 可以变为  1,那么这个数就是快乐数。 如果 n 是快乐数就返回 true ;不是,则返回 false 。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/happy-number 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ from typing import List class Solution: de...
1,592
803
from profileHelper import ProfileHelper from pybricks.parameters import Button, Color from pybricks.media.ev3dev import Image, ImageFile, Font, SoundFile # from UI.tools import Box class UIObject: def __init__(self, name: str, brick: EV3Brick, bounds: Box, contentType, content, padding=(0, 0, False), font=Font(f...
2,309
688
import os from types import SimpleNamespace import torch from torch.utils.data import DataLoader from torchvision import transforms from PIL import Image import numpy as np from tensorfn import distributed as dist, nsml, get_logger try: from nvidia.dali.pipeline import Pipeline from nvidia.dali im...
9,558
3,413
#!/usr/bin/env python # Converts moses phrase table file to HDF5 files # Written by Bart van Merrienboer (University of Montreal) import argparse import cPickle import gzip import sys import tables import numpy parser = argparse.ArgumentParser() parser.add_argument("input", type=argparse.FileTy...
2,990
923
""" Given an array of integers arr, write a function that returns true if and only if the number of occurrences of each value in the array is unique. Example: Input: arr = [1,2,2,1,1,3] Output: true Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two value...
1,137
406
from playground.common.os import isPidAlive from playground.common import CustomConstant as Constant from .NetworkManager import NetworkManager, ConnectionDeviceAPI, RoutesDeviceAPI import os, signal, time class PNMSDeviceLoader(type): """ This metaclass for PNMS device types auto loads concrete devic...
9,360
2,646
import enum """Declare all enumerations used in test.""" class ProjectConstants(enum.Enum): """All constants for project test.""" SUCCESS = 'success'
162
48
import os import pandas as pd import numpy as np from core.dataset import dataset_fn from core.model import model_fn, get_classification_model from core.mmdd import trainer_object_fn from core.muks import muks def stderr_proportion(p, n): return np.sqrt(p * (1-p) / n) def eval(exp_dir, exp_name, param...
3,315
1,082
import tornado.web import json from handlers.async_fetch import async_fetch, GET, POST class ProductAddHandler(tornado.web.RequestHandler): async def post(self): request_data = json.loads(self.request.body) data = { 'prod_id': request_data['product_id'], 'comp_id': request_d...
1,423
420
# 141, Суптеля Владислав # 【Дата】:「09.04.20」 # 17. Клас Покупець: Прізвище, Ім'я, По батькові, Адреса, Номер кредитної картки, Номер банківського рахунку; конструктор; # Методи: установка значень атрибутів, отримання значень атрибутів, висновок інформації. Створити масив об'єктів даного класу. # Вивести список покупців...
3,144
1,094
import numpy import pytest from openmm import unit from pydantic import ValidationError from absolv.models import ( DeltaG, EquilibriumProtocol, MinimizationProtocol, SimulationProtocol, State, SwitchingProtocol, System, TransferFreeEnergyResult, ) from absolv.tests import is_close cl...
7,344
2,741
import django_tables2 as tables from django_tables2.utils import A from entities.models import * from archiv.models import * class ArchResourceTable(tables.Table): id = tables.LinkColumn( 'archiv:archresource_detail', args=[A('pk')], verbose_name='ID' ) title = tables.LinkColumn( '...
868
253
# Generated by Django 3.0.3 on 2020-02-27 04:18 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('accounts', '0004_auto_20200226_2329'), ] operations = [ migrations.AlterModelOptions( name='usersocialnetwork', options={'ve...
376
138
# -*- coding: utf-8 -*- import multiprocessing from gensim.models import Word2Vec import csv def embedding_sentences(sentences, embedding_size = 64, window = 3, min_count = 0, file_to_load = None, file_to_save = None): ''' embeding_size Word Embedding Dimension window : Context window min_count : Word f...
3,745
1,221
import itertools import typing from collections import defaultdict from typing import Optional, List, Callable, Type from hearthstone.cards import MonsterCard, CardEvent, Card from hearthstone.events import BuyPhaseContext, EVENTS from hearthstone.hero import EmptyHero from hearthstone.monster_types import MONSTER_TYP...
10,914
3,538
# ------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. # ----------------------------------------------------------------------...
12,743
3,638
#! /usr/bin/env python3 ############################################################################### # File Name : l4e3.py # Created By : Félix Chiasson (7138723) # Creation Date : [2015-10-06 11:43] # Last Modified : [2015-10-06 11:56] # Description...
1,146
362
#!/usr/bin/env python # -*- coding: UTF-8 -*- import string import pandas as pd from pandas import DataFrame from base import BaseObject class TextQueryWindower(BaseObject): """ Window Text Query Results """ __exclude = set(string.punctuation) def __init__(self, query_results: d...
2,984
886
from L1TriggerConfig.CSCTFConfigProducers.CSCTFObjectKeysOnline_cfi import * from L1TriggerConfig.DTTrackFinder.L1DTTFTSCObjectKeysOnline_cfi import * from L1TriggerConfig.RPCTriggerConfig.L1RPCObjectKeysOnline_cfi import * from L1TriggerConfig.GMTConfigProducers.L1MuGMTParametersKeysOnlineProd_cfi import * from L1Trig...
683
248
# https://www.hackerrank.com/challenges/ctci-making-anagrams from collections import Counter def number_needed(a, b): aCounts = Counter(a) bCounts = Counter(b) aSet = set(aCounts) bSet = set(bCounts) similar = aSet.intersection(bSet) differences = aSet.symmetric_difference(bSet) matchingK...
640
215
n = int(input()) numbers = list(map(int, input().split())) add, sub, mul, div = map(int, input().split()) def dfs(now, i): global max_num, min_num, add, sub, mul, div if i == n: max_num = max(max_num, now) min_num = min(min_num, now) else: if add > 0: add -= 1...
803
323
# Generated by Django 2.2 on 2020-11-27 13:57 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('store', '0002_auto_20201127_1945'), ] operations = [ migrations.AlterModelOptions( name='category', options={'verbose_name_plu...
497
168
from typing import Tuple import numpy as np from numpy import ndarray from dataclasses import dataclass, field from scipy.linalg import block_diag import scipy.linalg as la from utils import rotmat2d from JCBB import JCBB import utils import solution @dataclass class EKFSLAM: Q: ndarray R: ndarray do_asso...
19,141
6,733
""" MIT License Copyright (c) 2020 PyKOB - MorseKOB in Python Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, me...
3,185
1,070
import requests from bs4 import BeautifulSoup as bs4 from docx import Document as doc from docx.shared import Cm import sys if len(sys.argv) != 3: print("The format should be \n./main.py <url> <output_file_name>") else: url = sys.argv[1] doc_name = sys.argv[2] document = doc() page = requests...
3,333
813
""" https://www.codewars.com/kata/566fc12495810954b1000030/train/python Given an pos int n, and a digit that is < 10, d. Square all ints from 0 - n, and return the number times d is used in the squared results. """ def nb_dig(n, d): ''' results = '' for i in range(n+1): results += str(i * i) ...
583
293
"""Demo resource strategy class.""" # pylint: disable=no-self-use,unused-argument from typing import TYPE_CHECKING, Optional from oteapi.models import AttrDict, DataCacheConfig, ResourceConfig, SessionUpdate from oteapi.plugins import create_strategy from pydantic import Field from pydantic.dataclasses import dataclas...
3,492
884
# This workaround makes sure that we can import from the parent dir import sys sys.path.append('..') from scrython.sets import Code import unittest import time promo_khans = Code('PKTK') khans = Code('KTK') class TestSets(unittest.TestCase): def test_object(self): self.assertIsInstance(khans.object(),...
1,480
507
import re def check(email): regex = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' if (re.fullmatch(regex, email)): return True else: return False
194
96
#!/usr/bin/env python3 import smtplib import time import configparser config = configparser.ConfigParser() config.read('/home/pi/Development/Python/InverterMQTT/emailcredentials.conf') email = config['credentials']['email'] password = config['credentials']['password'] to_email = config['credentials']['to_email'] # ...
1,587
516
#! /usr/bin/env python3 def func1(): f = open("test.txt", 'w') f.write("This is test") f.close() def func2(): with open("test.txt", 'r') as f: print(f.read()) import codecs def func3(): f = codecs.open("test.txt", 'w', 'utf-8', 'ignore') f.write("test func3") f.close() import os.path def func4(): ...
876
380
def run(msg: str) -> None: """ Print the message received parameters. """ print(msg) if __name__ == "__main__": message: str = "Zero commands Python to be typed!" run(message)
202
65
import logging from config.celery_configs import app from lib.sms import client as sms_client from lib.blockchain.pandora import Pandora from apps.user.models import UserProfile logger = logging.getLogger(__name__) @app.task def sync_monthly_billing(): logger.info("start sync_monthly_billing") accounts = Use...
702
228
'''Given a valid IP address, return a defanged version of that IP address. A defanged IP address replaces every period '.' with "[.]". Input Format A string Constraints non-empty String Output Format replacement String Sample Input 0 1.1.1.1 Sample Output 0 1[.]1[.]1[.]1 Sample Input 1 255.100.50.0 Sample Out...
449
182
from django.conf import settings from django.urls import path, re_path from django.views.static import serve from .views import * urlpatterns = [ re_path('^$', MainView.as_view(), name='main_view'), path('page/<int:page>/', MainView.as_view(), name='main_view_with_page'), re_path('^signup/$', UserRegistr...
4,981
1,764
import numpy as np import cv2 import os cap = cv2.VideoCapture(0) #model=cv2.CascadeClassifier(os.path.join("haar-cascade-files","haarcascade_frontalface_default.xml")) smile=cv2.CascadeClassifier(os.path.join("haar-cascade-files","haarcascade_smile.xml")) #eye=cv2.CascadeClassifier(os.path.join("haar-cascade-files",...
1,372
620
from inspect import signature def testFunction(a, b=None): pass class TestClass: def testMethod(me): pass if __name__ == '__main__': #sig = signature(testFunction) sig = signature(TestClass.testMethod) for key in sig.parameters: param = sig.parameters[key] print(key, p...
375
119
import os import sys from argparse import _SubParsersAction sys.path.append(os.path.abspath(os.path.join(__file__, '..', '..'))) from vee.commands.main import get_parser def get_sub_action(parser): for action in parser._actions: if isinstance(action, _SubParsersAction): return action pa...
1,371
447
#imports from routing_methods import on_launch, intent_router ############################## # Program Entry ############################## #lambda_handler (this is like main()) def lambda_handler(event, context): #event is a python dictionary #LaunchRequest is an object that means the user made a request to ...
551
139
# coding: utf-8 import os import thriftpy import json import logging from thriftpy.rpc import make_client from xylose.scielodocument import Article, Journal LIMIT = 1000 logger = logging.getLogger(__name__) ratchet_thrift = thriftpy.load( os.path.join(os.path.dirname(__file__))+'/ratchet.thrift') articlemeta_t...
13,303
3,325
from operator import sub import numpy as np from sklearn import metrics from sklearn.neighbors import NearestNeighbors from toolz import curry def global_false_nearest_neighbors(x, lag, min_dims=1, max_dims=10, **cutoffs): """ Across a range of embedding dimensions $d$, embeds $x(t)$ with lag $\tau$, finds a...
6,705
2,269
import unittest from unittest import IsolatedAsyncioTestCase from websites_metrics_collector.communication import webpages_fetcher class Test(IsolatedAsyncioTestCase): """ This Class tests the fetch_list_of_urls() async method used to fetch URLs """ async def test_a_fetch_with_valid_list_of_url(self): ...
2,026
705
#!/usr/bin/python import random import Gnuplot # Python 2 only from planegeometry.structures.points import Point from planegeometry.structures.segments import Segment gnu = Gnuplot.Gnuplot (persist = 1) visible = True for i in range(10): segment = Segment(random.random(), random.random(), random.random...
773
277
from django.contrib import admin # NOQA: F401 # Register your models here.
77
26
import python_speech_features as psf import soundfile as sf # import scipy.io.wavfile as wav import pickle as pkl import sys import os import re # linux to windows 路径转换 def path_lin2win(path): pattern = "/[a-z]/" position = re.findall(pattern,path)[0][1].upper() return re.sub(pattern,"%s:/"%pos...
1,050
470
def fake_response_from_file(file_name, url=None, meta=None): import os import codecs from scrapy.http import HtmlResponse, Request if not url: url = 'http://www.example.com' _meta = {'mid': 1291844, 'login': False} # 必要的信息,随便弄一个就行了 if meta: meta.update(_meta) else: ...
1,344
461
from pyning.combinationdict import CombinationDict import pytest def test_key_at_root_is_located(): items = CombinationDict( '/', { 'a': 10 } ) assert items[ 'a' ] == 10 def test_key_nested_1_level_is_located(): items = CombinationDict( '/', { 'a': { 'b': 10 } } ) assert items[ 'a/b' ] == 10 def ...
2,703
1,163
#!/usr/bin/env python3 # -*- coding:utf-8 -*- from bs4 import BeautifulSoup import requests from requests import post from requests import codes def information(symbol): URL = "https://goodinfo.tw/StockInfo/StockDetail.asp?STOCK_ID="+ symbol headers = {'user-agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit...
6,917
2,979
import os import shutil from datetime import datetime # INPUT PARAMS LDAP_URL = os.environ['TEST_LDAP_URL'] LDAP_BASE_DN = os.environ['TEST_LDAP_BASE_DN'] LDAP_ADMIN_DN = os.environ['TEST_LDAP_ADMIN_DN'] LDAP_ADMIN_PASSWORD = os.environ['TEST_LDAP_ADMIN_PASSWORD'] LDAP_BIND_TIMEOUT = os.environ.get('TEST_LDAP_BIND_TIM...
6,781
2,692
from concurrent.futures import ThreadPoolExecutor from tornado.concurrent import run_on_executor from webargs import fields from webargs.tornadoparser import use_args from loguru import logger from http_utils.base import BaseHandler, MAX_THREADS class TopPopularRecommendationHandler(BaseHandler): executor = Threa...
1,377
443
# Description: DSSR block representation for a multi-state example after loading the dssr_block.py script by Thomas Holder. The x3dna-dssr executable needs to be in the PATH. Edit the path to Thomas Holder's block script. # Source: Generated while helping Miranda Adams at U of Saint Louis. """ cmd.do('reinitialize;'...
662
267
import asyncio import logging import binascii import socket import os.path import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.components.climate import (DOMAIN, ClimateDevice, PLATFORM_SCHEMA, STATE_IDLE, STATE_HEAT, STATE_COOL, STATE_AUTO, STATE_DRY, SUPPORT_OPERATION_MOD...
12,007
3,928
from dnastorage.codec.base_conversion import convertIntToBytes,convertBytesToInt from dnastorage.arch.builder import * import editdistance as ed #from dnastorage.primer.primer_util import edit_distance from io import BytesIO from dnastorage.util.packetizedfile import * import math import struct from dnastorage.system.f...
6,492
2,409
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import from functools import partial import numba as nb from numba.containers import orderedcontainer import numpy as np INITIAL_BUFSIZE = 5 def notimplemented(msg): raise NotImplementedError("'%s' method of type 'typedtuple'" % ...
2,386
763
import os.path __dir__ = os.path.split(os.path.abspath(os.path.realpath(__file__)))[0] data_location = os.path.join(__dir__, "sources") src = "https://github.com/lambdaconcept/minerva" # Module version version_str = "0.0.post260" version_tuple = (0, 0, 260) try: from packaging.version import Version as V pvers...
1,353
601
# GLOBAL PARAMETERS DATASETS = ['sent140', 'nist', 'shakespeare', 'mnist', 'synthetic', 'cifar10'] TRAINERS = {'fedavg': 'FedAvgTrainer', 'fedavg4': 'FedAvg4Trainer', 'fedavg5': 'FedAvg5Trainer', 'fedavg9': 'FedAvg9Trainer', 'fedavg_imba': 'FedAvgTrainerImba',...
1,602
583
# coding=utf-8 from argparse import ArgumentParser import os import model_train from torchvision import models def parse_argvs(): parser = ArgumentParser(description='GAN') parser.add_argument('--data_path', type=str, help='data_path', default='./data') parser.add_argument('--num_workers', type=int, help...
3,266
1,234
from random import randint print('-=-'*10) print('JOGO DO PAR OU IMPAR') cont = 0 while True: print('-=-' * 10) n = int(input('Digite um valor: ')) op = str(input('Par ou impar? [P/I] ')).upper().strip()[0] ia = randint(0, 10) res = n + ia print('-'*30) print(f'Você jogou {n} e o computador ...
854
349
from django.core.exceptions import ValidationError from django.shortcuts import render, get_object_or_404 from django.db import IntegrityError from rest_framework import authentication, generics, permissions, status from rest_framework.exceptions import PermissionDenied from rest_framework.response import Response fr...
5,506
1,539
import imaplib, base64, os, email, re, configparser import tkinter as tk from tkinter import messagebox from datetime import datetime from email import generator from dateutil.parser import parse def init(): mail = imaplib.IMAP4_SSL(config['SERVER']['Host'],config['SERVER']['Port']) pwd = str(input("PWD: ")) ...
1,873
656
# # This program is a function that displays the first 100 pentagonal numbers with 10 numbers on each line. # A pentagonal number is defined as n(3n - 1)/2 for n = 1, 2, c , and so on. # So, the first few numbers are 1, 5, 12, 22, .... def get_pentagonal_number(n): pentagonal_number = round(n * (3 * n - 1) / 2)...
539
214
from __future__ import absolute_import from __future__ import division from __future__ import print_function from ._0errors import * from ._0imports import * class Database: def __init__(self, database_name, vital=False, date_to_update='daily', force_update=False, ask_size=None): package_name = 'iracli...
4,075
1,226
""" Write a program that accepts a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sorting them alphanumerically. Suppose the following input is supplied to the program: hello world and practice makes perfect and hello world again Then, the output should be: ...
1,029
293
import os import cv2 import json import numpy as np import h5py from PIL import Image TASK_TYPES = {1: "pick_and_place_simple", 2: "look_at_obj_in_light", 3: "pick_clean_then_place_in_recep", 4: "pick_heat_then_place_in_recep", 5: "pick_cool_then_place_in_recep", ...
6,063
2,091
__author__ = 'bsha3l173' import logging import datetime from conf import LOG_FILENAME class Log(): logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG) def log_d(self, message, text): last_name = '' first_name = '' user_name = '' if not message.from_u...
846
290
import os, time, pyautogui import selenium from selenium import webdriver from location_reference import country_map # STATIC SETTINGS DPI = 125 # Scaling factor of texts and apps in display settings screen_dims = [x / (DPI/100) for x in pyautogui.size()] code_map = country_map() print("International Google Searc...
1,850
625
"""The thomson component."""
29
10
import csv from django.contrib import admin from django.http import HttpResponse from .models import Student, SchoolList, Event, ShsTrack, SchoolOfficial class ExportCsvMixin: def export_as_csv(self, request, queryset): meta = self.model._meta field_names = [field.name for field in meta.fields] ...
2,027
642
import hashlib from itertools import islice from aoc.util import load_input def search(door_id, is_part1=False, is_part2=False): i = 0 while True: md5_hash = hashlib.md5((door_id + str(i)).encode()).hexdigest() if md5_hash.startswith("00000"): if is_part1: yield md...
1,251
451
import math import random import os os.environ["PYGAME_HIDE_SUPPORT_PROMPT"] = "1" import numpy as np import pygame as pg WINDOW_SIZE = (800, 600) FPS = 60 pg.init() window = pg.display.set_mode(WINDOW_SIZE) clock = pg.time.Clock() font = pg.font.SysFont("monospace", 20) def make_circle_array(diameter, hue): ...
2,324
883
from flask import ( abort, Blueprint, current_app, flash, g, redirect, render_template, request, url_for ) import giphy_client from werkzeug.exceptions import abort from choosy.auth import login_required from choosy import db bp = Blueprint("star", __name__) @bp.route("/stars") @login_required def index(): ...
1,268
420
#!/usr/bin/env python3 # %% # Assignment Pt. 1: Edit Distances import numpy as np from bs4 import BeautifulSoup import math vocabulary_file = open('../res/count_1w.txt', 'r') lines = vocabulary_file.readlines() vocabulary = dict() word_count = 0 # Strips the newline character for line in lines: line = line.strip...
7,700
3,080
class KeytabFileNotExists(RuntimeError): """ Raised when a Kerberos keytab file doesn't exist. """ pass class KtutilCommandNotFound(RuntimeError): """ Raised when ``ktutil`` command-line interface not found. """ pass
251
78
def isacn(obj): """isacn(string or int) -> True|False Validate an ACN (Australian Company Number). http://www.asic.gov.au/asic/asic.nsf/byheadline/Australian+Company+Number+(ACN)+Check+Digit Accepts an int, or a string of digits including any leading zeroes. Digits may be optionally separated with...
2,451
1,229
#!/usr/bin/env python2.6 # -*- coding: utf-8 -*- from __future__ import print_function import optparse import path_resolv from path_resolv import Path def check_file(f, show_info, override_ignores): text = f.read() if ("@code standards ignore file" in text) and (not override_ignores): return if "...
2,845
886
import ply.lex as lex from grease.core.indents import Indents reserved = { 'var': 'VAR', 'if': 'IF', 'else': 'ELSE', 'scan': 'SCAN', 'print': 'PRINT', 'and': 'AND', 'or': 'OR', 'Bool': 'BOOL', 'Int': 'INT', 'Float': 'FLOAT', 'Char': 'CHAR', 'fn': 'FN', 'interface': '...
2,368
1,112
# _*_ coding: utf-8 _*_ from importlib import import_module def is_iterable(var): return hasattr(var, '__iter__') def to_iterable(var): if var is None: return [] elif is_iterable(var): return var else: return [var] def load_class_by_name(qualified_name): last_dot = qua...
768
259
import tempfile import pytest import fault as f import magma as m from fault.verilator_utils import verilator_version @pytest.mark.parametrize('success_msg', [None, "OK"]) @pytest.mark.parametrize('failure_msg', [None, "FAILED"]) @pytest.mark.parametrize('severity', ["error", "fatal", "warning"]) @pytest.mark.parame...
3,673
1,205
from flask import session from flask_restful import Resource from flask_restful.reqparse import RequestParser from bcrypt import gensalt, hashpw from hashlib import sha256 from hmac import new as hash_mac from os import environ PEPPER = environ["PEPPER"].encode("utf-8") def hash(password, salt): return ...
3,098
1,191
from astropy.coordinates import Angle from astropy.time import Time import astropy.units as u from astropy.tests.helper import assert_quantity_allclose from sunpy.sun import sun def test_true_longitude(): # Validate against a published value from the Astronomical Almanac (1992) t = Time('1992-10-13', scale='...
4,606
2,017
"""Pyup.io Safety metrics collector.""" from typing import Final from base_collectors import JSONFileSourceCollector from source_model import Entity, SourceMeasurement, SourceResponses class PyupioSafetySecurityWarnings(JSONFileSourceCollector): """Pyup.io Safety collector for security warnings.""" PACKAGE...
1,031
309
import json import os import typing from io import IOBase from jaf.encoders import JAFJSONEncoder class JsonArrayFileWriterNotOpenError(Exception): pass class JsonArrayFileWriter: MODE__APPEND_OR_CREATE = 'ac' MODE__REWRITE_OR_CREATE = 'rc' def __init__(self, filepath: str, mode=MODE__REWRITE_OR_C...
2,580
837
def remove_every_other(my_list): return [my_list[it] for it in range(0,len(my_list),2)]
91
37
from aip import AipOcr BAIDU_APP_ID='14490756' BAIDU_API_KEY = 'Z7ZhXtleolXMRYYGZ59CGvRl' BAIDU_SECRET_KEY = 'zbHgDUGmRnBfn6XOBmpS5fnr9yKer8C6' client= AipOcr(BAIDU_APP_ID, BAIDU_API_KEY, BAIDU_SECRET_KEY) options = {} options["recognize_granularity"] = "big" options["language_type"] = "CHN_ENG" options["detect_dire...
812
351
import unittest from unittest.mock import Mock from unittest.mock import mock_open from contextlib import contextmanager class TestDocumentDB(unittest.TestCase): def test_reads_articles(self): db = DocumentDB() expected = [ {'article_idx': 0}, {'article_idx': 1} ] ...
1,233
391
from tkinter import * import random from tkinter import messagebox class GuessGame: def protocolhandler(self): if messagebox.askyesno("Exit", "Really Wanna stop Guessing?"): if messagebox.askyesno("Exit", "Are you sure?"): self.root.destroy() def result(self): ...
4,596
1,703
import configparser import sys from jiraparser import JiraJSONParser, TokenAuth import requests from requests.auth import AuthBase """ Getting a list of issues connected to a board id (defined by configuration) and printing analysis information """ # read config config = configparser.ConfigParser() config.read("confi...
2,051
610
# -*- coding: utf-8 -*- import json import requests import logging import csv url = "http://localhost:10000/parse" def get_result(text, lang, dims, latent=None, reftime=None, tz=None): data = { "text": text, "lang": lang, "dims": json.dumps(dims) } if reftime is not None: ...
1,268
457