content stringlengths 5 1.05M |
|---|
# 1st brute-force solution
class Solution:
def maxProduct(self, nums: List[int]) -> int:
largest = nums[0]
for i in range(len(nums)):
curProduct = 1
for j in range(i, len(nums)):
curProduct *= nums[j]
largest = max(largest, curProduct)
... |
from utils import load_pickle, save_pickle
import re
import string
ALPH = string.ascii_uppercase
def process_babi_dataset(save, print_dict=False):
file = open('dialog-bAbI-tasks/dialog-babi-task5-full-dialogs-trn.txt', 'r')
text = file.readlines()
file.close()
system_acts = load_pickle('system_acts.p... |
from conans import ConanFile, CMake, tools
import os
class Small3dTestConan(ConanFile):
settings = "os", "compiler", "build_type", "arch"
options = {"vulkan": [True, False]}
default_options = {"vulkan": False}
generators = "cmake"
def build(self):
cmake = CMake(self)
cmake.configur... |
import os
import sys
from ff3 import FF3Cipher
def encrypt():
c = FF3Cipher(sys.argv[1], sys.argv[2])
print(c.encrypt(sys.argv[3]))
def decrypt():
c = FF3Cipher(sys.argv[1], sys.argv[2])
print(c.decrypt(sys.argv[3]))
#if __name__ == '__main__':
# sys.exit(main())
|
# Standard imports
import os
import logging
import json
# Third-party imports
from pyomo.environ import SolverFactory
import pandas as pd
import matplotlib.pyplot as plt
# Internal imports
#from tou_model import model
from tou.tou_model_price import model
from generate_profile.constants import LOG_FORMAT
'''
Obtaine... |
from __future__ import annotations
import logging
import os
import re
import sys
from typing import List, Type, Pattern
import toml
log = logging.getLogger("socorepo")
class TomlDict:
_filename: str
_dict: dict
_prefix: List[str]
@staticmethod
def load(file: str) -> TomlDict:
return To... |
import skimage.io as io
import numpy as np
import skimage
from skimage import filters
import torch
import torch.nn.functional as F
import scipy.signal as sig
from torch.autograd import Variable as V
import matplotlib.pyplot as plt
import conv
from numpy.lib.stride_tricks import as_strided
def construct_response(img1,... |
"""
Pipeline module.
"""
import os
import subprocess
import sys
import tarfile
import zipfile
import shutil
from shutil import copyfile
from bsub import bsub
sys.stdout.flush()
__author__ = 'Nima Pakseresht, Blaise Alako'
class DtuCge:
'''
docker run -ti --rm -v /analysis/cbs/databases:/databases -v \
/analysis/ni... |
#!/usr/bin/env python
from distutils.core import setup
# Define __version__. Equivalent of execfile but works in Python 3.
with open("annex/version.py", "r") as version:
code = compile(version.read(), "annex/version.py", "exec")
exec(code)
kwargs = {
"name": "annex",
"version": __version__,
"pac... |
"""Manage home view access with gatekeeper"""
# pylint: disable=arguments-differ
# pylint: disable=useless-super-delegation
# pylint: disable=import-error
from django.conf import settings
from django.views.generic import TemplateView
class IndexView(TemplateView):
"""Template for the home page."""
templat... |
from deepmerge import Merger
class WTFormsHelpers(object):
"""WTForms helpers
Register some template helpers to allow developers to
map WTForms elements to the GOV.UK jinja macros
"""
def __init__(self, app=None):
self.app = app
if app is not None:
self.init_app(app)
... |
# Generated by Django 3.2.6 on 2021-08-18 11:33
import app.models
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('app', '0020_auto_20210817_0507'),
]
operations = [
migrations.CreateModel(
na... |
"""
neopixel baglantisi
PIXEL ESP32
GND - G
DIN - 4
4-7V - 3V3
"""
import neopixel
import utime
#import machine
from machine import Pin
led_sayisi=8
np = neopixel.NeoPixel(Pin(4) , led_sayisi)
#buzzer kullanimi icin
# PIN5 - BUZZER +
# GND - BUZZER -
from machine import PWM
buzzer_pin=5
beeper=PWM(Pin(buzzer_pin... |
from django.db import models
# Create your models here.
from UserManagement.models import User
from PostManagement.models import Post
class Comment(models.Model):
Comment_description = models.CharField(max_length=5000)
User = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
Post = models.Fo... |
from prefect import task
from icecream import ic
@task(log_stdout=True)
def query_diff_local_cloud(local_set: set, cloud_set: set, chunk_size: int, workers: int) -> set:
diff_set = cloud_set.difference(local_set)
if diff_set:
print(f"{len(diff_set)} new data files available for download.")
else:
... |
from types import FunctionType
import numpy as np
from copy import deepcopy
from Board.Board import Board
from Board.Disc import Disc
from Location.Location import Location
# ใขใณใใซใซใญๆจๆข็ดขใฎใใใฎใใผใใ่กจใใฏใฉใน
class Node:
def __init__(self, board:Board, parentNode:"Node", location:Location) -> None:
self.board = boa... |
# 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 writing, software
# distributed under the ... |
"""
Definition of the :class:`~django_mri.apps.DjangoMriConfig` class.
References
----------
* `Django applications`_
.. _Django applications:
https://docs.djangoproject.com/en/3.0/ref/applications/#module-django.apps
"""
from django.apps import AppConfig
class DjangoMriConfig(AppConfig):
"""
*django_mr... |
import docker
import requests
import sys
import time
import unittest
from test_utils import TestContainerRunner
class ContainerTest(unittest.TestCase):
def get_url(self, name):
client = docker.APIClient(base_url='unix://var/run/docker.sock')
port = client.port(name, 80)[0]["HostPort"]
ur... |
from django.db.models import Manager
from django.db.models.query import QuerySet
class JobQuerySet(QuerySet):
def approved(self):
return self.filter(status__exact=self.model.STATUS_APPROVED)
def archived(self):
return self.filter(status__exact=self.model.STATUS_ARCHIVED)
def draft(self)... |
# coding: utf-8
# flake8: noqa
"""
Yapily API
To access endpoints that require authentication, use your Application key and secret created in the Dashboard (https://dashboard.yapily.com) # noqa: E501
OpenAPI spec version: 0.0.29
Generated by: https://github.com/swagger-api/swagger-codegen.git
... |
# Generated by Django 2.1.3 on 2018-12-14 18:31
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('contas', '0003_auto_20181115_2318'),
]
operations = [
migrations.AlterField(
model_name='movime... |
from typing import List
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
rev = [-num for num in nums]
# print(nums)
res = []
for pos in range(0, len(nums) - 2):
if nums[pos] == nums[pos - 1] and pos - 1 >= 0:
co... |
#==========================================================================
#
# Copyright Insight Software Consortium
#
# 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... |
import logging
from analyzer.tasks.task_profile_dataset import task_profile_dataset
from datalakes.util import save_dataset_to_datalake
from datasets.models import DatasetRun
logger = logging.getLogger(__name__)
def task_refresh_data(dataset_run, task_parameters):
"""Refresh the instance of the dataset saved in... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# PYTHON_ARGCOMPLETE_OK
"""Crawl all configured sites and search for security issues."""
import argparse
import collections
import queue
import re
import shutil
import sys
import threading
from enum import Enum
import requests
import yaml
from termcolor import colored
t... |
import pygame
import sys
import random
import time
from point import *
pygame.init()
FPS = 5
WIN_WIDTH = 600
WIN_HEIGHT = 600
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RUNNING = True
clock = pygame.time.Clock()
sc = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))
sc.fill(WHITE)
pygame.display.update()
FONT = pygame.f... |
import logging
import discord
import json
import time
import datetime as dt
if __name__ == "__main__":
global data
data = {}
#Test Command
async def command_test(para):
channel = para[0]
await channel.send('Der Test hat geklappt!')
print('Der Command "Test" wurde ausgefรผhrt!')
print('----------... |
#!/usr/bin/env python3.9
import sys
import os
from pathlib import Path
import unittest
import time
import stat
import ctypes
import io
import contextlib
import filecmp
import random
import string
from collections import namedtuple
import utils
from pybatch import *
from pybatch import PythonBatchCommandAccum
from py... |
import os
import shutil
from shapely.geometry import Polygon
import networkx as nx
import json
import fiona
from .. import osm_create_maps
from .. import util
from .. import config
from ..record import transformer_4326_to_3857
TEST_FP = os.path.dirname(os.path.abspath(__file__))
def test_get_width():
assert osm_... |
import sys
import time
import argparse
from PyQt5 import QtCore, QtGui, QtWidgets
from psdaq.cas.pvedit import *
from psdaq.cas.collection_widget import CollectionWidget
from .xpm_utils import *
Transitions = [('ClearReadout',0),
('Configure' ,2),
('Enable' ,4),
('Disa... |
import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
class Network(nn.Module):
def __init__(self, input_dim, encoder_layers, decoder_layers, encoder_neurons, decoder_neurons, latent_dim, cond_dim):
super(Network, self).__init__()
self.input_dim = input... |
from setuptools import find_packages, setup
setup(name="somen", version="0.0.0", packages=find_packages("."), package_data={"somen": ["py.typed"]})
|
import os
import shutil
import platform
import argparse
import subprocess
import zipfile
version = "2.13.6"
gitUrl = "https://github.com/catchorg/Catch2.git"
gitPath = shutil.which("git")
curlPath = shutil.which("curl")
cmakePath = shutil.which("cmake")
def configureArguments():
parser = argparse.ArgumentParser(... |
class VamosError(Exception):
def __str__(self):
return "VamosError"
class InvalidMemoryAccessError(VamosError):
def __init__(self, access_type, width, addr):
self.access_type = access_type
self.width = width
self.addr = addr
def __str__(self):
return "Invalid Memor... |
#!/usr/bin/env python3
from ctypes import *
import m2m2_core
M2M2_APP_COMMON_STATUS_ENUM_t = {
"type":c_uint8,
"enum_values": [
("M2M2_APP_COMMON_STATUS_OK", 0x00),
("M2M2_APP_COMMON_STATUS_ERROR", 0x01),
("M2M2_APP_COMMON_STATUS_STREAM_STARTED", ... |
from random import randint
from time import sleep
pc = randint(0, 5)
print('-=-' * 20)
print('Vou pensar em um nรบmero de 0 a 5. Tente adivinhar: ')
print('-=-'*20)
jogador = int(input('Em que nรบmero eu pensei?: '))
print('PROCESSANDO... ')
sleep(3)
if jogador == pc:
print('Parabรฉns, vocรช acertou!')
else:
print(... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import ... |
#!/usr/bin/env python
from __future__ import print_function
def factorial(n):
if n == 1:
return n
else:
return n * factorial(n - 1)
f100 = factorial(100)
sf100 = str(f100)
s = 0
for n in sf100:
s += int(n)
print("sum of digits: ", s)
|
import os
import sys
import string
import random
import PySimpleGUI as sg
sg.theme('black')
layout = [
[
sg.Column([
[sg.Radio("Characters", 'random_words_radio', key='random_radio', default=True, enable_events=True), sg.Radio("Words", 'random_words_radio', key='words_radio', default=False, en... |
"""Implement Blaze/Bazel label."""
__all__ = [
'Label',
]
from collections import namedtuple
from pathlib import PurePath
from pathlib import PurePosixPath
import iga.context
import iga.fargparse
from iga.error import IgaError
class Label(namedtuple('Label', 'package target')):
@staticmethod
def parse... |
import sys
from distutils.core import setup, Extension
if sys.version_info >= (3,):
print('Building for Python 3')
module = Extension('hello', sources = ['hello-python3.c'])
elif sys.version_info >= (2,):
print('Building for Python 2')
module = Extension('hello', sources=['hello-python2.c'])
else:
... |
#!/usr/bin/env python
'''
This script is an extension to the "dark_rate_vs_threshold.py" script.
It takes in two sets of dark rate vs. threshold measurements and plots them on the same figure.
'''
import argparse
import glob
import matplotlib.pyplot as plt
import os
import uproot
def easy_savefig(plt, outfpn=None):
... |
#!/usr/bin/env python
# Requirements:
# numpy
# scipy
# tensorfont
# fonttools
|
import turtle
turtle.pendown()
rules = [ ["X", "X+YF++YF-FX--FXFX-YF+"],
["Y", "-FX+YFYF++YF+FX--FX-Y"]]
angle = 45
length = 10
depth = 5
start = "X"
def rewrite(S):
result = ""
for i in range(len(S)):
result += resultAddition(S[i])
return result
def resultAddition(C):
for r in ra... |
import os
import csv
import shutil
import subprocess
import time
import utilities.omictools
class Mapping(object):
# fieldnames for row representation of object
fieldnames = ['score', 'input', 'concept_name', 'concept_id']
def __init__(self, input, concept_name=None, concept_id=None, score=None)... |
# Copyright 2020 LINE Corporation
#
# LINE Corporation licenses this file to you 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 a... |
import string
import re
import os
import shutil
import inspect
from lib import BaseTest
def filterOutSignature(_, s):
return re.sub(r'Signature made .* using', '', s)
class UpdateMirror1Test(BaseTest):
"""
update mirrors: regular update
"""
longTest = False
fixtureCmds = [
"aptly -ar... |
from __future__ import unicode_literals
import csv
from django.core import management
from django.utils.encoding import force_bytes
from mayan.apps.documents.models import DocumentType, Document
from mayan.apps.documents.tests import GenericDocumentTestCase
from mayan.apps.documents.tests.literals import TEST_SMALL_... |
class Person:
def __init__(self, firstName, lastName):
self.firstName = firstName
self.lastName = lastName
self.emailId = firstName.lower() + '.' + lastName.lower() + '@' + 'company.org'
firstName = input("First name: ")
lastName = input("Last name: ")
p1 = Person(firstName, lastName)
print(p1.firstNam... |
from .fragment_field import FRAGMENT_FIELD
FRAGMENT_FIELD_CONNECTION = '''
fragment fragmentFieldConnection on FieldConnection {
totalCount
edges {
node {
...fragmentField
}
}
}
''' + FRAGMENT_FIELD
|
import os
import tarfile
import zipfile
import re
import requests
import platform
import subprocess
import json
import shutil
import io
import tempfile
from default_platform import default_platform
import deps_cross_checker
import aws
# Master table of dependency types.
# A dependency definition can specify 'type' to... |
B_46_01_9 = {0: {'A': -0.018, 'C': 0.004, 'E': 0.423, 'D': 0.613, 'G': -0.055, 'F': -0.871, 'I': -0.283, 'H': 0.03, 'K': -0.117, 'M': -0.257, 'L': -0.036, 'N': 0.253, 'Q': 0.338, 'P': 0.667, 'S': 0.12, 'R': 0.046, 'T': 0.192, 'W': -0.167, 'V': -0.121, 'Y': -0.761}, 1: {'A': -0.884, 'C': 0.086, 'E': 0.268, 'D': 0.34, 'G... |
import pytest
from arggo._internal.global_store import (
global_store_init,
global_store_get,
global_store_put,
global_store_delete,
_global_store,
GLOBAL_STORE_KEY,
)
class TestGlobalStore:
def setup_method(self):
""" setup any state specific to the execution of the given module.... |
import os
import cv2
import collections
import time
import tqdm
from PIL import Image
from functools import partial
import argparse
from importlib import import_module
train_on_gpu = True
import gc
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2020-07-19 23:39:35
# @Author : helingjie-maskmind (helingjie440@gmail.com)
# @Link : ${link}
# @Version : $Id$
import os
import numpy as np
import sys
from matplotlib.pyplot import plot
from matplotlib.pyplot import show
# ่ฏปๅๆฐๆฎ
bhp = np.loadtxt('BHP.csv',... |
from typing import Any
from uuid import uuid4
import pytest
from starlette.status import (
HTTP_200_OK,
HTTP_204_NO_CONTENT,
HTTP_400_BAD_REQUEST,
HTTP_404_NOT_FOUND,
)
from starlite import Controller, MediaType, create_test_client, delete, get
from tests import Person, PersonFactory
@delete()
def r... |
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import math
import numpy as np
from openvino.tools.mo.front.common.partial_infer.utils import int64_array, dynamic_dimension, dynamic_dimension_value
from openvino.tools.mo.front.extractor import bool_to_str
from openvino.tools.mo.grap... |
#!/usr/bin/env python3
# //////////////////////////////////////
# toggleLED.py
# Toggles the four built in USR LEDs
# They are all on chip 1 so they can be toggled together.
# Setup: sudo apt uupdate; pip3 install gpiod
# See: https://git.kernel.org/pub/scm/libs/libgpiod/libgpiod.git/tree/bindings/python/example... |
import os.path as osp
import configparser
from PIL import Image
import torch
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
from .datasets import *
from .sampler import *
from .sysumm import SYSUMM
from .regdb import RegDB
from .transforms import build_transforms
# from sampler import *... |
# remove in-place
#
class Solution:
def removeElement(self, nums, val):
if not nums:
return 0
last = 0
for i in range(len(nums)):
if nums[i] != val:
nums[last] = nums[i]
last += 1
return last
if __name__ == "__main__":
num... |
import numpy as np
import cv2
import imutils
from config import DIRECTION_VALUE_TO_NAME_DICT
def safe_slicing(slice_index, max_value):
return min(max(0, slice_index), max_value)
def safe_img_slicing(img, slice_1_start, slice_1_end, slice_2_start, slice_2_end):
if slice_1_end < slice_1_start:
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
dependencies = [
('library', '0039_auto_20170504_1149'),
]
operations = [
migrations.AddField(
model_name='synthesisite... |
class Solution:
def minOperations(self, nums: List[int]) -> int:
k=0
for i in range(1,len(nums)):
if nums[i-1]>=nums[i]:
k+=nums[i-1]-nums[i]+1
nums[i]+=nums[i-1]-nums[i]+1
return k
|
from .jws_algorithms import JWS_ALGORITHMS
from .jwe_algorithms import (
JWE_ALGORITHMS,
JWE_ALG_ALGORITHMS,
JWE_ENC_ALGORITHMS,
JWE_ZIP_ALGORITHMS,
)
from .jwk_algorithms import JWK_ALGORITHMS
__all__ = [
'JWS_ALGORITHMS',
'JWE_ALGORITHMS',
'JWE_ALG_ALGORITHMS',
'JWE_ENC_ALGORITHMS',
... |
import setuptools
with open("README.rst", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="brixs",
version="0.1",
author="Carlos Galdino",
author_email="galdino@ifi.unicamp.br",
description="Python package for analysis of RIXS spectra.",
long_description=long_description,
... |
import unittest
from unittest import TestCase
from la_deep_get import dget
class TestSimpleIterating(TestCase):
def test_string(self):
string = "test"
assert dget(string, 0) == "t"
assert dget(string, 1) == "e"
assert dget(string, 2) == "s"
assert dget(string, 3) == "t"
... |
""" CNN Trainer Module
Modules and functions used for CNN training.
This is mainly used inside `convnet_trainer.ipynb`
"""
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import copy
import os
import time
import urllib
import matplotlib.pyplot as plt
import numpy as np
import torch
import to... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
# Export this package's modules as members:
from .get_ip_set import *
from .get_regex_pattern_set import *
from .get_rule_group import ... |
import cv2
import numpy as np
import itertools
import time
import os
from os import listdir
from os.path import isfile, join
from utilities.yolo_model_architecture import *
from utilities.keras_ocr_model_architecture import *
# define some parameters that OCR will need
CHAR_VECTOR = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456... |
from .utilities.ggr_config import *
def globals(request):
NoGA = False
if 'Speed Insights' in request.META.get('HTTP_USER_AGENT', ''):
NoGA = True
return {
"FB_APP_ID": CONFIG['FB_APP_ID'],
"ENV": {
"DEPLOYMENT": CONFIG['DEPLOYMENT'],
"NoGA": NoGA
}
... |
import datetime
import argparse
import logging
import os
import sys
import time
from lib.utils.wind import file_util as wfile_util
from lib.utils.wind import git_info as wgit_info
from omegaconf import OmegaConf
from lib.config import resolver
# import resolver
def parse_argument():
parser = argparse.ArgumentPa... |
from .boolean import BooleanProperty
from .floating import FloatProperty
from .integer import IntegerProperty
from .string import StringProperty
python_type_mapper = {
bool: BooleanProperty,
float: FloatProperty,
int: IntegerProperty,
str: StringProperty,
}
|
import numpy as np
import matplotlib.pyplot as plt
def plot_multi_image(imgs, save_dir, caption=None):
# imgs is (h, w, imsize, imsize, 3), numpy arrays and not pytorch tensors!
if imgs.shape[-1] != 3:
imgs = np.moveaxis(imgs, 2, -1)
if imgs.dtype is not np.uint8:
imgs = np.clip((imgs * 2... |
"""
Author: Darren
Date: 01/02/2021
Solving https://adventofcode.com/2016/day/17
4x4 grid of rooms connected by doors. Start top left.
Need to get to vault in the bottom right.
Whether the doors are open or locked depends on the hex value of an MD5 checksum,
which is computed based on the path taken so far.
Thus, a ... |
#!/usr/bin/env python
from setuptools import setup
with open("README.md") as readme_file:
readme = readme_file.read()
requirements = ["aiohttp"]
setup_requirements = ["pytest-runner"]
test_requirements = [
"asynctest",
"pytest",
"pytest-cov",
"pytest-asyncio",
"wheel",
]
setup(
name="i... |
# Copyright (c) 2021, NVIDIA CORPORATION. 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 copyright
# notice, this list of conditions a... |
from .price_level import _PriceLevel # noqa: F401
from .ro import PriceLevelRO # noqa: F401
|
import logging
class Logger():
loggers = {}
def __init__(self, name, file_name_prefix, levels):
for level in levels:
self.loggers[level] = logging.getLogger(f'{name}_{level}')
handler = logging.FileHandler(f'{file_name_prefix}{level}')
handler.setLevel(logging.DEBUG... |
from .byes import *
|
# http://pymbook.readthedocs.io/en/latest/testing.html
from percivaltts import *
import unittest
global cfg
cfg = configuration() # Init configuration structure
cptest = 'tests/slt_arctic_merlin_test/' # The main directory where the data of the voice is stored
lab_size = 425
spec_size = 65
nm_size = 17
cfg.vocoder_... |
import argparse
import ast
import sys
from . import mind, mast, utils, optimizer
parser = argparse.ArgumentParser()
parser.add_argument(
'file', type=argparse.FileType('r'))
parser.add_argument(
'-o', '--output', type=argparse.FileType('w'), default=sys.stdout)
parser.add_argument('-c', '--clip', action='sto... |
'''
Store configuration values
'''
from pkg_resources import resource_filename
from os.path import abspath
from PyQt5.QtCore import QFile
# Input/output formats
VALID_IN_FMT = ('.txt')
VALID_OUT_FMT = ('.json')
# Output table labels
ENTITY_LABEL = 'Entity'
VALUE_LABEL = 'Value'
SELECTION_START_LABEL = 'Start'
SEL... |
from extract_patch_segmentation_mask import extract_segmentation_mask
import matplotlib.pyplot as plt
import numpy as np
from tqdm import trange
from PIL import Image
HE_image = np.array(Image.open('/home/pictorlambdanode3/Desktop/seg_folder/svs/crop_1.png'))
def color_bin(bin_labl):
"""
Colors bin image s... |
"""
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, Version 2.0 (the
"License"); you may not use this ... |
import filecmp
import os
import pathlib
import shlex
import shutil
import subprocess
import sys
import tarfile
import unittest
import urllib.request
from vtam.utils import pip_install_vtam_for_tests
from vtam.utils.PathManager import PathManager
from vtam.utils.constants import fastq_tar_gz_url1, fastq_tar_gz_url2, fa... |
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_selection import (SelectPercentile, VarianceThreshold,
f_classif)
from sklearn.linear_model import SGDClassifier
from sklearn.model_selection import train_test_split
fro... |
from .enhance_definer import enhance_class_list, enhance_dict, enhance_name_list, MAX_PARAM, MIN_PARAM
from .image_enhancer import ImageEnhancer, ImageEnhancerException, ResizableEnhancer
from PIL.Image import Image
from .generate_param import generate_random_param_list |
import csv
import numpy as np
csv_name =
def CSV_label(csv_name):
with open(csv_name, 'r') as f:
reader = csv.reader(f)
n = 0
b = np.zeros(shape=(100, 1), dtype=np.float32)
for row in reader:
if n <= 99:
b[n] = row
n +... |
# -*- coding: utf-8 -*-
from __future__ import print_function # (at top of module)
import sys, requests
# Note: in order to use this example, you need to have at least one account
# that you can send money from (i.e. be the owner).
# All properties are now kept in one central place
from props.default import *
#... |
from functools import singledispatch
from operator import attrgetter
import unittest
def dispatch(table, dispatch_method=attrgetter('__call__'), attr_joiner='__o__'):
def dispatching(ty, recv, spec_table):
def R(this, that):
r = recv(this)
m = dispatch_method(r)
D = ... |
# License: BSD 3 clause
import numpy as np
from tick.hawkes import ModelHawkesExpKernLogLik, SimuHawkesExpKernels
from tick.hawkes.inference.base import LearnerHawkesNoParam
from tick.hawkes.inference.build.hawkes_inference import (HawkesADM4 as
_HawkesADM4)
f... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2013 Jason R. Coombs <jaraco@jaraco.com>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
import unittest
import datetime
import jsonpickle
from jsonpickle._samples import Ob... |
# ฮฉ*
# โโโโโโโโโโโโโ โโโโโโโโโโโ โ โ โ โ โโ
# โโโโโโโโโโโโโ โโโโโโโโโโ โ โโโโ โ โ
# โโโโโโโโโโโโโ โโโโโโโโโ โ โโโโโโ โ
# โโโโโโโโโโโโโ โโโโโโโโโ โ โโโโโโโ
# โโโ โ โ โ โ โโโโโโ โโโโโโโโโ โ โ โโโโโโ
# โโ โ โโโโ โ โโโโโ โโโโโโโโโโ โ โ โโโโโ
# โ โ โโโโโโ โ โโโโ โโโโโโโโโโโ โ โ โ โโโ
# โ โ โโโโโโ โ โโโโ โโโโโโโโโโโโโ โ โ โ โ
# โ โ โ โ โ โ โ โ โ โโโโ โโโโโโโโโโโโโโโ โ โ
... |
import os
import pickle
import tempfile
def status_store_filename(basename):
return os.path.join(tempfile.gettempdir(), basename)
def load_status_store(basename):
try:
with open(status_store_filename(basename), 'rb') as f:
return pickle.load(f)
except:
return None
def save_... |
from django.conf.urls import url
from desafio import views
urlpatterns = [
url(r'^solicitante$', views.solicitante_list, name='solicitante_list'),
url(r'^solicitante_new$', views.solicitante_create, name='solicitante_new'),
url(r'^solicitante_edit/(?P<pk>\d+)$', views.solicitante_update, name='solicitante... |
from .model_wrapper import ModelWrapper, WeightsProvider
from .group import Group
from .model_splitter import ModelSplitter
|
'''
URL: https://leetcode.com/problems/basic-calculator/
Time complexity: O(n)
Space complexity: O(n)
'''
class Solution:
def _get_next_num(self, i, s):
curr_num = ""
while i < len(s) and s[i].isdigit():
curr_num += s[i]
i += 1
return i-1, int(curr_num)
def cal... |
import json
import io
from twisted.internet import defer
from twisted.trial.unittest import TestCase as TrialTestCase
from twisted.test.proto_helpers import StringTransport
from infobob.irc import Infobob
from infobob.config import InfobobConfig
class InfobobProtocolTestCase(TrialTestCase):
def setUp(self):
... |
from typing import Optional, List
import dateutil
from pyspark.ml import Estimator
from pyspark.ml.evaluation import BinaryClassificationEvaluator, ParamMap, \
Evaluator
from pyspark.ml.tuning import ParamGridBuilder, CrossValidator, \
CrossValidatorModel
from pyspark.sql import functions as F
from baskervill... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.