content
stringlengths
0
894k
type
stringclasses
2 values
import logging import os import requests from dotenv import load_dotenv logger = logging.getLogger('logger_main') logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) def create_workspace(trello_apikey, trello_token, wrksp_name): url = ...
python
from heapq import merge import math import os import time import sys #Uncomment this if the script will run within AEDT with Ironpython. Setup the path where pyaedt folder is. #path_to_pyaedt_root_folder="" #sys.path.append(path_to_pyaedt_root_folder) from pyaedt import Edb, Hfss3dLayout, is_ironpython from pyaedt.g...
python
# python Higher-order function print '************** Higher-order function Test Programs **************' print abs f = abs print f print f(-1) def add(x,y,f): return f(x) + f(y) print add(-1,-9,abs) raw_input()
python
import graphene from django.apps import apps from wagtail.documents.models import get_document_model from wagtail.images import get_image_model from wagtail.search.backends import get_search_backend from ..registry import registry def SearchQuery(): if registry.class_models: class Search(graphene.Union):...
python
import os, sys import glob import math import time import numpy as np import torch class UnorderedSeqFileData(object): def __init__(self, data_dir, file_list, bsz, dim, tgt_len, ext_len=None, device='cpu', normalize=True, distributed=False, down_sample=1): self.data_dir ...
python
#!/usr/bin/env python3 """ Geoscience Australia - Python Geodesy Package Coordinate Module """ from geodepy.constants import Projection, utm, grs80 from geodepy.angles import (DECAngle, HPAngle, GONAngle, DMSAngle, DDMAngle, dec2hpa, dec2gona, dec2dms, dec2ddm, ...
python
import ast import boto3 import subprocess import sys import csv from io import StringIO from urllib.parse import urlparse import logging logging.basicConfig( level=logging.INFO, format='%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S', ) LOGGER = l...
python
# coding=utf-8 # Copyright 2021 The Tensor2Robot 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 applicable ...
python
#!/usr/bin/python3.7 import os, time, random, threading, json, shutil, sys, ctypes from PIL import Image import stagger import io from pygame import mixer from flask import Flask from pynput.keyboard import Key, Listener import logging log = logging.getLogger('werkzeug') log.setLevel(logging.ERROR) ...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: Thilak Rathinavelu """ # Standard imports import logging import argparse import sys import os from subprocess import run from functools import partial logger = None home_dir = os.path.expanduser("~") script_dir = sys.path[0] git_config = ("git", "config",...
python
""" This is an straightforward example of the injectable framework in a single Python file. .. seealso:: For better understanding of this framework you can look at the other examples in the :ref:`usage_examples` section. The :ref:`basic_usage_example` is a good start! """ # sphinx-start from examples import E...
python
import numpy as np # def is_passable_coordinate(map_layout, coord_z, coord_x): def is_passable_coordinate(grid, z, x): # # Hole on the floor; can't pass # if self.is_passable_object(grid[0, z, x]): # return False # same level or above is passable; then can pass if z >= 0 and x >= 0 and z < gr...
python
from django.apps import AppConfig class PenerbitConfig(AppConfig): name = 'penerbit'
python
"""This module contains all the Facebook specific selectors and text. Whenever Facebook modifies their code, this will need to be updated to accomodate the changes. #webscraperlife CSS Selectors have better performance than XPath and should be used in all circumstances UNLESS you cannot select it properly in CSS. For ...
python
import numpy as np import pandas as pd from matplotlib import pyplot as plt admissions = pd.read_csv('binary.csv') #making dummy variables for ranks data = pd.concat([admissions, pd.get_dummies(admissions['rank'], prefix='rank')], axis=1) data = data.drop('rank',axis=1) #standardizing data for field in ['gre',...
python
from string import Template import numpy as np from PuzzleLib.Compiler.Codegen.Types import half_t, float_t from PuzzleLib.Cuda.Utils import prod, roundUpDiv minMaxTmpl = Template(""" extern "C" __global__ void minMaxOnRow$ext(int *idx, const $T *mat, int w) { float curMax = $initVal; int curIdx = -1; for (int ...
python
from django.conf import settings from django.urls import reverse, reverse_lazy from django.views.generic import ListView, UpdateView, DetailView, FormView, CreateView, View from .forms import QuillFieldForm, QuillPostForm from .models import QuillPost __all__ = ( 'QuillPostListView', 'QuillPostCreateView', ...
python
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import Dict from fbpmp.pid.service.credential_service.cloud_credential_service import CloudCredentialServi...
python
''' 剑指 Offer 48. 最长不含重复字符的子字符串 请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。   示例 1: 输入: "abcabcbb" 输出: 3 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。 示例 2: 输入: "bbbbb" 输出: 1 解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。 示例 3: 输入: "pwwkew" 输出: 3 解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。   请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。   提示: s.length <= 4...
python
import dill as pickle import numpy as np f = open('pickle/point_circle_second_order_safety_layer_gaussian_l2_projection_radial_action_second_order_layer_with_buffer.p', 'rb') d = pickle.load(f) f.close() safety_layer, ppo = d.values() env = ppo.env lb, ub = env.action_space.low, env.action_space.high obs = env.reset(...
python
from bs4 import BeautifulSoup import requests def get_href_to_list(url): """ Get all the href elements of a URL to a list :param url: URL of the website to extract the href elements :return: list of href elements """ page = requests.get(url) soup = BeautifulSoup(page.content, 'html.parser'...
python
# from os import popen from pathlib import Path from qbay.models import * import subprocess # Set the current folder current_folder = Path(__file__).parent # Creating a user object for frontend testing # of create product functionality register("TestUser", "create_product_test@qbay.com", "Password99...
python
# -*- coding: utf-8 -*- def main(): from math import sqrt from itertools import combinations n = int(input()) xy = list() for i in range(n): xy.append(tuple(map(int, input().split()))) ans = 0 for point1, point2 in list(combinations(xy, 2)): dist = sqrt(...
python
# This code is part of Qiskit. # # (C) Copyright IBM 2021, 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivat...
python
from .activities import get_activities from .activity import get_activity from .upload import post_upload from .config import set_config from .login import login from .logout import logout from .profile import get_profile from .stats import get_stats
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # -*- encoding: utf-8 -*- # # Copyright (c) 2020 anqi.huang@outlook.com # # 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.apach...
python
import os def makeFilesMap(curr_dir): myMap = {} for root, dirs, files in os.walk(curr_dir, topdown=False): for name in files: if os.path.isfile(os.path.join(root, name)): #print(os.path.join(root, name), "with size:", os.path.getsize(os.path.join(root, name))) ...
python
#...................Drive a pressure/temperature sensor.................. #Author: James Bramante #Date: May 8, 2017 import ms5837 import threading import time import statistics as stats class SensorDriver(object): def __init__(self, samplerate = 100., density = 997., baseTime = 0.): """ Cons...
python
apiLoginId = "5KP3u95bQpv" transactionKey = "346HZ32z3fP4hTG2" transactionId = "60163892435" payerId = "LM6NCLZ5RAKBY" customerProfileId = "1929820324" customerPaymentProfileId = "1841987457" customerProfileShippingId = "901056173" amount = "12.23" subscriptionId = "326280" days = 34
python
"""template_filter_demo URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home'...
python
# # PySNMP MIB module ZYXEL-SFLOW-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZYXEL-SFLOW-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:45:40 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27...
python
# -*- coding: utf-8 -*- from __future__ import absolute_import def teardown_module(module): from nltk.corpus import wordnet wordnet._unload()
python
# Copyright 2013-2018 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) from spack import * class RIrdisplay(RPackage): """An interface to the rich display capabilities of Jupyter front-e...
python
"""Hermes MQTT server for Rhasspy ASR using Kaldi""" import gzip import logging import os import threading import typing from collections import defaultdict from dataclasses import dataclass, field from pathlib import Path from queue import Queue import networkx as nx import rhasspynlu from rhasspyasr import Transcrib...
python
# Copyright (c) 2013 Shotgun Software Inc. # # CONFIDENTIAL AND PROPRIETARY # # This work is provided "AS IS" and subject to the Shotgun Pipeline Toolkit # Source Code License included in this distribution package. See LICENSE. # By accessing, using, copying or modifying this work you indicate your # agreement to t...
python
import pandas as pd import os import skimage.io as skio from collections import OrderedDict from glob import glob from tqdm import tqdm import argparse def process_dir(input_dir, save_dir, campaign_name, species_filename=None, save_csv=True): # Find all lst files lst_filenames = sorted(glob(os.path.join(input...
python
"""XMPP/Jabber Client Interface and Support.""" # stdlib import inspect import os import re # Third Party import treq from twisted.web import client as webclient from pyiem.util import utc, LOG from twisted.internet import reactor from twisted.words.xish import domish, xpath from twisted.words.xish.xmlstream import ST...
python
width = input('Please enter width: ') price_width = 10 item_width = width - price_width header_format = '%-*s%*s' format = '%-*s%*.2f' print '=' * width print header_format % (item_width, 'Item', price_width, 'Price') print '-' * width print format % (item_width, 'Apples', price_width, 0.4) print format % (i...
python
import numpy as np import re def update_all_tags(closest_roi): if closest_roi['Shape_type'] == 'Rectangle': closest_roi['Tags']['Center tag'] = (int(closest_roi['topLeftX'] + closest_roi['width'] / 2), int(closest_roi['topLeftY'] + closest_roi['height'] / 2)) closest_roi['Tags']['Top left tag'] = (...
python
# ----------------------------------------------------------------------------- # Copyright (c) 2009-2016 Nicolas P. Rougier. All rights reserved. # Distributed under the (new) BSD License. # ----------------------------------------------------------------------------- # from . import glfw from . import freetype try: ...
python
from training.models.chromosome import Chromosome from training.models.neural_bird import NeuralBird from utils import generate_random_int_range, generate_random_range def test_generate_random_int_range(): result = generate_random_int_range(min_range=0, max_range=100) assert (0 <= result < 100) def test_gen...
python
import string str=string.ascii_letters #Prime Number def prime(p): if p==1: print('1 is a uniqe number') elif p%2==0: print('Not a Prime Number') elif p%2!=0: for i in range (3,int(p**0.5),2): if p%i==0: print('Not a Prime number') break else: print('Prime number found') #Factorial def fact(n...
python
"""Create an applet from a Python script. This puts up a dialog asking for a Python source file ('TEXT'). The output is a file with the same name but its ".py" suffix dropped. It is created by copying an applet template and then adding a 'PYC ' resource named __main__ containing the compiled, marshalled script. """ i...
python
import pytest from aiohttp_pydantic.oas.struct import OpenApiSpec3 def test_info_title(): oas = OpenApiSpec3() assert oas.info.title is None oas.info.title = "Info Title" assert oas.info.title == "Info Title" assert oas.spec == {"info": {"title": "Info Title"}, "openapi": "3.0.0"} def test_info...
python
# -*- coding: utf-8 -*- # Copyright (c) oct2py developers. # Distributed under the terms of the MIT License. from __future__ import absolute_import, print_function, division import inspect import dis import threading import numpy as np from scipy.io import loadmat, savemat from scipy.io.matlab.mio5 impor...
python
from __future__ import print_function import py, sys, subprocess currpath = py.path.local(__file__).dirpath() def setup_make(targetname): if sys.platform == 'win32': raise OSError("win32 not supported yet") popen = subprocess.Popen(["make", targetname], cwd=str(currpath), ...
python
"""Check if the PR has a news item. Put a warning comment if it doesn't. """ import os from github import Github, PullRequest from fnmatch import fnmatch def get_added_files(pr: PullRequest.PullRequest): for file in pr.get_files(): if file.status == "added": yield file.filename def check_ne...
python
import os import nn from general_ml import model_suite from nn.mlp import train as mlp from nn.sepCnn.train_sepcnn import train_sequence_model as sepcnn from nn.simple_lstm.train_lstm import lstm from load_data import * from predict import * current_path = os.getcwd() accounts_dir = os.path.join(current_path.split("sc...
python
from datetime import datetime, timedelta from typing import Optional from bson.objectid import ObjectId from fastapi import Depends, HTTPException, status from fastapi.security import OAuth2PasswordBearer from fastapi.security.oauth2 import OAuth2PasswordRequestForm from pydantic.networks import EmailStr from pymongo....
python
from random import shuffle import tensorflow as tf from xcenternet.datasets.dataset import Dataset class McodDataset(Dataset): def __init__(self, dataset_path_tr, dataset_path_te, init_lr): self.features = { TfExampleFields.height: tf.io.FixedLenFeature((), dtype=tf.int64, default_value=1), ...
python
""" Readout compress a graph into a vector """ from typing import List, Optional import tensorflow as tf from m3gnet.config import DataType from m3gnet.graph import Index from m3gnet.utils import ( get_segment_indices_from_n, register, unsorted_segment_fraction, unsorted_segment_softmax, ) from ._cor...
python
from PyQt6.QtCore import QRunnable, pyqtSlot, QObject, pyqtSignal from numpy import ndarray from src.hopfield_nn.hopfield import Hopfield class WorkerSignals(QObject): result = pyqtSignal(ndarray) class Worker(QRunnable): def __init__(self, network, image_data: ndarray, iterations: int = 100, threshold: f...
python
#!/usr/bin/env python2.7 import psycopg2 DATABASE_NAME = "news" def runquery(query): """ Takes a query as parameter, runs against the database and returns the results """ db = psycopg2.connect(database=DATABASE_NAME) cursor = db.cursor() cursor.execute(query) results = curso...
python
from tkinter import * from math import factorial, sqrt root = Tk() root.geometry('410x150') def is_perfect_square(n): return int(sqrt(n)) ** 2 == n def callback(): n = int(entry.get()) if is_perfect_square(n): result.config(text='{} is a perfect square {} = {} ^ {}'.format(n, n, int(sqrt(n)), 2))...
python
"""Module implementing GORU Cell. """ import tensorflow as tf import numpy as np from tensorflow.python.framework import ops from tensorflow.python.ops import init_ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import control_flow_ops from tensorflo...
python
import torch import logging.config device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') __version__ = "0.0.0" logging.config.dictConfig({ 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': '%(asctime)-15s %(message)s' }, ...
python
# -*- coding: utf-8 -*- # # Copyright (c) 2021-2022, Geoffrey M. Poore # All rights reserved. # # Licensed under the BSD 3-Clause License: # http://opensource.org/licenses/BSD-3-Clause # from __future__ import annotations import io import os import platform import sys from typing import Callable, Optional, TextIO ...
python
import unittest from pybind_class import PybindClass from pybind_writer import PybindWriter class TestPybindClass(unittest.TestCase): def test_context_manager(self): writer = PybindWriter() with PybindClass(writer): writer.write_line('test') self.assertEqual(writer.t...
python
import typing from creme import base __all__ = ['StackingClassifier'] class StackingClassifier(base.EnsembleMixin, base.Classifier): """Stacking for binary classification. Parameters: classifiers meta_classifier include_features: Indicates whether or not the original features shoul...
python
import collections import logging import discord log = logging.getLogger(__name__) recently_proxied_messages = collections.deque(maxlen=1) def new_proxied_message(oldmsg: discord.Message): """Add a proxy-causing message to the delete-log cleanup cache.""" global recently_proxied_messages recently_proxi...
python
from nexgddp.routes.api.v1.nexgddp_router import nexgddp_endpoints
python
#! /usr/bin/python3 # --*coding: utf-8*-- import requests import bs4 import csv # link to scrap: https://price.ua/catc839t14.html?price[min]=10000&price[max]=20000 def write_page_to_html(content): with open('index.html', 'w') as file: file.write(content) def get_laptops_list(response) -> list: s...
python
import paho.mqtt.client as mqtt import configparser import logging import json import paho.mqtt.client as mqtt class Messaging: def __init__(self, config, subscription = None, on_message = None, clientId = None): global on_connect self.config = config if (clientId): self.clien...
python
import logging import ply.lex as lex # # Set up a logging object # logging.basicConfig( # level=logging.DEBUG, # filename="parselog.txt", # filemode="w", # format="%(filename)10s:%(lineno)4d:%(message)s" # ) class LexToken(object): class LexTokenError(Exception): pass def __init__(self, debug...
python
import mimetypes import magic import requests from django.core.files.uploadedfile import SimpleUploadedFile from django.core.management.base import BaseCommand from contents.management.commands.crawler import get_url, get_item, get_page_url from contents.models import Contents, Category, Actor, Director class Comma...
python
""" Basic deployment script (for Gunicorn or similar tools) """ from newsic import create_app from werkzeug.middleware.proxy_fix import ProxyFix app = create_app() # http://flask.pocoo.org/docs/1.0/deploying/wsgi-standalone/#proxy-setups # fixes possible redirects to localhost:port app.wsgi_app = ProxyFix(app.wsgi_ap...
python
# -*- coding: utf-8 -*- import scrapy import microdata import json import re from urllib.parse import urlparse from claimreview.parser import ClaimReviewParser from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor class ClaimReviewSpider(CrawlSpider): name = 'claimreview' ...
python
# coding: utf-8 from __future__ import absolute_import, division, print_function, unicode_literals import attr from utils.feishu.dt_enum import PayBuyType, PayPricePlanType, PayStatus from utils.feishu.dt_help import to_json_decorator @to_json_decorator @attr.s class PayOrder(object): order_id = attr.ib(type=s...
python
#!/usr/bin/env python3 """ Central script to run the HTPC. """ import configparser import datetime import io import json import subprocess import syslog import requests class HtpcManager(object): """ Class used to manage power on and power off times for the HTPC. """ def __init__(self, username, pas...
python
# Copyright 2022 The TensorFlow 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 applica...
python
# ------------------------------------------------------------------------------ # Copyright (c) 2019 Parallax Inc. - # - # Permission is hereby granted, free of charge, to any person obtaining ...
python
ikan_bakar = 2567 orang = 190 ikanbakarperoraang =ikan_bakar/orang print("selamat anda mendapatkan", ikanbakarperoraang)
python
''' Review function to evaluate if message conatains a valid namespace ''' def HasValidNamespace(reviewer,message): ns = message.NameSpace if ns in reviewer.env._socketIONamespaces: return True else: return False
python
def roundRobin(units, sets=None): """ Generates a schedule of "fair" pairings from a list of units """ if len(units) % 2: units.append(None) count = len(units) sets = sets or (count - 1) half = count / 2 schedule = [] for turn in range(sets): pairings = [] ...
python
from datetime import datetime from django.contrib.auth.decorators import login_required from django.db.models import Q from django.shortcuts import render # Create your views here. from common.access_decorators_mixins import sales_access_required from .models import Listing @login_required @sales_access_required def...
python
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: alter_word_index.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.pro...
python
import logging; logger = logging.getLogger("morse."+ __name__) import roslib, rospy from morse_helpers import adapters from morse.core.blenderapi import mathutils from morse.core.services import interruptible from morse.core.exceptions import MorseServiceError from morse_msgs.srv import PlaceIkTarget from morse_msgs....
python
class BitQueryLookupWrapper(object): def __init__(self, alias, column, bit): self.table_alias = alias self.column = column self.bit = bit def as_sql(self, qn, connection=None): """ Create the proper SQL fragment. This inserts something like "(T0.flags & value) !=...
python
import tensorflow as tf from graphsaint.tensorflow_version.inits import glorot,zeros,trained,ones,xavier,uniform from graphsaint.globals import * F_ACT = {'I': lambda x:x, 'relu': tf.nn.relu, 'leaky_relu': tf.nn.leaky_relu} # global unique layer ID dictionary for layer name assignment _LAYER_UIDS =...
python
# -*- coding: utf-8 -*- """Chemical Engineering Design Library (ChEDL). Utilities for process modeling. Copyright (C) 2016, 2017, 2018, 2019, 2020 Caleb Bell <Caleb.Andrew.Bell@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (t...
python
"""Describe what tasks this Process accomplishes.""" # Order of imported packages should be: # Standard libraries from pathlib import Path from shutil import copy2 # Third party libraries from plumbum import TEE # Resolwe from resolwe.process import ( Process, SchedulingClass, Persistence, Cmd, St...
python
"""Test converter classes.""" class Bar(object): def __init__(self, **kwargs): self.kwargs = kwargs def __call__(self, value, request, *args, **kwargs): return 'bar'
python
from googletrans import Translator detector = Translator(service_urls=['translate.googleapis.com']) string = 'ODEIO' # 'Porr Fmu eu te odeio, enfia essas aulas "híbridas" presenciais no seu c*...na moral EU NÃO POSSO IR PQ AGR MORO EM… https://t.co/42Cdld2fDX' frase2 =detector.translate(string,dest='en') dec_lan = d...
python
from tkinter import * import tkinter as tk from tkinter import filedialog from tkinter.filedialog import askopenfilename, asksaveasfilename import re import sys import os.path filename = "Output" fileexists = False root = tk.Tk() def asmtoint(asm): import re asm_split = re.split(" |, |\(|\)", asm) args...
python
from os import getenv from flask import Flask import boto3 import botocore import json app = Flask(__name__) @app.route('/') def call_lambda(): try: lambda_client = boto3.client('lambda', endpoint_url="http://host.docker.internal:3001", ...
python
""" :author: Maikel Punie <maikel.punie@gmail.com> """ import velbus COMMAND_CODE = 0xe4 class SetTemperatureMessage(velbus.Message): """ send by: VMB4RYLD received by: VMB6IN """ def __init__(self, address=None): velbus.Message.__init__(self) self.temp_type = 0x00 self.t...
python
"""Main module.""" import json from collections import defaultdict import numpy as np import pandas as pd from copy import deepcopy from math import nan, isnan from .constants import IMAGING_PARAMS DIRECT_IMAGING_PARAMS = IMAGING_PARAMS - set(["NSliceTimes"]) def check_merging_operations(action_csv, raise_on_error=Fa...
python
import sys from functools import reduce raw = sys.stdin.read() rawpoints, rawfolds = raw.split('\n\n') points = set((int(p.split(',')[0]), int(p.split(',')[1])) for p in rawpoints.split('\n')) folds = [ (f.split('=')[0][-1], int(f.split('=')[1])) for f in rawfolds.strip().split('\n') ] def applyFold(points, fold)...
python
class DictObjectProxy: def __init__(self, obj={}): super().__setattr__("obj",obj) def __getattr__(self, name): if not name in super().__getattribute__("obj"): raise AttributeError return super().__getattribute__("obj")[name] def __setattr__(self, key, value): s...
python
from peewee import * #import sqlite3 baseD = SqliteDatabase('LIBRERIA.db') class AUTOR(Model): ID_AUTOR = PrimaryKeyField(null=False) NOMBRE = TextField() APELLIDO = TextField() class Meta: database = baseD # This model uses the "LIBRERIA.db" database. def __str__(self):...
python
# Copyright 2021 ZBW – Leibniz Information Centre for Economics # # 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 b...
python
import pytest import unittest from sgnlp.models.ufd import ( UFDAdaptorDomainModel, UFDAdaptorGlobalModel, UFDCombineFeaturesMapModel, UFDClassifierModel, UFDModelBuilder, UFDModel ) class TestUFDModelBuilderTestCase(unittest.TestCase): def setUp(self) -> None: self.model_map = { ...
python
import unittest import sys import os sys.path.append('../') import torch import torch.nn as nn from torchlib import models as md class TestModel( unittest.TestCase ): def test_model_resnet( self ): num_channels=1 num_classes=10 imsize=64 net = md.resnet18( False, num_class...
python
import itertools class Solution(object): def matrixReshape(self, nums, r, c): l = len(nums) * len(nums[0]) if l != r * c: return nums it = itertools.chain(*nums) return [list(itertools.islice(it, 0, c)) for i in xrange(0, l, c)]
python
# This is just a simple recursion implementation of the problem. def maximum_profit(price, start, end): if end <= start: return 0 profit = 0 for i in range(start, end): for j in range(i + 1, end + 1): if price[j] > price[i]: curr_profit = price[j] - price[i] + ...
python
# 1. new_cut_dataset, num_train_epochs, deixar a correr com dataset grande, lstm com dw=3 # 1. deixar a correr com dataset grande, lstm só com dw=1 # 1. deixar a correr com dataset grande, lstm com média ponderada import random import torch import numpy as np #from datetime import timedelta #import pandas as pd #from...
python
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-02-16 00:50 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('grapher_admin', '0031_auto_20180216_0021'), ] operations = [ migrations.RemoveField( ...
python
import datetime import unittest from airflow.models import DAG, DagRun, TaskInstance as TI from airflow.operators.dummy import DummyOperator from airflow.utils import timezone from airflow.utils.session import create_session from airflow.utils.state import State from gcp_airflow_foundations.operators.branch.branch_on...
python
from mpl_toolkits.axes_grid1 import make_axes_locatable import numpy as np import matplotlib.pyplot as plt import os from scipy.interpolate import interp1d from mpl_toolkits.basemap import Basemap periods = np.array([8,10,12,14,16,18,20,22,24,26,28,30,32,35,40,45,50]) depth = np.array([0,3,10,15,20,30,40,60,80,100,120...
python
# -*- coding: utf-8 -*- """ Demonstrate how to synchronize 2 or more MFLI instruments or 2 or more UHFLI instruments using the MDS capability of LabOne. It also measures the temporal response of demodulator filters of both both instruments using the Data Acquisition (DAQ) Module. Copyright 2008-2018 Zurich Instruments...
python