text stringlengths 3.07k 12.6k |
|---|
import sublime
import sublime_plugin
import os
import os.path
import re
import sys
import subprocess
import locale
CMD_VAULT = ''
COMMENTSTRING = ''
CURPATH = []
HOST = ''
ISDEBUG = True
PASSWORD = ''
REPOSITORYNAME = ''
SSL = False
USERNAME = ''
VAULT_PATH = ''
class NotFoundError(Exception):
... |
import base64
import hashlib
import hmac
import logging
import random
import stringprep
import unicodedata
def clientFirstMessage(state):
buffer_ = gs2Header()
state = clientFirstMessageBare(state)
buffer_ += state['client_first_msg_bare']
state['client_first_msg'] = buffer_
return state
def c... |
# Leave a space between each Stock Symbol
import Stocks #Main API
import sys #To get Command Line arguments
import config #Config file API
import multiprocessing #It's obviuos :)
import time
StartEndString = "------------------------------------" #For neat printing.
StockApp = Stocks.Stocks() #Initialize API
bcolors... |
"""
@author: <NAME>
file: ZIPapliences.py
"""
import numpy as np # arrays similar to how R deals with arrays #document
import pandas as pd #time series
import scipy.stats as stats
###########################################
#CLASSE APLAENCES
###########################################
class ApplianceType(ob... |
# pylint: disable=no-self-use
"""Module that is used for sending data that can be shown on the admin dashboard"""
from datetime import datetime, timedelta, timezone
from flask_jwt_extended import jwt_required
from flask_restful import Resource
from sqlalchemy import and_, func
from api.models import Participant, Vers... |
import nltk
from nltk import pos_tag
from nltk.corpus import stopwords, wordnet
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import TweetTokenizer, word_tokenize
import pandas as pd
import re
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.model_selection import t... |
'''
Based on the @loboris ESP32 MicroPython port
Uses Adafruit Feather ESP32 and Adafruit Featherwing SSD1306 OLED
Uses the frozen ssd1306 module that @loboris port provides
play/pause button and a potentiometer.
Also displays track information that is being published by local raspi
sonos-companion script esp_check_mqt... |
#kyDoleuc04
#Final Project
from ggame import App, Color, LineStyle, Sprite, RectangleAsset, CircleAsset, EllipseAsset, PolygonAsset, Frame, TextAsset
pink = Color(0xFF00FF, 1.0)
red = Color(0xff0000, 1.0)
green = Color(0x39ff14, 1.0)
blue = Color(0x0000ff, 1.0)
black = Color(0x000000, 1.0)
white = Color(0xffffff, 1.0... |
import csv
import math
import random
import time
import brainex.database.genexengine as gxdb
from pyspark import SparkContext, SparkConf
from brainex.parse import generate_query
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import findspark
import os
# spark_location = '/Users/Leo/spark-2.... |
from datetime import datetime, timedelta
import boto3
from autobot_helpers import context_helper
from services.aws.utils import Constants, Helpers
autobot_region = 'Virginia'
def get_session(autobot_resources=False):
context_helper.logger().debug("get_session called for %s", str(autobot_resources))
session =... |
''' Question 1:
Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5,
between 2000 and 3200 (both included).
The numbers obtained should be printed in a comma-separated sequence on a single line.
Hints:
Consider use range(#begin, #end) method
'''
# Solution
list = []
... |
import os.path
import json
import pytz
from collections import defaultdict
from datetime import datetime
from dateutil import parser
class Data:
"""
Class to describe event data
"""
# Customer Events Master data
customer_master_dict = defaultdict(dict)
# Orders Master Data
order_master_... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import numpy as np
from node import Node, ColumnNode
# https://www-cs-faculty.stanford.edu/~knuth/preprints.html
# https://en.wikipedia.org/wiki/Dancing_Links
# dancing links' list
# ======================================================================
class DList():
def... |
# Sentinel-2 data extraction GUI
#############
## Imports ##
#############
## General imports
import os
import sys
from datetime import date
## GUI imports
import wx
from wx.adv import DatePickerCtrl
from wx.lib.intctrl import IntCtrl
## Custom imports
from image import Query, Image
###############
## Constants ##... |
import boto3
import re
import os
class EcsClient(object):
def __init__(self):
self._client = boto3.client('ecs')
def _describe_cluster(self, cluster):
rs = self._client.describe_clusters(clusters=[cluster])
ls = [EcsCluster(item) for item in rs[u'clusters']]
return ls[0] if ... |
"""Support for LG webOS Smart TV."""
from __future__ import annotations
from collections.abc import Callable
from contextlib import suppress
import logging
from typing import Any
from aiowebostv import WebOsClient, WebOsTvPairError
import voluptuous as vol
from homeassistant.components import notify as hass_notify
f... |
import numpy as np
import cv2
import glob,os
#!/usr/bin/env python
# coding:utf-8
"""
Name : Calibration.py
Author : <NAME>
Contact : <EMAIL>
Time : 07/02/2021 8:00 A.M
Desc : Functions: Calibration and UnDistortion of frames
"""
# termination criteria
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CR... |
# MIT License
#
# Copyright (c) 2017 <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... |
# -*- coding: utf-8 -*-
"""
Test of process functions
"""
import pytest
from aiida import orm
from aiida.plugins import CalculationFactory
def test_birch_murnaghan_fit(data_regression):
"""Birch–Murnaghan fit test"""
birch_murnaghan_fit = CalculationFactory(
'sssp_workflow.birch_murnaghan_fit')
... |
#!/usr/bin/env python3.6
# -*- coding: utf-8 -*-
"""
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 ... |
import re
class markupHtml(object):
def __init__(self,base):
self.resect = re.compile( '(\{[a-zA-Z]*\})' )
self.relink = re.compile( '(\[http\S*.*\])' )
self.base = base
def parse(self,ss):
for x in self.resect.findall( ss ):
ss = ss.replace( x, self.sectionlink(x) )
for x in self.relink... |
# plot data coverage
import pandas as pd
import os
import matplotlib.pyplot as plt
from astropy.time import Time
import astropy.io.fits as fits
import numpy as np
import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import (YEARLY, DateFormatter,
rrulewrapper, RRuleLocato... |
#!/usr/bin/python3
# This is the startup script for GCE VMs managed by runbatch.
import base64
import grp
import json
import logging
import os
import pwd
import select
import subprocess
import sys
import tempfile
import urllib.request
logging.basicConfig(level=logging.INFO)
# Set unbuffered so that we can see the o... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2021 Intel Corporation
#
# 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
#
# Unl... |
from functools import wraps
import connexion
import urllib3
from flask_migrate import Migrate
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
import jwt
import time
from consul_functions import get_host_name_IP, get_consul_service, register_to_consul
RESERVE_APIKEY = 'RESERVE MS SECRET'
JWT_LIFE... |
#!/usr/bin/env python3
import argparse
import os
import sys
import traceback
from datetime import datetime
import yaml
from util import db
from util import printing as p
from util import version
from alerts.discord import Discord
import games
import requests
from util import loader
from util.errors import TemporarySite... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import copy
import math
from transformers import Wav2Vec2Model,Wav2Vec2Config
from transformers.modeling_outputs import BaseModelOutput
from typing import Optional, Tuple
_CONFIG_FOR_DOC = "Wav2Vec2Config"
# the implementation of Wav... |
# PROJECT : Crypto
# FILE : strategy.py
# PROGRAMMER : <NAME>
# DATE : 2020-08-20
# DESCRIPTION : The functions in this file are used to support the strategy interface interface
import abc
from PIL import Image
import random
from .constants import image_key
from typing import Li... |
import random
from pysc2.agents.myAgent.myAgent_12.config import config, config_for_level_2_build_controller
from pysc2.agents.myAgent.myAgent_12.tools.unit_list import combat_unit, building
from pysc2.lib import features, actions, units
import numpy as np
hard_code = [ # 28种
0, # 军械库
5, # 兵营
0, # 飞行... |
import re
import os
import subprocess
import pytest
import tempfile
import io
from .Builder import Executable
from .util import invoke_process, infer_language
from .CFG.cfg import CFG
from .DebugInfo import DebugInfo
from .Exceptions import CFiddleException
class Source:
def source(self, show=None, language=... |
import os
import logging
from pyrogram import Client, filters
from pyrogram.types import InputMediaPhoto, InlineKeyboardMarkup, InlineKeyboardButton
from creds import Credentials
from telegraph import upload_file, Telegraph
logging.basicConfig(level=logging.WARNING)
telegraph = Telegraph()
telegraph.create_account(sh... |
import unittest
from ccdc.protein import Protein
from ccdc.io import MoleculeReader
from hotspots.hs_io import HotspotReader, HotspotWriter
from hotspots.result import Results
from hotspots.grid_extension import Grid
from hotspots.calculation import Runner
from hotspots.wrapper_pymol import PyMOLFile, PyMOLC... |
import math
from abc import abstractmethod, ABC
from typing import Sequence, Tuple, Union, Callable
from coba.backports import Literal
from coba.exceptions import CobaException
from coba.random import CobaRandom
from coba.utilities import PackageChecker
def iqr(values: Sequence[float]) -> float:
if len(values) ... |
"""
Low-level TCP/IP packet manipulation library
for Python 2.7.
Classes:
- PSocket
- IP, ICMP
"""
# data structure related imports
import fcntl
import array
import struct
import random
# network related imports
import socket
import time
def checksum (message):
"""grab the hashed checksum of ASCII text"""
... |
# written by allen.stevens
import re
import port_names
types = {'action': '^(?:permit|deny|remark)$',
'protocol': '^(?:ip|tcp|udp|icmp|pim|igmp|esp|eigrp)$',
'ip_or_mask': '^((?:\\d{1,3}\\.){3}\\d{1,3})$',
'port_op': '^(?:eq|lt|gt|range)$',
'integer': '^\\d+$',
'word': '\\w... |
# -*- coding: utf-8 -*-
"""Test plotting utilities."""
#------------------------------------------------------------------------------
# Imports
#------------------------------------------------------------------------------
import numpy as np
from numpy.testing import assert_array_equal as ae
from numpy.testing im... |
""" The TTD2 Discord chat bot. """
import asyncio
import pathlib
import re
import json
import appdirs
import cachetools
import discord
import openbsd
import common
import data
# ==============================================================================
db_con, db_cur = data.create_in_memory_database()
client =... |
# Copyright 2020 The SQLFlow Authors. All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
#!/usr/bin/env python3
from datetime import datetime
from pathlib import PurePath, Path
from itertools import chain
from subprocess import CalledProcessError
import tempfile
from lettersmith.util import get_deep, tap_each, replace
from lettersmith.argparser import lettersmith_argparser
from lettersmith import path as ... |
import datetime
from datetime import date
import pandas as pd
import numpy as np
import requests
from pandas.tseries.offsets import BDay
from mip import Model, xsum, minimize, BINARY, maximize
import re
api_key = '30d9085988663142ce4cb478d09e6d00'
def next_weekday(d, weekday):
days_ahead = weekday - d.weekday()
... |
# Ignoring some linting rules in tests
# pylint: disable=redefined-outer-name
# pylint: disable=missing-docstring
import warnings
import pytest
import numpy as np
from bingo.symbolic_regression.implicit_regression import ImplicitRegression, \
ImplicitRegressionSchmidt, \
... |
## This file is composed of some functions from ~/Work/ERATO/tracing/code/helpers.py
## UPDATE: With the addition of more functions.
from numpy import *
def color_spiral( i, N ):
'''
Takes parameters 'i' and 'N' where 'i' is a number in the range [0,'N'], where N > 0.
Returns a 3-tuple ( red, green, blue ... |
# Copyright 2019, the MIDOSS project contributors, The University of British Columbia,
# and Dalhousie University.
#
# 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
#
# https://www.apa... |
from torch import nn
class BasicBlock(nn.Module):
def __init__(self, num_cells=5, kernel_size=33, in_channels=256,
out_channels=256, dropout_rate=0.25,
norm_layer=None, activation=None):
super(BasicBlock, self).__init__()
self.num_cells = num_cells
self.... |
#!/usr/bin/env python3
import os
import sys
import signal
from time import monotonic as timer
from subprocess import Popen, PIPE, TimeoutExpired
import itertools
import csv
from pprint import pformat
from multiprocessing import Pool
# Constants
logics = ["lia", "strings", "slia"]
primitives = 6
generations = 20
files... |
from talon import webview, ui, cron
from talon.engine import engine
from talon.voice import Context
import functools
from .misc.repeat import get_agains, get_again_history
from .utils import format_keys
from .show_choices import show_choices
from .macro import is_recording, display_macro, macro_record_phrase, macro_st... |
from enum import Enum, unique
__all__ = [
'ImportStatus', 'STATUS_MESSAGE', 'get_row_error_message', 'Error', 'IMPORT_RENAME_ZH',
'IMPORT_ERROR_RENAME', 'EXPORT_RENAME_ZH'
]
@unique
class ImportStatus(Enum):
UPLOADED = 4001
READING = 4002
VALIDATING = 4003
IMPORTING = 4004
COMPLETED = 40... |
import os
import pickle
import random
import re
import string
import faiss
import hdbscan
import numpy as np
import umap
import xxhash
from datasketch import MinHash, MinHashLSH
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from spacy.lang.en import English
from spacy.lang.it import Itali... |
import os
import sys
import re
from os import mkdir
import subprocess
from datetime import datetime
from typing import Dict, List, Union
import argparse
USER = 'omid'
PICTURES = f'/home/{USER}/Pictures'
DIR_PATH = PICTURES
SS_PATH = os.path.join(DIR_PATH, 'SS')
INDEX_ROOT = os.path.join(SS_PATH, '_Index')
BACKUP_PATH ... |
import cv2
import os
import numpy as np
import torch
def create_lr_image(img, is_fp16):
if img.shape[2] == 3: img = img[:, :, [2, 1, 0]]
elif img.shape[2] == 4: img = img[:, :, [2, 1, 0, 3]]
img = torch.from_numpy(np.transpose(img, (2, 0, 1))).float()
if is_fp16: img = img.half()
return img.unsqu... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""cisco-dnac-platform-syslog-notifications Console Script.
Copyright (c) 2018 Cisco and/or its affiliates.
This software is licensed to you under the terms of the Cisco Sample
Code License, Version 1.1 (the "License"). You may obtain a copy of the
License at
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 26 10:55:11 2020
@author: <NAME> OrangeFrance/TGI/OLS/SOFT_LANNION
"""
# Some standard imports
import io
import os
from sys import argv
import re
import requests
import numpy as np
# acumos import
from acumos.modeling import Model, List, Dict, crea... |
import vtk
from vtk.util import numpy_support
import math
def poly_to_img(poly, origin=None, dim=None, spacing=(1.0, 1.0, 1.0)):
# compute dimensions and origin
bounds = [0 for _ in range(6)]
poly.GetBounds(bounds)
if dim is None:
dim = [0 for _ in range(3)]
for idx_dim in range(3):
... |
import os
import pytest
import shutil
import pandas as pd
from pyspark.sql import SparkSession
from pyspark.sql import DataFrame
from gensim.models import KeyedVectors
from gensim.models import Word2Vec as GensimW2V
from pyspark.ml.feature import Word2VecModel as SparkW2VModel
from node2vec.embedding import Node2VecBa... |
# coding: utf-8
#
# Py3 only
from __future__ import print_function
import os
import uuid
import pathlib
import shutil
import time
import io
import json
import traceback
import numpy as np
import imageio
import tornado.ioloop
import tornado.web
import tornado.websocket
from PIL import Image, ImageOps
from tornado impo... |
import datetime
import hashlib
import json
import re
import secrets
import binascii
import aiosqlite
from sanic_session import Session
async def date_time():
return str(datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S"))
async def user_name(request):
if not request.ctx.session.get('id') or request.ctx.s... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import csv
import _csv # typeshed is totally broken with csv module right now
import itertools
from io import StringIO
from typing import Iterator, List, Optional, TextIO, Union
from ..exceptions import DialectException
def _replace_invalid_c... |
#!/usr/bin/env python
from hlpr_single_plane_segmentation.srv import *
from ar_track_alvar_msgs.msg import AlvarMarkers
import rospy
import math
import tf
import tf2_ros
import tf2_geometry_msgs
from geometry_msgs.msg import Pose
GRID_WORLD_WIDTH = 5
GRID_WORLD_HEIGHT = 5
x_side = 0.1
y_side = 0.1
markers = {}
tfB... |
import os
import sys
import argparse
import re
import xml.etree.ElementTree as xml_et
from xml.dom import minidom
assert sys.version_info >= (3, 5)
def scan_cpp(base_path, rel_project_path):
test_project_path = os.path.join(base_path, rel_project_path)
if not os.path.isdir(test_project_path):
print('... |
from dataclasses import dataclass
from typing import Dict
import pytest
from magda.decorators import accept, produce, finalize
from magda.module import Module
from magda.testing import ModuleTestingWrapper
@dataclass(frozen=True)
class RawData(Module.Interface):
data: str
def __getitem__(self, index):
... |
#!/usr/bin/python
# -*- coding: iso-8859-1 -*-
"""Various helper functions related to VTK.
"""
import vtk
def set_mapper_input(mapper, data):
""" VTK 5 and 6 function to set a mapper input """
try:
mapper.SetInput(data)
except AttributeError:
mapper.SetInputData(data)
def pointCloudActor... |
import numpy as np
from decimer_segmentation.complete_structure import *
def test_get_bounding_box_center():
# Determine the center of a given polygon bounding box
test_bbox = np.array([[1, 1], [2, 1], [3, 1], [3, 0], [2, 0], [1, 0]])
expected_result = np.array([2, 0.5])
actual_result = get_bounding_b... |
#If you are using virtualenv, it is fine to install tkinter using sudo apt-get install python-tk(python2), sudo apt-get install python3-tk(python3), and and it will work fine in the virtual environment
from math import *
from sympy import *
from subprocess import call
from matplotlib.widgets import Slider, Button, Te... |
import json
from django.conf import settings
from django.contrib.auth.models import Permission
from django.core.exceptions import PermissionDenied
from django.http import JsonResponse
from django.shortcuts import redirect
from django.urls import path, include, reverse
from django.utils.html import format_html, escapej... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# This code is a test of a nearest neighbor algorithm. It measures
# times for finding all nearest neighbors (ie the nearest neighbor for
# each point in a set of points). In v0, test sets are 2D or 3D with
# x,y coordinates uniformly random in a unit square. In a futur... |
#-*- codeing =utf-8 -*-
#@Time:2020/6/8 12:13
#@Author: Demogorgon_Moriarty
#@File:getData.py
#@Software:PyCharm
# -*- coding:utf-8 -*-
import requests
import re
from bs4 import BeautifulSoup
from lxml import etree
import urllib.error,urllib.request
import sqlite3
findTitle=re.compile(r'target="_blank">(.*)</a></div... |
import os
import yaml
import json
from datetime import datetime
from src import custom_train_loop
import numpy as np
import pandas as pd
import torch
import random
from scripts.utils import plot_loss
def seed_all(seed):
np.random.seed(seed)
random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_s... |
#!/usr/bin/env python
import argparse
import json
import os.path
import re
import subprocess
import sys
DEFAULT_FILE_PATTERN = r".*\.[ch](pp)?"
# @@ -start,count +start,count @@
CHUNK_PATTERN = r"^@@\s+-\d+,\d+\s+\+(\d+)(?:,(\d+))?\s+@@"
def run_shell_command(arguments, process_name=None):
"""Executes a shell... |
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 3 14:36:14 2020
@author: <NAME>
"""
from pandas import Series
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from matplotlib import pyplot as plt
from sktime.utils.load_data import load_from_arff_to_datafra... |
#!/usr/bin/python
#!/usr/bin/python
from __future__ import absolute_import, division, print_function
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: ucs_fabric_eth_lac_pc
short_descr... |
# -*- coding: utf-8 -*-
"""
Command line interfaces
=======================
A simple command line interface, with the command h5plot.
The command should look something like this::
h5plot myfile.h5 --x-data=x --y-data=y --scale=linear\
--x-min=1 --x-max=10 --y-min=1 --y-max=10 --output=fig1.png
h5plot my... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of cryptidy module
"""
The cryptidy module wraps PyCrpytodome(x) functions into simple
symmetric and asymmetric functions
Versioning semantics:
Major version: backward compatibility breaking changes
Minor version: New functionality
Pat... |
'''Provides model classes for application.'''
# pylint: disable=invalid-name
import math
from enum import Enum
from typing import Dict
from typing import List
from typing import NamedTuple
from typing import Optional
from typing import Tuple
from . import segments
class Filter:
'''Filters are used to select lin... |
from mmseg.apis import inference_segmentor, init_segmentor
from mmpose.apis import (get_track_id, inference_top_down_pose_model,
init_pose_model, vis_pose_tracking_result)
from mmdet.apis import inference_detector, init_detector
import mmcv
import os
import cv2
from argparse import ArgumentPar... |
#!/usr/bin/env python
# encoding: utf-8
import os
import sys
import uuid
import logging
import logging.config
import random
import requests
from bottle import run, post
CONFIG = None
BACKUP_JOKES = None
# Production configuration
class Config(object):
def __init__(self):
""" Joke variables """
se... |
from __future__ import absolute_import, division, print_function
from __future__ import unicode_literals
import numpy as np
from random import randint
import pytest
from mmgroup.mm import mm_sub_test_prep_xy
from mmgroup import mat24 as m24
from mmgroup.tests.spaces.sparse_mm_space import SparseMmV
from mmgroup.t... |
# Modified by nemoramo.
# This script slightly change the original code from NeMo. The split mechanism
# is based on subsegments and uses torchaudio to speed up duration calculation.
#
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# y... |
# Databricks notebook source
# Shared settings
user_name = None # Should only contain alpha-numeric and underscores
# Names are used here to prevent collisions if users are in the same Databrick workspace or AML Workspace
model_dataset_name = 'model_dataset_{0}'.format(user_name)
pyspark_experiment_name = 'pyspark_tax... |
import os
import re
from collections import defaultdict
from io import StringIO
from unittest import mock
import dateutil.tz
import pytest
from lxml import etree
from nikola.nikola import Nikola, Post
from nikola.utils import LocaleBorg, TranslatableSetting
def test_feed_is_valid(rss_feed_content, rss_schema):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
================================================
common_colocated_gates
================================================
This program reads colocated gates files from two radars
and creates a new file with the gates that are common to
both radars
"""
# Author: fvj
#... |
import copy
from functools import partial
MONTH = 30
class Stomach():
force = False
class Movement():
def __enter__(self):
print('조혜련의 동작과', end=' ')
return True
def __exit__(self, type, value, traceback):
return True
class Ment():
def __enter__(self):
print('멘트를 들... |
# -*- coding: utf-8 -*-
import numpy as np
from collections import namedtuple
from numpy.linalg import LinAlgError
from scipy.optimize import nnls
from scipy.stats.mstats import mquantiles
from .utils import cached_property
Regression = namedtuple("Regression", 'stat_w stat_y r2')
class StatMixin(object):
def ... |
import numpy as np
import torch
import torch.nn as nn
from others.utils import suggested_ed2_path
from models.decoder_tf import TransformerDecoder
class NegativeDistanceScore(object):
'''
functions: get the distance score to compute the loss
'''
def __init__(self):
# pre-compute ... |
import json
import os
from contextlib import suppress
from pathlib import Path
from typing import Dict
from typing import List
from typing import Union
import click
from rich.console import Console
from rich.table import Table
from cos.utils import create_folder
from cos.utils import create_json_file
# types
TASK_DA... |
#!/usr/bin/env python
# Author: <NAME>; Feb/2020
# *************************************** #
import os
import logging
from nltk.corpus import stopwords
import datetime
import sys
from os.path import basename
import warnings
from sklearn import preprocessing
from sklearn.externals import joblib
import optparse
import... |
#from test import *
from train import *
from utils import *
from pointData import PointFeatures, SampleSet
import numpy as np
from name_generator import generate_names,re_generate_names
from analysis import *
import time
from cvinfo import *
import pandas as pd
import os
from collections import defaultdict
FILEPATH_SA... |
# -*- coding: utf-8 -*-
from datetime import datetime
import os
from pathlib import Path # Python 3.6+ only
import backtrader as bt
import pandas as pd
from pandas_datareader import data as pdr
import matplotlib.pyplot as plt
from dotenv import load_dotenv
__updated__ = "2021-08-09"
# proxy servers for internet con... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# =============================================================================
## @file
# Simple colorization of strings
# @author <NAME> <EMAIL>
# @date 2013-02-10
# =============================================================================
"""Simple colorization... |
from __future__ import division
import numpy as np
import src.snpgetter as sg
import time, sys, traceback, argparse
import src.printing as pr
import pandas as pd
def l2(x, n):
sq = np.square(x)
return sq - 1/n
def getBlockLefts(coords, max_dist):
M = len(coords)
j = 0
block_left = np.zeros(M)
for i ... |
import discord
import config
from django.db import models
from django.utils import timezone
from utils.user import get_user_obj
from web.apps.configs.models import TrophyRoomConfig
from django.contrib.postgres.fields import JSONField, ArrayField
class Case(models.Model):
CASE_STATUSES = (
('unknown', 'Unk... |
#####################################
##
## Imports
##
#####################################
import warnings
warnings.filterwarnings("ignore")
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from collections import Or... |
from pluginnet.sun397.sun397 import sun397_data_transform_val, sun397_data_transform_train, \
CrossEntropyLossOneHot, SUN397
from pluginnet.sun397.metrics import create_softmax_metrics_dictionary
from pluginnet.common.model import build_plugins
import torchvision
import torch
import torchvision.models as models
imp... |
import socket
import logging
import time
from traceback import format_exc
from threading import Thread
from ssl import SSLError
from websocket import websocket
from connection import Connection
from errors import HandshakeError
class Server(object):
"""
Websocket server, manages multiple client connections.
... |
"""Implementation of the 'einsum' macro."""
from opt_einsum import contract, contract_expression
from ..lib import InferenceError, macro
from . import primitives as P
def _tensordot(g, a, b, *, axes):
"""Tensordot for myia.
This a a generalized version of dot where the
multiplication/contraction can ha... |
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
This script is used to convert the SSL Framework models to the Detectron2 compatible
models.
"""
import argparse
import logging
import sys
... |
from __future__ import print_function
import six
import sys
from datetime import datetime
from insights import dr, rule
from insights.util import utc
RENDERERS = {}
_FORMATTERS = {}
def get_formatter(name):
"""
Looks up a formatter class given a prefix to it.
The names are sorted, and the first matchin... |
from __future__ import division
import os,copy
import annlib_adaptbx
import libtbx.load_env
annlib_under_build = libtbx.env.under_build("annlib_adaptbx")
annlib_adaptbx_dir = os.path.dirname(annlib_adaptbx.__file__)
annlib_under_build_include = os.path.join(annlib_under_build,"include")
annlib_dir = os.path.join(os.p... |
#!/usr/bin/env python
import json
import logging
import os
import random
import string
import sys
import unittest
from time import sleep
from orbitdbapi.client import OrbitDbAPI
base_url=os.environ.get('ORBIT_DB_HTTP_API_URL')
def randString(k=5, lowercase=False, both=False):
if both:
return ''.join(rand... |
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import absolute_import
import argparse
import sys
import numpy as np
import scipy.misc
import os
import glob
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
import json
import collections
import random
prev = 0
de... |
# -*- coding: utf-8 -*-
import os.path
use_fitsio = False
try:
import fitsio
use_fitsio = True
except:
from astropy.io import fits
use_fitsio = False
import matplotlib.pyplot as plt
import numpy as np
import spiderman
from scipy.interpolate import interp1d
def gen_grid(l1,l2,logg=4.5, response = Fals... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.