content stringlengths 5 1.05M |
|---|
from subsystems.drivesubsystem import DriveSubsystem
import commands2
import wpilib
#time in seconds
ticksDistance = 0
class rotateArm(commands2.CommandBase):
def __init__(self, power: float, distance: float) -> None:
super().__init__()
self.power = power
self.distance = distance
d... |
#
# Copyright 2017 the original author or authors.
#
# 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... |
#! /usr/bin/env python3
import numpy as np
from PIL import Image
def load_raw(f, w=3280, h=3280):
# Metadata: width, height
# Metadata: pixelPacking
arr = np.fromfile(f, np.uint8, w*h*3//2).reshape((h,w//2,3)).astype('H')
# Image is big endian 12 bit 2d array, bayered.
# This is detailed in the TX... |
ANSI_COLOURS = [
'grey',
'red',
'green',
'yellow',
'blue',
'magenta',
'cyan',
'white'
]
for i, name in enumerate(ANSI_COLOURS):
globals()[name] = str(30 + i)
globals()['intense_' + name] = str(30 + i) + ';1'
def get_colours():
cs = ['cyan', 'yellow', 'green', 'magenta', 'r... |
#######################################################################
# Copyright (C) 2017 Shangtong Zhang(zhangshangtong.cpp@gmail.com) #
# Permission given to modify the code as long as you keep this #
# declaration at the top #
################################... |
import itertools
def flatten(*arg):
return [item for sublist in arg for item in sublist]
def intersection(*args):
result = set(args[0])
for i in range(1, len(args)):
result = result.intersection(set(args[i]))
return result
def is_unique(*item_lists):
all_items = flatten(*item_lists)
... |
import torch
import torch.nn as nn
from torch.autograd import Function
class GdnFunction(Function):
@staticmethod
def forward(ctx, x, gamma, beta):
ctx.save_for_backward(x, gamma, beta)
n, c, h, w = list(x.size())
tx = x.permute(0, 2, 3, 1).contiguous()
tx = tx.view(-1, c)
... |
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
**Callable creation utility unit tests.**
This submodule unit tests the public API of the private
:mod:`beartype._util.utilfunc.ut... |
from os import *
import traceback
import sys
if len(sys.argv) != 2:
print("Utilisation: %s fichier"%(sys.argv[0]))
exit(0)
SIZE=256
try:
f=open(sys.argv[1], O_RDONLY)
bs = read(f, SIZE)
while len(bs) > 0:
write(sys.stdout.fileno(), bs)
bs = read(f, SIZE)
close(f)
except OSEr... |
from falcor import *
def render_graph_DefaultRenderGraph():
g = RenderGraph('DefaultRenderGraph')
loadRenderPassLibrary('BSDFViewer.dll')
loadRenderPassLibrary('AccumulatePass.dll')
loadRenderPassLibrary('TemporalDelayPass.dll')
loadRenderPassLibrary('Antialiasing.dll')
loadRenderPassLibrary('B... |
import histogram_dct as hd
import pandas as pd
# load data
data = pd.read_excel(r'Example\distributions.xlsx')
# uniform distribution:
hd.histogram_dct(data['unf'], bin=12.5, name='uniform distribution')
# normal distribution:
hd.histogram_dct(data['nrm'], bin=4, name='normal distribution')
# exp distri... |
""" Python Character Mapping Codec generated from '8859-2.TXT' with gencodec.py.
Written by Marc-Andre Lemburg (mal@lemburg.com).
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
(c) Copyright 2000 Guido van Rossum.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,erro... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class Flip(nn.Module):
"""
Flip indices transformation.
Example:
>>> f = stribor.Flip()
>>> x = torch.tensor([[1, 2], [3, 4]])
>>> f(x)[0]
tensor([[2, 1],
[4, 3]])
>>> f = stribor.Flip([0, 1])
>>> f(x)[0... |
# ••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
# Copyright (c) 2018, S.J.M. Steffann. This software is licensed under the BSD
# 3-Clause License. Please see the LICENSE file in the project root directory.
# •••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••... |
from typing import Dict, Optional
from fastapi import APIRouter, Depends, HTTPException
from src.api.serializers import UserIn, UserOut, UsersOut
from src.services.auth import get_current_user, get_user_login_from_token
from src.services.users import (
create_user,
get_user_by_id,
get_user_by_login,
se... |
import maestro
import time
import numpy as np
import scipy as sp
import scipy.interpolate
import sys
a1 = 0.1
a2 = 0.26
# In degrees from straight config
ee_pos_list = [
np.array([0.12, 0.17]),
#np.array([0.12, 0]),
#np.array([0.14, 0]),
np.array([0.325, 0.12]),
np.array([0.12, 0.17]... |
import cv2
import numpy as np
#####################################
#adjust as per ratio required
widthImg = 640
heightImg = 480
#####################################
cap = cv2.VideoCapture(0)
cap.set(3, widthImg)
cap.set(4, heightImg)
cap.set(10, 150) #id: 10, represents brigthness => adjust as required based on set... |
import django_tables2 as tables
from net.models import Connection
from utils.tables import BaseTable, ButtonsColumn, SelectColumn
class ConnectionTable(BaseTable):
pk = SelectColumn()
ipv6_address = tables.Column(linkify=True, verbose_name="IPv6")
ipv4_address = tables.Column(linkify=True, verbose_name="... |
import os
import json
from .constants import CUST_ATTR_GROUP
def default_custom_attributes_definition():
json_file_path = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
"custom_attributes.json"
)
with open(json_file_path, "r") as json_stream:
data = json.load(json_strea... |
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
from flask_restplus import Api
from jsonschema import FormatChecker
import logging
log = logging.getLogger(__name__)
# Instantiate a Flask-RESTPlus API
api = Api(version='1.0', title='iter8 analytics REST API',
description='API to perform analytics to support canary releases '
'and A/B tests',
... |
import sys
def subst(s, ls):
if s == "":
return ""
for j in xrange(0, len(ls), 2):
i = s.find(ls[j])
if i != -1:
return subst(s[:i], ls) + ls[j + 1] + subst(s[i + len(ls[j]) :], ls)
return s
test_cases = open(sys.argv[1], "r")
for test in test_cases:
s, sub = tes... |
from rest_framework import serializers
from daiquiri.metadata.models import Column
class ColumnSerializer(serializers.ModelSerializer):
class Meta:
model = Column
fields = (
'id',
'order',
'name',
'description',
'unit',
'ucd... |
from django.shortcuts import render, get_object_or_404, redirect
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.views.generic import ListView, DetailView, CreateView
from django.views.generic.edit import FormView, UpdateView
from django.contrib.auth import login, authenticate
... |
"""
Unit tests for PDF class
"""
import numpy as np
import unittest
import qp
class EvalFuncsTestCase(unittest.TestCase):
""" Tests of evaluations and interpolation functions """
def setUp(self):
"""
Make any objects that are used in multiple tests.
"""
self.xpts = np.linspace... |
import itsdangerous, json, atexit, traceback, logging
from flask import redirect, render_template, url_for, abort, \
flash, request
from flask_login import login_user, logout_user, current_user, login_required
from flask_mail import Message
from flask_admin import Admin, AdminIndexView, expose
from flask_admin.con... |
#!/usr/bin/env python3
# Copyright 2004-present Facebook. All Rights Reserved.
# Updates by Pablo Palafox 2021
import torch.nn as nn
import torch
import torch.nn.functional as F
import kornia
from utils import embedder
from utils import geometry_utils
class PoseDecoder(nn.Module):
def __init__(
self,
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2018-08-03 06:39
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hacker', '0017_auto_20180803_0633'),
]
operations = [
migrations.AddField(
... |
import re
from bottle import route, run, template
# shamelessly stolen from https://www.w3schools.com/howto/howto_js_sort_table.asp
js = """
<script>
function sortTable(n) {
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
table = document.getElementById("tbl");
switching = true;
dir =... |
#!/usr/bin/python3
import alley_oop
|
import glob
import json
import os
import argparse
import numpy as np
from PIL import Image, ImageDraw, ImageFont
from sklearn.preprocessing import MinMaxScaler
POSE_BODY_25_PAIRS_RENDER_GPU = \
[1, 8, 1, 2, 1, 5, 2, 3, 3, 4, 5, 6, 6, 7, 8, 9, 9, 10, 10, 11,
8, 12, 12, 13, 13, 14, 1, 0, 0, 15, 15, 17, 0, 16, 1... |
from flask import render_template,redirect,session,request, flash
from flask_app import app
from ..models import user, bag
@app.route("/bag/create")
def new_bag():
if 'user_id' not in session:
return redirect('/')
data = {
"id":session['user_id']
}
return render_template("add_bag.html",... |
import os
import zipfile
from arelle.CntlrCmdLine import parseAndRun
# from https://specifications.xbrl.org/work-product-index-registries-units-registry-1.0.html
REGISTRY_CONFORMANCE_SUITE = 'tests/resources/conformance_suites/utr/registry/utr-conf-cr-2013-05-17.zip/utr-conf-cr-2013-05-17/2013-05-17'
STRUCTURE_CONFOR... |
import os
import torch as torch
import numpy as np
from io import BytesIO
import scipy.misc
#import tensorflow as tf
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
from torchvision.datasets import ImageFolder
from torch.autograd import Variable
from matplotlib imp... |
import logging
from datetime import datetime, timezone
from brownie import chain
from yearn.historical_helper import export_historical, time_tracking
from yearn.networks import Network
from yearn.treasury.treasury import StrategistMultisig
from yearn.utils import closest_block_after_timestamp
logger = logging.getLogg... |
def write_fbk(file_name, feat_path):
with open(file_name, 'r') as f:
lines = f.readlines()
for lin_num, x in enumerate(lines):
audio_name = x.split("/wav/")[1].split(".")[0]
feat_name = ''.join([feat_path, audio_name, '.fbk'])
lines[lin_num] = ''.join([x.strip(),... |
import torch
import torch.nn as nn
import numpy as np
from skimage.morphology import label
class Dice(nn.Module):
"""The Dice score.
"""
def __init__(self):
super().__init__()
def forward(self, output, target):
"""
Args:
output (torch.Tensor) (N, C, *): The model o... |
import sort_for_vexflow
import pretty_midi
def notation(orchestra, inst, tech, dyn, note, tgt, onoff, microtone,masking_order_idx):
annotations=[]
orchestration_slice=[]
tgts=[]
for i in range(len(inst)):
# Check that you input proper values:
if tech[i] in list(orchestra[inst[i]].keys()... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2018-06-18 07:56
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('disturbance', '0005_auto_20180618_1123'),
]
operations = [
migrations.RemoveField(
... |
def shared_function(x, sep=':'):
return sep.join(['got', x]) |
from cleaner_console import Console
if __name__ == '__main__':
Console() |
from node import constants
def shout(data):
data['type'] = 'shout'
return data
def proto_page(uri, pubkey, guid, text, signature, nickname, PGPPubKey, email,
bitmessage, arbiter, notary, notary_description, notary_fee,
arbiter_description, sin, homepage, avatar_url):
data =... |
# -*- coding: utf-8 -*- #
# Copyright 2018 Google 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 requir... |
# -*- coding: utf-8 -*-
"""
controlbeast.utils.loader
~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: Copyright 2013 by the ControlBeast team, see AUTHORS.
:license: ISC, see LICENSE for details.
"""
import importlib
import os
import re
def __filter_members(item):
"""
Filter function to detect classes... |
# Generated by Django 3.2.4 on 2021-06-14 12:18
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('main_app', '0... |
from __future__ import annotations
from typing import (
Any,
Dict,
Iterator,
Mapping,
MutableMapping,
Optional,
Tuple,
TypeVar,
)
from apiwrappers import utils
VT = TypeVar("VT")
class NoValue:
__slots__: Tuple[str, ...] = tuple()
def __repr__(self):
return f"{self.... |
# -*- coding: utf-8 -*-from setuptools import setup, find_packages
from baseapp import get_version
setup(
name='feincms_baseapp',
version=get_version(),
description='This is a base app and contenttype for Feincms.',
author='',
author_email='',
url='https://github.com/',
packages=find_package... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/6/24 20:55
# @Author : ganliang
# @File : doctest_test.py
# @Desc : doctest测试 执行模块测试
import doctest
import src.deco
if __name__ == "__main__":
doctest.testmod(src.deco)
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/thumby/flask-thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2015 thumby.io dev@thumby.io
class FlaskThumbor:
__name__ = "FlaskThumbor"
def __init__(self,... |
import os
import sys
'''
3个空瓶换一瓶
input: n个空瓶
outpu: 最终可换瓶数
'''
def demo1():
while True:
try:
a = int(input())
if a != 0:
print(a//2)
except:
break
######################################
'''
input: n以及n个随机数组成的数组
output: 去重排序后的数组
'''
def dem... |
class SETTING:
server_list = {
"presto": {
"connect_type": "PrestoConnector",
"url": {
"username": "hive"
,"host": ""
,"port": 3600
,"param" : "hive"
,"schema": "default"
,"metastore": "my... |
# Copyright 2015: Mirantis 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 ap... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2017/8/23 下午12:54
# @Author : chenyuelong
# @Mail : yuelong_chen@yahoo.com
# @File : read.py
# @Software: PyCharm
import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(sys.argv[0]))))
class read():
'''
fastq中每条read
... |
# -*- coding: utf-8 -*-
"""
awsscripter.cli
This module implements awsscripter's CLI, and should not be directly imported.
"""
import os
import warnings
import click
import colorama
import yaml
from awsscripter.cli.init.init import init_group
from awsscripter.cli.audit.audit import audit_group
from awsscripter.cli.... |
import tfchain.polyfill.encoding.object as jsobj
import tfchain.polyfill.array as jsarr
import tfchain.polyfill.asynchronous as jsasync
import tfchain.polyfill.crypto as jscrypto
import tfchain.client as tfclient
import tfchain.errors as tferrors
from tfchain.chain import NetworkType, Type
from tfchain.balance import... |
import configparser
from fast_arrow import Client, OptionOrder
print("----- running {}".format(__file__))
config = configparser.ConfigParser()
config.read('config.debug.ini')
#
# initialize fast_arrow client and authenticate
#
client = Client(
username = config['account']['username'],
password = config['a... |
# This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
from datetime import time
from operator import itemgetter
import... |
#!/usr/bin/env python
# import necessay modules
from lxml import html
from lxml import etree
import requests
# top-level domain
parent_domain = 'http://trevecca.smartcatalogiq.com'
# parent page showing the porgrams of study
parent_page_url = parent_domain + '/en/2015-2016/University-Catalog/Programs-of-Study'
paren... |
x1 = int(input())
y1 = int(input())
x2 = int(input())
y2 = int(input())
x3 = int(input())
y3 = y2
a = abs(x3 - x2)
h = abs(y1 - y2)
s = a * h / 2
print(s) |
#!/usr/bin/python
import serial
import sys
import time
import string
from serial import SerialException
import RPi.GPIO as gpio
class SerialExpander:
def __init__(self, port='/dev/ttyS0', baud=9600, timeout=0, **kwargs):
self.__port = port
self.__baud = baud
self.ser = serial.Serial(self.__port, self.__baud, ... |
from setuptools import setup, find_packages
with open('README.md') as f:
readme = f.read()
with open('LICENSE') as f:
content = f.read()
setup(
name='Wechatbot',
version='0.0.1',
description='Wechatbot project',
long_description=readme,
install_requires=['itchat==1.3.10', 'requests==2.19.1... |
TLS_VERSIONING = "1.0.23"
TLS_DATE = "12 March 2019"
|
"""
This module deals with the definition of all the database models needed for the application
"""
from app import db, app
from passlib.apps import custom_app_context as pwd_context
from itsdangerous import (TimedJSONWebSignatureSerializer as Serializer, BadSignature, SignatureExpired)
from math import cos, sin,... |
from WConio2 import textcolor, clrscr, getch, setcursortype
import ctypes
ctypes.windll.kernel32.SetConsoleTitleW("n Numbers HCF")
def hcf(n):
a, b, r = n[0], n[1], 0
for x in range(0, len(n) - 1):
while a != 0:
r = b % a
b = a
a = r
a = b
if x + 2 ... |
# Copyright (c) 2019 AT&T Intellectual Property.
# Copyright (c) 2018-2019 Nokia.
#
# 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... |
# Copyright 2014 Facebook, Inc.
# Modified by Vivek Menon
from facebookads.adobjects.adaccount import AdAccount
from facebookads.adobjects.campaign import Campaign
from facebookads.adobjects.adset import AdSet
from facebookads.adobjects.adcreative import AdCreative
from facebookads.adobjects.ad import Ad
from facebook... |
def solution(s):
word_dict = {}
for element in s.lower():
word_dict[element] = word_dict.get(element, 0) + 1
if word_dict.get('p', 0) == word_dict.get('y', 0):
return True
return False
if __name__ == '__main__':
s = 'pPoooyY'
print(solution(s))
"""
def solution... |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
# ERPNext - web based ERP (http://erpnext.com)
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe, json
import http.client
import mimetype... |
import warnings
from datetime import datetime
import pytest
import pandas as pd
from mssql_dataframe.connect import connect
from mssql_dataframe.core import custom_warnings, custom_errors, create, conversion, conversion_rules
from mssql_dataframe.core.write import insert, _exceptions
pd.options.mode.chained_assignme... |
# Server must be restarted after creating new tags file
from django import template
register = template.Library ()
@ register.inclusion_tag ('oauth/tags/user_avatar.html')
def get_user_avatar_tag (user):
'''Return the user's picture, it is an img tag'''
return {'user': user} |
# -*- coding:Utf-8 -*-
from gi.repository import Gtk, GObject, GdkPixbuf
from crudel import Crudel
import glob
class PicsouDiapo(Gtk.Window):
""" Affichage d'une image dans une Gtk.Window """
def __init__(self, crud, args):
Gtk.Window.__init__(self, title=args)
self.crud = crud
self.ar... |
"""
======================
Geographic Projections
======================
This shows 4 possible geographic projections. Cartopy_ supports more
projections.
.. _Cartopy: http://scitools.org.uk/cartopy
"""
import matplotlib.pyplot as plt
###############################################################################
... |
"""
Wrappers around the Google API's.
"""
import os
import json
from datetime import (
datetime,
timedelta,
)
from collections import namedtuple
try:
# this is only an issue with Python 2.7 and if the
# Google-API packages were not installed with msl-io
from enum import Enum
except ImportError:
... |
#!/bin/python
#NOTE: modified from original to be more module friendly (PS)
#Original source: https://github.com/jczaplew/postgis2geojson/blob/master/postgis2geojson.py
import argparse
import datetime
import decimal
import json
import subprocess
import psycopg2
#defaults for use as a module, possibly modified by t... |
"""Package initialization procedures.
The cli package provides components to build and execute the CLI.
"""
|
import re
# noinspection PyShadowingBuiltins
def all(_path):
return True
def path_contains(*subs):
def func(path):
return any(map(path.__contains__, subs))
return func
def contains_regex(pattern):
def func(path):
with open(path) as f:
code = f.read()
return boo... |
#### import the simple module from the paraview
from paraview.simple import *
#### disable automatic camera reset on 'Show'
paraview.simple._DisableFirstRenderCameraReset()
# get color transfer function/color map for 'DICOMImage'
dICOMImageLUT = GetColorTransferFunction('DICOMImage')
# Rescale transfer function
dICOM... |
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.core.cache import cache
from .models import *
@receiver(post_save, sender=Email)
def question__delete_caches_on_create(sender, instance, created, **kwargs):
cache_name = "get_sent_emails_user_id_" + str(1)
if(cache_name i... |
from flask import Blueprint, session, redirect, render_template, request, flash, url_for, abort
from models import PageDetails, Database,Authentication, General
from functools import wraps
from validator_collection import *
admin_remove = Blueprint("admin_remove", __name__)
@admin_remove.route("/Admin/Remove", metho... |
#
# Test Netatmo class
#
import logging
import Netatmo
def main():
logging.basicConfig(level=logging.DEBUG)
netatmo = Netatmo.Netatmo("PyAtmo.conf")
home=netatmo.getHomesData()
netatmo.getHomeStatus()
if __name__ == "__main__":
main() |
# 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 the Apache License, Version 2.0 (the
# "License"); you may not u... |
import json
import random
from flask import Flask, request
from flask_restplus import Resource, Api, Namespace
import os
from datetime import date, datetime
from faker import Faker
import security
fake = Faker('en_AU')
## load bsb data into memory
with open('./resources/bsbs.json') as json_file:
bsbs = json.load(... |
import os
import pathlib
import re
from collections import defaultdict
from functools import lru_cache
import stanza
import torch
from loguru import logger
from nlgeval import NLGEval
from transformers import AutoModelForCausalLM, AutoTokenizer
current_dir = pathlib.Path(__file__).parent.absolute()
def step_len(fun... |
#
# Copyright (c) nexB Inc. and others. All rights reserved.
# VulnerableCode is a trademark of nexB Inc.
# SPDX-License-Identifier: Apache-2.0
# See http://www.apache.org/licenses/LICENSE-2.0 for the license text.
# See https://github.com/nexB/vulnerablecode for support or download.
# See https://aboutcode.org for mor... |
__all__ = ("MDRenderer", "LOGGER", "RenderTreeNode", "DEFAULT_RENDERER_FUNCS")
import logging
from types import MappingProxyType
from typing import Any, Mapping, MutableMapping, Sequence
from markdown_it.common.normalize_url import unescape_string
from markdown_it.token import Token
from mdformat.renderer._default_... |
import numpy as np
from utils import env_paths as paths
from base import Train
import time
class TrainModel(Train):
def __init__(self, model, output_freq=1, pickle_f_custom_freq=None,
f_custom_eval=None):
super(TrainModel, self).__init__(model, pickle_f_custom_freq, f_custom_eval)
... |
from typing import Text, Type
from aiogram import types
from aiogram.dispatcher.filters.builtin import Command, Text
from aiogram.dispatcher import FSMContext
from aiogram.types import message
from middlewares.states.all_states import download_sticker_state
import os
from loader import dp
@dp.message_handler(text="/c... |
import csv
import argparse
import enum
import sys
from normalizer import normalizer
from common import common
def RepresentsFloat(val):
try:
float(val)
return True
except ValueError:
return False
if __name__ == "__main__":
ft_type = enum.Enum("ft_type", ("train", "valid"))
p... |
import os
import sys
import json
import tweepy
import requests
import pandas as pd
from defipulse import DefiPulse
from coingecko import CoinGecko
from subprocess import call
# Data Preprocessing and Feature Engineering
consumer_key = os.environ.get('TWITTER_CONSUMER_KEY', 'ap-northeast-1')
consumer_secret = os.enviro... |
#
# Copyright (c) 2021 Incisive Technology Ltd
#
# 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, pu... |
"""Remote apps
=============
"""
|
import os
import sqlite3
'''
THING I THINK I'M MISSING
The completed date shouldn't be a boolean because it can be overdue.
It was an integer before so it could be set to the date in which it was marked completed.
This should be changed back.
'''
class Equipment:
def __init__(self, pk=-1, name=''):
sel... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
from scrapy import Item, Field
from collections import OrderedDict
import six
class ScholarshipItem(Item):
University = Field()
Program = Field()
Degree = ... |
import boto3
import csv
profile = "default"
def get_instance(instance_name):
ec2 = boto3.resource('ec2')
return ec2.instances.filter(Filters=[{'Name': 'tag:Name', 'Values': [instance_name]}])
boto3.setup_default_session(profile_name=profile)
ec2 = boto3.client('ec2')
ec2_list = []
sg_name_dict = {}
# dict ... |
# Copyright 2017-present Open Networking Foundation
#
# 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... |
from ..resources.resource import Resource
import requests
from requests.auth import HTTPBasicAuth
class Suppliers(Resource):
def __init__(self):
super().__init__("suppliers")
def delete(self, id):
raise NotImplementedError("Not possible to post a warehouse")
|
def tree(x):
print("\n".join([f"{'*'*(2* n + 1):^{2*x+1}}" for n in range(x)]))
def trunk(n):
for i in range(n):
for j in range(n-1):
print(' ', end=' ')
print('***')
tree(1)
trunk(3) |
# -*- coding: utf-8 -*-
import tkinter as tk
from tkinter import messagebox
import algoritmo
import aicSpider
class SampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self._frame = None
self.switch_frame(StartPage)
def switch_frame(self, frame_class):
"""Destroi frame ... |
from django.conf import settings
from django.urls import include, path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
path("... |
import argparse
import os
import torch
from torch import nn, optim
from torch.nn import functional as F
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
# setup
parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
parser.add_argument('--batch-size', type=int, defaul... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.