content
stringlengths
0
894k
type
stringclasses
2 values
import numpy as np import modeling.geometric_model as gm import modeling.collision_model as cm import visualization.panda.world as wd import basis.robot_math as rm import math import pickle from scipy.spatial import cKDTree import vision.depth_camera.surface.gaussian_surface as gs import vision.depth_camera.surface.rbf...
python
from django.http import Http404 from django.test import TestCase from model_bakery import baker from django.shortcuts import get_object_or_404 from paranoid_model.tests import models class TestGetObjectOr404(TestCase): def test_raise_when_object_does_not_exists(self): with self.assertRaises(Http404): ...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Sep 13 12:14:02 2018 @author: jguillaumes """ import os import sqlite3 import configparser import threading import calendar import pkg_resources from time import sleep from weatherLib.weatherUtil import WLogger,parseLine _SELECT_TSA = 'select maxt...
python
# Princeton University licenses this file to You 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 writin...
python
''' File name: GIN.py Discription: Learning Hidden Causal Representation with GIN condition Author: ZhiyiHuang@DMIRLab, RuichuCai@DMIRLab From DMIRLab: https://dmir.gdut.edu.cn/ ''' from collections import deque from itertools import combinations import numpy as np from causallearn.graph.GeneralGraph...
python
#!/usr/bin/python2.5 # # Copyright 2010 Google Inc. # # 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 ...
python
#!/bin/env python3.9 """ cyclic backup creating a tar file """ import datetime import getopt import logging import os import re import sqlite3 import stat import sys import tarfile import time import traceback from builtins import bool import jinja2 import yaml blocked = set() config = { 'db': 'cycbackup.db', ...
python
# -*- coding: utf-8 -*- from os.path import dirname, abspath from math import sqrt import numpy as np from scipy.stats import spearmanr, pearsonr from scipy.spatial.distance import cosine import matplotlib matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab! Needed for calculations on server....
python
from base import * import numpy as np from typing import List def numpy_heavy_create_dot(number, base): start = time.time() - base DIMS = 3000 a = np.random.rand(DIMS, DIMS) b = np.random.rand(DIMS, DIMS) np.dot(a, b) stop = time.time() - base return start, stop nums = range(1, 8) run_t...
python
from ..encoding import wif_to_secret_exponent from ..convention import tx_fee from .Spendable import Spendable from .Tx import Tx from .TxOut import TxOut, standard_tx_out_script from .pay_to import build_hash160_lookup class SecretExponentMissing(Exception): pass class LazySecretExponentDB(object): """ ...
python
from calendar import timegm from datetime import datetime import logging from django.contrib.sessions.middleware import SessionMiddleware from django.contrib.auth.middleware import AuthenticationMiddleware from django.core.urlresolvers import reverse from django.conf import settings from rest_framework import excepti...
python
import json import uuid from moto.awslambda.exceptions import ( PreconditionFailedException, UnknownPolicyException, ) class Policy: def __init__(self, parent): self.revision = str(uuid.uuid4()) self.statements = [] self.parent = parent def wire_format(self): p = self...
python
""" TensorFlow 基础概念 """ #%% 导入 TensorFlow import tensorflow as tf #%% 什么是Tensor # Tensor 是 TensorFlow 的基本对象 # 说白了就是多维向量 t0 = tf.constant(1) # 0阶 tensor t1 = tf.constant([1, 2]) # 1阶 tensor t2 = tf.constant([[1, 2], [3, 4]]) # 2阶 tensor t3 = tf.constant([[[1., 2., 3.]], [[7., 8., 9.]]]) # 3阶 tensor print(t0) print...
python
import unittest import pytest from api.utils import encode from api.utils import decode class UtilsTest(unittest.TestCase): def test_base62_encode_zero(self): n = 0 encoded_digit = encode(n) assert "0" == encoded_digit def test_base62_encode_digit(self): n = 4 encode...
python
#!/usr/bin/env python import subprocess import os import sys import glob import json import traceback import re import logging log = logging.getLogger('run-ci') import time import threading from benchmark import framework_test from benchmark.utils import gather_tests from benchmark.utils import header # Cross-platfor...
python
from .dns_server import DnsServer, DnsServerNotRunningException from .dns_demo_server import DnsDemoServer
python
import tempfile import unittest from pathlib import Path import numpy as np import pandas as pd from tests.fixtures.algorithms import DeviatingFromMean, DeviatingFromMedian from tests.fixtures.dataset_fixtures import CUSTOM_DATASET_PATH from timeeval import TimeEval, Algorithm, AlgorithmParameter, DatasetManager, Inp...
python
"""Kata: Binary Addition - Return the opposite of the input number. #1 Best Practices Solution by arzyk and 7 others def add_binary(a,b): return bin(a+b)[2:] """ def add_binary(a, b): return bin(a + b)[2:]
python
# -*- coding: utf-8 -*- import dataiku import pandas as pd, numpy as np from dataiku import pandasutils as pdu import requests import urllib import json import time from datetime import datetime from dataiku.customrecipe import * import dataiku_esri_utils import common from dataiku_esri_utils import recipe_config_get_s...
python
""" This file is needed as 1.6 only finds tests in files labelled test_*, and ignores tests/__init__.py. """ from south.tests import *
python
""" Copyright (c) 2018-2021 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in wri...
python
""" The ``agar.json`` module contains classes to assist with creating json web service handlers. """ import datetime import logging from google.appengine.ext.db import BadRequestError, BadValueError from agar.config import Config from agar.models import ModelException from pytz.gae import pytz from restler.seriali...
python
#!/usr/bin/python from math import floor def find_largest_factor(n): """ Return the largest prime factor of n: 1. Find i such that i is the smallest number that i * j = n 2. Therefore the largest prime factor of n is also the largest prime factor of j 3. Repeat until j is a prime number ...
python
# Generated by Django 3.2.6 on 2021-09-04 16:44 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('telegrambot', '0011_telegramuserbot'), ] operations = [ migrations.AddField( model_name='telegramuserbot', name='ses...
python
''' File name: utilities.py Author: Simonas Laurinavicius Email: simonas.laurinavicius@mif.stud.vu.lt Python Version: 3.7.6 Purpose: Utilities module defines various helper functions used by different modules ''' # Local modules import formats def return_shorter_str(str1, str2): if l...
python
CLAUSE_LIST = [(1,), (0,)] N = 3 A = 65 class SAT: """ This class is an SAT solver. Create an instance by passing in a list of clauses and the number of variables Uses notation of 2N + 1 to input tuples of clauses Ex: (A+B)(~B+C) - > (0, 2)(3, 4) There are 3 variables so: A = 0 = 2*(0) ...
python
from __future__ import unicode_literals from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.utils.translation import ugettext_lazy as _ from datetime import datetime as ...
python
#Much code directly from Google's TensorFlow """Library for creating sequence-to-sequence models.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from six.moves import xrange # pylint: disable=redefined-builtin import tensorflow as tf import inspect ...
python
# -*- coding: utf-8 -*- """ Created on Sun Jun 28 13:06:28 2020 @author: tomvi """ import pandas as pd import math import statistics as stat import statsmodels.api as sm from statsmodels.stats.diagnostic import het_white as white, \ het_breuschpagan as bpt import numpy as np import matplotlib.pyplot...
python
import torch from torch.nn.utils import clip_grad_value_ from torch.distributions import Categorical from radbm.utils.torch import torch_soft_hamming from radbm.search.elba import EfficientLearnableBinaryAccess def categorical_entropy(cat): """ -(cat*cat.log()).sum() without the annoying 0*inf Paramet...
python
import Print import os import shutil import sq_tools import io import sys import listmanager import csv import requests try: import ujson as json except: import json from tqdm import tqdm # SET ENVIRONMENT squirrel_dir=os.path.abspath(os.curdir) NSCB_dir=os.path.abspath('../'+(os.curdir)) if os.p...
python
"""Third-party commands enabled through drytoml.""" import importlib import os import shlex import subprocess as sp # noqa: S404 import sys import tempfile from contextlib import contextmanager from pathlib import Path from typing import IO from typing import Callable from typing import List from typing import Union ...
python
# 313. Super Ugly Number # ttungl@gmail.com class Solution(object): def nthSuperUglyNumber(self, n, primes): """ :type n: int :type primes: List[int] :rtype: int """ # runtime: 535ms ugly = [1]*n i = [-1]*len(primes) v = [1]*len(primes) ...
python
from django.core.management import call_command from unittest import mock from django_webpack_dev_server.management.generator import Generator class TestCommand: """ Test Class for testing the Command Class defined in the generate.py """ @mock.patch.object(Generator, "generate") def test_command(...
python
""" """ import numpy as np from ..diffstar_ew_kernels import _calc_ew_from_diffstar_params_const_lgu_lgmet from ..diffstar_ew_kernels import _calc_ew_from_diffstar_params_const_lgmet from ..sfh_model import DEFAULT_MAH_PARAMS, DEFAULT_MS_PARAMS, DEFAULT_Q_PARAMS from ..mzr import DEFAULT_MZR_PARAMS from .retrieve_fake_...
python
# ABC165A - We Love Golf def main(): # input K = int(input()) A, B = map(int, input().split()) # compute km=False for i in range(A,B+1): if i%K ==0: km=True # output if km: print("OK") else: print("NG") if __name__ == '__main__': main()
python
# Adapted from https://github.com/opencv/opencv_contrib/blob/master/modules/aruco/samples/detect_markers.cpp import argparse import cv2 import utils def main(args): # Read camera parameters camera_params_file_path = utils.get_camera_params_file_path(args.camera_name) image_width, image_height, camera_matri...
python
from unittest import TestCase from vision.flashless_utility import copy_backup_flashless_files, rollback_flashless_files from vision.constant import VisionException from mock import patch class TestFlashlessUtility(TestCase): @patch('os.path.isfile', return_value=True) @patch('shutil.copyfile') def tes...
python
from mandaw import * mandaw = Mandaw("Window!", width = 800, height = 600, bg_color = (0, 0, 0, 255)) mandaw.loop()
python
import uuid import unittest from TwitterSentimentAnalysis import ai, core, downloaders, datasets import numpy as np import os from sklearn.metrics import mean_squared_error class NeuralNetworksTweetsTestCase(unittest.TestCase): @classmethod def setUpClass(cls): base_dir = os.path.dirname(__file__) ...
python
import os import discord from dotenv import load_dotenv load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN') GUILD = os.getenv('DISCORD_GUILD') client = discord.Client() @client.event async def on_ready(): guild = discord.utils.get(client.guilds, name=GUILD) print( f'{client.user} is connected to the fo...
python
class NumArray(object): def __init__(self, nums): """ :type nums: List[int] """ self.prefixSum = [0] * (len(nums) + 1) currentSum = 0 for idx, num in enumerate(nums): currentSum += num self.prefixSum[idx + 1] = currentSum def sumRange(se...
python
# -*- coding: utf-8 -*- from sqlalchemy import Column, ForeignKey, Integer, String, UniqueConstraint from sqlalchemy.orm import relationship from .models import BASE class CaseGenelistLink(BASE): """Link between case and gene list.""" __tablename__ = 'case_genelist_link' __table_args__ = (UniqueConstra...
python
# Generated by Django 3.1 on 2020-09-26 19:45 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('projects', '0003_auto_20200912_1626'), ('delivery', '0001_initial'), ] operations = [ migrations.Alte...
python
"""Monkey patch other python libraries.""" import numpy as np import jax from jax import core, lax, numpy as jnp from jax._src.lib import xla_client as xc from jax._src.lib.xla_bridge import get_backend as default_get_backend from jax.interpreters import partial_eval as pe from jax.interpreters.xla import (xops, jaxpr_...
python
#coding: utf-8 import sys import os import re import argparse def process_file(input_file): log = {} log['clients'] = [] log['95per'] = [] log['min'] = [] log['med'] = [] log['max'] = [] for line in input_file: point = parse_line(line) if point: log['clients'].append(point['clients']) log['95per']...
python
import numpy as np from small_text.data import Dataset, DatasetView from small_text.data.exceptions import UnsupportedOperationException from small_text.integrations.pytorch.exceptions import PytorchNotFoundError try: import torch from torchtext.vocab import Vocab except ModuleNotFoundError: raise Pytorc...
python
# Generated by Django 3.2.5 on 2021-07-16 21:04 import colorfield.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('entertainment', '0001_initial'), ] operations = [ migrations.AlterField( model_name='article', ...
python
import sys import time import json import theano import theano.tensor as T import numpy as np if __name__=='__main__': data_location = sys.argv[1] print 'thinking' class Layer(object): ''' The base layer object. an artificial neural network is composed of many of these objects connected. ...
python
from unittest import TestCase from nestor_api.adapters.git.github_git_provider import GitHubGitProvider from nestor_api.adapters.git.provider import get_git_provider class TestProvider(TestCase): def test_get_git_provider_with_github(self): git_provider = get_git_provider({"git": {"provider": "github"}})...
python
import tensorflow as tf def conv(filters, kernel_size, strides = 1, padding = "same", use_bias = True, kernel_initializer = "he_normal", **kwargs): return tf.keras.layers.Conv2D(filters, kernel_size, strides = strides, padding = padding, use_bias = use_bias, kernel_initializer = kernel_initializer, **kwargs) clas...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """integration pytests for :mod:`graypy` .. note:: These tests require an local instance of Graylog to send messages to. """ import requests def validate_local_graylog_up(): """Test to see if a localhost instance of Graylog is currently running""" try: ...
python
import petsc4py import sys petsc4py.init(sys.argv) from petsc4py import PETSc def PCDKSPsetup(F, Q, A): # OptDB = PETSc.Options() # OptDB['pc_hypre_type'] = 'boomeramg' # OptDB['pc_hypre_boomeramg_strong_threshold'] = 0.5 # OptDB['pc_hypre_boomeramg_grid_sweeps_all'] = 1 kspF = PETSc.KSP() ...
python
""" Reasoner based on the 'model theory' by Guerth: https://github.com/CognitiveComputationLab/cogmods/blob/master/modal/student_projects/2019_guerth/models/mmodalsentential/reasoner.py Modified by Kaltenbl for propositional reasoning """ import numpy as np from .assertion_parser import parse_all, facts from .model_bu...
python
def find(db, user): """ find the notelist :param db: :param user: :return: """ document = db.notelist.find_one({"_id": user}) return document def find_all_lists(db, user): """ It finds all lists :param db: :param user: :return: """ document = db.notelist.fin...
python
# -*- coding: utf-8 -*- from .dataObject import DataObject from .muscle import Muscle from .cell import Cell from .network import Network class Worm(DataObject): """ A representation of the whole worm. All worms with the same name are considered to be the same object. Attributes ---------- ...
python
# This code is available under the MIT License. # (c)2010-2011 Nakatani Shuyo / Cybozu Labs Inc. # (c)2018-2019 Hiroki Iida / Retrieva Inc. import nltk import re import MeCab stopwords_list = nltk.corpus.stopwords.words('english') recover_list = {"wa":"was", "ha":"has"} wl = nltk.WordNetLemmatizer() def load_corpu...
python
#coding=utf8 import logging import logging.handlers import time from django.conf import settings from django.core.management.base import BaseCommand import django_rq from redis_cache import get_redis_connection from dbss.cardspace.models import warp_update_index from dbss.daemonize import Daemonize def test(): ...
python
from numpy import interp def rangeMap(num): return int(interp(num,[-32768,32768],[1,10])) while 1: print(rangeMap(int(input())))
python
""" @brief test log(time=0s) """ import os import unittest from pyquickhelper.loghelper import fLOG from pyquickhelper.pycode import check_pep8 class TestCodeStyle(unittest.TestCase): def test_code_style_src(self): fLOG( __file__, self._testMethodName, OutputPrin...
python
#!/usr/bin/env python # encoding: utf-8 """ Run the talus worker daemon, specifying the maximum number of cores to use, the maximum RAM available for the VMs, the AMQP host to connect to, and a plugins directory. """ # system imports import argparse import math import multiprocessing import os import sys # local i...
python
from __future__ import annotations from dataclasses import is_dataclass, fields, MISSING from typing import Any def nub(x: Any) -> dict[str, Any]: assert is_dataclass(x) out: dict[str, Any] = {} for f in fields(x): a = getattr(x, f.name) if ( isinstance(a, dict | set | list) ...
python
#! /usr/bin/env python # """CLI wrapper script, ensures that relative imports work correctly in a PyInstaller build""" from isolyzer.isolyzer import main if __name__ == '__main__': main()
python
from io import StringIO from collections import UserDict, UserList import numpy as np import confiddler.json as json def test(): """ Our drop-in json replacement can encode custom mappings and sequences, and also numpy arrays. """ d = UserDict() d['l'] = UserList([1,2,3]) d['a'] = np.aran...
python
from rick_roll_detector.image import verify_image import cv2 # vid_cap has to be a cv2.VideoCapture() def verify_video(vid_cap: cv2.VideoCapture) -> bool: success, image = vid_cap.read() while success: success, image = vid_cap.read() # If the video ended return false. if not success: ...
python
from src.bsl_python.preprocessing.experiments.experiment import Experiment from src.bsl_python.preprocessing.processor.spiking_activity import DefaultSpikingActivity, MeanFilteredActivity, \ FilteredActivity from src.bsl_python.preprocessing.processor.tuning_curve import TuningCurve from collections import Counter ...
python
#!/usr/bin/env python import rospy from std_msgs.msg import Bool from dbw_mkz_msgs.msg import ThrottleCmd, SteeringCmd, BrakeCmd, SteeringReport from geometry_msgs.msg import TwistStamped import math from twist_controller import Controller ''' You can build this node only after you have built (or partially built) th...
python
#!/usr/bin/env python2 """Utilities for training.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import datetime import numpy as np from caffe2.python import utils as c2_py_utils from caffe2.python import workspa...
python
import json AppSettings = dict() with open('app.config') as json_data: for k, v in json.load(json_data).items(): AppSettings[k] = v
python
# assign this folder as a namespace __path__ = __import__('pkgutil').extend_path(__path__, __name__) # __all__ = ['flow']
python
from os.path import expanduser, exists from ansible.parsing.vault import VaultLib, VaultSecret from yaml import load, SafeLoader class VaultReader: """ Read data from a vault file. """ def __init__(self, vault_file, vault_pass): """ Create a vault reader. :param vault_file: ...
python
import pymongo import os def get_mongo_config(): config = { 'username':os.environ['MDBUSR'], 'password':os.environ['MDBPWD'], 'host':'mongo', 'port':27017, } return config def connect_to_mongodb(): config = get_mongo_config() try: mc = pymongo.MongoCl...
python
from typing import List, Sequence def remove_redundant_fao_area_codes(s: Sequence[str]) -> List[str]: """Filters the input sequence of FAO areas to keep only the smallest non overlapping areas. This is useful to prune lists of FAO areas that result from intersecting a geometry (ports, vessel position...
python
# Skill pour demander au robot de nous guider import core.robot as robot from core.skills.ArgSkill import ArgSkill from core.communication import * with open('core/map.json', encoding='utf-8') as data_file: map = json.load(data_file) phrases = [ "guide moi", "amène moi", "amene moi", "emmene moi"...
python
import math import sys import time import pybullet as p import pybullet_data import model as m import util as ut BOUNCE = "bounce" ROLL = "roll" TIME_STEP_S = 0.01 def configPyBullet(): physicsClient = p.connect(p.GUI) p.setAdditionalSearchPath(pybullet_data.getDataPath()) # used by loadURDF p.resetSi...
python
import datetime as dt import json from json import encoder import xarray as xr import numpy as np from pandas import to_datetime from collections import OrderedDict import dateutil import logging import six logging.basicConfig() encoder.FLOAT_REPR = lambda o: format(o, '.4f').rstrip('0').rstrip('.') AXIS_VAR=['time'...
python
A, B = int(input()), int(input()) if A * B > 0: print(2 * max(abs(A), abs(B))) else: print(2 * abs(A) + 2 * abs(B))
python
from Crypto.Cipher import AES from base64 import b64encode, b64decode BLOCK_SIZE = 16 PADDING = '{' pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING def encrypt(key, msg): cipher = AES.new(pad(key).encode('utf-8')) return b64encode(cipher.encrypt(pad(msg))).decode('utf-8') def decrypt(key, msg): ...
python
"""Doxygen module. Create project's documentation. Website: http://www.doxygen.org """ import os def doxygen(loader, project=None, variant=None, *args): #pylint:disable=keyword-arg-before-vararg loader.setup_project_env(project, variant) loader.setup_virtualenv() loader.setup_shell_env() config = loa...
python
import sys sys.path.insert(0, '..') import numpy as np import pandas as pd from itertools import combinations from scipy.stats import binom import scipy.special import matplotlib.pyplot as plt import matplotlib.patches as mpatches from IPython.display import display, HTML #sys.path.append("../") from FrameBuilder.eige...
python
#!/usr/bin/env python3 import math import torch from torch.distributions import MultivariateNormal as TMultivariateNormal from torch.distributions.kl import register_kl from torch.distributions.utils import _standard_normal, lazy_property from .. import settings from ..lazy import LazyTensor, lazify from .distributi...
python
import torch from torch.utils.data import DataLoader import torchvision from torchvision.transforms import ToTensor from appfl.misc.data import * DataSet_name = "MNIST" num_channel = 1 # 1 if gray, 3 if color num_classes = 10 # number of the image classes num_pixel = 28 # image size = (num_pixel, num_pixel) """...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys from shutil import copy import pyshanb from pyshanb.helper import windows, home, default_configfile try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python se...
python
import os import time import queue import demomgr.constants as CNST from demomgr.filterlogic import process_filterstring, FILTERFLAGS from demomgr.helpers import readdemoheader from demomgr.threads.read_folder import ThreadReadFolder from demomgr.threads._threadsig import THREADSIG from demomgr.threads._base import _S...
python
""" writen by stephen """ import os import numpy as np import tensorflow as tf from alexnet import AlexNet from datagenerator import ImageDataGenerator from datetime import datetime import glob from tensorflow.contrib.data import Iterator learning_rate = 1e-4 num_epochs = 100 # 代的个数 batch_size = 1024 dropout_rate = ...
python
# -*- coding: utf-8 -*- # © 2016 Danimar Ribeiro, Trustcode # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from decimal import Decimal from datetime import date from datetime import datetime from unicodedata import normalize def normalize_str(string): """ Remove special characters and s...
python
""" Test Runner class. Lets you setup testrail and run a bunch of tests one after the other """ import os,subprocess class Test_Runner_Class: "Test Runner class" def __init__(self,base_url='http://qxf2.com',testrail_flag='N',browserstack_flag='N',os_name='Windows',os_version='7',browser='firefox',browser_vers...
python
import settings as S* from util import * import stress from genrig import * from graph import * from dist import * from numpy import * from scipy.linalg.basic import * from scipy.linalg.decomp import * v=8 d=2 E=array([[0,1],[0,2],[1,2],[1,4],[2,3],[2,5],[3,4],[3,7],[4,5],[5,6],[5,7],[6,7],[3,6],[0,4]], 'i') e=len(E) ...
python
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def hasCycle(self, head): """ :type head: ListNode :rtype: bool """ p1 = head p2 = head # ...
python
import os # Dates DATE_FORMAT: str = "%Y-%m-%d" # Default date format TIMESTAMP_FORMAT: str = '%Y-%m-%d %H:%M:%S.%f' # Default timestamp format # Paths DATA_PATH: str = os.path.join( os.path.dirname(os.path.dirname(__file__)), "data") # Order VAT: float = 1.21 # VAT tax applied in Order ORDER_TYPES = ['sale',...
python
################################################################################### # # # Workflow logic will be coded here, just to get rid of dirty code in the models. # # ...
python
def getStatusMessage(statusCode, default="Unknown status"): # TODO Add docs if not isinstance(statusCode, int): raise TypeError("Status code must be int") return { 100: 'Continue', 101: 'Switching Protocols', 102: 'Processing', 200: 'OK', 201: 'Created', ...
python
n = int(input()) S = input() T = input() result = 0 for i in range(n): if S[i] != T[i]: result += 1 print(result)
python
from django.core import validators from django.db import models from django.db.models.aggregates import Max from django.db.models.base import Model from django.core.validators import RegexValidator class entry(models.Model): pilot_name = models.CharField(max_length=200, blank=False, default="John Doe") pilot_i...
python
# Generated by Django 3.1.13 on 2021-11-16 14:57 from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): dependencies = [ ('analysis', '0016_auto_20211115_0020'), ] operations = [ migrations.AlterField( mod...
python
from __init__ import __version__ as version from __init__ import __author__ as author import requests author_name = requests.get("https://estra-api.herokuapp.com/ShowroomPY").json()["Author"] if author != author_name: print("Error: Incorrect author. Please do not change any of these attributes.") else: pass ...
python
# Yes python, it's a package
python
from typing import NoReturn from cryspy.A_functions_base.function_1_objects import \ form_items_by_dictionary from cryspy.B_parent_classes.cl_1_item import ItemN from cryspy.B_parent_classes.cl_2_loop import LoopN class Chi2(ItemN): """ Choise of the experimental data for the refinement procedure. ...
python
#!/usr/bin/python3 import sys import json import queue import requests import threading import subprocess from .logger import log from .cmd_args import args from .test_utils import last_message_as_json, ws_to_http class CliWalletException(Exception): def __init__(self, _message): self.message = _me...
python
def escreva(mens): t=len(m) print(f'~'*t) print(f'{mens}') print(f'~' * t) m=str(input('Quala Mensagem ? : ')) escreva(m)
python