content stringlengths 5 1.05M |
|---|
from __future__ import absolute_import
from sqlbuilder import smartsql
from ascetic.mappers import mapper_registry, Mapper
from ascetic.relations import ForeignKey, RelationDescriptor
from ascetic.utils import cached_property, classproperty, to_tuple
try:
str = unicode # Python 2.* compatible
string_types = (... |
import numpy as np
import time
import datetime
from . import do_cavity_freq_sweep, find_extreme, set_calibration_val, \
set_single_demod_freq, get_calibration_val, set_up_sequence, \
sweep1d, measure, measure_ssb, sweep2d_ssb, check_seq_uploaded, get_demod_freq
from .sequencing import make_spectroscopy_SSB_se... |
# -*- coding: utf-8 -*-
"""
Configures a workspace with a list of Bitbucket repositories.
Author: Eduardo Ferreira
"""
import requests
import bauen.config as config
import bauen.repository as repository
_BITBUCKET_DIRECTORY = config.get_work_directory('bitbucket')
def _get_access_token(key: str, secret: str) ->... |
import gzip
#TODO: find a more optimal means of compressing data
def compress(data):
return data#gzip.compress(data)
def decompress(data):
return data#gzip.decompress(data) |
class NoCommitsError(Exception):
pass
|
import collections
import datetime
import logging
import math
import time
# some constants to help define the states we could be in
OFF = 0
ON = 1
# can't talk to the cistern
COMM_ERROR = -1
# a pipe may be broken, the pump may be broken
FAULT = -2
DRIVER_SYSFS = "sysfs"
DRIVER_GPIOZERO = "gpiozero"
class Pump:
... |
#!/usr/bin/python3
import time
import pyaudio
import audioop
import pigpio
import numpy as np
import math
import threading
from flask import Flask
from util import fft, get_rgb_vol, get_rgb_freq_vol, colors, transform_brightness
# Raspberry PI GPIO pins
R = 17
G = 22
B = 24
# Microphone settings
fs = 32000
sample_f... |
from itertools import chain
from lib import microdata as md
from lib.htmlephant_extensions import Main
from lib.htmlephant import (
NOEL,
Anchor,
H1,
MDMeta,
OGMeta,
Span,
StdMeta,
Title,
)
from includes import (
collection,
project_card,
section,
subnav,
)
FILENAME_G... |
class Solution:
def buddyStrings(self, A: str, B: str) -> bool:
if len(A) != len(B):
return False
stack = []
for i in range(len(A)):
if A[i] != B[i]:
if len(stack) >= 2:
return False
else:
stack... |
#!/usr/bin/env python3
"""
Python to arduino serial sample
"""
import serial
import time
__author__ = "Hackspace"
__license__ = "MIT"
# sirib0400
def main():
# start serial connection, change first argument based on microcontroller's serial port
ser = serial.Serial('/dev/cu.usbserial-14130', 9600, timeout=1)
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Test Notification Endpoint"""
from unittest.mock import patch
import requests_mock
from acapi2.exceptions import (
AcquiaCloudNotificationFailedException,
AcquiaCloudTimeoutError,
)
from acapi2.resources.notification import Notification
from acapi2.tests imp... |
import os
import numpy
import json
import sys
import gzip
class Provider:
def __init__(self, dataset, root='.', audio_kind='mfcc', extra_train=True):
self.root = root
self.dataset = dataset
self.audio_kind = audio_kind
self.img = {}
self.txt = {}
self.img['train'] = numpy.load(open("{}/data/... |
import torch
from PIL import Image
import torchvision.transforms as transforms
from configs import model_config
from parse_config import get_model
model = get_model(model_config.arcface)
img_trans = transforms.Compose([
transforms.Resize(size=(112, 112)),
transforms.ToTensor(),
# transforms.Normalize(0)
... |
# Made by www.Movsisyan.info
import json
import requests
class Bot:
"""A simple class to ease bot access"""
def __init__(self, url, log = None):
"""
url: bot endpoint\n
log: bot log filepath
"""
self.url = url
self.log = log
def set_log(self, filepath):
... |
#!/usr/bin/env python3
"""
Author : Ken Youens-Clark <kyclark@gmail.com>
Date : 2020-01-24
Purpose: Convert EJSCREEN data to Scrutinizer format
"""
import argparse
import csv
import os
import re
from typing import Dict, List, NamedTuple, Optional, TextIO
class Args(NamedTuple):
file: List[TextIO]
headers: ... |
import atexit
import sys
from subprocess import Popen, TimeoutExpired
from time import sleep
from typing import Optional, Callable, Dict
from telepresence.runner import Runner
def kill_process(process: Popen) -> None:
"""Kill a process, make sure it's a dead."""
if process.poll() is None:
process.ter... |
#!usr/bin/env python3
# test/test_youtube_data.py - testing data wrangling
# - testing graph output
# by Shivan Sivakumaran
from tubestats.youtube_data import YouTubeData
from tests.test_settings import set_channel_ID_test_case
import pickle
from pathlib import Path
from datetime import date... |
#
# @lc app=leetcode id=405 lang=python3
#
# [405] Convert a Number to Hexadecimal
#
# @lc code=start
class Solution:
def toHex(self, num: int):
if num == 0:
return '0'
if num < 0:
num = (1 << 32) + num
hx = [str(i) for i in range(0, 10)] + ['a', 'b', 'c', 'd', 'e', ... |
# Activate Python venv for the script - uncomment to run script on commandline
activate_this_file = "/path/to/bin/activate_this.py"
execfile(activate_this_file, dict(__file__ = activate_this_file))
import cx_Oracle
import argparse
import sys
import csv
from tqdm import tqdm
sys.path.insert(0, '/path/to/gwas_data_sour... |
import json
import os.path
import torch
from tqdm import trange
from lib.models.gpt import LeanGPTConfig, LeanGPTForPreTraining
HERE = os.path.abspath(os.path.dirname(__file__)) + '/'
def test_gpt_forward_backward(filename: str = HERE + "gpt_test_data.pth"):
"""
tests the correctness model outputs, loss and... |
from django import template
register = template.Library()
@register.inclusion_tag("common/paginator.html")
def paginator(items):
adjacent_pages = 4
num_pages = items.paginator.num_pages
page = items.number
start_page = max(page - adjacent_pages, 1)
if start_page <= 3:
start_page = 1
... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from... |
# 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
#
# Authors:
# - Wen Guan, wen.guan@cern.ch, 2017-2018
import logging
import os
import shutil
impor... |
#!/usr/bin/env python
"""
@author: Francis Obiagwu
@software: SecureDocumentSharing
@file: DSMessageType.py
@time: 6/6/18 7:16 PM
"""
class DSMessageType:
CONNECT = b'CONNECT'
CREATE = b'CREATE'
CAUTH = b'CAUTH'
S_EDIT = b'S_EDIT'
S_COMMIT = b'S_COMMIT'
S_RELEASE = b'S_RELEASE... |
from django.http import HttpResponse
from django.shortcuts import render
from . import context_processors
def home(request):
return render(request, 'MundusInvicte/home.html')
def about(request):
return render(request, 'MundusInvicte/about.html') |
from argparse import ArgumentParser
from sys import exit
from string import Template
from os import error, path
from decouple import config
def read_source(source_path):
source_text = ""
if not path.exists(source_path):
raise FileNotFoundError("Source File Not found")
with open(source_path, "r") a... |
import model
def izpis_igre(igra):
tekst = (
'=========================================================\n\n'
'{pravilni_del_gesla}\n\n'
'Število preostalih poskusov: {stevilo_preostalih_poskusov}\n\n'
'Nepravilni ugibi: {nepravilni_ugibi}\n\n'
'{obesen}'
'==========... |
class Solution(object):
def coinchange(self, coins, number):
dp = [[0 for x in range(number+1)] for i in range(len(coins)+1)]
dp[0][0] = 1
for row in range(1, len(coins)+1):
dp[row][0] = 1
for col in range(1, number+1):
... |
from django.db import models
import cloudinary
from cloudinary.models import CloudinaryField
class Image(models.Model):
caption = models.CharField(max_length=100)
title = models.CharField(max_length=200, default='')
description = models.TextField(default='')
location = models.TextField(max_length=30,nu... |
import discord
import requests
import urllib3
from discord.ext import commands
from bs4 import BeautifulSoup
from pprint import pprint
import re
embedPlayer = discord.Embed(
title='SayuBOT Player',
description='Digite um numero entre 1 e 5',
colour=0xe74c3c
)
... |
import torch
import torch.nn
import torch.nn.functional as F
import torch.nn as nn
import numpy as np
import pdb
class NN(torch.nn.Module):
def __init__(self, in_dim, out_dim, n_hid):
super(NN, self).__init__()
self.in_dim = in_dim
self.out_dim = out_dim
self.n_hid = n_hid
... |
#!/usr/bin/env python3
import asyncio
from network import client, server, keys
async def test_001():
server_001 = server.Server()
await server_001.start()
client_001 = client.Client()
await client_001.start()
assert client_001.data_session is None
client_002 = client.Client()
await cli... |
from .twitter_list_mgmt import *
from .helpers import *
__version__ = "0.1.2"
|
#main program
import spacy
import pandas as pd
import preprocess
from preprocess import data_clean #preprocess.py
import dataframes
from dataframes import dataframing
import tokenise
from tokenise import tokenisation
import frequency
from frequency import word_frequency
import topwords
from topwords import most_repeate... |
"""
A skeleton/mock-up of the SecureCRT API, so you can write SecureCRT Python script
logic in an IDE, without having to actually install SecureCRT.
How to use:
1. copy to the directory w/ your SecureCRT scripts
2. In your scripts that make 'crt' calls, do this at the top, just after imports:
# load fake SecureCRT AP... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from steerable.SCFpyr_NumPy import SCFpyr_NumPy
import steerable.utils as utils
import cv2
import torch
import torchvision
# img_size=256
img=cv2.imread("./assets/lena.jpg",0)
# img=cv2.resize... |
from abc import ABCMeta, abstractmethod
from exception.SemanticError import SemanticError
class Type(metaclass=ABCMeta) :
size_unknown = -1
@abstractmethod
def size(self):
pass
def alloc_size(self):
return self.size()
def alignment(self):
return self.alloc_size()
... |
import argparse
from pathlib import Path
import matplotlib as mpl
import pandas as pd
mpl.use("Agg")
from deep_sentinel import utils
from deep_sentinel.models import dnn
activation_funcs = dnn.model.utils.ActivationFunc.choices()
def get_parser():
parser = argparse.ArgumentParser(description="Sample implement... |
class Solution:
"""
@param n: An integer
@return: True or false
"""
def checkPowerOf2(self, n):
# write your code here
if n == 1:
return True
if n <= 0:
return False
appera = 0
for item in bin(n)[2:]:
if item == '1' and appera ==... |
from subprocess import Popen, PIPE, STDOUT
from shlex import split
import sys
def run_command(cmd):
try:
print(f"executing: {str(cmd)} ")
process = Popen(split(cmd), stdout=PIPE, stderr=STDOUT, encoding='utf8')
while True:
output = process.stdout.readline()
if outpu... |
"""
Django settings for romme_net project.
Generated by 'django-admin startproject' using Django 3.2.8.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathl... |
# -*- coding: utf-8 -*-
# <nbformat>4</nbformat>
# <markdowncell>
# # imports
# <codecell>
from importlib import reload
from collections import namedtuple
import inspect
from itertools import groupby
from datetime import date
from functional import seq
from functools import reduce, partial
from glob import glob
imp... |
# Generated by Django 3.2 on 2021-05-14 18:32
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('django_api', '0004_rename_ispicth_user_ispitch'),
]
operations = [
migrations.CreateModel(
name='Cas'... |
import argparse
import zipfile
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--zip', type=str, required=True)
parser.add_argument('--file', type=str, required=True)
return parser.parse_args()
def update_zip():
args = parse_args()
with zipfile.ZipFile(args.zip, 'a'... |
import json
from dao.db_dao import DBDao
class SaveResult:
@staticmethod
def save(service_invoke_graph,final_root_services,services_diagnisis_results):
dbDao = DBDao()
fault_ids = dict()
# 存储识别出的故障服务到故障服务表
for fault_service_id in final_root_services:
serviceNode = ... |
"""
868. Binary Gap
"""
class Solution:
def binaryGap(self, N):
"""
:type N: int
:rtype: int
"""
res, d = 0, -32
while N:
if N & 1:
res, d = max(res, d), 0
d += 1
N >>= 1
return res
... |
import datetime
import pandas as pd
from time import time
from src.kmeans import KMeans
from sklearn import metrics
from sklearn.metrics import pairwise_distances, adjusted_rand_score
party_map = {
'Frente Amplio': 0,
'Partido Nacional': 1,
'Partido Colorado': 2,
'La Alternativa': 3,
... |
# coding: utf-8
# In[1]:
#################################################################################
# Step 1: Create a table in our database to hold the stock data
#################################################################################
# import some standard modules we can use to download URLs
imp... |
import torch
import torch.nn as nn
from lib.net.rpn import RPN
from lib.net.rcnn_net import RCNNNet
from lib.config import cfg
#from torch_cluster import fps
class PointRCNN(nn.Module):
def __init__(self, num_classes, num_point=512, use_xyz=True, mode='TRAIN',old_model=False):
super().__init__()
s... |
frutas = open('frutas.txt', 'r')
numeros = open('numeros.txt', 'r')
lista_frutas = []
lista_numeros = []
for i in frutas:
lista_frutas.append(i)
for i in numeros:
lista_numeros.append(i)
print(lista_frutas)
print(lista_numeros) |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-09-23 12:20
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("events", "0004_auto_20170921_1420")]
operations = [
migrations.AddField(
mod... |
#!/usr/bin/env python3
"""Calculate evaluation metrics for a trained model."""
import argparse
from time import perf_counter
import torch
import pandas as pd
from pose3d_utils.coords import ensure_homogeneous
from tele.meter import MeanValueMeter, MedianValueMeter
from tqdm import tqdm
from tabulate import tabulate... |
#!/usr/bin/env python
import os.path as os_path
import sys
_HERE_PATH = os_path.dirname(os_path.realpath(__file__))
_SRC_PATH = os_path.normpath(os_path.join(_HERE_PATH, '..', '..', '..', '..'))
old_sys_path = sys.path[:]
sys.path.append(os_path.join(_SRC_PATH, 'third_party', 'node'))
import node, node_modules
SERVE... |
from elf.types.section.header import SHType
from ..section_base import ElfSection
class NoBitsSection(ElfSection):
TYPE = SHType.SHT_NOBITS
@property
def data(self):
return bytearray(len(self))
@data.setter
def data(self, other):
raise NotImplementedError(f'Cannot set data for {t... |
from flask import request, Blueprint, jsonify, make_response
import json
from app.api.v1.models.office import PoliticalOffice
politicaloffice= Blueprint('politicaloffice',__name__,url_prefix='/api/v1/')
class Office():
@politicaloffice.route('/office',methods=['POST'])
def create_political_office():
o... |
import pandas as pd
import numpy as np
import sklearn as sk
from sklearn import preprocessing
def preprocess_data(df, schema, process_label=False):
df = df.copy()
preprocess_dict = {}
for fea in schema['features']:
if fea['name'] != schema['label']:
preprocess_dict[fea['name']] = {"typ... |
"""Transport views."""
from django import http
from django.core.urlresolvers import reverse, reverse_lazy
from django.utils.translation import ugettext as _, ugettext_lazy
from django.views import generic
from django.contrib.auth import mixins as auth_mixins
from django.contrib import messages
from . import backends... |
#!/usr/bin/env python
import logging
import urllib
import uuid
import datetime
import json
import tempfile
from zipfile import ZipFile,ZipInfo,ZIP_DEFLATED
from io import BytesIO
import pkg_resources
from flask import redirect
# aws
from botocore.exceptions import ClientError
# common
# flask
from werkzeug import secu... |
#
# Copyright 2017-2018 Government of Canada
# Public Services and Procurement Canada - buyandsell.gc.ca
#
# 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/LIC... |
# -*- coding: utf-8 -*-
"""
Current WsgiDAV version number.
http://peak.telecommunity.com/DevCenter/setuptools#specifying-your-project-s-version
http://peak.telecommunity.com/DevCenter/setuptools#tagging-and-daily-build-or-snapshot-releases
"""
__version__ = "1.1.0"
|
import numpy as np
import xarray as xr
class RDdata():
# container for an np array with pre-allocated memory for future values
# for a single trial in an RD sim
def __init__(self, a, steps, namePositions):
# 'a' is hist data as np.array, with vars as columns and steps as rows
# 'steps' is ... |
from bs4 import BeautifulSoup
import urllib
import urllib2
url = "http://www.portal.state.pa.us/portal/server.pt/community/2014/21611/february_2014_warn_notices/1725222"
content = urllib2.urlopen(url).read()
soup = BeautifulSoup(content)
for link in soup.find_all('a'):
print(link.get('href'))
for table in soup.... |
from django_filters.rest_framework import DjangoFilterBackend, FilterSet
from rest_framework import filters, viewsets
from pretix.api.serializers.event import EventSerializer, SubEventSerializer
from pretix.base.models import Event, ItemCategory
from pretix.base.models.event import SubEvent
class EventViewSet(viewse... |
x = 9
def f():
return x
|
from ebs_snapshots import ebs_snapshots_daemon
import sys
import kayvee
import logging
import traceback
logging.basicConfig(level=logging.INFO)
if __name__ == "__main__":
try:
ebs_snapshots_daemon.snapshot_timer()
except Exception as e:
logging.error(kayvee.formatLog("ebs-snapshots", "error", "... |
"""Test that each reference submission can run a train and eval step.
This is a brief test that runs the for the workload and reference submission
code for one train and one eval step for all workloads, without the real data
iterator because it is not realistic to have all datasets available at testing
time. For end-t... |
"""
Implementations of the Boid and Swarm classes.
"""
import random
import numpy as np
#Each instance of the Boid class represents a particular boid in the group
class Boid(object):
def __init__(self,x,y,vx,vy,swarmSize,behaviour):
self.position = np.array([x,y])
self.velocity = np.array([vx,vy])
self.swarmSi... |
import argparse
import numpy as np
import torch
import torch.nn.init as init
import torch.nn as nn
import torch.distributions as D
import torch.optim as optim
import matplotlib.pyplot as plt
from uncertainty_modeling.mdn.mixture_same_family import MixtureSameFamily
from uncertainty_modeling.gen_data import gen_datagri... |
# Future Imports
from __future__ import absolute_import
# Python Standard Library Imports
import decimal
import json
class DecimalEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, decimal.Decimal):
return "%.2f" % obj
elif type(obj) == set:
return list(... |
# Copyright © 2019 Province of British Columbia
#
# 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... |
'''
Python Newb Code Snippet #18.
90-Convert almost any audio format
Tested on Linux Mint and Windows 7
https://stevepython.wordpress.com/
Requires ffmpeg installed on system.
free from ffmpeg.org
https://www.ffmpeg.org/documentation.html
linux:sudo apt-get install ffmpeg
'''
import subprocess
ff_comm = "ffmpeg -... |
# -*- coding:utf-8 -*-
from inference.river_info_template_fd import river_info_rules_fd
from inference.book_info_template_fd import book_info_rules_fd
from inference.book_person_template_fd import book_person_rules_fd
from inference.movie_info_template_fd import movie_info_rules_fd
from inference.movie_person_template... |
import random
import os
import operator
from PIL import Image, ImageDraw, ImageEnhance
import numpy as np
import cv2
import matplotlib.pyplot as plt
import pandas as pd
from .base_functions import calc_rows_hue_aggregation
def check(img, model):
short_to_predict = []
hsvImage = cv2.cvtColor(img, cv2.C... |
"""
Description: This script runs LP on synthetic data
"""
from utils.networkx_operations import *
from utils.pandas_operations import *
from utils.time_operations import *
# from utils.steiner_tree_v3 import *
from tqdm import tqdm
# import pickle
import pandas as pd
import numpy as np
import copy
import argparse
im... |
#!/usr/bin/env python
'''
rovershout20.py Shout at the Brookstone Rover 2.0 to make it turn and run.
Copyright (C) 2014 Simon D. Levy
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either ... |
class BoundingBox(object):
def __init__(self, min_x, max_x, min_y, max_y):
self._min_x = min_x
self._max_x = max_x
self._min_y = min_y
self._max_y = max_y
def bbox
|
import unittest
from algorithms.algorithms.binarysearch import binary_search
class BinarySearchTest(unittest.TestCase):
def test_all_elements_in_an_odd_length_list(self):
"""All elements in a given list should return true to test"""
odd_length_array = list(range(5))
even_length_array = li... |
#!/usr/bin/python3.7
# Copyright 2020 Aragubas
#
# 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... |
import requests
import sys
import json
#CREATE PROJECT
print("Creating project")
filepath = 'new_project.json'
with open(filepath) as fh:
mydata = fh.read()
response = requests.post('http://localhost:3000/replan/projects/',
data=mydata,
headers={'content... |
from jet_django.deps.rest_framework import viewsets, serializers
from jet_django.deps.rest_framework.decorators import list_route, detail_route
from jet_django.deps.rest_framework.generics import get_object_or_404
from jet_django.deps.rest_framework.response import Response
from jet_django.deps.rest_framework.serialize... |
import configparser
import logging
import requests
import time
from flask import flash
from flask import current_app as app
from warden_modules import regenerate_nav
from specter_importer import Specter
from config import Config
from utils import fxsymbol, pickle_it
from datetime import datetime
from message_handler im... |
from unittest import TestCase
from collections import namedtuple
from rx import Observable
from cyclotron_aio.runner import run
class RunnerTestCase(TestCase):
def test_run(self):
''' Creates a cycle with one sink driver.
'''
'''
MainDrivers = namedtuple('MainDrivers', ['drv1'])
... |
from datetime import timedelta
from typing import Optional, Union
from python_on_whales.client_config import DockerCLICaller
from python_on_whales.utils import ValidPath, run
class SwarmCLI(DockerCLICaller):
def ca(
self,
ca_certificate: ValidPath = None,
ca_key: ValidPath = None,
... |
from ..algorithms import *
import math
DEBUG = False
inf = float("infinity")
def branch_generator(game_state, adjacency_list, owner, alpha, beta, is_final, depth):
pruning = False
# branch init
branch = {}
branch['nodes'] = []
# data gathering from game state
player = game_state['player']
p... |
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5 import QtSvg
import chess.pgn
class BoardView(QWidget):
def __init__(self, parent, controller, cellSize):
super(QWidget, self).__init__(parent=parent)
self.cellSize = cellSize
self.controller = c... |
# -*- coding: utf-8 -*-
# This code is a part of BELA package: https://github.com/letuananh/bela
# :developer: Le Tuan Anh <tuananh.ke@gmail.com>
# :license: MIT, see LICENSE for more details.
"""
Common functions
"""
import re
import logging
import string
try:
from nltk import word_tokenize
NLTK_AVAILABLE ... |
from django.views.generic import (
View as DjangoView, RedirectView as DjangoRedirectView,
TemplateView as DjangoTemplateView
)
class View(DjangoView):
"""
Intentionally simple parent class for all views. Only implements
dispatch-by-method and simple sanity checking.
"""
class RedirectView(D... |
from abstract.instruccion import *
from tools.console_text import *
from tools.tabla_tipos import *
class create_db(instruccion):
def __init__(self, id_db, replace_, if_exists, owner_mode, line, column, num_nodo):
super().__init__(line, column)
self.id_db = id_db
self.replace_ = replace_
... |
from flask import request
from core.types.abnfToken import ABNFToken
from core.types.httpBuzzTokens import DefaultGadgets, MandatoryGadgetTokens, GadgetTokens
class HttpRequestPrototype:
def __init__(self, gadgets: None, method: str = "GET", request_target: str = "/",
http_version: str = "1.1", a... |
# vim: set fileencoding=<utf-8> :
'''DBSCAN using hdbscan'''
# universal
import os
import sys
# hdbscan
import hdbscan
def fitDbScan(X, min_samples, min_cluster_size, cache_out):
"""Function to fit DBSCAN model as an alternative to the Gaussian
Fits the DBSCAN model to the distances using hdbscan
Args:
... |
"""
make calls to the NASA API to retrieve a unique picture of space
last update by Ilyass on 5/14/21
"""
import requests
import json
#prepare to make the API call by setting up the parameters
URL_NeoFeed = "https://api.nasa.gov/planetary/apod"
params = {
'api_key': 'DEMO_KEY',
}
#make the actual API call and read t... |
from .interval_reader import *
from .interval import *
from .quant_rule import *
from .quant_dataset import * |
from enum import Enum, IntFlag
class Intents(IntFlag):
"""An integer flag bitshift object representing flags respective for each gateway intent type."""
GUILDS = 1 << 0
GUILD_MEMBERS = 1 << 1
GUILD_BANS = 1 << 2
GUILD_EMOJIS_AND_STICKERS = 1 << 3
GUILD_INTEGRATIONS = 1 << 4
GUILD_WEBHOOKS... |
#YOUR CODE GOES HERE
def check_email(s):
try:
user, www = s.split("@")
web, ext = www.split(".")
if not user or not web or not ext:
return False
return not any([user != "".join(filter(lambda x: x.isalnum() or x in ["_", "-"], user)),
web != "".join(filter(lam... |
# Created by Martin Strohalm, Thermo Fisher Scientific
# import modules
import os
import os.path
import tempfile
import uuid
from xml.sax.saxutils import escape
from ..helpers import *
from .converter import register, StringValueConverter, ImageValueConverter
from .common import NumberConverter, DDMapConverter, Statu... |
import freetx
my_key = freetx.Key("5KSZ5h6AvZUdavtystU7ytR5XAxVyqpzYWHp14n7XnTc1m6kaHY")
print(my_key.get_balance("mbch"))
tx_id = my_key.sweep("bitcoincash:qr2vny04sxzqn7zeuufgr3wh7gs89uvzvu6jgfd3ge")
# Sweep your all bch to dest address
print(tx_id)
outputs = [
("bitcoincash:qr2vny04sxzqn7zeuufgr3wh7gs89u... |
"""
Common UCTT plugins
"""
from typing import Dict, Any
from configerus.loaded import LOADED_KEY_ROOT
from uctt.plugin import Factory, Type
from uctt.environment import Environment
from .dict_output import DictOutputPlugin
from .text_output import TextOutputPlugin
from .combo_provisioner import ComboProvisionerPlu... |
from pathlib import Path
import unittest
import os
ROOT_DIR = Path(__file__).parent
class MyTestCase(unittest.TestCase):
def test_toci(self):
from src.toci.Toci import Toci
toci = Toci()
toc = toci.execute(os.path.join(ROOT_DIR, 'data/notebook.ipynb'))
expected_toc = """# Table ... |
import torch
pretrained_weights = torch.load('fcos_mstrain_640_800_r101_caffe_fpn_gn_2x_4gpu_20190516-42e6f62d.pth')
num_class = 2
# store = []
# for index, name in enumerate(pretrained_weights['state_dict']):
# store.append(name)
# a = store[500:]
# b = pretrained_weights['state_dict']['bbox_head.fcos_cls.weig... |
from SimpleXMLRPCServer import SimpleXMLRPCServer
def add(x, y):
return x + y
if __name__ == '__main__':
s = SimpleXMLRPCServer(('127.0.0.1', 8080))
s.register_function(add)
s.serve_forever()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.