text stringlengths 3.07k 12.6k |
|---|
import json
from os.path import join
from typing import List, Optional, Type
import matplotlib.pyplot as plt
from fedot.core.chains.chain import Chain
from fedot.core.chains.chain_convert import chain_as_nx_graph
from fedot.core.data.data import InputData
from fedot.core.log import Log, default_log
from fedot.core.ut... |
import redis
import datetime
from abc import ABC, abstractmethod
from typing import Tuple, Optional
from gtmcore.logging import LMLogger
from gtmcore.inventory.inventory import InventoryManager
logger = LMLogger.get_logger()
class RepoCacheEntry(ABC):
""" Represents a specific entry in the cache for a specific ... |
# coding: utf-8
import os
import snap
import numpy as np
import matplotlib.pyplot as plt
from collections import Counter
RANDOM_SEED = 42
SUCCESS = -1
def loadPowerGridNetwork():
'''
Loads the US Power Grid network as a snap.TUNGraph
'''
path = 'data/USpowergrid_n4941.txt'
Graph = snap.LoadEdgeList(snap.... |
import pygame
class Slider():
def __init__(self, value_range, pos, shape, buttonColor=(0x03, 0xA9, 0xF4),
fillColor=(0xF5, 0xF5, 0xF5), lineColor=(0xBD, 0xBD, 0xBD), radius=None,
initialValue=0):
self.value_range = value_range
self.pos = pos
self.shape = shape # (width, height)
self.butto... |
#!/usr/bin/env python
# coding: utf-8
# ## Load libraries
# In[1]:
get_ipython().system('pip install -q -r requirements.txt')
# In[1]:
import sys
import os
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import rxrxutils.rxrx.io as rio
from scipy import misc
from PIL import Image
import... |
# -*- coding: utf-8 -*-
import time
import codecs
import multiprocessing as mp
import utils
import json
import consts
#TODO: rewrite to include sequentional version
class Guesser_Testable:
gloss: dict[str, list[str]]
candidates: list[str]
try_count: int = 0
used_letters: list[str] = []
def __init... |
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import spotixplore.credentials as cr
import tracks.track_class as T
### CREDENTIALS
api_client_id = cr.SPOTIPY_CLIENT_ID
api_client_secret = cr.SPOTIPY_CLIENT_SECRET
sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials(api_client... |
# -*- coding:utf-8 -*-
import os
from re import search
import win32com.client
def WMIDateStringToDate(dtmDate):
# Преобразует время из WMI формата в нормальный человеческий
strDateTime = ""
if (dtmDate[4] == 0):
strDateTime = dtmDate[5] + '/'
else:
strDateTime = dtmDate[4] + ... |
# This file is a template for V-rep environments
# all names in this file are just examples
# Search for '#modify' and replace accordingly
from vrep_env import vrep_env
from vrep_env import vrep # vrep.sim_handle_parent
import os
if os.name == 'nt':
#print('If you are running this code on windows you need to ma... |
#!/usr/bin/env python3
"""Investigates link entropy, graph entropy, and T-code complexity.
The main purpose of this script is to look at the three entropy
metrics using different parameters.
"""
import argparse # For command line
import matplotlib.pyplot as plt # For plotting
import numpy as np # For matrices
def ... |
import streamlit as st
import numpy as np
import pandas as pd
import plotly.express as px
import joblib
import os
@st.cache
def load_data(data):
df = pd.read_csv(data)
return df
@st.cache
def load_model(model_file):
loaded_model = joblib.load(open(os.path.join(model_file),"rb"))
return loaded_model... |
"""
Module containing helper functions that execute small tasks.
These can be parallellized with Ray.
"""
import tempfile, logging
import numpy as np
import cv2
import ray
# Setup logging
log = logging.getLogger(__name__)
# Load a single image
@ray.remote
def loadImage(image_path, dir):
"""
Load an image in ... |
import pytest
from datetime import datetime
from penn_chime.constants import CHANGE_DATE
from penn_chime.parameters import Parameters, Disposition
from penn_chime.models import SimSirModel as Model
import penn_chime.models as models
import penn_chime.cli as cli
from pandas import DataFrame
import numpy as np
import p... |
# -*- coding: utf-8 -*-
"""
# @file name : common_tools.py
# @author : TingsongYu https://github.com/TingsongYu
# @date : 2020-06-23
# @brief : 通用函数
"""
import os
import matplotlib.pyplot as plt
import numpy as np
import torch
from tqdm import tqdm
class ModelTrainer(object):
def __init__(self):
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: <NAME>
"""
import numpy as np
from scipy import optimize
from sklearn.isotonic import IsotonicRegression
"""
auxiliary functions for optimizing the temperature (scaling approaches) and weights of ensembles
*args include logits and labels from the calibration... |
"""Zeroconf based scanner"""
from __future__ import annotations
import logging
from threading import Event
from typing import Callable
from zeroconf import ServiceBrowser, ServiceInfo, ServiceListener, Zeroconf
from .const import DISCOVERY_TIMEOUT
from .utils import network as net_utils
LOGGER = logging.getLogger(_... |
import pandas as pd
import numpy as np
from sklearn import preprocessing, cluster
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
import matplotlib.pyplot as plt
import seaborn as sns
def plot_elbow(sse, ks):
fig, axis = plt.subplots(figsize=(9... |
from flask import Blueprint, request, render_template, redirect, Response
from flask_cors import CORS
from pyldapi import ContainerRenderer
from rdflib import Namespace
from rdflib.namespace import SDO, TIME
from api.model import GeoFeatureRenderer, LOCIDatasetRenderer
import api.config as config
from os.path import jo... |
from IMLearn.utils import split_train_test
from IMLearn.learners.regressors import LinearRegression
from IMLearn.metrics.loss_functions import mean_square_error
from typing import NoReturn
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
import plotly.io as pio
pio.... |
# Original file: https://github.com/ScanNet/ScanNet/blob/master/SensReader/python/SensorData.py
#
# Copyright 2017
# <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>
#
# Copyright 2021
# Modified by <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associ... |
import threading
# buffer of opinions to process
opinion_buffer = []
opinion_buffer_lock = threading.Lock()
firebase_client = None
# As this is the only process that's allowed to modify firebase we can
# decrease read costs by an in memory cache
conversations_map = {}
_dirty_list_ids = set()
# Very simple scheme to... |
from pathlib import Path
from test.utils import TestUtils
from typing import Any, Callable, Optional, Union
import pytest
from src.core.common.constants import Constants
from src.core.common.environment import Environment
from src.core.coral.coral_model import Coral
from src.core.hydrodynamics.delft3d import DimrMode... |
import os
import pythoncom
import win32com.client as comclt
from time import sleep
from PyQt5.QtCore import pyqtSignal, QThread
from src.ModsContainer import items_categories_filter
class LogListener(QThread):
entered_map = pyqtSignal(bool)
def __init__(self, settings_widget):
super().__init__()
... |
import argparse, itertools, jxmlease, more_itertools, numpy as np, pathlib
from ..utilities import units
from ..utilities.dataclasses import MetaDataAnnotation, MyDataClass
from ..utilities.misc import dummylogger, printlogger
from ..utilities.tableio import readtable, writetable
from .csvclasses import Annotation, Reg... |
import math
import operator
from typing import Optional, Union, Callable, Any
from .base import Loader, ILoaderClass
from .utils import keep, check_only
NUMBER_TYPES = (int, float)
NUMBER_TYPING = Union[int, float]
def numeric(int_ok: bool = True, float_ok: bool = True, inf_ok: bool = True) -> ILoaderClass:
if ... |
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
'''
Automates searching Shodan for vulnerable systems within the same postal code.
'''
# dunders
__author__ = '<NAME>'
__version__ = '0.1.0'
# built-in libraries
import argparse
import datetime
import glob
import itertools
import logging
import string
import sys
import... |
# Copyright 2015 Cloudbase Solutions Srl
# 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 r... |
from keras import layers
from keras import optimizers
from keras.layers import Input, Dense, Activation, BatchNormalization, Flatten, Conv2D, MaxPooling2D, GlobalAveragePooling2D, Dropout
from keras.models import Model
from keras.initializers import glorot_uniform
from keras.utils import to_categorical
from keras... |
import requests
import git
import logging
import sys
from pathlib import Path
from configparser import ConfigParser
# Global variables
config = None
# Basic Logging Config
logging.basicConfig(
stream=sys.stdout,
level=logging.INFO,
datefmt='%Y-%m-%d %H:%M:%S',
format='%(asctime)s %(levelname)s %(messa... |
from collections import defaultdict
def split_quoted_str(src, dlm, preserve_quotes=False):
assert dlm != '"'
if src.find('"') == -1: #optimization for majority of lines
return (src.split(dlm), False)
result = list()
cidx = 0
warning = False
while cidx < len(src):
if src[cidx] ==... |
import os
import json
import xmltodict
import zipfile
import pandas as pd
from pathlib import Path
import pytest
import sys
import filecmp
class OoxmlFile:
"""
OOXML file class object to load various XMLs from the zip of the OOXML file and
saving them in json format in the coresponding path in the generate folder... |
from __future__ import print_function, unicode_literals
from collections import defaultdict
from functools import wraps
import json
import os
import re
import time
import calendar
import urlparse
import traceback
from weblab.core.wl import weblab_api
from weblab.core.i18n import gettext
from flask import current_app, ... |
#<NAME>
#Python Hangman
#Last updated 2/9/16
import random
import os
def currentHangman(life):
if(life==8):
print(" ",'\n'," ",'\n'," ",'\n'," ",'\n'," ",'\n'," ",'\n'," ",'\n'," ")
elif(life==7):
print(" ",'\n'," ",'\n'," ",'\n'," ... |
import copy
import urllib3
from django import forms
from guardian.models import UserObjectPermission
from django.core.exceptions import ValidationError
from profiles.models import BillingGroup
from service_catalog.forms.utils import get_fields_from_survey
from service_catalog.models import Service, Operation, Instanc... |
# -*- coding: utf-8 -*-
"""
The executor submodule contains the PipelineExecutor, which runs an image processing pipeline.
"""
import gc
import logging
try:
import tqdm
except ImportError:
tqdm = None
from itertools import product
from collections import OrderedDict
from copy import deepcopy
from ..misc.pro... |
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 25 20:57:10 2022
@author: LiCheng_Xu
"""
import pandas as pd
import numpy as np
from rdkit import Chem
from rdkit.Chem import AllChem,Descriptors
from ase import Atoms as ASE_Atoms
from dscribe.descriptors import MBTR,ACSF,SOAP,LMBTR
from rdkit.ML.Descriptors ... |
import datetime
import os
import sys
import traceback
import uuid
os.environ["KERAS_BACKEND"] = "theano"
from flask import Flask, request, make_response
from neuralNets.FlairWrapper import FlairWrapper
# from neuralNets.BiLSTMWrapper import BiLSTM
from util.CASProcessor import parse_prediction_request
from util.confi... |
''' Contains utility functions that deals with time(stamps), file handling
with AWS S3 and IO operation with PostgreSQL database.
'''
import datetime as dt
import os
from boto3 import client
from pyspark import SparkContext, SparkConf
from pyspark.sql import SparkSession, SQLContext
def spark_init(s_name):
''' Cre... |
from itertools import groupby # for unique function.
from bisect import bisect_left, insort_left # for unique function.
def unique(seq, stable=False):
"""unique(seq, stable=False): return a list of the elements in seq in arbitrary
order, but without duplicates.
If stable=True it keeps the original element... |
# MrRazamataz's RazBot
# Logs Cog
import random
import discord
from discord import reaction
from discord.ext import commands
import asyncio
import os
import aiofiles
import datetime
from discord.utils import get
class mod(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.list... |
'''
Preferences related to C++ compilation
Preferences
--------------------
.. document_brian_prefs:: codegen.cpp
'''
from distutils.ccompiler import get_default_compiler
from brian2.core.preferences import prefs, BrianPreference
from .codeobject import sys_info
__all__ = ['get_compiler_and_args']
# Try to get arc... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... |
"""
preproc.py - functions for preprocessing the raw EKG signal,
e.g. de-trending EKG leads using gaussian smoothing, squashing the range into
[-1, 1]preprocess EKG signal functions
"""
from scipy import ndimage
import numpy as np
import pandas as pd
import pyprind
from biosppy.signals import ecg as becg
def pre... |
from datetime import date, datetime, timedelta
from dateutil.relativedelta import relativedelta
from src.backend.eligibility_eval import is_eligible
def test_eligible__more_than_5_years():
five_years_ago = date.today() - timedelta(days=5*365)
ten_years_ago = date.today() - timedelta(days=10*365)
assert... |
from contextlib import contextmanager
from logging import getLogger
from time import sleep
from uuid import uuid4
from raptiformica.distributed.exec import try_machine_command
from raptiformica.shell.execute import run_command_print_ready, raise_failure_factory, run_critical_command_print_ready
log = getLogger(__nam... |
#Python script for pulling data from the Twitter API and analyzing it into a pandas dataframe
#Resources used:
#https://www.youtube.com/watch?v=ujId4ipkBio&ab_channel=ComputerScience
#https://www.youtube.com/watch?v=bNDRiaFyLrs&ab_channel=Algovibes
import tweepy
import pandas as pd
import numpy as np
import json
from... |
import re
import collections
import sklearn
import gensim
import gensim.models
import gensim.downloader
import numpy as np
import requests
import zipfile
import urllib.parse
import os
from pathlib import Path
from vectorian.tqdm import tqdm
def gensim_version():
return int(gensim.__version__.split(".")[0])
_custo... |
# -*- coding: utf-8 -*-
"""
:platform: Linux, Windows, python 2.7 and 3.x
:synopsis: Create an SWD file using shape = 6 (Airy waves)
Author - <NAME>, DNVGL
Created - 2019-11-17
"""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import... |
import logging
import os
import json
logging.basicConfig(
format='%(asctime)s %(levelname)s %(name)s: %(message)s', level=logging.DEBUG)
logger = logging.getLogger(__file__)
class Photovoltaic:
def __init__(self, id, node, phases, voltage, max_power, max_q_power, powerfactor, control_strategy="ofw", meta=No... |
from .base import SchemaGenerator, TypedSchemaGenerator
import re
from titlecase import titlecase
class Typeless(SchemaGenerator):
"""
schema generator for schemas with no type. This is only used when
there is no other active generator, and it will be merged into the
first typed generator that gets ad... |
# actransit_apis.py
# -*- coding: utf-8 -*-
# @Author: <NAME>
# @Date: 2017-01-11 14:48:11
# @Last Modified by: <NAME>
# @Last Modified time: 2017-02-14 09:52:25
__author__ = 'sidmishraw'
# __PERSONAL_API_KEY__ = '<KEY>'
__PERSONAL_API_KEY__ = None
# The base URL for the AC Transit APIs
__BASE_URL__ = 'https://... |
# Copyright (c) 2020 PaddlePaddle 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 app... |
import pandas as pd
import logging
from typing import List, TextIO, Tuple, Dict
import importlib.resources as pkg_resources
import data
import plotly.graph_objects as go
import numpy as np
def flight_network_dataset() -> Tuple[pd.DataFrame, pd.DataFrame]:
logger = logging.getLogger(__name__)
# download airpo... |
import random
from battleship_ship import Ship
def read_file(path):
"""
Read data from file and store to 2D list
:param path: path to the file
:return: battlefield in format of 2D list
"""
with open(path, 'r') as field_file:
battlefield = [[ch for ch in row.strip('\n')] for row in fiel... |
# Patch generator tool for Flipnote Studio 3D
# Generates luma code patches which allow the app to connect to a custom server
# Original patch written for Kaeru Gallery by Shutterbug2000
# github.com/shutterbug2000
# JPN support and Python tooling by Jaames
# github.com/jaames | jamesdaniel.dev
from sys import argv
im... |
import pandas as pd
import numpy as np
import keras.backend as K
from keras import Sequential
from keras.layers import Dense, Dropout
class EmbeddingsGenerator:
def __init__(self, train_users, data):
self.train_users = train_users
# preprocess
self.data = data.sort_values(by... |
import sys
import os
import collections
#used to switch to various predefined ways the final table can look
"""
Default 'file' shows
---
annotation | file name | line number
signature
---
compact
---
annotation
signature
---
ansig
---
annotation | signature
---
"""
STYLE = "compact"
OUTPUTDIR = "docs/"
steps = []
... |
import numpy as np
from matplotlib import pyplot as plt
import os
from PIL import Image
from skimage.util.shape import view_as_blocks
# Note: Data shape example are only for 240x416 images
# 480x832 images will double the block hight and block width
# Print out a block of patches one by one
# patch (390,... |
# Copyright 2014 Rackspace Hosting
# 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... |
# -*- coding: utf-8 -*-
from flask import Blueprint, request, redirect, jsonify
from common.libs.Helper import ops_render
from common.models.member.Member import Member
from common.models.food.Food import Food
from common.models.pay.PayOrder import PayOrder
from common.models.pay.PayOrderItem import PayOrderItem
from a... |
from lxml import etree
import re
dungeonList = etree.parse('./dungeon.xml')
monsterList = etree.parse('./monster.xml')
spawnList = etree.parse('./spawn.xml')
npcList = etree.parse('./npc.xml')
roomList = etree.parse('./room.xml')
def printText(text):
print(text)
print()
def findSpawnTable(spawnTableName):
... |
import sys
from getpass import getpass
from socket import *
import json
import time
import subprocess
import base64
serverName = '0.0.0.0'
serverPort = 12000
DEFAULT_SERVER_NAME = '0.0.0.0'
DEFAULT_SERVER_PORT = 2121
DEFAULT_CLIENT_PORT = 12000
serverName = ''
serverPort = 0
clientControlPort = 0
ENDMARK = ' '
EN... |
from pygame import *
import pygame_menu
import time as t
sy = 3
sx = 4
wscr = 3
s1 = 0
s2 = 0
init()
win = display.set_mode((700, 500))
g_name1 = '<NAME>'
g_name2 = 'The Doctor'
def an1(name1):
global g_name1
print('Player name is: ', name1)
g_name1 = name1
def an2(name2):
... |
TPB = 4
from numba import cuda, int32
import numpy as np
import cupy as cp
import math
from skimage.util.shape import view_as_windows
dim = (8,8)
@cuda.jit
def gpu_memory_test(arr, block, thread, shared_sum_arr, local_sum_arr, padded_arr):
x, y = cuda.grid(2)
width, height = dim
tx = cuda.threadIdx.x
... |
import argparse
import json
import sys
import os
import yaml
import tnt.opts as opts
from tnt.utils.logging import init_logger, logger, beautify_info
from tnt.model_builder import ModelBuilder
import tnt.dataloaders as data_loaders
parser = argparse.ArgumentParser(description='PyTorch Training')
parser.add_argument('-... |
import subprocess
import os
import datetime
import time
from config import Config
def start_server():
c = Config()
return subprocess.run([c.adb, 'start-server'], stdout=subprocess.PIPE)
def kill_server():
c = Config()
return subprocess.run([c.adb, 'kill-server'], stdout=subprocess.PIPE)
def list_... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 19 02:44:54 2020
@author: farzanehmeimandi
"""
# Problem 1
# As we are using Max-pooling, it does not differ in the order of Max-pooling and the activation function
# Problem 2
# 2d & 1d (in the following code) - It seems to be a debate whether us... |
import math
from random import randint
my_file = open("bip0039.txt", "r")
content = my_file.read()
"""
Dicts and sets have an O(1)
time complexity for membership checking because
entries are accessed via a hashing algorithm
stackoverflow.com/questions/60568734/what-is-the-time-complexity-of-checking-membership-in-tu... |
#!/usr/bin/env python
# All original code, based on Alpha-Beta algorithm
import numpy as np
import morris
import time
# SETTINGS
LOG = False # Enables logging of timeTaken's
def step(board, color, pieces_self, pieces_opponent):
global last_times
startTime = time.perf_counter()
depth = 3
best... |
# Author:zsk-d
import shutil,xlwt,xlrd,time,os,sys
import openpyxl
from openpyxl.styles import PatternFill
COPY_EXCEL_PATH = 'data\\export_{}.xlsx'
TEMP_EXCEL_FILE_PATH = 'data\\export_temp.xlsx'
MAX_FILL_COLOR = 'ff0000'
MAX_KEY_PRESS_COUNT = 0
def getKeyDataXY(keyName):
''' 获取键盘按键对应excel模板位置 '''
try:
... |
response.menu=[
['Main',False,URL(r=request,c='default',f='index')],
]
if not auth.user:
response.menu.append([T('Register'),False,URL(r=request,c='default',f='register')])
response.menu.append([T('Conference'),False,'http://us.pycon.org/2009/conference'])
submenu_info=[
[T('Companies'),False,URL(r=... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
HEADER_COLUMNS = ['k', 'h', 'h_extra', 'paa_block', 'ts_index',
'ts_start', 'ts_end', 'jaccard_ksim', 'wjaccard_ksim',
'jaccard_paa', 'wjaccard_paa', 'time_ksim', 'time_bf', 'time_paa']
all_dataset_metadata = [
... |
import os
import operator
import string
from random import shuffle
from collections import Counter
import json
import pickle
import nltk
from nltk.tokenize import TweetTokenizer
from nltk.stem import WordNetLemmatizer
__author__ = "<NAME> and <NAME>"
def tokenize(data):
""" Tokenization.
Tokenize and lemmatize... |
"""
This script tests the result of Lemma 1 using toy constants
"""
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from scipy import stats
from pylab import rcParams
rcParams['figure.figsize'] = 12, 8
rcParams['mathtext.default'] = 'regular'
rcParams['font.size'] = 20
matplotlib.rcParams.update... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 7 14:35 2016
@author: daphnehb
"""
# pour les vieilles versions (Excel avant 2010)
from xlwt import Workbook as Old_Workbook
# pour versions récentes (Excel apres 2010)
from openpyxl import Workbook, cell as Xls_cell
import exceptions as exc
import os, subprocess
import s... |
from __future__ import annotations
import textwrap
import logging
import os
import re
from dataclasses import dataclass
from distutils.util import strtobool
from typing import Any, List, Optional
from discord import CategoryChannel, Guild, Role, TextChannel, Message
from discord.abc import Messageable
from discord.ut... |
# -*- coding: utf-8 -*-
"""
Spyder Editor
The purpose of this script is to analyse Guppy camera images that has been
used for checking the stability of the MTF test setup.
Input to this derived from:
- 'guppy usage Ferhat 20-9-2017.ipynb' which captures the images from the
Guppy in a defined sequen... |
import random
from abc import ABC, abstractmethod
import numpy as np
from tqdm import tqdm
from cellular_algorithm import Grid
class Evolution(ABC):
def __init__(
self,
crossover,
mutation,
selection,
succession,
boundaries,
function,
maximize=True... |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import collections
import torch
import torch.nn as nn
import numpy as np
# clip gradient
def clip_gradient(optim... |
# -*- coding: utf-8 -*-
import os
from datetime import datetime, timezone, timedelta
from flask import Flask, render_template, redirect, url_for, request, session, flash, jsonify, send_from_directory
from werkzeug.utils import secure_filename
import platform
from functools import wraps
import secrets
cwd = os.getcwd(... |
# file: text.py
# vim:fileencoding=utf-8:ft=python:fdm=marker
# Copyright © 2011-2021 <NAME> <<EMAIL>>. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause
# Created: 2011-03-27 13:59:17 +0200
# Last modified: 2021-08-10T14:40:58+0200
"""Text output routines for lamprop."""
from .version import __version__
im... |
#import copy
import os
import os.path as osp
#import modelindex
ROOT_DIR = '/home/oschung_skcc/git'
WORK_DIR = osp.join(ROOT_DIR, 'mymm/oxford')
DATA_ROOT= osp.join(WORK_DIR, 'data')
IMG_PREFIX = osp.join(DATA_ROOT,'images')
ANN_PREFIX = osp.join(DATA_ROOT,'annotations','xmls')
# metaTrain0 = osp.join(DATA_ROOT, '... |
# -*- coding:utf-8 -*-
import sys
import re
import os
import chess3
from chess3 import *
def xboard_play(board, process_pool, history=[], respond=lambda x: sys.stdout.write(x + '\n')):
mymove = find_best_move(board, process_pool)
if mymove:
respond('move ' + mymove.to_xboard_notation())
histor... |
# Copyright (c) 2016-2019, <NAME>
# 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 source code must retain the above copyright notice, this
# list of conditions ... |
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
#!/usr/bin/env python
"""
This sample application demonstrates a mix-in class for commandable properties
(not useful for Binary Out or Binary Value objects that have a minimum on and off
time, or for Channel objects).
"""
from bacpypes.debugging import bacpypes_debugging, ModuleLogger
from bacpypes.consolelogging imp... |
#!/usr/bin/env python
# coding=utf-8
# Copyright (c) 2014-2018 <NAME> (pr3d4t0r)
# All rights reserved.
#
# Version - see _VERSION global
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source ... |
from __future__ import absolute_import, print_function
import argparse
import logging
import os.path
import sqlite3
import stat
import sys
from datetime import datetime
from typing import List, Optional, Tuple
from .hpss import hpss_get, hpss_put
from .hpss_utils import add_files
from .settings import (
DEFAULT_C... |
import numpy as np
import os,sys
# import torch
import glob
from cv2 import imread
from tqdm import tqdm
TAG_FLOAT = 202021.25
def EPE(input_flow, target_flow):
# return torch.norm(target_flow-input_flow,p=2,dim=1).mean()
return np.linalg.norm(target_flow-input_flow, ord=2, axis=1).mean()
def flow_read(file)... |
import torch
import torchvision
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torchvision.utils as utils
from torch_cv_wrapper.dataloader.albumentation import *
from torch.utils.data import DataLoader
from torch.utils.data import Dataset
from tqdm import notebook
fr... |
from rest_framework import viewsets, mixins
from rest_framework.permissions import IsAuthenticated, BasePermission, IsAuthenticatedOrReadOnly
from rest_framework.response import Response
from rest_framework.decorators import detail_route
from rest_framework.exceptions import ValidationError
from django.shortcuts import... |
# -*- coding: utf-8 -*-
# add the MPI function to reference in the glossary here. This skullduggery is
# necessary to get consistent monospace formatting of the function. Each list
# entry should be a list of a string of the name of the MPI function and an
# integer of the node number of the MPI standard document webp... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2021, <NAME> <<EMAIL>>
#
# Permission to use, copy, modify, and/or distribute this software for any purpose
# with or without fee is hereby granted, provided that the above copyright notice
# and this permission notice appear in all copies.
#
# THE SOFTWARE IS P... |
import numpy as np
from torch import nn, optim
from ..utils.utils_net import TorchNetRes, criterion_func
# from ..utils.utils_plot import plot_roc_curve, plot_pr_curve, plot_roc_ind, plot_pr_ind
from ..utils.utils_results import performance, final_results_output, prob_output, print_metric_dict
def get_partition(feat... |
import numpy as np
import time
import sys
class Progbar(object):
"""Displays a progress bar.
# Arguments
target: Total number of steps expected.
val_target: Total number of validation steps expected, None if not validation.
width: Progress bar width on screen.
verbose: Verbosity... |
# uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: __init__.py
import dsz
import pc.payload.config
import pc.payload.exe
import dsz.lp
import dsz.path
import glob
import os
import shutil
import xml.do... |
import asyncio
from sys import version_info
import unittest.mock
from uuid import uuid4
from microengine_utils.config import EngineInfo
from microengine_utils.constants import (
SCAN_FAIL,
SCAN_NO_RESULT,
SCAN_SUCCESS,
SCAN_VERDICT,
)
from microengine_utils.errors import UnprocessableScanError
from mic... |
# -*- coding: utf-8 -*-
__author__ = "苦叶子"
"""
公众号: 开源优测
Email: <EMAIL>
"""
import sys
import codecs
from flask import current_app, session, url_for, g
from flask_mail import Mail, Message
import threading
from threading import Thread
import multiprocessing
import time
import smtplib
from email.mime.text import ... |
import datetime
import json
import time
import itchat
import requests
import sxtwl
from wxpy import TEXT
# 1. 创建一个日历函数
def getYMD(): # 获得对应的农历
ymc = [u"十一", u"十二", u"正", u"二", u"三", u"四", u"五", u"六", u"七", u"八", u"九", u"十"]
rmc = [u"初一", u"初二", u"初三", u"初四", u"初五", u"初六", u"初七", u"初八", u"初九", u"初十",
... |
from flask import Flask,render_template,request,session,redirect
from flask_sqlalchemy import SQLAlchemy
import pre_process as pp
import psycopg2
import random
import string
import os
app=Flask(__name__)
app.secret_key=os.urandom(24)
global zip_code
ENV='dev'
if ENV=='dev':
app.debug=True
a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.