content stringlengths 5 1.05M |
|---|
import socket
import sys
import threading
def scanTarget(target_ip, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = s.connect_ex((target_ip, port))
socket.setdefaulttimeout(1)
if result == 0:
print(f"port {port} is open.")
s.close()
def main():
if len(sys.argv)... |
from .build_file_tree import build_file_tree # noqa
|
#
# PySNMP MIB module INTEL-L3LINK-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/INTEL-L3LINK-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:54:31 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... |
"""Tests for DAgger."""
import glob
import os
import gym
import numpy as np
import pytest
from stable_baselines.common.policies import BasePolicy
import tensorflow as tf
from imitation.algorithms import dagger
from imitation.policies import serialize
from imitation.util import rollout, util
ENV_NAME = 'CartPole-v1'
... |
from flask import Flask,jsonify,request,make_response
import json
import requests
import os
import sys
from pixivpy3 import *
username = "1240188105@qq.com"
password = "kgs196983"
aapi = AppPixivAPI()
aapi.login(username, password)
papi = PixivAPI()
papi.login(username, password)
class mod:
@staticmethod
de... |
lista_capitais = []
lista_capitais.append('Brasília')
lista_capitais.append('Buenos Aires')
lista_capitais.append('Pequim')
lista_capitais.append('Bogotá')
print(lista_capitais)
lista_capitais.remove('Buenos Aires')
lista_capitais.pop(2)
|
"""
*Is-Close*
"""
import jax.numpy as jnp
from ._operator import GeometricProperty
__all__ = ["Count"]
class Count(
jnp.size,
GeometricProperty,
):
pass
|
from enum import IntEnum
from typing import Dict, List, Optional
from app.db.pydantic_objectid import PydanticObjectId
from bson import ObjectId
from pydantic import BaseModel, Field
class SlideStatus(IntEnum):
ERROR = 0
SUCCESS = 1
RUNNING = 2
class Slide(BaseModel):
name: str
... |
__author__ = 'dylanjf'
import os
import pickle
import logging
import scipy as sp
import numpy as np
from re import sub
from sklearn.grid_search import GridSearchCV
from sklearn import cross_validation
logger = logging.getLogger(__name__)
N_TREES = 300
INITIAL_PARAMS = {
'LogisticRegression': {'C': 1, 'penalty':... |
lst=[]
for i in range(3):
lst.append(int(input()))
lst.sort(reverse=True)
print(lst[1])
|
import os
import json
from .base import BaseIsolatedDataset
from ..data_readers import load_frames_from_video
class WLASLDataset(BaseIsolatedDataset):
"""
American Isolated Sign language dataset from the paper:
`Word-level Deep Sign Language Recognition from Video: A New Large-scale Dataset and Method... |
# Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
def migration_test(name, versions, **kwargs):
native.sh_test(
name = name,
srcs = ["//sandbox-migration:test.sh"],
deps = ["@bazel_tools//tools/bash/runfil... |
import urllib.request
import json
from tsp import *
import math
import os
import numpy as np
inf = 0
file = open(os.path.abspath('key.txt'),'r')
key = file.read().strip()
vector = []
firstTime = False
addrRead = open(os.path.abspath('addr.txt'),'r')
vectorList = addrRead.read().splitlines()
for j in range(len(vec... |
import unittest
try:
from rest_framework.test import APITestCase
except ImportError:
raise unittest.SkipTest("Skipping DRF tests as DRF is not installed.")
from rest_framework import status
from tests.test_app.models import (
NaturalKeyChild, ModelWithNaturalKey, ModelWithSingleUniqueField,
)
from natural... |
import json
from google.appengine.ext import db
import jsonschema
class JSONProperty(db.Property):
"""Property for storing simple JSON objects backed by a schema."""
data_type = db.Blob
def __init__(self, schema=None, *args, **kwargs):
"""Constructor.
Args:
schema: a JSON Schema per draft 3 or... |
import json
from argparse import ArgumentParser
import tweepy
parser = ArgumentParser()
parser.add_argument('friends_repo')
parser.add_argument('-a', '--auth-filepath', help='Path to auth file',
required=True)
args = parser.parse_args()
FRIENDS_IDS = args.friends_repo
with open(args.auth_filepath) as f:
AUTH ... |
import copy
import numpy as np
from . import base, mean, summing
class Cov(base.Bivariate):
"""Covariance.
Parameters
----------
ddof
Delta Degrees of Freedom.
Examples
--------
>>> from river import stats
>>> x = [-2.1, -1, 4.3]
>>> y = [ 3, 1.1, 0.12]
>>> c... |
from panda3d.core import *
from CCDIK.IKChain import IKChain
from CCDIK.IKActor import IKActor
from CCDIK.Utils import *
from WalkCycle import WalkCycle
from FootArc import FootArc
from CollisionTerrain import CollisionTerrain
from direct.actor.Actor import Actor
class RiggedChar():
def __init__( self, terrain ):... |
h = 6.6260755e-27 # planck's constant (ergs-s)
c = 2.99792458e10 # speed of light (cm/s)
k = 1.380658e-16 # boltzmann constant (ergs/K)
pi = 3.14159 # just pi
sb = 5.6704e-5 # stefan boltzman constant (ergs cm^-2 s^-1 K^-4)
m_e = 9.10938188e-28 # mass of electron (g)
m_p = 1.6726215... |
"""Parser for the command line arguments."""
import argparse
import datetime
import re
import shutil
import string
import sys
import textwrap
from typing import cast, List, Set, Tuple
from dateutil.parser import parse
from pygments.styles import get_all_styles
from .config import read_config_file, write_config_file,... |
# coding: utf-8
import logging
from collections import OrderedDict
from django.db.models import Prefetch, Q
from django.utils.translation import ugettext_lazy as _
from future.utils import viewitems
logger = logging.getLogger(__name__)
class ColumnChoice(object):
def __init__(self, model, key, label, lookup, ... |
from cassandra.cluster import Cluster
from collections import Counter
from itertools import combinations
#import matplotlib.pyplot as plt
import csv
import pandas as pd
import numpy as np
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
import re
cluster = Cluster()
se... |
# https://practice.geeksforgeeks.org/problems/min-cost-climbing-stairs/1#
# Approach is to memorize the min cost for last two steps and use it to compute next step
# update the min_costs and move to next
class Solution:
def minCostClimbingStairs(self, cost, N):
mc1 = 0
mc2 = 0
for i in ra... |
# -*- coding: utf-8 -*-
#
# Copyright 2017-2019 - Swiss Data Science Center (SDSC)
# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and
# Eidgenössische Technische Hochschule Zürich (ETHZ).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in c... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The definition of the base classes Host and VM which
provide the necessary primitives to interact with a vm and
test a submission bundle."""
from __future__ import with_statement
# Use simplejson or Python 2.6 json, prefer simplejson.
try:
import simplejson as js... |
"""
tests.test_utils
~~~~~~~~~~~~~~~~
Test utility functions
:copyright: Copyright 2017 by ConsenSys France.
:license: BSD, see LICENSE for more details.
"""
import pytest
from cfg_loader.utils import parse_yaml, parse_yaml_file, add_prefix
def test_parse_yaml():
assert parse_yaml("""
... |
from re import match
from typing import Optional
from bs4 import BeautifulSoup
class Clubs:
def __init__(self, soup: BeautifulSoup, base_url: str) -> None:
self.soup = soup
self.base_url = base_url
def __call__(self) -> dict:
return {
"data": [
{
... |
'''
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
'''
def moveZeroes(... |
#
# oci-objectstorage-onsr-put-object-python version 1.0.
#
# Copyright (c) 2021 Oracle, Inc.
# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
#
import io
import os
import json
import sys
from fdk import response
import oci.object_storage
# Certs location
cert_... |
# !/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@file : province_city_area_to_txt.py
@comments :
@time : 2022/01/24
@author : Jacob Zhou <jacob.zzh@outlook.com>
@ver : 1.0
'''
import requests
from bs4 import BeautifulSoup
import time
import json
class GetCitysToLocal(object):
def __ini... |
import os
import finder
from ml import predictor
from django.shortcuts import render
from django.views import View
from django.core.files.storage import FileSystemStorage
class Index(View):
submitted = False
def __init__(self):
self._template = 'index.html'
self._checkpoint_path = 'ml/model/ch... |
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.a... |
from random import randint
from colorama import Fore
from colorama import Back
from colorama import Style
import os
class game:
playGame = True
numberOfRounds = 0
# Each challange has its own text, value to add to score if completed and
# a value to decrease the score if not completed.
#
# EP... |
from lxml import etree
parser = etree.HTMLParser()
print(type(parser))
tree = etree.parse('test.html', parser)
root = tree.getroot()
result = etree.tostring(root, encoding='utf-8',
pretty_print=True, method="html")
print(str(result, 'utf-8'))
print(root.tag)
print('lang =', root.get('lang'))
pr... |
'''
Read site soil moisture fields form FLUXNET-FULLSET '.csv' file and save it into '.nc' file
Todo: Transform into function; add Quality flag columns;
@aelkouk 11202020
'''
import numpy as np
import xarray as xr
import pandas as pd
import os
flx_fullset_csv = '../0_data/FLX_NL-Loo_FLUXNET2015_FULLSET_HH_1996-2014_1... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 12 13:23:55 2021
@author: rayaabuahmad
"""
from code.preprocessing.preprocessor import Preprocessor
from code.util import COLUMN_TWEET, COLUMN_PUNCTUATION_INPUT
class HashtagMentionRemover(Preprocessor):
# constructor
def __init__(sel... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'interfaceTelecomunicacoes.ui'
#
# Created: Tue May 27 15:40:06 2014
# by: PyQt4 UI code generator 4.7.2
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
class Ui_MainWindow(object):
def setu... |
class Solution:
def longestConsecutive(self, num):
range_length = collections.defaultdict(int)
max_length = 0
for n in num:
if range_length[n] != 0:
continue
range_length[n] = 1
left_length = range_length[n - 1]
r... |
"""
## Introduction
When subclasses grow and get developed separately, identical (or nearly identical) fields and methods appear.
Pull up field refactoring removes the repetitive field from subclasses and moves it to a superclass.
## Pre and Post Conditions
### Pre Conditions:
1. There should exist a corresponding c... |
import asyncio
import functools
import json
import time
from collections import Counter, defaultdict, deque
from fractions import Fraction
from typing import Dict, List, Optional, Tuple, Union
from quarkchain.cluster.filter import Filter
from quarkchain.cluster.miner import validate_seal
from quarkchain.cluster.neighb... |
#!/usr/bin/env python3
import fnmatch
import os
import re
import sys
def get_files():
# Allow running from root directory and tools directory
root_dir = ".."
if os.path.exists("addons"):
root_dir = "."
sqf_files = []
for root, _, files in os.walk(root_dir):
for file in fnmatch.f... |
# -*- coding: utf-8 -*-
__license__ = \
"""Copyright 2019 West University of Timisoara
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.... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import os
import sys
import multiprocessing
if hasattr(sys, "frozen"):
exedir = os.path.dirname(sys.executable)
os.environ['PATH'] = exedir
paths = ['lib',
'lib/library.zip',
'lib/butterflow',
'lib/numpy/core',
... |
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 27 17:34:07 2014
@author: ydzhao
"""
import scipy.io as sio
import numpy as np
def pro_mat2py(matdir):
matdata=sio.loadmat(matdir)
banlist=['__header__', '__globals__','__version__']
for item in (set(matdata.keys())-set(banlist)):
if matdata[item].sha... |
"""
This program can be solved by the concept of backtracking.
Fix a character in the first position
and swap the rest of the character
with the first character.
Like in ABC, in the first iteration
three strings are formed:
ABC, BAC, and CBA by swapping A with A,
B and C respectively.
Repeat step 1 for t... |
from iconservice import *
class Delegation(TypedDict):
address: Address
value: int
class SampleSystemScoreInterCall(IconScoreBase):
def __init__(self, db: IconScoreDatabase) -> None:
super().__init__(db)
self.use_interface = VarDB("use_interface", db, value_type=bool)
def on_install... |
# Copyright 2014 Nervana Systems Inc., 2016 Hugh Perkins 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 requ... |
#!/usr/bin/env python
# coding: utf-8
# created by hevlhayt@foxmail.com
# Date: 2016/10/7
# Time: 12:29
import datetime
import networkx as nx
from django.db.models import Q
from friendnet.models import Link, GroupMember
def global_core(G):
for (s, t, d) in G.edges(data=True):
# w = d['weight']
#... |
from . import portfolio
'''
TODO:
- chart growth of 10k
- Fix problem of potentially getting older return series
(maybe just always construct a new return series?)
'''
class Chart:
def __init__(self, portfolio_obj):
if not isinstance(portfolio_obj, portfolio.Portfolio):
raise TypeError(f'{po... |
from django.contrib.auth.models import User
from django.test import TestCase
from django.urls import reverse
from model_mommy import mommy
from rest_framework.exceptions import ErrorDetail
from rest_framework.test import APIClient
from rest_framework import serializers
from unittest.mock import patch, MagicMock
from s... |
import secrets
from fastapi import Depends, HTTPException, Security, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from fastapi.security.api_key import APIKeyCookie, APIKeyHeader, APIKeyQuery
from starlette.status import HTTP_403_FORBIDDEN
import config
# API_KEY = "1234567asdfgh"
API_KEY = co... |
"""
I/O for VTU.
<https://vtk.org/Wiki/VTK_XML_Formats>
<https://vtk.org/wp-content/uploads/2015/04/file-formats.pdf>
"""
import base64
import re
import sys
import zlib
import numpy as np
from ..__about__ import __version__
from .._common import info, join_strings, raw_from_cell_data, replace_space, warn
from .._exce... |
from io import BytesIO
from pyrogram import Client, filters
from pyrogram.types import Message
from config import prefix
from consts import http
from localization import use_chat_lang
from utils import commands
@Client.on_message(filters.command("print", prefix))
@use_chat_lang()
async def prints(c: Client, m: Mess... |
from gym_221bbakerstreet.environments.baker_street import BakerStreetEnvironment
|
'''Faça um programa que tenha uma função chamada maior(), que receba vários parâmetros
com valores inteiros.
Seu programa tem que analisar e dizer qual deles é o maior.'''
#Não fiz!
from time import sleep
def maior(* núm):
cont = maior = 0
print('-'*30)
print('\nAnalisando os valores passados... ')
for... |
import argparse
from utils import int_tuple
def get_evaluation_parser():
parser = get_training_parser()
parser.add_argument("--dset_type", default="test", type=str)
parser.add_argument("--noise_mix_type", default="global")
parser.add_argument('--metrics', type=str, default='accuracy', choices=['accura... |
from gym.envs.registration import register
# Mujoco
# ----------------------------------------
# - randomised reward functions
register(
'AntDir-v0',
entry_point='environments.wrappers:mujoco_wrapper',
kwargs={'entry_point': 'environments.mujoco.ant_dir:AntDirEnv',
'max_episode_steps': 200},
... |
import os
import sys
import time
import datetime
import logging
import shutil
import mumaxc as mc
import subprocess as sp
log = logging.getLogger(__name__)
class MumaxRunner:
"""Base class for running mumax3.
Don't use this directly. Use get_mumax_runner() to pick a subclass
of this class.
"""
... |
import numpy as np
from keras.utils import to_categorical
from keras.models import Sequential, Model
from keras.layers import Dense, Activation, Dropout, Flatten, Conv2D, MaxPooling2D
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import data_process
#Load sign language ... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
from .views import index as home
urlpatterns = [
url(r'^$', home, name='index'),
url(r'^store/$', include('store.urls')),
url(r'^admin/', include(admin.site.urls)),
]
# settings for development environment DEBUG
from d... |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 5 14:52:14 2016
@author: shibom
"""
import sys, os, time
import PyQt4.QtGui as Qt
import PyQt4.QtCore as QC
import subprocess as sub
import plot_utils as psx
import plot_cluster as pc
from sphase import Building
import run_shelx
def writer(filename, symm, sites, resolut... |
from data import *
from utilities import *
from networks import *
import matplotlib.pyplot as plt
import numpy as np
num_known_classes = 65 #25
num_all_classes = 65
def skip(data, label, is_train):
return False
batch_size = 32
def transform(data, label, is_train):
label = one_hot(num_all_classes,label)
d... |
# Generated by Django 3.1.8 on 2021-04-19 12:59
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
]
operations = [
migrations.CreateMode... |
import json
import requests
import urllib3
from bs4 import BeautifulSoup
from base.casadecambio import CasaDeCambio
from base.origintype import OriginType
from base.cotizacion import Cotizacion
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
class Interfisa(CasaDeCambio):
__id = "interfisa"
... |
import os, sys
import math
import numpy as np
import skimage.io
import cv2
from PIL import Image
# Root directory of the project
ROOT_DIR = os.path.abspath("../..")
if ROOT_DIR not in sys.path:
sys.path.insert(0, ROOT_DIR)
from instance_segmentation.object_config import Config
import utils
class ObjectsConfig(C... |
def cfgParser(path):
f = open(path,'r')
#contents = list()
cfgDict = dict()
for i in f.readlines():
data = i.strip('\n')
if data == '' or data[0] == '#':
continue
name,value=data.split('=')
if name == 'lossFunction' or name == 'optimizer' or name == 'devic... |
import json
from dataclasses import dataclass
from pathlib import Path
import web3
from web3.contract import Contract
from beamer.typing import Address, BlockNumber, ChainId
@dataclass
class ContractInfo:
address: Address
deployment_block: BlockNumber
abi: list
def make_contracts(w3: web3.Web3, contra... |
import os
import json
def loadJson(relative_file_location):
with open(relative_file_location) as json_data:
return json.load(json_data)
def addOneToString(stringInt):
return str(int(stringInt) + 1)
def loadStuffTextLabels(relative_file_location):
file = open(relative_file_location, 'r')
stuff... |
import os
import pytz
from .models import Bot, BotflowExecution, SmtpAccount
from django.dispatch import receiver
from django.db.models.signals import pre_save, post_save
from smtplib import SMTP, SMTP_SSL
from email.message import EmailMessage
from os.path import basename
from datetime import datetime
@receiver(pre_... |
import matlab.engine # Must import matlab.engine first
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as models
from collections import OrderedDict
import pdb
class BackboneNet(nn.Module):
def __init__(self, in_features, class_num, dropout_rate, cls_branch_num,
... |
# -*- coding: utf-8 -*-
"""
EnigmaLight Plugin by Speedy1985, 2014
https://github.com/speedy1985
Parts of the code are from other plugins:
all credits to the coders :-)
EnigmaLight 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 S... |
import time
from sqlalchemy import func
from app import db
from app import work_log
from app.main.dbmodel.logdb import t_host_cpu
class MonitorTask(object):
"""docstring for MonitorTask"""
def __init__(self):
super(MonitorTask, self).__init__()
def HostUptimeData(self, data):
ip = data.ge... |
#!/usr/bin/env python3
from settings import *
class Rom:
@staticmethod
def atualizar():
os.chdir(home + "/"+ rom_custom)
os.system("repo sync -c -f --force-sync -j32 --no-tags --no-clone-bundle --force-broken")
@staticmethod
def limpar():
os.chdir(home + rom_custom + outdir... |
# Type examples
#my_cat = "garfield is 2"
#print(my_cat)
#print(type(my_cat))
#print(type(12))
#print(type(3.14))
"""
Thinking of a grocery list, it might be:
- eggs
- milk
- bread
- bacon
- cheese
"""
# my_blank_list = []
# basic_list = ["item1", "item2"]
groceries = ["eggs", 3.14, "milk", "bre... |
import os
import tarfile
import tempfile
from copy import copy
from pkg_resources import safe_version, to_filename
from pdm.builders.base import Builder
from pdm.context import context
def normalize_file_permissions(st_mode):
"""
Normalizes the permission bits in the st_mode field from stat to 644/755
... |
#!/usr/bin/env python3
# −*− coding:utf-8 −*−
import numpy as np
from scipy.linalg import eigh_tridiagonal
class Multitaper(object):
'''
A class to perform the spectral density estimation of an input signal based on the multitaper method
'''
def __init__(self, nn, nw=3.5, kk=7):
'''
... |
import musekafka
def test_version_exists():
"""musekafka.__version__ is set."""
assert musekafka.__version__ is not None
|
import abc
import copy
import inspect
import json
import os
import six
from fireworks.core.firework import FireTaskBase
from fireworks.core.firework import FWAction
from fireworks.core.firework import Workflow
from fireworks.core.firework import Firework
from fireworks.core.launchpad import LaunchPad
from fireworks.ut... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module estimates the X-rays and extreme-ultraviolet luminosity of a star.
"""
from __future__ import (division, print_function, absolute_import,
unicode_literals)
import numpy as np
import astropy.units as u
__all__ = ["x_rays_luminosity... |
import svgwrite as sw
# Require the python package svgwrite
# Input sequence here for graphic generation
sequence = "TTLTNLTTLESIK"
output_filename = "TTLTNLTTLESIK.svg"
def draw_aa(group, canvas, aa, x_pos, y_pos, font_size=10, font_style="normal", font_family="Courier"):
# Function for drawing amino acid letter
... |
from django.db import models
from django.contrib.auth.models import User
from PIL import Image
from django.urls import reverse
class Neighbourhood(models.Model):
name = models.CharField(max_length=50)
def __str__(self):
return self.name
def get_absolute_url(self):
return revers... |
# This file is a part of Arjuna
# Copyright 2015-2021 Rahul Verma
# Website: www.RahulVerma.net
# 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... |
#
# @lc app=leetcode.cn id=69 lang=python3
#
# [69] sqrtx
#
None
# @lc code=end |
# -*- encoding: utf-8 -*-
"""
=================================================
@path : pointnet.pytorch -> tools.py
@IDE : PyCharm
@Author : zYx.Tom, 526614962@qq.com
@Date : 2021-12-23 15:11
@Version: v0.1
@License: (C)Copyright 2020-2021, zYx.Tom
@Reference:
@Desc :
=========================================... |
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from navigation import Menu
from .icons import icon_cabinet_list
menu_cabinets = Menu(
icon_class=icon_cabinet_list, label=_('Cabinets'), name='cabinets menu'
)
|
"""Visualization helpers."""
from contextlib import contextmanager
import copy
import os.path as op
import numpy as np
from scipy import linalg
from mne import read_proj, read_events, pick_types
from mne.utils import verbose
from mne.viz.utils import tight_layout, plt_show
from ._sss import compute_good_coils
from ... |
from snovault import upgrade_step
@upgrade_step('publication', '1', '2')
def publication_1_2(value, system):
if 'identifiers' in value:
for i in value['identifiers']:
path = i.split(':')
if path[0] == 'doi':
value['doi'] = path[1]
elif path[0] == 'PMID':
value['pmid'] = path[1]
del value['identi... |
n = int(input("Welcher Wert für n?"))
j = 0
i = 1
zeilenbreite = n + (n-1)
while j < (n*2-1):
if j <= n-1: #dach wird hier gemacht
zeile = i+(i-1)
zeilenseite = int((zeilenbreite - zeile)/2)
print (zeilenseite*" ",end='')
print (zeile*"0", end='')
print (zeilenseite*" ")... |
import os.path
import numpy as np
import numpy.testing as npt
import pytest
from base import _AdapterTester
from scmdata import ScmRun
from openscm_runner import run
from openscm_runner.adapters import FAIR
from openscm_runner.utils import calculate_quantiles
class TestFairAdapter(_AdapterTester):
@pytest.mark.... |
import inspect
import wrapt
from typing import NamedTuple, List
from functools import reduce
class FunctionReference(NamedTuple):
name: str
line: int
source: str
short_purpose: List[str] = []
references: List[str] = []
class Biblio(dict):
track_references: bool = False
def __str__(self)... |
import json
from datetime import datetime
class CRMSystemError(Exception):
def __init__(self, errorId, errorMessage, *args, **kwargs):
super().__init__(errorMessage, *args, **kwargs)
self.errorId = errorId
self.errorMessage = errorMessage
def __str__(self):
message = "{} - {}... |
# -*- coding: utf-8 -*-
import cv2, os
import numpy as np
from scipy.io import loadmat
import matplotlib.pyplot as plt
class stereoCameral(object):
def __init__(self):
stereoParameters = loadmat("./internal_reference/stereoParameters.mat")
self.cam_matrix_left = stereoParameters["stereoParamete... |
import CatalogItem
from toontown.toonbase import ToontownGlobals
from toontown.fishing import FishGlobals
from direct.actor import Actor
from toontown.toonbase import TTLocalizer
from direct.interval.IntervalGlobal import *
class CatalogTankItem(CatalogItem.CatalogItem):
sequenceNumber = 0
def makeNewItem(sel... |
def dfs(grafo, origen, v, padre, distancia, peso_min_actual):
for w in grafo.adyacentes(v):
if w == origen and padre[v] != origen:
peso_camino = distancia[v] + grafo.peso_arista(v, origen)
if len(distancia) == len(grafo) and peso_camino < peso_min_actual[0]:
peso_min_... |
from crawler.exportExcel import export_product_excel
from crawler.stringgetter import get_page_string
from bs4 import BeautifulSoup
import time
depth = [('445726', '445626', '강아지 사료', '건식사료', '건식사료', '건식사료'),
('445727', '445627', '강아지 사료', '소프트사료', '소프트사료', '소프트사료'),
('445728', '445628', '강아지 사료', '습... |
import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
clr.AddReference("RevitNodes")
import Revit
clr.ImportExtensions(Revit.Elements)
clr.AddReference('RevitServices')
import RevitServices
from RevitServices.Persistence import DocumentManager
doc = DocumentManager.Instance.CurrentDBDocument
if n... |
class C:
"""
Examples
----------
>>> c = C()
>>> c.setx(4)
>>> print(c.getx())
4
>>> c.delx()
"""
def __init__(self):
self._x = None
def getx(self):
return self._x
def setx(self, value):
if value < 0:
raise ValueError
else:
... |
import sys
from os.path import abspath, dirname
root_dir = dirname(dirname(abspath(__file__)))
sys.path.append(root_dir)
pytest_plugins = [
]
|
# -*- coding: utf-8 -*-
from sys import stdout
if __name__ == '__main__':
input = int(input())
for x in range(input, 0, -1):
for y in range(input - x):
stdout.write(" ")
for z in range(2 * x - 1):
stdout.write("*")
print()
for x in range(1, in... |
# 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, software
# d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.