content stringlengths 5 1.05M |
|---|
from django.apps import AppConfig
class CoursesappConfig(AppConfig):
name = 'coursesApp'
|
import torch,os
import torch.nn as nn
import torch.optim as optim
import tqdm
from torch.utils.data import DataLoader
from models import lrcm as lrcm
from datahandler import cubdataset as cubdataset
from utils import utils
from loss import custom_loss
import config
random_seed = 524626546435
torch.manual_seed(random... |
import pygame
import time
pygame.font.init()
def outer(numbers,a):
pygame.font.init()
#color init
black=(0,0,0)
white=(255,255,255)
dark_grey=(77,77,77)
grey=(102,102,102)
red=(255,0,0)
lime=(51,255,51)
light_green=(200,255,200)
light_grey=(128,128,128)
back=(199,209,199... |
# -*- coding: utf-8 -*-
# @author: juforg
# @email: juforg@sina.com
# @date: 2020/04/06
# SJ编程规范
# 命名:
# 1. 见名思意,变量的名字必须准确反映它的含义和内容
# 2. 遵循当前语言的变量命名规则
# 3. 不要对不同使用目的的变量使用同一个变量名
# 4. 同个项目不要使用不同名称表述同个东西
# 5. 函数/方法 使用动词+名词组合,其它使用名词组合
# 设计原则:
# 1. KISS原则: Keep it simple and stupid !
# 2. SOLID原则: ... |
# Copyright (c) 2016-2020, Thomas Larsson
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions... |
#!/usr/bin/python
from datetime import datetime, date, timedelta
import os
import sys; sys.path += ['/var/canvas/common', '../../common']
import yaml
from collections import defaultdict
from boto.ec2.connection import EC2Connection
from configuration import aws
def clean_backups():
"""
dumb script that clea... |
from DeepModel.AlexNet import AlexNet, AlexCNN
from DeepModel.NNutil import *
from DeepModel.ResNet import Resnet_improve, ResNet_18
from DeepModel.ResNet_deeper import ResNet101, ResNet50, ResNet152
from DeepModel.ResNet_deeper import ResNet_deeper
from DeepModel.SimpleCNN import SCNN, LeNet5
from DeepModel.SimpleFull... |
import netCDF4 as nc #case matters for importing netCDF4 module
import numpy as np
# read netCDF "metadata"
def open_netCDF_meta(path,key):
data = nc.Dataset(path)
return data.__dict__[key]
# read netCDF "dimensions"
def open_netCDF_dimension(path,key):
data = nc.Dataset(path)
return data.dimensions[key]
# read ... |
import unittest
import unittest.mock
import decimal
import prosperpy
def get_candles():
data = ['44.34', '44.09', '44.15', '43.61', '44.33', '44.83', '45.10', '45.42', '45.84', '46.08', '45.89', '46.03',
'45.61', '46.28', '46.28', '46.00', '46.03', '46.41', '46.22', '45.64', '46.21', '46.25', '45.71'... |
from python_to_you.models import Role
class Role():
def __init__(self):
self.role = Role
def get(self, id):
return self.role.query.filter_by(id=id).first()
def create(self, user_id, is_admin):
role = self.role(
user_id,
is_admin ... |
"""
helper_fxns.py
by Benjamin Hamilton
------------------------------------------
A few helper functions that were aggregated from activities I found myself repeating.
Included are
- graphing feature importance (created for CatBoost but should work
with relevant sklearn models
- mass scoring that generates a ... |
import matplotlib.pyplot as plt
import networkx as nx
import pdb
G = nx.Graph()
G.add_edge('a', 'b', weight=0.6)
G.add_edge('a', 'c', weight=0.2)
G.add_edge('c', 'd', weight=0.1)
G.add_edge('c', 'e', weight=0.7)
G.add_edge('c', 'f', weight=0.9)
G.add_edge('a', 'd', weight=0.3)
elarge = [(u, v) for (u, v, d) in G.edg... |
from . import BASE_CONTEXT
from .dataobject import DataObject, ObjectProperty, This
from .context_common import CONTEXT_IMPORTS
# ContextDataObject was moved to a separate module from Context to avoid a dependency
# cycle with dataobject
class ContextDataObject(DataObject):
""" Represents a context """
class... |
"""
container for the Periodicity estimator
"""
from typing import List
import librosa
import numpy as np
from automix.featureExtraction.estimator import Estimator, Parameter
from automix.model.classes.signal import Signal
class Periodicity(Estimator):
"""
Estimator infering the periodicity of a track
... |
# -*- coding: utf-8 -*-
"""A simple script for computing child model parameters and controller search space
complexities
ZZJ, 11.19.2019
"""
import numpy as np
def child_model_params(num_features, num_layers, max_units):
c = num_features * num_layers * max_units + (max_units * num_layers) ** 2 / 2
return c
... |
from typing import Dict
from airflow.sensors.base_sensor_operator import BaseSensorOperator
from airflow.utils.decorators import apply_defaults
from sai_airflow_plugins.operators.fabric_operator import FabricOperator
class FabricSensor(BaseSensorOperator, FabricOperator):
"""
Executes a command on a remote ... |
import json
class Alpha:
def __init__(self):
self.a = json.loads('file_A')
self.b = json.loads('file_B')
self.c = None
self.d = None
def foo(self):
json.dumps(self.d)
def bar(self, dummy):
self.c = dummy.x
self.d = dummy.y
self.foo()
clas... |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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... |
import cv2
import numpy as np
import mediapipe as mp
np.random.seed(123)
class Point(object):
"""
Class to denote a joint in 2-D space
Arguments:
x, y : x-axis and y-axis co-ordinates
visibility : visibility score of the joint
"""
def __init__(self, x=0.0, y=0.0, visibility=0.0):
self... |
# Copyright 2016 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file acc... |
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 3.0.12
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info as _swig_python_version_info
from glob import glob
import platform
import distutils.sys... |
from django.contrib import admin
from profile.models import UserProfile
admin.site.register(UserProfile) |
import os
from collections import defaultdict
from Fuzzy_clustering.version2.common_utils.logging import create_logger
from Fuzzy_clustering.version2.dataset_manager.create_dataset_for_load_lv import dataset_creator_LV
from Fuzzy_clustering.version2.dataset_manager.create_dataset_for_load import dataset_creator_load
f... |
from django.shortcuts import render, redirect, get_object_or_404, get_list_or_404
from django.views import generic
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from .models import Materias,... |
import numpy as np
from numpy.linalg import det
from numpy import sqrt
from deform.model.dl_model import *
from deform.model.create_dataset import *
from deform.model.hidden_dynamics import get_next_state_linear
import math
import torch
from torch.utils.data import Dataset, DataLoader
from torchvision.utils import save... |
#!/usr/bin/env python3
#
# Since: January, 2019
# Author: gvenzl
# Name: functions.py
# Description: Common functions for csv2db
#
# Copyright 2019 Gerald Venzl
#
# 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 ... |
import pytest
from starlite.utils.url import join_paths, normalize_path
@pytest.mark.parametrize( # type: ignore[misc]
"base,fragment, expected",
[
("/path/", "sub", "/path/sub"),
("path/", "sub", "/path/sub"),
("path", "sub", "/path/sub"),
("/path/", "sub/", "/path/sub"),
... |
###############################################################################
#
# Drone Simulator Sample Setup 1
#
# Copyright (c) 2017, Mandar Chitre
#
# This file is part of dronesim which is released under Simplified BSD License.
# See file LICENSE or go to http://www.opensource.org/licenses/BSD-3-Clause
# for ful... |
from flask import Flask
# UPLOAD_FOLDER = 'static/uploads/'
app = Flask(__name__)
app.secret_key = "secret key"
# app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 |
import functools
import itertools
import logging
import more_itertools
import numpy as np
from attrdict import AttrDict
import util
TRAIN = 0
VALID = 1
TEST = 2
class Pose3DDataset:
def __init__(
self, joint_info, train_examples=None, valid_examples=None, test_examples=None):
self.joint_inf... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import ops
import data
import utils
import models
import argparse
import numpy as np
import tensorflow as tf
import image_utils as im
from datetime import datetime
from dateutil import tz
from glob import glo... |
""" One by one show real images in the CelebA-HQ npy files' directory
Very useful for analyzing the data. press Q to move to the next image """
import argparse
import os
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
def parse_arguments():
"""
default command line argument parse... |
"""
TFX Beam implementation to make a pipeline for solving santander problem.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl import app
from absl import flags
import os
import tensorflow as tf
import tensorflow_model_analysis as tfma
from tf... |
#!/usr/bin/env python
"""
blepty.py connects to a JNHuaMao Bluetooth Low Energy module and
creates a pseudo-terminal (pty) that can be opened like a serial
port. The program writes the path to the terminal program and then
runs in the background, passing data between the BLE module and
the PTY.
This program must be r... |
# --------------
import pandas as pd
import numpy as np
from sklearn.cross_validation import train_test_split
# code starts here
df = pd.read_csv(path)
df.head(5)
# X = df[['ages', 'num_reviews', 'piece_count', 'play_star_rating', 'review_difficulty', 'star_rating', 'theme_name', 'val_star_rating', 'country']].shape[0... |
import scrapy
from ..items import NewsScrapeItem
import re
class NationSpider(scrapy.Spider):
name = "nation"
def start_requests(self):
urls = ['https://www.nationtv.tv/main/content/latest/']
for url in urls:
yield scrapy.Request(url=url, callback=self.parse)
d... |
#!/usr/bin/env python3.6
# example usage: ./2_1_per_module_metrics.py
import numpy as np
import os, json, time, re, subprocess
def is_cpp_file(file_name):
end = file_name.split(".")[-1]
return end in ["h", "cpp", "hpp", "c"]
def transform_file_paths(output, lookup):
transformed_files = []
for o in ... |
# Copyright 2017 The Armada 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 agreed to in w... |
from django.db import models
from wagtail.core.models import Page
from wagtail.core.fields import RichTextField
from wagtail.admin.edit_handlers import FieldPanel
from wagtailmenus.models import MenuPage
from django.shortcuts import render
from django.core.mail import EmailMessage
from django.template.loader import ... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'gui.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.se... |
import numpy as np
def line_segments_from_homogeneous(lines, bbox):
x,y,w,h = bbox
# Corner points
A = np.array([x,y,1])
B = np.array([x+w,y,1])
C = np.array([x+w,y+h,1])
D = np.array([x,y+h,1])
# Cross product of pairs of corner points
edges = [
np.cross(a,b) for a,b in ... |
# Copyright 2015 Oursky Ltd.
#
# 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 writing, ... |
import uuid
from unittest.mock import Mock, patch
import pytest
import requests_mock
from teatime import Context, Issue, NodeType, Report, Severity
from teatime.plugins.eth1 import (
AccountCreation,
AccountUnlock,
GethAccountImport,
GethDatadir,
GethNodeInfo,
GethStartRPC,
GethStartWebsoc... |
from handlers.decorators import OsuEvent
from objects.constants.Modificators import Mods
from packets.OsuPacketID import OsuPacketID
from packets.Reader.PacketResolver import PacketResolver
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from objects.Player import Player
# client packet: 51, bancho response:... |
import numpy as np
class GenericRegularizer:
def __init__(self):
pass
def pre_optim_update(self, layer):
pass
def post_optim_update(self, layer):
pass
class L1(GenericRegularizer):
def __init__(self, regularization_amount=1e-2):
self.regularization_amount = regulari... |
#!/usr/bin/python3
#-*- coding: utf-8 -*-
# This code is PEP8-compliant. See http://www.python.org/dev/peps/pep-0008/.
"""
Wyrd In: Time tracker and task manager
CC-Share Alike 2012 © The Wyrd In team
https://github.com/WyrdIn
This module implements parsers for entities used in the program. A parser is
understood as ... |
# -*- coding: utf-8 -*-
# @Author: 1uci3n
# @Date: 2021-10-07 17:59:35
# @Last Modified by: 1uci3n
# @Last Modified time: 2021-10-07 17:59:55
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
if x < 10:
return True
ints = [x % 10]
... |
'''Utility functions'''
import collections
def flatten(parent_dict, parent_key='', sep='_'):
'''Flatten a nested dict into a single layer'''
items = []
for key, val in parent_dict.items():
new_key = parent_key + sep + key if parent_key else key
if isinstance(val, collections.MutableMapping... |
# coding: utf-8
from twisted.internet import defer, protocol
from twisted.internet.task import LoopingCall
from twisted.protocols import basic
from txamqp import spec
from txamqp.codec import Codec
from txamqp.connection import Header, Frame, Method, Body, Heartbeat
from txamqp.message import Message
from txamqp.conten... |
import torch
from torch import nn
import math
class LandmarkLoss(nn.Module):
def __init__(self, n_landmark=98):
super(LandmarkLoss, self).__init__()
self.n_landmark = n_landmark
def forward(self, landmark_gt, landmark_pred):
loss = wing_loss(landmark_gt, landmark_pred, N_LANDMARK=self... |
#!/usr/bin/python
import json
import facebook
##data = urllib2.urlopen('http://graph.facebook.com/alswblog/').read()
access_token = 'CAAMzCQes4NkBAORJ93mpnXb3cjwbaFOuN5xiUU87enAdOZC9v4agnF4yZBN9bw6QaM6xjnYb3cuMIE8wBZBqDL3vDeHYBAjNrpJFzAzi1kBX7GHBel4NIh1Cqvkazqpjv0o5J6GrTtzWKnkZADehk3P16nwxEwioLCgOVRCpaj6njqyTrydim70G... |
"""
Implementation of wrapper API
"""
import os
import sys
import ctypes
import numpy
from google import protobuf
from . import utils
from .exceptions import ARTM_EXCEPTION_BY_CODE
from .spec import ARTM_API
class LibArtm(object):
def __init__(self, lib_name=None):
self.cdll = self._load_cdll(lib_name)... |
from neuralpp.util.group import Group
class BruteForce:
@staticmethod
def run(query, factors):
total_product = Group.product(factors)
other_variables = {v for f in factors for v in f.variables if v != query}
marginal = (total_product ^ other_variables).normalize()
return margin... |
# This File will contains Loss Function
# This File is to eable Package import, will mostly keep it blank
import os
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
import warnings
warnings.simplefilter("ignore")
class DiceLoss(nn.Module):
"""Calculate dice loss."""
def __init_... |
import torch
from sequence_generator import SequenceGenerator
import config
import argparse
from preprocess import read_tokenized_src_file
from utils.data_loader import load_vocab
from pykp.io import build_interactive_predict_dataset, KeyphraseDataset
from torch.utils.data import DataLoader
import predict
import os
d... |
med = 0
h = ''
m = 0
hi = 0
for c in range(1, 5):
n = input(f'Qual o nome da {c}ª pessoa? ')
s = input(f'Qual o sexo da {c}ª pessoa [M/F]? ').strip().lower()
i = int(input(f'Qual a idade da {c}ª pessoa? '))
if s in 'f' and i < 20:
m += 1
if s in 'm' and i > hi:
hi = i
h = n
... |
import traceback
import uuid
from aecErrorCheck import aecErrorCheck
from aecGeomCalc import aecGeomCalc
class aecGeomCalc:
# utility objects and data shared by all instances.
__aecErrorCheck = aecErrorCheck() # An instance of aecErrorCheck.
__aecGeomCalc = aecGeomCalc() # An instance of... |
# @lc app=leetcode id=55 lang=python3
#
# [55] Jump Game
#
# https://leetcode.com/problems/jump-game/description/
#
# algorithms
# Medium (35.24%)
# Likes: 6069
# Dislikes: 418
# Total Accepted: 613.4K
# Total Submissions: 1.7M
# Testcase Example: '[2,3,1,1,4]'
#
# Given an array of non-negative integers nums, y... |
"""
This module contains functions needed for easy upload of files
to the web server.
"""
import os
from PIL import Image
from typing import List
from scipy.ndimage import rotate
from directdemod import constants
from directdemod.misc import save_metadata
from directdemod.georeferencer import Georeferencer
def prepr... |
# stdlib
import pathlib
from pprint import pprint
# 3rd party
import astropy.units as u
# this package
import py2latex
from py2latex.glossaries import glossary_from_file
from py2latex.markdown_parser import load_markdown
from py2latex.sectioning import make_chapter
from py2latex.siunit import SI, si
chapters_list = ... |
#!/usr/bin/env python
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2008,2009,2010,2011,2012,2013,2014,2015,2016,2017 Contributor
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance... |
import mock
from .context import aiociscospark
class TestSparkAppClient:
def test_initialization(self, event_loop, credentials):
with mock.patch.object(aiociscospark.APIClient, 'http_client_class',
side_effect=aiociscospark.http_client.HTTPClient) as http_client_class_mock:... |
from django.db import models
from django.utils import timezone
from django.urls import reverse
class Post(models.Model):
author = models.ForeignKey('auth.User',on_delete=models.CASCADE)
title = models.CharField(max_length = 250)
text = models.TextField()
create_date = models.DateTimeField(default = tim... |
from rest_framework.generics import get_object_or_404
from rest_framework.mixins import ListModelMixin
from rest_framework.reverse import reverse
from rest_framework.viewsets import GenericViewSet
from drf_hal.views import HalRetrieveModelMixin
from registronavale import relations
from . import models
from . import se... |
import click
from ..api import GithubException
from .utils import repo_manager
@click.command()
@click.option(
"--sandbox",
is_flag=True,
help="Validate only on sandbox/deploy branch",
default=False,
)
@click.option(
"--yes-no",
is_flag=True,
help="Return yes for version is good, no for v... |
# -*- coding: utf-8 -*- #
# Copyright 2017 Google LLC. 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... |
from datetime import datetime
from django.test import TestCase
from django.test.client import Client
from corehq.apps.receiverwrapper.models import RepeatRecord, AppStructureRepeater
from corehq.apps.app_manager.models import Application
class TestAppStructureRepeater(TestCase):
def setUp(self):
self.cli... |
"""
Tests for decomposing documents into basis vectors
"""
import unittest
from os.path import join
from crossmap.crossmap import Crossmap
from crossmap.tools import read_yaml_documents
from .tools import remove_crossmap_cache
data_dir = join("tests", "testdata")
config_file= join(data_dir, "config-similars.yaml")
d... |
# Note that this requires yt 4!
import yt
import contextlib
from collections import defaultdict
ds = yt.load_sample("snapshot_033")
print(ds.index)
reg = ds.r[0.25:0.5, 0.5:0.75, 0.2:0.25]
for chunk in reg.chunks([], "io"):
print(chunk)
# So what has just happened is that `_identify_base_chunk` was called, and t... |
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 19 23:27:24 2020
@author: dkloe
"""
import numpy as np
import cv2
from matplotlib import pyplot as plt
img1 = cv2.imread('T_sensor_right_up.png', 0) # query Image
img2 = cv2.imread('Capture.png',0) # target Image
# Initiate SIFT detector
orb = cv... |
from numpy import maximum, percentile, full, nan, where, tile, inf, isnan
from skimage.measure import regionprops
from neurofinder import match, centers, shapes
from regional import many
from extraction.model import ExtractionModel
from .utils import norm
from .CC import CC
def compare(model, modelReference, threshold... |
import requests
import random
import string
# Vuln Base Info
def info():
return {
"author": "cckuailong",
"name": '''Cisco Prime Infrastructure Unauthorized RCE''',
"description": '''Cisco Prime Infrastructure Health Monitor HA TarArchive Directory Traversal Remote Code Execution Vulnerabi... |
import re
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from extractnet.util import get_and_union_features
from sklearn.decomposition import PCA
class AuthorFeatures(BaseEstimator, TransformerMixin):
"""
An sklearn-style transformer that takes an ordered sequence of ``Block`` obje... |
""" Utility methods """
import calendar
from datetime import datetime
from dateutil.parser import parse
from dateutil.relativedelta import relativedelta
from dateutil.tz import tzlocal, tzutc
from decimal import Decimal
from dynamo3 import Binary
try:
from shutil import get_terminal_size # pylint: disable=E0611
... |
import graphene
from graphene import relay
from rx import Observable
from channels import Group
from products.schemas import ProductNode
from products.models import Product
from graphene_django.filter import DjangoFilterConnectionField
def make_sub(info, gid):
inst = relay.Node.get_node_from_global_id(info, gid)
... |
from django import forms
from django.contrib.auth.models import User
from .models import Friend, RequestCall
class AddForm(forms.Form):
uname = forms.CharField(label="",widget=forms.TextInput(attrs={'autofocus':'on','autocomplete':'off','class':'form-control','placeholder':'Username of your friend'}))
|
from django.http.response import JsonResponse
from django.utils.translation import gettext as _
from django.contrib.auth.decorators import login_required, permission_required
from datetime import datetime
from app.base_views import MyViewCreateUpdateDelete
from .forms import *
from .tables import *
from .filters impo... |
#!/usr/bin/env python3
import pytest
import json
import os
# git-python seems buggy (repo got corrupted) and hard to use
version_file = "./static/swagger.json"
# dont actually execute shell commands if True
DRY_RUN=False
# wrap os.system
def shell(cmd):
print(cmd)
if DRY_RUN: return
ret = os.system(cmd)
if... |
from __future__ import division
from six.moves import range
# LIBTBX_SET_DISPATCHER_NAME cbf.dump
import sys
def process(file_name, out=None):
if (out is None): out = sys.stdout
import pycbf
print >> out, "File name:", file_name
object = pycbf.cbf_handle_struct() # FIXME
object.read_file(file_name, pycbf.MS... |
from ztag.annotation import *
class CiscoHTTPS(TLSTag):
protocol = protocols.HTTPS
subprotocol = protocols.HTTPS.TLS
port = None
tests = {
"cisco_ios_server":{
"global_metadata":{
"manufacturer":"Cisco",
},
"tags":["embedded",]
}
... |
from typing import List
class State:
name: str
value: str
def __init__(self, name: str, value: str):
self.name = name
self.value = value
class File:
name: str
def __init__(self, name: str):
self.name = name
class Path:
state: List[State]
file: List[File]
... |
tipos_de_classes = {
(1, 'Econômica'),
(2, 'Executiva'),
(3, 'Primeira Classe')
} |
from pluginnet.sun397.sun397 import sun397_data_transform_val, CrossEntropyLossOneHot
from pluginnet.sun397.metrics import create_softmax_metrics_dictionary
from pluginnet.sun397.partial_evidence import build_plugins, AlexNetPartialEvidence, SUN397PE
from pluginnet.sun397.sun397 import SUN397
import torchvision
import ... |
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
from myweight import db
class EverydayWeight(db.Model): # 表名将会是 everydayweight(自动生成,小写处理)
id = db.Column(db.Integer, primary_key=True) # 主键
username = db.Column(db.String(20)) # 用户名
date ... |
import multiprocessing
import os
from scalene.scalene_profiler import Scalene
import sys
import threading
@Scalene.shim
def replacement_pjoin(scalene: Scalene):
def replacement_process_join(self, timeout: float = -1):
from multiprocessing.process import _children
# print(multiprocessing.process.ac... |
""" utility functions"""
import re
import os
from os.path import basename
import gensim
import torch
from torch import nn
PAD = 0
UNK = 1
START = 2
END = 3
def count_data(path):
""" count number of data in the given path"""
matcher = re.compile(r'[0-9]+\.json')
match = lambda name: bool(matcher.match(nam... |
from django.test import SimpleTestCase
from django.urls import reverse, resolve
from orders.views import home, piechart, cohort, barchart, get_shipping_data, get_top3_products
class TestUrls(SimpleTestCase):
def test_home_url_resolves(self):
url = reverse('home')
self.assertEquals(resolve(url).func... |
#!coding:utf8
#author:yqq
#date:2020/2/20 0020 17:29
#description: TRX 接口
import logging
from base_handler import BaseHandler
from utils import decimal_default, get_linenumber
import json
import sql
from utils import is_hex_str
import decimal
from decimal import Decimal
from decimal import getcon... |
#!/usr/bin/env python3
"""
Author : Dawei Zhang <davyzhang325@gmail.com>
Date : 2021-06-22
Purpose: Rock the Casbah
"""
import argparse
# --------------------------------------------------
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Jump the Five... |
# Import sys
import sys
# Import pathlib and csv
import pathlib
import csv
# Set path for file with pathlib.Path(), pointing to the budget_data.csv file saved in the Resources folder
csvpath = pathlib.Path("./Resources/budget_data.csv")
# Open the CSV using the `with` keyword
with open(csvpath) as csvfile:
# Use... |
import fitsio
from FitsIngest import FitsIngest
class Extinction(FitsIngest):
def __init__(self, datafile, idDict, filetype, dbh):
""" Class to ingest exctintion_ebv and extinction_band data
"""
FitsIngest.__init__(self, filetype, datafile, idDict, dbh=dbh)
self.constants = {
... |
"""
In this example we write a CLI tool with brigade and click to deploy configuration.
"""
import logging
from brigade.core import Brigade
from brigade.plugins.inventory.simple import SimpleInventory
from brigade.plugins.tasks import data, networking, text
import click
def base_config(task):
"""
1. logs al... |
from typing import Any
from unittest.mock import MagicMock
from pandas import DataFrame
from dagster import IOManager, io_manager
def create_db_connection() -> Any:
return MagicMock()
def train_recommender_model(df: DataFrame) -> Any:
del df
def pickle_to_s3(object: Any, key: str) -> None:
pass
de... |
import sys, os, re
import pprint
import filecmp
sys.path.append("../src")
import pronlex
import phonecodes
"""This script should be run from the command line, in the test directory.
It will load some pronlexes from the 'fixtures' subdirectory,
test phone code conversion, and test both word and phone searches.""... |
# Copyright 2018 NTT DATA, 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 r... |
#!/usr/bin/env python3
# pytexnumber.py
#
# Renumbers LaTeX references
#
# Type python3 pytexnumber.py --help for help
# Copyright (c) 2013 - 2021 Vlad Gheorghiu. All rights reserved.
#
# MIT License
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated doc... |
#!/usr/bin/env python
#coding: utf-8
class Solution:
# @param A, a list of integers
# @return an integer
def trap(self, A):
left, right = 0, len(A) - 1
total, block = 0, 0
curlevel = 0
while left <= right:
curmin = min(A[left], A[right])
if curmin > ... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from imagekit.models import ImageSpecField
from imagekit.processors import ResizeToFill
from ..utils import slugify
from .locale import *
from .profiles import *
from .events import *
from .search im... |
"""This example is testing domain adaptation for action recognition, using PyTorch Lightning.
We can load and test different trained models without training.
"""
import argparse
import logging
import pytorch_lightning as pl
import torch
from config import get_cfg_defaults
from model import get_model
from kale.loadd... |
import os
import sys
from common import (QtToolModuleNotFoundError, catch_known_errors,
is_installed, remove_vendor_suffix)
def run():
sys.argv[0] = remove_vendor_suffix(sys.argv[0])
# lupdate-pyside6 is deprecated can have bug:
# https://bugreports.qt.io/browse/PYSIDE-1376?focusedCo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.