content stringlengths 5 1.05M |
|---|
from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
res = []
if root is None:
return res
self.__helper(root, ... |
from .fontconfig import has_fontconfig, query_fontconfig_database
__all__ = ['find_font', 'query_fontconfig_database']
if not has_fontconfig():
raise OSError(
'This module currently only supports systems using "fontconfig"'
)
def find_font(name, **kwargs):
try:
return query_fontconfig_da... |
import os
from dotenv import load_dotenv
import openai
load_dotenv()
openai.organization = "org-D2FBgBhwLFkKAOsgtSp86b4i"
openai.api_key = os.getenv("OPENAI_API_KEY")
remote_files = openai.File.list()["data"]
training_files = filter(lambda f: "answers.jsonl" in f["filename"], remote_files)
latest_file = max(training... |
from graphene import ID, String, ObjectType, List, NonNull
from .company import Company
from btb.api.schema.resolvers import companies_by_principal
class User(ObjectType):
id = ID(required=True)
external_id = ID(required=True)
email = String(required=True)
"""Deprecated"""
name = String(required=... |
#!/usr/bin/env python3
import json
import os
import shutil
import zipfile
from os.path import join
import init
from utils import file_utils
from utils import process_utils
VERSION_FILE = 'version.txt'
BUILD_FOLDER = 'build'
class BuildInfo():
def __init__(self):
self.files = set()
def include(sel... |
""" train.py """
import argparse
from utils.load import load_yaml
from model import get_model
def parser():
parser = argparse.ArgumentParser('Classification Argument')
parser.add_argument('--configfile', type=str, default='./configs/default.yml', help='config file')
parser.add_argument('--eval', action='s... |
from django.http.response import Http404
from django.shortcuts import render,HttpResponse
import pickle
import pandas as pd
import sklearn
# Create your views here.
def home(request):
return render(request, 'home.html')
def predict(request):
with open("static/india_home_price_prediction.pickle", 'rb') as... |
# -*- encoding: utf-8 -*-
# Module iadist
from numpy import *
from ia870.iasecross import iasecross
def iadist(f, Bc=iasecross(), METRIC=None):
from iagray import iagray
from iaintersec import iaintersec
from iaisequal import iaisequal
from iaero import iaero
from iasebox import iasebox
if ME... |
import logging
import re
from typing import List, Optional
from pydantic import BaseModel, validator
from .meta.pydanticbase import PydanticBase
logger = logging.getLogger(__name__)
# Matching 00p in currency
CURRENCY_PENCE_REGEX = re.compile(r"(\d{2})[p]")
# Matches any whitespace characters and £ symbol
CURRENCY... |
from bottle import Bottle, route, run, request, response, abort, error, redirect
from rdflib import ConjunctiveGraph, URIRef
from pyld import jsonld
from pyld.jsonld import compact, expand, frame, from_rdf, to_rdf, JsonLdProcessor
import json
import codecs
import sys
import requests
import os
from cromulent.model ... |
from typing import List
import requests, json
from guet.steps.action import Action
class RemoveCommitterAction(Action):
def __init__(self, committers):
super().__init__()
self.committers = committers
def execute(self, args: List[str]):
committer = self.committers.by_initials(args[0])
... |
from __future__ import division
import math
import LLRcalc
class SPRT:
"""
This class performs a GSPRT for H0:elo=elo0 versus H1:elo=elo1
See here for a description of the GSPRT as well as theoretical
(asymptotic) results.
http://stat.columbia.edu/~jcliu/paper/GSPRT_SQA3.pdf
In addition we ... |
def some_dead_code():
if 5 == 4:
print("5 = 4")
elif 4 == 3:
print("4 = 3")
x = 4
y = 5
def main():
a = 5
b = 6
c = 7
# Dead code
if False:
a = b
print(a)
# Augmented Assignment
c += 3
# Multiple Target Assignment
d = b = a = c
so... |
from ray.rllib.utils.framework import try_import_tf
from ray.rllib.utils.typing import TensorType, TensorShape
tf1, tf, tfv = try_import_tf()
class GRUGate(tf.keras.layers.Layer if tf else object):
def __init__(self, init_bias: float = 0.0, **kwargs):
super().__init__(**kwargs)
self._init_bias = ... |
from selenium import webdriver
from selenium.webdriver.support.ui import Select
driver = webdriver.Chrome()
driver.get("http://localhost/litecart/en/")
eml = "test8@test.com"
passw = "11111111"
def login():
driver.find_element_by_xpath(".//*[@id='navigation']//input[@name='email']").send_keys(eml)
driver.fi... |
"""КР, Ларькин Владимир, М8О-303Б-18"""
import time
import numpy as np
import fire # CLI
import multiprocessing as mp
from typing import List
from tqdm import tqdm # прогресс-бары
import matplotlib.pyplot as plt
from utilities import parse_matrix # парсинг матрицы из файла
from sem1.lab1_1.gauss import lu_solve
... |
#!/usr/bin/python
# Copyright 2014 Google.
#
# 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... |
from flask import(
Flask,
render_template,
flash,
redirect,
url_for,
session,
request,
logging
)
from . import mensagens as bp
from .. import mysql
from ..formularios import MessageForm
##############################################################
###############################... |
import os
import time
from collections import Counter
import numpy as np
from garageofcode.kaggle.word2vec import get_words as get_words_list
def get_top_1000_words():
data_dir = "/home/jdw/garageofcode/data/"
fn = os.path.join(data_dir, "1-1000.txt")
return [line for line in open(fn, "r").read().split(... |
import os, sys; sys.path.insert(0, os.path.join("..", ".."))
import re
from pattern.web import Google, URL
from pattern.web import Document, plaintext
# An interesting experiment on how to use the Google API
# and http://amplicate.com for opinion mining.
# (let's hope we get a real Amplicate API soon!)
query = "smu... |
"""Compile embedding evaluation stats and generate plots as presented in Van Paridon & Thompson (2020)."""
import numpy as np
import pandas as pd
import os
import seaborn as sns
import matplotlib.pyplot as plt
import argparse
path = os.path.dirname(__file__)
df_corpus = pd.read_csv(os.path.join(path, 'paper_res... |
from unittest import TestCase
import numpy as np
import torch
from strimadec.models.modules import RNN
class testRNN(TestCase):
BATCH_SIZE = 5
SEED = 7
def setUp(self):
np.random.seed(testRNN.SEED)
# (deterministic) random setup of RNN
self.random_config = testRNN.build_random_... |
import copy
import itertools
from graph_generator import generate_complete_graph
from models import LinearLayout, Graph
from view import show_linear_layouts
def observation_1(show_layouts=True):
"""
Generate all possible 2-stack 1-queue layouts of a complete graphs with
8 vertices. Except that edges (i, ... |
import logging
from park.envs.circuit.simulator.utility.logging import StructuredFormatterBuilder, get_console_handler
__all__ = ['get_logger', 'get_default_logger']
def get_logger(name, *handlers: logging.Handler, level=logging.DEBUG, propagate=True):
logger = logging.getLogger(name)
logger.setLevel(level)... |
from pyg_base import presync, dt, drange, eq
from pyg_base import df_fillna, df_reindex, nona, reducing, Dict, np_reindex
import pandas as pd; import numpy as np
import pytest
def test_df_fillna():
s = pd.Series([0., 1., 4., np.nan, 16.], np.arange(0,5))
assert np.isnan(df_fillna(s)[3])
assert df_fillna(s,... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on 22/01/2015
@author: jorgesaw
'''
from __future__ import absolute_import, print_function, unicode_literals
class RecursosCSS(object):
CSS = ''
@staticmethod
def cargarRecursoCss(file):
with open(file, 'r') as fh:
R... |
#!/usr/bin/env python
"""
https://pypi.python.org/pypi/paho-mqtt
"""
import paho.mqtt.client as mqtt
import RPi.GPIO as GPIO
from time import sleep
#define some pin numbers
pinLedSw = 19
pinLedRd = 13
#we have to clean up to reset pin definitions
#GPIO.cleanup()
#set the software to use the Broadcom numbers
GPIO.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayCommerceEducateSceneConfigCreateModel(object):
def __init__(self):
self._business_scene = None
self._pid = None
self._school_id = None
self._school_std_code ... |
# Copyright (c) 2019 Cisco and/or its affiliates.
# 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 ag... |
"""GCN implementation copied from https://github.com/mie-lab/traffic4cast-
Graph-ResNet/blob/master/models/graph_models.py with permission."""
# Copyright 2021 Institute of Advanced Research in Artificial Intelligence (IARAI) GmbH.
# IARAI licenses this file to You under the Apache License, Version 2.0
# (the "L... |
import asyncio
import aiohttp
import json
from ..helpers import pick_by
from ..backend import Backend
from ..update import Message, ReceiverType, Update, UpdateType, Attachment
from ..exceptions import RequestException
from ..logger import logger
SUPPORTED_ATTACHMENT_TYPES = (
"audio",
"document",
"photo"... |
"""Module with functions called to perform various benchmarks."""
import time
import datetime
def measurement_log(thread_id, i, delta, measurement_count):
"""Log an info about the measurement status."""
if thread_id is not None:
print(" thread: #{t} call {i}/{m} {delta}".format(t=thread_id,
... |
from django.shortcuts import render
import re
from django.utils.timezone import datetime
from django.http import HttpResponse
#from hello import spotify_signin
def home(request):
return render(
request,
'hello/signIn.html'
)
spotify_signin.spotify_auth()
# def hello_there(request, name... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Math operations with uncertainties and units.
Simplified version of `uncertainties` python package with some
`~astropy.units` addings, in a much more free form."""
import copy
from astropy import units
import numpy as np
from ._deriv import numpy_ufu... |
# -*- coding: UTF-8 -*-
import os
import pygame
from pygame.locals import *
from constants import BLACK, GAME_WIDTH, GAME_HEIGHT, ITEMS, STATS, TACTICS, PLACES
from text import create_prompt, MenuBox, MenuGrid
ITEMS_MENU = {
'HEAL ITEMS': {
'sort_order': 0,
},
'ATTACK ITEMS': {
'sort_or... |
def bar():
foo()
def foo():
try:
asdf()
except:
pass
try:
asdf()
except:
pass
def asdf():
raise Exception()
|
from rest_framework import permissions
from django.db.models import Q
from .models import Task
class TaskPermission(permissions.BasePermission):
def has_permission(self, request, view):
authenticated = request.user.is_authenticated()
if view.action == 'list':
return authenticated
... |
# 단어 1개 입력받아 나누어 출력하기
s = input()
for a in s:
print(a) |
class QQAPIError(Exception):
"""QQ接口调用异常"""
pass
|
# Copyright (c) 2015 - 2016 Intel Corporation.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, pu... |
# -*- coding: utf-8 -*-
# Copyright (c) 2016, Webonyx and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.db_schema import DbTable
def rename_custom_field(doctype, old_fieldname, new_fieldname):
if not frappe.db.exists('DocTyp... |
import unittest
from pyspark.sql import SparkSession, SQLContext
from pyselica.ml.feature import JapaneseTokenizer
class TestCases(unittest.TestCase):
def setUp(self) -> None:
self.spark = SparkSession.builder.appName('unittest').getOrCreate()
def test_japanese_tokenizer(self):
tokenizer = J... |
"""Example: optimization with different wake models
This example uses a dummy cost function to optimize a simple wind turbine
layout that is subject to constraints. The optimization pushes the wind turbine
locations to specified locations in the farm.
"""
import os
from matplotlib.patches import Polygon
import numpy ... |
from typing import List
nums = [3,30,34,5,9]
# alist=list(map(str,nums))
# print(alist)
# def Compare(str):
# def __lt__(x,y):
# return x+y<y+x
# ans=sorted(map(str,nums),key=Compare,reverse=True)
# print(ans)
alist=['2','1','3','0']
class Compare(str):
def __lt__(x, y):
print('x=',x,'y=',... |
from django.contrib import admin
from .models import Passport
# Register your models here.
admin.site.register(Passport) |
#This script performs the functions required for lumin transfer that
#leongatys/NeuralImageSynthesis' Color Control code performs.
#https://github.com/leongatys/NeuralImageSynthesis/blob/master/ExampleNotebooks/ColourControl.ipynb
#Standalone script by github.com/ProGamerGov
import skimage
import numpy as np
import ... |
import logging
import json
from datetime import datetime
import scraper_tools.title_list_scraper as title_list_scraper
import scraper_tools.data_processor as data_processor
import db_tools.db_reader as db_reader
import db_tools.db_writer as db_writer
def read_news_site_list(news_sites_file):
with open(news_sites_... |
import os
import json
import numpy as np
from PIL import Image
from collections import Counter
import torch
from torch.utils.data import Dataset
import torchvision.transforms as transforms
id_map = {0: 24, 1: 25, 2: 26, 3: 27, 4: 28, 5: 31, 6: 32, 7: 33, 8: 0}
reversed_id_map = {24: 0, 25: 1, 26: 2, 27: 3, 28: 4, 31:... |
from django.conf.urls import url
from django.urls import path
from medrecords_app import views
app_name = "medrecords_app"
urlpatterns = [
url("record_create/", views.MedicalRecordCreateView.as_view(), name="medrecord_form"),
url("list", views.MedicalRecordView.as_view(), name="medical_record"),
url('^rec... |
from PyQt4 import QtGui
from ui_mant_libros_new import NewLibrosWindow
from ui_mant_libros_edit import EditLibrosWindow
from ui_mant_libros_id_edit import GetIdEditWindow
# Debug only
import inspect
class MenuLibros(QtGui.QWidget):
"""
Ventana-menu para editar Libros
"""
def __init__(self):
... |
# -*- coding: utf-8 -*-
"""
Data generation for Figure 09
"""
import sys
sys.path.append("../main/")
from ODEdrop2D import *
from pdeloader import *
from matplotlib.gridspec import GridSpec
V = lambda t: Vperiodic(t,m=20,p=100,Vavg=2,Vamp=1)
theta = lambda x: 1 + .1*np.cos(1.6*np.pi*x) + 0.2*np.sin(0.2*np.pi*x)
# Sol... |
import unittest
import numpy as np
import pandas as pd
from numpy.testing import assert_array_equal
from scipy.special import expit
from sklearn.linear_model import LinearRegression, LogisticRegression
from functools import partial
from skater.core.local_interpretation.lime.lime_tabular import LimeTabularExplainer
... |
# -*- coding: utf-8 -*-
# pylint: disable=missing-docstring
__version__ = "0"
"""Some packages' test package initialisation."""
|
import os
from pathlib import Path
DEFAULT_ROOT_PATH = Path(os.path.expanduser(os.getenv("AVOCADO_ROOT", "~/.avocado/mainnet"))).resolve()
|
from typing import Any, Optional
class VerifierResult():
error: Optional[str]
result: Any
|
# When you import a directory but you havent given a specific file name then it will import __init__.py by default
from controllers.user_controller import user # Importing the user blueprint
from controllers.word_controller import words
from controllers.auth_controller import auth
registerable_control... |
# Random Walk mit beliebigem Winkel und variabler Schrittlänge
import turtle as t
import random as r
import math
WIDTH = 800
HEIGHT = 800
wn = t.Screen()
wn.setup(WIDTH, HEIGHT)
wn.colormode(255)
wn.bgcolor(50, 50, 50)
wn.title("Random-Walk (3)")
def distance(a, b):
return(math.sqrt(a**2 + b**2)) #/SL
colo... |
# coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... |
# -*- coding: utf-8 -*-
'''print('hello, world')
a = 123
print(a);
print(not True)
classmate = ['Michael','Bob','Tracy']
print(classmate)
print(classmate[0])
classmate.clear()
#classmate.pop()
print(classmate)
classmates = ('Michael', 'Bob', 'Tracy')
print(classmates)
t =(1,)
print(t)
age = 20
if age >= 6:
pr... |
import unittest
from nose.tools import (assert_is_not_none, assert_true, assert_raises,
assert_in, assert_equal, assert_less_equal)
import numpy
from sklearn.base import clone
from sknn.mlp import Classifier as MLPC
from sknn.mlp import Layer as L, Convolution as C
class TestClassifierFuncti... |
from django.core.management.base import BaseCommand
from app.models import Tasks
import datetime
import pytz
from django.core.mail import send_mail
from django.conf import settings
class Command(BaseCommand):
help = 'Send notifications fors tasks that are close to \
scheduled date/time'
def handle(se... |
import json
import unittest
from automerge_backend import Backend, default_sync_state
from automerge import doc
from automerge.datatypes import Counter
# we want changes to have the same timestamp to make the tests deterministic
# (prevents the bloom filter from failing)
ts = lambda: 0
# TODO: Some tests have `0` ti... |
"""
outpu by npy
"""
import xml.etree.ElementTree as ET
import cv2
import numpy as np
from pathlib import Path
import matplotlib.pyplot as plt
import matplotlib
# return number of vectors
def compute_vector(
black, pre, nxt, result, result_l, result_y, result_x, result_z, ks, zv, sgm
):
img_l = black.copy... |
"""
You are given a string of length `N` and a parameter `k`. The string can be
manipulated by taking one of the first `k` letters and moving it to the end,
with an unlimited number of moves.
For example, if we are given the string `daily` and `k = 1`, then the best we
can do is `ailyd`, since you can only move the fi... |
#!/usr/bin/env python3
#
# Copyright (c) 2017 Jon Turney
#
# 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,... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Program: diffusionEq2D_ForwardEulerV
Created: Aug 2020
@author: Ryan Clement (RRCC)
scisoft@outlook.com
Purpose: Solve the partial differential equation (PDE)
u_t = alpha * (u_xx + u_yy)
in (0,Lx)x(0,Ly) with vanishing boundary conditions or
... |
# import the necessary packages
from .simplepreprocessor import SimplePreprocessor
from .imagetoarraypreprocessor import ImageToArrayPreprocessor |
# -*- python -*-
# This software was produced by NIST, an agency of the U.S. government,
# and by statute is not subject to copyright in the United States.
# Recipients of this software assume all responsibilities associated
# with its operation, modification and maintenance. However, to
# facilitate maintenance we as... |
"""Implements Load checkpoint."""
from abc import ABC
import torch
from torchflare.callbacks.callback import Callbacks
from torchflare.callbacks.states import CallbackOrder
class LoadCheckpoint(Callbacks, ABC):
"""Class to load checkpoint."""
def __init__(self, path_to_model: str = None):
"""Constr... |
import pygame
import pyscroll
import pytmx.util_pygame
from player import Joueur
class Game:
def __init__(self):
# creer la fenetre du jeu
self.screen = pygame.display.set_mode((800,600))
pygame.display.set_caption("Pygamon - Adventure")
#charger la carte(tmx)
tmx_data =... |
import string
from typing import List
default_censor: List[str] = ["@everyone", "@here"]
def filter_words(original_message: str,
censored_words: List[str] = None) -> str:
if censored_words is None:
censored_words = default_censor
censored_message: str = original_message
for censo... |
from django.db import migrations, transaction
from ultimatejobweb.models import Job, Company
class Migration(migrations.Migration):
dependencies = [
('ultimatejobweb', '0002_test_data_company'),
]
def generate_data(apps, schema_editor):
jobs = [('Facebook', 'Production Engineer', 'https:... |
#!/usr/bin/env python3
import sys
import numpy as np
import zxntools as zxn
VERSION = "1.00.00"
DATE = "20210407"
NAME = 'imgtosl2'
def my_help(name):
version()
sys.stderr.write(
("Usage: {} [<options>] [<infile>] [<outfile>]\n"
"\toptions are\n"
"\t-2\t--256x192\t256x192 resoulti... |
#!/usr/bin/python3
nota1 = input("Digite a primeira nota: ")
nota2 = input("Digite a primeira nota: ")
nota3 = input("Digite a primeira nota: ")
nota4 = input("Digite a primeira nota: ")
a = float(nota1)
b = float(nota2)
c = float(nota3)
d = float(nota4)
soma = a + b + c + d
print("A média aritmética é: ", soma / ... |
STATUS_CHOICES = [
# first: Stored value, second: Displayed value
('draft', 'Draft'),
('published', 'Published'),
]
def upload_cover_photo_to(instance, filename):
return f"post-photos/{instance.author.username}/{filename}" |
#! /usr/bin/env python
########################################################################
#
# Copyright 2018 cloudmesh.org
#
# 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
#
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 20 14:05:29 2018
@author: amolsingh
"""
import cv2
import VideoPrep
import numpy as np
import time, os
import matplotlib.pyplot as plt
#%% Main
def stitch(folder):
time1 = time.time()
VideoPrep.vid2imgs(folder)
dir_path = os.path.dirna... |
import tflearn
import tensorflow as tf
import cb_utils
import json
words = cb_utils.loadFromFile('words.csv')
classes = cb_utils.loadFromFile('classes.csv')
# reset underlying graph data
tf.reset_default_graph()
# Build neural network
net = tflearn.input_data(shape=[None, len(words)])
net = tflearn.fully_connected(ne... |
import numpy as np
from sklearn.datasets import load_wine
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import classification_report
from sklearn.utils import shuffle
# Set random seed for reproducibility
np.random.seed(1000)
if __name__ == "__main__":
# Load the dataset
wine = load_wine(... |
"""
Summary:
Factory class for building the AUnits from an ISIS data file.
This is used to read and build the parts of the ISIS dat file.
Author:
Duncan Runnacles
Created:
01 Apr 2016
Copyright:
Duncan Runnacles 2016
TODO:
There are a few functions in here that should be made prote... |
import os
import pprint
import sys
sys.path.append("src/")
import hydra
import numpy as np
import pandas as pd
import tqdm
from hydra.utils import instantiate
from omegaconf import DictConfig, OmegaConf
@hydra.main(config_path="../../config", config_name="default")
def main(config: DictConfig) -> None:
print("-... |
#!/usr/bin/env python
'''
enrich_plot: contains a number of functions that use matplotlib to generate visualizations of enrich data. This module is intended to be extensible, containing all enrich-related visuals
'''
__author__ = "Douglas M. Fowler"
__copyright__ = "Copyright 2011"
__credits__ = ["Douglas M Fowler", ... |
import os
import uuid
from django.db.models.fields.files import FileField, ImageField, ImageFieldFile, FieldFile
try:
from django.urls import reverse_lazy
except ImportError:
from django.core.urlresolvers import reverse_lazy
PROTECTION_METHODS = ['basic', 'nginx', 'lighttpd', 'apache']
class PrivateFieldFil... |
from . import temperature_manager
from . import temperature_monitor
__all__ = ['temperature_manager', 'temperature_monitor']
|
# Generated by Django 3.1 on 2020-11-20 09:03
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('sample', '0009_auto_20201120_0845'),
]
operations = [
migrations.AddField(
model_name='districtmi... |
# -*- coding: utf-8 -*-
# Copyright (C) 1999-2002 Joel Rosdahl
# Copyright © 2011-2013 Jason R. Coombs
"""
Internet Relay Chat (IRC) protocol client library.
This library is intended to encapsulate the IRC protocol at a quite
low level. It provides an event-driven IRC client framework. It has
a fairly thorough su... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 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 ... |
# -*- coding: utf-8 -*-
# @Time : 2021/1/22 5:17 下午
# @Author : islander
# @File : vanilla_train.py
# @Software: PyCharm
import tensorflow as tf
from typing import Dict
# wrapper of train, replace ph and sess with model.Din
def train_by_net(net, **kwargs):
return train(sess=net.session,
... |
"""
### NOTICE ###
You DO NOT need to upload this file
"""
import argparse
import numpy as np
from environment import Environment
seed = 11037
def parse():
parser = argparse.ArgumentParser(description="MLDS 2018 HW4")
parser.add_argument('--test_pg', action='store_true', help='whether test policy gradient'... |
# -*- coding: utf-8 -*-
# @Date : 2020/5/20
# @Author: Luokun
# @Email : olooook@outlook.com
import matplotlib.pyplot as plt
import numpy as np
class KNN:
"""
K nearest neighbor classifier(K近邻分类器)
"""
def __init__(self, k: int):
"""
:param K: 分类近邻数
"""
self.k = k
... |
# Copyright 1999-2009 University of Chicago
#
# 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 t... |
class ArangodanticError(Exception):
"""Generic Arangodantic error class."""
pass
class CursorNotFoundError(ArangodanticError):
pass
class DataSourceNotFound(ArangodanticError):
pass
class ModelNotFoundError(ArangodanticError):
pass
class MultipleModelsFoundError(ArangodanticError):
pass... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
import glob
import shutil
import os
import pandas as pd
import numpy as np
import nrrd
import re
import matplotlib
import matplotlib.pyplot as plt
import pickle
from time import gmtime, strftime
from datetime import datetime
import timeit
from sklearn.model_selection import train_test_split
from tensorflow.keras.utils ... |
from collections import defaultdict, deque
from functools import lru_cache
from typing import List
class Solution:
def loudAndRich(self, richer: List[List[int]], quiet: List[int]):
graph = defaultdict(set)
for u, v in richer:
graph[v].add(u)
ans = [-1 for _ in range(len(quiet))... |
# 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 ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 2 14:37:04 2019
@author: B.Mika-Gospodorz
Input files: stdin with bam file with multi-mapped reads, reference_host_names.txt and reference_pathogen_names.txt files that contain references extracted with extract_reference_names_from_fasta_files.sh
... |
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2018 Contributor
#
# 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
#
# ... |
"""Autcompletion support for the fish shell"""
from typing import Union
from pathlib import Path
from arc import types
from arc.config import config
from arc._command import Command, helpers
COMPLETE = "complete -c"
SEEN_SUBCOMMAND = "__fish_seen_subcommand_from"
class FishCompletion:
def __init__(self, command:... |
from sync_conda_environments.helpers.process import run_subprocess
def test_run_subprocess():
output = run_subprocess(["pwd"])
assert output is not None
assert isinstance(output, bytes)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.