text
string
size
int64
token_count
int64
from quickkart_api import app from quickkart_api.models import Users from flask_jwt import JWT, jwt_required, current_identity from flask import abort def authenticate(username, password): user = Users.query.filter_by(username=username).first() if user and user.check_password(password): return user ...
497
144
# -*- coding: utf-8 -*- import sys, os # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinxcontrib.seometatwi...
1,665
514
from omnia_timeseries.api import TimeseriesAPI, TimeseriesEnvironment
69
17
from dimagi.utils.couch import CriticalSection from corehq.apps.receiverwrapper.util import submit_form_locally def form_requires_input(form): """ Returns True if the form has at least one question that requires input """ for question in form.get_questions([]): if question["tag"] not in ("tri...
799
252
import numpy as np from scipy.integrate import simps def get_wss_magnitude(wss_vector): if (wss_vector.shape[-1] != 3): return wss_vector return np.sum(wss_vector ** 2, axis=-1) ** 0.5 def get_tawss(wss, dt): x = np.arange(0, len(wss)) x = np.asarray(x) * dt wss_int = simps(wss, x, axis=...
1,531
724
#!/usr/bin/env python -OO # encoding: utf-8 ########### # ORP - Open Robotics Platform # # Copyright (c) 2010 John Harrison, William Woodall # # 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 Softwa...
6,511
2,051
import inspect import sys from uma import message from rrtest.check import Error, get_protocol_response from rrtest import Unknown from oictest import check __author__ = 'roland' CLASS_CACHE = {} class MatchResourceSet(Error): """ Verify that the returned resource set is as expected """ cid = "match...
1,661
440
import os import cv2 import glob import logging import numpy as np from pathlib import Path import torch from torch.autograd import Variable import torch.distributed as dist class strLabelConverter(object): def __init__(self, alphabet_): """ 字符串标签转换 """ self.alphabet = alphabet_ +...
10,959
3,964
#!/usr/bin/env python from smoothie.plugins.interfaces import run as interfaces from smoothie.plugins.list_networks import run as list_networks from smoothie.plugins.target_network import run as target_network
211
57
import asyncio import threading import time import pytest from aiohttp import ClientSession from mmpy_bot import Settings from mmpy_bot.threadpool import ThreadPool from mmpy_bot.webhook_server import NoResponse, WebHookServer @pytest.fixture(scope="function") def threadpool(): pool = ThreadPool(num_workers=1) ...
3,912
1,069
import urllib.request import json import pprint url = 'http://localhost:18080/kabusapi/ranking' #?type=1&ExchangeDivision=ALL params = { 'type': 15 } #type - 1:値上がり率(デフォルト)2:値下がり率 3:売買高上位 4:売買代金 5:TICK回数 6:売買高急増 7:売買代金急増 8:信用売残増 9:信用売残減 10:信用買残増 11:信用買残減 12:信用高倍率 13:信用低倍率 14:業種別値上がり率 15:業種別値下がり率 params['ExchangeDivisi...
1,023
590
from flask import Blueprint, jsonify, make_response from flask.views import MethodView from sfa_api import spec, json from sfa_api.schema import ZoneListSchema from sfa_api.utils.storage import get_storage from sfa_api.utils.request_handling import validate_latitude_longitude class AllZonesView(MethodView): def...
3,905
1,115
from random import randint n = (randint(1, 9), randint(1, 9), randint(1, 9), randint(1, 9), randint(1, 9)) print('Os números sorteados foram: ', end='') for c in n: print(c, end=' ') print(f'\nO maior valor sorteado foi: {max(n)}') print(f'O menor valor sorteado foi: {min(n)}')
283
117
import requests from localstack.http import Response, Router from localstack.http.adapters import RouterListener from localstack.utils.testutil import proxy_server class TestRouterListener: def test_dispatching(self): def endpoint(request, args): resp = Response() resp.set_json({"...
1,228
327
from cx_Freeze import setup, Executable import sys base = None if sys.platform == "win32": base = "Win32GUI" executables = [Executable("Archer.py", base=base, icon="favicon.ico")] setup(name="Archer", version="1.0.0", options={"build_exe": {"packages": ["tkinter", "mysql", "PIL", "time",...
647
240
# Übung 11 - Aufgabe 1 # Mitarbeiter-Kartei # Bereitgestellt von M. Drews im Wintersemester 2021/22 # Funktionen def trenner(anzahl_striche): for i in range(anzahl_striche): print("-", end="") print() def fehler(): print("\nFehler: Bitte geben Sie nur Zahlen an, die zur Auswahl stehen.") def ...
2,772
953
import maya.api.OpenMaya as om from . import asciitreemixin, asciiattribute, asciiplug from .collections import hashtable, weakreflist, notifylist import logging logging.basicConfig() log = logging.getLogger(__name__) log.setLevel(logging.INFO) class AsciiNode(asciitreemixin.AsciiTreeMixin): """ Overload of...
20,230
5,622
""" (c) Copyright 2015-2016 Hewlett-Packard Enterprise Company L.P. 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...
1,325
413
""" moviepy.video.fx.all is deprecated. Use the fx method directly from the clip instance (e.g. ``clip.resize(...)``) or import the function from moviepy.video.fx instead. """ import warnings from moviepy.video.fx import * # noqa F401,F403 warnings.warn(f"\nMoviePy: {__doc__}", UserWarning)
297
105
from .resource import * from .dist_manager import * from ...utils import get_cpu_count, get_gpu_count
102
32
class AppStartingMsg(object): '''应用程序启动消息''' def __init__(self): self.ErrorMsg = ""
101
41
print "This line will be printed." x = "rachel" if x == "rachel": print "Rachel" print "Hello, World!"
109
42
# pyonms.py from dao import api, alarms, events, nodes class pyonms(): def __init__(self, hostname, username, password): self.hostname = hostname self.api = api.API(hostname=hostname, username=username, password=password) self.nodes = nodes.Nodes(self.api) self.events = events.Eve...
434
140
""" Utility functions for Neural network """ import pandas as pd from keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint from sklearn.preprocessing import StandardScaler from keras.layers import Dense, BatchNormalization, Input, LeakyReLU, Dropout from keras.models import Model, load_model from ke...
5,195
2,108
"""============================================================= ~/fn_portal/fn_portal/tests/api/test_FN026.py Created: 26 May 2021 18:01:30 DESCRIPTION: This file contains a number of unit tests that verify that the api endpoint for FN026 objects works as expected: + the fn026 list returns all of the spaces...
2,809
1,034
# Copyright Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompan...
13,534
4,483
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import with_statement # Required in 2.5 import subprocess import os import fnmatch import gzip import re import commands import getopt import sys import signal import resource import time import struct import random from random import choice from subproces...
31,261
9,314
""" ******************************************************* * Copyright (C) 2017 MindsDB Inc. <copyright@mindsdb.com> * * This file is part of MindsDB Server. * * MindsDB Server can not be copied and/or distributed without the express * permission of MindsDB Inc **************************************************...
5,182
1,621
import pygame from random import randint from time import sleep import data SCREEN_SIZE = 700 STAGE_SIZE = 175 # 175 is largest size without bezels for 700 x 700 window sizeof_rect = int(SCREEN_SIZE / STAGE_SIZE) bezel = int((SCREEN_SIZE - (STAGE_SIZE * sizeof_rect)) / 2) def draw_bordered_square(x, y, f...
2,538
1,197
r""" latexnewfloat.py extension for latex builder to replace literal-block environment by \captionof{LiteralBlockNewFloat}{caption_title} command. For \captionof command (in capt-of pacakge), the new environment LiteralBlockNewFloat should be configured by newfloat pagage instead of original float package. needspace ...
3,494
1,031
""" Module to fetch and parse regional NIC delegation data """ import urllib.parse import ftplib import os from functools import lru_cache import socket import ipaddress from binascii import hexlify import tempfile TWD = tempfile.gettempdir() DELEGATES = [ # America (non-latin) "ftp://ftp.arin.net/pub/stats/a...
9,347
2,973
# -*- coding: utf-8 -*- from helper.resource import YuzukiResource from helper.template import render_template from config.config import SITE_DESCRIPTION from helper.content import markdown_convert_file class Index(YuzukiResource): def render_GET(self, request): with open("page/index") as f: c...
548
153
# -*- coding: utf-8 -*- """ Author : Jacques Flores Created : October 17th,2019 About: Script for creating datasets in Dataverse. An Empty JSON file with Dataverse structure is imported and converted into a JSON dict Metadata is imported from an excel file into a pandas dataframe and written into the ...
6,281
1,717
from flask_script import Manager, prompt_bool # from flask_migrate import Migrate, MigrateCommand from school_api.app import create_app from school_api.db import create_tables, drop_tables from school_api.data_generator import test_db """ Refused flask_migration because it was overkill for this project """ app = create...
778
257
p="\nTell me something, and I will repeat it back to you" p+="\nEnter 'quit' to end the program." active = True while active: message=input(p) if message =='quit': active = False else: print(message)
214
81
# Sample implementation of a custom layer info module def layer_info(layer, x, y, crs, params, identity): """Query layer and return info result as dict: { 'features': [ { 'id': <feature ID>, # optional 'attributes': [ ...
2,512
728
from google.auth.transport.requests import Request from googleapiclient.discovery import build from googleapiclient.errors import HttpError import google_auth_oauthlib.flow import logging import os class gCalIntegratinator: """ Object for handling interactions between RADSA and Google Calendar API. This ...
20,740
4,728
from random import choice from django.contrib import admin from pins.models import Batch, Pin from pins.forms import BatchForm def gen_randomdigits(size=10): return ''.join([choice('1234567890') for i in range(size)]) class BatchAdmin(admin.ModelAdmin): list_display = ('count', 'used', 'created_on', 'down...
933
300
def getMinFix(K, N, signals): if K == 1: if set(signals) == {False}: return 1 return 0 startInd = 0 endInd = K - 1 lastStart = signals[0] curCount = signals[0:K].count(False) minCount = curCount for _ in range(N-K): startInd += 1 endInd += 1 if not lastStart: curCoun...
961
374
''' Given an unsorted integer array, find the smallest missing positive integer. Example 1: Input: [1,2,0] Output: 3 Example 2: Input: [3,4,-1,1] Output: 2 Example 3: Input: [7,8,9,11,12] Output: 1 Note: Your algorithm should run in O(n) time and uses constant extra space. ''' class Solution: def firstMissingP...
752
280
""" Calculate the translational entropy with EW, HSM and IGM models """ import numpy as np import matplotlib.pyplot as plt from scipy import integrate plt.style.use("paper") ha2kjmol = 627.5 * 4.184 class Constants: hbar_au = 1.0 h_au = hbar_au * 2.0 * np.pi kb_au = 3.1668114E-6 # hartrees K-1 h_...
6,531
3,017
from .nlgsearch import templatize # NOQA: F401
53
22
############################################## # # Author: Aniruddha Gokhale # # Created: Spring 2022 # # Purpose: demonstrate a basic remote procedure call-based client # # A RPC uses message passing under the hood but provides a more # type-safe and intuitive way for users to make invocations on the remote # side bec...
5,300
1,343
import sys from PyQt5.QtWidgets import QApplication,QMainWindow,QDialog from PyQt5 import QtCore, QtGui, QtWidgets from ui.main_window import Ui_MainWindow # from login import Ui_dialog from lib.tcmd import TCmdClass # from SignalsE import Example class MyMainWindow(QMainWindow,Ui_MainWindow): def __init__(se...
1,305
443
# Copyright 2014-2015, Tresys Technology, LLC # # This file is part of SETools. # # SETools is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundation, either version 2.1 of # the License, or (at your option) any l...
1,675
477
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- """Description: """ import os import sys import comtypes.client try: ETABSObject = comtypes.client.GetActiveObject("CSI.ETABS.API.ETABSObject") print("Coneccion exitosa!.\nadjuntando a una instancia existente.") except (OSError, comtypes.COMError): ...
2,108
908
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("msgs", "0039_outgoing_text_non_null")] operations = [ migrations.AlterField( model_name="outgoing", name="backend...
826
252
#variables de entrada print("area del triangulo") #datos de entrada B=int(input("ingrese base:")) H=int(input("ingrese haltura:")) #proceso area=(B*H)/2 #datos de salida print("el area es: ", area)
197
79
from typing import Any, Optional from django.contrib.sessions.middleware import SessionMiddleware class SessionTestMixin: """Session Test mixin.""" def is_session_empty(self, request) -> int: """Check if request.session is empty.""" return len(request.session.values()) == 0 def assertSes...
1,756
468
import cloudpassage import provisioner import pytest import os here_dir = os.path.abspath(os.path.dirname(__file__)) fixture_dir = os.path.join(here_dir, "../fixture") class TestIntegrationHalo(object): def instantiate_halo_object(self, config): """Return an instance of the provisioner.Halo object.""" ...
2,930
951
import os import sys import boto3 import boto import moto import botocore import unittest import logging import re import sure import botocore.session from datetime import datetime from moto import mock_sns_deprecated, mock_sqs_deprecated from botocore.stub import Stubber from freezegun import freeze_time from mock imp...
22,665
7,399
import json from api.helper import json_405_response, json_error_response def no_test(func): """ Use for URLs that do not require testing, use wisely """ def inner(request, *args, **kwargs): return func(request, *args, **kwargs) inner.__name__ = func.__name__ inner.__module__ = func._...
1,929
577
''' Created on Apr 16, 2012 @author: Haak Saxberg ''' from django.core.management.base import BaseCommand, CommandError from django.core.exceptions import ObjectDoesNotExist from django.db.utils import IntegrityError from ...models import Campus, Course, Professor, Section, Meeting, Timeslot, Day, Semester,\ ...
16,484
4,339
import pandas as pd classificacoes = pd.read_csv('email.csv') textosPuros = classificacoes['email'] textosQuebrados = textosPuros.str.lower().str.split(' ') dicionario = set() for lista in textosQuebrados: dicionario.update(lista) totalPalavras = len(dicionario) tuplas = list(zip(dicionario, range(totalPalavras)...
858
332
import copy import os import pickle import unittest from unittest.mock import patch from dgcastle import dgcastle from dgcastle.exceptions import IncompleteException from dgcastle.exceptions import ValidationException from dgcastle.handlers.challonge import Challonge TEST_TOURNAMENT = pickle.loads(b'\x80\x03}q\x00(X\...
23,901
19,538
# uncompyle6 version 3.3.5 # Python bytecode 2.7 (62211) # Decompiled from: Python 3.7.3 (default, Apr 24 2019, 15:29:51) [MSC v.1915 64 bit (AMD64)] # Embedded file name: c:\Jenkins\live\output\win_64_static\Release\python-bundle\MIDI Remote Scripts\pushbase\step_duplicator.py # Compiled at: 2018-11-30 15:48:12 from _...
4,917
1,605
from django.db import models #Utilities from cride.utils.models import BetmatcherModel class Exchange(BetmatcherModel): user = models.ForeignKey( "users.User", on_delete = models.CASCADE, related_name = "user" ) prize = models.ForeignKey( "users.Prize", on_delete = models.CASCADE, rela...
1,058
371
# This macro allows changing the position of an external axis by hand or within a program as a function call. # Example of a function call (units are in mm or deg): # MoveAxis(0) # MoveAxis(100) # https://robodk.com/doc/en/RoboDK-API.html import sys # allows getting the passed argument parameters from robodk.rob...
1,540
479
import os.path import unittest from setup import iter_vendored_files class IterVendoredFilesTests(unittest.TestCase): def test_all(self): filenames = set(iter_vendored_files()) self.assertEqual(filenames, VENDORED) VENDORED = {file.replace('/', os.path.sep) for file in [ 'pydevd/pydev_run...
11,035
4,891
from psycopg2 import connect from psycopg2.sql import SQL, Identifier, Literal, Composed from collections import OrderedDict from itertools import count from pgcsv.util import normalize_column class Database(object): def __init__(self, uri, table, headers): self.conn = connect(uri) self.table = ...
3,126
818
##Rate Coefficients import numpy as np def k1(T): T_eV = T / 11605. log_T_eV = np.log(T_eV) rv = np.exp(-32.71396786375 + 13.53655609057*log_T_eV - 5.739328757388*log_T_eV**2 + 1.563154982022*log_T_eV**3 - 0.2877056004391*log_T_eV**4 + 0.03482559773736999...
4,629
2,964
import math import numpy as np FULL_RANGE = 1024 class VectoringThrusterData(object): def __init__(self, position, axis, start, angle, offset, _reversed = False): vector_axis = np.array(axis) vector_1 = np.array(start) self.vector_axis = vector_axis / np.linalg.norm(vector_axis) self.force_1 = vecto...
2,525
871
# XXX verification for bug 30828 - runs ice_pbdagcon on a spurious cluster # and checks that it discards the resulting all-N consensus sequence import subprocess import tempfile import unittest import os.path as op from pbcore.io import FastaReader CLUSTER_FA = """\ >m54007_151222_230824/47383194/334_64_CCS CATTGAA...
1,956
933
/home/runner/.cache/pip/pool/a5/a1/10/06eab95524f667caa51362a09c577fd5f6d45980e5390034745c0a322f
96
76
import unittest def banana(): "Yellow" return 42 def orange(): "Oran" "ge" def blackbirds(): 4 + 20 # Not a docstring def do_nothing(): pass def make_adder(n): "Function adding N" def add(x): "Compute N + X" return n + x return add class Strawberry: "Deli...
4,028
1,324
from __future__ import print_function import argparse import json import jsonschema import logging import numpy as np import networkx as nx import os import pandas as pd import random import sys logger = logging.getLogger(name=__file__) def _load_schema(): schema_file = os.path.join(os.path.dirname(__file__), ...
11,609
3,982
from dataclasses import dataclass, field from typing import List from itertools import chain @dataclass class Word: word: str wordtype: str shortdef: List[str] = field(default_factory=list) synonyms: List[str] = field(default_factory=list) antonyms: List[str] = field(default_factory=list) stem...
756
256
import os, time, datetime, threading, random import numpy as np import matplotlib.pyplot as plt import sys from cortix.src.module import Module from cortix.src.port import Port from cortix.src.cortix_main import Cortix import time from bb_plot import Plot import shapely.geometry as geo import shapely.ops from shapely i...
9,487
3,308
# Copyright 2018 Mathias Burger <mathias.burger@gmail.com> # # SPDX-License-Identifier: MIT import os import shutil import textwrap from tempfile import TemporaryDirectory import numpy as np import pytest from pgimp.GimpFile import GimpFile, GimpFileType from pgimp.GimpFileCollection import GimpFileCollection, NonEx...
23,904
7,837
# -*- coding: utf-8 -*- """ Created on Thu Sep 29 13:07:10 2016 @author: chyam purpose: A vanila lstm model for text classification. """ from __future__ import print_function from keras.models import Sequential from keras.layers import Dense, Dropout, Activation from keras.layers import LSTM from sklearn.feature_ex...
2,542
983
# 1 1 2 3 5 8 13 21 .... # f(n) = f(n - 1) + f(n - 2) # f(0) = f(1) = 1 def fibonacci(n: int): if n == 0 or n == 1: return 1 return fibonacci(n - 1) + fibonacci(n - 2) print(fibonacci(5))
207
121
#pythran export entry() #runas entry() import simple_case_import def forward(a): return simple_case_import.imported(a) def entry(): return forward(1)
160
55
import torchvision.models from .resnext101_32x4d import resnext101_32x4d from .inception_v4 import inception_v4 from .inception_resnet_v2 import inception_resnet_v2 from .wrn50_2 import wrn50_2 from .my_densenet import densenet161, densenet121, densenet169, densenet201 from .my_resnet import resnet18, resnet34, resnet5...
7,584
3,002
#!/usr/bin/env python3 """ Add +x to every .sh file """ # import argparse import os import subprocess def go_recursive(search_dir: str): objects = os.listdir(search_dir) for obj in objects: if obj == ".git": continue obj_path = f"{search_dir}/{obj}" if os.path.isdir(obj...
585
194
# TEXAS HOLD'EM (Program by Isaac Thompson) import random, itertools, copy, sys import os from playsound import playsound import pyttsx3 # Set to true to enable betting. do_bets = False RANKS = ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A'] SUITS = ['C', 'D', 'H', 'S'] SORT_RANKS = {'2': 0, '3': 1...
25,985
7,817
""" s="preeni" ss="e" """ s=input("enter the string:") ss=input("enter the substring:") j=0 for i in range(len(s)): m=s.find(ss) #the first occurence of ss if(j==0): print("m=%d"%m) if(m== -1 and j==0): print("no such substring is available") break if(m== -...
443
191
#!/bin/usr/python # -*- coding:utf-8 -*- # 628.三个数的最大乘积 class Solution: def maximumProduct(self, nums): if len(nums) == 3: return nums[0] * nums[1] * nums[2] elif len(nums) < 3: return None else: z_num, f_num = [], [] for i in nums: ...
1,039
408
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 16 15:35:53 2021 @author: alef """ import os.path # modulo de instropecção amigável import inspect print('Objeto: ', inspect.getmodule(os.path)) print('Classe?', inspect.isclass(str)) # Lista todas as funções que existem em os.path print('Memb...
437
170
import sys import pyfiglet import pandas as pd import numpy as np from tabulate import tabulate import dateutil import datetime import re result = pyfiglet.figlet_format("h r s y s t e m", font="slant") strStatus = "" class UserSelection: """Handles User Selection Logic the class is used to implement a case...
20,610
5,588
from . import similarity from .distance import frechet_dist from .similarity import pcc, sa from . import robust from .robust import iqr, cv, fwhm, count_missing_values
169
52
import scraper.scraper as scraper import scraper.parser as parser import sys from dotenv import load_dotenv load_dotenv() if __name__ == "__main__": if "--noScrape" not in sys.argv: scraper.main() parser.main()
229
80
from __future__ import division import time import json from collections import deque import serial import redis import numpy as np def build_update_basic(info): basic_info = { "cmd": "update_basic", "clients" : "%d" % info["connected_clients"], "memory" : info["used_memory_human"], ...
1,928
718
from django.db import models from django.utils import timezone class Article(models.Model): title = models.CharField(max_length = 100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.CharField(max_length = 100) def __str__(self): re...
433
132
from syft_tensorflow.serde.serde import MAP_TF_SIMPLIFIERS_AND_DETAILERS
73
31
#!/bin/env python # In this challenge, we are going to use regular expressions to manipulate # text data import re # 1. Compile a regular expression that matches URLs P_URL = re.compile(r'http://dlab\.berkeley\.edu', flags=re.I) # 2. Using that pattern, write a function that pulls all of the URLs out of a document...
549
151
# ----------------------------------------------------------------------------- # WSDM Cup 2017 Classification and Evaluation # # Copyright (c) 2017 Stefan Heindorf, Martin Potthast, Gregor Engels, Benno Stein # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associ...
8,706
2,598
from struct import unpack, pack from math import ceil, inf, acos, degrees from vectors import Vector3, Triangle, Vector2, Matrix3x3 from re import match UPVECTOR = Vector3(0.0, 1.0, 0.0) FWVECTOR = Vector3(1.0, 0.0, 0.0) SIDEVECTOR = Vector3(0.0, 0.0, 1.0) def round_vector(vector, digits): vector.x = round(vector...
25,470
8,946
#!/usr/bin/env python3 # https://open.kattis.com/problems/integerlists for _ in range(int(input())): p = input() n = int(input()) i, j = 0, n xs = input()[1:-1].split(',') front = True for c in p: if c == 'R': front = not front elif i == j: i += 1 ...
585
209
import pytest from django.http import HttpResponse from django.urls import reverse from main.middleware import IpRestrictionMiddleware def dummy_view(_): return HttpResponse(status=200) class TestIpRestrictionMiddleware: def test_middleware_is_enabled(self, client, settings): settings.IP_RESTRICT =...
3,177
1,179
import json import re from urllib.request import urlopen ''' The use of objects has various benefits. 1. Better control of context 2. State that can be evaluated 3. Data can be created and then processing can be added 4. Clean interface ''' class TopicSummarizer(): """TopicSummarizer - Summarizes ...
2,418
846
import pandas as pd import numpy as np import json from simpletransformers.classification import ClassificationModel, ClassificationArgs import sklearn from sklearn.model_selection import train_test_split import torch import re import matplotlib.pyplot as plt import matplotlib.ticker as ticker import os from tqdm impor...
4,154
1,596
#!/usr/bin/env python3 """ A module that defines any general purpose functions used by all scripts, including loading configuration files, connecting to the database, and handling Twitch's timestamp formats. """ import json import sqlite3 from datetime import datetime from typing import Tuple, Union ##############...
3,339
1,313
from unidecode import unidecode from unicodedata import name import ftfy for i in range(33, 65535): if i > 0xEFFFF: continue # Characters in Private Use Area and above are ignored if 0xD800 <= i <= 0xDFFF: continue h = hex(i) u = chr(i) f = ftfy.fix_text(u, normalization="NFKC") ...
986
361
import dash_bootstrap_components as dbc from dash import html from app import app layout = dbc.Container( children=[ dbc.Card([ #dbc.CardHeader("EURONEWS (União Européia)"), dbc.CardBody([html.Iframe(className="ytvid", width="420", height="315", src="https://www.youtube.com/embed...
4,363
1,658
# -*- coding: utf-8 -*- """ ~~~~~~~~~~~~~~~~~~~~~~ main module #author guoweikuang """ from flask import render_template from flask import redirect from flask import url_for from flask import request from flask_login import login_required from pyecharts import Bar from pyecharts.utils import json_dumps #from pyechart...
4,387
1,472
#!/usr/bin/env python # (C) Copyright IBM Corporation 2004 # All Rights Reserved. # # 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 # on the...
2,598
1,005
from __future__ import division class Rational(object): def __init__(self, numer, denom): if denom == 0: raise ValueError('denom should not be 0') i = 2 while i <= abs(numer): if numer % i == 0 and denom % i == 0: numer = numer // i d...
1,728
549
from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Div, Submit, HTML, Button, Row, Field from crispy_forms.bootstrap import AppendedText, PrependedText, FormActions from webui.dataforj import get_flow class SelectedStepForm(forms.Form): step_name = forms.Cha...
6,269
1,918
import logging from c8ydp.device_proxy import DeviceProxy, WebSocketFailureException from threading import Thread import threading from c8yMQTT import C8yMQTT import concurrent.futures import os logging.basicConfig(level=logging.INFO,format='%(asctime)s %(name)s %(message)s') logger = logging.getLogger(__name__) def...
3,109
960
from context import fe621 import numpy as np import pandas as pd def convergenceSegmentLimit(): """Function to compute the number of segments required for convergence of various quadrature methods. """ # Objective function def f(x: float) -> float: return np.where(x == 0.0, 1.0, np.sin(x...
1,397
439