text
string
size
int64
token_count
int64
""" Copyright (c) 2012 Wyss Institute at Harvard University 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, merge...
4,217
1,351
# BSD LICENSE # # Copyright(c) 2010-2014 Intel Corporation. All rights reserved. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copy...
5,383
1,775
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_dj-pylti ------------ Tests for `dj-pylti` models module. """ from django.test import TestCase from dj_pylti import models class TestDj_pylti(TestCase): def setUp(self): pass def test_something(self): pass def tearDown(self): ...
331
126
"""Mutation. Usage: mutation play [--verbose] [--exclude=<globs>] [--only-deadcode-detection] [--include=<globs>] [--sampling=<s>] [--randomly-seed=<n>] [--max-workers=<n>] [<file-or-directory> ...] [-- TEST-COMMAND ...] mutation replay [--verbose] [--max-workers=<n>] mutation list mutation show MUTATION mut...
30,467
9,551
import argparse from ColorDetector import ColorDetector def main(): detector = ColorDetector() parser = argparse.ArgumentParser() # --k : number of clusters, --image: image path, --debug: debug level parser.add_argument("--k", nargs=1, type=int, help='maximum number of colors to be identified. Default:...
1,058
360
print('===== DESAFIO 64 =====') num = 0 cont = 0 soma = 0 num = int(input('Digite um número [999 para SAIR]: ')) while num != 999: soma += num cont += 1 num = int(input('Digite um número [999 para SAIR]: ')) print(f'Você digitou {cont} números! A soma entre eles é {soma}')
286
124
from elasticapm.contrib.flask import ElasticAPM import os from flask import Flask, request, render_template from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy APP = Flask(__name__) APP.config['ELASTIC_APM'] = { } apm = ElasticAPM(APP) APP.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False APP.co...
2,062
726
# -*- coding: utf-8 -*- from sys import platform def get_pytify_class_by_platform(): if 'linux' in platform: from linux import Linux return Linux elif 'darwin' in platform: from darwin import Darwin return Darwin else: raise Exception('%s is not supported.' % platf...
325
96
# -*- coding: utf-8 -*- from datetime import datetime import logging import os.path import requests import time import urllib from bs4 import BeautifulSoup from utils import mongo class FetchMeetings: def __init__(self, **kwargs): # fetch the logger self._logger = logging.getLogger("spud") ...
8,836
2,423
from django import template register = template.Library() @register.filter def mimetype(value, mime_type): mediafiles = [] for mediafile in value: if mediafile.metadata.get('mime_type') == mime_type: mediafiles.append(mediafile) return mediafiles
282
84
import os import boto3 import dj_database_url from mbq import env, metrics SECRET_KEY = 'fake-key' DEBUG = True ATOMIQ = { 'env': 'Test', 'service': 'test-service', } database_url = os.environ.get('DATABASE_URL', 'mysql://root:@mysql:3306/atomiqdb') DATABASES = { 'default': dj_database_url.parse(databa...
561
236
import json import requests def upload_file(upload_url, file_path): files = {'file': open(file_path, 'rb')} response = requests.post(upload_url, files=files) ret = response.content.decode('utf-8') ret_json = json.loads(ret) print ret_json return ret_json['data'] def post_json(post_url, post...
720
239
""" Tools for creating a CA cert and signed server certs. Divined from http://svn.osafoundation.org/m2crypto/trunk/tests/test_x509.py The mk_temporary_xxx calls return a NamedTemporaryFile with certs. Usage ; # Create a temporary CA cert and it's private key cacert, cakey = mk_temporary_cacert() # Create a ...
4,761
2,089
from collections import deque class IndexedObject: """Container for an object that has indices :param name: Name of the object :param indices: Indices attached to it """ def __init__(self,name,indices): """Constructor """ self.name = name self.indices = indic...
2,615
745
import copy from utils.file_utils.dataset_reader_pack.ml_dataset_reader import get_TV_T_dataset, get_T_V_T_dataset from ml_sl.rf.dt_0 import Node, save_node, load_node from ml_sl.ml_data_wrapper import pack_list_2_list, single_point_list_2_list, reform_labeled_dataset_list from ml_sl.ml_data_wrapper import split_label...
10,942
4,513
from SAGIRIBOT.basics.aio_mysql_excute import execute_sql async def update_setting(group_id, setting_name, new_setting_value) -> None: """ Update setting to database Args: group_id: Group id setting_name: Setting name new_setting_value: New setting value Examples: awa...
874
298
from distutils.core import setup setup( name = 'caro-diario', packages = ['caro-diario'], # this must be the same as the name above version = '0.1', description = 'Diario', author = 'Francesco Maida', author_email = 'francesco.maida@gmail.com', url = 'https://github.com/fmaida/caro-diario.git', # use the ...
486
163
# Copyright 2021 Guillermo Blázquez # # Licensed under the Apache License, Version 2.0 (the "License") # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wr...
3,695
1,135
# -*- coding: utf-8 -*- """ This file contains tests for tensor.py """ import sys import pathlib import pytest import numpy as np from testing_utils import isclose # Ensure that 'matmodlab2' is imported from parent directory. sys.path.insert(0, str(pathlib.Path(__file__).absolute().parent.parent)) import matmodlab2 i...
8,027
4,597
from trumania.core import circus import trumania.core.population as population import trumania.core.random_generators as gen import trumania.core.operations as ops import trumania.core.story as story import trumania.components.time_patterns.profilers as profilers import trumania.core.util_functions as util_functions im...
10,380
3,083
import math class Complex(object): def __init__(self, real, imaginary): self.real = real self.imaginary = imaginary def __add__(self, no): return (Complex(self.real + no.real, self.imaginary + no.imaginary)) def __sub__(self, no): return (Complex(self.real ...
1,104
411
from itertools import product from hyperparameter_tuner.single_parameter_generator import single_parameter_generator as sgen class run_command_generator(): def __init__(self, single_parameter_generator_list, command_prefix="python ../experiment.py", output_path="./results"): for gen in s...
1,828
561
# # Copyright 2017 Barcelona Supercomputing Center (www.bsc.es) # # 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...
1,718
486
# pylint: disable=C0114 import unittest from origin_response import lambda_handler event = { "Records": [ { "cf": { "config": {"requestId": "thisfakeidisthisfakeidisthisfakeidis"}, "request": {"uri": ""}, "response": {"headers": {}, "status": 0}...
5,476
1,743
from abc import ABCMeta, abstractmethod class BaseQueue(metaclass=ABCMeta): """Abstract Class """ def __init__(self): self.contents = list() @abstractmethod def Enqueue(self, item): pass @abstractmethod def Dequeue(self): pass def Print_Contents(self): ...
377
113
from rest_framework.routers import DefaultRouter from .views import PermissionsViewset, GroupPermissionsViewset permission_router = DefaultRouter() permission_router.register(r'permissions', PermissionsViewset, basename="permissions") permission_router.register(r'grouppermissions', GroupPermissionsViewset, basename="...
338
89
#!/usr/bin/env python # encoding: utf-8 """Classes used for rendering (parts) of the canvas. Every parsed :class:`~inscriptis.model.html_element.HtmlElement` writes its textual content to the canvas which is managed by the following three classes: - :class:`Canvas` provides the drawing board on which the HTML page...
6,158
1,650
# -*- coding: utf-8 -*- """ zoom.tests.webdriver_tests.test_admin test admin app functions """ from zoom.testing.webtest import AdminTestCase class SystemTests(AdminTestCase): """MyApp system tests""" def add_user(self, first_name, last_name, email, username): self.get('/admin') s...
9,324
2,840
import json import torch from flask import Flask, request, jsonify from flask_limiter import Limiter from flask_limiter.util import get_remote_address from model.lofi2lofi_model import Decoder as Lofi2LofiDecoder from model.lyrics2lofi_model import Lyrics2LofiModel from server.lofi2lofi_generate import decode from se...
1,832
658
#!/usr/bin/env python3 ''' Cryptowat.ch API https://cryptowat.ch/docs/api https://api.cryptowat.ch/markets/prices ''' import urllib.request, json, datetime, time from urllib.request import urlopen from pathlib import Path csv_file_price = Path(__file__).parents[0] / 'data' / 'cryptowatch-bitcoin-price2.csv' def requ...
1,153
396
# -*- coding: utf-8 -*- """actor_critic.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/17Gpya9yswf-xonOvKhoHpmQGhCYpq8x4 """ # !pip install box2d-py # !pip install gym[Box_2D] import torch from torch import nn from torch.nn import functional as...
3,516
1,168
#!/usr/bin/env python # coding: UTF-8 import os import struct from .sta import * import json import copy import base64 from collections import OrderedDict class Stream: def __init__(self, byte): self.byte = byte self.index = 0 def read(self, size=None): data = '' if size is N...
6,145
2,000
#!/usr/bin/python3 """ Consider all the leaves of a binary tree. From left to right order, the values of those leaves form a leaf value sequence. For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8). Two binary trees are considered leaf-similar if their leaf value sequence is the same. R...
1,494
438
class ChatKnowledgeMemDict: """ class for storing dict data on the django memory for speed up dict search action """ # cc_id - entitiy_id -value list ngram = {} ngram_order = {} ngram_conf = {} data = {} data_conf = {} data_order = {} #ordered proper_noun synonym = {} ...
332
110
from datetime import datetime, timedelta from typing import Optional from fastapi import Depends, HTTPException, status from fastapi.security import OAuth2PasswordBearer from jose import JWTError, jwt from passlib.context import CryptContext from apollo.crud import query_first_user from apollo.main import si...
2,465
803
from App import App from utils.get_screen_size import get_screen_size if __name__ == "__main__": app = App() h, w, ch = get_screen_size() while True: app.proccessing(h, w, ch)
200
76
class BaseValidator(): MISSING = 0 INVALID = 1 def check(self, config): raise NotImplementedError() class Validator(BaseValidator): def __init__(self, *validators): self._validators = validators def check(self, config): errors = [] for validator in self._validat...
1,836
501
#!/usr/bin/python2.4 # # Copyright 2008 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/LICENSE-2.0 # # Unless required by applicable law o...
3,695
1,246
# Download the data you import os import tarfile import requests def fetch_data(dataset_url): file_name = dataset_url.split('/')[-1] dataset_path = os.path.join("datasets", file_name.split('.')[0]) print(dataset_path) print(f"File name: {file_name.split('.')[0]}") os.makedirs(dataset_path, exist_o...
608
222
""" A place to implement built-in functions. We use the bytecode for these when doing cross-version interpreting """ from xpython.pyobj import Function, Cell, make_cell from xdis import codeType2Portable, PYTHON_VERSION, IS_PYPY def func_code(func): if hasattr(func, "func_code"): return func.func_code ...
4,526
1,411
# import the necessary packages import os # Set the dataset base path here BASE_PATH = "/content/Keras-retinanet-Training-on-custom-datasets-for-Object-Detection--/dataset" # build the path to the annotations and input images ANNOT_PATH = os.path.sep.join([BASE_PATH, 'annotations']) IMAGES_PATH = os.path.sep.join([BA...
857
295
# -*- coding: utf-8 -*- # Copyright (c) 2016, Silvio Peroni <essepuntato@gmail.com> # # Permission to use, copy, modify, and/or distribute this software for any purpose # with or without fee is hereby granted, provided that the above copyright notice # and this permission notice appear in all copies. # # THE SOFTWARE I...
4,199
1,342
import re import os from collections import OrderedDict as odict from .conf import USER_DIR from .util import cacheattr, setcwd, runsyscmd, logdbg from . import util from . import err _cache_entry = r'^(.*?)(:.*?)=(.*)$' def hascache(builddir): c = os.path.join(builddir, 'CMakeCache.txt') if os.path.exists...
14,738
4,467
#!/usr/bin/env python __author__ = "bt3" import random ''' The simplest way...''' def quickSelect(seq, k): # this part is the same as quick sort len_seq = len(seq) if len_seq < 2: return seq # we could use a random choice here doing #pivot = random.choice(seq) ipivot = len_seq // 2 pivo...
2,130
783
import numpy as np import cv2 import sys import os #######################RGB Image Data Analysis############################################################ ###Should follow the data structure of image data: Genotype --> Replicates (Plants) --> Different Views --> Image captured by each Day### # mfold defines the fol...
3,744
1,662
import numpy as np from . import vector as V def rbm_to_dualquat(rbm): import cgkit.cgtypes as cg q0 = cg.quat().fromMat(cg.mat3(rbm[:3,:3].T.tolist())) q0 = q0.normalize() q0 = np.array([q0.w, q0.x, q0.y, q0.z]) t = rbm[:3, 3] q1 = np.array([ -0.5*( t[0]*q0[1] + t[1]*q0[2] + t[2]*...
4,620
2,327
# coding: utf-8 # Team : uyplayer team # Author: uyplayer # Date :2019/11/20 下午4:22 # Tool :PyCharm ''' https://blog.csdn.net/c9Yv2cf9I06K2A9E/article/details/79739287 https://msd.misuland.com/pd/13340603045208861 ''' class AttnDecoderRNN(nn.Module): def __init__(self, hidden_size, output_size, dr...
2,214
1,025
""" Write a Python program that reads a date (from 2016/1/1 to 2016/12/31) and prints the day of the date. Jan. 1, 2016, is Friday. Note that 2016 is a leap year. """ from datetime import date print("Input month and date(separated by a single space): ") m, d = map(int, input().split()) weeks = {1: "Monday", 2: "Tuesda...
497
213
""" 题目描述 给定n个字符串,请对n个字符串按照字典序排列。 输入描述: 输入第一行为一个正整数n(1≤n≤1000),下面n行为n个字符串(字符串长度≤100),字符串中只含有大小写字母。 输出描述: 数据输出n行,输出结果为按照字典序排列的字符串。 示例1 输入 9 cap to cat card two too up boat boot 输出 boat boot cap card cat to too two up """ list = [] n = int(input()) for i in range(0, n): s = input() list.append(s) list.sort() f...
347
261
class CubicCell: """ represents confining cell for the polymer """ def __init__(self, a,b,c): """ init the cell :param a: ``OX`` dimension :type a: int :param b: ``OY`` dimension :type b: int :param c: ``OZ`` dimension :type c: int ...
1,340
480
import jsonhandler from LuyckxFeatures import * import timblClassification as timbl import os import numpy as np from collections import Counter def parseC10(c10_path): jsonhandler.loadJson(c10_path) jsonhandler.loadTraining() candidates = jsonhandler.candidates unknowns = jsonhandler.unknowns f...
2,558
894
from bs4 import BeautifulSoup from multiprocessing import Pool import requests def lineid(lineno): lineurl = "http://61.43.246.153/openapi-data/service/busanBIMS2/busInfo?lineno="+lineno+"&serviceKey=0XeO7nbthbiRoMUkYGGah20%2BfXizwc0A6BfjrkL6qhh2%2Fsl8j9PzfSLGKnqR%2F1v%2F%2B6AunxntpLfoB3Ryd3OInQ%3D%3D" lin...
3,133
1,481
# -*- coding: utf-8 -*- """ Created on Mon Nov 23 13:54:58 2020 @author: Patrice CHANOL & Corentin MORVAN--CHAUMEIL """ import numpy as np import torch import time import visualisation from datetime import datetime def main(model, criterion, optimizer, scheduler, data_train_loader, data_test_loader, num_epochs, inp...
4,256
1,318
import numpy as np import pandas as pd import datetime def gen_cols(Pad, cur, lag): currency = list(np.sort(Pad['currency pair'].unique())) tmp = Pad[Pad['currency pair'] == cur].sort_values(by=['timestamp']) for i in range(1,lag+1): colname1 = 'bid_lag_' + str(i) colname2 = 'ask_lag_' + st...
3,679
1,455
import math import os from argparse import ArgumentParser import numpy as np import torch from pytorch_lightning import Trainer from pytorch_lightning import seed_everything from pytorch_lightning.utilities import rank_zero_info from pytorch_lightning.callbacks import XLAStatsMonitor from torch.utils.data import Datas...
3,863
1,336
# -*- coding: utf-8 -* import requests import json def get_weather(city: str) -> json: req = requests.get("https://free-api.heweather.net/s6/weather?location=" "{}&key=89d6bbc3861844d59a6313c16448d293".format(city)) json_data = json.loads(req.text, encoding="UTF8") return json_data ...
2,059
868
import os import numpy as np from .utils import get_class_names from ..abstract import Loader from ..backend.image import resize_image # IMAGES_PATH = '../datasets/fer2013/fer2013.csv' # LABELS_PATH = '../datasets/fer2013/fer2013new.csv' class FERPlus(Loader): """Class for loading FER2013 emotion classification...
2,536
859
from typing import List class Solution: def maxArea(self, height: List[int]) -> int: # We can create "left" and "right" pointers # the initial width between "l" and "r" is already the maximum l, r = 0, len(height) - 1 width = r - l # We can use greedy metho...
863
256
# This Python file uses the following encoding: utf-8 """ MIT License Copyright (c) 2020 Nils DEYBACH & Léo OUDART 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 ...
3,578
1,259
from correlcalc import * bins = np.arange(0.002,0.062,0.002) #corrdr12flcdmls=tpcf('/usr3/vstr/yrohin/Downloads/galaxy_DR12v5_CMASS_North.fits',bins,randfile='/usr3/vstr/yrohin/randcat_dr12cmn_2x_pdf10k.dat',estimator='ls',cosmology='lcdm',weights='eq') print("--------------------------------------------") corrdr12flcl...
1,503
681
import torch from torchvision import transforms from PIL import Image import numpy as np import math from sklearn.linear_model import LinearRegression from .grid import Grid, grid_split import torch.backends.cudnn as cudnn ''' Global Constants: TASK_NAME: Name of the verification task (deprecate...
10,965
3,716
from telnetlib import Telnet from exception.exceptions import * from datetime import date import time import os from dotenv import load_dotenv import json load_dotenv() ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) f = open(f'{ROOT_DIR}/equipamentos.json') equipamentos = json.load(f)['equipamentos'] def ma...
5,537
1,812
#!/usr/bin/env python PROJECT = 'musubi' VERSION = '0.2' import distribute_setup distribute_setup.use_setuptools() from setuptools import setup, find_packages try: long_description = open('README.rst', 'rt').read() except IOError: long_description = 'Uh oh, we may need a new hard drive.' setup( name=PR...
1,623
522
import os import pandas as pd import click from datetime import date @click.command("preprocess") @click.option("--input-dir") @click.option("--output-dir") @click.option("--mode") def preprocess(input_dir: str, output_dir, mode): if mode == "data": data = pd.read_csv(os.path.join(input_dir, "data.csv"))...
1,048
356
from time import sleep from sys import stdout def barra(v): v = int(v) print('[ ', end='') for v in range(0, v): print(f'-', end='', flush=True) sleep(0.1) print(' ]', end='\n') def calcularNotas(): soma = 0 v = 0 for i in range(0, 2): nota = float(input(f'\n{i + ...
581
251
from datetime import datetime from sqlalchemy import or_ from app import db from .mixin import ModelMixin class Show(db.Model, ModelMixin): __tablename__ = "shows" id = db.Column(db.Integer, primary_key=True) start_time = db.Column(db.DateTime, nullable=False) artist_id = db.Column( ...
4,329
1,379
# Generated by Django 2.2.4 on 2019-08-30 21:56 from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import model_utils.fields class Migration(migrations.Migration): initial = True dependencies = [ ('conferences', '0007_auto_20190811_1953'), ] ...
2,141
631
from .alien_config import AlienConfig from .alien_connection import AlienConnection from .alien_tag import AlienTag from .alien_tag_list import AlienTagList
156
47
from subprocess import run, PIPE def check(password,filedata): print("Trying passphrase={:s}".format(password)) cmd = run("gpg --pinentry-mode loopback --passphrase '{:s}' -d {:s}".format(password,filedata), shell=True, stdout=PIPE) if cmd.returncode == 0: output = cmd.stdout.decode('utf-8') ...
658
211
import sys as _sys import pandas as _pd from apodeixi.testing_framework.a6i_unit_test import ApodeixiUnitTest from apodeixi.util.formatting_utils import DictionaryFormatter from apodeixi.util.a6i_error import ApodeixiError, FunctionalTrace...
8,524
2,338
import numpy as np class MateBase: def apply(self, ind1, ind2): pass def __call__(self, ind1, ind2): return self.apply(ind1, ind2) class LambdaMate(MateBase): def __init__(self, function_ref, **kw): self.kwargs = kw self.apply = lambda ind1, ind2: function_ref(ind1, in...
944
349
__author__ = 'varun' from django import forms class ContactUsForm(forms.Form): name = forms.CharField() email = forms.CharField() phone = forms.CharField() message = forms.CharField(widget=forms.Textarea)
223
66
# # Copyright (c) 2018 Via Technology Ltd. All Rights Reserved. # Consult your license regarding permissions and restrictions. # """ Administration operations for the geo db. """ import os import socket import time from pru.db.geo.geo_init import load_airspace, remove_all_sectors, tear_down from pru.db.geo.geo_init i...
4,236
1,301
from typing import List, Tuple import easymunk as a from easymunk import BB, Vec2d class TestAutoGeometry: def test_is_closed(self) -> None: not_closed: List[Tuple[float, float]] = [(0, 0), (1, 1), (0, 1)] closed: List[Tuple[float, float]] = [(0, 0), (1, 1), (0, 1), (0, 0)] assert not a.i...
4,040
1,619
def test_client(client): assert client.get("/").status_code == 200 def test_root(root): me = root.user.get_me() assert me["id"] == "root" assert me["role"] == "root" def test_user(user): res = user("guyskk", email="guyskk@purepage.org") me = res.user.get_me() assert me["id"] == "guyskk"...
384
151
# -*- coding: utf-8 -*- import cffi import ctypes import numpy as np import pandas as pd from darshan.api_def_c import load_darshan_header from darshan.discover_darshan import find_utils from darshan.discover_darshan import check_version API_def_c = load_darshan_header() ffi = cffi.FFI() ffi.cdef(API_def_c) lib...
13,144
4,706
from django.conf import settings from rest_framework import generics, status from rest_framework.response import Response from rest_framework_simplejwt.backends import TokenBackend from rest_framework.permissions import IsAuthenticated from authApp.models.user import User from authApp.serializers.userSerializer import ...
1,017
291
import time def countdown(time_sec, to_do): while time_sec: mins, secs = divmod(time_sec, 60) timeformat = '{:02d}:{:02d}'.format(mins, secs) print(timeformat, end='\r') time.sleep(1) time_sec -= 1 if time_sec == 0: print("Det här har du att göra: ") ...
882
363
from django.shortcuts import render, get_object_or_404 from django.views.decorators.cache import cache_page from .models import PhotoAlbum, VideoAlbum from blog.utils import get_pagination_page def albums_list(request): album_specific_data = {'photo': (PhotoAlbum, 'Фото альбомы'), 'video': (VideoAlbum, 'Видео ал...
1,397
477
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from __future__ import print_function, division, unicode_literals import unittest import os import json from zhihu import Post from test_utils import TEST_DATA_PATH class ColumnTest(unittest.TestCase): @classmethod def setUpClass(cls): url = 'http://zhu...
2,134
780
from tfutils.helpers import import_transformer import_transformer()
69
20
from .modules.linear import LazyBilinear from .modules.mlp import MLP from .modules.mlp import LazyMLP from .modules.normalization import LazyBatchNorm from .modules.normalization import LazyBatchNorm1d from .modules.normalization import LazyBatchNorm2d from .modules.normalization import LazyBatchNorm3d from .modules.n...
354
107
import sys import json import numpy as np import imageio from argparse import Namespace def loadenv(config_path): """Load configuration file of Lightmetrica environment""" # Open config file with open(config_path) as f: config = json.load(f) # Add root directory and binary directory to sys.pa...
874
315
def getArray(): line = input() line = line.strip().split(' ')[1:] s = [] for x in line: s.append(int(x)) return s def merge(s1, s2): n1 = len(s1) n2 = len(s2) p1 = 0 p2 = 0 s = [] while(p1 < n1 or p2 < n2): if(p1 < n1 and (p2 >= n2 or s1[p1] < s2[p2])): s.append(s1[p1]) p1 += 1 else: s.a...
503
280
import csv import json from pprint import pprint import os stockData = ['RIO'] for i in range(0,len(stockData)): csvfile = open(stockData[i]+'.csv', 'r') fieldnames = ("NetworkTime","StockID","Open","High", "Low", "Close", "Adj Close", "Volume") reader = csv.DictReader( csvfile, fieldnames) data = o...
1,276
439
import requests class Api: def __init__(self, token): self.token = token def get_history(self): r = requests.get('https://api-mifit-de2.huami.com/v1/sport/run/history.json', headers={ 'apptoken': self.token }, params={ 'source': 'run.mifit.huami.com', ...
700
234
import time,sys,os import subprocess class Tools_watch_sub(): def check_sub_process(self, SCR, SCRfield): subs = SCR['sub_process'] command = SCRfield['command'] cmd_l = ['tasklist','/fo','csv'] pid_set = set('') if command == 'bash': ps_str = subprocess.Popen...
1,431
509
#!/usr/bin/env python """ DBS 3 Migrate REST model unittests The DBS3 Migration Service must be stopped before executing the unittest. In addition, take care that no instance is running on the same DB. Else the single unittests can happen to fail due to race conditions with DBS3 Migration Service. """ from dbsserver_t...
7,616
2,293
from setuptools import setup, find_packages # from distutils.core import setup # import py2exe # import sys import os del os.link # sys.setrecursionlimit(5000) with open('requirements.txt') as f: required = f.read().splitlines() def readme(): with open('README.md') as f: return f.read() setup(name=...
844
274
# # Copyright (C) 2021 Vaticle # # Licensed to the Apache Software Foundation (ASF) 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, Versi...
2,334
740
def signum(x): if x > 0: return 1 if x < 0: return -1 return 0 # copy of Python 3.5 implementation - probably not needed def isclose(a, b, rel_tol=1e-09, abs_tol=0.0): return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol) def gcd(a, b): """Greatest common divisor""" return _gcd_in...
1,668
545
import sys sys.path.insert(1, './GR_BASS/BASS_only_original/') sys.path.insert(1, './GR_BASS/') import bass as md import numpy as np import sys import bassLibrary as bl # BASS algorithm parameters eps = 0.1 p_d = 0.2 Jthr = 0.15 seed = 0 # Creating synthetic data for process BASS on and to learn the GMM model nbC...
2,477
1,009
from pydantic import BaseModel, EmailStr class CreateResetPasswordRequest(BaseModel): email: EmailStr
108
30
#! /bin/env python """ Examples ======== **Rectilinear** Create a rectilinear grid that is 2x3:: (0) --- (1) --- (2) | | | | | | | [0] | [1] | | | | | | | (3) --- (4) --- (5) Numbers in parens are node IDs, and numbers in square br...
3,707
1,319
import pygame from conteudo import Conteudo, Nave, Tiro import random class Jogo: def __init__(self): self.fundo1 = Conteudo("arquivos/espaco.png", 0, 0) self.fundo2 = Conteudo("arquivos/espaco.png", 0, -960) self.nave = Nave("arquivos/nave1.png",630,750) self.comando = Conteudo("a...
27,447
10,635
import inspect import typing from di.api.dependencies import CacheKey from di.dependant import Dependant, Marker from xpresso._utils.typing import Protocol from xpresso.binders.api import SupportsExtractor, SupportsOpenAPI T = typing.TypeVar("T", covariant=True) class SupportsMarker(Protocol[T]): def register_...
1,308
385
import sys import unittest as ut import numpy as np import xarray as xr # Import from directory structure if coverage test, or from installed # packages otherwise if "--cov" in str(sys.argv): from src.geocat.f2py import grid_to_triple else: from geocat.f2py import grid_to_triple # Size of the grids ny = 2 mx...
3,698
1,541
def main(): import time # Write a for loop that counts to five. # Body of the loop - print the loop iteration number and the word "Mississippi". # Body of the loop - use: time.sleep(1) # Write a print function with the final message. for i in range(5): print(f'{i + 1} ...
440
145
#!/usr/bin/env python # Copyright 2020 The HuggingFace Team. 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...
1,252
437
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a cop...
8,931
2,771