text
string
size
int64
token_count
int64
# -*- coding: utf-8 -*- """Top-level package for commonutils.""" __author__ = """lrbsunday""" __email__ = '272316131@qq.com' __version__ = '0.1.0'
149
72
# -*- coding: utf-8 -*- from django.utils.timesince import timesince class CreatedByAdminMixin: def save_model(self, request, obj, form, change): if getattr(obj, 'created_by', None) is None: obj.created_by = request.user # noinspection PyUnresolvedReferences super().save_model...
826
268
import os from os.path import join, isfile from shutil import Error from sys import exec_prefix import numpy as np import fit import simple_read_data from tabulate import tabulate import logging np.seterr(all='raise') class DataFormatError(Exception): pass class WrongPathFormat(Exception): pass def check_dat...
8,936
2,747
from django.db import models from wagtail.admin.edit_handlers import FieldPanel, StreamFieldPanel, MultiFieldPanel from wagtail.core.blocks import StreamBlock from wagtail.core.fields import StreamField from wagtail.images.edit_handlers import ImageChooserPanel from falmer.content import components from falmer.content....
1,729
514
import pandas as pd import matplotlib.pyplot as plt import numpy as np import re import spacy from time import time import pickle from collections import defaultdict import pmi_tfidf_classifier as ptic path = "../data/" pd.set_option("display.max_rows", None, "display.max_columns", None) np.random.seed(250) spacy.pre...
1,089
420
"""Tests for the marion application fields""" from marion.defaults import DocumentIssuerChoices from ..fields import IssuerLazyChoiceField, LazyChoiceField def test_fields_lazy_choice_field(): """ LazyChoiceField class. Choices instance attribute should not be customizable. """ field = LazyChoic...
956
319
# -*- coding: utf-8 -*- """ Created on Thu Mar 3 12:15:40 2022 @author: udaya """ # -*- coding: utf-8 -*- """ Created on Sun Feb 27 18:06:29 2022 @author: udaya """ import cv2 import numpy as np from djitellopy import Tello frameWidth = 640 frameHeight = 480 ############################### ...
2,331
1,040
# (C) Copyright 2020 ECMWF. # # This software is licensed under the terms of the Apache Licence Version 2.0 # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. # In applying this licence, ECMWF does not waive the privileges and immunities # granted to it by virtue of its status as an intergovernmenta...
16,101
4,773
# This file is part of the Data Cleaning Library (openclean). # # Copyright (C) 2018-2021 New York University. # # openclean is released under the Revised BSD License. See file LICENSE for # full license details. """Collection of helper functions for various purpoeses.""" from typing import Optional import uuid de...
3,044
818
nome= input('Qual seu nome ?: ') print ('Olá {} Seja bem vindo'.format(nome))
78
28
from .openpondk_class_diagram_parser import OpenponkClsDiagramParser
68
22
from .conv import Conv from .conv_maxpool import ConvMaxpool from .embedding import Embedding from .linear import Linear from .lstm import LSTM __all__ = ["LSTM", "Embedding", "Linear", "Conv", "ConvMaxpool"]
254
81
#following tutorial: https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_colorspaces/py_colorspaces.html#converting-colorspaces import numpy as np import cv2 #there are more than 150 color-space conversions methods available in OpenCV #why so many? #gets all possible color space conver...
1,141
450
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: # # Copyright 2021 The NiPreps Developers <nipreps@gmail.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may...
1,724
553
# -*- coding: UTF-8 -*- import os import numpy as np import pandas as pd from tqdm import tqdm import json import cv2 from sklearn.model_selection import train_test_split import matplotlib from keras.utils import np_utils from keras.optimizers import * from keras.preprocessing.image import ImageDataGenerator from f...
7,026
2,344
"""Auto-generated file, do not edit by hand. QA metadata""" from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_QA = PhoneMetadata(id='QA', country_code=None, international_prefix=None, general_desc=PhoneNumberDesc(national_number_pattern='[129]\\d{2,4}', possible_length=(3, 4, ...
700
253
""" Organizing test and parametrizing """ # Parametrized tests: Run many tests in one # pylint: disable=W0622 # pylint: disable=R0201 # pylint: disable=R0903 import pytest from word_counter import count_words class TestWordCounterParametrization: """ In this case we want to test many tests in one function "...
815
294
from argparse import ArgumentParser import os import pdb import sys from dep_appearances.appearances_report import AppearancesReport def main(): parser = ArgumentParser(description='Find dependencies that are unused and underused in your codebase.') parser.add_argument( 'project_root', metava...
1,685
488
from django_filters import Filter from django_filters.fields import Lookup class ListFilter(Filter): def filter(self, qs, value): value_list = value.split(u',') return super(ListFilter, self).filter(qs, Lookup(value_list, 'in'))
250
76
from polyphony import testbench def expr08(a, b, c): return a < b < c @testbench def test(): assert False == expr08(0, 0, 0) assert True == expr08(0, 1, 2) assert False == expr08(1, 0, 2) assert False == expr08(2, 1, 0) assert True == expr08(-1, 0, 1) assert True == expr08(-2, -1, 0) test...
323
146
from pyfirmata import Arduino, util from time import sleep import pymysql def arduino_map(x, in_min, in_max, out_min, out_max): return(x-in_min) * (out_max-out_min) / (in_max-in_min) + out_min PORT = "COM4" uno = Arduino(PORT) sleep(5) it = util.Iterator(uno) it.start() a4 = uno.get_pin('a:4:i') a5 = uno.get_p...
1,175
502
import flask from find_files import find as find_files views_blueprint = flask.Blueprint('views', __name__, url_prefix='') @views_blueprint.route('/', methods=['GET']) def index_get(): return flask.render_template( 'index.html', custom_elements_files=find_files.custom_elements_files())
303
94
#! /usr/bin/env python import warnings, numpy with warnings.catch_warnings(): warnings.simplefilter("ignore") from libpyarr_example import * def main(): my_uninited_arr = bar() my_uninited_arr[:, 0,0] = -50 print "some -50s, some uninitialized:",my_uninited_arr[:,:2,0] foo(my_uninited_arr...
577
213
import logging from watchdog.events import LoggingEventHandler, FileSystemEventHandler class AnnoEventHandler(FileSystemEventHandler): """Logs all the events captured.""" def __init__(self, logger=None): super().__init__() self.logger = logger or logging.root def on_moved(self, event): ...
1,167
363
import sys import numpy as np from tqdm import tqdm from contextlib import nullcontext class DenseLayer: _update_state = None _softmax_minicolumns = None _update_counters = None _update_weights = None _update_bias = None def __init__( self, in_features, hyp...
11,037
3,329
from flux_sensors.localizer.localizer import Localizer, Coordinates, LocalizerError, PozyxDeviceError from flux_sensors.light_sensor.light_sensor import LightSensor from flux_sensors.config_loader import ConfigLoader from flux_sensors.flux_server import FluxServer, FluxServerError from flux_sensors.models import models...
6,879
1,724
import math import torch # import torch.utils.serialization # it was removed in torch v1.0.0 or higher version. arguments_strModel = 'sintel-final' SpyNet_model_dir = './models' # The directory of SpyNet's weights def normalize(tensorInput): tensorRed = (tensorInput[:, 0:1, :, :] - 0.485) / 0.229 tensorGre...
11,288
4,161
#!/usr/bin/python # -*- coding: UTF-8 -*- """ @file : acl_test.py @Time : 2020/11/9 9:25 @Author: Tao.Xu @Email : tao.xu2008@outlook.com """ import os import unittest from storagetest.libs import utils from storagetest.libs.log import log from storagetest.libs.exceptions import PlatformError, NoSuchDir, NoSuchBina...
2,668
934
#!/usr/bin/python import sys, getopt, os, time, array from pyftdi.spi import SpiController def download ( filename, speed=5000000, chunksize=32 ): try: with open(filename, 'rb') as filein: data = filein.read () data = array.array('B', data).tolist() except IOError: print "ERROR: Could not open file {0}".f...
1,518
679
import numpy as np class NeuralNetwork(): ''' This neural network is designed for Pedestrian Car Project. It constructs an input layer that gets 4 road and car parameters. Using neural network algorithm, it gives optimum steering angle of the car. To use this class: -Firstly, using training...
3,845
1,147
import pyhf from pyhf.parameters import ParamViewer def test_paramviewer_simple_nonbatched(backend): pars = pyhf.tensorlib.astensor([1, 2, 3, 4, 5, 6, 7]) parshape = pyhf.tensorlib.shape(pars) view = ParamViewer( parshape, {'hello': {'slice': slice(0, 2)}, 'world': {'slice': slice(5, 7)}...
1,405
605
from typing import Dict, Optional, Tuple import numpy as np import torch import torch.nn.functional as F from allennlp.common.checks import ConfigurationError from allennlp.common.util import START_SYMBOL, END_SYMBOL from allennlp.data.vocabulary import Vocabulary from allennlp.models.model import Model from allennlp....
15,276
4,230
import numpy as np from hrv.rri import RRi from hrv.utils import _create_time_info def quotient(rri): # TODO: Receive option to replaced outliers with stats # functions (i.e mean, median etc) # TODO: Receive option to re-create time array with cumsum of filtered rri if isinstance(rri, RRi): ...
1,372
582
paraview_plugin_version = '1.1.39' # This is module to import. It provides VTKPythonAlgorithmBase, the base class # for all python-based vtkAlgorithm subclasses in VTK and decorators used to # 'register' the algorithm with ParaView along with information about UI. from paraview.util.vtkAlgorithm import * # Helpers: fr...
20,428
6,000
import json import secrets import brownie from dotmap import DotMap import pytest import pprint from brownie import * from helpers.constants import * from helpers.registry import registry from rich.console import Console FARM_ADDRESS = "0xa0246c9032bC3A600820415aE600c6388619A14D" XSUSHI_ADDRESS = "0x8798249c2E60744...
20,333
6,533
# Filename: HCm_UV_v4.11.py import string import numpy as np import sys #sys.stderr = open('errorlog.txt', 'w') #Function for interpolation of grids def interpolate(grid,z,zmin,zmax,n): ncol = 9 vec = [] for col in range(ncol): inter = 0 no_inter = 0 for row in range(0,len(grid)): ...
23,869
10,556
feFirst = ['Emma', 'Olivia', 'Ava', 'Isabella', 'Sophia', 'Charlotte', 'Mia', 'Amelia', 'Harper', 'Evelyn', 'Abigail', 'Emily', 'Elizabeth', 'Mila', 'Ella', 'Avery', 'Sofia', 'Camila', 'Aria', 'Scarlett', 'Victoria', 'Madison', 'Luna', 'Grace', 'Chloe', 'Penelope', 'Layla', 'Riley', 'Zoey', 'Nora', 'Lily', 'Eleanor', '...
20,746
9,667
from nose.tools import eq_ from oldtoronto.toronto_archives import get_citation_hierarchy # noqa def test_get_citation_hierarchy(): eq_([ 'Fonds 200, Series 123', 'Fonds 200' ], get_citation_hierarchy('Fonds 200, Series 123, Item 456')) eq_([ 'Fonds 257, Series 12, File 1983', ...
444
199
# excel2.py import xlrd def print_xls(path): xlsFile = xlrd.open_workbook(path) try: mySheet = xlsFile.sheets()[0] # 访问第1张表序号0 // xlsFile.sheet_by_name('sheetName') 通过工作表名访问 except: print('no such sheet in file') return print('%d rows, %d cols' % (mySheet.nrows, mySheet.ncols)...
979
542
import multiprocessing as mp import portpicker from .client import Client, NumpyLoader, TorchCudaLoader from .sampler import PERSampler from .server.main_loop import main_loop from .utils import get_local_ip def start_server( capacity, batch_size, host=None, port=None, samplers=None, cache_policy=None ): if...
1,162
401
import random import numpy as np import torch import torch.optim as optim import torch.nn.functional as F import torchvision.transforms as T from memory import Transition, ReplayMemory, PrioritizedReplayMemory, NStepMemory from DQN import DQN, DuelingDQN, NoisyDQN, DistributionalDQN class Agent: def __...
7,171
2,398
import qsharp from DeutschJozsa import SayHello, RunDeutschJozsa SayHello.simulate() RunDeutschJozsa.simulate(N=10)
121
51
"""Apply a stylesheet to an XML file""" import sys from lxml import etree if len(sys.argv) != 3: print >>sys.stderr, "Usage: %s <stylesheet> <xml doc> ..." % sys.argv[0] sys.exit(1) transform = etree.XSLT(etree.XML(open(sys.argv[1], "r").read())) for xmlfile in sys.argv[2:]: with open(xmlfile, "r") as fp...
413
163
# -*- coding: utf-8 -*- # # io3d documentation build configuration file, created by # sphinx-quickstart on Mon Nov 27 12:01:57 2017. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All ...
7,122
2,354
# -*- coding: utf-8 -*- """RED_linear_run1.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1-WN1MY9YYluGcnigLgrndqsxcOYldbB6 """ #@title mount your Google Drive #@markdown Your work will be stored in a folder called `cs285_f2021` by default to pr...
33,401
12,583
from django.shortcuts import render, get_object_or_404, redirect from .models import TeacherInfo from .forms import CreateTeacher from django.contrib import messages from django.core.paginator import Paginator # Create your views here. def teacher_list(request): teachers = TeacherInfo.objects.all() paginator ...
2,096
662
# from flask import request from flask_restful import request # import logging from .utils import log_request from .base import BaseResource from ..services.jobs import get_events, get_event from ..services.utils import APIResponse import logging logger = logging.getLogger(__name__) class ListEvents(BaseResource): ...
4,326
1,556
import unittest # https://docs.python.org/3/library/unittest.html from calc import Calc class TestCalc(unittest.TestCase): pass
136
48
import unittest from unittest.mock import patch from waves_gateway.model import Transaction, TransactionReceiver from waves_gateway.service import IntegerConverterService class IntegerConverterServiceSpec(unittest.TestCase): @patch.multiple( # type: ignore IntegerConverterService, __abstractmethods__=s...
3,267
1,003
#!/usr/bin/env python # -*- coding: utf-8 -*- """ LIVE DEMO This script loads a pre-trained model (for best results use pre-trained weights for classification block) and classifies American Sign Language finger spelling frame-by-frame in real-time """ import string import cv2 import time from processing import square...
6,670
2,369
"""Fetches gene sequence from gene fasta created by extract_genes.py""" import prob2020.python.utils as utils class GeneSequence(object): def __init__(self, fasta_obj, nuc_context=1.5): self.fasta = fasta_obj self.nuc_context = nuc_context def set_gene(self, bed_line): ...
8,770
2,763
# -*- coding:utf-8 -*- # --------------------------------------------- # @file http_request # @description http_request # @author WcJun # @date 2021/07/19 # --------------------------------------------- from src.main.python.request.options import RequestOptions class HttpRequest: """ Http Request """ ...
1,118
319
from time import sleep from threading import Thread from bot import aria2, download_dict_lock, download_dict, STOP_DUPLICATE, TORRENT_DIRECT_LIMIT, ZIP_UNZIP_LIMIT, LOGGER, STORAGE_THRESHOLD from bot.helper.mirror_utils.upload_utils.gdriveTools import GoogleDriveHelper from bot.helper.ext_utils.bot_utils import is_mag...
5,728
1,753
import pygame from pygame.locals import * from pygamehelper import * from vec2d import * from random import randrange class Matrix: def __init__(self, w, h): self.w, self.h = w, h self._data = [] for i in range(self.w * self.h): self._data.append(None) def __getitem__(se...
3,407
1,256
from gna.graph.walk import GraphWalker from gna.graph.timeit import * from gna.graph.walk_functions import *
109
37
# Forward Implementation def print_to_n_reverse(n): if n == 1: # Base Condition print(1, end=" ") return print(n, end=" ") # Induction print_to_n_reverse(n - 1) # Hypothesis # Backward implementation # - Here backward implementation, would be a bit typical to do, # - Forward implementa...
434
145
"""Azure App Gateway Certbot installer plugin.""" from __future__ import print_function import os import sys import logging import time import OpenSSL import base64 try: from secrets import token_urlsafe except ImportError: from os import urandom def token_urlsafe(nbytes=None): return urandom(nbyt...
7,835
2,314
from pathlib import Path from glob import glob as glob from extractor.Ignition import Ignition import logging logger = logging.getLogger(__name__) class Ignitions: """ """ def __init__(self, path, scenario_name, redis): self.redis = redis self.active = False self.name = "Ignition...
1,999
520
""" This code sample is a part of a simple demo to show beginners how to create a skill (app) for the Amazon Echo using AWS Lambda and the Alexa Skills Kit. For the full code sample visit https://github.com/pmckinney8/Alexa_Dojo_Skill.git """ from __future__ import print_function import requests import json alcohol_...
11,913
3,519
#!/usr/bin/env python3 import sys def ints(itr): return [int(i) for i in itr] with open(sys.argv[1], "r") as f: lines = [l for l in f.read().split("\n") if l] ilist = [] imap = {} total = 0 result = 0 other = 0 last = -1 while True: for l in lines: val = int(l.split()[0]) if last !...
474
195
#-*- coding: utf-8 -*- import pythingspeak import unittest class TestPyThingSpeak(unittest.TestCase): def test_update(self): ts = pythingspeak.ThingSpeak( channel_id=59596, api_key='ISXCEH1JHRQR85O4' ) results = ts.update( [ 1, 2 ] ) self.assertTrue(results) def test_feeds(self): ts = pythingspeak.ThingSpe...
2,142
1,029
# coding=utf-8 """ Creates graphic of perfs """ import datetime import typing from collections import namedtuple from tempfile import mktemp import humanize from esst.core import CTX PLT = GRID_SPEC = TICKER = None # https://stackoverflow.com/questions/4931376/generating-matplotlib-graphs-without-a-running-x-serv...
11,920
4,049
# # @lc app=leetcode id=20 lang=python3 # # [20] Valid Parentheses # # https://leetcode.com/problems/valid-parentheses/description/ # # algorithms # Easy (36.20%) # Total Accepted: 554.4K # Total Submissions: 1.5M # Testcase Example: '"()"' # # Given a string containing just the characters '(', ')', '{', '}', '[' a...
1,267
448
import redis from flask import g, session import device import message_queue import os class RedisMQ(message_queue.MessageQueue): redis = None def push(self, data): RedisMQ.redis.lpush(self.queue_key, data) RedisMQ.redis.ltrim(self.queue_key, 0, self.max_size) def pop(self): ...
428
151
import tensorflow as tf import theano import pandas as pd import numpy as np import matplotlib # matplotlib.use('pdf') import matplotlib.pyplot as plt from keras.layers import Dense, Dropout, LSTM, Embedding, Activation, Lambda, Bidirectional from sklearn.preprocessing import OneHotEncoder from keras.engine import Inpu...
4,956
1,669
"""-""" SETTINGS = { 'logging': { 'level': 'DEBUG' } }
72
33
# Copyright 2020 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 ac...
6,911
1,926
class RateRequest(object): """" Used by Price Engine Clients to query the Price Engine """ def __init__(self, exch_1, curr_1, exch_2, curr_2): self.exch_1 = exch_1 self.curr_1 = curr_1 self.exch_2 = exch_2 self.curr_2 = curr_2 self.rate = 0 self.path = [] ...
343
127
# -*- coding: utf-8 -* # @Time : 2020/12/22 15:58 from fastapi import Depends from motor.motor_asyncio import AsyncIOMotorClient from app.api.db.mongoDB import get_database import pandas as pd import numpy as np from io import BytesIO class ExcelTools: def __init__(self, columns_map=None, order=None): ...
2,613
947
"""Simple socket client for the simple socket client.""" import sys import socket import time SOCKET_ADDRESS = "127.0.0.1" SOCKET_PORT = 6996 def build_client_tcp(address: str, port: int): """Builds the TCP client.""" try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(...
1,164
418
import bs4 import nltk import json import re import requests with open('./acronym_abbreviation_id.json', 'r') as f: data = f.read() list_acronym_abbreviation = json.loads(data) from_wikipedia = False if from_wikipedia: # Take text with Indonesian language from Wikipedia randomly html = requests.get('h...
2,689
1,000
'''THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OT...
2,295
958
from DeepRTS import Engine, Constants from DeepRTS.python import GUI from DeepRTS.python import Config from DeepRTS.python import DeepRTSPlayer import numpy as np import random import os import argparse import gym dir_path = os.path.dirname(os.path.realpath(__file__)) class Game(Engine.Game): def __init__(se...
4,330
1,335
from enum import Enum from os.path import expanduser from lairgpt.utils.remote import local_dir class Config(Enum): """Settings for preconfigured models instances """ SMALL = { "d_model": 768, "n_heads": 12, "n_layers": 12, "vocab_size": 50262, "max_seq_len": 1024 ...
1,147
487
import shutil from .smart_open_lib import * DEFAULT_CHUNKSIZE = 16*1024*1024 # 16mb def copy_file(src, dest, close_src=True, close_dest=True, make_path=False): """ Copies file from src to dest. Supports s3 and webhdfs (does not include kerberos support) If src does not exist, a FileNotFoundError is rais...
1,546
497
import rules from backend.models import Folder def add_folder_to_tree_dictionary(folder, resulting_set, include_ancestors=False): """ Adds folder, folder's ancestors and folder's descendants Ancestors are needed to build the traverse path in tree view Descendants are needed because user has permissi...
4,706
1,293
from flask import Flask from flask_cors import CORS from src.ext import configuration def minimal_app(**config): app = Flask(__name__) configuration.init_app(app, **config) CORS(app) return app def create_app(**config): app = minimal_app(**config) configuration.load_extension...
348
118
import datetime as dt import matplotlib.pyplot as plt import matplotlib.dates as mdates import matplotlib.ticker as ticker from matplotlib.dates import MO, TU, WE, TH, FR, SA, SU dates = ['2/29/2020', '3/1/2020', '3/2/2020', '3/3/2020', '3/4/2020', '3/5/2020', '3/6/2020', '3/7/2020', '3/8/2020', '3/9/2020', '3/10/2020...
11,314
9,044
import os import numpy as np import matplotlib.pyplot as plt from PIL import Image import albumentations as A from pathlib import Path import torch from torch import nn from src_backup.cdan import get_model from src.backbone.iresnet import get_arcface_backbone class MyModel(nn.Module): def __init__(self, backbo...
4,357
1,616
import pytest from datetime import datetime from freezegun import freeze_time from pytest_splunk_addon.standard_lib.sample_generation.time_parser import ( time_parse, ) @pytest.fixture(scope="session") def tp(): return time_parse() def generate_parameters(): result = [] for s in ("s", "sec", "secs"...
2,481
1,152
#!/usr/bin/env python """igcollect - Artfiles Hosting Metrics Copyright (c) 2019 InnoGames GmbH """ import base64 from argparse import ArgumentParser from time import time try: # Try importing the Python3 packages from urllib.request import Request, urlopen from urllib.parse import urlencode except Impor...
2,756
910
# -*- coding: utf-8 -*- """ file: corpus.py Description: defines the Corpus object. It is an object representation of a CoNLL-formatted corpus. author: Yoann Dupont MIT License Copyright (c) 2018 Yoann Dupont Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associa...
5,459
1,672
import time import torch from recbole.config import Config from recbole.utils import get_model, init_seed import gensim import gensim.downloader as api from recbole.data import create_dataset, data_preparation import numpy as np URL_FIELD = "item_url" class ItemLM: def __init__(self, checkpoint_file, model_name,...
3,426
1,164
# parsetab.py # This file is automatically generated. Do not edit. # pylint: disable=W,C,R _tabversion = '3.10' _lr_method = 'LALR' _lr_signature = 'INTEGER L_BRACE L_BRACKET RESERVED R_BRACE R_BRACKET SEMICOLON STRUCT TYPE_BOOL TYPE_CSTDINT TYPE_PRIMITIVE_FLOAT TYPE_PRIMITIVE_INT TYPE_STRING TYPE_UNSIGNED VAR_NAMEM...
2,842
1,481
from packet import packet # Camada Fisica class fisica(): ''' @param link list(hosts) @param ativo boolean (true|false) ''' def __init__(self): self.__link = [] # self.__link = link self.__is_ativo = False self.__dado = packet def __SetAtivo(self,ativo): self.__is_ativo = ativo de...
548
203
from backend import * from basement import * from pausable import * from kittyaccesscontrol import * from kittybase import KittyBase from erc721 import ERC721 from erc721metadata import ERC721Metadata # @title The facet of the CryptoKitties core contract that manages ownership, ERC-721 (draft) compliant. # @author Ax...
11,792
3,667
import os import const as CONST from datetime import datetime # Const MENU_ROOT = 0 MENU_SPECIFY_DATE = 1 MENU_SPECIFY_PERCENT_TRAINED = 2 currMenu = MENU_ROOT stockList = ['AAPL', '^DJI', '^HSI', '^GSPC'] def welcomeMessage(): print('##############################################################################'...
5,009
1,557
# Copyright 2022, Lefebvre Dalloz Services # # 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 ag...
3,410
1,080
import numpy as np from tqdm import tqdm from scipy.sparse import csr_matrix, hstack, vstack from sklearn.neighbors import NearestNeighbors class MFKnn(object): """ Implementation of """ def __init__(self, metric, k): self.k = k self.metric = metric def fit(self, X, y): # self.X_train = X self.y_tr...
2,361
1,161
#Given 2 strings, a and b, return the number of the positions where they contain the same length 2 substring. So "xxcaazz" and "xxbaaz" yields 3, since the "xx", "aa", and "az" substrings appear in the same place in both strings. #string_match('xxcaazz', 'xxbaaz') → 3 #string_match('abc', 'abc') → 2 #string_match('abc...
581
222
#!/usr/bin/env python #-*- coding:utf-8 -*- """ Tools http://en.wikipedia.org/wiki/Haversine_formula ToDo: ToFix / ToTest """ import math def waypoint_bearing(lat1, lon1, lat2, lon2): """ Calculates the bearing between 2 locations. Method calculates the bearing between 2 locations. @param lon1 ...
2,458
972
from django.shortcuts import render, redirect, render_to_response from django.template.context import RequestContext from account.views import login from models import Course from website.views import index from forms import CourseForm, CourseInitialForm from account.util import createImage from django.core.context_pro...
10,951
3,105
from rx.core import ObservableBase, AnonymousObservable, typing from rx.disposables import CompositeDisposable, \ SingleAssignmentDisposable, SerialDisposable def delay_with_selector(self, subscription_delay=None, delay_duration_mapper=None) -> ObservableBase: """Time shifts the observ...
2,701
703
class Palindrome: def __init__(self, test): self.test = test def __call__(self): test_strip = list([n for n in self.test if n.isalpha() or n.isnumeric()]) self.test = "".join(test_strip) self.test = self.test.lower() #Test to see if the phrase/word is a palindrome ...
719
239
#!/usr/bin/env python3 import hash_framework as hf hf.config.model_dir = "/home/cipherboy/GitHub/sat/sat-competition-2018/models" import time, sys, os, random run = False release = False if '--run' in sys.argv: run = True if '--release' in sys.argv: release = True if '-h' in sys.argv or '--help' in sys.argv:...
3,890
1,557
import os import datetime import xxhash import json from flask_sqlalchemy import SQLAlchemy from methinks.utils import str_to_date from methinks.config import get_default_conf db = SQLAlchemy() class Entry(db.Model): __tablename__ = 'entry' id = db.Column(db.Integer, primary_key=True) hexid = db.Colum...
3,357
1,071
import functools def log(func): @functools.wraps(func) def wrapper(*args, **kw): print('call %s():' % func.__name__) return func(*args, **kw) return wrapper @log def now(): print('2018-01-29') now() def logger(text): def decorator(func): @functools.wraps(func) def...
580
218
''' point clouds estimation: transfer sparse map to dense map, work for both depth and reflectance. ''' import sys sys.path.append("..") from utils import data_provider from utils import velo_2_cam import numpy as np # fetch image and point clouds: coordinates and reflectance def rawData(pc_path_, img_path_): ...
2,797
955
from ogle.code_generator.code_generator import CodeGenerator from ogle.lexer.lexer import Lexer from ogle.parser.parser import Parser from ogle.semantic_analyzer.semantic_analyzer import SemanticAnalyzer def _get_errors_warnings(all_errors): errors = [e for e in all_errors if 'Error' in e[1]] warnings = [e for...
1,014
328
# !depth first search !dfs !graph # dict of nodes as the key and sets for the edges(children) graph = {'A': set(['B', 'C', 'D']), 'B': set(['E', 'F']), 'C': set([]), 'D': set(['G', 'H']), 'E': set([]), 'F': set(['I', 'J']), 'G': set(['K']), 'H': set([]), 'I': set([]), 'J': set([]), 'K': ...
817
314