text stringlengths 3.07k 12.6k |
|---|
#
# Copyright (C) 2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
#
import os
import errno
import shutil
import argparse
def copyfile(src, dst, file):
"""
This simple function copies a file named ``file`` from the ``src`` path to the ``dst`` path.
:param src: Path of the source file.
:... |
"""
A few pytests for SnailToken contract (based on snl-trade code).
(c) <NAME>, under the MIT License (MIT)
Usage:
cd ./test && pytest
Note that snl_trade must be symlinked to ../snl-trade repository.
"""
from snl_trade.contract import ContractProvider
from snl_trade.simulation import Simulation
from snl_trad... |
import time
import os
import sys
from elasticsearch import Elasticsearch
from flask import Flask, request, render_template, jsonify, redirect
from flask_assets import Environment, Bundle
from flask_restful import Resource, Api
from werkzeug.datastructures import ImmutableMultiDict
from app import app
esserver = ['192... |
"""Core."""
import threading
import logging
import sys
import pickle
import struct
import time
import argparse
import socket
from datasift.client import Client
def get_balance_metrics(balance_data, ts=None):
"""
Return a list of balance metrics.
Parsed from the [balance](http://dev.datasift.com/docs/ap... |
import numpy as np
import torch
from tensorboardX import SummaryWriter
from copy import deepcopy
import logging # 引入logging模块
logging.basicConfig(level=logging.INFO) # 设置日志级别
"""
By https://github.com/GyChou
"""
class TensorBoard:
_writer = None
@classmethod
def get_writer(cls, load_path=None):
... |
#
# Copyright (c) SAS Institute Inc.
#
# 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 w... |
import numpy as np
import torch.nn
from ivory.core.client import create_client
def test_client_repr(client):
assert repr(client) == "Client(num_instances=2)"
def test_search_run_ids(client):
run = client.create_run("rfr")
run.start("train")
run.start("test")
run_ids = list(client.search_run_ids... |
# Copyright 2018 Google Inc.
#
# 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 and the following disclaimer.
#
#... |
"""
Utility functions to generate plotly figures from dataframe. Called in app.py
"""
import plotly.graph_objects as go
import plotly.express as px
import numpy as np
import pandas as pd
import plotly.io as pio
from plotly.validators.scatter.marker import SymbolValidator
from data_input import normalize_by_population... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
@author: maryam
"""
from __future__ import division
from nltk.tag import StanfordNERTagger
import sys, os
import json
from mitie import *
from polyglot.text import Text
#reload(sys)
#sys.setdefaultencoding("utf-8")
def get_JSONfile(JSONfileName):
with... |
from django.shortcuts import render
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from django.http import HttpResponse
import json
import os
import pymongo
from py2neo import Graph, Node, Relationship, NodeMatcher, RelationshipMatch... |
import numpy as np
import math
def normalize(v):
v = np.array(v)
norm=np.linalg.norm(v)
if norm==0:
norm=np.finfo(v.dtype).eps
return v/norm
def calculateCSRotationQuaternion(lst1,lst2,matchlist=None):
if not matchlist:
matchlist=range(len(lst1))
M=np.matrix([[0,0,0],[0,0,0],[0... |
import PID
import ultrasonic_sensor as uss
import flight_control as fc
import startDrone
import pickle
import time
import numpy as np
import RPi.GPIO as GPIO
import camera
GPIO.setmode(GPIO.BOARD)
def initalise_sensors(front, left, right, rear, bottom):
global front_sensor, rear_sensor, left_sensor, ri... |
from optparse import OptionParser
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sbn
def main():
usage = "%prog"
parser = OptionParser(usage=usage)
#parser.add_option('--keyword', dest='key', default=None,
# help='Keyword argument: default=%d... |
import os
import sys
import pdb
sys.path.append(os.getcwd())
import numpy as np
import glob
import pickle as pk
import joblib
import torch
from tqdm import tqdm
from meva.utils.transform_utils import (
convert_aa_to_orth6d, convert_orth_6d_to_aa, vertizalize_smpl_root,
rotation_matrix_to_angle_axis, rot6d_t... |
## Making the code corpus
## This involves
## Hit every directory and read every supported files
## Form a corpus of words without special symbols
## Tokenize Camel case and Hungarian to split out new words
## Any word below 3 letter is not Allowed
import os
import pandas as pd
import sys
import pickle
import configpa... |
from ict.connection.node import Node as ConnectionNode
from ict.protobuf.core_pb2 import MetaMessage
from ict.protobuf.obnl_pb2 import *
class Node(ConnectionNode):
"""
This is the base class for all Nodes of the system. Improvement
"""
SCHEDULER_NAME = "scheduler"
SIMULATION = "obnl.simulatio... |
import os
import sys
import getopt
import glob
import math
import numpy as np
import random
import fabio
import multiprocessing
from popcorn.input_output import open_image
from popcorn.sixteen_bit_converter import conversion_from_list_of_files, multi_threading_conversion
from popcorn.stitching import stitch_multiple... |
import os
import sys
import numpy as np
import torch
import metric.core.config as config
from metric.core.config import cfg
import glob
from sklearn import cluster
from sklearn import mixture
import shutil
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
import pandas as pd
from scipy.spatial imp... |
#!/usr/bin/env python3
from typing import Any, Dict, List
import difflib
import os
import re
import sys
DEBUG = bool(os.environ.get("DEBUG"))
EXACT = bool(os.environ.get("EXACT"))
REPLACE_STR_DEFAULT = "\x00"
if EXACT:
REPLACE_STR = "__027b596b_2b2b_451e_b051_2130237b863f__{}__"
else:
REPLACE_STR = REPLACE_ST... |
#!/usr/bin/env python
from __future__ import print_function
import rospy
from geometry_msgs.msg import Twist
from hector_uav_msgs.srv import EnableMotors
import math
import numpy as np
from gazebo_msgs.srv import GetModelState
from dron_path import nodes
from nav_msgs.msg import Odometry
def angle_wrap(a):
## l... |
# This file is part of PyOP2
#
# PyOP2 is Copyright (c) 2012, Imperial College London and
# others. Please see the AUTHORS file in the main source directory for
# a full list of copyright holders. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted ... |
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers, Input, Model, metrics, Sequential
class AutoEncoder(tf.keras.Model):
def __init__(self, latent_dim, image_target_height, image_target_width):
super().__init__()
self.latent_dim = latent_dim
self.ima... |
# Utility script to plot images.
#
# Copyright (c) 2016 <NAME> / Erasmus MC, the Netherlands
# This code is licensed under the MIT license. See LICENSE for details.
import matplotlib.pyplot as plt
import numpy as np
# (filters, height, width)
def plot_filters(d, normalise_pixel=False, normalise_filter=False, groupdims... |
# This code is largely adapted from Udacity's CarND lectures.
# Available: https://classroom.udacity.com/nanodegrees/nd013/
import matplotlib.pyplot as plt
import cv2
import numpy as np
from HOG import feature_extract
from train import loadModel, train
from scipy.ndimage.measurements import label
import glob
debug = ... |
import threading
import requests
import copy
import os
from urllib.parse import urlparse
import queue
import time
import os
import grp
import signal
import daemon
import lockfile
from webfetch.fsutils import Fs, Action, Exists, Make, MakeDirs, View
from webfetch.fetcher import Config, Resource, Fetcher, download, fetc... |
from flask import Flask, render_template, request, session, redirect, url_for
from datetime import date,time, datetime
import sqlite3 as sql
import os
# Create Database if it doesnt exist
if not os.path.isfile('database.db'):
conn = sql.connect('database.db')
conn.execute('CREATE TABLE IF NOT EXISTS Dono... |
#<NAME>, <NAME>
'''
Generates csv files for each table used from athlete_events.csv and noc_regions.csv
'''
import csv
import sys
def main():
print("Warning: this program could take close to 20 minutes to execute")
#opens the files with a csv reader
try:
event_file = open("athlete_even... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Author: <NAME>
# @Date: Friday, November 15th 2019, 12:05:29 pm
# Adapted in February 2022 by <NAME>
import logging
import sys
import time
import numpy as np
import usb
from ibllib.graphic import popup
from pybpodapi.protocol import Bpod, StateMachine
import iblrig.bons... |
import json,os,uuid,shutil
import urllib.parse
from django.db.models.fields.related import ManyToManyField
from ApiManager.utils.file_tools import get_time_stamp
def get_report_name(projectName='',moduleName='',caseName=''):
time_stamp = get_time_stamp()
report_name = ''
if projectName == '' and moduleNa... |
# peasantProblem.py
# Date: 01/19/2021
# Course: Artificial Intelligence CSCI 0461
# Authors:
# <NAME>, <NAME>, <NAME>, <NAME>.
#
# Purpose: To implement a BFS algorithm to solve the peasant problem.
# The peasant problem:
# Move a peasant, a cabbage, a goat and a wolf from one side of the
# river to the other... |
from django.db.models import TextChoices
from json import JSONDecodeError
from .client import Client
from grades.models import Semester, Course, Grade
"""
API documentation can be found at:
https://dbh.nsd.uib.no/dbhvev/dokumenter/api/api_dokumentasjon.pdf
"""
class FilterType(TextChoices):
TOP = "top", "Topp"... |
# Copyright 2012 Viewfinder Inc. All Rights Reserved.
"""Handlers for setting/resetting staging attribute on users.
Users with the staging attribute set will have their requests routed to the staging cluster
instead of the production cluster.
ModifyStagingUserHandler: Handles most of the requests relating to admini... |
# -*- coding: utf-8 -*-
"""
Created on Sat May 16 19:20:58 2020
@author: PratikSharma
"""
# Import packages
import nltk; nltk.download('wordnet'); nltk.download('stopwords')
from nltk.stem import WordNetLemmatizer
from nltk.corpus import wordnet as wn
from nltk.corpus import stopwords
from wordcloud import WordCloud
... |
#
# gemini_python
#
# gempy.utils
# logutils.py
# -----------------------------------------------------------------------... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
this module calculates the MOS using only data from the client
* rt_1, rt
* r[t] = reportedBitrate in time [t] / max_bitrate
* srt = not_running_time / (not_running_time + execution_time)
"""
import numpy as np
from Environment.generic_ap import ... |
import pandas as pd
import urllib.request
import urllib
import re
import argparse
import pickle
import sys
import time
import os
import json
import requests
import traceback
from bs4 import BeautifulSoup
from urllib.parse import quote
from tqdm import tqdm
from functools import wraps
from joblib import Memory
from lxml... |
"""
The MIT License (MIT)
Copyright (c) 2020 <NAME>.
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, publ... |
import asyncio
import logging
import time
import aiodns
import yaml
from . import DEFAULT_STDOUT_FORMAT, parse_host
from .pf import stream_queue_status
from .graphite import TCPGraphite
from .ping import ping, ICMPResponse, AbnormalExit, ExitAfterPolicy, Unit
from .ifstats import sample
logger = logging.getLogger("p... |
"""Queryset optimization. """
import logging
import typing
import django.db.models as djm
import graphql
import graphql.language.ast as ast_
import phrases_case
if typing.TYPE_CHECKING:
class OptimizationOption(typing.TypedDict):
"""
Optimization option dict.
See :doc:`/optimize` for mor... |
# Authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# License: BSD 3 clause
import inspect
import sys
import warnings
import importlib
from pkgutil import walk_packages
from inspect import getsource, isabstract
from sklearn.base import signature
from sklearn.utils.testing import SkipTest, _get_args
from sklearn.... |
import glob
import math
import os
import pickle
import random
import re
import requests
import subprocess
import tarfile
DATA_PATH = os.path.join('..', '..', 'data')
RAW_PATH = os.path.join(DATA_PATH, 'raw')
INT_PATH = os.path.join(DATA_PATH, 'interim')
# path to reference docs
REF_PATH = os.path.join('..', '..', 're... |
import torch
import torch.nn as nn
from torch import cat
from torch.nn.functional import relu
from einops import rearrange
from functools import partial
def identity(x): return x
FAST_CUDA = False
try:
if torch.cuda.is_available():
from .cuda import fast_weight_memory
FAST_CUDA = True
except:
... |
import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from blinker import Signal
import os
class FileReference:
def __init__(self, filename):
self.filename = filename
def hash_file_reference(file_reference):
filename = file_reference.filen... |
# django
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, render, redirect, reverse
from django.http import HttpResponse
from django.contrib import auth
from django.db.models import F
from... |
# Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Helpers for using libcloud.
"""
from zope.interface import (
Attribute as InterfaceAttribute, Interface, implementer)
from characteristic import attributes, Attribute
from twisted.conch.ssh.keys import Key
from flocker.provision._ssh import run_rem... |
######################################
# Provisions Load Balancing Resources
######################################
from helpers import common
def getHealthCheck(name, region):
return {
'name': name,
'type': common.REGION_HEALTH_CHECKS_TYPE,
'properties': {
'description': 'Deplo... |
"""
Copyright (c) 2015 <NAME> and Bamboo HR 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 w... |
import urllib
from datetime import timedelta
from xml.etree import ElementTree as ET
from django.http import HttpResponse, Http404
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404
from django.utils.translation import ugettext as _
from django.utils.translation import get_lang... |
'''
Copyright (c) 2020, 2021 <NAME> <<EMAIL>>, <NAME> <<EMAIL>>
This code is free software; you can redistribute it and/or modify it
under the terms of the BSD License.
@author: <NAME>, <NAME>
@contact: <EMAIL>, <EMAIL>
'''
import sys,argparse
import os,glob,shutil
import numpy as np
import pandas as pd
import rand... |
#!/usr/bin/env python3
######################################################################
# \file
# \author <NAME> <<EMAIL>>
# \brief
#
# \copyright
# Copyright 2007-2017, by the California Institute of Technology.
# ALL RIGHTS RESERVED. United States Government Sponsorship
# acknowledged. Any commercial ... |
# MIT License
#
# Copyright (c) 2018 <NAME>
#
# 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, pub... |
#!/usr/bin/env python
# A collection of functions for calculating and plotting 3D tracer budgets.
# It is presumed in each case that the terms in the budget are known.
# Created August 2019 by <NAME> (<EMAIL>)
import xarray as xr
from matplotlib import pyplot as plt
import copy
def calc_budget(ds, terms, tend, omit=[... |
#!/usr/bin/env python
import os, sys
EXEC_NAME = "muse-calculateVolumes"
############################ FUNCTIONS ############################
### Version info
def print_version():
ver = "$Revision: 391 $"
print("@PROJECT_VERSION@ ( rev" + ver[:-1] + ")")
sys.exit(0)
# Usage info
def usage():
"""usage informa... |
from typing import Optional
import numpy as np
from numpy import ndarray
from scipy.optimize import minimize
from scipy.special import binom
import gdsfactory as gf
from gdsfactory.component import Component
from gdsfactory.geometry.functions import (
angles_deg,
curvature,
extrude_path,
path_length,
... |
import sys
import argparse
import numpy as np
import pandas as pd
import pickle
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.multioutput import MultiOutputClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.multiclass import OneVsRestClassifier
from sklearn.s... |
#!/usr/bin/env python
import roslib
from roslib import message #-
import rospy, tf
import math
import time
from PointMap import *
from CloudIterator import *
#
from geometry_msgs.msg import Twist
from tf.transformations import euler_from_quaternion
from math import degrees
# Add additional imports for each of the m... |
import factory
import names
import random
from faker import Faker
from datetime import datetime, timedelta
from vtn.models import *
import string
from django.utils import timezone
import logging
# This is necessary or else DEBUG statements for FactoryBoy will be sent to output
logging.getLogger("factory").setLevel(log... |
from pygdbmi.gdbcontroller import GdbController
def trim_by_part_and_type(response, type, part):
""" get specific data """
array = []
for item in response:
if item['type'] == type:
array.append(item[part])
return array
def initialize_session():
# Start gdb process
gdbmi =... |
# import codecs
#
#
#
# infile = codecs.open('/Users/vale/PycharmProjects/Modality/data/only_bio/0/train_prejacent_bio_1.bmes', 'r')
# target_file = codecs.open('/Users/vale/PycharmProjects/Modality/data/binary_prej/0/train_prejacent_bio_1.bmes', 'r')
# outfile = codecs.open('/Users/vale/PycharmProjects/Modality/data/0... |
#! /usr/bin/env python
#
# Backup/create encrypted/not encrypted dumps from HashiCorps's Vault secrets to json/yaml dumps
# Populate Vault from json/yaml dump
#
# ENV variables:
# VAULT_ADDR: for example: 'http://vault.vault.svc.cluster.local:8200' for k8s cluster
# ROLE_ID: RoleID for AppRole auth
# SECRET_ID: SecretI... |
# -*- coding: utf-8 -*-
"""
Functionality for parcellating data
"""
import nibabel as nib
from nilearn.input_data import NiftiLabelsMasker
import numpy as np
from neuromaps.datasets import ALIAS, DENSITIES
from neuromaps.images import construct_shape_gii, load_gifti
from neuromaps.resampling import resample_images
fr... |
# Copyright 2020 DeepLearningResearch
#
# Copyright 2017 Google Inc.
#
# 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... |
#!/usr/bin/env python3
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import sonnet as snt
import tensorflow as tf
from . import i3d
_CHECKPOINT_PATHS = {
'rgb': 'data/checkpoints/rgb_scratch/model.ckpt',
'rgb600': 'data/checkpoi... |
#!/usr/bin/env python
# coding=utf-8
"""
A simple tokenizer for MT preprocessing.
Library usage:
from util.tokenize import Tokenizer
t = Tokenizer({'lowercase': True, 'moses_escape': True})
tokenized = t.tokenize(text)
Command-line usage:
./tokenize.py [-h] [-l] [-e ENCODING] [-m] [-f FACTOR-NUM] \... |
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
import click
from spider import DistrictData
app = Flask(__name__)
# sqllite
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
# app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:19940619_Wbb@localhost:3306/test'
... |
from copy import deepcopy
from typing import Tuple, Union
from pathlib import Path
from pynars import Narsese, NAL, NARS
from time import sleep
from multiprocessing import Process
import os
from pynars.Narsese.Parser.parser import TreeToNarsese
from pynars.Narsese import Sentence
import random
from pynars.NARS import R... |
from .models import Product, Product_categories, ProductImage
from django.http import HttpResponse, Http404
from django.shortcuts import get_object_or_404
from rest_framework import viewsets, permissions
from rest_framework.response import Response
from rest_framework.renderers import JSONRenderer
from .serialize... |
import numpy as np
import random
class FloydWarshall:
def __init__(self, grid):
self.grid = grid
self.dists, self.nexts = self.__floyd_warshall(grid)
def distance(self, *indices):
(x1, y1), (x2, y2) = indices
return self.dists[self.rc_to_ind(y1, x1), self.rc_to_ind(y2, x2)]
... |
"""
A set of functions designed to work with colors and shapes for websites
"""
import hashlib
import math
# Shapes, only those in Cytoscape.js and Cytoscape desktop are included (XGMML export)
__SHAPES = ['rectangle', 'roundrectangle', 'ellipse', 'triangle',
'hexagon', 'octagon', 'diamond', 'vee', 'rhomb... |
from importlib import import_module
import pickle as pkl
import cv2
import numpy as np
import pandas as pd
import os
import torch
from tqdm import tqdm
from utils.data_utils import *
from utils.training_utils import ModelCheckpoint
from config import Config
import argparse
class ImgGenerator:
def __init__(self, ... |
"""
Utilities useful for getting information from IPs
Author: <NAME>
"""
import logging
import os
import pathlib
import random
import re
import numpy as np
import pandas as pd
import requests
import geoip2.database
import miniupnpc
import scpyutils.cacheutils as chu
from scpyutils.logutils import setup_logger
HOME... |
import turtle
import time # Time module can be used to create a delay
import random # It helps us choose random modules
delay = 0.1 # Setting delay variable to 0.1 seconds
# Score
score = 0 # Initialising variable score and high_score
high_score = 0
#Set up the screen
wn = turtle.Screen()
wn.title("Snake Game b... |
from concurrent.futures import ThreadPoolExecutor, as_completed
import numpy as np
from skbeam.core.accumulators.binned_statistic import BinnedStatistic1D
from skbeam.core.mask import margin
from pdfstream.vend.jittools import mask_ring_mean, mask_ring_median
mask_ring_dict = {"median": mask_ring_median, "mean": mas... |
import argparse
import os
import pathlib
import json
import math
import numpy as np
from tqdm import tqdm
from functools import reduce
from yellowbrick.text import TSNEVisualizer
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.decomposition import PCA
from sklearn.manifold imp... |
import wx
import wx.lib.stattext
import koko
from koko.struct import Struct
from koko.dialogs import error
from koko.fab.image import Image
from koko.c.region import Region
from koko.cam.panel import FabPanel
################################################################################... |
import base64
import binascii
import os
import struct
import zipfile
from Crypto.Cipher import AES, XOR
SECRET_FILE = 'secret.txt'
GIF_HEADER = 'GIF89a'
GIF_COMMENT_HEADER = '\x21\xfe'
GIF_COMMENT_TRAILER = '\x00'
PNG_HEADER = '\x89PNG\r\n\x1a\n'
PNG_ANC_BLOCK_TYPE = 'maTt'
AES_KEY = 'this_isnt_a_flag'
AES_BLOCK_SIZE... |
#
# Copyright (C) 2019 Google Inc.
#
# 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... |
# -*- coding: utf-8 -*-
import logging
import sys
from argparse import ArgumentParser
from collections import defaultdict
import colorlog
import yaml
from requests import exceptions
from .report import SEVERITIES
from .docker_registry import LocalRegistry, RemoteRegistry
from .docker_image import Image
from .clair imp... |
import logging
from pkg_resources import get_distribution
import numpy as np
# allow nan without warnings
# some dask warnings are still non filtered: https://github.com/dask/dask/issues/3245
np.errstate(invalid='ignore')
__version__ = get_distribution("xsarsea").version
logger = logging.getLogger("xsarsea")
logger.... |
from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.config import ConfigError
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from zope.interface import implements
from fnmatch import fnmatchcase
class RehashCommand(ModuleData):
implements(IPlugin, IMo... |
from sklearn.metrics import confusion_matrix
import pandas as pd
import numpy as np
import argparse
from classifiers import *
# Mode constants
SESSION_5 = 0
WILD = 1
STACKER = 2
# Model constants
SVM = 0
RANDOM_FOREST = 1
LOGISTIC_REGRESSION = 2
# Returns training and test data from the IEMOCAP dataset
# Training d... |
'''
Get all judgements in your private intelligence, put all result into tinyDB
with json output and csv output
resource for honeypot_tiles_demo.py
'''
import requests
import json
from crayons import *
import sys
import datetime
import sqlite3
def insert_data_to_db(data):
sql_create="CREATE TABLE IF NOT EXIST... |
"""
Extended math utilities.
"""
# Original authors from Sckit-Learn:
# <NAME>
# <NAME>
# <NAME>
# <NAME>
# <NAME>
# <NAME>
# <NAME>
# <NAME>
# License: BSD 3 clause
# This code originates from the Scikit-Learn library,
# it was since modified to... |
# -*- coding: utf-8 -*-
import os
import copy
import torch
import time
import pandas as pd
import matplotlib.pyplot as plt
class Epoch_History(object):
''' Tracking and ploting loss and acc for each epoch. '''
def __init__(self):
self.train_loss_history = []
self.val_loss_history = []
... |
from django.utils.decorators import available_attrs
from django.utils.functional import wraps
from django_facebook import settings as fb_settings
from django_facebook.api import get_persistent_graph, require_persistent_graph
from django_facebook.utils import get_oauth_url, parse_scope, response_redirect, \
has_perm... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2019 <NAME> <<EMAIL>>
#
# Distributed under terms of the MIT license.
"""Module to understand gsd files"""
import logging
from pathlib import Path
from typing import Iterator, List, Optional, Tuple
import gsd.hoomd
from gsd.hoomd import... |
#
# Image augmentation functions
#
# Adapted from:
# https://github.com/kekmodel/FixMatch-pytorch/blob/master/dataset/randaugment.py
# https://github.com/ildoonet/pytorch-randaugment/blob/master/RandAugment/augmentations.py
# https://github.com/google-research/fixmatch/blob/master/third_party/auto_augment/augmentations... |
import numpy as np
from chairs import sample, sample2, waiting_area
def map_area(data):
return np.array([[np.nan if c == "." else 0 for c in row] for row in data.split("\n")])
def analyze_chairs(m):
"""Iterate through the room & build two lists of indices.
Use a rolling window to search for empty chairs... |
import bpy
import os
import math
import random
import json
bpy.ops.wm.addon_enable(module='import_runtime_mhx2')
scene = bpy.data.scenes['Scene']
camera = bpy.data.objects['Camera']
def get_config():
with open('config.json', 'r') as f:
return json.load(f)
def init_renderer():
render = scene.render... |
# -*- coding: utf-8 -*-
try:
from ducc0.wgridder import dirty2ms, ms2dirty
except ImportError as e:
ducc_import_error = e
else:
ducc_import_error = None
import numpy as np
from africanus.util.docs import DocstringTemplate
from africanus.util.requirements import requires_optional
@requires_optional('ducc... |
import numpy as np
import time
import logging
from pprint import pprint
import matplotlib.pyplot as pt
import qcodes
import qcodes.logger as logger
from qcodes.logger import start_all_logging
from pulse_lib.base_pulse import pulselib
from pulse_lib.tests.mock_m3202a import MockM3202A_fpga
from pulse_lib.tests.mock_m3... |
from django.shortcuts import render, render_to_response
from django.template import RequestContext, loader
from django.http import HttpResponseRedirect,HttpResponse
from users.models import User
from cargo_app.models import CorporateUser
from cargo_app.models import Shipment
from IPython import embed
def e... |
# MIT License
#
# Copyright (c) 2021 TrigonDev
#
# 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... |
#!/usr/bin/env python
import numpy
import math
import ant
import types
import random
from random import shuffle
from multiprocessing import Process, Queue
# Parameters used -
# index - stores the city number
# x - x coordinate for the city i
# y - y coordinate for the city i
class City:
def __init__(self,i=0, x_c... |
from nbconvert.preprocessors import CellExecutionError
from nbconvert.preprocessors import ExecutePreprocessor
from pathlib import Path
from piper.io import list_files
from piper.utils import get_config
import json
import logging
import nbformat
import pandas as pd
import re
from typing import (
Any,
... |
# Some codes are from https://github.com/shauli-ravfogel/nullspace_projection
import sys
sys.path.append("nullspace_projection/src")
sys.path.append("nullspace_projection/")
import debias
import random
import sklearn
import numpy as np
from sklearn import cluster
from sklearn import metrics
from sklearn.manifold impor... |
import argparse
from ..training import ThanosTrainer
from ..datasets import DatasetMultiOmicsGDCTrainTest
from ..models import FC_VAE, Simple_Classifier, Adversarial_Classifier
from ..metrics import ROCRandomForest, OmicsReconstructionError
from ..utils import HParams
import json
from sklearn.model_selection import P... |
import sys
sys.path.append("../../dies/")
sys.path.append("../dies/")
import copy
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from dies.data import (
combine_datasets,
create_databunch,
ds_from_df,
split_by_date,
train_test_split_dataset,
train_test_spl... |
# Copyright 2012 <NAME>
# Copyright 2012,2013 <NAME>
#
# 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 ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.