content
stringlengths
5
1.05M
def intro(): print("Ctrl Everything")
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.4' # jupytext_version: 1.1.5 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # s_di...
from setuptools import setup setup( name = "greeksyntax", version = "0.1.dev0", license = "Apache 2.0", author = "Jonathan Robie", author_email = "jonathan.robie@biblicalhumanities.org", packages = ["greeksyntax"], package_data = { "greeksyntax" : "greeksyntax/*.css", }, install_re...
import pytest from tempfile import NamedTemporaryFile @pytest.fixture def temp_db_file(): with NamedTemporaryFile('w', buffering=1) as temp_file: yield temp_file @pytest.fixture def temp_csv_file(): with NamedTemporaryFile('w', buffering=1, suffix='.csv') as temp_file: yield temp_file @pyt...
import math import matplotlib from ai2thor.controller import Controller matplotlib.use("TkAgg", warn=False) from PIL import Image, ImageDraw import copy import numpy as np class ThorPositionTo2DFrameTranslator(object): def __init__(self, frame_shape, cam_position, orth_size): self.frame_shape = frame_...
from panther_base_helpers import deep_get def policy(resource): return deep_get(resource, 'SSEDescription', 'Status') == 'ENABLED'
from PIL import Image, ImageDraw, ImageFont, ImageFilter from random import randint def generate_captcha(): # Generate one letter def gen_letter(): return chr(randint(65, 90)) def rndColor(): return (randint(64, 255), randint(64, 255), randint(64, 255)) def rndColor2(): retur...
import pandas as pd import os from csv import writer dataset = pd.read_csv("All_Year_Player_Points_IPL.csv") rows = dataset.shape[0] # players = {} # print(rows) for i in range(0, rows): name = " ".join(dataset["PLAYER"][i].split()) + ".csv" name = name.replace(" ", "_") # print(name) data = [dataset["...
class KnownError(Exception): def __init__(self, message: str, detail: str = ""): self.detail = detail self.message = message
from itertools import permutations def read_input(input_file): with open(input_file, "r") as f: return [i for i in f.readlines()] def parse_segment(input: str): return [tuple(l.split(" ")) for l in input.replace("\n", "").split(" | ")] def get_numbers_of_unique_segments(input_file: str): lines...
import numpy as np import time from meta_mb.logger import logger import gym from gym import error, spaces from meta_mb.meta_envs.base import MetaEnv from blue_interface.blue_interface import BlueInterface class BlueReacherEnv(MetaEnv, BlueInterface, gym.utils.EzPickle): def __init__(self, side='right', ip='127.0....
# The MIT License (MIT) # Copyright (c) 2021 Tom J. Sun # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, ...
from copy import deepcopy # class AvoidPartnerPassDominoesBehavior: # class SeekEnemyPassDominoesBehavior: class GreedyDominoesBehavior: def __init__(self): pass def update_world_state(self, world_state, event, value): return world_state def eval(self, action, world_state): i...
import platform import os import time # numpy/opencv import numpy as np import cv2 as cv import pandas as pd import bokeh from bokeh.io import curdoc from bokeh.events import SelectionGeometry from bokeh.models import ColumnDataSource, HoverTool, Button, Div, BoxSelectTool, CustomJS from bokeh.plotting import figure...
from xendit.models._base_model import BaseModel class InvoiceRetailOutlet(BaseModel): """EWallet data detail in Invoice (API Reference: Invoice) Attributes: - ewallet_type (str) """ ewallet_type: str
# -*- coding: utf-8 -*- """ Copyright (c) 2020, Ernest Iu Created by the Plotnikov Lab at the University of Toronto Email Contacts: Ernest Iu: ernest.iu@mail.utoronto.ca Sergey Plotnikov: sergey.plotnikov@utoronto.ca This script is part of a software designed for the analysis of cell spreading assays. This softwa...
import numpy as np import os import struct # import matplotlib.pyplot as plt from nn import * from layers import * from functions import * # def loadMnist(path, kind='train'): ''' import the MNIST dataset from path, which is the path of the folder kind should be either 'train', which is the training set o...
from SingletonProcess import SingletonProcess, block from time import sleep def printListSlow(l: list): for item in l: print(item) sleep(1) @SingletonProcess def printListMP(l: list): for item in l: print(item) sleep(1) if __name__ == "__main__": print("No Multiprocessing:...
# encoding: utf-8 """ 一个用于调试的WSGI App """ import os import time import random import threading from flask import Flask, request, g from flask_redis import FlaskRedis from flask_sqlalchemy import SQLAlchemy from sqlalchemy import Column from sqlalchemy import func, text as _text TMP_LIST = [] class Application(obj...
# Lint as: python2, python3 """Specification of a training cluster.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from REDACTED.transformer_lingvo.lingvo.core import cluster as lingvo_cluster import numpy as np from six.moves import range class _Clus...
from scipy import stats import matplotlib.pyplot as plt fig = plt.figure() ax1 = fig.add_subplot(211) x = stats.loggamma.rvs(5, size=500) + 5 prob = stats.probplot(x, dist=stats.norm, plot=ax1) ax1.set_xlabel('') ax1.set_title('Probplot against normal distribution') ax2 = fig.add_subplot(212) xt, _ = stats.boxcox(x) ...
# It's important that these modules are imported automatically, # so that their classes are registered with KnownArchivedObject and KnownStruct. from . import nextstep # noqa: F401 from . import appkit # noqa: F401 from . import foundation # noqa: F401
# shows how linear regression analysis can be applied to moore's law # # notes for this course can be found at: # https://deeplearningcourses.com/c/data-science-linear-regression-in-python # https://www.udemy.com/data-science-linear-regression-in-python # transistor count from: https://en.wikipedia.org/wiki/Transistor_...
# from pathlib import Path # from text_utils.ipa2symb import IPAExtractionSettings # from text_utils.language import Language # from text_utils.text import EngToIpaMode # def test_app_merge(tmp_path: Path): # base_dir = tmp_path / "base_dir" # text_path = tmp_path / "input.txt" # text_path.write_text("line1\nl...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os from threading import Thread from flask import Flask from flask import flash from flask import redirect, render_template, url_for, session from flask_bootstrap import Bootstrap from flask_mail import Mail, Message from flask_migrate import Migrate, Mig...
# 递归函数, 自己调用自己 # count = 1 # def func(): # global count # print('admin是很帅的', count) # count = count + 1 # func() # func() # 递归深度. 你可以自己调用自己的次数.官方文档中递归最大深度是1000. 在这之前就会给你报错 # 遍历 D:/sylar文件夹, 打印出所有的文件和普通文件的文件名 import os def func(filepath, n): # fullStackPython/p1_basic/day01_07base/ # 1,打开这个文件夹 ...
# Time: O(logn + k) # Space: O(1) import bisect class Solution(object): def findClosestElements(self, arr, k, x): """ :type arr: List[int] :type k: int :type x: int :rtype: List[int] """ i = bisect.bisect_left(arr, x) left, right = i-1, i wh...
# coding: utf-8 from models.models import Group from models.models import Person from random import randrange def test_add_group(app): old_groups = app.object.get_group_list() group = Group(name="test progon", header="jhvgvhgv", footer="khgcvkvv", ) a...
import sys def main(message): print message print('hello world')
class Televisao: def __init__(self): self.ligada = False self.canal = 2 def muda_canal_para_baixo(self): self.canal -= 1 def muda_canal_para_cima(self): self.canal += 1 tv = Televisao() print tv.muda_canal_para_cima() print tv.muda_canal_para_cima() print tv.canal
# https://codeforces.com/problemset/problem/677/A n, h = [int(x) for x in input().split()] heights = list(map(int, input().split())) total = 0 for height in heights: if height > h: total += 2 else: total += 1 print(total)
from typing import List from pathlib import Path import time from selenium.webdriver.firefox.webdriver import WebDriver from selenium.webdriver.firefox.options import Options from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expec...
"""General functions for string transformations.""" def convert_chemformula(string): """ Convert a chemical formula string to a matplotlib parsable format (latex). Parameters ---------- string or Adsorbate: str String to process. Returns ------- str Processed string. ...
import torch import PIL import os import copy import numpy as np from torch import nn import matplotlib.pyplot as plt from torchvision import transforms from skimage import io # Some basic setup: # Setup detectron2 logger import detectron2 from detectron2.utils.logger import setup_logger setup_logger() # import some ...
""" Copyright (c) 2022 Huawei Technologies Co.,Ltd. openGauss is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, W...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ URL scraping API. This module contains utility functions to extract (scrape) URLs from data. Currently only HTML and plain text data are supported. """ __license__ = """ GoLismero 2.0 - The web knife - Copyright (C) 2011-2014 Golismero project site: https://github.c...
import json def test_availability_register_product(client): res = client.get('/product/1') assert res.status_code == 200 def test_availability_get_all_available_products(client): res = client.get('/products/available') assert res.status_code == 200 def test_availability_get_all_sold_products(clien...
function keyRename(array $hash, array $replacements) { foreach($hash as $k=>$v) if($ok=array_search($k,$replacements)) { $hash[$ok]=$v; unset($hash[$k]); } return $hash; }
from bs4 import BeautifulSoup soup = BeautifulSoup("<html>a web page</html>", 'html.parser') # Tag object tag = soup.html print(type(tag)) print(tag) # tag name print(tag.name) # the tag name can be set tag = BeautifulSoup('<b id="boldest">bold</b>', 'html.parser').b print(tag['id']) # or print(tag.attrs) tag['id']...
""" Contains `RNN`: a simple wrapper for training `fn(state, *args) → state` functions. Run this file to test it. Usage example: ```python import torch import torch.nn as nn class OnlyFirstArg(nn.Module): def __init__(self, fn): super(OnlyFirstArg, self).__init__() self.fn = fn def forward(se...
#!/usr/bin/env python # Copyright (c) 2014 Palantir Technologies # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy,...
import abc class WorkerTask(abc.ABC): async def start_task(self, *args, **kwargs): raise NotImplementedError def is_task_active(self): raise NotImplementedError def set_task_status(self): raise NotImplementedError
import discord from discord.ext import commands class other(commands.Cog): def __init__(self, client): self.client = client @commands.command(aliases=["pfp"]) async def profile(self, ctx, user: discord.User): '''Fetch a user's profile picture''' await ctx.send(f'Profile image for u...
"""test module for cal functions""" # imports import unittest # required for testing import cal_functions # module under test class TestCalFunctions(unittest.TestCase): """class to test functions in cal functions""" def test_add(self): """add function test""" self.assertEqual(cal_...
import os import re import pickle import configparser DB_DIR = os.path.realpath(os.environ.get('DB_DIR', './db')) BASE = { 'edux': os.path.join(DB_DIR, 'edux'), 'user': os.path.join(DB_DIR, 'user'), } EXT = '.txt' USER = { 'config': '' + EXT, 'feed': '_feed.p', } EDUX = { 'pages': 'edux' + EXT, ...
from math import sqrt def quad(a, b, c): delta = b*b -4 * a * c if a == 0: print("Om a = 0 så är det inte en andragradsekvation, vänligen ange ett annat värde för a") elif delta < 0: print("Det finns inga reella lösningar för denna andragradsekvation") elif delta == 0: print("x = {}".format(-b/(2*a...
from NodeAndEdge import Node,Edge import xml.etree.ElementTree as ET import os import numpy as np import pandas as pd import pickle from Graph import Graph, creategraph if __name__=='__main__': filelist = [file for file in os.listdir('Instances/')] #graphs = [creategraph('Instances/' + file) for file in os.li...
from django.db import models from account_info.models import User """ from wallet_info.models import Wallet from task_info.models import Task from accept_task_info.models import AcceptTask Create your models here. """ class Wallet(models.Model): # walletID = models.AutoField(unique=True, primary_key=True) balan...
import asyncio from typing import Optional, Iterator import discord from discord.ext import commands class TTTGame: def __init__(self, ctx: commands.Context, player_2: discord.Member) -> None: self.ctx = ctx self.player_1 = ctx.author self.player_2 = player_2 self.curr...
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import gym import numpy as np class GenericMujocoEnv: """This class evaluates policy of OpenAI Gym environment. Parameters --...
from protos import interface_pb2_grpc as interface from protos import interface_pb2 as itf_msg class Explorer(interface.ExplorerServicer): def __init__(self, directory): self._directory = directory def StrategyList(self, request, context): with self._directory.read() as d: strategi...
from django.urls import path from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from . import views urlpatterns = [ path('', views.index, name='index'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, doc...
from edi_835_parser import parse from edi_835_parser import find_edi_835_files from log_conf import Logger input_dir = 'input' output_dir = 'output/remits_poc' files = find_edi_835_files(input_dir) for file in files: file_path = f'{input_dir}/{file}' transaction_set = parse(file_path) remits_df = transaction_s...
# ============================================================================= # # -*- coding: utf-8 -*- # """ # Created on Sat Aug 4 12:15:42 2018 # # @author: cui # """ # 18. 4Sum # Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? ...
# pyncoin/transaction.py ''' Implements a cryptocurrency transaction. ''' import functools import hashlib from decimal import Decimal import ecdsa from utils import RawSerializable, bytes_to_int, int_to_bytes, bytes_to_hex, hex_to_bytes from utils import BadRequestError, UnauthorizedError def get_public_key(private...
#Author:Huangliang #Time:2018/5/5 import cv2 import numpy as np import random from tkinter.filedialog import * import tkinter as tk import tkinter.messagebox def load_images(dirname, amout = 9999): #默认有9999张图片 img_list = [] file = open(dirname) #只读,把dirname加载到内存,用file接收,.lst文件估计是文本文件 img_name = file....
# Generated by Django 2.2 on 2019-03-05 16:20 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('gameApp', '0002_auto_20190305_1620'), ] operations = [ migrations.RenameField( model_name='usermodel', old_name='dateaccountcr...
""" Train a DeepLabV3 segmentation network Ref: https://pytorch.org/hub/pytorch_vision_deeplabv3_resnet101/ Paper: https://arxiv.org/pdf/1802.02611v3.pdf """ import torch import torch.nn as nn from torchvision import models class DeepLabV3(nn.Module): def __init__(self, num_classes=1, pretrained=True): su...
import sys import math from collections import defaultdict, deque sys.setrecursionlimit(10 ** 6) stdin = sys.stdin INF = float('inf') ni = lambda: int(ns()) na = lambda: list(map(int, stdin.readline().split())) ns = lambda: stdin.readline().strip() dx = defaultdict(int) dy = defaultdict(int) for i in range(3): ...
"""Adding flagged individuals. Revision ID: 9293ade6aa95 Revises: 9ed4811a814d Create Date: 2020-03-04 01:42:27.071216 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '9293ade6aa95' down_revision = '9ed4811a814d' branch_labels = None depends_on = None def upg...
# Resource object code (Python 3) # Created by: object code # Created by: The Resource Compiler for Qt version 6.2.3 # WARNING! All changes made in this file will be lost! from PySide6 import QtCore qt_resource_data = b"\ \x00\x00H\xc6\ <\ ?xml version=\x221.\ 0\x22 encoding=\x22UTF\ -8\x22 standalone=\x22\ no\x22?>\...
#!/usr/bin/env python3 import numpy as np import pandas as pd import os test_dir = './results/em_results' sample = [] unit = [] condition = [] for file in os.listdir(test_dir): if file.endswith(".counts"): sample.append(file) else: pass for i in range(len(sample)): base = os.path.sp...
# Generated by Django 3.2.11 on 2022-01-24 10:57 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("main", "0059_alter_financialinformation_area_of_work"), ] operations = [ migrations.AlterField( model_name="financialinformatio...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import logging import argparse import collections import os from Bio import SeqIO def main(param): logger = logging.getLogger() logging.basicConfig(level=param.loglevel, format='%(asctime)s (%(relativeCreated)d ms) -> %(levelname)s:%(message)s', datefmt='%I:%M...
import os, secrets key=secrets.token_urlsafe(32) basedir = os.path.abspath(os.path.dirname(__file__)) class Config(object): DEBUG=True #TESTING=False SECRET_KEY = key SQLALCHEMY_TRACK_MODIFICATIONS=False SQLALCHEMY_DATABASE_URI = '' class DevelopmentgConfig(Config): DEBUG=True SQLALCHEMY_T...
# _*_ coding: utf-8 _*_ """ password-validate.utils ----------------------- This module provides utility functions that are used within password_validate that are also useful for external consumption. """ import hashlib from os.path import abspath, dirname, join DICTIONARY_LOC = "dictionary_files" DICTIONARY = "dicti...
# This Python file uses the following encoding: utf-8 """Production application config.""" import os DEBUG = False TESTING = False GITHUB_OAUTH_CLIENT_ID = os.environ.get('GITHUB_OAUTH_CLIENT_ID') GITHUB_OAUTH_CLIENT_SECRET = os.environ.get('GITHUB_OAUTH_CLIENT_SECRET') SECRET_KEY = os.environ.get('SECRET_KEY')
from ._internal.frameworks.easyocr import load from ._internal.frameworks.easyocr import save from ._internal.frameworks.easyocr import load_runner __all__ = ["load", "load_runner", "save"]
from clock import start_clock from worker import start_worker
import torch.nn as nn class ResNetTrunk(nn.Module): """ Adapted from https://github.com/xu-ji/IIC/blob/master/ """ def __init__(self): super(ResNetTrunk, self).__init__() def _make_layer(self, block, planes, blocks, stride=1): downsample = None if stride != 1 or self.inpla...
""" Program to find LCM of two numbers recursive function to return gcd of a and b """ def gcd(a: int, b: int) -> int: if a == 0: return b return gcd(b % a, a) # function to return LCM of two numbers def lcm(a: int, b: int) -> float: return (a / gcd(a, b)) * b if __name__ == '__main__': a ...
'''Exercicio 4: Uma pista de Kart permite 10 voltas para cada um de 6 corredores. Escreva um programa que leia todos os tempos em segundos e os guarde em um dicionário, onde a chave é o nome do corredor. Ao final diga de quem foi a melhor volta da prova e em que volta; e ainda a classificação final em ordem (1o o campe...
import streamlit as st from requests_toolbelt.multipart.encoder import MultipartEncoder import requests from PIL import Image import io import zipfile import glob import os import json st.title('MoroccoAI Data Challenge : Automatic Number Plate Recognition (ANPR) in Morocco Licensed Vehicles.') # fastapi endpoint url...
from utils import read_file def calc_parents(connections, node): if node == 'COM': return 0 else: return 1 + calc_parents(connections, connections[node]) def get_connections(map_): connections = {} for line in map_: from_, to_ = line.split(')') connections[to_] = from...
#!/usr/bin/env python3 """Nickel and Dime""" import argparse import os import random import sys # -------------------------------------------------- def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Argparse Python script', formatter_class=argpar...
def swap(): input1=input("enter file name 1:") input2=input("enter file name 2:") u = open(input2,"r") v = open(input1,"r") data_u = u.read() data_v = v.read() u = open(input2,"w") u.write(data_v) v = open(input1,"w") v.write(data_u) swap()
from typing import Dict from typing import Tuple from typing import Union import hypothesis.strategies as st from myrtlespeech.protos import eval_config_pb2 from tests.protos.test_dataset import datasets from tests.protos.utils import all_fields_set # Fixtures and Strategies ----------------------------------------...
__all__ = ["craw_reviews"]
#! /usr/bin/env python # -*- coding: utf-8 -*- # Standard modules import os import math # Third-party modules import numpy import matplotlib from mpl_toolkits.axes_grid1 import make_axes_locatable import matplotlib.pyplot as plt try: import weblogo # Weblogo compatibility # With version < 3.5, the col...
from numpy import * def encrypt(): cnt=0 j=0 for i in range(len(plaintext)): if(cnt%2==0): m[j,i]=plaintext[i] j+=1 if(j==depth-1): cnt+=1 continue else: m[j,i]=plaintext[i] ...
from vanilla.vanillaBase import VanillaBaseObject, VanillaBaseControl, VanillaError from vanilla.vanillaBox import Box, HorizontalLine, VerticalLine from vanilla.vanillaBrowser import ObjectBrowser from vanilla.vanillaButton import Button, SquareButton, ImageButton, HelpButton from vanilla.vanillaCheckBox import CheckB...
# -*- coding: utf-8 -*- """ Natural language processing =========================== Provides a wrapper around NLTK to extract named entities from HTML text:: from coaster.utils import text_blocks from coaster.nlp import extract_named_entities html = "<p>This is some HTML-formatted text.</p><p>In two par...
from scrapy.commands.list import Command as BaseCommand class Command( BaseCommand ): def syntax( self ): return "[options|<pattern>]" def short_desc( self ): return "List available spiders matched with pattern if provided." def add_options( self, parser ): super( Command, self ).add_options( parser ) pa...
import re def email(value): """Validate an email address >>> email("barney@purpledino.com") True >>> email("barneydino.com") 'An email address must contain a single @' """ usernameRE = re.compile(r"^[^ \t\n\r@<>()]+$", re.I) domainRE = re.compile(r''' ^(?:[a-z0-9][a-z0-9\...
import scrapy class ArticleSpider(scrapy.Spider): name = 'article' def start_requests(self): urls = [ 'http://sz.to8to.com/zwj/'] return [scrapy.Request(url=url, callback=self.parse) for url in urls] def parse(self, response): url = response.url title ...
# %% import pandas as pd import math import os.path import time from binance.client import Client from datetime import timedelta, datetime, timezone from dateutil import parser from tqdm import tqdm_notebook # (Optional, used for progress-bars) import json import requests import pandas as pd ### CONSTANTS binsizes...
import tensorflow as tf from keras.models import Sequential from keras.layers import Convolution2D from keras.layers import MaxPooling2D from keras.layers import Flatten from keras.layers import Dense classifier=Sequential() #convolution classifier.add(Convolution2D(32,3,3,input_shape=(64,64,3) , activation='re...
''' Demo code for imaging through turbulence simulation Z. Mao, N. Chimitt, and S. H. Chan, "Accerlerating Atmospheric Turbulence Simulation via Learned Phase-to-Space Transform", ICCV 2021 Arxiv: https://arxiv.org/abs/2107.11627 Zhiyuan Mao, Nicholas Chimitt, and Stanley H. Chan Copyright 2021 Purdue Uni...
from django import forms from .models import Idea from .models import Comments class Blog_creation(forms.ModelForm): class Meta: model=Idea fields=['title','content','date_posted','tag_name'] class Comment(forms.ModelForm): class Meta: model=Comments fields=['description'] #...
#!/usr/bin/env python from nephoria.testcase_utils.cli_test_runner import CliTestRunner, SkipTestException from cloud_utils.log_utils import get_traceback, red, ForegroundColor, BackGroundColor, markup from cloud_utils.net_utils.remote_commands import RemoteCommands from cloud_utils.net_utils.sshconnection import SshC...
from conduit import * import nose def verify_array(value): inputs = {'value': value} array = [0,1,2,3] for element in array: nose.tools.assert_equal(inputs['value'], element) inputs = yield def incremental_generator_with_output(): array = [0,1,2,3] for value in array: yie...
import os import argparse import pandas as pd import numpy as np import time from collections import Counter def save_preds(source, dataset, output): df = pd.read_csv(dataset) ids = df['Id'].values.tolist() preds = ['Id,Category'] label_dict = { 0: 'Negativo', 1: 'Neutro', 2: '...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Created by tz301 on 2020/05/20 """Converter module."""
import pandas as pd import numpy as np import random def train_data_generator(): r_src = "/home/LAB/zhuxk/project/data/ER-dataset-benchmark/ER/DBLP-ACM/origin/DBLP2.csv" l_src = "/home/LAB/zhuxk/project/data/ER-dataset-benchmark/ER/DBLP-ACM/origin/ACM.csv" map_src = "/home/LAB/zhuxk/project/data/ER-dat...
def list_to_string(strings: [str]) -> str: return '\n'.join(strings)
import random, sys, math caseno = dict() PROBID = "smallschedule" MAXQ = 1000 MAXL = MAXS = MAXM = 1000000 # The first argument is a short string describing the "type" of data # (eg. sample, hand, random), the rest have the test case data. # # This will generate the file in the data directory, putting type "sample"...
#!/usr/bin/env python # Copyright (c) 2018-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import os import sys import torch from console_lib import GoConsoleGTP from rlpytorch import E...
# 15/15 tp = int(input()) pop = int(input()) dmo = sorted(map(int, input().split())) peg = sorted(map(int, input().split())) pairs = [] for index in range(pop): if tp == 1: pairs.append([dmo[index], peg[index]]) elif tp == 2: pairs.append([dmo[index], peg[(-1 * index) - 1]]) total = sum(map...
from autoconf import conf import autoarray as aa import numpy as np from autogalaxy.galaxy import galaxy as g from autolens.pipeline.phase import dataset class Result(dataset.Result): @property def max_log_likelihood_fit(self): return self.analysis.positions_fit_for_tracer( tr...
from imhotep.diff_parser import DiffContextParser diff = """diff --git a/foo.py b/foo.py new file mode 100644 index 0000000..78ce7f6 --- /dev/null +++ b/foo.py @@ -0,0 +1,7 @@ +class Foo(object): + pass + +class Bar(object): + pass + +print "Works"; """ def test_file_adds_arent_off(): parser = DiffContextParse...