content
stringlengths
5
1.05M
from opcode import opmap from asm.ops.abc import Opcode class GET_LEN(Opcode): def __init__(self): super().__init__(opmap["GET_LEN"], 0) class MATCH_MAPPING(Opcode): def __init__(self): super().__init__(opmap["MATCH_MAPPING"], 0) class MATCH_SEQUENCE(Opcode): def __init__(self): ...
"""Storage for change and authentication history.""" from __future__ import annotations import re from typing import TYPE_CHECKING from sqlalchemy import and_, or_ from sqlalchemy.sql import text from gafaelfawr.models.history import ( HistoryCursor, PaginatedHistory, TokenChangeHistoryEntry, ) from gaf...
# Generated by Django 2.2.5 on 2020-06-30 11:56 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('subscriptions', '0002_auto_20200630_0617'), ] operations = [ migrations.AddField( model_name='subscriptionplan', nam...
__version__ = "1.0.0" import scrapy import MyUtilities.common from scrapy.crawler import CrawlerProcess #Required Modules ##py -m pip install #See: https://benbernardblog.com/web-scraping-and-crawling-are-perfectly-legal-right/#generaladviceforyourscrapingorcrawlingprojects #See: http://doc.scrapy.org/en/1.0/topics/...
# Copyright 2021 ncdhz # 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, s...
# Generated by Django 3.1.3 on 2020-11-28 05:32 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0012_request_status'), ] operations = [ migrations.AlterModelOptions( name='request', options={'ordering': ['...
S = input() print(S.count("+")-S.count("-"))
# -*- mode: python; encoding: utf-8 -*- # # Copyright 2012 Jens Lindström, Opera Software ASA # # 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...
## ## Dictionary based bibliography manager ## ## @author Daniel J. Finnegan ## @date February 2019 import importlib # import difflib import re from mendproc.parsers.bibtexparser import BibTexParser from mendproc.parsers.csvparser import CSVParser from mendproc.parsers.mswordxmlparser import MSWordXMLParser from mendp...
from pygame import * font.init() font2 = font.SysFont('Arial', 36) mixer.init() game = True clock = time.Clock() FPS = 120 win = display.set_mode((1000, 700)) display.set_caption("game") place = transform.scale(image.load('place.png'),(1000,700)) class GameSprite(sprite.Sprite): def __init__(self, gamer_image,gamer...
"""Shuffle your team for virtual stand-ups!""" import argparse import enum import json import random from typing import Dict, Generator, List, Optional def _assert_members_xor_subteams(members, subteams): """Assert that only one of members or subteams is not None. Args: members: The contents of the ...
import pandas as pd import plotly.graph_objs as go import plotly.offline as offline offline.init_notebook_mode(connected=True) # Colors for plotting EDFGreen = '#509E2F' EDFLightGreen = '#C4D600' EDFOrange = '#FE5815' EDFBlue = '#001A70' EDFColors = [EDFGreen, EDFBlue, EDFOrange] def plotly_data_by_column...
# coding=utf-8 # !/usr/bin/env python """ :mod:"Vacuubrand_CVC_3000" -- API for Vacuubrand CVC3000 remote controllable vacuum controller =================================== .. module:: Vacuubrand_CVC_3000 :platform: Windows :synopsis: Control CVC3000 vacuum controller. .. moduleauthor:: Sebastian Steiner <s.stei...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/9/12 18:17 # @Author : JackyLUO # @E-mail : lingluo@stumail.neu.edu.cn # @Site : # @File : eval.py # @Software: PyCharm import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import roc_curve, auc # files = ...
""" The following classes are defined: Register4 Register8 Register16 """ from .. import wire from .. import signal from . import FLOP Wire = wire.Wire Bus4 = wire.Bus4 Bus8 = wire.Bus8 Bus16 = wire.Bus16 class Register4: """Construct a new 4-bit storage register. Args: data_bus: An obj...
import unittest from hamcrest import * from src.students import Students from key_generator.key_generator import generate from src.exampleData import Data class StudentsHamcrestTest(unittest.TestCase): def setUp(self): self.temp = Students(Data().example) def test_add_student_positive(self): ...
from collections import Counter def solveDay(myFile): data = parseData(myFile) print('Part 1: ', part1(data)) print('Part 2: ', part2(data)) def parseData(myFile): return [[x.split() for x in line.split('|')] for line in open(myFile).readlines()] def part1(data): return sum( ...
# -*-coding:utf-8-*- import re from knlp.seq_labeling.crf.crf import CRFModel from knlp.common.constant import KNLP_PATH class Inference: def __init__(self): self.label_prediction = [] # 预测标签序列 self.out_sentence = [] # 预测结果序列 def spilt_predict(self, in_put, file_path): """ ...
import torch import numpy as np from ..models import * from ..data.two_dim import two_dim_ds from ..data.mnist import MNIST #from ..data.emnist import EMNIST from ..data.celeba import CelebA from .plotters import TwoDPlotter, ImPlotter from torch.utils.data import TensorDataset import torchvision.transforms as transfo...
import os, sys, subprocess sys.path.append(os.path.dirname(__file__) + "/../lib") from test_helper import create_virtenv, run_test ENV_NAME = "formencode_test_env_" + os.path.basename(sys.executable) SRC_DIR = os.path.abspath(os.path.join(ENV_NAME, "src")) PYTHON_EXE = os.path.abspath(os.path.join(ENV_NAME, "bin", "p...
import asyncio from nats.aio.client import Client as NATS from nats.errors import ConnectionClosedError, TimeoutError async def main(): nc = NATS() try: # It is very likely that the demo server will see traffic from clients other than yours. # To avoid this, start your own locally and modify...
from __future__ import unicode_literals import json from django import template from django.core.serializers.json import DjangoJSONEncoder from django.http import HttpResponse, HttpResponseForbidden from django.shortcuts import get_object_or_404 from django.template import RequestContext, Template from django.views.d...
#!/usr/bin/env python # -*- encoding=utf8 -*- # # File: cmd.py # # Copyright (C) 2013 Hsin-Yi Chen (hychen) # Author(s): Hsin-Yi Chen (hychen) <ossug.hychen@gmail.com> # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software")...
def Sum(num): return sum(range(1,num+1)) def main(): num = input("Please enter your number to sum: ") print(Sum(int(num))) if __name__ == "__main__": main()
from django.db.models.signals import post_delete from django.dispatch import Signal, receiver from baserow.contrib.database.table.cache import ( invalidate_table_model_cache_and_related_models, ) from baserow.contrib.database.table.models import Table table_created = Signal() table_updated = Signal() table_delete...
import numpy as np from wavespectra.construct.helpers import (spread, check_coordinates, arrange_inputs, make_dataset) def jonswap(tp, dp, alpha, gamma=3.3, dspr=20, freqs=np.arange(0.04,1.0,0.02), dirs=np.arange(0,360,10), coordinates=[], sumpart=True): """Constructs JONSWAP spectra from peak peri...
#!/usr/local/bin/python # -*- coding: utf-8 -*- import re import sys import isharp.datahub.yaml_support as iYaml import nameko.cli.main import isharp.datahub.web.webconsole as web from multiprocessing import Process def main(): sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) iYaml.set_up_unsa...
# ABBA reversed is ABBA, print all such palindromes user_input = input().split() result = [word for word in user_input if word == word[::-1]] result = list(set(result)) #result.sort(key = str.lower) result.sort(key = str.upper) print(*result, sep = ', ')
# Copyright 2021 Zilliz. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
from typing import List, Dict, Set from nuscenes.map_expansion.map_api import NuScenesMap from nuscenes.nuscenes import NuScenes def get_egoposes_on_drivable_ratio(nusc: NuScenes, nusc_map: NuScenesMap, scene_token: str) -> float: """ Get the ratio of ego poses on the drivable area. :param nusc: A NuScen...
from PIL import Image, ImageDraw, ImageColor, ImageFont import cv2 import skimage import matplotlib.pyplot as plt import numpy as np import string import random import json import pprint import generate_code image_width = 1920 # in pixel image_height = 1080 # in pixel border_padding = 100 text_color = "white" font_ty...
#!/usr/bin/python3 import pytest from brownie.exceptions import IncompatibleEVMVersion, VirtualMachineError from brownie.network.contract import ProjectContract from brownie.network.transaction import TransactionReceipt def test_returns_contract_on_success(BrownieTester, accounts): """returns a Contract instanc...
''' Generate a random number of length, N and all digits are unique ''' from __future__ import print_function import random from collections import OrderedDict # keep generating till all are unique # This is a brute force approach where I store the digits generated # so far in a OrderedDict and if the next random numb...
#!/usr/bin/env python3 import glob import os import platform import sys import shutil import subprocess import re import multiprocessing import itertools from contextlib import contextmanager # Overall script settings this_project_package = f'{os.getcwd()}/bdsg' this_project_source = f'{this_project_package}/src' t...
#! /usr/bin/python # SPDX-License-Identifier: GPL-3.0-or-later # # 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....
import pysrt import os from bs4 import BeautifulSoup import sys import ntpath def extractHTML(x,y): soup = BeautifulSoup(open("Friends-Script/season01/0101.html")) index = 1 srtdict = {} title = ''.join(soup.find('h1')) fname = "Friends-Script/season01/0101.html" ntpath.basename(fname) s...
# -*- coding: utf-8 -*- import os import pandas as pd from pyEX import Client, PyEXception def _get_data(symbol, start, end, client=None): if client is None and not os.environ.get('IEX_TOKEN'): raise PyEXception('Must provide pyEX client or set IEX_TOKEN environment variable') elif client is None: ...
# -*- coding: utf-8 -*- # Transformer based Mutation Recognition of SETH Corpus (NLP-NER) # Pipeline for prediciton of IOB-Tags in a given text using the best tuned model # inspired by: https://huggingface.co/dslim/bert-base-NER import torch # conda install pytorch=1.5 from transformers import AutoTokenizer, AutoModel...
#!/home/ian/Documents/Instagram-pics/virtual/bin/python from django.core import management if __name__ == "__main__": management.execute_from_command_line()
#!/usr/bin/python3 import copy p1 = 0 p2 = 0 lines = open("day03.dat", "r").read().splitlines() com = [] nocom = [] for i in range(len(lines[0])): c0 = 0 c1 = 0 for line in lines: if line[i] == "1": c1 += 1 if line[i] == "0": c0 += 1 if (c1 > c0): com.append("0") nocom.app...
# -*- coding: utf-8 -*- from django.http.request import QueryDict from rest_framework import serializers from ralph.api.tests._base import RalphAPITestCase from ralph.data_center.tests.factories import IPAddressFactory from ralph.security.api import SaveSecurityScanSerializer from ralph.security.tests.factories import...
# Description: The datatime.date Class import time from datetime import date """ The datetime.date object: * A date object represents a date (year, month and day) in the current Gregorian calendar calendar. * The attributes of the datetime.date object are year, month, and day. """ # Constructor # 1. All arguments ar...
# ------------------------------------------------------------------------- # # Part of the CodeChecker project, under the Apache License v2.0 with # LLVM Exceptions. See LICENSE for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # # ---------------------------------------------------...
from pupa.models import Jurisdiction, JurisdictionSession from .base import BaseImporter class JurisdictionImporter(BaseImporter): _type = 'jurisdiction' model_class = Jurisdiction related_models = {'sessions': JurisdictionSession} def __init__(self, jurisdiction_id): super(JurisdictionImport...
from abc import ABCMeta, abstractmethod from dataclasses import dataclass from typing import Optional @dataclass class User: username: str password: str salt: str is_enabled: bool class AuthProvider(metaclass=ABCMeta): @abstractmethod async def create(self, user: User) -> bool: ... ...
import unittest from enumerater import Enumerater import random from predictor import Predictor import os from ddt import ddt, data import copy from info_str import NAS_CONFIG @ddt class Test_pred(unittest.TestCase): global test_info test_info = [] for i in range(10): test_info.append...
# Copyright 2020 Google LLC # # 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, ...
from PyQt5 import QtWidgets, QtGui, Qt class CollapsableWidget(QtWidgets.QFrame): def __init__(self, parent=None, direction=QtWidgets.QBoxLayout.LeftToRight, collapsed=False): QtWidgets.QFrame.__init__(self, parent) self.direction = direction self.collapsed = collapsed self.layout = QtWidgets.QBoxLayout(dire...
import time from . import utils utils.compile_contract("OffchainDKG") contract = utils.deploy_contract("OffchainDKG", should_add_simplified_call_interfaces=False) time.sleep(1.0)
#!/usr/bin/env python3 from app.ioc import injector from app.types import App injector.get(App).run()
#!/usr/bin/env python import sys from cv2 import cv def example2_4(image): cv.NamedWindow("Example4-in") cv.NamedWindow("Example4-out") # show the image cv.ShowImage("Example4-in", image) # transform the input out = cv.CreateImage(cv.GetSize(image), cv.IPL_DEPTH_8U, 3) cv.Smooth(image, out, cv.CV_GAUS...
""" TensorFlow Models ================== Creator: Til Gärtner example file showing use of the given models """ # %% Imports import tensorflow as tf # %% Read Models Wsym = tf.keras.models.load_model(r"..\models\Wsym_model_12-12-12") Wdir = tf.keras.models.load_model(r"..\models\Wdir_model_18-18-18...
from typing import Callable, Tuple, ClassVar, Dict import matplotlib.pyplot as plt import numpy as np class SparseMatrix: values: ClassVar[Dict[Tuple[int, int], float]] shape: ClassVar[Tuple[int, int]] def __init__(self, values: Dict[Tuple[int, int], float], shape: Tuple[int, int]): self.values =...
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. """ A recurrent GAN model that draws images based on dialog/description turns in sequence """ import os import gc import torch import torch.nn as nn from torch.nn import DataParallel import numpy as np from ..models.networks...
# # PySNMP MIB module JUNIPER-UTIL-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/JUNIPER-UTIL-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:01:23 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar ...
from astropy import units as u from astropy.cosmology import Planck15 import numpy as np from scipy.integrate import cumtrapz, quad, simps, trapz from time import time try: import pyccl as ccl has_ccl = True except ImportError: has_ccl = False from .helpers.cosmology import BaseCosmo from .helpers.decorat...
# read and write files use -> function open() # manipulate paths use -> os.path module # read all the lines in all the files on the command line see the -> fileinput module # create temporal file and directories use -> tempfile module # high-level file and directory handling -> shutil module import os # print(os.nam...
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2016-12-09 22:44 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.Crea...
# # PDF # --- # This script contains the # class PDF # # Date: 2021-02-05 # # Author: Lorenzo Coacci # # # Copyright (C) 2021 Lorenzo Coacci # # pylint: disable=logging-format-interpolation,too-many-lines # # + + + + + Libraries + + + + + # import basic from golog.log import ( error_print, warning_print, ...
""" filename : envelope_info.py This script is responsible for fetching envelope informations from docusign. """ from docusign_esign import EnvelopesApi, ApiClient from datetime import datetime, timedelta import pandas as pd import streamlit as st import subprocess from PyPDF2 import PdfFileMerger from app.utils.uti...
# -*- coding: utf-8 -*- # Copyright (c) 2017 Mirantis 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 ...
#!/usr/bin/env python import os import sys sys.path.append(os.path.abspath(os.path.dirname(os.path.dirname(__file__)))) from kido import app from kido.constants import PERMISSION_ADMIN from kido.forms import EmailForm from kido.models import db, User, Group, Permission def main(): if not len(sys.argv) == 2: ...
import os import uuid import shutil import random import filecmp import itertools from collections import namedtuple from unittest.mock import patch, call import pytest import alphacopy @pytest.fixture(scope='function') def random_tree(): """ This fixture creates a random folder tree in ./tmp/ filled with ...
import copy import datetime from collections import defaultdict import numpy as np import pycocotools.mask as mask_utils class SegCocoEval: def __init__(self, coco_gt=None, coco_dt=None, iou_type='segm'): self.cocoGt = coco_gt # ground truth COCO API self.cocoDt = coco_dt # detections COCO API ...
def changedp (A,V): a=[[0]*(A+1) for x in xrange(len(V))] for j in range (1,A+1): a[0][j]=j for i in range(1,len(V)): for j in range (1,A+1): if (j>=V[i]): a[i][j]=min(a[i-1][j],1+a[i][j-V[i]]) else: a[i][j]=a[i-1][j] minChange=a[len(V)-1][A] #the following code to trace back and...
from itertools import product import matplotlib.pyplot as plt import mpl_extras as me import tpsim as tp import numpy as np import warnings import os # --------------------------------------------------------------------------- # # Simulation parameters # ------------------------------------...
from typing import Union, Optional from ..codes import OpCodes class OutGoingResponse: def __init__( self, req_id: int, status: Optional[int] = None, headers: Optional[Union[list, tuple]] = None, body: Optional[str] = None ): if req_id is no...
import traceback import discord from discord.ext import commands #from src.utils.execption import PermError from utils.execption import PermError from utils.create_embed import embeds from data import colors class handling(commands.Cog): """ 에러를 처리하는 곳이야 """ def __init__(self,bot): self.bot = ...
# Generated by Django 3.2.9 on 2021-11-08 17:26 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='DateRange', fields=[ ...
def greet(people): printout = [] for p in people: to_print = 'hello {}'.format(p) printout.append(to_print) print(to_print) return printout if __name__ == '__main__': everybody = [ 'colin', 'pierre' ] greet(everybody)
import torch import torch.nn as nn import numpy as np from torch.distributions import Normal def get_acq_fn(args): if args.acq_fn.lower() == "ucb": return UCB elif args.acq_fn.lower() == "ei": return EI else: return NoAF class AcquisitionFunctionWrapper(): def __init__(self, ...
import sys, pathlib sys.path.append(pathlib.Path('..'))
# generated by datamodel-codegen: # filename: openapi.yaml # timestamp: 2021-12-31T02:59:10+00:00 from __future__ import annotations from enum import Enum from typing import Annotated, Any, List, Optional from pydantic import BaseModel, Field class InvalidParameterException(BaseModel): __root__: Any cla...
import os from alttprbot.alttprgen.randomizer import roll_aosr from alttprbot.tournament.core import TournamentConfig from alttprbot_discord.bot import discordbot from .sglcore import SGLRandomizerTournamentRace class AOSR(SGLRandomizerTournamentRace): async def configuration(self): guild = discordbot.ge...
from __future__ import print_function import unittest import ospsurvey.version class TestSample(unittest.TestCase): def test_sample(self): self.assertTrue(True) v = ospsurvey.version.version() print(v)
from heapq import nlargest from typing import List Scores = List[int] def latest(scores: Scores) -> int: """The last added score.""" return scores[-1] def personal_best(scores: Scores) -> int: """The highest score.""" return max(scores) def personal_top_three(scores: Scores) -> Scores: """The...
IMAGE_MAX_WH = 300
# Exercise 13 # https://learnpythonthehardway.org/book/ex13.html from sys import argv script, first, second, third = argv print "The script is called:", script print "Your first variable is:", first print "Your second variable is:", second print "Your third variable is:", third opinion = raw_input("What do you thin...
import machine, time import ssd1306, ds18x20, onewire ENABLE_OLED = True def main(): while True: show() time.sleep_ms(250) def show(): wtemp = read_ds18(750) # water temperature print("W=" + wtemp) if ENABLE_OLED == True: oled.fill(0) oled.text("[water]", 0, 0) oled.text("W="...
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from . import models, serializers class Notifications(APIView): def get(self, request, format =None): user =request.user notification = models.Notification.objects.filt...
# Copyright 2021 Huawei Technologies Co., Ltd # # 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...
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
import argparse import json import os import matplotlib.pyplot as plt import numpy as np import seaborn as sns from matplotlib.ticker import FuncFormatter from rl_baselines.visualize import loadCsv, movingAverage, loadData from srl_zoo.utils import printGreen, printYellow, printRed # Init seaborn sns.set() # Style f...
import os import autograd.numpy as np from autograd import value_and_grad from scipy.optimize import minimize from util import get_median_inter_mnist, Kernel, load_data, ROOT_PATH,_sqdist,nystrom_decomp,remove_outliers,nystrom_decomp, chol_inv from scipy.sparse import csr_matrix import random import time Nfeval = 1 se...
import pandas as pd import os,re,gzip from igf_data.utils.fileutils import check_file_path def identify_fastq_pair(input_list,sort_output=True,check_count=False): ''' A method for fastq read pair identification :param input_list: A list of input fastq files :param sort_output: Sort output list, default true ...
def max_buffed_damage(max_base_damage: float, blood_drinker: float, blood_thirst: float): return max_base_damage + blood_drinker + blood_thirst def min_buffed_damage(max_buffed_damage: float, weapon_variance: float): return max_buffed_damage * (1.0 - weapon_variance) def starting_weapon_variance(min_base_da...
import math from typing import List def mean(target_list: List[int], floor: bool = True) -> int: """ Gets the mean value of the list, rounded down if floor is True, else rounded up """ if floor: return mean_floor(target_list) return mean_ceil(target_list) def mean_floor(target_list: Lis...
# Created by MechAviv # ID :: [4000021] # Maple Road : Entrance to Adventurer Training Center sm.setSpeakerID(12100) selection = sm.sendNext("This is the perfect place to train your basic skills. Where do you want to train?\r\n#b#L0#Adventurer Training Center 1#l\r\n#b#L1#Adventurer Training Center 2#l\r\n#b#L2#Advent...
"""Window class for Nuke. TODO: Get callbacks from https://learn.foundry.com/nuke/developers/110/pythonreference/ TODO: Figure out how to launch a floating panel """ from __future__ import absolute_import, print_function import inspect import uuid from collections import defaultdict from functools import partial fro...
import pytest from obsei.preprocessor.text_splitter import TextSplitterConfig from obsei.payload import TextPayload DOCUMENT_1 = """I love playing console games.""" DOCUMENT_2 = """Beyoncé Giselle Knowles-Carter (/biːˈjɒnseɪ/ bee-YON-say; born September 4, 1981)[6] is an American singer, songwriter, record producer, ...
#!/usr/bin/env python # encoding: utf-8 import sys from setuptools import setup version = "1.0.6" description = ( "A pure Python implementation for the famous DES algorithm" ) if sys.version_info < (3, ): kw = {} else: kw = {"encoding": "utf-8"} long_description = open("README.md", **kw).read() class...
from argparse import ArgumentError from typing import Tuple from numpy import dtype from nn_trainer.utils import * import torch import torch.optim from nn_trainer.data import * from nn_trainer.models import * from nn_trainer.trainers import * from nn_trainer.plotters import * from nn_trainer.metrics import * from nn_...
#!/usr/bin/env python3 """ Top 100 most starred GitHub projects grouped by topic description. Visualized as a interactive 3D pie chart in HTML 5 hosted on GitHub Pages using Google Charts JavaScript library. """ from datetime import datetime, timedelta import time from lxml import html import requests from pandas_d...
#!/bin/python EMISSION_SPEED_FACTOR = 19 DIFFICULTY_TARGET = 240 # seconds MONEY_SUPPLY = 88888888000000000 GENESIS_BLOCK_REWARD = 8800000000000000 FINAL_SUBSIDY = 4000000000 COIN_EMISSION_MONTH_INTERVAL = 6 #months COIN_EMISSION_HEIGHT_INTERVAL = int(COIN_EMISSION_MONTH_INTERVAL * 30.4375 * 24 * 3600 / D...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import mig_main.location_field class Migration(migrations.Migration): dependencies = [ ('mig_main', '0007_memberprofile_location'), ] operations = [ migrations.AlterField( ...
from typing import List class FindAllAnagrams: def find(self, text: str, pattern: str) -> List[int]: current_pointer_character_map = {} pattern_character_map = {} for i in range(len(pattern)): pattern_character_map[pattern[i]] = pattern_character_map.get(pattern[i], 0) + 1 ...
##### 3. 비지도 학습과 데이터 전처리 #### 3.1 비지도 학습의 종류 ### 1) 비지도 변환 ## 데이터를 새롭게 표현하여, 사람이나 다른 ML Algorithm이 원래 데이터보다 알아보기 쉽도록 하는 것 # ex) 고차원 데이터의 차원 수를 줄이면서 필요한 데이터로 표현하는 차원 축소 # ex) 텍스트 문서에서 주제 추출하기 ### 2) 군집 ## 데이터를 비슷한 것끼리 그룹으로 묶는 것 #### 3.2 비지도 ...
# -*- coding:utf-8 -*- from torcms.core import tools from torcms.model.post_hist_model import MPostHist from torcms.model.post_model import MPost class TestMPostHist(): def setup(self): print('setup 方法执行于本类中每条用例之前') self.uid = '' self.post_id = 'llk8' def test_create_post_history(self...
import numpy # from chainer import testing # from chainer import utils import ideep4py x1 = numpy.ndarray(shape=(2, 16, 2, 2), dtype=numpy.float32, order='C') x2 = numpy.ndarray(shape=(2, 16, 2, 2), dtype=numpy.float32, order='C') mx1 = ideep4py.mdarray(x1) mx2 = ideep4py.mdarray(x2) numpy.copyto(x2, x1) ideep4py.basi...
from api.gcp.tasks.baseTask import baseTask import json import datetime from core.input_form_singleton import input_form_singleton from core.form_singleton import formSingleton_singleton from db.connection_pool import MysqlConn from utils.status_code import response_code from config import configuration import tracebac...