content stringlengths 5 1.05M |
|---|
from typing import Any, Dict, Iterable, Optional
from django.http import HttpRequest, HttpResponse
from django.utils.translation import ugettext as _
from zerver.decorator import webhook_view
from zerver.lib.webhooks.common import check_send_webhook_message
from zerver.lib.request import REQ, has_request_variables
fr... |
# coding: utf-8
"""
Gitea API.
This documentation describes the Gitea API. # noqa: E501
OpenAPI spec version: 1.1.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility libra... |
# coding=utf8
# Copyright 2018 JDCLOUD.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.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... |
from collections import defaultdict
# Ordered List of Coin Symbol Dictionaries
COIN_SYMBOL_ODICT_LIST = [
{
'coin_symbol': 'btc',
'display_name': 'Bitcoin',
'display_shortname': 'BTC',
'blockcypher_code': 'btc',
'blockcypher_network': 'main',
... |
#
# PySNMP MIB module SCC-ENTERPRISE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SCC-ENTERPRISE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:53:04 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... |
from django.http import HttpResponse
from _internalredirect import _convert_file_to_url
def sendfile(request, filename, **kwargs):
response = HttpResponse()
url = _convert_file_to_url(filename)
response['X-Accel-Redirect'] = url.encode('utf-8')
return response
|
"ESGF modules"
__version__ = '0.1.1'
|
import os
from HSTB.shared import path_to_NOAA, path_to_root_env, path_to_conda, path_to_supplementals
def is_pydro():
"""
Quick check to see if kluster is being run from Pydro. If so, the paths we build in this module will be valid.
Returns
-------
True if this environment is within Pydroxl
... |
from pyodide_build.testing import run_in_pyodide
@run_in_pyodide(packages=["sqlalchemy"])
def test_sqlalchemy():
from sqlalchemy import create_engine, text
engine = create_engine("sqlite+pysqlite:///:memory:", future=True)
with engine.connect() as conn:
result = conn.execute(text("select 'hello w... |
from six import add_metaclass
from six.moves import zip
from . import path, safe_str
from .iterutils import isiterable, iterate
from .file_types import *
from .platforms.framework import Framework
class option_list(object):
def __init__(self, *args):
self._options = []
self.collect(*args)
de... |
# Allows one to plot many data points with many different customizations (marker size, color, legend label etc),
# without writing code. Instead the customizations are specified by the input spreadsheets, in which each row is
# a data point (run code without inputs for instructions). Documentation and variable names as... |
import os
import argparse
import numpy as npy
try:
import cupy as np
except ImportError:
import numpy as np
print("GPU not enabled on this machine.")
from vae.models.vae_model import VAE
from vae.utils.functionals import load_mnist, BCE
def parse_args():
parser = argparse.ArgumentParser()
parser.... |
import traceback
from re import match
class DataMixin():
def type_validate(self, fields_type):
result = {}
if not fields_type:
return
for key, value in fields_type.items():
if type(key) != value:
result.update({key: False})
else:
... |
#!/usr/bin/python
# Copyright 2012 Google Inc. 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 applic... |
"""
Week 7 - Activity: Classes
---------
AUTHOR: Edward Camp
"""
from Week7.Animal import Animal
'''
Up until now, we've been coding away within either methods or 'activity' python files to accomplish tasks and finish
projects. However, a lot of the based code provided and methods you've tasked to code in h... |
#
# @lc app=leetcode id=263 lang=python3
#
# [263] Ugly Number
#
# @lc code=start
class Solution:
def isUgly(self, num: int) -> bool:
if num < 0: return False
if num == 1: return True
ugly_prime = (2,3,5)
if num in ugly_prime: return True
while(num):
if int(num ... |
def maxsumseq(sequence):
start, end, sum_start = -1, -1, -1
maxsum_, sum_ = 0, 0
for i, x in enumerate(sequence):
sum_ += x
if maxsum_ < sum_: # found maximal subsequence so far
maxsum_ = sum_
start, end = sum_start, i
elif sum_ < 0: # start new sequence
... |
"""
Datos de entrada
billestes de 50k-->cin-->int
billetes de 20k-->vei-->int
billetes de 10k-->die-->int
billetes de 5k-->cin-->int
billetes de 2k-->dos-->int
billetes de 1k-->uno-->int
billetes de 500-->qui-->int
billetes de 100-->cie-->int
Datos de salida
Total de 50k-->Tc-->int
Total de 20k-->Tv-->int
Total de 10k-... |
from elasticizer.pipelines import *
|
# optimizer
optimizer = dict(type='SGD', lr=0.1, momentum=0.9, weight_decay=0.0001)
optimizer_config = dict(grad_clip=None)
# learning policy
runner = dict(type='EpochBasedRunner', max_epochs=200)
lr_config = dict(
policy='CosineAnnealing',
min_lr=0,
warmup='exp',
warmup_iters=5,
warmup_ratio=0.1,... |
# Copyright 2021 Touca, Inc. Subject to Apache-2.0 License.
from conans import ConanFile, CMake
class ToucaConan(ConanFile):
name = "touca"
homepage = "https://touca.io"
description = "client library for regression testing arbitrary execution workflows"
topics = ( "regression-testing", "test-framewor... |
from flask import Blueprint
from database import Database
import json
from flask import request
api = Blueprint('api', __name__, template_folder='templates')
@api.route('/entries', methods=["GET"])
def get_all_entries():
entries = Database.get_records()
for entry in entries:
entry['_id'] = str(entry['... |
from __future__ import print_function
import io
import sys
import os.path
from setuptools import setup, find_packages
readme_path = os.path.join(os.path.dirname(__file__), 'README.rst')
changelog_path = os.path.join(os.path.dirname(__file__), 'CHANGELOG')
readme = io.open(readme_path, encoding='utf-8').read()
change... |
from pytest import fixture
from ..step_multimodal import StepMultimodal
__SAMPLES = [
([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 0),
]
@fixture
def step_multimodal() -> StepMultimodal:
return StepMultimodal(blocks=[5, 5], step_size=0.1)
def test_samples(step_multimodal: StepMultimodal, helpers):
helpers.check_s... |
import argparse
from typing import Any, Dict
import torch
import torch.nn as nn
import torchvision
PRETRAINED = True
NUM_CLASSES = 5
DROPOUT = False
DROPOUT_PROB = 0.5
DROPOUT_HIDDEN_DIM = 512
class RGBResnetClassifier(nn.Module):
"""Classify an image of arbitrary size through a (pretrained) ResNet network"""
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Functions used by dax_tools like in dax_upload/dax_test/dax_setup.
"""
from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from builtins import filter
from builtins import input
from builtins import str
from bu... |
"""Test cases for representations."""
import numpy as np
import muspy
from .utils import TEST_JSON_PATH
def test_note_representation():
music = muspy.load(TEST_JSON_PATH)
# Encoding
encoded = muspy.to_representation(music, "note")
assert encoded.shape == (9, 4)
assert encoded.dtype == int
... |
import io
import sys
from collections import deque
from conscodec import ConsCodec
from pathlib import Path
def PARSE_NUMBER(s):
try:
return int(s)
except TypeError as e:
print(repr(s), e, file=sys.stderr)
return 0
def PARSE_FUNCTIONS(fn):
def parse_ast(tokens):
stream = ... |
# mnist_runner.py
#
# Author : James Mnatzaganian
# Contact : http://techtorials.me
# Organization : NanoComputing Research Lab - Rochester Institute of
# Technology
# Website : https://www.rit.edu/kgcoe/nanolab/
# Date Created : 12/05/15
#
# Description : SLURM runner for MNIST.... |
import gc
import random
from pathlib import Path
import numpy as np
import pandas as pd
import wandb
from annoy import AnnoyIndex
from more_itertools import chunked
from scipy.spatial.distance import cdist
from sklearn.neighbors import NearestNeighbors
from tensorflow.keras.callbacks import EarlyStopping
from tree im... |
import tkinter.messagebox as msgbox
import tkinter.ttk as ttk
from tkinter import*
root=Tk()
root.title('Molecular Work Tool')
root.geometry("1150x600+100+50")
Label(root, text='안녕하세요 교수님!').grid(row=0,column=2)
wframe=LabelFrame(root, text='어떤 작업을 하실 생각이신가요?')
wframe.grid(row=1, column=0)
fframe=LabelFr... |
# -*- coding: utf-8 -*-
"""
/dms/lecture/views_show_complete.py
.. zeigt den Inhalt eines Ordners an
Django content Management System
Hans Rauch
hans.rauch@gmx.net
Die Programme des dms-Systems koennen frei genutzt und den spezifischen
Beduerfnissen entsprechend angepasst werden.
0.01 28.01.2007 Beginn d... |
# -*- coding: utf-8 -*-
import base64
import json
import sys
import time
import warnings
from concurrent.futures import ThreadPoolExecutor, wait, as_completed
from operator import itemgetter
import dlib
import cv2
import os
import glob
import numpy as np
from iface import IFace
class FaceDlib(IFace):
def __ini... |
# Importing Libraries
import serial
import time
import cv2 as cv
def open_cr(key):
opencr.write(bytes(key, 'utf-8'))
value = opencr.readline()
time.sleep(0.5)
def key_push() :
panel = cv.imread('mcu_arduino/hyunjoowhoon/Turtlebot3_logo.jpg')
cv.imshow('arduino control', panel)
while... |
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.generic import ListView, DetailView, CreateView, FormView
from django.urls import reverse_lazy
from django.db import transaction
from .forms import PostForm, SubscriptionForm, UnSubscription... |
from common import unittest2
import pyuv
class MultiHandleTest(unittest2.TestCase):
def test_multihandle1(self):
self.close_cb_called = 0
self.prepare_cb_called = 0
def close_cb(handle):
self.close_cb_called += 1
def prepare_cb(prepare):
self.prepare_cb_ca... |
from threading import Lock
import pygame
from config import Config
from pygame.threads import Thread
import math, random
class PhysicsController(object):
def __init__(self, config, ballsList):
self.config = config
self.threadList = []
self.lock = Lock()
self.ballsList = ballsList... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import subprocess
import pwndbg.commands
import pwndbg.which
@pwndbg.commands.Command
@pwndbg.commands.OnlyWithFile
def c... |
'''
Parsing - Exercise 6
The script reads a multiple sequence regord FASTA file and
writes the sequences to a new file separated by a blank line.
'''
fasta = open('sprot_prot.fasta')
seqs = open('seqs.txt', 'w')
for line in fasta:
if line[0] == '>':
seqs.write('\n')
elif line[0] != '>':
seqs.write(line.strip... |
"""Photometer
These functions handle data files from spectrophotometers for easy and direct import
The functions are:
* uprtek_import_spectrum - Imports the spectrum from a UPRtek spectrophotometer
* uprtek_import_r_vals - Imports the R values generated by a UPRtek spectrophotometer
* uprtek_file_import ... |
#!/usr/bin/env vpython3
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Unit tests for presubmit_support.py and presubmit_canned_checks.py."""
# pylint: disable=no-member,E1103
from __future__ imp... |
import datetime
import urllib.request
import math
months = ['January', 'July']
def urlrange(year):
minyr = math.floor(year / 10) * 10
maxyr = minyr + 9
return(f"{minyr}-{maxyr}")
for year in range(1970, 2018):
for month in months:
filename = f"{month}{year}.pdf"
url = f"https://workforcesecurity.doleta.... |
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 3.0.12
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info as _swig_python_version_info
if _swig_python_version_info >= (2, 7, 0):
def swig_im... |
from datetime import datetime
from scrapy import log
from twisted.enterprise import adbapi
class ItemProcessPipeline:
def process_item(self, item, spider):
# parse year
item["year"] = datetime.strptime(item["custom"]["date"], "%Y-%m-%dT%H:%M:%S").year
# parse genres
if item.get(... |
#
# ----------------------------------------------------------------------------------------------------
# DESCRIPTION
# ----------------------------------------------------------------------------------------------------
#
# --------------------------------------------------------------------------------------------... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class ScrapyBookingItem(scrapy.Item):
# define the fields for your item here like:
name = scrapy.Field()
hotel_id = scrapy.Field()
ratin... |
from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread
clientes= {}
address = {}
HOST = ''
PORT = 3000
BUFSIZE = 1024
ADDR = (HOST, PORT)
SERVER = socket(AF_INET, SOCK_STREAM)
SERVER.bind(ADDR)
def aceitar_clientes():
while True:
client , client_addr = SERVER... |
"""
@Author : sean cheng
@Email : aya234@163.com
@CreateTime : 2019/6/30
@Program : 绘制游戏界面的模块
"""
import pygame
from gobang.init_var import init_var
setting = init_var()
def draw_chess(screen, chess_color, posx, posy):
# 绘制棋子,传入的参数包括棋子的颜色和位置
pygame.draw.circle(screen, chess_color, (posx, ... |
import unittest
from scrapers.journalscrapers import HindawiScraper
class TestJournalScraper(unittest.TestCase):
def setUp(self):
self.instance = HindawiScraper("http://www.hindawi.com/apc/")
def test_strip_chars(self):
for row in self.instance.get_entries():
print row |
#!/bin/env python
# -*- coding: utf8 -*-
from setuptools import setup, find_packages
setup(
name='unicards',
version='0.6',
description="Convert strings into unicode playing cards",
author='Luke Macken',
author_email='lmacken@redhat.com',
url='http://github.com/lmacken/unicards',
license='A... |
"""Style handling for QuteStyleWindow."""
import logging
from typing import Dict, Optional
from PyQt5.QtCore import QRect, QSettings, QSize
from PyQt5.QtGui import QColor, QPainter, QPixmap
log = logging.getLogger(
f"qute_style.{__name__}"
) # pylint: disable=invalid-name
# Use this variable when referencing a... |
import add_module
print(add_module.add(100, 200))
# 300
|
# coding: utf-8
# flake8: noqa
"""
ARC contrib functionality.
"""
__all__ = ["ARCJobManager", "ARCJobFileFactory", "ARCWorkflow"]
# provisioning imports
from law.contrib.arc.job import ARCJobManager, ARCJobFileFactory
from law.contrib.arc.workflow import ARCWorkflow
|
from unittest.mock import patch
from django.test import TestCase
from accounts.models import School
from accounts.update_schools import update_all_schools
@patch("accounts.update_schools.requests.get")
class UpdateMajorsTestCase(TestCase):
def testTotalSchoolCount(self, mock_source_file):
with open(r"./... |
import urllib.parse
from datetime import date
from datetime import datetime
import numpy as np
import ocflib.printing.quota as quota
from django.http import HttpResponse
from django.shortcuts import redirect
from django.urls import reverse
from matplotlib.figure import Figure
from matplotlib.ticker import MaxNLocator
... |
import pytest
from pathlib import Path
examples_path = Path(__file__).parent / 'examples'
@pytest.fixture
def example():
return lambda p: open(examples_path / p).read() |
# Generated by Django 2.0.4 on 2018-04-12 09:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('workouts', '0005_session_session_slug'),
]
operations = [
migrations.AlterField(
model_name='session',
name='created... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 23 07:58:27 2021
@author: daniel
"""
import numpy as np
import fmatrices as fm
n = int(input("¿tamaño de la matriz? "))
cuadro = fm.cuadromag1(n)
fm.escribirmat(cuadro)
print (type(cuadro))
try:
np.savetxt('cuadro.txt',cuadro)
except:
... |
import urllib
import urllib.request
print(type(urllib))
print(type(urllib.request))
|
"""
copyright 2020 kartik sharma, saurabh saxena
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 ... |
import os
import json
import pickle
import numpy as np
import scipy as sp
import scipy.stats as stats
import matplotlib.pyplot as plt
import seaborn as sns
from eval.eval_bm25_coliee2021 import read_label_file #ranking_eval
from retrieval.bm25_aggregate_paragraphs import sort_write_trec_output
from preprocess... |
from django.shortcuts import render, redirect
from django.utils.timezone import now
from .models import (
GreensRolling,
TeeRolling,
FairwayRolling
)
from .forms import (
GreensRollingForm,
TeeRollingForm,
FairwayRollingForm
)
def curr_time():
return now()
def greensIndex(request):
r... |
class LED_64_4_D1:
keySize = 64
keySizeConst0 = (keySize >> 4)
keySizeConst1 = (0x01 ^ (keySize >> 4))
keySizeConst2 = (0x02 ^ (keySize & 0x0F))
keySizeConst3 = (0x03 ^ (keySize & 0x0F))
sBoxInv = [0x05, 0x0E, 0x0F, 0x08, 0x0C, 0x01, 0x02, 0x0D, 0x0B, 0x04, 0x06, 0x03, 0x00, 0x07, 0x09, ... |
import numpy as np
import os
from spektral.data import Dataset, Graph
import tensorflow as tf
import glob
from tensorflow import keras
import json
## MyDataSet not used anywhere
class MyDataset(Dataset):
"""
Turn swarm into a graph
"""
def __init__(self, nodes, feats, **kwargs):
s... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.28 on 2020-10-17 15:40
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('notifications', '0002__'),
]
operations = [
migrations.AddField(
... |
import json
import os
from ..util.exceptions import PypactSpectrumDoesNotExistException
_this_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)))
__SPECTRUM_JSON_LIB_FILE__ = os.path.join(
_this_dir, 'data', 'spectrumlib.min.json')
class SpectrumLibJSONReader:
def __init__(self, filename=__SPEC... |
"""
@version 0.1
@contant QQ597806630
@author zc
@desc 本项目淘宝抢购
@date 2020/12/04
说明:
classes: Mes()
function:
"""
import pyautogui
import time
from selenium import webdriver
import sys
from PyQt5.QtCore import QThread,pyqtSignal,Qt
from PyQt5.QtWidgets import QApplication,QFileDialog, QMainWindow,QMessageBox,QCheckBox,... |
import numpy as np
import math
from copy import copy
from typing import List
import subprocess
def write_cfgs_from_otf(otf_run, cell, species, start_frame, no_frames,
folder_name, image_quality, scr_dest, trans_vec,
skip=1):
# make folder for cfgs
subprocess.ca... |
# -*- coding:utf-8 -*-
from __future__ import unicode_literals
from django.contrib.sites.managers import CurrentSiteManager
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
@python_2_unicode_compatible
class BaseEntry(... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** 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 _utilities
__... |
import logging
logger = logging.getLogger(__name__)
from mqfactory.message import Message
class Store(object):
def __getitem__(self, key):
raise NotImplementedError("implement get collection from the store")
class Collection(object):
def load(self):
raise NotImplementedError("implement loading the colle... |
from output.models.ms_data.datatypes.facets.idrefs.idrefs_enumeration002_xsd.idrefs_enumeration002 import (
Foo,
FooType,
FooIdrefsAttr,
Test,
)
__all__ = [
"Foo",
"FooType",
"FooIdrefsAttr",
"Test",
]
|
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
# Copyright © 2016, Continuum Analytics, Inc. All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
# -------------------------------------------------------------------... |
import sys
import datetime
from pathlib import Path
current_path = Path(__file__).absolute()
abs_path = str(current_path.parent.parent)
sys.path.append(abs_path)
from capture import Capture
def from_api_to_db_deputados(data_list, url, capture_number):
func = lambda datum: dict(
ide_cadastro= dat... |
import time
import tensorflow as tf
import tensorlayer as tl
from tensorlayer.layers import *
def SRGAN_g(t_image, is_train=False, reuse=False):
""" Generator in Photo-Realistic Single Image Super-Resolution Using a Generative Adversarial Network
feature maps (n) and stride (s) feature maps (n) and stride (s)... |
from asynceth.jsonrpc.client import JsonRPCClient
__all__ = ['JsonRPCClient']
|
import sys
sys.path.insert(0, '../../')
import pyrosim
# toggle joint drawing by pressing 'd'
sim = pyrosim.Simulator(eval_steps=-1, play_paused=True)
cyl = sim.send_cylinder(position=(0.25, 0, 1),
orientation=(1, 0, 0),
length=0.5)
sphere = sim.send_sphere(position=(0.... |
#appending and extending lists in python
list_odd=[1,3,5,7,9]
'''
list_odd[5]=11
print(list_odd)
--> this will run into an error as the index gets out of the range for the specified length of a list
INorder to overcome this erros, one needs to use append() function - in-built function
'''
list_odd.append(11)
list_odd... |
# Copyright 2015 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... |
import os
import numpy as np
# Writes particles and error scalars for best, median, and worst
# pred_particles and true_particles are numpy array with dims: # in set, # of particles, 3 coordinates
def write_examples(pred_particles, true_particles, out_dir):
if not os.path.exists(out_dir):
os.makedirs(out_dir)
# g... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from argparse import ArgumentParser
import os
import re
import sys
import unicodedata
import yaml
# Local files
import cfg
import jiralogin
from helper import vprint, eprint
################################################################################
# Class node
#... |
# -*- coding: utf-8 -*-
"""
Пример использования модуля расчета параметров воздушных линий PVL в соответствии с
Руководящими указаниями по релейной защите № 11 Расчеты токов короткого
замыкания для релейной защиты и системной автоматики 110-750 кВ
г.Саратов 24.11.2020г.
"""
#import numpy as np
import PVL... |
# A linear-time BFS-based solution.
from collections import deque
def bfs(rate_graph, start, end):
to_visit = deque()
to_visit.appendleft( (start, 1.0) )
visited = set()
while to_visit:
node, rate_from_origin = to_visit.pop()
if node == end:
return rate_from_origin
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import pandas as pd
from EMNaiveBayes import EMNaiveBayes
def main():
data_fn = 'data/Soybean/soybean-large.data.txt'
col_idx_of_y = 0
# Read data with dtype = str.
X = pd.read... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
import PostEstimation_pb2 as PostEstimation__pb2
class PostEstimationServiceStub(object):
# missing associated documentation comment in .proto file
pass
def __init__(self, channel):
"""Constructor.
Args:
channel: ... |
from .multiclass_classification import MultiClassClassificationDataset
LABELS = [
"AnnualCrop",
"Forest",
"HerbaceousVegetation",
"Highway",
"Industrial",
"Pasture",
"PermanentCrop",
"Residential",
"River",
"SeaLake",
]
class EurosatDataset(MultiClassClassificationDataset):
... |
from torch.utils.data import DataLoader
class BaseDataLoader(DataLoader):
def split_validation(self) -> DataLoader:
return NotImplementedError
|
class BinaryTree:
def __init__(self):
self.root = None
def find(self, key: int) -> bool:
if not self.root:
return False
current = self.root
while current.key != key:
if current.key < key:
current = current.right
else:
... |
from collections import defaultdict
import os
from pathlib import Path
import joblib
import numpy as np
import pandas as pd
import torch
from .transforms.util import get_transforms
from .engine.voc_assayer import VOCAssayer
from .datasets import VOCDetection
from .utils.general import make_save_path
def assay(csv_f... |
number = int(input("Podaj cyfrę: "))
divisors_list = []
if number == 0:
print("Podzielnikami liczby 0 są wszystkie liczby rzeczywiste z wyłączeniem 0")
else:
original = number
number = abs(number)
for i in range((int(number / 2)) + 1):
if i == 0:
pass
elif number % i == 0:
... |
"""Custom OpenAPI schema."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Callable
from fastapi.openapi import docs, utils
import imagesecrets
from imagesecrets.api.dependencies import get_config
if TYPE_CHECKING:
from fastapi import FastAPI
from fastapi.responses import HTMLRes... |
# Generated by Django 2.1.7 on 2019-02-17 17:44
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('images_backend', '0002_auto_20190217_1555'),
]
operations = [
migrations.RenameModel(
old_name='InstanceValues',
new_name='I... |
# -*- coding: utf-8 -*-
# Generate QR Code of any type.
# It's based on PyQRCode Library.
import pyqrcode
qr=pyqrcode.create('QrCode Generator')
qr.png('generator.png', scale=10)
|
# coding: utf-8
import os
import sys
import time
import pytest
import easytrader
sys.path.append(".")
class TestThsClientTrader:
@pytest.fixture
def user(self):
_user = easytrader.use("ths")
# _user.prepare(
# user="31016658", password= "211122", comm_password="211122"
# )... |
from simobject import SimObject
class Robot(SimObject):
"""The robot is a :class:`~simobject.SimObject` that implements drawing
and information functions to interface with supervisor.
This class is not intended to be subclassed in user code. Use one
of the provided subclasses instead: ... |
############# Credits and version info #############
# Definition generated from Assembly XML tag def
# Date generated: 2018/12/03 04:56
#
# revision: 1 author: Assembly
# Generated plugin from scratch.
# revision: 2 author: -DeToX-
# Fixed some Reflexives..
# revision: 3 author: -DeToX-
# Named some v... |
import argparse
import logging
from py4gh.utility import decrypt_files, encrypt_files, get_files, process_output
def cli_parser() -> None:
parser = argparse.ArgumentParser(
description="Decrypt/Encrypt files in root dir and sub dir using crypt4gh"
)
parser.add_argument(
"--filepath",
... |
"""
TrexGUIZ0Plan.py - Services for importing data to the thesarus and GUI.
Using this thesarus a producer or consumer can locate a common field to process.
It can, with a few appropriate changes, connect to anyEnv Uci driven.
It knows about ArchEdenZ0Plan Uci so covers much of the processing.
*Trex is short for Trex... |
import sys
import apple
from PyQt4.QtGui import QApplication, QMainWindow
if __name__ == '__main__':
app = QApplication(sys.argv)
MainWindow = QMainWindow()
ui = apple.Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
|
# In Initialize
self.AddForex("EURUSD", Resolution.Minute) # or
self.AddForex("EURUSD", Resolution.Minute, Market.FXCM)
# For OANDA, we need to explictly define the market
self.AddForex("EURUSD", Resolution.Minute, Market.Oanda) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.