content stringlengths 5 1.05M |
|---|
from utils.print import print_block
import pandas as pd
from utils.prediction import PredictionType
def generate_cf_for_all(packs, cf_func, feature_names):
output_column_names = [f'orgin_{f}' for f in feature_names] + [
f'cf_{f}' for f in feature_names] + ['time(sec)'] + ["prediction_type"]
# Create... |
"""Test aspects of lldb commands on universal binaries."""
import os, time
import unittest2
import lldb
from lldbtest import *
import lldbutil
class UniversalTestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
def setUp(self):
# Call super's setUp().
TestBase.setUp(self)
# F... |
from .baseinternal import BaseInternal
from math import sin, cos, radians, sqrt
class LiquidRing(BaseInternal):
def __init__(self):
return
def draw(self, ctx):
if self.parent is None:
Warning("Internal has no parent set!")
return
unit = self.parent
li... |
# Copyright 2016 Isotoma 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 to in writing... |
def main():
n = int(input())
x,y = map(int,input().split())
k = int(input())
a = list(map(int,input().split()))
a.append(x)
a.append(y)
if len(a) == len(list(set(a))):
print("YES")
else:
print("NO")
if __name__ == "__main__":
main() |
#!/usr/bin/env python
"""
Reads output of Transcar sim, yielding Incoherent Scatter Radar plasma parameters.
python transcar2isr.py tests/data/beam52
"""
from pathlib import Path
from matplotlib.pyplot import show
from argparse import ArgumentParser
from datetime import datetime
#
import transcarread.plots as pl... |
import numpy as np
from common.constant import *
from common.clusteringAlgorithms import ClusteringAlgorithm
from utils.distance import get_EuclideanDistance_matrix
class FCMA(ClusteringAlgorithm):
def __init__(self, X : np.ndarray, cluster_num : int, m = 2):
super(FCMA, self).__init__(X, cluster... |
def foo(y1):
y1 + 1
print y1
|
#!/usr/bin/python
from expanduino.subdevice import Subdevice
from expanduino.codec import *
from enum import IntEnum
from time import time
from cached_property import cached_property
import asyncio
import os
import termios
import re
from fcntl import ioctl
from ..utils import run_coroutines, create_link, forever, fd_r... |
from django.urls import path
from . import views
urlpatterns = [
path("", views.index),
path("<int:month>", views.monthly_challege_by_number),
path("<str:month>", views.monthly_challenge, name="month-challenge")
] |
from flask import jsonify, request, abort
from flask_login import current_user, login_user, logout_user
from datetime import datetime
import uuid
import json
from random import random
from searchTwd import searchTwd
from searchTwdComponents import sanitizeTwd
from searchTwdComponents import matchInventory
from searchC... |
import math
import numpy as np
from helpers.agent8 import forward_execution, parent_to_child_dict
from src.Agent import Agent
class Agent8(Agent):
def __init__(self):
super().__init__()
# Override execution method of Agent class
def execution(self, full_maze: np.array, target_position=None):
... |
# Implement a function that takes as input three variables, and returns the largest of the three. Do this without
# using the Python max() function!
#
# The goal of this exercise is to think about some internals that Python normally takes care of for us. All you need
# is some variables and if statements!
def largest... |
from threading import Thread
import time
from typing import Tuple
from room import Room
from structsock import StructuredSocket, PeerDisconnect
from service import format_config, log, Signal, hexdump
from result import Status, StatusCode
import elite, msgpack, queue
# global configuration
config = {
"MinBetween": ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from collections import defaultdict, deque
def is_value(x):
return x.isdigit() or (x[0] == '-' and x[1:].isdigit())
class Program(object):
def __init__(self, instructions, pid):
self.registers = defaultdict(lambda: 0)
self.registers['p'] = pid
... |
# multivariate lin regresion of heights vs weights
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import norm, uniform, multivariate_normal
from scipy.interpolate import griddata
import pymc3 as pm
d = pd.read_csv('../../rethinking/data/WaffleDivorce.csv',... |
# -*- coding: utf-8 -*-
from django.conf import settings
from django.forms.forms import BoundField
from django.forms.models import formset_factory
from django.template import Context
try:
from django.template.loader import get_template_from_string
except ImportError:
from django.template import Engine
def... |
from builtins import range
import pandas as pd # type: ignore
from langdetect import detect
from datamart_isi.profilers.helpers.feature_compute_hih import is_Decimal_Number
import string
import numpy as np # type: ignore
import re
# till now, this file totally compute 16 types of features
def compute_missing_space... |
from nose.tools import *
import pygraphviz as pgv
|
import textwrap
from typing import ForwardRef, List, Optional
import pytest
import databases
import ormar
import sqlalchemy
import strawberry
database = databases.Database("sqlite:///db.sqlite")
metadata = sqlalchemy.MetaData()
MasterRef = ForwardRef("Hero")
class City(ormar.Model):
class Meta:
data... |
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
# Faça um programa que leia três números e mostre qual é o maior e qual é o menor.
a = int(input('Informe o primeiro número: '))
b = int(input('Informe o segundo número: '))
c = int(input('Informe o terceiro número: '))
# Verificando quem é menor
menor = a
if b < a and b < c:
menor = b
if c < a and c < b:
me... |
import os, sys
import unittest
sys.path.append(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'tools'))
from hcx_report import HouseCallXReport
class HouseCallXReportTestCase(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_get_scores(s... |
f=open("testfile.txt", "w") # it removes initial written things and write new things and also create a new file if not created at first
f.write("I'm loving Solus.")
f.close() #must close the file after writing
|
# Generated by Django 2.1.3 on 2020-08-22 15:04
import commons.models
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django_extensions.db.fields
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(sett... |
from random import randrange
bolso = 100
resultado = 0
resposta = "s"
while(resposta=="s"):
numero_apostado = int(input("Escolha um número entre 1 e 6 para você apostar: "))
valor_aposta = float(input("Qual o valor da aposta? "))
bolso -= valor_aposta
dado1 = randrange(1,6)
dado2 = randrange(1,6)
print("Sor... |
import pandas as pd
import numpy as np
def voting(time_matrix, values_array):
time_matrix = np.array(time_matrix)
col_sum = time_matrix.sum(axis=0) # Sum of votes for every option
idx = col_sum.argmax()
matrix_size = time_matrix.shape
if col_sum[idx] > matrix_size[0]/2: # If at least ... |
from __future__ import unicode_literals
import unittest
import mock
import vcr
from mopidy_youtube import Extension
from mopidy_youtube.backend import resolve_playlist
from mopidy_youtube.backend import search_youtube
from mopidy_youtube.backend import resolve_track
class ExtensionTest(unittest.TestCase):
def ... |
class bindings:
def __init__(self):
pass
def getName(self):
return "bindings"
def getDescription(self):
return "Flow snowboard bindings"
|
from time import perf_counter
import warnings
import torch
import torch.nn.functional as F
import numpy as np
from mmdet.datasets.builder import PIPELINES
from mmdet.datasets.pipelines.compose import Compose
@PIPELINES.register_module()
class Timer(Compose):
"""Times a list of transforms and stores result in img... |
#!/usr/bin/python
#-*- coding:utf8 -*-
"""
本程序用来获取音乐台网站的NV排行榜的数据
音悦台:http://www.yinyuetai.com
参考书籍
《用Python写网络爬虫》
《Python网络爬虫实战》
"""
import requests
import sys
import os
import re
import random
import time
from bs4 import BeautifulSoup
reload(sys)
sys.setdefaultencoding('utf8')
"""
Item 代表一个MV榜单
"""
class Item(obj... |
"""
This is essentially an interface for other converter classes,
these methods MUST be present!
"""
class BaseConverter:
def get_file(self):
raise NotImplementedError()
def get_filename(self):
raise NotImplementedError()
def is_inline(self):
raise NotImplementedError()
def ... |
#! /usr/bin/env python
import sourmash
import pickle
import argparse
from sourmash.search import gather_databases
from sourmash.lca import lca_utils
from sourmash.lca.lca_utils import LCA_Database
def main():
p = argparse.ArgumentParser()
p.add_argument("node_mh_pickle")
p.add_argument("lca_db")
args ... |
###############################################################################
# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. #
# #
# Licensed under the Apache License, Version 2.0 (the "License"). #
... |
# -*- coding: utf-8 -*-
from permission import Permission
from app import db
class Role(db.Model):
__tablename__ = 'roles'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, nullable=True, unique=True)
default = db.Column(db.Boolean, default=False)
permissions = db.Column(db.... |
"""
:attr:`~django.db.models.Field.help_text` string constants for the various
fields.
"""
SERIES_UID = "Unique identifier of the series"
SERIES_DATE = "Date the series started"
SERIES_TIME = "Time the series started"
SERIES_DESCRIPTION = "Description of the series"
PIXEL_SPACING = "Physical distance in the patient bet... |
from knx_stack.decode.usb_hid.report_body import usb_protocol_header
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated Thu Dec 13 17:56:14 2018 by generateDS.py version 2.29.5.
# Python 3.6.5 (default, May 19 2018, 11:27:13) [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)]
#
# Command line options:
# ('-o', '../python/eVSCertifyRequest.xsd.py')
#
# Command line a... |
import zipfile
import re
from django.utils.html import strip_tags
from util.textcleanup import split_into_chunks, calculate_unique_score_for_chunk, remove_special_characters
from util.handlequeries import build_query_result
def get_queries(source, num_queries=3):
scored_chunks = []
zip_data = zipfile.ZipFil... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Gobuster Module
'''
import os
import configparser
import sys
from core.config import cfg
CFG = configparser.ConfigParser()
CFG.read('config.ini')
class GoBusterModule:
'''Class GoBusterModule'''
@staticmethod
def display_wordlists_filenames(wordlist_dir... |
#
# run all the regression tests
#
# [or, you can request specific ones by giving their names on the command line]
#
import sys
import os
import subprocess
def system (cmd):
fo = open ('/dev/null', 'wb')
p = subprocess.Popen (cmd, shell=True, stdout=fo, stderr=subprocess.STDOUT)
return os.waitpid (p.pid, ... |
'''
Created on Aug 25, 2016
@author: David Zwicker <dzwicker@seas.harvard.edu>
'''
from __future__ import division
import copy
import unittest
import tempfile
import numpy as np
from .. import cache
from ...testing import deep_getsizeof
class TestCache(unittest.TestCase):
""" test collection for caching met... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__autor__ = u'Juan Beresiarte'
from math import sqrt
try:
input = raw_input
except NameError:
pass
def Tpitagoras(Hipotenusa=None, Cateto1=None, Cateto2=None):
if Hipotenusa == None:
return sqrt(Cateto1**2 + Cateto2**2)
elif Cateto1 == None:
return sqrt(Hipotenu... |
import exercises as e
from itertools import islice
import unittest
class GeneratorTests(unittest.TestCase):
# Uloha 1:
def test_square_generator(self):
self.assertNotIsInstance(e.square_generator(range(7)), list)
self.assertEqual(list(e.square_generator(range(7))), [0,1,4,9,16,25,36])
#... |
# -*- coding: utf-8 -*-
import h5py
import collections
def runSubsetInputs(self):
'''
This step reads the subset information - freq, pol and spatial.
'''
state = self.state
subset_dict = self.get_value(['runconfig', 'groups', 'processing',
'input_subset', 'list_of_frequencies'])
if is... |
from typing import Optional
from posthog.constants import (
BIN_COUNT,
DISPLAY,
FUNNEL_FROM_STEP,
FUNNEL_ORDER_TYPE,
FUNNEL_STEP,
FUNNEL_TO_STEP,
FUNNEL_VIZ_TYPE,
FUNNEL_WINDOW_DAYS,
INSIGHT,
INSIGHT_FUNNELS,
TRENDS_LINEAR,
FunnelOrderType,
FunnelVizType,
)
from post... |
#!/usr/bin/env python3
import argparse
import logging
import os
import sys
from wwpdb.utils.dp.electron_density.common_functions import convert_mdb_to_binary_cif, run_command_and_check_output_file
logger = logging.getLogger()
class EmVolumes:
def __init__(
self,
em_map,
node_path,
... |
# -*- coding: utf-8 -*-
import asyncio
from datetime import datetime, timedelta
import discord
import toml
from discord.ext import commands
class Rollback(Exception):
pass
class DBUtils(commands.Cog):
def __init__(self, bot):
super().__init__()
self.bot = bot
# ===================== #
... |
"""
A scripts to build the forward simulation structure and submit the job.
"""
from ...slurm.submit_job import submit_job
from ...tasks.xsede.forward import forward_task
# * test is passed for this script on 01/07/2020
class Run_multiple_forward_jobs(object):
def __init__(self, base=None, N_total=None, N_each=N... |
#!-*- coding:utf-8 -*-
#!/usr/bin/env python
#---------------------------------------------------
#掲示板のIDが空いているかを確認
#copyright 2010-2012 ABARS all rights reserved.
#---------------------------------------------------
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.api... |
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
from base import BaseModel
import segmentation_models_pytorch as smp
class conv_block(nn.Module):
def __init__(self, channel_in, channel_out):
super(conv_block, self).__init__()
self.conv = nn.... |
# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the... |
import math
import time
from utils import dataset, randomizer, exporter
from assignment3 import forward, backward, squared_error, optimize_sgd
class Autoencoder:
"""Simple Autoencoder implementation with one hidden layer, that uses the
identity function f(x) = x as its activation function and optimizes with
... |
from .datamodules import *
from .datasets import *
|
import torch
import math
import warnings
import pyro
from pyro import poutine
from pyro.infer.autoguide.utils import mean_field_entropy
from pyro.contrib.oed.search import Search
from pyro.infer import EmpiricalMarginal, Importance, SVI
from pyro.util import torch_isnan, torch_isinf
from pyro.contrib.util import lexpa... |
import numpy as np
import os
import sys
import errno
import shutil
import os.path as osp
import scipy.io as sio
from sklearn.neighbors import NearestNeighbors
from scipy import sparse
import scipy.sparse as sps
import timeit
from pyflann import FLANN
import multiprocessing
#import random
#random.seed(0)
#np.random.se... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import ... |
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.style
import matplotlib as mpl
import matplotlib.pyplot as plt
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
... |
# -*- coding: utf-8 -*-
#
# __init__.py
#
# Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# SPDX-License-Identifier: MIT-0
#
#
__author__ = "Rafael M. Koike"
__email__ = "koiker@amazon.com"
__date__ = "2016-11-14"
__version__ = '0.1.5'
|
"""
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3.
Note that the answer must be a ... |
from sklearn import datasets
from sklearn import metrics
from sklearn.metrics import classification_report
from sklearn import svm
from sklearn.model_selection import train_test_split
cancer = datasets.load_breast_cancer()
print("Features: ", cancer.feature_names)
print("Labels: ", cancer.target_names)
canc... |
import numpy as np
import init
import image_service
import image_draw
import perceptron
import noise_generation
N = 36
H = 30
M = 5
ALPHA = 1
BETA = 1
D = 0.02
letter_map = {
'K': 0,
'L': 1,
'O': 2,
'T': 3,
'U': 4
}
letter_image_map = {}
letter_vector_map = {}
for letter in letter_map:
le... |
import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
import launch_ros.actions
from launch.actions import DeclareLaunchArgument
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node
from launch.conditions import IfCondition... |
class Interval:
type_name = {0:'tick',
1:'m1',
2:'m5'}
name_type = {v:k for k,v in type_name.items()}
names = list(name_type.keys())
def __init__(self, value='m1'):
if value not in self.names:
return AssertionError, 'Interval value not exists'... |
# -*- coding: utf-8 -*-
# Copyright (c) 2016 Ericsson 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 ... |
#!/usr/bin/env python3
# std import
import sys
import string
import pkgutil
import configparser
# string-utils import
import string_utils
# project import
from . import logger
from .abcstep import StepStat
def main(config_path):
""" Main function of programme read configuration and run enable step """
confi... |
from .app.models import Category, Article
from .weakrefs import IdMapWeakRefsTests
class IdMapStrongRefsTests(IdMapWeakRefsTests):
# derives from tests with weak refs
# all tests should pass except CachedToRegular, where the expected
# result is the contrary
@classmethod
def setUpClass(cls):
... |
import datetime
import http.client
import mock
from rdr_service.clock import FakeClock
from rdr_service.code_constants import CONSENT_PERMISSION_YES_CODE, RACE_NONE_OF_THESE_CODE
from rdr_service.dao.biobank_order_dao import BiobankOrderDao
from rdr_service.dao.participant_dao import ParticipantDao
from rdr_service.da... |
import os
from scipy import io as sio
import numpy as np
import tensorflow as tf
import plotly.graph_objs as go
NUM_POINTS = 31
METER_SCALER = 0.001
CONNECTIONS = ((0, 1), (1, 2), (2, 3), (3, 4), (3, 5), (0, 6), (6, 7), (7, 8),
(8, 9), (8, 10), (0, 11), (11, 12), (12, 13), (13, 14), (14, 15),
... |
import datetime
import threading
import time
import mraa
import InternationalMorseCode as ICM
BASE_TIME_SECONDS = 1.0
TOLERANCE = BASE_TIME_SECONDS / 2.0
# Initialize GPIO settings
def initialize_gpio():
global metronomeLED
metronomeLED = mraa.Gpio(27) #Metronome
metronomeLED.dir(mraa.DIR_OUT)
metron... |
# encoding:utf-8
__author__ = 'shiliang'
__date__ = '2019/2/21 19:28'
import xadmin
from xadmin import views
from .models import EmailVerifyRecord
# 创建admin的管理类,这里不再是继承admin,而是继承object
class EmailVerifyRecordAdmin(object):
# 配置后台我们需要显示的列
list_display = ['code', 'email', 'send_type', 'send_time']
# 配置搜索字段,... |
from PySide2.QtGui import *
from PySide2.QtCore import *
from PySide2.QtWidgets import *
import traceback
from mcedit_ui.ui_sprite_editor import Ui_SpriteEditor
from mcedit_ui.clickable_graphics_scene import *
from mcedit_ui.custom_graphics_items import *
from mclib.sprite_loading import SpriteLoadingData
from mcl... |
import os
import pickle
from pathlib import Path
import networkx as nx
import numpy as np
import sys
# sys.path.insert(1, "./transitions_main")
from transitions_main import check
def nodes_func(nodes_file,data_name):
nodes = set()
year_nodes = dict()
nodes_year_labels = dict()
for i, row in enumerate(... |
import ray
class _NullLogSpan:
"""A log span context manager that does nothing"""
def __enter__(self):
pass
def __exit__(self, type, value, tb):
pass
NULL_LOG_SPAN = _NullLogSpan()
def profile(event_type, extra_data=None):
"""Profile a span of time so that it appears in the timel... |
#!/usr/bin/env python3
"""転移学習の練習用コード。Food-101を10クラスの不均衡データにしたもの。
train: 25250 -> 250+10*9 = 340 samples
val: 75750 samples
val_acc: 0.582
"""
import pathlib
import typing
import albumentations as A
import numpy as np
import tensorflow as tf
import pytoolkit as tk
num_classes = 10
train_shape = (256, 256, 3)
... |
from _md5 import md5
from urllib.parse import urlencode
from jinja2 import environment
from slugify import slugify
environment.DEFAULT_FILTERS['md5'] = lambda s: md5(s.encode('utf-8'))
environment.DEFAULT_FILTERS['hexdigest'] = lambda s: s.hexdigest()
environment.DEFAULT_FILTERS['urlencode'] = urlencode
environment.D... |
from typing import TYPE_CHECKING, List, Literal
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import relationship
from sqlalchemy.sql.expression import cast
from sqlalchemy.sql.schema import Column, ForeignKey
from sqlalchemy.sql.sqltypes import BOOLEAN, INTEGER, SMALLINT
from typing_extensions... |
from discord.ext import commands
class Fun(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.cooldown(1, 2, commands.BucketType.guild)
@commands.command()
async def norskeuniversiteter(self, ctx):
await ctx.send('<https://imgur.com/a/uGopaSq>')
@commands.cooldown(1... |
from __future__ import unicode_literals
from geckoboard import Dataset, Field as F
from datetime import date, datetime, timedelta
def test_create_delete(session):
fields = {
'date': F.date('Date', unique=True),
'datetime': F.datetime('Date Time'),
'number': F.number('Number'),
'pe... |
from mpi4py import MPI
import numpy as np
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
if rank == 0:
# in real code, this section might
# read in data parameters from a file
numData = 10
comm.send(numData, dest=1)
data = np.linspace(0.0,3.14,numData)
comm.Send(data, dest=1)
elif rank == 1:
... |
'''
Function:
define the base model for all models
Author:
Zhenchao Jin
'''
import copy
import torch
import numpy as np
import torch.nn as nn
import torch.distributed as dist
from ...losses import *
from ...backbones import *
from ..base import BuildAssigner
'''base model'''
class BaseModel(nn.Module):
de... |
"""Declare API endpoints with Django RestFramework viewsets."""
from django.apps import apps
from django.shortcuts import get_object_or_404
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .. import defaults, serializers
from ..models import Video
from ..utils.api_util... |
import mapnik
m = mapnik.Map(2560,2560)
mapnik.load_map(m, "mapnik.xml")
m.zoom_all()
mapnik.render_to_file(m, "the_image.png")
|
import inspect
from .metric import Metric
from .decoding import Decoding
from .dimensionality import Dimensionality
from .factorization import Factorization
from .generalization import Generalization
from .neural_fits import NeuralFits
from .rdm import RDM
from .sparsity import Sparsity
from .curvature import Curvatur... |
from xml.etree.ElementTree import fromstring, ElementTree
import time, datetime, os
import json
import boto3
import urllib
S3R = boto3.resource('s3')
OUTPUT_BUCKET_NAME = os.environ['OUTPUT_BUCKET_NAME']
print('Loading function')
def lambda_handler(event, context):
bucket = event['Records'][0]['s3']['bucket']['... |
import re
# order and rank functions are from here
# http://code.activestate.com/recipes/491268-ordering-and-ranking-for-lists/
def order(x, NoneIsLast=True, decreasing=False):
"""
Returns the ordering of the elements of x. The list
[ x[j] for j in order(x) ] is a sorted version of x.
Missing values ... |
class Activity(Dict):
def __init__(self, name, desc, res_gained, res_consumed, duration=0, optimal_env, **kargs):
self.name = name
self.desc = desc
self.res_gained = res_gained
self.res_consumed = res_consumed
self.optimal_env = optimal_env
self.duration = duration
... |
import time
import math
'''
FORMAT:
# Police ID
# First Name
# Last Name
# Current precinct
# Complaint id
# Month recieved
# Year recieved
# Month closed
# Year Closed
# Command during incident
# Rank Abbreviation at incident
# Rank Abbreviation now
# Rank at incident
# Rank now
# Officer Ethnicity
# Officer Gender
#... |
import argparse
import os
import shutil
def _parse_args():
parser = argparse.ArgumentParser(description="arg parser")
parser.add_argument(
"--dir", type=str, required=True, help="directory to be cleaned"
)
parser.add_argument(
"--date", type=int, required=True, help="logs before this d... |
# Generated by Django 3.2.9 on 2021-12-03 09:27
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('hotels_app', '0008_auto_20211203_0906'),
]
operations = [
migrations.RemoveField(
model_name='review',
name='reservation',
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 2 16:19:01 2021
@author: ccamargo
"""
import numpy as np
# import scipy.optimize as opti
import xarray as xr
import matplotlib.pyplot as plt
import sys
sys.path.append("/Users/ccamargo/Documents/py_scripts/")
import utils_SL as sl
import utils_SL... |
# -*- coding:utf-8 -*-
#
# Copyright (C) 2019-2020, Maximilian Köhl <koehl@cs.uni-saarland.de>
from __future__ import annotations
import typing as t
def get_subclasses(cls: type, recursive: bool = True) -> t.AbstractSet[type]:
subclasses: t.Set[type] = set()
if recursive:
queue = [cls]
while... |
import argparse
import os
import glob
from KerasRFCN.Model.Model import RFCN_Model
from keras.preprocessing import image
from WiderFace import RFCNNConfig
def loadModel(config, modelPath):
model = RFCN_Model(mode="inference", config=config,
model_dir=os.path.join(ROOT_DIR, "logs"))
if ... |
#
# This file is part of CasADi.
#
# CasADi -- A symbolic framework for dynamic optimization.
# Copyright (C) 2010-2014 Joel Andersson, Joris Gillis, Moritz Diehl,
# K.U. Leuven. All rights reserved.
# Copyright (C) 2011-2014 Greg Horn
#
# CasADi is free software; you can... |
from molecules.ml.unsupervised.point_autoencoder.aae import AAE3d
from molecules.ml.unsupervised.point_autoencoder.hyperparams import AAE3dHyperparams
|
from parallelm.mlops import mlops
from parallelm.mlops.constants import PyHealth
from parallelm.mlops.mlops_exception import MLOpsException
from parallelm.mlops.stats.mlops_stat import MLOpsStat
from parallelm.mlops.stats.mlops_stat_getter import MLOpsStatGetter
from parallelm.mlops.stats.stats_utils import check_list_... |
from models.fast_scnn import get_fast_scnn
import torch
import numpy as np
from torch import nn
import torch.utils.model_zoo as model_zoo
import torch.onnx
model = get_fast_scnn(dataset= 'simulation', aux= False)
model.eval()
x = torch.randn(1, 3, 160, 320, requires_grad=True)
torch_out = model(x)
print(torch_out[0]... |
"""Unit test package for easy_selenium."""
|
"""
A handy script for extracting all events from a particular year
from an ICS file into another ICS file.
@author Derek Ruths (druths@networkdynamics.org)
"""
import argparse
import re
import sys, os
from datetime import datetime
from datetime import timedelta
parser = argparse.ArgumentParser()
parser.add_argumen... |
'''
ANKIT KHANDELWAL
15863
Exercise 7
'''
from math import sin, sqrt, pi
import matplotlib.pyplot as plt
import numpy as np
def q(u):
alpha = pi / (20 * 10 ** -6)
return sin(alpha * u) ** 2
def y(u):
return sqrt(q(u))
w = 200 * 10 ** -6
W = 10 * w
wavelength = 500 * 10 ** -9
f = 1
n = 40
N = 10 * n
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.