content
stringlengths
5
1.05M
import logging import pickle import time from abc import ABC, abstractmethod from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Tuple, Type, Union import numpy as np from srl.base.define import EnvAction, EnvInvalidAction, EnvObservation, EnvObservationType, Info, RenderType from sr...
import os import sys os.chdir(os.path.abspath(os.path.dirname(sys.argv[0]))) def get_cookies_files(dirpath): return [os.path.join(dirpath, x) for x in os.listdir(dirpath) if x.endswith(".json") or x.endswith(".txt")]
import sys as _sys from typing import List from collections import _iskeyword # type: ignore from tensorboardX import SummaryWriter import os SUMMARY_WRITER_DIR_NAME = 'runs' def get_sample_writer(name, base=".."): """Returns a tensorboard summary writer """ return SummaryWriter(log_dir=os...
import cPickle as pickle import hashlib import hmac import os from Crypto.Cipher import AES class AuthenticationError(Exception): pass class Crypticle(object): PICKLE_PAD = "pickle::" AES_BLOCK_SIZE = 16 SIG_SIZE = hashlib.sha256().digest_size def __init__(self, key_string, key_size=192): sel...
#!/usr/bin/env python # (c) 2016-2017, Toshio Kuratomi <tkuratomi@ansible.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or #...
#!/usr/bin/python3 import sys class Unbuffered(object): def __init__(self, stream): self.stream = stream def write(self, data): self.stream.write(data) self.stream.flush() def writelines(self, datas): self.stream.writelines(datas) self.stream.flush() def __getattr__(self...
# This file is part of Pynguin. # # Pynguin is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Pynguin is distributed in the ho...
""" Documentation supporting the 5Bp data. Created 2012-05-07 by Tom Loredo 2019: Converted to Python 3 """ import webbrowser __all__ = ['show_ssc', 'show_archive', 'show_tech', 'show_sw', 'show_4B', 'show_5Bp', 'show_problems'] # Access to CGRO SSC documents, incl. 4B, 5Bp ("Current") catalog web page...
"""Module for HGVS tokenization.""" from typing import Optional from .tokenizer import Tokenizer from variation.tokenizers.reference_sequence import REFSEQ_PREFIXES from variation.schemas.token_response_schema import Token, TokenMatchType from hgvs.parser import Parser from hgvs.exceptions import HGVSParseError, HGVSIn...
#!/usr/bin/env python # -*- coding:utf-8 -*- def login(): print 'login' def logout(): print 'logout'
import random from tkinter import * from math import * from time import * from tkinter import filedialog from tkinter import font import tkinter.font as tkFont import tkinter as tkr root = Tk() root.geometry("800x400") root.title( "Simulation MCU 1.0v" ) root.config(bg="#ABB2B9") menubar = Menu(root,bg="red") global ...
############################ # written by Lam M. Nguyen and Trang H. Tran ############################ """ Load Data files """ import numpy as np import sys, os import pandas as pd from csv import reader #------------------------------------------------------------------------------- # Load a CSV file ...
from . import config import torch import torch_geometric as tg from tqdm.auto import tqdm import itertools as it class EmbedModel(torch.nn.Module): def __init__(self, n_layers, input_dim, hidden_dim, output_dim, conv='gin', pool='add'): super().__init__() self.n_layers = n_layers self.inp...
# This file contains functions that have been replaced in # analysisUtils by newer functions which use the ASDM bindings # library. We need to keep these for usage on machines that do not # have this library installed. - Todd Hunter from __future__ import print_function # prevents adding old-style print statements ...
load("//third_party:maven_binaries.bzl", register_tooling = "register") load("//third_party:third_party.bzl", "dependencies") def bazelizer(): register_tooling() dependencies()
import os import pickle import re import tensorflow as tf from keras.models import load_model from pymatgen import MPRester, Composition from pymatgen.core.periodic_table import get_el_sp from pymatgen.io.vasp.sets import _load_yaml_config DATA_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../data")...
#!/bin/env python import argparse import collections import pprint import pickle import os import re import cbor import logging logr = logging.getLogger( __name__ ) # Exception type is part of the error signature err_type_re_signature = { "<type 'exceptions.OSError'>": re.compile( '([^:]+):?' ), "<type 'e...
# @file NuGet.py # This module contains code that knows how to download nuget # # Copyright (c), Microsoft 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: # 1. Redistributions of sourc...
import random import unittest from putput.combiner import combine from putput.joiner import ComboOptions from tests.unit.helper_functions import compare_all_pairs class TestCombiner(unittest.TestCase): def setUp(self): random.seed(0) def test_one_token(self) -> None: utterance_combo = (('the...
import pytest import pathlib from typing import List import shutil import io from cincan.frontend import ToolImage @pytest.fixture(autouse=True, scope="function") def disable_tty_interactive(monkeypatch): """Mock stdin to make tty part of tests to complete""" monkeypatch.setattr('sys.stdin', io.StringIO('')) ...
from typing import List # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next # Array -> Listed-List @classmethod def array_to_list(cls, data: List): if len(data) == 0: return None head...
#!/usr/bin/env python3 # # This file is part of LiteX-Boards. # # Copyright (c) 2021 Sergiu Mosanu <sm7ed@virginia.edu> # Copyright (c) 2020-2021 Florent Kermarrec <florent@enjoy-digital.fr> # Copyright (c) 2020 Antmicro <www.antmicro.com> # # SPDX-License-Identifier: BSD-2-Clause # To interface via the serial port u...
magic = { 'SX_OBJECT': b'\x00', # ( 0): Already stored object 'SX_LSCALAR': b'\x01', # ( 1): Scalar (large binary) follows (length, data) 'SX_ARRAY': b'\x02', # ( 2): Array forthcoming (size, item list) 'SX_HASH': b'\x03', # ( 3): Hash forthcoming (size, key/value pair list) 'SX_R...
from threading import Thread import traceback import os.path import remi.gui as gui from remi import start, App from k40nano import PngPlotter from .EgvParser import parse_egv from .EgvSend import send_egv class K40WebServer(App): def __init__(self, *args): res_path = os.path.join(os.path.dirn...
from os.path import exists import seaborn as sns from analyze_results import get_number_of_edges from helper import file_utils as file, io_utils as io import pandas as pd import numpy as np from visualization.visualize_gcn import generate_doc_labels from visualization.visualize_tsne import reduce_dimensions, visualize...
"""Create a connection to Board Game Arena and interact with it.""" import json import logging from logging.handlers import RotatingFileHandler import re import time import urllib.parse import requests from bga_game_list import get_game_list LOG_FILENAME = "errs" logger = logging.getLogger(__name__) handler = Rotatin...
import ruamel.yaml def load_yml_from_file(file_path): yaml = ruamel.yaml.YAML() Data = None with open(file_path) as file: Data = yaml.load(file) return Data def save_yml_to_file(data, file_path): yaml = ruamel.yaml.YAML() with open(file_path, "w") as file: yaml.dump(data, fil...
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by ...
# # Time complexity: # O(lines*columns) (worst case, where all the neighbours have the same color) # O(1) (best case, where no neighbour has the same color) # # Space complexity: # O(1) (color changes applied in place) # def flood_fill(screen, lines, columns, line, column, color): def inbound(l, c)...
n = int(input('Digite um numero qualquer:')) if n % 2 == 0: print('O número {} é \033[32m Par!\033[m'.format(n)) else: print('O número {} é \033[31m Impar!\033[m'.format(n))
# -*- coding: utf-8 -*- import struct def write_int8(octet: bytes, pos: int, value: int): octet = bytearray(octet) octet[pos] = value return bytes(octet) def write_int16(octet: bytes, pos: int, value: int, big_endian: bool = False): octet = bytearray(octet) if big_endian: octet[pos] = v...
import argparse import logging import os import numpy as np import torch import utils import model.net as net from model.data_loader import DataLoader parser = argparse.ArgumentParser() parser.add_argument('--model_dir', default='experiments/base_model', help="Directory containing params.json") par...
# -*- coding: iso-8859-1 -*- from app import db class User(db.Model): __tablename__ = 'alumnos' # TIENE QUE ESTAR EN LOWERCASE!!! increible... CODIGO = db.Column('CODIGO', db.Integer, primary_key=True) NOMBRE = db.Column('NOMBRE', db.String(150)) APELLIDO = db.Column('APELLIDO', db.String(100)...
""" Tests for defer() and only(). """ from django.db import models from django.db.models.query_utils import DeferredAttribute class Secondary(models.Model): first = models.CharField(max_length=50) second = models.CharField(max_length=50) class Primary(models.Model): name = models.CharField(max_length=50)...
from wetterdienst.dwd.forecasts.api import DWDMosmixSites, DWDMosmixData from wetterdienst.dwd.forecasts.metadata import ( DWDForecastDate, DWDForecastParameter, DWDMosmixType, )
with open('inputs/input2.txt') as fin: raw = fin.read() def parse(raw): start = [(x[:3], int(x[4:])) for x in (raw.split('\n'))] return start a = parse(raw) def part_1(arr): indices = set() acc = 0 i = 0 while i < len(arr): pair = arr[i] if i in indices: bre...
from .utils import Atom, Residue, ActiveSite from .io import read_active_sites import numpy as np from random import seed from itertools import combinations as combo from math import log ########################### # Clustering By Partition # ########################### def cluster_by_partitioning(active_sites,num_c...
import sys import json # see http://initd.org/psycopg/docs/usage.html import psycopg2 # from psycopg2.extras import RealDictCursor # see https://stackoverflow.com/questions/10252247/how-do-i-get-a-list-of-column-names-from-a-psycopg2-cursor # about half way down import psycopg2.extras # see https://stackoverflow.com...
from dataclasses import make_dataclass from datetime import date, timedelta import logging import os from settings.constants import VITIGEOSS_CONFIG_FILE from pandas.core.frame import DataFrame import json import torch from torch._C import device, dtype import torch.nn.functional as F from phenoai.models import ModelsE...
import tensorflow as tf input_batch = tf.constant([ [ # First Input [[0.0], [1.0]], [[2.0], [3.0]] ], [ # Second Input [[2.0], [4.0]], [[6.0], [8.0]] ] ]) kernel = tf.constant([ [ [[1.0, 2.0]] ] ]) conv2d = tf.nn.conv2d(input_batch, kernel, strides=[1,...
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. from typing import Tuple import torch from pytorch3d.transforms import Transform3d def camera_to_eye_at_up( world_to_view_transform: Transform3d, ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """ Given a world to view transf...
from django.shortcuts import render, redirect from .models import Room from .forms import RoomForm # Create your views here. def home(request): rooms = Room.objects.all() context = {'rooms':rooms} #we put our parameters into a dictionary return render(request,'base/home.html', context) def room(request,p...
import ctypes import time import os import pybgfx class App(object): def __init__(self): pass def init(self): pass def shutdown(self): pass def update(self, dt): pass def run(self): glfw_dll_path = os.path.dirname(__file__) + "\\glfw3" glfw = c...
import numpy as np from gym import spaces as gym_spaces from . import Space class DictSpace(Space): def __init__(self, space_dict): super().__init__() self._space_dict = space_dict # calculate dimension of flat space associated to this space self._flat_dim = self._get_flat_dim_u...
from picalculator import PiCalculator def test(): pc = PiCalculator(10, 'T') tasks = pc.submit_tasks() for task in tasks: task.run() print(sum(task.result for task in tasks) / pc.n_cpu) pc.close()
from torch.utils.data import Dataset from kogpt2.utils import download, tokenizer, get_tokenizer from gluonnlp.data import SentencepieceTokenizer import gluonnlp import numpy as np import pandas as pd def sentencePieceTokenizer(): tok_path = get_tokenizer() sentencepieceTokenizer = SentencepieceTokenizer(tok...
# Time: push: O(n), pop: O(1), top: O(1) # Space: O(n) # # Implement the following operations of a stack using queues. # # push(x) -- Push element x onto stack. # pop() -- Removes the element on top of the stack. # top() -- Get the top element. # empty() -- Return whether the stack is empty. # Notes: # You must use onl...
cont = 0 cont_m = 0 cont_f20 = 0 cont_maioridade = 0 while True: sexo = ' ' while(sexo not in 'MF'): sexo = str(input('Masculino ou Feminino[M/F]? ')).upper().strip() idade = int(input(f'Qual a idade da {cont + 1}° pessoa: ')) if(sexo == 'M'): cont_m = cont_m + 1 elif(sexo == 'F' and...
#-*- coding: UTF-8 -*- from OpenGL.GL import * import numpy as np class Material(object): def __init__(self, ambient, diffuse, specular, shininess): self.__ambient = np.array(ambient, dtype = np.float32) self.__diffuse = np.array(diffuse, dtype = np.float32) self.__specular = np.array(specular, dtype = np.floa...
print(True and True)
import datetime from django.test import TestCase from freezegun import freeze_time from symposion.proposals.tests.factories import ( ProposalBaseFactory, ProposalKindFactory, ProposalSectionFactory, ) from symposion.conference.tests.factories import SectionFactory class ProposalsTest(TestCase): def ...
import csv from pathlib import Path root = "data/" def parse_file(filename): """Returns content of file as a list or dictionary :param filename: filename (including file extension) :return: a list containing the contents of each line if filename ends in .txt, otherwise a dictionary corresponding to the co...
default_app_config = 'events.apps.EventsAppConfig'
# Copyright 2015-present The Scikit Flow 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 require...
import sympy as sym from sympy.abc import s, t, x, y, z import numpy as np from sympy.integrals import inverse_laplace_transform import matplotlib.pyplot as plt # Define inputs # First step (up) starts at 1 sec U1 = 2 / s * sym.exp(-s) # Ramp (down) starts at 3 sec U2 = -1 / s ** 2 * sym.exp(-3 * s) # Ramp completes a...
# MIT LICENSE # # Copyright 1997 - 2020 by IXIA Keysight # # 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,...
import json import sys # from pyyaml package import yaml _dsl_schema_cache = None _dsl_validator_cache = None _table_admin_privs = ["SELECT", "INSERT", "DELETE", "OWNERSHIP"] _table_public_privs = ["SELECT"] def dsl_json_schema(): global _dsl_schema_cache if _dsl_schema_cache is not None: return _d...
# Unicode symbols in UTF-8 # DOWNWARDS ARROW DOWN_ARROW = b"\xe2\x86\x93" # BLACK DOWN-POINTING TRIANGLE DOWN_TRIANGLE = b"\xe2\x96\xbc"
# Generated by Django 3.1.5 on 2021-01-22 22:24 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ("course", "0023_auto_20210115_1332"), ("quiz", "0002_auto_20210120_0738"), ] operations = [ migratio...
#!/usr/bin/env python3 import os import yaml import click import logging import pandas as pd logging.basicConfig(level=logging.INFO) @click.group() def cli(): pass @cli.command() @click.option('-i', '--input', type=click.Path(exists=True), help=""" path to a TSV to be summarised....
import requests import threading from config import GITTER_WEBHOOK, SLACK_WEBHOOK def notify_all(label, counter): threads = [] gitter = threading.Thread(target=_gitter, args=(label, counter)) threads.append(gitter) slack = threading.Thread(target=_slack, args=(label, counter)) threads.append(sl...
from kivy.garden.matplotlib.backend_kivyagg import ( FigureCanvasKivyAgg, NavigationToolbar2Kivy, ) from kivy.app import App from kivy.uix.label import Label from kivy.uix.boxlayout import BoxLayout from matplotlib.figure import Figure import numpy as np def on_canvas_click(event): if event.inaxes: ...
import random from pygamelib.assets import graphics from pygamelib.gfx import core from pygamelib import board_items, constants, actuators, base from blessed import Terminal from game import media import time from copy import deepcopy terminal = Terminal() class Cell(board_items.BoardItemComplexComponent): def _...
# from genut.models.seq2seq_vae import from archive.genut import load_prev_state from archive.genut import RNNLM from archive.genut.util.argparser import ArgParser from archive.genut import Tester from archive.genut import LMTrainer if __name__ == "__main__": ap = ArgParser() opt = ap.parser.parse_args() ...
from keras.models import Sequential from keras.layers import Dense, Activation ## https://keras.io/zh/getting-started/sequential-model-guide/ """ 基本的过程 1. 输入数据的尺寸 Dense 2. 配置学习过程 compile 优化器,损失函数,评估标准 3. 加数据 data 训练 fit """ # model = Sequential([ # Dense(32, input_shape=(784,)), # Activation('relu'), # ...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Tue May 9 21:13:29 2017 @author: Luis Ariel Valbuena """ from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as pl import matplotlib.colors as mplc import numpy as np #from svmutil import * import math import HW2 as hw2 def markovProcess(P,l...
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import DataMigration from django.db import models import redis from django.conf import settings class Migration(DataMigration): def forwards(self, orm): r = redis.Redis(connection_pool=settings.REDIS_POOL) keys = r.keys(...
import discord import asyncio from discord.ext import commands # A class that support navigating pages of embeds. class Pages: """ A paginator that allows using Discord reactions to switch pages in an ordered manner. By default, there are 5 functionalities: - `fast_previous`: Return to page 0. ...
from .MaskEdgeDetector import MaskEdgeDetector from .TwoLineAverage import TwoLineAverage from .segment import HoughLines from .roi import RegionOfInterest from .clahe import Clahe, ClaheGray from .cte import CrossTrackError from .error import Error, CrossTurnError from .average import MovingAverage from . import annot...
# -*- coding: utf-8 -*- from sqlalchemy.orm import object_session """ This module contains the classes for the models. """ class BaseModel(object): """ BaseModel provides a base object with a set of generic functions """ @classmethod def populate(cls, **kwargs): """ Creates an ins...
""" Checks that Pylint does not complain about various methods on Django model fields. """ # pylint: disable=missing-docstring,wrong-import-position from django.db import models from django.db.models import ForeignKey, OneToOneField class Genre(models.Model): name = models.CharField(max_length=100) class Autho...
# Generated by Django 2.1.7 on 2019-04-23 21:07 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('fpiweb', '0011_auto_20190415_0430'), ] operations = [ migrations.AlterField( model_name='box', name='exp_month_end',...
from OpenGLCffi.GLES3 import params @params(api='gles3', prms=['pname', 'value']) def glBlendParameteriNV(pname, value): pass @params(api='gles3', prms=[]) def glBlendBarrierNV(): pass
frase=str(input('Escreva uma frase:')).upper().strip() print('Analisando...') print('Nessa frase aparece {} vezes a letra A'.format(frase.count('A'))) print('A primeira letra A apareceu na posição {}'.format(frase.find('A')+1)) print('A última letra A apareceu na posição {}'.format(frase.rfind('A')+1))
from django.apps import AppConfig class BasesConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'bases'
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: spaceone/api/identity/plugin/auth.proto """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _refl...
x = f"Hello {f' my name is {<caret>'}"
import numpy as np import random import itertools import Levenshtein import copy import pickle import os class stack: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return s...
from .base_installer import FlaskExtInstaller import os from ..config import TAB class FlaskLoginInstaller(FlaskExtInstaller): package_name = "Flask-Login" imports = ["from flask_login import LoginManager"] inits = ["login_manager = LoginManager()"] attachments = ["login_manager.init_app(app)"] de...
"""empty message Revision ID: 5ac4e9a16950 Revises: 731438255690 Create Date: 2020-09-27 14:58:05.837249 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '5ac4e9a16950' down_revision = '731438255690' branch_labels = None depends_on = None def upgrade(): # ...
class BaseQueue(object): """ Base class for queues settings_namespace is a class attribute that will be used to get the needed parameters to create new queue instance from a settings file. """ settings_namespace = None def report(self, name, metric, value, tags, id_): raise NotIm...
from .smc import SMC try: from importlib.metadata import version # type: ignore except ImportError: from importlib_metadata import version # type: ignore # from .version import __version__ __author__ = 'Kevin J. Walchko' __license__ = 'MIT' __version__ = version("smc")
import tempfile from multiprocessing import Pool, get_context from itertools import combinations from typing import List from . import discovery from .clustering_utils import generate_global_ranks, process_columns, ingestion_column_generator, process_emd from ..base_matcher import BaseMatcher from ..match import Match...
import logging from typing import Any import rasa.utils.common from rasa.utils.common import RepeatedLogFilter def test_repeated_log_filter(): log_filter = RepeatedLogFilter() record1 = logging.LogRecord( "rasa", logging.INFO, "/some/path.py", 42, "Super msg: %s", ("yes",), None ) record1_sam...
import time __author__ = 'Junior Teudjio' def timer(function): def wrapper(*pargs, **kargs): t0 = time.time() result = function(*pargs, **kargs) t1 = time.time() print function.__name__, ' took %s seconds'% (t1 - t0) return result return wrapper
from typing import List, Optional import requests from arguments import Arguments from installer import Installer _URL = "http://0.0.0.0:8080" _URL_TOOLS = "registry/tools" _URL_DATASETS = "registry/datasets" _URL_PIPELINE_REG = "registry/pipelines" _URL_PIPELINE = "pipeline" def get_tools(name: Optional[str] = No...
from provider import OVHProvider class DNSConfig: def __init__(self, record, target, provider, config): if provider == "ovh": self.provider = OVHProvider(config_file=config) self.target = target self.record = record chunk = str(record).rsplit(".", maxsplit=2) if len(chunk) < 3: raise Exception("I'm ...
import json, re, sys, evaluation import numpy as np from keras.layers import Dense, LSTM, Input from keras.layers.embeddings import Embedding from keras.models import Model from keras.preprocessing import sequence from keras.preprocessing.text import Tokenizer from keras.utils import np_utils from sklearn.model_selecti...
class Node: def __init__(self): self.children: dict[str, Node] = {} # dict[str, Node] self.value: any = None def find(node: Node, key: str) -> any: for char in key: if char in node.children: node = node.children[char] else: return None return node.val...
# Copyright (c) FlowTorch Development Team. All Rights Reserved # SPDX-License-Identifier: MIT import torch import torch.distributions as dist import torch.optim import flowtorch import flowtorch.bijectors import flowtorch.params def test_compose(): flow = flowtorch.bijectors.Compose( [ flowt...
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------ # # Copyright 2018-2019 Fetch.AI Limited # # 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 ...
# # Copyright 2020- IBM Inc. All rights reserved # SPDX-License-Identifier: Apache2.0 # from typing import Optional import numpy as np from abc import ABC, abstractmethod class BaseWholeSeller(ABC): def __init__(self, seed: Optional[int] = None): if seed is None: seed = sum([ord(s) for s in ...
#!/usr/bin/env python3 # Sets are unordered collections of unique elements. # A list with recurring elements when converted to # a set will only have elements occuring once. my_list = [1, 2, 1, 3, 4, 5] print(my_list) my_set = set(my_list) print(my_set) # The set when called from the python REPL, will be # similar ...
import asyncio from concurrent.futures import ThreadPoolExecutor from asgiref.sync import sync_to_async from django.utils import timezone from merger.mergers import (AgentMerger, ArchivalObjectMerger, ArrangementMapMerger, ResourceMerger, SubjectMerger) from pis...
#!/usr/bin/env python2 # Copyright (C) 2013: # Gabes Jean, naparuba@gmail.com # Pasche Sebastien, sebastien.pasche@leshop.ch # # 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...
#!/usr/bin/env python from atip.common.steps import * from atip.web.steps import * import time import datetime import md5 import Image # get md5 of a input string def get_string_md5(str): m = md5.new() m.update(str) return m.hexdigest() # standardize the image def make_regalur_image(img, size=(256, 2...
import numpy as np def my_nb(x,gnd): a,b = x.shape my_lab = np.unique(gnd) NumOfClass = my_lab.size pw = np.zeros([NumOfClass]) my_m = np.zeros([a,NumOfClass,1]) my_std = np.zeros([a,NumOfClass,1]) for i in range(NumOfClass): temp = np.sum(gnd==my_lab[i]) pw[i] = temp/gnd.si...
import os import pandas as pd def getCSVsAsList(): """ get all parsable CSV in project as full path :return: string list """ fileList = [] # CSVs to skip because country name is not a PK csvSkipList = [ "university_rankings.csv", "traffic_index.csv", ] for root, _...
from tkinter import Frame, OptionMenu, StringVar, Tk, Entry, Button, Label, Text, END, Y from tkinter.filedialog import askopenfilename from tkinter.messagebox import showinfo from matplotlib import pyplot as plt from pandas import read_csv, read_excel from os.path import basename # Main Window root = Tk() root.config...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('trains', '0002_trainclass_fare'), ] operations = [ migrations.CreateModel( name='Bogey', fields=[ ...