text stringlengths 3.07k 12.6k |
|---|
import pandas as pd
import numpy as np
import numba
from pathlib import Path
from collections import Counter
import itertools
from config import ROOT, UTILITY, SUBMISSIONS
def read_base_feats(flag="train"):
return pd.read_feather(str(Path(UTILITY) / "{}_basefeats.ftr".format(flag)))
def correct_dob(x):
x =... |
import os
import logging
from urllib.parse import urljoin
from dateutil.parser import parse, ParserError
from astropy.io import fits
__all__ = ['MetadataRecord', 'DataLocationRecord']
# Methods to convert the FITS keywords value to the proper SVO type
KEYWORD_VALUE_CONVERSION = {
'text': str,
'boolean': bool,
'int... |
# -*- encoding:utf-8 -*-
# HINT:image
import tensorflow as tf
'''
Alexnet:
ImageNet Classification with Deep Convolutional Neural Networks
http://www.cs.toronto.edu/~fritz/absps/imagenet.pdf
'''
def inference(images, keep_prob):
def weight_variable(shape):
# conv : shape=[kernel_height, kernel_widht, ne... |
# This code is originated from https://github.com/andywu0913/OpenAI-GYM-CarRacing-DQN
# Also uses https://github.com/pythonlessons/Reinforcement_Learning/blob/master/03_CartPole-reinforcement-learning_Dueling_DDQN/Cartpole_Double_DDQN.py
import gym
import os, sys
import random
import numpy as np
from collections import... |
"""
Copyright 2019 Samsung SDS
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 ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from zeroconf import ServiceBrowser, Zeroconf
import threading
import time
import ipaddress
import subprocess
import sys
import requests
import paho.mqtt.client as mqtt
import logging
import logging.config
import json
from argparse import ArgumentParser
from common import ... |
# Copyright (c) 2006-2008 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.
"""Classes for failures that occur during tests."""
import path_utils
class FailureSort(object):
"""A repository for failure sort orders and too... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright (c) 2020, <NAME> aka KiLLA
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright n... |
"""
imutils/ml/utils/taxonomy_utils.py
Created on: Sunday April 10th, 2022
Created by: <NAME>
"""
import hydra
import pandas as pd
import pyarrow as pa
import pytorch_lightning as pl
from pytorch_lightning.utilities import rank_zero_only
import wandb
from typing import *
from imutils.ml.utils import template_... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
""" Resources
URI segments are the actual segments within the URLs from incoming HTTP
requests.
URI segment patterns are the URI segments with replacement markers (such
as 'marco{polo}ping{pong}').
URI segment regexes are the regexes that allow matching incoming URI
segments to a specific URI s... |
import gzip
import os
import re
import yaml
def get_log_age(path):
filename = os.path.basename(path)
parts = filename.split('.')
if len(parts) < 4:
return 0
else:
return int(parts[2])
class LogScraper(object):
# Example log line
# 2018-10-26 16:14:47,527 INFO zuul.nodepool: N... |
# Nuthouse01 - 08/24/2020 - v5.00
# This code is free to use and re-distribute, but I cannot be held responsible for damages that it may or may not cause.
#####################
# first, system imports
from typing import List
from abc import ABC, abstractmethod
# second, wrap custom imports with a try-except to catch... |
#!/usr/bin/python3
import os, glob
def get_subdirs(folder):
dirs = list()
for f in glob.glob(os.path.join(folder, '*', '')):
dirs.append(os.path.basename(os.path.normpath(f)))
return dirs
def get_files(folder, ext):
files = list()
for f in glob.glob(os.path.join(folder, ext)):
files.append(os.path.... |
import torch
import torch.nn as nn
from typing import Type, Optional
from collections import OrderedDict, namedtuple
import numpy as np
import warnings
def to_subspace_class(model_class: 'Type[nn.Module]', num_vertices: Optional[int] = 2,
verbose: Optional[bool] = False) -> 'Type[nn.Module]':
... |
import cffi
import os
import re
import sys
import rpy2.situation
from rpy2.rinterface_lib import ffi_proxy
ifdef_pat = re.compile('^#ifdef +([^ ]+) *$')
define_pat = re.compile('^#define +([^ ]+) +([^ ]+) *$')
cffi_source_pat = re.compile(
'^/[*] cffi_source-begin [*]/.+?/[*] cffi_source-end [*]/',
flags=re.M... |
from cairio import client as ca
import json
import subprocess
import sys
import pytest
import time
import os
import signal
import tempfile
def test_cairio(tmpdir):
tmpdir = str(tmpdir)
os.environ['KBUCKET_CACHE_DIR'] = tmpdir+'/sha1-cache'
from cairio import CairioClient
cc = CairioClient()
# Se... |
"""
module docstring
author: <NAME>
"""
import random
from collections import namedtuple, Counter
from functools import reduce
import operator
from typing import Tuple, List, Union, Generator
import numpy as np
import plate_generator
from plate_generator import core
from .core import Plate
__all__ = ["generator", ... |
# inspiro_bot.py
import boto3
import httplib
import json
import logging
import os
import time
import decimal
from base64 import b64decode
from urlparse import parse_qs, urlparse
# decrypting the key passed thru the gateway from slack
encrypted_slackKey = os.environ['slackKey']
expected_token = boto3.client('kms').de... |
import os
from flask import Flask, session, render_template, request, flash, redirect, url_for, jsonify
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SECRET_KEY'] = 'hard to get secure key'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
# setup SQLAlchemy
basedir = os.path.abspath(os... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2015 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 requi... |
import re
from functools import wraps
from gooey.gui.components.filtering.prefix_filter import OperatorType
class SuperBool(object):
"""
A boolean which keeps with it the rationale
for when it is false.
"""
def __init__(self, value, rationale):
self.value = value
self.rationale = ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of Pysilhouette.
#
# Copyright (c) 2009 HDE, Inc.
#
# 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, in... |
class Character:
"""
Information about a Japanese character.
Attributes:
__hiragrana:
a string
__katakana:
a string
__romaji:
a string
__timewrong:
an integer
"""
def __init__(self, hiragana, katakana, romaji):
"""Creates a character w... |
#
# ARCADIA Mocks
#
# Copyright (C) 2017 SINTEF Digital
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the MIT license. See the LICENSE file for details.
#
from arcadiamock.servicegraphs import *
import xml.etree.ElementTree as etree
from lxml import etree as lxmletree... |
"""Build a dart_vm_binary to run code generation."""
load("//third_party/bazel_skylib/lib:dicts.bzl", "dicts")
load("//dart/build_rules/internal:common.bzl", "SDK_LIB_FILES")
load("//dart/build_rules:vm.bzl", "dart_vm")
load(":_labels.bzl", "labels")
load(
"//third_party/dart/rules_dart/build_rules/common:kernel.b... |
"""Generate XML code coverage reports."""
from __future__ import annotations
import os
import time
import typing as t
from xml.etree.ElementTree import (
Comment,
Element,
SubElement,
tostring,
)
from xml.dom import (
minidom,
)
from ...io import (
make_dirs,
read_json_file,
)
from ...u... |
import copy
import unittest
import os
import numpy
import csep
from csep.core import regions, forecasts
from csep.utils.time_utils import strptime_to_utc_epoch, strptime_to_utc_datetime
from csep.core.catalogs import CSEPCatalog
def comcat_path():
root_dir = os.path.dirname(os.path.abspath(__file__))
data_di... |
import numpy as np
from utils.mapie_utils import (
predict_with_mapie,
get_prediction_bounds,
invert_prediction_bounds,
)
from utils.reviews_utils import get_steam_api_url
from utils.time_utils import get_target_date_as_timestamp
from utils.transform_utils import (
get_review_chance,
get_review_mul... |
"""
This file is part of the accompanying code to our manuscript:
<NAME>., <NAME>., <NAME>., and <NAME>.: A note on leveraging synergy in multiple meteorological
datasets with deep learning for rainfall-runoff modeling, Hydrol. Earth Syst. Sci. Discuss.,
https://doi.org/10.5194/hess-2020-221, in review, 2020.
You sho... |
import os
from flask import Flask, render_template, request,redirect
from flask import session
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import json
import math
from werkzeug.utils import secure_filename
with open('config.json','r') as c:
params = json.load(c)['params']
local_server = ... |
import os
from os.path import dirname, join
import pytest
from pypi_simple import PYPI_SIMPLE_ENDPOINT, parse_simple_index
DATA_DIR = join(dirname(__file__), os.pardir, "data")
def test_empty():
with pytest.warns(DeprecationWarning):
projects = list(parse_simple_index("", PYPI_SIMPLE_ENDPOINT))
asser... |
import torch
import math
import numpy as np
import pickle
from torch import nn
import torch.functional as F
from pyro.distributions import Normal, Independent, Categorical, LogNormal
import sys, os
from torch.autograd import grad
from models.iefs.logcellkill import LogCellKill
from models.iefs.treatexp import Treatmen... |
"""
@author: <NAME>
helper functions, part of:
ProbFire, a probabilistic fire early warning system for
Indonesia.
"""
import numpy as np
import xarray as xr
import pandas as pd
#Define sub-region bounding boxes
bboxes = {
'South Kalimantan': [-1.5, 110.5, -4., 115],
'South Sumatra': [-2.2, 103, -5, 10... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import copy
import logging
import os
import time
from pathlib import Path
import sys, traceback
from argparse import Namespace
import torch
import torch.optim as optim
from torch.nn.parallel import DistributedDataParallel as DDP
import torch.mult... |
# -*- coding: utf-8 -*-
# file: main.py
# author: JinTian
# time: 11/03/2017 9:53 AM
# Copyright 2017 JinTian. 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
#
# htt... |
# <NAME>
# 08 Nov 2019
import numpy as np
from enum import Enum
from .optimizer import Optimizer
class _Particle:
def __init__(self, shape, x_val_init):
# weights for self, others
self.phi = [2.05, 2.05]
# set current vector position to something in range [-1.0, 1.0]
self.x = np.random.rand(shape) * 2 - 1
... |
try:
import defusedxml.cElementTree as ET
except ImportError:
try:
import defusedxml.ElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
import datetime
import numpy as np
class Block:
""" Represents a "Block" in a tbwk file."""
Measurement = 151
head = N... |
from rediscluster import RedisCluster # redis-py-cluster 2.0.0 版本无 StrictRedisCluster
from scrapy.utils.reqser import request_to_dict, request_from_dict, _find_method, _get_method
from scrapy.http import Request
from scrapy.utils.python import to_unicode, to_native_str
from scrapy.utils.misc import load_object
fr... |
from collections import deque
import math
from PIL import Image, ImageDraw, ImageFont
class PEL:
def __init__(self,currposition,distance,previous):
self.currposition = currposition
self.distance = distance
self.previous = previous
def shortestPath(graph,n,points,lastRound):
firstRound = PEL("A1",0,"")
qu... |
# def flog_jump(x, leaves):
# blaetter = (set(range(1, x+1)))
# print(blaetter)
# af_s = set()
# for idx, num in enumerate(leaves):
# af_s.add(num)
# print(af_s)
# if af_s == blaetter:
# return idx
# return -1
#
#
# print(flog_jump(1, [1]))
def double_pointer(li... |
def _get_data_dir():
import os, warnings
from pathlib import Path
DIR_DATA = os.environ.get('MAGNET_DATAPATH', '~/.data')
if DIR_DATA is None:
warnings.warn('You need to have an environment variable called MAGNET_DATAPATH. Add this to your .bashrc file:\nexport MAGNET_DATAPATH=<path>\n'
... |
"""
**apps_authenticator**
will handle internal application api calls
**NOTE:**
this authenticator runs on the api side will have access to all the data classes
"""
__developer__ = "mobius-crypt"
__email__ = "<EMAIL>"
__twitter__ = "@blueitserver"
__github_repo__ = "https://github.c... |
import argparse
import cv2
import numpy as np
import torch
from torch.autograd import Function
from torchvision import models, transforms
class ModelWrapper:
def __init__(self, model, feature_module):
self.model = model
self.feature_module = feature_module
self.feature_gradients = None
... |
import xml.etree.ElementTree as ElementTree
from flask import flash, render_template, request
from watch import app
from watch.utils.decorate_view import *
from watch.utils.oracle import execute
from watch.utils.parse_args import parse_parameters
from watch.utils.render_page import render_page
@app.route('/<target>... |
import json
import logging
from ckan import model
from ckan.common import _
from ckan.plugins.toolkit import c, check_access, get_action
# TODO: Should not be cross dependant to ckanext.ytp
# This is specific to ytp
from ckanext.ytp.helpers import get_translated
log = logging.getLogger(__name__)
def field_options(f... |
#!/usr/bin/python3
# Copyright 2019 Tricot Inc.
# Use of this source code is governed by the license in the LICENSE file.
"""Executes syncherator scripts, which are scripts to sync specified repos."""
import hashlib
import os
import os.path
import subprocess
import sys
import requests
assert sys.version_info >= (... |
##
# Copyright (c) 2016-2017 Apple Inc. 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 l... |
import asyncio
import config
import discord
from discord.ext import commands
from discord.ext.commands import Cog
from helpers.checks import check_if_staff
import io
import os
import random
import re
class ListsVerification(Cog):
def __init__(self, bot):
self.bot = bot
self.verification = ""
... |
from __future__ import division
from datetime import datetime, timedelta
from uuid import uuid4
from projectpredict.pdf import GaussianPdf, TimeUnits, DurationPdf, DatePdf
class Entity(object):
"""Base class for entities which provides a UUID and a hashability to the child classes
Attributes:
uid (... |
# -*- coding: utf-8 -*-
"""Main module."""
import daiquiri
import logging
import pandas as pd
import os
import numpy as np
from sklearn.ensemble import RandomForestRegressor
import time
daiquiri.setup(level=logging.INFO)
def get_data_source(data_set: str = 'default') -> (str, list, list):
"""
Return the res... |
#! /usr/bin/env python3
import urllib.request
import os
import sys
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets.base import load_iris
from sklearn.model_selection import cross_validate
from sklearn.neural_network import MLPClassifier
from sklearn.linear_model import Perce... |
# -*- coding: utf-8 -*-
# Run this app with `python app.py` and
# visit http://127.0.0.1:8050/ in your web browser.
import json
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import plotly.figure_factory as ff
import dash_table
imp... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
import datetime
import xarray
import datetime
import os
from .config import get_plot_values, get_field_parameters
def quicklooks_1panel(file, field, config, image_directory=None, **kwargs):
"""
Quciklooks, produces a one ... |
"""This module defines metaclasses used to trace the parameters passed through operation-critical
classes that are members of other libraries. These are only used in cases where it is impractical
or impossible to effectively retrieve the arguments explicitly provided by a user, as well as the
default arguments for the ... |
# coding: utf-8
import json
# World Health Organization data
f = open("who_maternal_mortality.json")
content = f.read()
content = content.replace("Côte", "Cote")
f.close()
who_countries = {}
# rename some WHO countries to CIA naming scheme
renames = {
"united_states_of_america": "united_states",
"united_kin... |
# /***********[combinations.py]
# Copyright (c) 2020 <NAME>, <NAME>, <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 u... |
import time
from urllib.parse import urlparse, parse_qs
from threading import Thread
from threading import Lock
from .server import HttpServer
from .configuration import Configuration
from .scenario import Scenario
from .clients.android import AndroidClient
from .clients.ios import IosClient
from .clients.osx import Os... |
import time
import logging
logger = logging.getLogger(__name__)
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.db.models import Q
from django.shortcuts import render
from django.views.generic import TemplateView
from taggie.parser import generate_tags
from .models import Tag, Tut... |
# -*- coding: utf-8 -*-
# MIT License
#
# Copyright (c) 2021 <NAME>
#
# Permission is hereby granted, free of charg>
# of this software and associated documentati>
# in the Software without restriction, includ>
# to use, copy, modify, merge, publish, distr>
# copies of the Software, and to permit perso>
# furnished to ... |
from charms.reactive import when
from charms.reactive import when_not
from charms.reactive import set_state
from charms.reactive import remove_state
from charms.reactive.helpers import data_changed
from charms.layer.hadoop_base import get_hadoop_base
from jujubigdata.handlers import HDFS
from jujubigdata import utils
f... |
from unittest.mock import patch
from django.contrib.auth import get_user_model
from django.test import TestCase
from bulk_sms.models import Batch
from bulk_sms.tasks import message_reminder_task, \
CheckinReminderMessage, PollingDayReportReminderMessage
from polling_reports.models import StaffPhone, PollingReport... |
from klampt.plan import robotplanning
from klampt.plan.cspace import MotionPlan
from klampt.model import trajectory
from klampt.model.trajectory import Trajectory,RobotTrajectory, execute_path,path_to_trajectory
from klampt import vis
from klampt.model import ik
from klampt.math import vectorops,so3,se3
from klampt im... |
#****************************************************************************
#* vte main
#****************************************************************************
import argparse
import jinja2
import os
import stat
from stat import *
from . import template_rgy
def substitute(vars, str):
i=0
while i < len... |
"""
test_malign
===========
Tests for the `malign` package.
"""
# Import the library itself
import malign
import pytest
def test_dumb_pw_align():
"""
Test `dumb` pairwise alignment.
"""
alms = malign.multi_align(["tra", "fatata"], method="dumb")
assert len(alms) == 1
assert tuple(alms[0].se... |
# -*- coding: utf-8 -*-
#Coded By <NAME> https://github.com/AshkanRafiee/PingWidget/
################Libraries################
import PySimpleGUI as sg
import webbrowser
import time
import threading
from pythonping import ping
################Libraries################
status = None
mypings1 = []
mypings2 = []
mypings... |
from enum import Enum
class EventChangeStrategies(Enum):
DEFAULT_EVENT_CHANGE = 0
@staticmethod
def get_all():
result = {}
for strategy in EventChangeStrategies:
result[strategy.name] = strategy
return result
@staticmethod
def get_strategy(p_strategy_name):
... |
import logging
from os.path import dirname, join
from pandas import DataFrame
import json
import pandas as pd
from pybleau.reporting.plot_report_element import PlotReportElement
from pybleau.reporting.section_report_element import SectionReportElement
from pybleau.reporting.string_definitions import IDX_NAME_KEY, CONT... |
from __future__ import absolute_import
import os
import traceback
import warnings
from ptvsd.socket import Address
from ptvsd._util import new_hidden_thread, Closeable, ClosedError
from .debugadapter import DebugAdapter, wait_for_socket_server
from .debugsession import DebugSession
# TODO: Add a helper function to s... |
from .lin_op import LinOp
from ..utils.cuda_codegen import indent, sub2ind, ind2subCode, NodeReverseInOut, ReverseInOut
import numpy as np
class vstack(LinOp):
"""Vectorizes and stacks inputs.
"""
def __init__(self, input_nodes, implem=None):
height = sum([node.size for node in input_nodes])
... |
"""Advent of Code 2020 Solutions
Author: <NAME>
"""
import io, itertools, math, re, modules.userInput
TARGET_CYCLES = 6
NEIGHBOURS3 = [p for p in itertools.product([-1,0,1], repeat=3) if p.count(0) < 3]
NEIGHBOURS4 = [p for p in itertools.product([-1,0,1], repeat=4) if p.count(0) < 4]
STAY_ACTIVE = dict.fromkeys([2, ... |
# Copyright (c) 2020, Digi International Inc.
#
# 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... |
from django.utils.html import format_html, format_html_join, escape
from django.utils.safestring import mark_safe
from django.forms.utils import flatatt
from . import wrappers
from .utils import pad, get_choices, get_placeholder_text
def render_charfield(field, attrs):
"""
Render the generic CharField.
"""
retur... |
"""
Perform inference on object frames of the Epic Kitchens Dataset
"""
import logging
import os
import torch
import json
from tqdm import tqdm
from collections import OrderedDict
from torch.nn.parallel import DistributedDataParallel
import detectron2.utils.comm as comm
from detectron2.config import get_cfg
from dete... |
#!/usr/bin/env python3
#
# Copyright 2021 <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 o... |
import sys
import re
import numpy as np
import argparse
import random
# from keras import backend as K
def tokenize(sent):
'''
data_reader.tokenize('a#b')
['a', '#', 'b']
'''
return [x.strip().lower() for x in re.split('(\W+)?', sent) if x.strip()]
def map_to_idx(x, vocab):
'''
x is a seque... |
# Copyright (c) The Diem Core Contributors
# SPDX-License-Identifier: Apache-2.0
from dataclasses import dataclass, field, asdict
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
from typing import List, Optional, Any, Dict
from .app import KycSample, Event
from .app.sto... |
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# DATA COMPARISONS OF NEW hurs AND OLD hur DOWNSCALED DATA
# <NAME> (<EMAIL>) September 2018
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def open_raster( fn, band=1 ):
with rasterio.open( fn ) as rst:
arr = rst.read( band )
... |
import logging
import multiprocessing as mp
import os
import time
import typing as t
from gunicorn.app.base import Application
from gunicorn.pidfile import Pidfile
from dimensigon import defaults
from dimensigon.exceptions import DimensigonError
from dimensigon.use_cases.base import TerminateInterrupt
from dimensigon... |
from collections import OrderedDict
import datetime
from typing import Iterator, List
from flask_sqlalchemy import SQLAlchemy
from psycopg2.extensions import QuotedString
from sqlalchemy import Table
#: Number of rows to insert per batch transaction
BATCH_SIZE = 50000
class Column:
def __init__(self, name: str... |
# All fields except for BlobField written by <NAME> <<EMAIL>>
from django.db import models
from django.core.exceptions import ValidationError
__all__ = ('RawField', 'ListField', 'DictField', 'SetField', 'BlobField')
class _HandleAssignment(object):
"""
A placeholder class that provides a way to set the attri... |
# Copyright (c) 2016 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
import datetime
from flask_wtf import FlaskForm as Form
from wtforms import Form as WTForm, ValidationError
fro... |
from time import time
import numpy as np
import random
from kdtree import KDTree
class SimpleTree:
def __init__(self, dim):
self._parents_map = {}
self._kd = KDTree(dim)
def __len__(self):
return len(self._kd)
def insert_new_node(self, point, parent=None):
node_id = sel... |
#!/usr/bin/python
import Adafruit_BBIO.GPIO as GPIO
import Adafruit_BBIO.SPI as SPI
#GPIO.setwarnings(False)
import time
import argparse
import threading
import math
from pkg_resources import Requirement, resource_filename
from itertools import cycle
from PIL import Image
#import st7565.backlight
import st7565.lcd... |
#==============================================================================#
# #
# Title: utils #
# Purpose: Provide the utilities to be used by other modules ... |
#!/usr/bin/env python
# coding: utf8
#
# Copyright (c) 2020 Centre National d'Etudes Spatiales (CNES).
#
# This file is part of LIBSGM
#
# https://github.com/CNES/Pandora_libsgm
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# Y... |
from django.core.exceptions import PermissionDenied
from django.forms import inlineformset_factory
from django.shortcuts import redirect, render
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.contrib.sites.models import Site
from django.core.urlresolvers import... |
"""The pandas backend is a departure from the typical ibis backend in that it
doesn't compile to anything, and the execution of the ibis expression coming
dervied from a PandasTable is under the purview of ibis itself rather than
sending something to a server and having it return the results.
Design
------
Ibis uses ... |
#
# MIT License
#
# 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, pub... |
"""
This file is used to recover texts from the LEGIFRANCE API.
"""
import os
import requests
import pandas as pd
from tqdm import tqdm
from bs4 import BeautifulSoup
CLIENT_ID = ""
CLIENT_SECRET = ""
API_URL = "https://api.piste.gouv.fr/dila/legifrance-beta/lf-engine-app"
TOKEN_URL = "https://oauth.piste.gouv.fr/api/... |
# 使用APIView
import json
from celery.result import AsyncResult
# Create your views here.
from django.db import IntegrityError
from rest_framework import status
from rest_framework.response import Response
from rest_framework.decorators import api_view
import re
import os
from interface_test.common.common import get_ref... |
from .utils import *
from ..util.common_ut import *
import random
def test_recursive_collec():
vg = ValueGenerator()
vg.populate(iterations=30)
for collec in vg.pool:
assert collec_same_shape(collec, collec)
flat, index = flatten_collection_atoms(collection=collec, start_idx=0)
asse... |
import os
import csv
import json
import argparse
from tqdm import tqdm
import numpy as np
from PIL import Image
from numpy.lib.format import open_memmap
def process_labels(label_dir):
label_info = dict()
subjects = sorted(os.listdir(label_dir))
label_info['subjects'] = subjects
label_info['frames... |
#!/usr/bin/env python
"""
Example usage command:
>> ./bin/run_scripts/step1_generatemodel.py --dryrun -cn step1_study_control_1ccccab7-dfbe-4974-86ed-5744b659f938
================================================================================
"""
import os
import sys
import time
import datetime
from argparse impor... |
import math
import os
import pandas as pd
import numpy as np
import torch
from tensorflow.python.keras import Model
from tensorflow.python.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.utils import to_categorical
from transformers import AutoTokenizer, AutoModel
from utils import clean_up
fro... |
import sys
import os
sys.path.append(os.getcwd())
import threading
import time
import glob
import numpy as np
from utils.file_io import *
from argparse import ArgumentParser
import speechmetrics as sm
MAX_THREAD = 3
root = os.getcwd()
MUSDB_TEST = "data/musdb18hq/test"
def sdr(references, estimates):
# compute S... |
#!python3
import os
import argparse
import numpy as np
import pandas as pd
from glob import glob
from ete3 import Tree
from plot_module import plot_correlation, plot_tree, to_float
def remove_units(str):
return str.replace("(g)", "").replace("(days)", "").replace("(yrs)", "").replace("(kg)", "").replace("(cm)", "... |
#!/usr/bin/python3.4
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by app... |
from collections import defaultdict
import copy
from enum import Enum
import math
import pygame
from .entity.individual import Individual
from .entity.position import Position
class UpdateMode(Enum):
SYNCHRONOUS=0
ASYNCHRONOUS=1
class GameMode(Enum):
CONWAY=0
class Game():
def __init__(self, upda... |
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
from django.conf import settings
import csv
import os
def get_image_path(patient_id,mri_type,slice_num):
pt = 'images/'+patient_id + '/' \
+ mri_type +'/'\
+ mri_type+'-slice'+str(slice_num).zfill(2)+'.pn... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.