text stringlengths 3.07k 12.6k |
|---|
import re
import operator
import sys, getopt
import os
import pandas as p
import numpy as np
import random
import scipy.stats as ss
import scipy as sp
import scipy.misc as spm
import scipy.special as sps
import math
from operator import mul, truediv, eq, ne, add, ge, le, itemgetter
def elop(Xt, Yt, op):
X = np.co... |
import numpy as np
def sigmoid_function(x):
# Activation function: f(x) = 1 / (1 + e ^ (-x))
return 1 / (1 + np.exp(-x))
def mse_loss(y_true, y_pred):
# y_true/y_pred: numpy arrays of same length
return ((y_true - y_pred) ** 2).mean()
def derive_sigmoid(x):
# Sigmoid derivative: f'(x) = f(x) * (1... |
from flask import Flask, render_template, request, redirect, url_for, flash, jsonify
app = Flask(__name__)
# -- Database connection --
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Base, Restaurant, MenuItem
# Using '?check_same_thread=False' to preven... |
import os
import numpy as np
import cv2
import matplotlib.pyplot as plt
# from utils import yuv2rgb_np
# import tensorflow as tf
# from tensorflow.data import Iterator
# from Dataset import SegDataLoader
def visulize_npy_result(log_dir):
save_dir = os.path.join(log_dir, 'test')
if not os.path.exists(save_dir):... |
import itertools
import re
import sys
import operator
from collections import defaultdict, namedtuple
from dataclasses import dataclass
from itertools import product
from math import prod
from typing import List, Dict, Any, Tuple, Set
import aocd
from advent_of_code_ocr import convert_6
from . import aoc_year
from log... |
import os
import re
import sys
import logging
import click
import difflib
from jinja2 import Environment, FileSystemLoader, StrictUndefined
from .helpers.config_parser import parse_config, patch_config
from .helpers.helpers import get_all_source_data, diff_backup_and_replace, get_global_variables
from .version import v... |
# -*- coding: utf-8 -*-
import os
import pickle
import shutil
import zipfile
from threading import Lock
lock = Lock()
def legitimize(text):
"""Converts a string to a valid filename.
"""
import platform
os_ = platform.system()
# POSIX systems
text = text.translate({
0: None,
or... |
'''Python implementation of Operational Transform(OT) text type
Original:
https://github.com/ottypes/docs
https://github.com/ottypes/text/blob/master/lib/text.js
'''
OP_SKIP = 0
OP_DELETE = 1
OP_INSERT = 2
def _resolve_op(op):
if isinstance(op, int):
return (OP_SKIP, op)
elif isinstance(op, dict):
... |
'''Module to make metrics for evaluating reco'''
import numpy as np
import matplotlib.pyplot as plt
import tensorflow_probability as tfp
import tensorflow as tf
def angle(pred, true):
pred, true=tf.cast(pred, tf.float32), tf.cast(true, tf.float32)
return tf.math.acos(
tf.clip_by_value(
... |
"""Create all tables
Revision ID: 26e24938c75b
Revises:
Create Date: 2021-04-24 14:43:41.613345
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generat... |
"""Element and grid objects for implementing solar cell dynamic grid
optimization model that uses power debt messaging to update current flow and
wire scaling."""
# import logging
# from collections import deque
import autograd.numpy as np
# from autograd import grad
from .dynamic_grid import Element, Grid
from .util... |
"""
"""
import pypylon.pylon as pylon
import pypylon.genicam as geni
import os
import time
import logging
import sys
import numpy as np
from collections import deque
import csv
def OpenCamera(cam_params, bufferSize=500, validation=False):
n_cam = cam_params["n_cam"]
cam_index = cam_params["cameraSelection"]
camer... |
# ToDo: Those classes need refactoring, I dont like them
from __future__ import annotations
import itertools
from dataclasses import dataclass, field
from enum import Enum, Flag, auto
from typing import List, Optional, Sequence, TYPE_CHECKING
from mcscript.exceptions.exceptions import McScriptArgumentError
from mcscr... |
##
# Print JUnit Test Results.
#
# - Description: Only prints iOS-formatted results (AllTests > Suites > Subsuites > Cases).
#
# - Usage:
# - `python3 PrintBluepillJUnitResults.py <XML file>`
#
# - Arguments:
# - JUnit results XML file
# - [optional] Format (e.g. "terminal" or "slack") (default: "terminal")
#
# -... |
#-*- coding=utf-8 -*-
#@Time : 2020/9/30 5:59 PM
#@Author : 小邋遢
#@File : dongbei_expert_spider.py
#@Software : PyCharm
import json
import os
from urllib.request import urlretrieve
import requests
import re
from expert.config import *
import pymysql
import pandas as pd
import time
def parse_expert_id(url):
r = req... |
import tensorflow as tf
from ..modules.attention import BaseAttention
class ConvBlock:
def __init__(self, filters, alpha, kernel=3, strides=1):
self.filters = filters
self.alpha = alpha
self.kernel = kernel
self.strides = strides
def __call__(self, x):
filters = int(se... |
import numpy as np
import h5py
import json
sys.path.append('F:\Linux')
import illustris_python as il
import matplotlib.pyplot as plt
def Flatness(MassTensor):
#c / a = (M3)**0.5 / (M1)**0.5
return np.sqrt(MassTensor[0]) / np.sqrt(MassTensor[2])
def BtoA(MassTensor):
#b / a = (M2)**0.5 / (M1)... |
from bs4 import BeautifulSoup
import json
import requests
import sys
def FormatAPN(apn):
return '{0}-{1}-{2}-{3}-{4}-{5}-{6}-{7}'.format(apn[0:2], apn[2:5], apn[5:7], apn[7:9], apn[9:11], apn[11], apn[12:14], apn[14:len(apn)])
def ExtractJSONAPNS(fileloc):
file = open(fileloc, 'r')
extractedJSON = json.JSONDecode... |
##############################################################################
# Some functions to make Monte-Carlo simulations smoother
# Authored by <NAME>, 29/10/2018
# e-mail: <EMAIL>
##############################################################################
# Copyright 2018 @CentraleSupelec
#
# Licensed under ... |
#! python3
import os
import struct
import logging as log
from PIL import Image, ImageDraw, ImageColor
# Debug Setting
log.basicConfig(level=log.DEBUG, format='%(asctime)s | %(levelname)s | %(message)s')
heatmap = [
'#000000',
'#142966', '#152a67', '#152b68', '#152e6a', '#152f6b', '#15326d', '#15356f', '#15387... |
#!/usr/bin/env python
"""Installer for gemini: a lightweight db framework for disease and population genetics.
https://github.com/arq5x/gemini
Handles installation of:
- Required third party software
- Required Python libraries
- Gemini application
- Associated data files
Requires: Python 2.7 (or 2.6 and argparse),... |
# Third-party libraries
import numpy as np
from tensorflow.contrib.learn.python.learn.datasets import base
from tensorflow.python.framework import random_seed
# DataSet class
class DataSet(object):
def __init__(self, inp, tar, seed=None):
seed1, seed2 = random_seed.get_seed(seed)
np.ra... |
import numpy as _np
from mpi4py import MPI as _MPI
from jax import abstract_arrays, core
from jax.core import Primitive
from jax.interpreters import ad, xla
from jax.lib import xla_client
from jax.lax import create_token, stop_gradient
from ..utils import (
HashableMPIType,
_constant_s32_scalar,
_constant... |
import math
from networktables.util import ntproperty
import wpilib
import ctre
class PhysicsEngine:
rr_degrees = ntproperty("/SmartDashboard/drive/rr_module/degrees", 0)
lr_degrees = ntproperty("/SmartDashboard/drive/rl_module/degrees", 0)
rf_degrees = ntproperty("/SmartDashboard/drive/fr_module/degree... |
#!/usr/bin/env python
import io
import os
import subprocess
import sys
def read_until(f, char):
result = b''
while True:
next = f.read(1)
if next != char:
result = result + next
else:
break
return result
def parse_status(f):
def type(char):
retu... |
#!/usr/bin/env python
import sys
import os
import os.path
import unittest
from I3Tray import I3Tray
from I3Tray import I3Units
import icecube.icetray
import icecube.dataio
import icecube.clsim
import icecube.clsim.shadow.cylinder_utils
import icecube.dataclasses
import icecube.phys_services
import icecube.simclasse... |
#!/usr/bin/env python
import datetime
import logging
import smtplib
import sys
import traceback
import urllib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import argparse
import requests
def check_arg(args=None):
parser = argparse.ArgumentParser(description="Script to get R... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import ConfigParser
import telegram
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, Job
import logging
import os
import urllib2
import json
from datetime import datetime
CONFIG_FILE = 'unni.cfg'
config = ConfigParser.ConfigParser()
config.read(CO... |
import cv2
import numpy as np
from numba import vectorize, float32, float64, jit, boolean
from math import sqrt
from pppr.aabb import IoU
def convert_aabb(aabb):
"""
(tx, ty, bx, by) => (tx, ty, w, h)
:param aabb:
:return:
"""
tx = aabb[0]
ty = aabb[1]
w = aabb[2] - tx
h = aabb[3] ... |
import xarray as xr
import pandas as pd
import numpy as np
def to_deltas(dt):
"""
Convert from delta-ts to time steps
:param dt: range of delta ts
:return: range of time steps
"""
dts = [dt[0]]
for i in range(1, len(dt)):
dts.append(dts[i-1]+dt[i])
return np.array(dts)
def cr... |
#
# ジャイロ加速度センサー(SH200Q).
# 動作未確認.
#
##################################################
# import
##################################################
import lcd
from machine import I2C
##################################################
# constants
##################################################
SH200Q_A... |
import datetime
from django.conf import settings
from django.contrib.auth.models import Group, User
from django.core import mail
from django.utils.timezone import now
from mock import patch
from nose.tools import eq_, ok_
from test_utils import TestCase
from remo.profiles.tests import UserFactory
from remo.remozilla... |
#-*-encoding: utf-8 -*-
import glob
import os
import os.path as path
from PIL import Image
import scipy.io as scio
import numpy as np
import scipy.ndimage
import pickle
from tqdm import tqdm
# gauss kernel
def gen_gauss_kernels(kernel_size=15, sigma=4):
kernel_shape = (kernel_size, kernel_size)
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Version of WMCore/Services/Rucio intended to be used with mock or unittest.mock
"""
from __future__ import print_function, division
from future.utils import listitems
# from builtins import object # avoid importing this, it beraks things
import json
import logging
impo... |
#!/usr/bin/env python3
# coding = utf-8
########################################################################################
## (c) https://github.com/Pet-Series
## https://github.com/Pet-Series/pet_ros2_lightbeacon_pkg
##
## Maintainer: <EMAIL>
## The MIT License (MIT)
##
## Input: Subscribe to ROS2-topics
##... |
from collections import defaultdict
from typing import NamedTuple, Iterable
import requests
from wistia.schema import Media, CaptionTrack, Project
from wistia.client import WistiaClient
import logging
log = logging.getLogger(__name__)
class FakeResponse(NamedTuple):
status_code: int
class DummyWistiaClient... |
#!/usr/bin/env python3
# rpi_ws281x library strandtest example
# Author: <NAME> (<EMAIL>)
#
# Direct port of the Arduino NeoPixel library strandtest example. Showcases
# various animations on a strip of NeoPixels.
import time
from rpi_ws281x import *
import argparse
from config import *
the_strip = None
def rea... |
__author__ = "konwar.m"
__copyright__ = "Copyright 2022, AI R&D"
__credits__ = ["konwar.m"]
__license__ = "Individual Ownership"
__version__ = "1.0.1"
__maintainer__ = "konwar.m"
__email__ = "<EMAIL>"
__status__ = "Development"
import cv2
import numpy as np
import utility.KITTI.kitti_util as utils
from utility.KITTI.k... |
from logger import logger
from xml.etree import ElementTree
from common_utils.path_utils import get_all_files_of_extension, get_rootname_from_path
class Source:
def __init__(self, database: str):
self.database = database
class Size:
def __init__(self, width: int, height: int, depth: int):
self... |
#!/usr/bin/env python3
import argparse
import random
import socket
from my_utils import *
def connect_to_servers(srv_address_port):
# attempt to connect to the servers in srv_address_port
# remove the servers that are unreachable from the list
servers_down = []
socket_list = []
for (add, port) in ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import time
import numpy as np
import tensorflow as tf
from collections import namedtuple
from tensorflow.python.training import moving_averages
flags = tf.app.flags
FLAGS = flags.FLAGS
class Model(object):
def __init__(self, **kwargs):
allowed_kwa... |
import re
lookup_table = {}
def get_name_identifier(name):
try:
return lookup_table[name]
except KeyError:
new_id = len(lookup_table) + 1
lookup_table[name] = new_id
return new_id
def compute_arithmetic_lexeme(lexeme):
match = re.match('^([-+])?(.+?)$', lexeme)
unary... |
# import numpy as np
import os
# %%PARAMS
from cup_project.config import data_dir, reportings_dir, log_dir
import ampligraph
print(ampligraph.__version__)
KEYSPACE_NAME = "cup_1747_1" # cup_100_1 cup_200_2 cup_1000_1
# KEYSPACE_NAME = "cup_1"
# %% Dirs variables
_3ples_directory = data_dir / "proce... |
##Grab this from Thomas
##http://www.geophysique.be/2011/02/20/matplotlib-basemap-tutorial-09-drawing-circles/
#
# BaseMap example by geophysique.be
# tutorial 09
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np
### PARAMETERS FOR MATPLOTLIB :
import matplotlib as mpl
mpl... |
"""
process_file_view
~~~~~~~~~~~~~~~~~
View for processing the full file.
"""
import tkinter as tk
import tkinter.ttk as ttk
import tkinter.messagebox as tkmessagebox
from . import util
_text = {
"loading" : "Loading...",
"loading2" : "Attempting to load entire file using current settings",
"cancel" : "... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import svm, tree
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.cluster import KMeans
from sklearn.cluster import DBSCAN
from sklearn.metrics import silhouette_score
from skle... |
from flask import Blueprint, render_template, flash, current_app
from flask_login import login_required
from flask_wtf import FlaskForm
from wtforms import StringField, SelectField, SubmitField
from wtforms.validators import DataRequired, Length
from flask_wtf.file import FileField, FileAllowed
from werkzeug.utils imp... |
# -*-coding:utf-8 -*-
import json
import random
import threading
import time
import uuid
from collections import defaultdict
import dwebsocket
from django.http import HttpResponse
from django.shortcuts import render
from dwebsocket import accept_websocket, require_websocket
from rec.tankgame.room import Room
from rec.t... |
import pytest
import datetime
import json
import pandas as pd
import numpy as np
from tabloo.backend import Backend, to_json, convert_column
@pytest.fixture
def df_simple():
df = pd.DataFrame({
"A": [1, 3, 2],
"B": [6, 5, 4],
})
df = df[sorted(df.columns)]
return df
@pytest.fixtur... |
from __future__ import absolute_import
import random
import socket
from datetime import datetime
import mock
from django.test import TestCase
from rest_framework import serializers
from celery_rpc.base import DRF3
from .. import config, utils
from ..client import Client
from .utils import SimpleModelTestMixin
clas... |
import sys
import os
import logging
import time
from typing import Union, Tuple
import winsound
import win32gui
import win32ui
from ctypes import windll
import pygetwindow as gw
import numpy as np
import cv2
from PIL import Image
import waiting
def screen_window(hwnd: int) -> Union[str, None]:
"""
Original:... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, division, print_function, absolute_import
import re
import logging
import time
import datetime
import pydub # https://github.com/jiaaro/pydub
from google.cloud import storage
from google.cloud.exceptions import NotFound
from google.cloud import speech
fr... |
from rpi_ws281x import * #import for led driving
import time
import sys
import random as r
#Block for setting up the actual LEDs, hardware definitions etc...
LED_COUNT = 150*1 #150 lights per strip...
LED_PIN = 21 #GPIO pin
LED_FREQ_HZ = 800000 #light signal requency
LED_DMA = 10 #dma pin internally
LED_BRIGHTNESS = ... |
# Copyright 2016 datawire. 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 applicable law or agr... |
"""
Reformat data for simulated SNRs by <NAME> from TXT to ECSV
"""
import numpy as np
import astropy.units as u
from astropy.table import Table, Column
from gammapy.utils.coordinates import galactic as compute_galactic_coordinates
import numpy as np
def read_txt_files(version):
filename = 'test_roberta_september_... |
import numpy as np
import pandas as pd
import pickle
num_cores = 4
import multiprocessing as mp
import time
nboot=200
from sklearn.utils import resample
from sklearn import linear_model
C=1
seed = 42
tol=1e-3
model = {"Logistic Regression" :
linear_model.LogisticRegression(
C=C,
penalty='l1',
solver="liblinear... |
import re
import json
from collections import Counter
from transition_amr_parser.amr import JAMR_CorpusReader
import ast
import xml.etree.ElementTree as ET
def read_frame(xml_file):
'''
Read probpank XML
'''
root = ET.parse(xml_file).getroot()
propbank = {}
for predicate in root.findall('... |
from __future__ import absolute_import
from django.core.exceptions import PermissionDenied
from django.contrib import messages
from django.contrib.auth import logout
from django.contrib.auth.decorators import permission_required, login_required
from django.urls import reverse
from django.http import HttpResponse, HttpR... |
#! /usr/bin/env python
import functions as fn
def load_dictionary(filename, key_col, value_col):
file = open(filename)
dictionary = dict()
for line in file:
line=line.rstrip("\n")
fields = line.split("\t")
key = fields[key_col]
value = fields[value_col]
hpo_l = value.split(", ")
if key not in dictio... |
import logging
import os
from unittest import TestCase
from intent.igt.consts import ODIN_LANG_TAG, ODIN_JUDGMENT_ATTRIBUTE, ODIN_TRANS_TAG
from xigt.codecs import xigtxml
from intent.igt.rgxigt import RGCorpus, retrieve_normal_line, retrieve_lang_phrase_tier, retrieve_trans_phrase
from intent.interfaces.stanford_par... |
#!/usr/bin/env python3
# Copyright 2021 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.
import argparse
import json
import logging
import os
import pandas as pd
import plistlib
def GetDictionaryKeys(value, keys):
""" ... |
import logging, os
import json
from kiteconnect import KiteTicker
# from db import insert_ticks
import sqlite3
from datetime import datetime
from dateutil import tz
API_KEY = os.getenv("API_KEY")
API_SECRET = os.getenv("API_SECRET")
ACCESS_TOKEN = os.getenv("ACCESS_TOKEN")
DB_FILE = f"{os.getenv('DB_FIL... |
#
# mobilenet.py
# <NAME> <<EMAIL>>
#
# Copyright (C) 2019 University of Bologna
# All rights reserved.
#
# This is an implementation of the quantized mobilenet built from
# https://github.com/marvis/pytorch-mobilenet/blob/master/main.py
#
import PIL
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
imp... |
# ## Control ED with direct input
# ### Get latest keybinds file
from sys import platform
from os import environ, listdir
from os.path import join, isfile, getmtime
from xml.etree.ElementTree import parse
from pynput.keyboard import Key, Controller as KeyController
from pynput.mouse import Button, Controller as Butto... |
import copy
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class Bert_Dialogue(nn.Module):
def __init__(self, bert, opt):
super(Bert_Dialogue, self).__init__()
self.opt = opt
self.bert = bert
self.dropout = nn.Dropout(opt.dropout)
self.gcn_dr... |
r"""Exp 7: Demonstrate the effect of bucketing on Krum
- Fix:
- n=20, f=3
- m=0
- Number of iterations = 1200
- Aggregator: Krum
- Not *Long tail* (alpha=1)
- Always NonIID
- Number of runs = 1
- LR = 0.01
- ATK= LF
Experiment:
- bucketing: 0, 2, 3
"""
import json
import loggin... |
"""
MIT License
Copyright (c) 2020 GamingGeek
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, publish, dis... |
import asyncio
import logging
import ssl
import aiojobs
from aiohttp import web, WSMsgType, WSCloseCode
log = logging.getLogger(__name__)
class InvalidPortError(Exception):
pass
class Proxy(object):
def __init__(self, ws, protocol, port, loop):
if protocol != 'TCP':
raise NotImplemente... |
#!/usr/bin/env python2
# -*- coding: utf8 -*-
import uuid
from typing import List, Any
from functools import wraps
def auth(func):
"""验证"""
@wraps(func)
def wapper(who: User, what: Target, check: bool = False):
user_roles = who.get_roles()
work_roles = []
# 获取可用的 role
f... |
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch import optim
from torchvision import datasets, models
import torchvision
import numpy as np
import math
import argparse
from copy import deepcopy
import torchvision.transforms as transforms
from cifar_generator import CIFAR10
## train: t... |
#!/usr/bin/env python3
import collections
import itertools
import sys
import ptb
MAX_CONSTITUENT_LENGTH = 3
def transform(t):
ptb.remove_empty_elements(t)
ptb.simplify_labels(t)
return ptb.add_root(t, 'ROOT')
def trees(filename):
with open(filename) as f:
for t in ptb.parse(f):
... |
import random
import functools
import matplotlib.pyplot as plt
import numpy as np
import copy
# default functions ----------------------------------------------------------------------
def random_individual():
"""Generate a random individual phenotype"""
return [random.randrange(0,2) for i in range(10)]
def... |
from dataclasses import dataclass
from enum import Enum
from typing import List, Dict, Optional, Union
from .attr import Attr
class DataType(Enum):
xsd_decimal = "xsd:decimal"
xsd_anyURI = "xsd:anyURI"
xsd_gYear = "xsd:gYear"
xsd_dateTime = "xsd:dateTime"
xsd_int = "xsd:int"
xsd_string = "xsd... |
"""Transforms for Panoptic FPN."""
from __future__ import absolute_import
import copy
from random import randint
import mxnet as mx
import numpy as np
from .. import bbox as tbbox
from .. import image as timage
from .. import mask as tmask
__all__ = ['transform_test', 'load_test',
'PanopticFPNDefaultTrai... |
# coding: utf-8
# MIT License
#
# Copyright (c) 2018 <NAME>, 4IF, INSA Lyon
#
# 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... |
# Copyright (C) 2008 Abiquo Holdings S.L.
#
# 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... |
'''
Adapted from https://github.com/sthalles/SimCLR/tree/master/data_aug
'''
import os, time
import torch
import numpy as np
from torch.utils.data import DataLoader
from torch.utils.data.sampler import SubsetRandomSampler
import torchvision.transforms as transforms
from data_aug.gaussian_blur import GaussianBlur
from t... |
"""
Intended for use in Jupyter notebooks like:
%run -m datasci.notebook.init
Or:
from datasci.notebook.init import *
"""
# pylint: disable=unused-import
# stdlib
import sys
import os
import re
import math
import time
import random
import logging
import gzip
import json
import operator
import itertools
import... |
from datetime import datetime
from django.shortcuts import render
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseRedirect
from django.forms import ModelForm
from django.views.generic import UpdateView, DeleteView
from crispy_forms.helper import FormHelper
from crispy_fo... |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
from typing import Any, Dict, List, Type, Union
import pytest
import yahp as hp
import composer.callbacks
import composer.loggers
import composer.profiler
from composer import Callback
from composer.callbacks import EarlyStopper, Memory... |
skip_training = False
import os
import numpy as np
import matplotlib.pyplot as pl
import torch
import torchvision
import torch.nn as nn
from torch.nn import functional as F
from torchvision import transforms
import torchvision.utils as utils
data_dir = "."
if torch.cuda.is_available() and not skip_training:
de... |
#! /usr/bin/python3 -i
# coding=utf-8
import os,time,numpy,joblib.numpy_pickle
from spacy.symbols import LEMMA,POS,TAG,DEP,HEAD
from spacy.tokens import Doc
from spacy.language import Language
from spacy_combo.utils import Token,Tree
PACKAGE_DIR=os.path.abspath(os.path.dirname(__file__))
DOWNLOAD_DIR=os.path.join(PAC... |
#!/usr/bin/env python2.7
# Copyright 2020 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import sys
import unittest
from host import Host
from fuzzer import Fuzzer
# This file contains the top-level implementat... |
from base64 import b64decode, b64encode
from collections import OrderedDict
from html.entities import name2codepoint
from datetime import timedelta
from dateutil.parser import parse
from enum import Enum
import re
from twisted.words.protocols.irc import assembleFormattedText as colour, attributes as A
graySplitter =... |
# coding: utf-8
import numpy as np
import torchvision
import time
import os
import copy
import pdb
import time
import argparse
import sys
import cv2
import torch
from torch.utils.data import Dataset, DataLoader
from torchvision import datasets, models, transforms
from retinanet.dataloader import CocoDataset, CSVDat... |
# Copyright: <NAME> <<EMAIL>>
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
from aqt.qt import *
from operator import itemgetter
from aqt.utils import showInfo, askUser, getText, maybeHideClose, openHelp
import aqt.modelchooser, aqt.clayout
from anki import stdmodels
from aqt.utils imp... |
import numpy as np
import matplotlib.pyplot as plt
#Entry point into the program
def main():
epochs = 30
learning = 0.1
batch = 300
#load data into matrices
pre_data = np.loadtxt(open("mnist_train.csv", "rb"), delimiter=",", skiprows=1)
pret_data = np.loadtxt(open("mnist_test.csv", "rb"), delimiter=",", skiprows... |
# coding=utf-8
# Copyright 2020 The Google Research 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 applicab... |
import flask
import flask.json
import common.url
import common.rpc
from www import server
from www import login
from www import history
import re
import datetime
import pytz
import asyncio
import sqlalchemy
@server.app.route('/spam')
@login.require_mod
async def spam(session):
link_spam = "link_spam" in flask.reques... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from __future__ import print_function
import h2o
import sys
sys.path.insert(1,"../../../") # allow us to run this standalone
from h2o.estimators.random_forest import H2ORandomForestEstimator
from h2o.estimators.gbm import H2OGradientBoostingEstimator
from h2o.estimato... |
# -*- coding: utf-8 -*-
""" Fast EER computation """
__author__ = "<NAME>"
__copyright__ = "Copyright 2020, <NAME>"
__license__ = "Apache 2.0"
import numpy as np
def precise_eer(negative_scores, positive_scores):
"""Linear complexity EER computation
Args:
negative_scores (numpy array): impostor sc... |
################################################################################
# Copyright (c) <NAME> - CEA (<EMAIL>)
# All rights reserved.
#
# 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 Softwar... |
# ------------------------------------------------------------------------------
# CodeHawk C Source Code Analyzer
# Author: <NAME>
# ------------------------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2017-2020 Kestrel Technology LLC
#
# Permission is hereby granted... |
from rubik_solver.Move import Move
from rubik_solver.Cubie import Cube
from rubik_solver.Cubie import Cubie
from rubik_solver.Solver import CFOP
from rubik_solver.Solver.CFOP.F2LSolver import F2LSolver
from rubik_solver.Solver.CFOP.OLLSolver import OLLSolver
from rubik_solver.Solver.CFOP.PLLSolver import PLLSolver
from... |
#!/usr/bin/env python3
import argparse
import time
import json
import math
import sys
import os
import csv
parser = argparse.ArgumentParser(
description='Read a CSV file and combine <span> rows. For each selected column, an extra column is calculated. Other columns containing numerical values are replaced by the... |
## Code author SP
###########
### Python libraries
############
# uncomment below two rows when running code for the first time. This is to create these folders in the cwd.
#os.mkdir(path_python+'/count_data')
#os.mkdir(path_python+'/figures_python')
import sys
import numpy as np
np.set_printoptions(threshold=sys.... |
# convert the omimGene2 sql table format to bigBed format with a mouse over string
import sys, os
def inhModeToCode(inhModes):
inhCodes = []
inhModes = inhModes.split(", ")
for inhMode in inhModes:
inhMode = inhMode.strip("?")
if inhMode == "":
inhCode = ""
elif inhMode ... |
def coding_problem_06():
"""
An XOR linked list is a more memory efficient doubly linked list.
Instead of each node holding next and prev fields, it holds a field named both, which is a XOR of the next node
and the previous node. Implement a XOR linked list; it has an add(element) which adds the element... |
#! /usr/bin/env python
##############################################################################
## DendroPy Phylogenetic Computing Library.
##
## Copyright 2010-2015 <NAME> and <NAME>.
## All rights reserved.
##
## See "LICENSE.rst" for terms and conditions of usage.
##
## If you use this work or any portio... |
import cv2
import dlib
DETECTOR = dlib.get_frontal_face_detector()
def get_face_bounds(img):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
rects = DETECTOR(gray, 1)
return rects
def resize(img, size_x, size_y=None):
size_y = size_y or size_x
h, w = img.shape[:2]
if size_y < h or size_x < w:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.