text string | size int64 | token_count int64 |
|---|---|---|
import os
import zipfile
import zlib
def make_rel_archive(a_parent, a_name):
archive = zipfile.ZipFile("release/" + a_name + ".zip", "w", zipfile.ZIP_DEFLATED)
def do_write(a_relative):
archive.write(a_parent + a_relative, a_relative)
do_write("F4SE/Plugins/" + a_name + ".dll")
do_write("F4SE/Plugins/" + a_name... | 936 | 392 |
#!/usr/bin/env python3
# MIT License
#
# Copyright (c) 2020, Alex M. Maldonado
#
# 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 right... | 8,246 | 3,260 |
"""Evaluating Prophet model on M4 timeseries
"""
from darts.models import Prophet
from darts.utils.statistics import check_seasonality
from darts.utils import _build_tqdm_iterator
import numpy as np
import pandas as pd
import pickle as pkl
from M4_metrics import owa_m4, mase_m4, smape_m4
if __name__ == "__main__"... | 3,553 | 1,104 |
import codecs
import sys
import argparse
parser = argparse.ArgumentParser(description='manual to this script')
parser.add_argument('--file', type=str, default = None)
parser.add_argument('--quantity', type=int, default=5785)
args = parser.parse_args()
output = codecs.open('weightcn.txt', 'w', 'utf-8')
dic = {}
i = 0
f... | 1,100 | 378 |
#!/usr/bin/env python
# encoding: utf-8
# The MIT License (MIT)
# Copyright (c) 2019-2020 CNRS
# 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 limita... | 16,619 | 4,388 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import os
from datasets import convert_data
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string('data_type', None,
'The type of the dataset to convert, ne... | 1,352 | 398 |
# -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
import numpy as np
from numpy.testing import assert_array_equal, assert_allclose
from vispy.testing import run_tests_if_main
from vispy.geometry import (create_box, create_cub... | 1,933 | 725 |
import logging
import numpy as np
from bico.geometry.point import Point
from bico.nearest_neighbor.base import NearestNeighbor
from bico.utils.ClusteringFeature import ClusteringFeature
from datetime import datetime
from typing import Callable, TextIO, List
logger = logging.getLogger(__name__)
class BICONode:
de... | 3,990 | 1,262 |
"""
Lite install NLTK resource
"""
import nltk
dler = nltk.downloader.Downloader()
dler._update_index()
dler._status_cache['panlex_lite'] = 'installed' # Trick the index to treat panlex_lite as it's already installed.
dler.download('all')
| 239 | 86 |
import pyvisa
def find_instruments():
rm = pyvisa.ResourceManager()
instruments = rm.list_resources()
return {'usb':[i for i in instruments if 'USB' in i],
'gpib':[i for i in instruments if 'GPIB' in i],
'serial':[i for i in instruments if 'ASRL' in i]}
def play_star_wars(smu):
... | 1,224 | 580 |
# import required module
import ctypes
# create node class
class Node:
def __init__(self, value):
self.value = value
self.npx = 0
# create linked list class
class XorLinkedList:
# constructor
def __init__(self):
self.head = None
self.tail = None
self.__nodes = []
# method to insert no... | 5,406 | 2,297 |
"""
class to read files in specific ways
"""
import glob
import random
class Filer:
"""
read files
"""
def __init__(self, file_path):
self.path = file_path
def get_random_iter(self):
"""
get file contents in random
"""
nb_files = sum(1 for _ in glob.iglob(self.path))
file_iter = glob.glob(self.path... | 354 | 144 |
import numpy as np
from scipy.stats import linregress as li
from math import exp
def calc_factor(field,stepsize=0.01):
"""
Function for calculation of the summed binning.
The returned result is an integral over the binning of the velocities.
It is done for the negative and positive half separately.
... | 6,335 | 2,374 |
from machine import Pin, UART
from grip import Grip
import time
class Floppy:
AXIS_POS_LIMIT = (0, 5, 5)
AXIS_NEG_LIMIT = (-7.5, 0, -5)
def __init__(self):
# region Attributes
self._speed = 20
self._buffer = 0
self._pos_tracker = [0.0, 0.0, 0.0]
# endregion
... | 4,347 | 1,476 |
from controllers.controller import Controller
from dao.wind_measurement_dao import WindMeasurementDao
from sensors.wind_measurement_sensor import WindMeasurementSensor
class WindMeasurementController(Controller):
""" Represents the controller with the wind measurement sensor and DAO """
def __init__(self, an... | 891 | 193 |
import FWCore.ParameterSet.Config as cms
# AlCaReco for track based alignment using MinBias events
OutALCARECOTkAlMinBias_noDrop = cms.PSet(
SelectEvents = cms.untracked.PSet(
SelectEvents = cms.vstring('pathALCARECOTkAlMinBias')
),
outputCommands = cms.untracked.vstring(
'keep *_ALCARECOTk... | 750 | 285 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.10 on 2016-11-04 21:12
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_depende... | 984 | 302 |
"""
https://leetcode.com/problems/rectangle-overlap/
A rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) are the coordinates of its bottom-left corner, and (x2, y2) are the coordinates of its top-right corner.
Two rectangles overlap if the area of their intersection is positive. To be clear, two rec... | 1,282 | 471 |
import os
def get_token():
return os.environ['VACCINEBOT_TOKEN'] | 69 | 28 |
import logging
from fluiddb.data.store import getMainStore
from fluiddb.exceptions import FeatureError
from fluiddb.model.namespace import NamespaceAPI
from fluiddb.model.tag import TagAPI
from fluiddb.model.user import UserAPI, getUser
TESTING_DATA = {
u'users': [
u'testuser1',
u'testuser2'],
... | 2,651 | 813 |
import urllib3
import pandas as pd
import numpy as np
import zipfile
import copy
import pickle
import os
from esig import tosig
from tqdm import tqdm
from multiprocessing import Pool
from functools import partial
from os import listdir
from os.path import isfile, join
from sklearn.ensemble import RandomForestClassifier... | 6,752 | 2,433 |
#-------------------------------------------------------------------------------
# Filename: create_pics.py
# Description: creates square pictures out of a picture which is mostly empty
# for training a neural network later.
# The parameters to fool around with include:
# factor: scaled down image for faster imag... | 7,254 | 2,295 |
from .metatradercom import (MetatraderCom, ConnectionTimeoutError,
DataNotFoundError)
from .timeframe import MT5TimeFrame
| 150 | 37 |
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class Driver(models.Model):
name = models.CharField(max_length=30)
password = models.CharField(max_length=30)
email = models.EmailField()
Contact = models.CharField(max_length=10)
def s... | 2,600 | 857 |
"""
Helper functions for the tests
"""
import os
import numpy as np
from msl.io import read
def read_sample(filename, **kwargs):
"""Read a file in the 'samples' directory.
Parameters
----------
filename : str
The name of the file in the samples/ directory
Returns
-------
A root... | 1,870 | 673 |
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 19 17:35:09 2016
@author: yxl
"""
from imagepy.core.engine import Tool
import numpy as np
from imagepy.core.manager import ColorManager
from imagepy.core.draw.fill import floodfill
class Plugin(Tool):
title = 'Flood Fill'
para = {'tor':10, 'con':'8-connect'}
... | 1,019 | 402 |
"""Signal dispatchers and handlers for the articles module"""
from django.db.models.signals import post_save
from django.dispatch import receiver, Signal
from authors.apps.articles.models import Article
# our custom signal that will be sent when a new article is published
# we could have stuck to using the post_save ... | 953 | 244 |
"""TFTBechmark scripts"""
import shutil
import tempfile
import time
import tensorflow as tf
import tqdm
from datasets import load_dataset
from transformers import RobertaTokenizerFast
from tf_transformers.models import Classification_Model
from tf_transformers.models import RobertaModel as Model
_ALLOWED_DECODER_TYP... | 4,923 | 1,487 |
class Node():
def __init__(self,data):
self.data=data
self.ref=None
class LinkedList():
def __init__(self):
self.head=None
def Print_ll(self):
n=self.head
if n is None:
print("LinkedList is empty")
else:
while n is not None:
... | 393 | 123 |
from flask import Flask
from flask_migrate import Migrate
from devlivery.ext.db import db
migrate = Migrate()
def init_app(app: Flask):
migrate.init_app(app, db)
| 170 | 64 |
from src.models.catalog.video_info import VideoMetaInfo
from src.query_planner.abstract_plan import AbstractPlan
from src.query_planner.types import PlanNodeType
class StoragePlan(AbstractPlan):
"""
This is the plan used for retrieving the frames from the storage and
and returning to the higher levels.
... | 1,027 | 292 |
/usr/local/lib/python3.6/base64.py | 34 | 18 |
import logging
import matplotlib.pyplot as plt
import argparse
from typing import List
from enum import Enum
from enum import Enum
class Constants:
class PlotType(Enum):
HAILSTONE = 'HAILSTONE'
PEAK = 'PEAK'
STOPPING_TIMES = 'STOPPING_TIMES'
class Stats:
def __init__(self, num : int, total_stopping_time : int... | 2,802 | 1,158 |
#
# Copyright(c) 2020-2021 Intel Corporation
# SPDX-License-Identifier: BSD-3-Clause-Clear
#
import os
import pytest
from api.cas import casadm
from api.cas.cache_config import CacheMode
from core.test_run import TestRun
from storage_devices.disk import DiskTypeSet, DiskType, DiskTypeLowerThan
from test_tools.dd impo... | 2,894 | 929 |
import pygame
from pygame.locals import *
from .GameState import GameState
class ResultState(GameState):
def __init__(self, stateSwitcher): super().__init__(stateSwitcher)
def Event(self, event):
if event.type == KEYDOWN:
if event.key == K_RETURN or event.key == K_SPACE or event.key == K_z:... | 393 | 128 |
# type: ignore
# This is a small script to parse the header files from wasmtime and generate
# appropriate function definitions in Python for each exported function. This
# also reflects types into Python with `ctypes`. While there's at least one
# other generate that does this already it seemed to not quite fit our p... | 7,093 | 2,266 |
#!/usr/bin/env python3
#encoding=utf-8
#------------------------------------------------
# Usage: python3 3-desc-state-inst.py
# Description: descriptor for attribute intercept
#------------------------------------------------
class InstState: # Using instance state, (object) in 2.X
def __get__(self, inst... | 1,115 | 403 |
import time
from dataclasses import dataclass
from datetime import date, datetime
from property_app.config import get_config
config = get_config()
@dataclass
class AppInfo:
project: str = config.ASGI_APP
commit_hash: str = config.APP_BUILD_HASH
build_date: date = datetime.today()
build_epoch_sec: i... | 342 | 109 |
bind = "0.0.0.0:5000"
backlog = 2048
workers = 1
worker_class = "sync"
threads = 16
spew = False
reload = True
loglevel = "debug"
| 133 | 66 |
import requests
print """
CVE-2015-6668
Title: CV filename disclosure on Job-Manager WP Plugin
Author: Evangelos Mourikis
Blog: https://vagmour.eu
Plugin URL: http://www.wp-jobmanager.com
Versions: <=0.7.25
"""
website = raw_input('Enter a vulnerable website: ')
filename = raw_input('Enter a file nam... | 723 | 258 |
#!/usr/bin/env python3
import setuptools
setuptools.setup(
name='sql-remove-comma',
description='remove illegal trailing commas from your SQL code',
use_scm_version=True,
author='Io Mintz',
author_email='io@mintz.cc',
long_description=open('README.md').read(),
long_description_content_type='text/markdown',
li... | 1,129 | 439 |
from utils import project_list
from learning import IncrementalLearningModel
def get_testing_dataset_size(prj):
l = IncrementalLearningModel(prj['name'], 'RF', 30, 1)
y_proba, y_test = l.get_predicted_data()
return len(y_test)
def main():
for idx, prj in enumerate(project_list):
print(prj['... | 418 | 151 |
import zebra
from workflow import Workflow
if __name === '__main__':
wf = Workflow()
wf.cache_data('zebra_all_projects', zebra.get_all_projects())
wf.cache_data('zebra_aliased_activities', zebra.get_aliased_activities()) | 228 | 89 |
# ================================================================
# MIT License
# Copyright (c) 2022 edwardyehuang (https://github.com/edwardyehuang)
# ================================================================
import tensorflow as tf
from iseg.layers.normalizations import normalization
from iseg.utils.attent... | 10,729 | 3,523 |
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... | 2,009 | 541 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/home/rach/Documents/lanzou-gui/share.ui'
#
# Created by: PyQt5 UI code generator 5.13.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, D... | 5,979 | 2,080 |
for t in range(int(input())):
n=int(input())
if n%2==0:
print(int(n/2-1))
else:
print(int(n//2)) | 129 | 59 |
import sys
import os
import time
import random
import numpy as np
from termcolor import colored
from functools import partial
from tensorboardX import SummaryWriter
import torch
from torch.utils.data import DataLoader
from torchvision import transforms as tv_transforms
import solt.transforms as slt
import solt.c... | 6,959 | 2,276 |
from . import shellcommands
from ..linux import LinuxOS
__author__ = 'Filinto Duran (duranto@gmail.com)'
# TODO: break unix/linux to a bare and expand from there
class BusyBoxOS(LinuxOS):
"""
Embedded Linux device
"""
name = 'busybox'
cmd = shellcommands.get_instance()
| 293 | 94 |
import math
import numpy as np
import os.path
import urllib.request as urllib
import gzip
import pickle
import pandas as pd
from scipy.misc import imsave
from src.utils.download import *
import src.utils.image_load_helpers as image_load_helpers
import glob
def CelebA_load(label_data = None, image_paths = None, batch_... | 11,988 | 4,504 |
value1 = int(input()); value2 = value1//100
if value1 % 2==0 and value2 % 2==0:
print("Even")
elif value1 % 2==0 and value2 % 2==1:
print("Even Odd")
elif value1 % 2==1 and value2 % 2==1:
print("Odd")
elif value1 % 2==1 and value2 % 2==0:
print("Odd Even")
| 282 | 130 |
#!/usr/bin/env python
column1 = "NETWORK_NUMBER"
column2 = "FIRST_OCTET_BINARY"
column3 = "FIRST_OCTET_HEX"
ip_addr = '88.19.107.0'
formatter = '%-20s%-20s%-20s'
octets = ip_addr.split('.')
a = bin(int(octets[0]))
b = hex(int(octets[0]))
print ""
print formatter % (column1, column2, column3)
print formatter % (ip_ad... | 339 | 164 |
from serendipity.linear_structures.singly_linked_list import LinkedList
class Set:
def __init__(self):
self._list = LinkedList()
def get_size(self):
return self._list.get_size()
def is_empty(self):
return self._list.is_empty()
def contains(self, e):
return self._list... | 511 | 192 |
# -*- coding: utf-8 -*-
"""
settings = conf.default.py + settings_{env}.py
"""
# import os
# import importlib
from conf.default import *
# ========================================================================================
# IMPORT ENV SETTINGS
# =================================... | 1,546 | 459 |
#!/usr/bin/env python
# coding: utf-8
import argparse
import elitech
import datetime
from elitech.msg import (
StopButton,
ToneSet,
AlarmSetting,
TemperatureUnit,
)
from elitech.msg import _bin
import six
import os
def main():
args = parse_args()
if (args.command == 'simple-set'):
com... | 7,958 | 2,838 |
#!/usr/bin/env python
import sys
import string
import re
for line in sys.stdin:
if '"' in line:
entry = re.split(''',(?=(?:[^'"]|'[^']*'|"[^"]*")*$)''', line)
else:
entry = line.split(",")
licence_type = entry[2]
amount_due = entry[-6]
print("%s\t%s" % (licence_type, amount_due))
| 295 | 132 |
from .gan_attack import GAN_Attack # noqa: F401
from .generator_attack import Generator_Attack # noqa: F401
from .gradientinversion import GradientInversion_Attack # noqa: F401
from .mi_face import MI_FACE # noqa: F401
from .utils import DataRepExtractor # noqa: F401
| 273 | 107 |
# Задача 4. Вариант 7.
# Напишите программу, которая выводит имя, под которым скрывается Мария Луиза Чеччарелли. Дополнительно необходимо вывести область интересов указанной личности, место рождения, годы рождения и смерти (если человек умер), вычислить возраст на данный момент (или момент смерти). Для хранения всех не... | 867 | 340 |
from flask_restplus import fields, Model
def add_models_to_namespace(namespace):
namespace.models[route_request_model.name] = route_request_model
route_request_model = Model("Represents a Route Request", {
"id": fields.Integer(description="Unique identifier for the ride"),
"start_point_lat": fields.Floa... | 676 | 184 |
# @Time : 2016/8/17 10:56
# @Author : lixintong
import logging
import os
import sys
from PyQt5 import uic
from PyQt5.QtCore import pyqtSignal, Qt
from PyQt5.QtWidgets import QMainWindow, QApplication, QDesktopWidget, QMessageBox
from uitester.test_manager.tester import Tester
from uitester.ui.case_manager.case_ed... | 4,554 | 1,389 |
from collections import OrderedDict
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Module
'''
# ===================================
# Advanced nn.Sequential
# reform nn.Sequentials and nn.Modules
# to a single nn.Sequential
# ===================================
'''
def sequen... | 13,034 | 4,473 |
#
# Copyright (c) 2019-2021 Ibrahim Umit Akgun
# Copyright (c) 2021-2021 Andrew Burford
# Copyright (c) 2021-2021 Mike McNeill
# Copyright (c) 2021-2021 Michael Arkhangelskiy
# Copyright (c) 2020-2021 Aadil Shaikh
# Copyright (c) 2020-2021 Lukas Velikov
# Copyright (c) 2019-2021 Erez Zadok
# Copyright (c) 2019-2021 Sto... | 8,251 | 2,578 |
# -*- encoding: utf-8 -*-
"""
Created by Ênio Viana at 01/09/2021 at 19:51:44
Project: py_dss_tools [set, 2021]
"""
import attr
import pandas as pd
from py_dss_tools.model.other import VSource
from py_dss_tools.utils import Utils
@attr.s
class Circuit(VSource):
_name = attr.ib(validator=attr.validators.instanc... | 6,374 | 2,256 |
from dataclasses import dataclass
from util import load_input, bear_init
box_specs = load_input(2)
@bear_init
@dataclass
class Box:
l: int
w: int
h: int
@classmethod
def from_str(cls, s: str) -> "Box":
l, w, h = tuple(map(int, s.split("x")))
return Box(l, w, h)
@property
... | 1,270 | 493 |
# Copyright (c) 2021 - Jojo#7791
# Licensed under MIT
import asyncio
from contextlib import suppress
from typing import List
import discord
from redbot.core import commands
from redbot.core.utils.chat_formatting import pagify
from redbot.core.utils.predicates import MessagePredicate
from ..abc import TodoMixin
from ... | 7,928 | 2,194 |
# This file is part of MaixPY
# Copyright (c) sipeed.com
#
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license.php
#
from network_espat import wifi
wifi.reset()
print(wifi.at_cmd("AT\r\n"))
print(wifi.at_cmd("AT+GMR\r\n"))
'''
>>> reset...
b'\r\n\r\nOK\r\n'
b'AT version:1.1.0.0(May 1... | 544 | 289 |
from preprocessing.dataset import SVHNDataset
import numpy as np
import configparser as cp
from datetime import datetime as dt
import os
from sklearn.decomposition import PCA
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
if __name__ == "__main__":
config = cp.ConfigParser()
config.r... | 1,513 | 520 |
# File: DoodleParser.py
#
# Author: Luigi Berducci
# Date: 2018-11-30
import sys
import datetime
import requests
import json
class DoodleParser:
"""
Retrieves poll data from doodle.com and fill data structure
for participants, options and preferences.
"""
pollID = ""
participan... | 4,117 | 1,202 |
"""
VARIÁVEIS DE CONFIGURAÇÃO DO BOT
True PARA ATIVAR E False PARA DESATIVAR
"""
escrever_nos_campos = True # PREENCHE OS CAMPOS COM AS RESPOSTAS
modo_de_aprendizado = False # APRENDE NOVAS RESPOSTAS SALVANDO AS RESPOSTAS DOS OUTROS JOGADORES
clica_botao_avaliar_respostas = True # CLICA NO BOTÃO "AVALIAR"
clic... | 381 | 184 |
# -*- coding: utf-8 -*-
def a(i,x,X,Y):
rep=1
for j in range(min(len(X),len(Y))):
if (i!=j):
rep*=(x-X[j])/(X[i]-X[j])
return (rep)
def P(x,X,Y):
rep=0
for i in range(min(len(X),len(Y))):
rep+=a(i,x,X,Y)*Y[i]
return (rep)
X=[-2,0,1,2]
Y=[49,5,7,49]
#x=float(input(" Vous voulez estimer... | 1,164 | 726 |
#!/usr/bin/env python
import rospy, tf
from gazebo_msgs.srv import *
from geometry_msgs.msg import *
if __name__ == '__main__':
rospy.init_node("stock_products")
rospy.wait_for_service("gazebo/delete_model") # <1>
rospy.wait_for_service("gazebo/spawn_sdf_model")
delete_model = rospy.ServiceProxy("gazebo/delete... | 990 | 427 |
'''
Mass evolution of GC
Created Apr. 2020
Last Edit Apr. 2020
By Bill Chen
'''
import numpy as np
# Note: all times in [Gyr]
# ***** Dynamic evolution of GC in Choksi & Gnedin (2018) *****
def t_tid_cg18(m):
# Tidally-limited disruption timescale in Choksi & Gnedin (2018)
P = 0.5
return 5 * ((m/2e5)*... | 846 | 417 |
import solutions
def test_deploy_config():
deploy_config = solutions.config.deploy_config
assert deploy_config['reference_case'] == 'ref_case'
assert type(deploy_config['reference_case_path']) == list
assert deploy_config['reference_case_file_format'] == 'history'
assert deploy_config['case_to_com... | 355 | 102 |
from django.conf import settings
from django.db import models
class Tasks(models.Model):
"Generated Model"
task_name = models.TextField()
| 148 | 42 |
from django.conf.urls import include, url
from django.contrib import admin
from rest.views import TestRestView, TestAuthHeaderView, TestAuthUrlView
urlpatterns = [
url('^rest/$', TestRestView.as_view(), name='rest'),
url('^auth_header_rest/$', TestAuthHeaderView.as_view(), name='rest_auth_header'),
url('^a... | 405 | 135 |
import os
import json
from vector2d import Vector2D
from interpolator import Interpolator
from utils import map_range
# Each game controller axis returns a value in the closed interval [-1, 1]. We
# limit the number of decimal places we use with the PRECISION constant. This is
# done for a few reasons: 1) it makes th... | 16,625 | 4,738 |
from django.db import models
LOJAS = (
('TES', 'TES'),
('TEU', 'TEU'),
('TMA', 'TMA'),
('TPI', 'TPI'),
('TMO', 'TMO'),
('TEZ', 'TEZ'),
('TED', 'TED'),
('TPP', 'TPP'),
('TIM', 'TIM'),
('TEC', 'TEC'),
('RTT', 'RTT'),
... | 2,387 | 960 |
import numpy as np
from scipy.optimize import linear_sum_assignment
def intersection_over_union(segmented_map, gt_map):
s_array = segmented_map.getEmMap().data()
gt_array = gt_map.getEmMap().data()
labels = np.unique(gt_array)
if s_array.shape != gt_array.shape:
return ValueError("Arrays must h... | 7,377 | 2,608 |
import operator
import unittest
from asq.queryables import Queryable
__author__ = "Robert Smallshire"
class TestPreScan(unittest.TestCase):
def test_pre_scan_empty_default(self):
a = []
b = Queryable(a).pre_scan().to_list()
c = []
self.assertEqual(b, c)
def test... | 1,554 | 670 |
class ComplexNumber:
# TODO: write your code here
def __init__(self,real=0, imag=0):
self.real_part = real
self.imaginary_part = imag
def __str__(self):
return f"{self.real_part}{self.imaginary_part:+}i"
if __name__ == "__main__":
import json
input_args = list(json.loads(inp... | 504 | 177 |
# -*- coding: utf-8 -*-
#
import wx
from form.panel.BasePanel import BasePanel
from utils.MLogger import MLogger # noqa
logger = MLogger(__name__)
class ParamAdvancePanel(BasePanel):
def __init__(self, frame: wx.Frame, export: wx.Notebook, tab_idx: int):
super().__init__(frame, export, tab_idx)... | 1,853 | 764 |
import numpy as np
from scipy.optimize import leastsq, least_squares
from hexrd import instrument
from hexrd.matrixutil import findDuplicateVectors
from hexrd.fitting import fitpeak
from hexrd.ui.hexrd_config import HexrdConfig
from hexrd.ui.utils import convert_tilt_convention
class InstrumentCalibrator(object):
... | 10,830 | 3,346 |
import pandas as pd
root = "Split/"
types = ["train-70", "test-30"]
for type in types:
filenames = ["2020-03-"+str(i)+"-Labels-"+type for i in range(12, 29)]
for suffix in ["pos", "neg", "neu"]:
data = []
for filename in filenames:
path = root + filename
data += li... | 503 | 190 |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@Project: python
@Date: 8/30/2018 9:53 PM
@Author: xuegangliu
@Description: login
"""
import urllib.request
import http.cookiejar
import urllib.parse
def getOpener(header):
'''构造文件头'''
# 设置一个cookie处理器,它负责从服务器下载cookie到本地,并且在发送请求时带上本地的cookie
coo... | 1,638 | 706 |
from django.core.exceptions import SuspiciousOperation
from django.core.signing import Signer, BadSignature
from django.forms import HiddenInput
signer = Signer()
class SignedHiddenInput(HiddenInput):
def __init__(self, include_field_name=True, attrs=None):
self.include_field_name = include_field_name
... | 1,277 | 380 |
class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
money = [0, 0, 0]
for x in bills:
if x == 5:
money[0] += 1
if x == 10:
if money[0] >= 1:
money[1] += 1
money[0] -= 1
... | 738 | 217 |
# MIT License
#
# Copyright (c) 2021 Soohwan Kim and Sangchun Ha and Soyoung Cho
#
# 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... | 3,684 | 1,094 |
#Do Not Edit
#colors R G B
white = (255, 255, 255)
red = (255, 0, 0)
green = ( 0, 255, 0)
blue = ( 0, 0, 255)
black = ( 0, 0, 0)
cyan = ( 50, 255, 255)
magenta = (255, 0, 255)
yellow = (255, 255, 0)
orange = (255, 127, 0)
#The Service/Notifications List
# L... | 1,231 | 551 |
from fastapi import APIRouter
from starlette.requests import Request
router = APIRouter()
@router.get('/')
async def read_root(request: Request):
return "ML serving with fastapi"
@router.get('api/predict')
async def predict_number(request: Request):
model = request.app.ml_model
return model.predict('bla... | 324 | 96 |
# Copyright 2020 The TensorFlow Probability Authors.
#
# 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 o... | 1,902 | 591 |
config = {}
with open("config.txt", "r") as f:
lines = f.readlines()
for line in lines:
key, value = line.split("=")
value = value.replace("\n", "")
config[key] = value
print(f"Added key {key} with value {value}")
user_key = input("Which key would you like to see? ")
if user_ke... | 788 | 266 |
"""
Extensões populares
Flask Mail - Fornece uma interface SMTP para o aplicativo Flask
Flask WTF - Adicione renderização e validação de WTForms
Flask SQLAlchemy - Adicionando suporte SQLAlchemy para o aplicativo Flask
Flask Sijax-Sijax - biblioteca de interface-Python/jQuery para tornar o AJAX fácil de usar em apl... | 414 | 137 |
import os
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
def isAccess(path):
try:
os.listdir(path)
return True
except PermissionError:
return False
@login_required
def isExist(request):
return HttpResponse(os.path.exists(os.path.abspat... | 1,128 | 361 |
"""
1D Maxwellian distribution function
===================================
We import the usual modules, and the hero of this notebook,
the Maxwellian 1D distribution:
"""
import numpy as np
from astropy import units as u
import matplotlib.pyplot as plt
from astropy.constants import (m_e, k_B)
from plasmapy.formula... | 1,887 | 601 |
from .kvae import KVAE
__all__ = (
'KVAE',
)
| 50 | 27 |
# -*- coding: utf-8 -*-
import pymysql
import time
import os
import matplotlib.pyplot as plt
print(os.getcwd())
db = pymysql.connect(
host='localhost',
user='root',
passwd='xxxx',
database='男运动鞋'
)
cur = db.cursor()
cur.execute('select productSize from all_comments;')
all_size... | 1,603 | 656 |
# A little bit of molecular biology
# Codons are non-overlapping triplets of nucleotides.
# ATG CCC CTG GTA ... - this corresponds to four codons; spaces added for emphasis
# The start codon is 'ATG'
# Stop codons can be 'TGA' , 'TAA', or 'TAG', but they must be 'in frame' with the start codon. The first stop codon ... | 3,769 | 1,459 |
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.views.generic import TemplateView
class LiquidsoapScriptView(TemplateView):
content_type = "text/plain"
template_name = "radio/radio.liq"
def dispatch(self, request, *args, **kwargs):
secret_key = req... | 528 | 149 |
from abc import ABC, abstractmethod
from torch import nn
from typing import Dict, List
import torch
class Merge(ABC, nn.Module):
'''A Merge module merges a dict of tensors into one tensor'''
@abstractmethod
def forward(self, xs: dict) -> torch.Tensor: # pragma: no cover
raise NotImplementedError... | 2,601 | 766 |
import os
import logging
import pdb
import time
import random
from multiprocessing import Process
import numpy as np
from client import MilvusClient
import utils
import parser
from runner import Runner
logger = logging.getLogger("milvus_benchmark.local_runner")
class LocalRunner(Runner):
"""run local mode"""
... | 6,919 | 1,848 |