text stringlengths 3.07k 12.6k |
|---|
"""Main class, contain entry point to use the pycalc syntax."""
from typing import Optional, List
import datetime
from .Storage import Storage
from .Data import Data, Variable
from .Manager import Register
from .operator.Addition import Addition
from .operator.BaseOperator import BaseOperator
from .type.Base64 impor... |
from sklearn.model_selection import train_test_split,StratifiedKFold
from sklearn.metrics import classification_report
from sklearn.neural_network import MLPClassifier
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn import svm
from sklearn.... |
from django import template
from jobboard.handlers.oracle import OracleHandler
from jobboard.models import Specialisation, Keyword
from member_profile.models import Schedule, Busyness, Profile
from vacancy.models import MemberOnVacancy
register = template.Library()
CHANGE_FILTERS = {'specialisation': 'specialisation... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pyburst.grids import grid_analyser
from pyburst.synth import synth
from pyburst.plotting import plot_tools
from pyburst.mcmc import mcmc_plot, mcmc_versions, mcmc_tools, burstfit
# TODO:
# - plot contours
def plot_posteriors(source, mc_vers... |
from __future__ import absolute_import, division, print_function
from collections import OrderedDict
from io import StringIO
from ctd import (
DataFrame,
Series,
derive_cnv,
lp_filter,
movingaverage,
plot_section,
rosette_summary
)
from ctd.utilities import Path, read_file
from pandas... |
"""
A GUI Ipython terminal window which can interact
with Glue. Based on code from
https://stackoverflow.com/a/9796491/1332492
and
https://stackoverflow.com/a/11525205/1332492
Usage:
new_widget = glue_terminal(**kwargs)
"""
# must import these first, to set up Qt properly
from qtpy import QtWidgets
from IP... |
from operator import attrgetter
import time
start = time.time()
with open("9.txt") as f:
input = f.read().splitlines()
#part 1
# input = ['2199943210',
# '3987894921',
# '9856789892',
# '8767896789',
# '9899965678']
noOfRows = len(input)
totalRisk = 0
for i in range(noOfRows):
noOfCols = len(inpu... |
"""
Module containing functions involed in number theory:
** isEven(x) x%2==0
** isOdd(x) x%2!=0
** isPrime(x)
** GCD(*nums) #Euclid's Algorithm for Greatest Common Divisior
** LCM(*nums) #Probably Another algorithm of Euclid, getting the Least Common Multiple
** Floa... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
#!/usr/bin/env python
# encoding: utf-8
import os
import sys
import math
import json
import pickle
import random
import numpy as np
import pandas as pd
from datetime import datetime
from datetime import timedelta
from multiprocessing import Pool
PWD = os.path.dirname(os.path.realpath(__file__))
def load_stock(s):
... |
#!/usr/bin/env python3
# Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma de
# Barcelona (UAB).
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
"""Test suite for testing CARLAUE4."""
import argparse
import glob
import i... |
import codecs
import json
import pickle
import os
import string
import sys
import numpy as np
cwd = os.getcwd()
sys.path.append(cwd)
import tqdm
def get_desc(path):
table = str.maketrans('', '', string.punctuation)
with open(path, 'r', encoding='utf8') as f:
desc = f.read()
#... |
# Copyright (c) Facebook, Inc. and its affiliates.
from math import ceil
import torch
import torch.nn.functional as functional
from seamseg.utils.parallel import PackedSequence
from seamseg.utils.sequence import pack_padded_images
class SemanticSegLoss:
"""Semantic segmentation loss
Parameters
-------... |
from datetime import date
from django.db import models
from django.db.models import Q
from simple_history.models import HistoricalRecords
from aemter.models import Funktion
class Mitglied(models.Model):
"""
Datenbankmodell Mitglied
Felder:
* name: Nachname des Mitglieds. Darf nicht null sein.
* v... |
from __future__ import absolute_import
import sys
import traceback
import cStringIO
from unittest import suite
from unittest import case
from unittest import runner
import mut
from . import actions
class MpiTestSuite(suite.TestSuite):
_instance = None
def __init__(self, *args, **kwargs):
suite.TestSuite... |
# Copyright (C) 2019-2020 Greenweaves Software Limited
# 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, me... |
# -*- coding: utf-8 -*-
#
"""
Python library for the Withings API
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Withings Body metrics Services API
<http://www.withings.com/en/api/wbsapiv2>
Uses Oauth 1.0 to authentify. You need to obtain a consumer key
and consumer secret from Withings by creating an application
here: <https:/... |
#encoding=utf8
'''
Detection with SSD
In this example, we will load a SSD model and use it to detect objects.
'''
import os
import sys
import argparse
import numpy as np
import cv2
from PIL import Image, ImageDraw
# Make sure that caffe is on the python path:
caffe_root = '../../../../caffe_train/'
sys.path.insert(0, ... |
# pylint: disable=missing-module-docstring
#
# Copyright (C) 2020 by UsergeTeam@Github, < https://github.com/UsergeTeam >.
#
# This file is part of < https://github.com/UsergeTeam/Userge > project,
# and is released under the "GNU v3.0 License Agreement".
# Please see < https://github.com/uaudith/Userge/blob/master/LIC... |
#!/usr/bin/env python3
import argparse
import logging
from odf import config, math, style, table
from odf.opendocument import load, OpenDocumentSpreadsheet
from odf.text import P
import sys
import xml.etree.ElementTree as ET
import xml.dom.minidom
logging.basicConfig(format='[%(levelname)s] %(message)s', level=loggin... |
# -*- coding: utf-8 -*-
import argparse
import sys
import logging
from cron_parser import __version__
__author__ = "<NAME>"
__copyright__ = "Kewei Duan"
__license__ = "mit"
_logger = logging.getLogger(__name__)
def isInt(astring):
""" Is the given string an integer? """
try:
int(astring)
except... |
import time
import geocoder
from textblob import TextBlob
import sys
import tweepy
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import os
import nltk
import pycountry
import re
import string
# from wordcloud import WordCloud, STOPWORDS
from PIL import Image
from nltk.sentiment.vader import Se... |
import numpy as np
import torch
from scipy.special import softmax
def prima(m, title=None):
""" Prints a matrix to the terminal """
if title:
print(title)
for row in m:
print(', '.join([str(x) for x in row]))
print('')
def path(m):
""" Returns a path matrix """
p = [list(row)... |
'''
sunkejia
main file
python main.py
'''
import datetime
import glob
import sys
import tensorflow as tf
import args as args
import dataEffect as effect
from train import Trainer
from util import ImageReader_Customize
flags = tf.app.flags
flags.DEFINE_integer("batch_size", 64, 'tarin_batch_size for one gpu')
flags.D... |
# -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
import os
from selenium.webdriver import DesiredCapabilities
from misc.browser import Driver, open_browser
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from browsers.screenshot import screenshot_website, kill_browser
from misc.setup_logger import logger
CURRENT_DIR = os.getcwd(... |
# Copyright (c) Meta Platforms, Inc. and 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 logging
from typing import List, Optional, Tuple
import torch
from pytorch3d.implicitron.tools.config i... |
from __future__ import print_function
import numpy as np
import tensorflow as tf
from six.moves import range
from data import Data
'''
**Assignment 4**
Previously in assignment02 and assignment03, we trained fully connected
networks to classify notMNIST characters.
The goal of this assignment is make the neural netw... |
"""
test.test_component_group
~~~~~~~~~~~~~~~~~~~~~~~~~
Tests the group compoments.
"""
# pylint: disable=protected-access,too-many-public-methods
import unittest
import logging
import homeassistant as ha
import homeassistant.components as comps
import homeassistant.components.group as group
def setUpModule(): # ... |
# Copyright (c) 2020 CNES
#
# All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
"""
Tidal constituents analysis
###########################
"""
from typing import List, Optional, Tuple, Union
import datetime
import numpy
from . import core
from . im... |
from . import pubmed
#import pubmed
import re
class NameParser(object):
SPACE = " "
COMMA = ","
WHITESPACE_PATTERN = re.compile(r"\s+")
NAME_CHAR = "[-a-zA-Z]"
LAST_NAME_FIRST_PATTERN = re.compile("^(%s*) ?, ?(%s*)$" % (NAME_CHAR, NAME_CHAR))
def __init__(self, name_parts):
if name_par... |
from intake.catalog import Catalog
# Need to post on intake's page to see if this would be a useful contribution...
# https://github.com/intake/intake/blob/0.6.4/intake/source/utils.py#L216
def _pattern_to_glob(pattern):
"""
Adapted from intake.source.utils.path_to_glob to convert a path as pattern into a glob... |
from __future__ import division
from builtins import zip
from builtins import range
from past.utils import old_div
from builtins import object
import numpy as np
from sherpa.astro import datastack
from sherpa.models import TableModel
from threeML.plugin_prototype import PluginPrototype
import matplotlib.pyplot as plt
... |
from __future__ import division
from textwrap import wrap
import pygame
from pygame.constants import SRCALPHA
from .base import Widget, Button
from ..utils import convert_color
class TextWidget(Widget):
def __init__(self, pos, gd, text, size=None, fontname=None, fontsize=None,
color=None):
... |
"""Ring road example."""
import numpy as np
from flow.envs import WaveAttenuationPOEnv
from flow.envs.multiagent import MultiAgentWaveAttenuationPOEnv
from flow.networks import RingNetwork
from flow.core.params import SumoParams, EnvParams, InitialConfig, NetParams
from flow.core.params import VehicleParams, SumoCarFo... |
#!/usr/bin/env python3
"""
Get OECD data.
Using the API instead of pandasdmx, as the datastructure is not directly retrievable by it.
Data is already unpivoted.
We create a datapackage preserving the data stats, whose change is used to trigger an update.
@author: giuseppeperonato
"""
import json
import logging
import... |
#!/usr/bin/env python3
from __future__ import (
division,
absolute_import,
with_statement,
print_function,
unicode_literals,
)
import os
import tqdm
import cv2
import torch
import argparse
import torch.nn as nn
import numpy as np
import pickle as pkl
from common import Config
from lib import PVN3D
f... |
# Copyright (c) 2016. Mount Sinai School of Medicine
#
# 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 o... |
# The following defined functions are used to assist in the output and calculations for data analysis.
# Please use Python 3.8.5 and import library 'myfunctions' to use the functions shown below.
from pathlib import Path
import csv
def import_csv_data(file_name, delimiter_separator):
'''Reads data from a .csv fil... |
import logging
import os
import subprocess
import sys
import mlflow
from mlflow.projects import (
RunEnvironment,
DockerRunEnvironment,
SingularityRunEnvironment,
CondaRunEnvironment
)
from mlflow.projects.submitted_run import LocalSubmittedRun
from mlflow.projects.backend.abstract_backend import Abs... |
# -*- coding: utf-8 -*-
__all__ = ['Graph']
from collections import defaultdict
from .func import Func, Result, Parameter, empty
from .evaluators import SerialEvaluator
class Graph:
active = None
_evaluator_ = SerialEvaluator
_evaluator_params_ = {}
def __init__(self, name):
self.name = nam... |
import re
import csv
from difflib import get_close_matches
from io import StringIO
import requests
from slackbot import settings
from slackbot.bot import respond_to, listen_to
from db import Session
from haro.alias import get_slack_id
from haro.botmessage import botsend
from haro.plugins.thx_models import ThxHistory
f... |
"""
Add support for the Xiaomi Gateway Radio.
"""
import logging
import voluptuous as vol
import asyncio
from functools import partial
import homeassistant.helpers.config_validation as cv
from homeassistant.components.media_player import (
MediaPlayerDevice, PLATFORM_SCHEMA)
from homeassistant.components.media_pl... |
"""
Run inference with model and plot some example results.
@author: developmentseed
pred_plot_examples.py
"""
import os.path as op
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from keras import backend as K
from keras.utils import multi_gpu_model... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, division
import os
import sys
import time
import json
import yara
import raven
import queue
import signal
import logging
import requests
import threading
from pastebot.weibo import WeiBo
logger = logging.getLogger(__name__)
_signames = dict((getattr... |
import pandas as pd
import random,time,csv
import numpy as np
import math,copy,os
from imblearn.over_sampling import SMOTE
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeRegressor,DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.ensemble ... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# Copyright 2017 <NAME> <<EMAIL>>
#
# 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... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 OpenStack 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 requ... |
"""
Author <<EMAIL>> <NAME>
Copyright 2018 SPARKL Limited
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed t... |
import logging
import torch
import numpy as np
import torch.nn as nn
from torchmetrics import F1Score
from argparse import ArgumentParser
from mypyfunc.logger import init_logger
from mypyfunc.torch_models import LSTM, F1_Loss
from mypyfunc.torch_data_loader import Streamer
from mypyfunc.torch_utility import save_check... |
# -*- coding: utf-8 -*-
from .base import BaseDataGenerator
from .single_file_3d import Gen3D
import logging
import threading
import queue
import traceback
import signal
import sys
import random
class SingleFileThread(threading.Thread):
"""
Wrapper thread for buffering data from a
single file
"""
# Lo... |
import sys
# function zone
def summary():
global water, milk, coffee_beans, disposable_cups, money
print("The coffee machine has:")
print(f"{water} of water")
print(f"{milk} of milk")
print(f"{coffee_beans} of coffee beans")
print(f"{disposable_cups} of disposable cups")
if money != 0:
... |
#!/usr/bin/env python
import argparse
parser = argparse.ArgumentParser(description="")
parser.add_argument("depth", help="tab seperated file, contig pos depth" )
parser.add_argument("png",help="output png, the name must have the .png ext",default=None)
parser.add_argument("--m5",help="an m5 output from blasr that ... |
import bpy
from mathutils import Vector
from amaranth.utils import cycles_exists
# FEATURE: Add Meshlight
class AMTH_OBJECT_OT_meshlight_add(bpy.types.Operator):
"""Add a light emitting mesh"""
bl_idname = "object.meshlight_add"
bl_label = "Add Meshlight"
bl_options = {'REGISTER', 'UNDO'}
single... |
"""
Creates the BitFlag and BitFlagType object,
which enables efficient storage of the boolean
array for each Handle catch points.
"""
from collections import OrderedDict as ODict
from sqlalchemy.types import TypeDecorator, Integer
from sqlalchemy.ext.mutable import Mutable
class BitFlag(Mutable, object):
"""
... |
##################################################
# Importando Bibliotecas/Pacotes
##################################################
# Manipulating data
import pandas as pd
import numpy as np
# visualization Libraries
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.express as px
... |
import warnings
import numpy as np
from sklearn.utils import check_array
import matplotlib.pyplot as plt
from netanalytics.random_models import ER
def clustering_coefficient(X):
degrees = np.sum(X, axis=1)
D = np.zeros(X.shape[0])
for node in range(X.shape[0]):
neighbors = np.where(X[node,:]!=0... |
#===============================================================================
'''
Project:Lecture - Structural Wind Engineering WS19-20
Chair of Structural Analysis @ TUM - <NAME>, <NAME>
Author: <EMAIL>
Description: Helper script to postprocess H5 pressure output using additional ref pressure fi... |
'''
ID3 信息增益
C4.5 信息增益/特征数 信息增益比
CART分类树 利用基尼指数做最优特征选择和最优切分点选择,终止条件:样本数少于预定阈值 样本集的基尼指数小于预定阈值 没有更多特征
总结,根据节点的分裂规则可以得出,ID3 C4.5属于极大似然估计概率模型,适合少特征,小样本。CART更加适合大样本
CART回归树(优化切分成两部分的平方误差和来寻找最佳切分点,所以也叫最小二乘回归树)
code infer:https://blog.csdn.net/slx_share/article/details/79992846
'''
#encoding=utf-8
import cv2
import time... |
"""
Test the views served by third_party_auth.
"""
import unittest
import ddt
import pytest
from django.conf import settings
from django.urls import reverse
from lxml import etree
from onelogin.saml2.errors import OneLogin_Saml2_Error
from common.djangoapps.third_party_auth import pipeline
# Define some XML namespa... |
"""Tests for fooof.core.io."""
import os
import pkg_resources as pkg
from fooof import FOOOF
from fooof.core.info import get_obj_desc
from fooof.core.io import *
###################################################################################################
######################################################... |
import copy
from typing import List, Optional
from openff.toolkit.topology import Molecule
from openff.toolkit.utils.toolkits import OPENEYE_AVAILABLE, RDKIT_AVAILABLE
from typing_extensions import Literal
def molecules_to_pdf(
molecules: List[Molecule],
file_name: str,
columns: int = 4,
toolkit: Opt... |
# This file is a part of the The Fog Development Kit (FDK)
#
# Developed by:
# - <NAME>
# - <NAME>
# - Dr. <NAME>
#
# In the Internet of Things Research Lab, Santa Clara University, CA, USA
import socket
import sys
import json
import os
import time
import subprocess
import random
# Get MAC address on <interface> and... |
import getopt
import json
import os
import sys
from typing import List
class KeyEntity(object):
def __init__(self):
self.key: str = ''
self.key_short: str = ''
self.key_upper: str = ''
self.value: str = ''
self.bool_value: bool = False
self.is_a_bool: bool = False
... |
import torch
import torchvision
import torchvision.transforms as transforms
import torch.utils.data.dataloader as dataloader
from torch.utils.data import Subset,Dataset
import torch.nn as nn
import torch.optim as optim
from torch.nn.parameter import Parameter
import numpy as np
import network as net
from random import ... |
#!/usr/bin/env python3 -u
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import pytest
from sktime.datasets import load_airline
from sktime.utils.plotting import plot_series, plot_correlations
from sktime.utils.validation._dependencies import _check_soft_dependencies
from sktime.utils.validation.serie... |
# Copyright (c) 2021 Seagate Technology LLC and/or its Affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... |
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
"""
Copyright (C) 2019. Huawei Technologies Co., Ltd. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the Apache License Version 2.0.You may not use
this file except in compliance with the License.
This program ... |
from PIL import Image, ImageFilter
import numpy as np
def get_edges_v1(array):
array = array.astype(float).sum(axis=2)
vertical_filter = np.full((array.shape[0], 3), 0, float)
vertical_filter[:, 0] = -1.0
vertical_filter[:, 2] = 1.0
horizontal_filter = np.full((3, array.shape[1]), 0, float)... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from collections import deque
from collections import defaultdict
import discord
import asyncio
import re
import gtts.lang
from discord.ext import commands
from typing import Optional, Dict, Set, Deque
import logging
from ..bot import MelosBot
from ..utils.ttss import T... |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
plt.rcParams['figure.dpi'] = 300
plt.rcParams['savefig.dpi'] = 300
######################################################################
def plot_poly_elems(ax, elems_d, facecolor='0.4', alpha=0.3, edgecolor='black', label=... |
import subprocess
import re
import sqlite3
import datetime
import time
import json
CONST_MEGA = 1000000
CONST_KILO = 1000
if_re = re.compile('^(\S*)[\s\S]*RX bytes:(\d*).*TX bytes:(\d*)')
if_list = []
interfaces = False
header = False
buffer = ""
log = []
prev_eth0_in = -1
prev_eth0_out = -1
prev_rf0_in = -1
prev_r... |
# -*- coding: utf-8 -*-
"""route entry block parsing functionality."""
from __future__ import absolute_import, unicode_literals
import re
from gettext import translation
from logging import getLogger
# l18n
_ = translation(__name__, 'locale', fallback=True).gettext
ROUTE_FILE_HEADER = re.compile(
r'''
^(\s*... |
"""Tool for generating random events on the sky."""
import argparse
from configparser import ConfigParser
import code
import logging
import numpy as np
import pandas as pd
max_iter_npoints = 1000000
min_iter_npoints = 100
info = logging.info
def num_events(rate, volume, uptime, nyears):
"""Randomly determine a n... |
#!/usr/bin/env python
# usage: completeness_check.py
__author__ = "<NAME>"
__copyright__ = "Copyright (c) 2019-2020 <NAME> All Rights Reserved."
__email__ = "<EMAIL>"
__license__ = "Apache 2"
import copy
import math
from statistics import mean, stdev
import csv
import json
import urllib
import requests
from pprint imp... |
import logging
import re
_MAIN_IDENTIFIER = "__main_config__"
MINIMUM_UPDATE_RATE = 0.001
class ConfigParseError(Exception):
pass
# class ConfigError(Exception):
# pass
def check_and_convert_type(key, value):
# float types
if key in ['update_rate', 'low_value', 'high_value', 'hide_if_over_value', 'h... |
import logging
import copy
import pathlib
from typing import IO
import argparse
import os
import logging
import yaml
try:
from yaml import CLoader as Loader
except ImportError:
from yaml import Loader
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('-sp', '--streams_path', he... |
import logging
import os
import traceback
from base64 import b64decode
import magic
from parse_emails.handle_eml import handle_eml
from parse_emails.handle_msg import handle_msg
class EmailParser(object):
"""
The core class for the EmailParser.
"""
def __init__(self, file_path, max_depth=3, parse_o... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from model.gcn import GCN
from utils.model_helper import *
class GraphVAE(nn.Module):
"""
Variational Graph Generative Model
"""
def __init__(self, config):
super(GraphVAE, self).__init__()
self.config = config
... |
import logging
import random
import numpy as np
import pandas as pd
import torch
import torch.nn.functional as F
import torch.utils.data as data
from torch.autograd import Variable
import torchvision.transforms.functional as FT
log = logging.getLogger(__name__)
INPUT_DIM = 224
MAX_PIXEL_VAL = 255
MEAN = 58.09
STDD... |
"""
This module provides tools to interact with SQLite databases.
"""
from collections import deque
from itertools import chain, repeat
import os
from sqlite3 import Connection, IntegrityError, OperationalError, ProgrammingError, Row
import traceback
import warnings
from .utils import patch_object, IGNORE, ROOT
cla... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
########################
# Import local library #
########################
sys.path.insert(1, os.path.dirname(__file__))
from util import *
from np_util import *
from mcmc import *
def log_lik_nb(
y : np.ndarray, ... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
Criado em 17 de Agosto de 2016.
Descricao: esta biblioteca possui as seguintes funcoes:
geraDados: esta funcao gera um histograma dos dados fornecida uma imagem em formato numpy
(imagem esta resultante da combinacao de uma amostra de imagens da serie de d... |
"""
Trains an agent with (stochastic) Policy Gradients on MineSweeper.
Stolen from https://gist.github.com/karpathy/a4166c7fe253700972fcbc77e4ea32c5
And https://gist.github.com/etienne87/6803a65653975114e6c6f08bb25e1522
"""
import numpy as np
import minesweeper as ms
import cPickle as pickle
# hyperparameters
H = 200 ... |
import pandas as pd
from game import Game
from player import Player
import json
def get_players():
# CSV file with all the players and every game they've played in
gl = pd.read_csv('../data/Updated_Game_Lineup.csv')
# Makes dictionary with key = player_id, value = Player object
players = get_all_p... |
import random
import time
import sys
sys.setrecursionlimit(2147000)
deck = [1,2,3,4,5,6,7,8,9,10,10,10,10]
deck = deck * 4
playerHand = []
dealerHand = []
playerValue = 0
dealerValue = 0
playerSoft = 0
dealerSoft = 0
wins = 0
loses = 0
draws = 0
hands = 100
hands2 = 100
soft17 = 0#does dealer hit s... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Provides functions for neatly printing debug information to the terminal
output, well-suited for multithreaded programs.
"""
__author__ = "<NAME>"
__authoremail__ = "<EMAIL>"
__url__ = "https://github.com/Dennis-van-Gils/python-dvg-debug-functions"
__date__ = "18-07-202... |
import rospy
import math
from frontier import Frontier
from explorer_node_base import ExplorerNodeBase
class Cell(object):
def __init__(self, coords):
# Set coordinates
self.coords = coords
# This class implements a super dumb explorer. It goes through the
# current map and marks the first cel... |
#!/usr/bin/env python
import sys
import math
from argparse import ArgumentParser
from mglib import safe_print, VERSION, API_URL, AUTH_LIST, obj_from_url, get_auth_token
import mglib.aplotter as aplotter
prehelp = """
NAME
mg-display-statistics
VERSION
%s
SYNOPSIS
mg-display-statistics [ --help, --user <... |
# coding=utf-8
# Copyright 2019 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 torch
import pickle as pkl
import random
import cv2
import numpy as np
def non_max_sup(dets, thresh):
x1 = dets[:, 0]
y1 = dets[:, 1]
x2 = dets[:, 2]
y2 = dets[:, 3]
scores = dets[:, 4]
areas = (x2 - x1 + 1) * (y2 - y1 + 1)
_, order = torch.sort(scores, descending=True)
keep =... |
import scrapy
from scrapy.crawler import CrawlerProcess
from scrapy.loader.processors import MapCompose, TakeFirst, Identity
import sys
import pymongo
from pymongo import ReplaceOne
import json
import logging
import credentials
import datetime
category = sys.argv[1]
hours = sys.argv[2]
categories = {
"1": "Hardw... |
#!/usr/bin/env python
# Built-in imports
import time
import sys
import numpy as np
import socket
# Own imports
import face_detect_hc as fdhc
import baxter_vision_mapping.baxter_camera_complete_transform as bcp
# General module imports
import rospy
import rosgraph
import cv2 as cv
import cv_bridge
from baxter_interf... |
import numpy as np
import time
import os
from PIL import Image
from photo_mosaic.image_stitcher import ImageStitcher
from photo_mosaic.tile_processor import TileProcessor
from photo_mosaic.progress_bar import parallel_process
def get_unique_fp():
return 'mosaic_{}.jpg'.format(int(time.time() * 1000))
def eucl... |
import sys
import argparse
from collections import OrderedDict
from utils import *
def load_train_data(train_dir, batch_size):
train_transforms = transforms.Compose([transforms.RandomRotation(30),
transforms.RandomResizedCrop(300),
... |
#!/usr/bin/python3
#
# Copyright 2017, The Android Open Source Project
#
# 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 b... |
from aiogram import types
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.state import State, StatesGroup
from misc import dp, bot
from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, ReplyKeyboardRemove
import req
import markup
from aiogram.dispatcher.filters import Text
import data... |
#!/usr/bin/env python
# coding: utf-8
# # GenCode Explore
#
# Explore the human RNA sequences from GenCode.
#
# Assume user downloaded files from GenCode 38 [FTP](http://ftp.ebi.ac.uk/pub/databases/gencode/Gencode_human/release_38/)
# to a subdirectory called data.
#
# Build on 102 which excluded mitochondrial gene... |
import time
import os
import sys
import filecmp
import numpy
import shutil
import readline
import logging
import ConfigParser
from ast import literal_eval
import glob
import collections
import casadef
# Read configuration file
def read_config(configfile):
'''
Parses the configuration file of parameters passed... |
# -*- coding: utf-8 -*-
import string
import StringIO
import csv
import transaction
from logging import getLogger
from Acquisition import aq_inner
from five import grok
from zope.lifecycleevent import modified
from zope.component import getUtility
from plone.directives import form
from z3c.form import button
from z3... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.