text
string
size
int64
token_count
int64
import os import numpy as np import torch import torch.nn as nn import torch.optim as optim import argparse from tqdm import tqdm import sys import distributed as dist import utils from models.vqvae import VQVAE, VQVAE_Blob2Full from models.discriminator import discriminator visual_folder = '/home2/bipasha31/python_...
8,125
2,766
# pylint: disable=unused-variable,unused-argument,expression-not-assigned from django.forms.models import model_to_dict import arrow import pytest from expecter import expect from api.elections.models import Election from .. import models @pytest.fixture def info(): return models.Identity( first_name=...
1,245
425
class Solution: def isStrobogrammatic(self, num: str) -> bool: strobogrammatic = { '1': '1', '0': '0', '6': '9', '9': '6', '8': '8' } for idx, digit in enumerate(num): if digit not in strobogrammatic or strobogrammatic[...
404
129
from operator import itemgetter def is_direct_award_project_accessible(project, user_id): return any([user['id'] == user_id for user in project['users']]) def get_direct_award_projects(data_api_client, user_id, return_type="all", sort_by_key=None, latest_first=None): projects = data_api_client.find_direct_a...
992
316
class Solution(object): def dfs(self,stones,graph,curpos,lastjump): if curpos==stones[-1]: return True # since the jump need based on lastjump # only forward,get rid of the stay at the same pos rstart=max(curpos+lastjump-1,curpos+1) rend=min(curpos+lastjump+1,ston...
824
254
from typing import Optional, Dict, Any from fastapi import APIRouter from jina.helper import ArgNamespace from jina.parsers import set_pod_parser from ....excepts import PartialDaemon400Exception from ....models import PodModel from ....models.partial import PartialStoreItem from ....stores import partial_store as sto...
2,261
761
import yaml class Config: def __init__(self, path: str): self.path = path self.cfg = {} self.parse() def parse(self): with open(self.path, 'r') as f: self.cfg = yaml.load(f) @property def secret(self) -> str: return self.cfg.get('secret') @pro...
708
252
#!/usr/bin/env python3 import argparse import csv import logging import os import re import sys DELIMITER = ',' class CsvFilter: def __init__( self, file=None, deduplicate=False, filter_query=None, filter_inverse=False, ignore_case=False,...
4,379
1,228
def check_candidate(a, candidate, callback_when_different, *args, **kwargs): control_result = None candidate_result = None control_exception = None candidate_exception = None reason = None try: control_result = a(*args, **kwargs) except BaseException as e: control_exception ...
1,435
357
# coding=utf-8 from builtins import str import json from django.contrib.auth.models import Group, Permission from django.urls import reverse from rest_framework import status from bluebottle.impact.models import ImpactGoal from bluebottle.impact.tests.factories import ( ImpactTypeFactory, ImpactGoalFactory ) from...
9,883
2,983
from . import ParserV2 import dotmotif import unittest _THREE_CYCLE = """A -> B\nB -> C\nC -> A\n""" _THREE_CYCLE_NEG = """A !> B\nB !> C\nC !> A\n""" _THREE_CYCLE_INH = """A -| B\nB -| C\nC -| A\n""" _THREE_CYCLE_NEG_INH = """A !| B\nB !| C\nC !| A\n""" _ABC_TO_D = """\nA -> D\nB -> D\nC -> D\n""" _THREE_CYCLE_CSV ...
11,613
4,385
from typing import List import click import torch from fandak.utils import common_config from fandak.utils import set_seed from fandak.utils.config import update_config from proj.config import get_config_defaults from proj.datasets import MNISTClassification from proj.evaluators import ValidationEvaluator from proj.m...
1,382
461
from problem_solving.algorithms.sorting import * def test_q1_big_sorting(capsys, monkeypatch): inputs = ["6", "31415926535897932384626433832795", "1", "3", "10", "3", "5"] monkeypatch.setattr('builtins.input', lambda: inputs.p...
864
355
import sqlite3 from sqlite3 import Error import os import time import datetime import re import random import schedule import cryptography from apscheduler.schedulers.background import BackgroundScheduler from slackclient import SlackClient from cryptography.fernet import Fernet conn = sqlite3.connect('...
9,975
4,006
from PIL import Image import cv2 import pytesseract import tesserocr from pyocr import pyocr from pyocr import builders import sys import os def get_image_filename(img_id): filename = "img_src/src{0:0>3}".format(img_id) for ext in [".png", ".jpg", ".jpeg"]: if os.path.exists(os.path.join(os.getcwd(), ...
1,555
592
# Copyright (c) 2021 PPViT Authors. 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...
6,718
2,221
from django import template from django.forms import widgets register = template.Library() @register.inclusion_tag('formfield.html') def formfield(field): widget = field.field.widget type_ = None if isinstance(widget, widgets.Input): type_ = 'input' elif isinstance(widget, widgets.Textarea): ...
632
190
# CONFIG seeds = [6598903756360202179, 2908409715321502665, 6126375328734039552, 1447957147463681860, 8611858271322161001, 1129180857020570158, 6362222119948958210, 7116573423379052515, 6183551438103583226, 4025455056998962241, 3253052445978017587, 8447055112402476503, 5958072666039141800, 704315598608973559, 127314171...
2,104
2,095
import torch import torch.nn as nn import numpy as np class VisitationSoftmax(nn.Module): def __init__(self, log=False): super(VisitationSoftmax, self).__init__() self.log = log self.logsoftmax = nn.LogSoftmax() self.softmax = nn.Softmax(dim=1) def forward(self, visitation_di...
2,793
822
n = int(input()) % 8 if n == 0: print(2) elif n <= 5: print(n) else: print(10 - n)
96
50
#!/usr/bin/env python3 # coding:utf-8 import urllib from xml.etree import ElementTree import xml.dom.minidom as md class Niko(object): def __init__(self): self.url_ranking = 'http://www.nicovideo.jp/ranking/fav/hourly/sing?rss=2.0&lang=ja-jp' self.url_news = 'http://news.nicovideo.jp/categories/10...
908
313
#!/usr/bin/env python3 import os import shutil from subprocess import Popen, PIPE from datetime import date import yaml os.chdir(os.path.dirname(os.path.realpath(__file__))) CLIMBING_FOLDER = "." CLIMBING_VIDEOS_FOLDER = os.path.join(CLIMBING_FOLDER, "videos") CLIMBING_INFO = os.path.join(CLIMBING_FOLDER, "videos....
927
341
from django.db import models from categorias.models import Categoria from django.contrib.auth.models import User from django.utils import timezone # Create your models here. class Post(models.Model): titulo_post = models.CharField(max_length=50, verbose_name='Titulo') autor_post = models.ForeignKey(User, on_...
952
300
#!/usr/bin/env python import datetime import logging import os import random import rospy import schedule from interaction_engine.cordial_interface import CordialInterface from interaction_engine.database import Database from interaction_engine.int_engine import InteractionEngine from interaction_engine.message impor...
2,765
985
# -*- coding: utf-8 -*- """ @author: nicolas.posocco """ from abc import ABC import numpy as np class MulticlassDistribution(ABC): def __init__(self): """ Initializes the distribution, allowing later sampling and posterior probabilities calculations. """ pass def sample(sel...
2,441
718
#!/usr/bin/env python """Script used to test the network with batfish""" from pybatfish.client.commands import * from pybatfish.question import load_questions from pybatfish.client.asserts import ( assert_no_duplicate_router_ids, assert_no_incompatible_bgp_sessions, assert_no_incompatible_ospf_sessions, ...
3,169
1,071
""" A fixed-capacity queue implemented as circular queue. Queue can become full. * enqueue is O(1) * dequeue is O(1) """ class Queue: """ Implementation of a Queue using a circular buffer. """ def __init__(self, size): self.size = size self.storage = [None] * size self.first =...
1,176
363
""" Create train and dev set from bronze data Example call: $ python3 create_train_dev.py --pos /mounts/work/ayyoob/results/gnn_align/yoruba/pos_tags_tam-x-bible-newworld_posfeatFalse_transformerFalse_trainWEFalse_maskLangTrue.pickle --bible tam-x-bible-newworld.txt --bronze 1 --lang tam $ python3 create_train_dev.py ...
4,300
1,660
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) import os import pytest import stat from spack.hooks.permissions_setters import ( chmod_real_entries, InvalidPermissi...
1,076
421
import dask.dataframe as dd def descibe_dataframe(df): error_cols = [col for col in df.columns if 'errorCode' in col] df = df.categorize(columns=error_cols) statistics = df.describe(include='all').compute() statistics = statistics.T statistics.to_excel('../statistics/variables_statistics.xls...
323
106
#!/usr/bin/python # -*- coding: UTF-8 -*- import numpy as np import pandas as pd ''' 如何用sql的方式打开pandas ''' from pandas import DataFrame, Series from pandasql import sqldf, load_meat, load_births df1 = DataFrame({'name': ['jack', 'tony', 'pony'], 'data1': range(3)}) print(df1) sql = "select * from df1 where name = ...
393
158
import pytest from mock import patch import pandas as pd import pyarrow as pa import pyarrow.parquet as pq import boto3 from string import ascii_lowercase import random from dfmock import DFMock import s3parq.publish_parq as parq import s3fs from moto import mock_s3 @mock_s3 class Test: def setup_s3(self): ...
5,016
1,574
#import sys #sys.path.append("../..") import pyiomica as pio from pyiomica import categorizationFunctions as cf if __name__ == '__main__': # Unzip example data with pio.zipfile.ZipFile(pio.os.path.join(pio.ConstantPyIOmicaExamplesDirectory, 'SLV.zip'), "r") as zipFile: zipFile.extractall(...
2,936
1,039
# returns number of unique records for icews with different filtering: # -by rounded lat/lon (100,000) # -by country, district, province, city (100,000) # -by lat/lon, filtered by 2 or more matches (70,000) from pymongo import MongoClient import os mongo_client = MongoClient(host='localhost', port=27017) # Default p...
2,612
919
# Copyright (c) 2020. Hanchen Wang, hw501@cam.ac.uk # Ref: https://github.com/fxia22/pointnet.pytorch/pointnet/model.py import torch, torch.nn as nn, numpy as np, torch.nn.functional as F from torch.autograd import Variable def feature_transform_regularizer(trans): d = trans.size()[1] I = torch.eye(d)[None...
7,576
3,170
import MapReduce import sys """ SQL style Joins in MapReduce """ mr = MapReduce.MapReduce() # ============================= # Do not modify above this line def mapper(record): # key: document identifier # value: document contents value = str(record[0]) num = str(record[1]) mr.emit_intermediate(num, (value...
747
301
from anonapi.testresources import ( MockAnonClientTool, JobInfoFactory, RemoteAnonServerFactory, JobStatus, ) def test_mock_anon_client_tool(): some_responses = [ JobInfoFactory(status=JobStatus.DONE), JobInfoFactory(status=JobStatus.ERROR), JobInfoFactory(status=JobStatus....
823
284
"""The Mikrotik router class.""" from datetime import timedelta import logging import socket import ssl import librouteros from librouteros.login import plain as login_plain, token as login_token from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME, CONF_VERIFY_SSL from homeassistant.exceptions imp...
13,442
3,937
from bs4 import BeautifulSoup import requests import re from lxml.html import fromstring from lxml.etree import ParserError from gemlog_from_rss.spip import SinglePost def localize(lang): if lang == "pl": return { "our_articles": "Nasze artykuły" } if lang == "fr": return {...
4,137
1,316
# Copyright (c) 2017 David Sorokin <david.sorokin@gmail.com> # # Licensed under BSD3. See the LICENSE.txt file in the root of this distribution. from simulation.aivika.modeler.model import * from simulation.aivika.modeler.port import * def create_arrival_timer(model, name, descr = None): """Return a new timer tha...
1,421
475
m = float(input('digite o metro ')) print(f'{m} metros e igual {m*100} centimetros e {m*1000} milimetros')
106
48
#!/usr/bin/env python import rospy import rosbag import os import sys import textwrap import yaml lidarmsg=None ################# read the lidar msg from yaml file and return ############## def readlidardummy(): global lidarmsg if lidarmsg==None: lidarmsg= doreadlidar() return lidarmsg def doreadlidar():...
859
307
from flyteidl.plugins import qubole_pb2 as _qubole from flytekit.models import common as _common class HiveQuery(_common.FlyteIdlEntity): def __init__(self, query, timeout_sec, retry_count): """ Initializes a new HiveQuery. :param Text query: The query string. :param int timeout_...
4,375
1,340
# -*- coding: utf-8 -*- from dataclasses import asdict from logging import DEBUG import os from flask import Flask, jsonify, request from werkzeug.exceptions import HTTPException from mecab_parser import MecabParserFactory app = Flask(__name__) app.config["JSON_AS_ASCII"] = False @app.route("/parse", methods=["PO...
1,583
506
#!/usr/bin/env python # -*- coding: UTF-8 -*- """Emitters are used to export models to output format. This module contains all classes for emitters: base and actuals. Currently the system has two emitters: :class:`~.CSVEmitter` and :class:`~.MySQLEmitter` implemented, of which the last is the default emitter. An emitt...
1,402
451
# Generated by Django 2.0.9 on 2018-12-12 08:18 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('cycleshare', '0012_cycle_toprofile'), ] operations = [ migrations.RemoveField( model_name='cycle', name='toprofile', ...
330
118
import math import numpy as np from scipy import signal #%% 全自动的数据生成 M = 16; N = 100; AddImm = 1000; MAT_M = 3; MAT_N = 5; MAT_P = 7; Pm = 5; Pn = 5; Km = 5; Kn = 5; MODE = 1; fpp = open("./npu_verification_para.list", "w") fpp.write("%d\n"%(M)) fpp.write("%d\n"%(N)) fpp.write("%d\n"%(AddImm)) fpp.write("%d\n"%(MAT_M...
5,495
3,250
A = 1 B = 2 C = 4
17
15
from . import up
17
6
def área(larg, comp): a = larg * comp print(f'A área de um terreno {larg}x{comp} é de {a}m²') print('Controle de Terrenos') print('--------------------') l = float(input('Largura (m): ')) c = float(input('Comprimento (m): ')) área(l, c)
247
99
import logging from functools import wraps from django.http import Http404 from readthedocs.projects.models import Project, ProjectRelationship log = logging.getLogger(__name__) # noqa def map_subproject_slug(view_func): """ A decorator that maps a ``subproject_slug`` URL param into a Project. :raise...
2,678
709
import discord import asyncio import re import logging from data.groups_name import free_random_name logging.basicConfig(level=logging.INFO) client = discord.Client() class ClientEvents(discord.Client): ''' Classe initialization ''' def __init__(self, *args, **kwargs): super().__init__(*args...
4,217
1,231
from flask import request, make_response, jsonify, g from datetime import datetime from functools import wraps import jwt from models import DBContext, User from settings import SECRET_KEY from service import is_token_valid def login_required(func): @wraps(func) def wrapper(*args, **kwargs): not_auth...
566
160
""" Utilities --------- The utilities module. """ from collections.abc import Mapping, Sequence from functools import wraps import types class FrozenDict(Mapping): """A frozen dictionary implementation that prevents the object from being mutated. This is primarily used when defining a dict-like object as a ...
2,189
645
try: from . import generic as g except BaseException: import generic as g class NormalsTest(g.unittest.TestCase): def test_vertex_normal(self): mesh = g.trimesh.creation.icosahedron() # the icosahedron is centered at zero, so the true vertex # normal is just a unit vector of the v...
1,817
532
# /*********************************************************************** # Copyright 2019 Google 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/LICE...
14,692
3,880
# coding:utf-8 # # The MIT License (MIT) # # Copyright (c) 2018-2020 azai/Rgveda/GolemQuant base on QUANTAXIS/yutiansut # # 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, ...
19,390
8,124
#!/usr/bin/env python """ Installs ETA. Copyright 2017-2021, Voxel51, Inc. voxel51.com """ import os from setuptools import setup, find_packages from wheel.bdist_wheel import bdist_wheel VERSION = "0.6.1" class BdistWheelCustom(bdist_wheel): def finalize_options(self): bdist_wheel.finalize_options(self...
3,125
995
# Kernel introspection module to enrich branch collected data # This code is part of BranchMonitoring framework # Written by: Marcus Botacin - 2017 # Federal University of Parana (UFPR) from xml.etree.ElementTree import ElementTree # Parse XML import subprocess # Run dump tools i...
8,582
2,482
from .development import DevelopmentConfig from .testing import TestingConfig from .production import ProductionConfig app_config = { 'development': DevelopmentConfig, 'testing': TestingConfig, 'production': ProductionConfig, }
243
60
import tkinter as tk from tkinter import ttk from functools import partial def popup(parent, title, details, icon, *, buttons): dialog = tk.Toplevel() result = None big_frame = ttk.Frame(dialog) big_frame.pack(fill="both", expand=True) big_frame.columnconfigure(0, weight=1) big_frame.rowconf...
5,026
1,681
# proxy module from __future__ import absolute_import from etsdevtools.endo.docerror import *
94
28
# Copyright (c) 2012-2020, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. # # *** Do not modify - this file is autogenerated *** # Resource specification version: 18.6.0 from . import AWSObject from . import AWSProperty from . import Tags from .validators import boolean from ....
12,591
3,540
import wx import cv2 #---------------------------------------------------------------------- # Panel to display image from camera #---------------------------------------------------------------------- class WebcamPanel(wx.Window): # wx.Panel, wx.Control def __init__(self, parent, camera, fps=15, flip=Fals...
3,046
952
import pynk from pynk.nkpygame import NkPygame class InputBox: def __init__(self, max_len): # self.max_len = pynk.ffi.new("int *", max_len) self.len = pynk.ffi.new("int *", 0) self.max_len = max_len # self.len = 0 self.cur_text = pynk.ffi.new("char[{}]".format(max_len)) ...
580
235
''' 自定义实现双层网络,实现Relu激活函数 ''' import tensorflow as tf import numpy as np import sys sys.path.append("..") from softmax_test import train_che3 from tensorflow.keras.datasets.fashion_mnist import load_data # 加载数据集;转换类型并做归一化处理 (x_train,y_train),(x_test,y_test)=load_data() batch_size=256 x_train=tf.cast(x_tra...
1,454
802
""" A simple script for numbering nUp tickets for the print shop. """ def numbering_main() -> None: """ Gets numbering sequences for nUp ticket numbering. Gets the total number of tickets requested along with now many will fit on a sheet (n_up) as well as the starting ticket number and prints the tic...
1,704
521
# -*- coding: utf-8 -*- """ Created on Mon May 15 21:32:17 2017 @author: Aaron Sharpe """ import numpy as np import os from matplotlib.colors import LinearSegmentedColormap def igorTerrain(n): n1 = np.around(n*25/256) n2 = np.around(n*37/256) n3 = np.around(n*100/256) n4 = np.around(n*150/256) r...
2,539
1,364
def arg_to_step(arg): if isinstance(arg, str): return {'run': arg} else: return dict(zip(['run', 'parameters', 'cache'], arg)) def steps(*args): return [arg_to_step(arg) for arg in args]
217
75
import os import shutil import tempfile from taskmage2.utils import filesystem, functional from taskmage2.asttree import asttree, renderers from taskmage2.parser import iostream, parsers from taskmage2.project import taskfiles class Project(object): def __init__(self, root='.'): """ Constructor. ...
11,843
3,320
from discord.ext import commands class FilteredUser(commands.UserConverter): """ A simple :class:`discord.ext.commands.UserConverter` that doesn't allow bots or the author to be passed into the function. """ def __init__(self, *, allow_author: bool = False, allow_bots: bool = False): supe...
1,611
459
a = 289326 coords = [(1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1), (0, 1), (1, 1)] x,y = (0,0) dx,dy = (1,0) M = {(x,y):1} while M[(x, y)] < a: x, y = x+dx, y+dy M[(x, y)] = sum([M[(x+ox, y+oy)] for ox,oy in coords if (x+ox,y+oy) in M]) if (x == y) or (x > 0 and x == 1-y) or (x < 0 and x == -y): ...
361
214
""" Q learning """ import numpy as np import plot Q = np.array(np.zeros([11, 3])) GAMMA = 0.9 ALPHA = 0.1 def action_select(s_s): """ action select """ return np.random.choice([i for i in range(1, 4) if i + s_s < 11]) for i in range(10000): S_STATE = 0 while S_STATE != 10: a_state = acti...
811
344
from django.db import models from django.utils import timezone class GameIdea(models.Model): name=models.CharField(max_length=100) genre= models.CharField(max_length=100) currentdate= models.DateTimeField(blank=True, null=True) def __str__(self): return self.name, self.genre def displaye...
390
122
import unittest from datetime import date import numpy as np import pandas as pd from numpy.testing import assert_array_almost_equal from scipy.stats import gamma from epyestim.estimate_r import overall_infectivity, sum_by_split_dates, estimate_r, gamma_quantiles class EstimateRTest(unittest.TestCase): def test...
4,296
1,928
# Copyright 2019 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
3,355
1,196
# Improved version of the code from chapter 03 # created in chapter 11 to accelerate execution import random XMAX, YMAX = 19, 16 def create_grid_string(dots, xsize, ysize): """ Creates a grid of size (xx, yy) with the given positions of dots. """ grid = "" for y in range(ysize): f...
1,781
724
from api.models.models import User from api import db, create_app db.create_all(app=create_app())
98
32
import numpy as np import scipy.stats as stats from UQpy.Distributions.baseclass.Distribution import Distribution class DistributionContinuous1D(Distribution): """ Parent class for univariate continuous probability distributions. """ def __init__(self, **kwargs): super().__init__(**kwargs) ...
1,820
602
import torch from torch import nn import torch.nn.functional as F import math from functools import partial class MLP(torch.nn.Module): def __init__(self, input_dim, layer_widths, activate_final = False, activation_fn=F.relu): super(MLP, self).__init__() layers = [] prev_width = input_dim ...
1,666
576
#!/usr/bin/python # -*- coding: utf-8 -*- # Finds submissions with chessboard images in them, # use a tensorflow convolutional neural network to predict pieces and return # a lichess analysis link and FEN diagram of chessboard import praw import collections import os import time from datetime import datetime from praw....
10,920
3,550
import requests import re import time import random import pprint import os headers = {"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3858.0 Safari/537.36"} def youdict(threadName, q): res = [] index = 0 url = q.get(timeout = 2) ...
1,557
624
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2015-12-23 08:44 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Mall', ...
769
230
#---------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. #------------------------------------------------------------------...
16,406
5,670
from redat import __version__ import argparse as _argparse import sys as _sys def CLI(): _parser = _argparse.ArgumentParser( description='simple str & int obfuscator (c) zvtyrdt.id', formatter_class=_argparse.RawTextHelpFormatter, version=__version__) _parser.add_argument('txt', metava...
2,546
799
""" Useful classes and functions for SIMPLE. """ import numpy as np import warnings import math from scipy import integrate r_sun_au = 0.004649 r_earth_r_sun = 0.009155 day_hrs = 24.0 #@profile def impact_parameter(a, e, i, w, r_star): """ Compute the impact parameter at for a transiting planet. Paramet...
15,435
5,552
#inputFile = 'sand.407' inputFile = 'sand.407' outputFile= 'sand.out' def joinLine(): pass with open(inputFile) as OF: lines = OF.readlines() print(lines[0:3])
179
81
#!/usr/bin/env python3 """ Created by sarathkaul on 14/11/19 Basic authentication using an API password is deprecated and will soon no longer work. Visit https://developer.github.com/changes/2020-02-14-deprecating-password-auth for more information around suggested workarounds and removal dates. """ import requests...
718
237
class MergeSort: def __init__(self, lst): self.lst = lst def mergeSort(self, a): midPoint = len(a) // 2 if a[len(a) - 1] < a[0]: left = self.mergeSort(a[:midPoint]) right = self.mergeSort(a[midPoint:]) return self.merge(left, right) else: ...
1,362
405
#!/usr/bin/env python3 # vim: set ai et ts=4 sw=4: import os import subprocess import argparse import time import calendar import re def run(cmd): code = subprocess.call(['/bin/bash', '-o', 'pipefail', '-c', cmd]) if code != 0: raise RuntimeError("Command `%s` returned non-zero status: %d" % ...
3,952
1,486
import redis import copy from functools import wraps from .exception import ErrorMessage from .decorators import raise_exception from .serializer import Serializer TTL = 604800 class Cart(object): """ Main Class for Cart, contains all functionality """ @raise_exception("E-Cart can't be initiali...
7,195
2,052
import pytest from app.main import app from app.models import TransactionRegistration from app.settings import settings from httpx import AsyncClient from tests.conftest import RequestCache registration = TransactionRegistration( to_address="cx0000000000000000000000000000000000000001", from_address="cx00000000...
1,172
415
# Copyright 2013 Red Hat, 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 law or agr...
33,565
9,613
# Recall material on NP Universal Functions from Ch2 # PD builds on ufuncs functionality a few ways: # first, for unary operations (negation / trig funcs), ufuncs preserve # index and column labels in the output # second, for binary operations (addition / multiplication) PD aligns # indices when passing objects to th...
3,683
1,208
from itertools import chain from components.config import getConfig from components.convert import fetchUser, pretRes import discord from discord import channel from discord.ext import commands class Feelings(commands.Cog): def __init__(self, client) -> None: self.client = client self.config = get...
1,286
415
''' There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). You may assume nums1 and nums2 cannot be both empty. ''' ### Nature: the meaning of MEDIAN, is that, the number of elements less than it, ##...
2,400
845
from abc import ABC, abstractmethod class MarioGame(ABC): @abstractmethod def getPort(self) -> int: pass @abstractmethod def initGame(self): pass @abstractmethod def stepGame(self, left: bool, right: bool, down: bool, speed: bool, jump: bool): pass @abstractmetho...
781
234
import torch import torch.optim as optim import torch.nn.functional as F import optimizers import time, os, random import numpy as np import math, copy from collections import deque from common.utils import epsilon_scheduler, beta_scheduler, update_target, print_log, load_model, print_args from model import DQN fro...
16,832
5,502
#!/usr/bin/env python # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2012,2013,2015,2016,2017,2018 Contributor # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. #...
6,290
2,205
######################################################################################### # semi-supervised learning: use label propagation to make pseudo labels for no label data # This is not the parallel implement of label propagation, may requires a lot of time # Author: Jiaxuan Lu #################################...
11,289
3,872